<commit_before>#include "ExampleAndroidHandler.h"
#include <AndroidLog.h>
#include <GooglePlayServices.h>
#include <GoogleGames.h>
#include <AppState.h>
#include <time.h>
#include "ExampleStateListener.h"

class SignInListener : public Android::ISignInListener
{
private:
	ExampleStateListener m_StateListener;

public:
	virtual void OnSignInSucceeded()
	{
		LOGV( "Signed in!" );
		char state[] = "Hello Cloud Save!";
		Android::AppState::UpdateState( 1, state, sizeof( state ) );
		Android::AppState::LoadState( 1, &m_StateListener );
	}

	virtual void OnSignInFailed()
	{
		LOGE( "Sign in failed." );
	}

	SignInListener() { }
	virtual ~SignInListener() { }
};

ExampleAndroidHandler::ExampleAndroidHandler()
{
	// State variables
	m_bShouldQuit 	= false;
	m_bIsVisible 	= false;
	m_bIsPaused		= true;

	// Egl
	m_Display = EGL_NO_DISPLAY;
	m_Surface = EGL_NO_SURFACE;
	m_Context = NULL;
}

ExampleAndroidHandler::~ExampleAndroidHandler()
{
	DestroyOpenGL();
}

void ExampleAndroidHandler::Run()
{
	SignInListener signInListener;
	Android::GooglePlayServices::SetSignInListener( &signInListener );

	// Example asset read
	Android::Asset* pAsset = Android::GetAssetManager().GetAsset( "test.txt" );
	if ( pAsset )
	{
		// Create a buffer to read the content into,
		// [ Size() + 1 ] for null terminator character for LOG usage
		char* pBuffer = new char[ pAsset->Size() + 1 ];

		// Read the buffer
		pAsset->Read( pBuffer, pAsset->Size() );

		// Set null terminating for LOG
		pBuffer[ pAsset->Size() ] = 0;

		// Delete the asset file
		delete pAsset;

		// Show us the file's content!
		LOGV( "[Example]: File content: %s", pBuffer );

		// Delete the buffer
		delete [] pBuffer;
	}

	// Create time measurement
	timespec timeNow;
	clock_gettime( CLOCK_MONOTONIC, &timeNow );
	uint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;

	// Connect to Google Play
	Android::GooglePlayServices::SignIn();

	// While application is alive...
	while ( !m_bShouldQuit )
	{
		// Handle Android events
		Android::PollEvents();

		// Calculate delta time
		clock_gettime( CLOCK_MONOTONIC, &timeNow ); // query time now
		uint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; // get time in nanoseconds
		float fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; // 1 second = 1,000,000,000 nanoseconds
		uPreviousTime = uNowNano; // set previous time to new time

		// If not paused...
		if ( !m_bIsPaused )
		{
			// Update logic
			Update( fDeltaSeconds );
		}

		// If visible
		if ( m_bIsVisible )
		{
			// Draw
			Draw();
		}

	}

	LOGV( "[Example]: Mainloop terminated." );
}

void ExampleAndroidHandler::Update( float fDeltaSeconds )
{
	// Do stuff here
}

void ExampleAndroidHandler::Draw()
{
	// Draw things here
	glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	if ( !eglSwapBuffers( m_Display, m_Surface ) )
	{
		LOGE( "[Example]: eglSwapBuffers() returned error %d", eglGetError() );
	}
}

bool ExampleAndroidHandler::InitOpenGL()
{
	const EGLint attribs[] =
	{
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_BLUE_SIZE, 8,
		EGL_GREEN_SIZE, 8,
		EGL_RED_SIZE, 8,
		EGL_NONE
	};

	EGLDisplay display;
	EGLConfig config;
	EGLint numConfigs;
	EGLint format;
	EGLSurface surface;
	EGLContext context;
	EGLint width;
	EGLint height;
	GLfloat ratio;

	LOGV( "[Example]: Initializing context" );

	if ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )
	{
		LOGE( "[Example]: eglGetDisplay() returned error %d", eglGetError() );
		return false;
	}

	if ( !eglInitialize( display, 0, 0 ) )
	{
		LOGE( "[Example]: eglInitialize() returned error %d", eglGetError() );
		return false;
	}

	if ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )
	{
		LOGE( "[Example]: eglChooseConfig() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )
	{
		LOGE( "[Example]: eglGetConfigAttrib() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	// Set buffer geometry using our window which is saved in Android
	ANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );

	if ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )
	{
		LOGE( "[Example]: eglCreateWindowSurface() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !( context = eglCreateContext( display, config, 0, 0 ) ) )
	{
		LOGE( "[Example]: eglCreateContext() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !eglMakeCurrent(display, surface, surface, context ) )
	{
		LOGE( "[Example]: eglMakeCurrent() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||
		!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )
	{
		LOGE( "[Example]: eglQuerySurface() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	m_Display = display;
	m_Surface = surface;
	m_Context = context;

	glDisable( GL_DITHER );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
	glClearColor(0, 0, 0, 0);
	glEnable( GL_CULL_FACE );
	glEnable( GL_DEPTH_TEST );

	return true;
}

void ExampleAndroidHandler::DestroyOpenGL()
{
	if ( m_Display )
	{
		LOGV( "[Example]: Shutting down OpenGL" );

		eglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
		eglDestroyContext( m_Display, m_Context );
		eglDestroySurface( m_Display, m_Surface);
		eglTerminate( m_Display );

		m_Display = EGL_NO_DISPLAY;
		m_Surface = EGL_NO_SURFACE;
		m_Context = NULL;
	}
}

// Application
void ExampleAndroidHandler::OnShutdown()
{
	LOGV( "[Example]: Shutting down!" );
	m_bShouldQuit = true;
}

// Surface
void ExampleAndroidHandler::OnSurfaceCreated()
{
	LOGV( "[Example]: Creating surface!" );
	if ( InitOpenGL() == false )
	{
		m_bShouldQuit = true;
	}
}

void ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )
{
	LOGV( "[Example]: Setting viewports!" );

	// Set new viewport
	glViewport( 0, 0, iWidth, iHeight );
}

void ExampleAndroidHandler::OnSurfaceDestroyed()
{
	LOGV( "[Example]: Destroying egl!" );
	DestroyOpenGL();
}

// States
void ExampleAndroidHandler::OnPause()
{
	LOGV( "[Example]: Paused!" );
	m_bIsPaused = true;
}

void ExampleAndroidHandler::OnResume()
{
	LOGV( "[Example]: Resumed!" );
	m_bIsPaused = false;
}

void ExampleAndroidHandler::OnVisible()
{
	LOGV( "[Example]: Visible!" );
	m_bIsVisible = true;
}

void ExampleAndroidHandler::OnHidden()
{
	LOGV( "[Example]: Hidden!" );
	m_bIsVisible = false;
	//Android::GooglePlayServices::SignOut();
}

void ExampleAndroidHandler::OnLowMemory()
{
	LOGV( "[Example]: Clearing some memory to stay alive..." );

	// BigMemoryObject->Release();
}

// Input
void ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )
{
	LOGV( "[Example]: Got key! %i %c", iKeyCode, iUnicodeChar );

}

void ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )
{
	//LOGV( "[Example]: Touch: %i, x: %f y:, %f action:, %i.", iPointerID, fPosX, fPosY, iAction );

	if ( iAction == 0 )
	{
		// On touch start show keyboard!
		Android::ShowKeyboard();
		Android::GooglePlayServices::SignIn();
		//Android::GoogleGames::SubmitScore( "CgkIp8rf-fkTEAIQCQ", 1337 );
		//Android::GoogleGames::UnlockAchievement( "CgkIp8rf-fkTEAIQAw" );
	}

	else if ( iAction == 1 )
	{
		// On touch up, hide keyboard...
		Android::HideKeyboard();
		//Android::GooglePlayServices::ShowAlert( "Test Alert!", "Test" );
		//Android::GoogleGames::ShowAllLeaderboards();
		//Android::GoogleGames::ShowAchievements();

	}
}
<commit_msg>Notification example<commit_after>#include "ExampleAndroidHandler.h"
#include <AndroidLog.h>
#include <GooglePlayServices.h>
#include <GoogleGames.h>
#include <AppState.h>
#include <time.h>
#include "ExampleStateListener.h"
#include <Notification.h>

class SignInListener : public Android::ISignInListener
{
private:
	ExampleStateListener m_StateListener;

public:
	virtual void OnSignInSucceeded()
	{
		LOGV( "Signed in!" );
		char state[] = "Hello Cloud Save!";
		Android::AppState::UpdateState( 1, state, sizeof( state ) );
		Android::AppState::LoadState( 1, &m_StateListener );
	}

	virtual void OnSignInFailed()
	{
		LOGE( "Sign in failed." );
	}

	SignInListener() { }
	virtual ~SignInListener() { }
};

ExampleAndroidHandler::ExampleAndroidHandler()
{
	// State variables
	m_bShouldQuit 	= false;
	m_bIsVisible 	= false;
	m_bIsPaused		= true;

	// Egl
	m_Display = EGL_NO_DISPLAY;
	m_Surface = EGL_NO_SURFACE;
	m_Context = NULL;
}

ExampleAndroidHandler::~ExampleAndroidHandler()
{
	DestroyOpenGL();
}

void ExampleAndroidHandler::Run()
{
	SignInListener signInListener;
	Android::GooglePlayServices::SetSignInListener( &signInListener );

	// Example asset read
	Android::Asset* pAsset = Android::GetAssetManager().GetAsset( "test.txt" );
	if ( pAsset )
	{
		// Create a buffer to read the content into,
		// [ Size() + 1 ] for null terminator character for LOG usage
		char* pBuffer = new char[ pAsset->Size() + 1 ];

		// Read the buffer
		pAsset->Read( pBuffer, pAsset->Size() );

		// Set null terminating for LOG
		pBuffer[ pAsset->Size() ] = 0;

		// Delete the asset file
		delete pAsset;

		// Show us the file's content!
		LOGV( "[Example]: File content: %s", pBuffer );

		// Delete the buffer
		delete [] pBuffer;
	}

	// Create time measurement
	timespec timeNow;
	clock_gettime( CLOCK_MONOTONIC, &timeNow );
	uint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;

	// Connect to Google Play
	Android::GooglePlayServices::SignIn();

	// While application is alive...
	while ( !m_bShouldQuit )
	{
		// Handle Android events
		Android::PollEvents();

		// Calculate delta time
		clock_gettime( CLOCK_MONOTONIC, &timeNow ); // query time now
		uint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; // get time in nanoseconds
		float fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; // 1 second = 1,000,000,000 nanoseconds
		uPreviousTime = uNowNano; // set previous time to new time

		// If not paused...
		if ( !m_bIsPaused )
		{
			// Update logic
			Update( fDeltaSeconds );
		}

		// If visible
		if ( m_bIsVisible )
		{
			// Draw
			Draw();
		}

	}

	LOGV( "[Example]: Mainloop terminated." );
}

void ExampleAndroidHandler::Update( float fDeltaSeconds )
{
	// Do stuff here
}

void ExampleAndroidHandler::Draw()
{
	// Draw things here
	glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	if ( !eglSwapBuffers( m_Display, m_Surface ) )
	{
		LOGE( "[Example]: eglSwapBuffers() returned error %d", eglGetError() );
	}
}

bool ExampleAndroidHandler::InitOpenGL()
{
	const EGLint attribs[] =
	{
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_BLUE_SIZE, 8,
		EGL_GREEN_SIZE, 8,
		EGL_RED_SIZE, 8,
		EGL_NONE
	};

	EGLDisplay display;
	EGLConfig config;
	EGLint numConfigs;
	EGLint format;
	EGLSurface surface;
	EGLContext context;
	EGLint width;
	EGLint height;
	GLfloat ratio;

	LOGV( "[Example]: Initializing context" );

	if ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )
	{
		LOGE( "[Example]: eglGetDisplay() returned error %d", eglGetError() );
		return false;
	}

	if ( !eglInitialize( display, 0, 0 ) )
	{
		LOGE( "[Example]: eglInitialize() returned error %d", eglGetError() );
		return false;
	}

	if ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )
	{
		LOGE( "[Example]: eglChooseConfig() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )
	{
		LOGE( "[Example]: eglGetConfigAttrib() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	// Set buffer geometry using our window which is saved in Android
	ANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );

	if ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )
	{
		LOGE( "[Example]: eglCreateWindowSurface() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !( context = eglCreateContext( display, config, 0, 0 ) ) )
	{
		LOGE( "[Example]: eglCreateContext() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !eglMakeCurrent(display, surface, surface, context ) )
	{
		LOGE( "[Example]: eglMakeCurrent() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	if ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||
		!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )
	{
		LOGE( "[Example]: eglQuerySurface() returned error %d", eglGetError() );
		DestroyOpenGL();
		return false;
	}

	m_Display = display;
	m_Surface = surface;
	m_Context = context;

	glDisable( GL_DITHER );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
	glClearColor(0, 0, 0, 0);
	glEnable( GL_CULL_FACE );
	glEnable( GL_DEPTH_TEST );

	return true;
}

void ExampleAndroidHandler::DestroyOpenGL()
{
	if ( m_Display )
	{
		LOGV( "[Example]: Shutting down OpenGL" );

		eglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
		eglDestroyContext( m_Display, m_Context );
		eglDestroySurface( m_Display, m_Surface);
		eglTerminate( m_Display );

		m_Display = EGL_NO_DISPLAY;
		m_Surface = EGL_NO_SURFACE;
		m_Context = NULL;
	}
}

// Application
void ExampleAndroidHandler::OnShutdown()
{
	LOGV( "[Example]: Shutting down!" );
	m_bShouldQuit = true;
}

// Surface
void ExampleAndroidHandler::OnSurfaceCreated()
{
	LOGV( "[Example]: Creating surface!" );
	if ( InitOpenGL() == false )
	{
		m_bShouldQuit = true;
	}
}

void ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )
{
	LOGV( "[Example]: Setting viewports!" );

	// Set new viewport
	glViewport( 0, 0, iWidth, iHeight );
}

void ExampleAndroidHandler::OnSurfaceDestroyed()
{
	LOGV( "[Example]: Destroying egl!" );
	DestroyOpenGL();
}

// States
void ExampleAndroidHandler::OnPause()
{
	Android::Notification notification;
	notification.SetContentTitle( "New Test Title" );
	notification.SetContentText( "Test Content" );
	notification.SetSmallIcon( 0x7f020000 );

	Android::GetNotificationManager().Notify( 500, notification );

	LOGV( "[Example]: Paused!" );
	m_bIsPaused = true;
}

void ExampleAndroidHandler::OnResume()
{
	LOGV( "[Example]: Resumed!" );
	m_bIsPaused = false;
}

void ExampleAndroidHandler::OnVisible()
{
	LOGV( "[Example]: Visible!" );
	m_bIsVisible = true;
}

void ExampleAndroidHandler::OnHidden()
{
	LOGV( "[Example]: Hidden!" );
	m_bIsVisible = false;
	//Android::GooglePlayServices::SignOut();
}

void ExampleAndroidHandler::OnLowMemory()
{
	LOGV( "[Example]: Clearing some memory to stay alive..." );

	// BigMemoryObject->Release();
}

// Input
void ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )
{
	LOGV( "[Example]: Got key! %i %c", iKeyCode, iUnicodeChar );

}

void ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )
{
	//LOGV( "[Example]: Touch: %i, x: %f y:, %f action:, %i.", iPointerID, fPosX, fPosY, iAction );

	if ( iAction == 0 )
	{
		// On touch start show keyboard!
		Android::ShowKeyboard();
		Android::GooglePlayServices::SignIn();
		//Android::GoogleGames::SubmitScore( "CgkIp8rf-fkTEAIQCQ", 1337 );
		//Android::GoogleGames::UnlockAchievement( "CgkIp8rf-fkTEAIQAw" );
	}

	else if ( iAction == 1 )
	{
		// On touch up, hide keyboard...
		Android::HideKeyboard();
		//Android::GooglePlayServices::ShowAlert( "Test Alert!", "Test" );
		//Android::GoogleGames::ShowAllLeaderboards();
		//Android::GoogleGames::ShowAchievements();

	}
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "BasicsC/common.h"

#include <stdio.h>
#include <iomanip>

#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/string-buffer.h"
#include "BasicsC/terminal-utils.h"
#include "Logger/Logger.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////

ArangoClient BaseClient;

////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////

static volatile int Started = 0;

////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////

Mutex StartMutex;

////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////

static bool Async = false;

////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////

static int BatchSize = 0;

////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////

static string Collection = "ArangoBenchmark";

////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////

static uint64_t Complexity = 1;

////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////

static int Concurrency = 1;

////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////

static bool Delay = false;

////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////

static bool KeepAlive = true;

////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////

static int Operations = 1000;

////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////

static bool Progress = true;

////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////

static string TestCase = "version";

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////

#include "Benchmark/test-cases.h"

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////

static void UpdateStartCounter () {
  MUTEX_LOCKER(StartMutex);
  ++Started;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////

static int GetStartCounter () {
  MUTEX_LOCKER(StartMutex);
  return Started;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////

static void Status (const string& value) {
  if (! BaseClient.quiet()) {
    cout << value << endl;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////

static void ParseProgramOptions (int argc, char* argv[]) {
  ProgramOptionsDescription description("STANDARD options");

  description
    ("async", &Async, "send asychronous requests")
    ("concurrency", &Concurrency, "number of parallel connections")
    ("requests", &Operations, "total number of operations")
    ("batch-size", &BatchSize, "number of operations in one batch (0 disables batching")
    ("keep-alive", &KeepAlive, "use HTTP keep-alive")
    ("collection", &Collection, "collection name to use in tests")
    ("test-case", &TestCase, "test case to use")
    ("complexity", &Complexity, "complexity parameter for the test")
    ("delay", &Delay, "use a startup delay (necessary only when run in series)")
    ("progress", &Progress, "show progress")
  ;

  BaseClient.setupGeneral(description);
  BaseClient.setupServer(description);

  vector<string> arguments;
  description.arguments(&arguments);

  ProgramOptions options;
  BaseClient.parse(options, description, argc, argv, "arangob.conf");
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup arangoimp
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////

int main (int argc, char* argv[]) {
  TRIAGENS_C_INITIALISE(argc, argv);
  TRIAGENS_REST_INITIALISE(argc, argv);

  TRI_InitialiseLogging(false);

  BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());

  // .............................................................................
  // parse the program options
  // .............................................................................

  ParseProgramOptions(argc, argv);

  // .............................................................................
  // set-up client connection
  // .............................................................................

  BaseClient.createEndpoint();

  if (BaseClient.endpointServer() == 0) {
    LOGGER_FATAL_AND_EXIT("invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')");
  }

  BenchmarkOperation* testCase = GetTestCase(TestCase);

  if (testCase == 0) {
    LOGGER_FATAL_AND_EXIT("invalid test case name " << TestCase);
    return EXIT_FAILURE; // will not be reached
  }

  Status("starting threads...");

  BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
  ConditionVariable startCondition;

  vector<Endpoint*> endpoints;
  vector<BenchmarkThread*> threads;

  const double stepSize = (double) Operations / (double) Concurrency;
  int64_t realStep = (int64_t) stepSize;
  if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
    realStep++;
  }
  if (realStep % 1000 != 0) {
    realStep += 1000 - (realStep % 1000);
  }
  // add some more offset we don't get into trouble with threads of different speed
  realStep += 10000;

  // start client threads
  for (int i = 0; i < Concurrency; ++i) {
    Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
    endpoints.push_back(endpoint);

    BenchmarkThread* thread = new BenchmarkThread(testCase,
        &startCondition,
        &UpdateStartCounter,
        i,
        (unsigned long) BatchSize,
        &operationsCounter,
        endpoint,
        BaseClient.databaseName(),
        BaseClient.username(),
        BaseClient.password(),
        BaseClient.requestTimeout(),
        BaseClient.connectTimeout(),
        KeepAlive,
        Async);

    threads.push_back(thread);
    thread->setOffset(i * realStep);
    thread->start();
  }

  // give all threads a chance to start so they will not miss the broadcast
  while (GetStartCounter() < Concurrency) {
    usleep(5000);
  }

  if (Delay) {
    Status("sleeping (startup delay)...");
    sleep(10);
  }
  Status("executing tests...");

  Timing timer(Timing::TI_WALLCLOCK);

  // broadcast the start signal to all threads
  {
    ConditionLocker guard(&startCondition);
    guard.broadcast();
  }

  const size_t stepValue = (Operations / 20);
  size_t nextReportValue = stepValue;

  if (nextReportValue < 100) {
    nextReportValue = 100;
  }

  while (1) {
    const size_t numOperations = operationsCounter.getValue();

    if (numOperations >= (size_t) Operations) {
      break;
    }

    if (Progress && numOperations >= nextReportValue) {
      LOGGER_INFO("number of operations: " << nextReportValue);
      nextReportValue += stepValue;
    }

    usleep(20000);
  }

  double time = ((double) timer.time()) / 1000000.0;
  double requestTime = 0.0;

  for (int i = 0; i < Concurrency; ++i) {
    requestTime += threads[i]->getTime();
  }

  size_t failures = operationsCounter.failures();

  cout << endl;
  cout << "Total number of operations: " << Operations <<
          ", keep alive: " << (KeepAlive ? "yes" : "no") <<
          ", async: " << (Async ? "yes" : "no")  <<
          ", batch size: " << BatchSize <<
          ", concurrency level (threads): " << Concurrency <<
          endl;

  cout << "Test case: " << TestCase <<
          ", complexity: " << Complexity <<
          ", database: '" << BaseClient.databaseName() <<
          "', collection: '" << Collection << "'" <<
          endl;

  cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
  cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
  cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
  cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
  cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
  cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;

  if (failures > 0) {
    cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
  }

  testCase->tearDown();

  for (int i = 0; i < Concurrency; ++i) {
    threads[i]->join();
    delete threads[i];
    delete endpoints[i];
  }

  delete testCase;

  TRIAGENS_REST_SHUTDOWN;

  return (failures == 0) ? EXIT_SUCCESS : 2;
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>fix typo in help text<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "BasicsC/common.h"

#include <stdio.h>
#include <iomanip>

#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/string-buffer.h"
#include "BasicsC/terminal-utils.h"
#include "Logger/Logger.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////

ArangoClient BaseClient;

////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////

static volatile int Started = 0;

////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////

Mutex StartMutex;

////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////

static bool Async = false;

////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////

static int BatchSize = 0;

////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////

static string Collection = "ArangoBenchmark";

////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////

static uint64_t Complexity = 1;

////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////

static int Concurrency = 1;

////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////

static bool Delay = false;

////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////

static bool KeepAlive = true;

////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////

static int Operations = 1000;

////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////

static bool Progress = true;

////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////

static string TestCase = "version";

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////

#include "Benchmark/test-cases.h"

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////

static void UpdateStartCounter () {
  MUTEX_LOCKER(StartMutex);
  ++Started;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////

static int GetStartCounter () {
  MUTEX_LOCKER(StartMutex);
  return Started;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////

static void Status (const string& value) {
  if (! BaseClient.quiet()) {
    cout << value << endl;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////

static void ParseProgramOptions (int argc, char* argv[]) {
  ProgramOptionsDescription description("STANDARD options");

  description
    ("async", &Async, "send asychronous requests")
    ("concurrency", &Concurrency, "number of parallel connections")
    ("requests", &Operations, "total number of operations")
    ("batch-size", &BatchSize, "number of operations in one batch (0 disables batching)")
    ("keep-alive", &KeepAlive, "use HTTP keep-alive")
    ("collection", &Collection, "collection name to use in tests")
    ("test-case", &TestCase, "test case to use")
    ("complexity", &Complexity, "complexity parameter for the test")
    ("delay", &Delay, "use a startup delay (necessary only when run in series)")
    ("progress", &Progress, "show progress")
  ;

  BaseClient.setupGeneral(description);
  BaseClient.setupServer(description);

  vector<string> arguments;
  description.arguments(&arguments);

  ProgramOptions options;
  BaseClient.parse(options, description, argc, argv, "arangob.conf");
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup arangoimp
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////

int main (int argc, char* argv[]) {
  TRIAGENS_C_INITIALISE(argc, argv);
  TRIAGENS_REST_INITIALISE(argc, argv);

  TRI_InitialiseLogging(false);

  BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());

  // .............................................................................
  // parse the program options
  // .............................................................................

  ParseProgramOptions(argc, argv);

  // .............................................................................
  // set-up client connection
  // .............................................................................

  BaseClient.createEndpoint();

  if (BaseClient.endpointServer() == 0) {
    LOGGER_FATAL_AND_EXIT("invalid value for --server.endpoint ('" << BaseClient.endpointString() << "')");
  }

  BenchmarkOperation* testCase = GetTestCase(TestCase);

  if (testCase == 0) {
    LOGGER_FATAL_AND_EXIT("invalid test case name " << TestCase);
    return EXIT_FAILURE; // will not be reached
  }

  Status("starting threads...");

  BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
  ConditionVariable startCondition;

  vector<Endpoint*> endpoints;
  vector<BenchmarkThread*> threads;

  const double stepSize = (double) Operations / (double) Concurrency;
  int64_t realStep = (int64_t) stepSize;
  if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
    realStep++;
  }
  if (realStep % 1000 != 0) {
    realStep += 1000 - (realStep % 1000);
  }
  // add some more offset we don't get into trouble with threads of different speed
  realStep += 10000;

  // start client threads
  for (int i = 0; i < Concurrency; ++i) {
    Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
    endpoints.push_back(endpoint);

    BenchmarkThread* thread = new BenchmarkThread(testCase,
        &startCondition,
        &UpdateStartCounter,
        i,
        (unsigned long) BatchSize,
        &operationsCounter,
        endpoint,
        BaseClient.databaseName(),
        BaseClient.username(),
        BaseClient.password(),
        BaseClient.requestTimeout(),
        BaseClient.connectTimeout(),
        KeepAlive,
        Async);

    threads.push_back(thread);
    thread->setOffset(i * realStep);
    thread->start();
  }

  // give all threads a chance to start so they will not miss the broadcast
  while (GetStartCounter() < Concurrency) {
    usleep(5000);
  }

  if (Delay) {
    Status("sleeping (startup delay)...");
    sleep(10);
  }
  Status("executing tests...");

  Timing timer(Timing::TI_WALLCLOCK);

  // broadcast the start signal to all threads
  {
    ConditionLocker guard(&startCondition);
    guard.broadcast();
  }

  const size_t stepValue = (Operations / 20);
  size_t nextReportValue = stepValue;

  if (nextReportValue < 100) {
    nextReportValue = 100;
  }

  while (1) {
    const size_t numOperations = operationsCounter.getValue();

    if (numOperations >= (size_t) Operations) {
      break;
    }

    if (Progress && numOperations >= nextReportValue) {
      LOGGER_INFO("number of operations: " << nextReportValue);
      nextReportValue += stepValue;
    }

    usleep(20000);
  }

  double time = ((double) timer.time()) / 1000000.0;
  double requestTime = 0.0;

  for (int i = 0; i < Concurrency; ++i) {
    requestTime += threads[i]->getTime();
  }

  size_t failures = operationsCounter.failures();

  cout << endl;
  cout << "Total number of operations: " << Operations <<
          ", keep alive: " << (KeepAlive ? "yes" : "no") <<
          ", async: " << (Async ? "yes" : "no")  <<
          ", batch size: " << BatchSize <<
          ", concurrency level (threads): " << Concurrency <<
          endl;

  cout << "Test case: " << TestCase <<
          ", complexity: " << Complexity <<
          ", database: '" << BaseClient.databaseName() <<
          "', collection: '" << Collection << "'" <<
          endl;

  cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
  cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
  cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
  cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
  cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
  cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;

  if (failures > 0) {
    cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
  }

  testCase->tearDown();

  for (int i = 0; i < Concurrency; ++i) {
    threads[i]->join();
    delete threads[i];
    delete endpoints[i];
  }

  delete testCase;

  TRIAGENS_REST_SHUTDOWN;

  return (failures == 0) ? EXIT_SUCCESS : 2;
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


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

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }
};

// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall FAILS_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
                       MAYBE_InstallAndUninstall) {
  host_resolver()->AddRule("www.example.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  std::string base_url = base::StringPrintf(
      "http://www.example.com:%u/files/extensions/",
      test_server()->host_port_pair().port());

  std::string testing_install_base_url = base_url;
  testing_install_base_url += "good.crx";
  InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());

  std::string page_url = base_url;
  page_url += "api_test/extension_gallery_install/test.html";
  ASSERT_TRUE(RunPageTest(page_url.c_str()));
}
<commit_msg>Disables ExtensionGalleryInstallApiTest.InstallAndUninstall on Windows<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }
};

// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
                       MAYBE_InstallAndUninstall) {
  host_resolver()->AddRule("www.example.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  std::string base_url = base::StringPrintf(
      "http://www.example.com:%u/files/extensions/",
      test_server()->host_port_pair().port());

  std::string testing_install_base_url = base_url;
  testing_install_base_url += "good.crx";
  InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());

  std::string page_url = base_url;
  page_url += "api_test/extension_gallery_install/test.html";
  ASSERT_TRUE(RunPageTest(page_url.c_str()));
}
<|endoftext|>


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

#include "chrome/browser/importer/firefox_importer_unittest_utils.h"

#include "base/bind.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/importer/firefox_importer_utils.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_switches.h"
#include "testing/multiprocess_func_list.h"

#define IPC_MESSAGE_IMPL
#include "chrome/browser/importer/firefox_importer_unittest_messages_internal.h"

namespace {

// Name of IPC Channel to use for Server<-> Child Communications.
const char kTestChannelID[] = "T1";

// Launch the child process:
// |nss_path| - path to the NSS directory holding the decryption libraries.
// |channel| - IPC Channel to use for communication.
// |handle| - On return, the process handle to use to communicate with the
// child.
bool LaunchNSSDecrypterChildProcess(const FilePath& nss_path,
    IPC::Channel* channel, base::ProcessHandle* handle) {
  CommandLine cl(*CommandLine::ForCurrentProcess());
  cl.AppendSwitchASCII(switches::kTestChildProcess, "NSSDecrypterChildProcess");

  // Set env variable needed for FF encryption libs to load.
  // See "chrome/browser/importer/nss_decryptor_mac.mm" for an explanation of
  // why we need this.
  base::EnvironmentVector env;
  std::pair<std::string, std::string> dyld_override;
  dyld_override.first = "DYLD_FALLBACK_LIBRARY_PATH";
  dyld_override.second = nss_path.value();
  env.push_back(dyld_override);

  int ipcfd = channel->TakeClientFileDescriptor();
  if (ipcfd == -1)
    return false;

  file_util::ScopedFD client_file_descriptor_closer(&ipcfd);
  base::FileHandleMappingVector fds_to_map;
  fds_to_map.push_back(std::pair<int,int>(ipcfd, kPrimaryIPCChannel + 3));

  bool debug_on_start = CommandLine::ForCurrentProcess()->HasSwitch(
                            switches::kDebugChildren);
  base::LaunchOptions options;
  options.environ = &env;
  options.fds_to_remap = &fds_to_map;
  options.wait = debug_on_start;
  return base::LaunchProcess(cl.argv(), options, handle);
}

}  // namespace

//----------------------- Server --------------------

// Class to communicate on the server side of the IPC Channel.
// Method calls are sent over IPC and replies are read back into class
// variables.
// This class needs to be called on a single thread.
class FFDecryptorServerChannelListener : public IPC::Channel::Listener {
 public:
  FFDecryptorServerChannelListener()
      : got_result(false), sender_(NULL) {}

  void SetSender(IPC::Message::Sender* sender) {
    sender_ = sender;
  }

  void OnInitDecryptorResponse(bool result) {
    DCHECK(!got_result);
    result_bool = result;
    got_result = true;
    MessageLoop::current()->Quit();
  }

  void OnDecryptedTextResonse(const string16& decrypted_text) {
    DCHECK(!got_result);
    result_string = decrypted_text;
    got_result = true;
    MessageLoop::current()->Quit();
  }

  void QuitClient() {
    if (sender_)
      sender_->Send(new Msg_Decryptor_Quit());
  }

  virtual bool OnMessageReceived(const IPC::Message& msg) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(FFDecryptorServerChannelListener, msg)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_InitReturnCode, OnInitDecryptorResponse)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_Response, OnDecryptedTextResonse)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

  // If an error occured, just kill the message Loop.
  virtual void OnChannelError() {
    got_result = false;
    MessageLoop::current()->Quit();
  }

  // Results of IPC calls.
  string16 result_string;
  bool result_bool;
  // True if IPC call succeeded and data in above variables is valid.
  bool got_result;

 private:
  IPC::Message::Sender* sender_;  // weak
};

FFUnitTestDecryptorProxy::FFUnitTestDecryptorProxy()
    : child_process_(0) {
}

bool FFUnitTestDecryptorProxy::Setup(const FilePath& nss_path) {
  // Create a new message loop and spawn the child process.
  message_loop_.reset(new MessageLoopForIO());

  listener_.reset(new FFDecryptorServerChannelListener());
  channel_.reset(new IPC::Channel(kTestChannelID,
                                  IPC::Channel::MODE_SERVER,
                                  listener_.get()));
  CHECK(channel_->Connect());
  listener_->SetSender(channel_.get());

  // Spawn child and set up sync IPC connection.
  bool ret = LaunchNSSDecrypterChildProcess(nss_path,
                                            channel_.get(),
                                            &child_process_);
  return ret && (child_process_ != 0);
}

FFUnitTestDecryptorProxy::~FFUnitTestDecryptorProxy() {
  listener_->QuitClient();
  channel_->Close();

  if (child_process_) {
    base::WaitForSingleProcess(child_process_, 5000);
    base::CloseProcessHandle(child_process_);
  }
}

// A message_loop task that quits the message loop when invoked, setting cancel
// causes the task to do nothing when invoked.
class CancellableQuitMsgLoop : public base::RefCounted<CancellableQuitMsgLoop> {
 public:
  CancellableQuitMsgLoop() : cancelled_(false) {}
  void QuitNow() {
    if (!cancelled_)
      MessageLoop::current()->Quit();
  }
  bool cancelled_;
};

// Spin until either a client response arrives or a timeout occurs.
bool FFUnitTestDecryptorProxy::WaitForClientResponse() {
  // What we're trying to do here is to wait for an RPC message to go over the
  // wire and the client to reply.  If the client does not reply by a given
  // timeout we kill the message loop.
  // The way we do this is to post a CancellableQuitMsgLoop for 3 seconds in
  // the future and cancel it if an RPC message comes back earlier.
  // This relies on the IPC listener class to quit the message loop itself when
  // a message comes in.
  scoped_refptr<CancellableQuitMsgLoop> quit_task(
      new CancellableQuitMsgLoop());
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&CancellableQuitMsgLoop::QuitNow, quit_task.get()),
      TestTimeouts::action_max_timeout_ms());

  message_loop_->Run();
  bool ret = !quit_task->cancelled_;
  quit_task->cancelled_ = false;
  return ret;
}

bool FFUnitTestDecryptorProxy::DecryptorInit(const FilePath& dll_path,
                                             const FilePath& db_path) {
  channel_->Send(new Msg_Decryptor_Init(dll_path, db_path));
  bool ok = WaitForClientResponse();
  if (ok && listener_->got_result) {
    listener_->got_result = false;
    return listener_->result_bool;
  }
  return false;
}

string16 FFUnitTestDecryptorProxy::Decrypt(const std::string& crypt) {
  channel_->Send(new Msg_Decrypt(crypt));
  bool ok = WaitForClientResponse();
  if (ok && listener_->got_result) {
    listener_->got_result = false;
    return listener_->result_string;
  }
  return string16();
}

//---------------------------- Child Process -----------------------

// Class to listen on the client side of the ipc channel, it calls through
// to the NSSDecryptor and sends back a reply.
class FFDecryptorClientChannelListener : public IPC::Channel::Listener {
 public:
  FFDecryptorClientChannelListener()
      : sender_(NULL) {}

  void SetSender(IPC::Message::Sender* sender) {
    sender_ = sender;
  }

  void OnDecryptor_Init(FilePath dll_path, FilePath db_path) {
    bool ret = decryptor_.Init(dll_path, db_path);
    sender_->Send(new Msg_Decryptor_InitReturnCode(ret));
  }

  void OnDecrypt(std::string crypt) {
    string16 unencrypted_str = decryptor_.Decrypt(crypt);
    sender_->Send(new Msg_Decryptor_Response(unencrypted_str));
  }

  void OnQuitRequest() {
    MessageLoop::current()->Quit();
  }

  virtual bool OnMessageReceived(const IPC::Message& msg) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(FFDecryptorClientChannelListener, msg)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_Init, OnDecryptor_Init)
      IPC_MESSAGE_HANDLER(Msg_Decrypt, OnDecrypt)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_Quit, OnQuitRequest)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

  virtual void OnChannelError() {
    MessageLoop::current()->Quit();
  }

 private:
  NSSDecryptor decryptor_;
  IPC::Message::Sender* sender_;
};

// Entry function in child process.
MULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) {
  MessageLoopForIO main_message_loop;
  FFDecryptorClientChannelListener listener;

  IPC::Channel channel(kTestChannelID, IPC::Channel::MODE_CLIENT, &listener);
  CHECK(channel.Connect());
  listener.SetSender(&channel);

  // run message loop
  MessageLoop::current()->Run();

  return 0;
}
<commit_msg>Update uses of TimeDelta in mac firefox importer test code.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/importer/firefox_importer_unittest_utils.h"

#include "base/bind.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/importer/firefox_importer_utils.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_switches.h"
#include "testing/multiprocess_func_list.h"

#define IPC_MESSAGE_IMPL
#include "chrome/browser/importer/firefox_importer_unittest_messages_internal.h"

namespace {

// Name of IPC Channel to use for Server<-> Child Communications.
const char kTestChannelID[] = "T1";

// Launch the child process:
// |nss_path| - path to the NSS directory holding the decryption libraries.
// |channel| - IPC Channel to use for communication.
// |handle| - On return, the process handle to use to communicate with the
// child.
bool LaunchNSSDecrypterChildProcess(const FilePath& nss_path,
    IPC::Channel* channel, base::ProcessHandle* handle) {
  CommandLine cl(*CommandLine::ForCurrentProcess());
  cl.AppendSwitchASCII(switches::kTestChildProcess, "NSSDecrypterChildProcess");

  // Set env variable needed for FF encryption libs to load.
  // See "chrome/browser/importer/nss_decryptor_mac.mm" for an explanation of
  // why we need this.
  base::EnvironmentVector env;
  std::pair<std::string, std::string> dyld_override;
  dyld_override.first = "DYLD_FALLBACK_LIBRARY_PATH";
  dyld_override.second = nss_path.value();
  env.push_back(dyld_override);

  int ipcfd = channel->TakeClientFileDescriptor();
  if (ipcfd == -1)
    return false;

  file_util::ScopedFD client_file_descriptor_closer(&ipcfd);
  base::FileHandleMappingVector fds_to_map;
  fds_to_map.push_back(std::pair<int,int>(ipcfd, kPrimaryIPCChannel + 3));

  bool debug_on_start = CommandLine::ForCurrentProcess()->HasSwitch(
                            switches::kDebugChildren);
  base::LaunchOptions options;
  options.environ = &env;
  options.fds_to_remap = &fds_to_map;
  options.wait = debug_on_start;
  return base::LaunchProcess(cl.argv(), options, handle);
}

}  // namespace

//----------------------- Server --------------------

// Class to communicate on the server side of the IPC Channel.
// Method calls are sent over IPC and replies are read back into class
// variables.
// This class needs to be called on a single thread.
class FFDecryptorServerChannelListener : public IPC::Channel::Listener {
 public:
  FFDecryptorServerChannelListener()
      : got_result(false), sender_(NULL) {}

  void SetSender(IPC::Message::Sender* sender) {
    sender_ = sender;
  }

  void OnInitDecryptorResponse(bool result) {
    DCHECK(!got_result);
    result_bool = result;
    got_result = true;
    MessageLoop::current()->Quit();
  }

  void OnDecryptedTextResonse(const string16& decrypted_text) {
    DCHECK(!got_result);
    result_string = decrypted_text;
    got_result = true;
    MessageLoop::current()->Quit();
  }

  void QuitClient() {
    if (sender_)
      sender_->Send(new Msg_Decryptor_Quit());
  }

  virtual bool OnMessageReceived(const IPC::Message& msg) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(FFDecryptorServerChannelListener, msg)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_InitReturnCode, OnInitDecryptorResponse)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_Response, OnDecryptedTextResonse)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

  // If an error occured, just kill the message Loop.
  virtual void OnChannelError() {
    got_result = false;
    MessageLoop::current()->Quit();
  }

  // Results of IPC calls.
  string16 result_string;
  bool result_bool;
  // True if IPC call succeeded and data in above variables is valid.
  bool got_result;

 private:
  IPC::Message::Sender* sender_;  // weak
};

FFUnitTestDecryptorProxy::FFUnitTestDecryptorProxy()
    : child_process_(0) {
}

bool FFUnitTestDecryptorProxy::Setup(const FilePath& nss_path) {
  // Create a new message loop and spawn the child process.
  message_loop_.reset(new MessageLoopForIO());

  listener_.reset(new FFDecryptorServerChannelListener());
  channel_.reset(new IPC::Channel(kTestChannelID,
                                  IPC::Channel::MODE_SERVER,
                                  listener_.get()));
  CHECK(channel_->Connect());
  listener_->SetSender(channel_.get());

  // Spawn child and set up sync IPC connection.
  bool ret = LaunchNSSDecrypterChildProcess(nss_path,
                                            channel_.get(),
                                            &child_process_);
  return ret && (child_process_ != 0);
}

FFUnitTestDecryptorProxy::~FFUnitTestDecryptorProxy() {
  listener_->QuitClient();
  channel_->Close();

  if (child_process_) {
    base::WaitForSingleProcess(child_process_, 5000);
    base::CloseProcessHandle(child_process_);
  }
}

// A message_loop task that quits the message loop when invoked, setting cancel
// causes the task to do nothing when invoked.
class CancellableQuitMsgLoop : public base::RefCounted<CancellableQuitMsgLoop> {
 public:
  CancellableQuitMsgLoop() : cancelled_(false) {}
  void QuitNow() {
    if (!cancelled_)
      MessageLoop::current()->Quit();
  }
  bool cancelled_;
};

// Spin until either a client response arrives or a timeout occurs.
bool FFUnitTestDecryptorProxy::WaitForClientResponse() {
  // What we're trying to do here is to wait for an RPC message to go over the
  // wire and the client to reply.  If the client does not reply by a given
  // timeout we kill the message loop.
  // The way we do this is to post a CancellableQuitMsgLoop for 3 seconds in
  // the future and cancel it if an RPC message comes back earlier.
  // This relies on the IPC listener class to quit the message loop itself when
  // a message comes in.
  scoped_refptr<CancellableQuitMsgLoop> quit_task(
      new CancellableQuitMsgLoop());
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&CancellableQuitMsgLoop::QuitNow, quit_task.get()),
      TestTimeouts::action_max_timeout());

  message_loop_->Run();
  bool ret = !quit_task->cancelled_;
  quit_task->cancelled_ = false;
  return ret;
}

bool FFUnitTestDecryptorProxy::DecryptorInit(const FilePath& dll_path,
                                             const FilePath& db_path) {
  channel_->Send(new Msg_Decryptor_Init(dll_path, db_path));
  bool ok = WaitForClientResponse();
  if (ok && listener_->got_result) {
    listener_->got_result = false;
    return listener_->result_bool;
  }
  return false;
}

string16 FFUnitTestDecryptorProxy::Decrypt(const std::string& crypt) {
  channel_->Send(new Msg_Decrypt(crypt));
  bool ok = WaitForClientResponse();
  if (ok && listener_->got_result) {
    listener_->got_result = false;
    return listener_->result_string;
  }
  return string16();
}

//---------------------------- Child Process -----------------------

// Class to listen on the client side of the ipc channel, it calls through
// to the NSSDecryptor and sends back a reply.
class FFDecryptorClientChannelListener : public IPC::Channel::Listener {
 public:
  FFDecryptorClientChannelListener()
      : sender_(NULL) {}

  void SetSender(IPC::Message::Sender* sender) {
    sender_ = sender;
  }

  void OnDecryptor_Init(FilePath dll_path, FilePath db_path) {
    bool ret = decryptor_.Init(dll_path, db_path);
    sender_->Send(new Msg_Decryptor_InitReturnCode(ret));
  }

  void OnDecrypt(std::string crypt) {
    string16 unencrypted_str = decryptor_.Decrypt(crypt);
    sender_->Send(new Msg_Decryptor_Response(unencrypted_str));
  }

  void OnQuitRequest() {
    MessageLoop::current()->Quit();
  }

  virtual bool OnMessageReceived(const IPC::Message& msg) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(FFDecryptorClientChannelListener, msg)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_Init, OnDecryptor_Init)
      IPC_MESSAGE_HANDLER(Msg_Decrypt, OnDecrypt)
      IPC_MESSAGE_HANDLER(Msg_Decryptor_Quit, OnQuitRequest)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

  virtual void OnChannelError() {
    MessageLoop::current()->Quit();
  }

 private:
  NSSDecryptor decryptor_;
  IPC::Message::Sender* sender_;
};

// Entry function in child process.
MULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) {
  MessageLoopForIO main_message_loop;
  FFDecryptorClientChannelListener listener;

  IPC::Channel channel(kTestChannelID, IPC::Channel::MODE_CLIENT, &listener);
  CHECK(channel.Connect());
  listener.SetSender(&channel);

  // run message loop
  MessageLoop::current()->Run();

  return 0;
}
<|endoftext|>


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

#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif

namespace connectivity
{
    //**************************************************************
    //************ Class: ODatabaseMetaDataResultSetMetaData
    //**************************************************************
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>   ODatabaseMetaResultSetMetaData_BASE;

    class ODatabaseMetaDataResultSetMetaData :  public  ODatabaseMetaResultSetMetaData_BASE
    {
        TIntVector                                  m_vMapping; // when not every column is needed
        ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
        ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;

        sal_Int32                                   m_nColCount;
    protected:
        virtual ~ODatabaseMetaDataResultSetMetaData();
    public:
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        ODatabaseMetaDataResultSetMetaData( )
                :   m_nColCount(0)
        {
        }
        /// Avoid ambigous cast error from the compiler.
        inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
        { return this; }

        virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        // methods to set the right column mapping
        void setColumnPrivilegesMap();
        void setColumnMap();
        void setColumnsMap();
        void setTableNameMap();
        void setTablesMap();
        void setProcedureColumnsMap();
        void setPrimaryKeysMap();
        void setIndexInfoMap();
        void setTablePrivilegesMap();
        void setCrossReferenceMap();
        void setTypeInfoMap();
        void setProcedureNameMap();
        void setProceduresMap();
        void setTableTypes();
        void setBestRowIdentifierMap() { setVersionColumnsMap();}
        void setVersionColumnsMap();
        void setExportedKeysMap() { setCrossReferenceMap(); }
        void setImportedKeysMap() { setCrossReferenceMap(); }
        void setCatalogsMap();
        void setSchemasMap();
    };
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.6.122); FILE MERGED 2008/04/01 15:09:05 thb 1.6.122.3: #i85898# Stripping all external header guards 2008/04/01 10:53:16 thb 1.6.122.2: #i85898# Stripping all external header guards 2008/03/28 15:24:04 rt 1.6.122.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: FDatabaseMetaDataResultSetMetaData.hxx,v $
 * $Revision: 1.7 $
 *
 * 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 _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_

#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <cppuhelper/implbase1.hxx>
#ifndef _VECTOR_
#include <vector>
#endif
#include "FDatabaseMetaDataResultSet.hxx"
#include "OColumn.hxx"
#include "connectivity/StdTypeDefs.hxx"

namespace connectivity
{
    //**************************************************************
    //************ Class: ODatabaseMetaDataResultSetMetaData
    //**************************************************************
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>   ODatabaseMetaResultSetMetaData_BASE;

    class ODatabaseMetaDataResultSetMetaData :  public  ODatabaseMetaResultSetMetaData_BASE
    {
        TIntVector                                  m_vMapping; // when not every column is needed
        ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
        ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;

        sal_Int32                                   m_nColCount;
    protected:
        virtual ~ODatabaseMetaDataResultSetMetaData();
    public:
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        ODatabaseMetaDataResultSetMetaData( )
                :   m_nColCount(0)
        {
        }
        /// Avoid ambigous cast error from the compiler.
        inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
        { return this; }

        virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        // methods to set the right column mapping
        void setColumnPrivilegesMap();
        void setColumnMap();
        void setColumnsMap();
        void setTableNameMap();
        void setTablesMap();
        void setProcedureColumnsMap();
        void setPrimaryKeysMap();
        void setIndexInfoMap();
        void setTablePrivilegesMap();
        void setCrossReferenceMap();
        void setTypeInfoMap();
        void setProcedureNameMap();
        void setProceduresMap();
        void setTableTypes();
        void setBestRowIdentifierMap() { setVersionColumnsMap();}
        void setVersionColumnsMap();
        void setExportedKeysMap() { setCrossReferenceMap(); }
        void setImportedKeysMap() { setCrossReferenceMap(); }
        void setCatalogsMap();
        void setSchemasMap();
    };
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_

<|endoftext|>