<commit_before>#include "BooPHF.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <random>

using namespace std;

typedef boomphf::SingleHashFunctor<u_int64_t>  hasher_t;
typedef boomphf::mphf<  u_int64_t, hasher_t  > boophf_t;

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

	//PARAMETERS
	u_int64_t nelem = 1000000;
	uint nthreads = 1;

	if(argc !=3 ){
		printf("Usage :\n");
		printf("%s <nelem> <nthreads> \n",argv[0]);
		return EXIT_FAILURE;
	}

	if(argc ==3 ){
		nelem = strtoul(argv[1], NULL,0);
		nthreads = atoi(argv[2]);
	}

	uint64_t ii, jj;
	u_int64_t *data;

	/////  generation of random keys
	uint64_t rab = 100;
	static std::mt19937_64 rng;
	rng.seed(std::mt19937_64::default_seed); //default seed

	//rng.seed(seed2); //random seed from timer
	data = (u_int64_t * ) calloc(nelem+rab,sizeof(u_int64_t));

	for (u_int64_t i = 1; i < nelem+rab; i++){
		data[i] = rng();
	}
	printf("de-duplicating items \n");

	std::sort(data,data+nelem+rab);

	for (ii = 1, jj = 0; ii < nelem+rab; ii++) {
		if (data[ii] != data[jj])
			data[++jj] = data[ii];
	}
	printf("found %lli duplicated items  \n",nelem+rab-(jj + 1) );

	//////////////////
	// at this point, array data contains a set of nelem random unique keys

	boophf_t * bphf = NULL;
	double t_begin,t_end; struct timeval timet;

	printf("Construct a BooPHF with  %lli elements  \n",nelem);

	gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);

	// mphf takes as input a c++ range. A simple array of keys can be wrapped with boomphf::range
	// but could be from a user defined iterator (enabling keys to be read from a file or from some complex non-contiguous structure)
	auto data_iterator = boomphf::range(static_cast<const u_int64_t*>(data), static_cast<const u_int64_t*>(data+nelem));

	double gammaFactor = 1.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query

	//build the mphf
	bphf = new boomphf::mphf<u_int64_t,hasher_t>(nelem,data_iterator,nthreads,gammaFactor);

	gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
	double elapsed = t_end - t_begin;

	printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", nelem,elapsed);
	printf("boophf  bits/elem : %f\n",(float) (bphf->totalBitSize())/nelem);

	//query mphf like this
	uint64_t  idx = bphf->lookup(data[0]);
	printf(" example query  %lli ----->  %llu \n",data[0],idx);

	free(data);
	delete bphf;
	return EXIT_SUCCESS;
}
<commit_msg>compil<commit_after>#include "BooPHF.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <random>
#include <algorithm>

using namespace std;

typedef boomphf::SingleHashFunctor<u_int64_t>  hasher_t;
typedef boomphf::mphf<  u_int64_t, hasher_t  > boophf_t;

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

	//PARAMETERS
	u_int64_t nelem = 1000000;
	uint nthreads = 1;

	if(argc !=3 ){
		printf("Usage :\n");
		printf("%s <nelem> <nthreads> \n",argv[0]);
		return EXIT_FAILURE;
	}

	if(argc ==3 ){
		nelem = strtoul(argv[1], NULL,0);
		nthreads = atoi(argv[2]);
	}

	uint64_t ii, jj;
	u_int64_t *data;

	/////  generation of random keys
	uint64_t rab = 100;
	static std::mt19937_64 rng;
	rng.seed(std::mt19937_64::default_seed); //default seed

	//rng.seed(seed2); //random seed from timer
	data = (u_int64_t * ) calloc(nelem+rab,sizeof(u_int64_t));

	for (u_int64_t i = 1; i < nelem+rab; i++){
		data[i] = rng();
	}
	printf("de-duplicating items \n");

	std::sort(data,data+nelem+rab);

	for (ii = 1, jj = 0; ii < nelem+rab; ii++) {
		if (data[ii] != data[jj])
			data[++jj] = data[ii];
	}
	printf("found %lli duplicated items  \n",nelem+rab-(jj + 1) );

	//////////////////
	// at this point, array data contains a set of nelem random unique keys

	boophf_t * bphf = NULL;
	double t_begin,t_end; struct timeval timet;

	printf("Construct a BooPHF with  %lli elements  \n",nelem);

	gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);

	// mphf takes as input a c++ range. A simple array of keys can be wrapped with boomphf::range
	// but could be from a user defined iterator (enabling keys to be read from a file or from some complex non-contiguous structure)
	auto data_iterator = boomphf::range(static_cast<const u_int64_t*>(data), static_cast<const u_int64_t*>(data+nelem));

	double gammaFactor = 1.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query

	//build the mphf
	bphf = new boomphf::mphf<u_int64_t,hasher_t>(nelem,data_iterator,nthreads,gammaFactor);

	gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
	double elapsed = t_end - t_begin;

	printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", nelem,elapsed);
	printf("boophf  bits/elem : %f\n",(float) (bphf->totalBitSize())/nelem);

	//query mphf like this
	uint64_t  idx = bphf->lookup(data[0]);
	printf(" example query  %lli ----->  %llu \n",data[0],idx);

	free(data);
	delete bphf;
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <configuration.hpp>
#include <CommandLine.hpp>
#include <Kernels.hpp>
#include <Memory.hpp>
#include <Pipeline.hpp>

int main(int argc, char *argv[])
{
    // Command line options
    Options options{};
    DeviceOptions deviceOptions{};
    DataOptions dataOptions{};
    GeneratorOptions generatorOptions{};
    // Memory
    HostMemory hostMemory{};
    DeviceMemory deviceMemory{};
    HostMemoryDumpFiles hostMemoryDumpFiles{};
    // OpenCL kernels
    OpenCLRunTime openclRunTime{};
    KernelConfigurations kernelConfigurations{};
    Kernels kernels{};
    KernelRunTimeConfigurations kernelRunTimeConfigurations{};
    // Timers
    Timers timers{};
    // Observation
    AstroData::Observation observation;

    // Process command line arguments
    isa::utils::ArgumentList args(argc, argv);
    try
    {
        processCommandLineOptions(args, options, deviceOptions, dataOptions, hostMemoryDumpFiles, kernelConfigurations, generatorOptions, observation);
    }
    catch (std::exception &err)
    {
        return 1;
    }

    // Load or generate input data
    try
    {
        try
        {
            hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int)));
        }
        catch (std::out_of_range &err)
        {
            std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl;
            return 1;
        }
        try
        {
            AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels);
            AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps);
        }
        catch (AstroData::FileError &err)
        {
            std::cerr << err.what() << std::endl;
            return 1;
        }
        hostMemory.input.resize(observation.getNrBeams());
        if (dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA)
        {
            loadInput(observation, deviceOptions, dataOptions, hostMemory, timers);
        }
        else
        {
            for (unsigned int beam = 0; beam < observation.getNrBeams(); beam++)
            {
                // TODO: if there are multiple synthesized beams, the generated data should take this into account
                hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches());
                AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random);
            }
        }
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        return 1;
    }

    // Print message with observation and search information
    if (options.print)
    {
        std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", ";
        std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl;
        std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl;
        std::cout << std::endl;
        std::cout << "Beams: " << observation.getNrBeams() << std::endl;
        std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl;
        std::cout << "Batches: " << observation.getNrBatches() << std::endl;
        std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl;
        std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl;
        std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz";
        std::cout << std::endl;
        std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)";
        std::cout << std::endl;
        std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)";
        std::cout << std::endl;
        std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl;
        std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl;
        if (options.subbandDedispersion)
        {
            std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", ";
            std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true));
            std::cout << ")" << std::endl;
        }
        std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", ";
        std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")";
        std::cout << std::endl;
        std::cout << std::endl;
    }

    // Initialize OpenCL
    openclRunTime.context = new cl::Context();
    openclRunTime.platforms = new std::vector<cl::Platform>();
    openclRunTime.devices = new std::vector<cl::Device>();
    openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>();
    try
    {
        isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues);
    }
    catch (isa::OpenCL::OpenCLError &err)
    {
        std::cerr << err.what() << std::endl;
        return 1;
    }

    // Memory allocation
    allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory);
    if (observation.getNrDelayBatches() > observation.getNrBatches())
    {
        std::cerr << "Not enough input batches for the specified search." << std::endl;
        return 1;
    }
    try
    {
        allocateDeviceMemory(observation, openclRunTime, options, deviceOptions, hostMemory, deviceMemory);
    }
    catch (cl::Error &err)
    {
        std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl;
        return 1;
    }

    // Generate OpenCL kernels
    try
    {
        generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels);
    }
    catch (std::exception &err)
    {
        std::cerr << "OpenCL code generation error: " << err.what() << std::endl;
        return 1;
    }

    // Generate run time configurations for the OpenCL kernels
    generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations);

    // Search loop
    pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations, kernelRunTimeConfigurations, hostMemory, deviceMemory, hostMemoryDumpFiles);

    // Store performance statistics before shutting down
    std::ofstream outputStats;
    outputStats.open(dataOptions.outputFile + ".stats");
    outputStats << std::fixed << std::setprecision(6);
    outputStats << "# nrDMs" << std::endl;
    if (options.subbandDedispersion)
    {
        outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl;
    }
    else
    {
        outputStats << observation.getNrDMs() << std::endl;
    }
    outputStats << "# timers.inputLoad" << std::endl;
    outputStats << timers.inputLoad.getTotalTime() << std::endl;
    outputStats << "# timers.search" << std::endl;
    outputStats << timers.search.getTotalTime() << std::endl;
    outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl;
    outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " ";
    outputStats << timers.inputHandling.getStandardDeviation() << std::endl;
    outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl;
    outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " ";
    outputStats << timers.inputCopy.getStandardDeviation() << std::endl;
    if (!options.subbandDedispersion)
    {
        outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl;
        outputStats << timers.dedispersionSingleStep.getTotalTime() << " ";
        outputStats << timers.dedispersionSingleStep.getAverageTime() << " ";
        outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl;
    }
    else
    {
        outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl;
        outputStats << timers.dedispersionStepOne.getTotalTime() << " ";
        outputStats << timers.dedispersionStepOne.getAverageTime() << " ";
        outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl;
        outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl;
        outputStats << timers.dedispersionStepTwo.getTotalTime() << " ";
        outputStats << timers.dedispersionStepTwo.getAverageTime() << " ";
        outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl;
    }
    outputStats << "# integrationTotal integrationAvg err" << std::endl;
    outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " ";
    outputStats << timers.integration.getStandardDeviation() << std::endl;
    if (options.snrMode == SNRMode::Standard)
    {
        outputStats << "# snrTotal snrAvg err" << std::endl;
        outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " ";
        outputStats << timers.snr.getStandardDeviation() << std::endl;
    }
    else if (options.snrMode == SNRMode::Momad)
    {
        outputStats << "# maxTotal maxAvg err" << std::endl;
        outputStats << timers.max.getTotalTime() << " " << timers.max.getAverageTime() << " ";
        outputStats << timers.max.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansStepOneTotal medianOfMediansStepOneAvg err" << std::endl;
        outputStats << timers.medianOfMediansStepOne.getTotalTime() << " " << timers.medianOfMediansStepOne.getAverageTime() << " ";
        outputStats << timers.medianOfMediansStepOne.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansStepTwoTotal medianOfMediansStepTwoAvg err" << std::endl;
        outputStats << timers.medianOfMediansStepTwo.getTotalTime() << " " << timers.medianOfMediansStepTwo.getAverageTime() << " ";
        outputStats << timers.medianOfMediansStepTwo.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansAbsoluteDeviationStepOneTotal medianOfMediansAbsoluteDeviationStepOneAvg err" << std::endl;
        outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepOne.getAverageTime() << " ";
        outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansAbsoluteDeviationStepTwoTotal medianOfMediansAbsoluteDeviationStepTwoAvg err" << std::endl;
        outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepTwo.getAverageTime() << " ";
        outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getStandardDeviation() << std::endl;
    }
    outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl;
    outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " ";
    outputStats << timers.outputCopy.getStandardDeviation() << std::endl;
    outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl;
    outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " ";
    outputStats << timers.trigger.getStandardDeviation() << std::endl;
    outputStats.close();

    return 0;
}
<commit_msg>Leon's patch to load the integration steps correctly.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <configuration.hpp>
#include <CommandLine.hpp>
#include <Kernels.hpp>
#include <Memory.hpp>
#include <Pipeline.hpp>

int main(int argc, char *argv[])
{
    // Command line options
    Options options{};
    DeviceOptions deviceOptions{};
    DataOptions dataOptions{};
    GeneratorOptions generatorOptions{};
    // Memory
    HostMemory hostMemory{};
    DeviceMemory deviceMemory{};
    HostMemoryDumpFiles hostMemoryDumpFiles{};
    // OpenCL kernels
    OpenCLRunTime openclRunTime{};
    KernelConfigurations kernelConfigurations{};
    Kernels kernels{};
    KernelRunTimeConfigurations kernelRunTimeConfigurations{};
    // Timers
    Timers timers{};
    // Observation
    AstroData::Observation observation;

    // Process command line arguments
    isa::utils::ArgumentList args(argc, argv);
    try
    {
        processCommandLineOptions(args, options, deviceOptions, dataOptions, hostMemoryDumpFiles, kernelConfigurations, generatorOptions, observation);
    }
    catch (std::exception &err)
    {
        return 1;
    }

    // Load or generate input data
    try
    {
        hostMemory.input.resize(observation.getNrBeams());
        if (dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA)
        {
            loadInput(observation, deviceOptions, dataOptions, hostMemory, timers);
        }
        else
        {
            for (unsigned int beam = 0; beam < observation.getNrBeams(); beam++)
            {
                // TODO: if there are multiple synthesized beams, the generated data should take this into account
                hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches());
                AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random);
            }
        }
        try
        {
            hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int)));
        }
        catch (std::out_of_range &err)
        {
            std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl;
            return 1;
        }
        try
        {
            AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels);
            AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps);
        }
        catch (AstroData::FileError &err)
        {
            std::cerr << err.what() << std::endl;
            return 1;
        }
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        return 1;
    }

    // Print message with observation and search information
    if (options.print)
    {
        std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", ";
        std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl;
        std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl;
        std::cout << std::endl;
        std::cout << "Beams: " << observation.getNrBeams() << std::endl;
        std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl;
        std::cout << "Batches: " << observation.getNrBatches() << std::endl;
        std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl;
        std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl;
        std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz";
        std::cout << std::endl;
        std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)";
        std::cout << std::endl;
        std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)";
        std::cout << std::endl;
        std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl;
        std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl;
        if (options.subbandDedispersion)
        {
            std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", ";
            std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true));
            std::cout << ")" << std::endl;
        }
        std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", ";
        std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")";
        std::cout << std::endl;
        std::cout << std::endl;
    }

    // Initialize OpenCL
    openclRunTime.context = new cl::Context();
    openclRunTime.platforms = new std::vector<cl::Platform>();
    openclRunTime.devices = new std::vector<cl::Device>();
    openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>();
    try
    {
        isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues);
    }
    catch (isa::OpenCL::OpenCLError &err)
    {
        std::cerr << err.what() << std::endl;
        return 1;
    }

    // Memory allocation
    allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory);
    if (observation.getNrDelayBatches() > observation.getNrBatches())
    {
        std::cerr << "Not enough input batches for the specified search." << std::endl;
        return 1;
    }
    try
    {
        allocateDeviceMemory(observation, openclRunTime, options, deviceOptions, hostMemory, deviceMemory);
    }
    catch (cl::Error &err)
    {
        std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl;
        return 1;
    }

    // Generate OpenCL kernels
    try
    {
        generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels);
    }
    catch (std::exception &err)
    {
        std::cerr << "OpenCL code generation error: " << err.what() << std::endl;
        return 1;
    }

    // Generate run time configurations for the OpenCL kernels
    generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations);

    // Search loop
    pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations, kernelRunTimeConfigurations, hostMemory, deviceMemory, hostMemoryDumpFiles);

    // Store performance statistics before shutting down
    std::ofstream outputStats;
    outputStats.open(dataOptions.outputFile + ".stats");
    outputStats << std::fixed << std::setprecision(6);
    outputStats << "# nrDMs" << std::endl;
    if (options.subbandDedispersion)
    {
        outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl;
    }
    else
    {
        outputStats << observation.getNrDMs() << std::endl;
    }
    outputStats << "# timers.inputLoad" << std::endl;
    outputStats << timers.inputLoad.getTotalTime() << std::endl;
    outputStats << "# timers.search" << std::endl;
    outputStats << timers.search.getTotalTime() << std::endl;
    outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl;
    outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " ";
    outputStats << timers.inputHandling.getStandardDeviation() << std::endl;
    outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl;
    outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " ";
    outputStats << timers.inputCopy.getStandardDeviation() << std::endl;
    if (!options.subbandDedispersion)
    {
        outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl;
        outputStats << timers.dedispersionSingleStep.getTotalTime() << " ";
        outputStats << timers.dedispersionSingleStep.getAverageTime() << " ";
        outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl;
    }
    else
    {
        outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl;
        outputStats << timers.dedispersionStepOne.getTotalTime() << " ";
        outputStats << timers.dedispersionStepOne.getAverageTime() << " ";
        outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl;
        outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl;
        outputStats << timers.dedispersionStepTwo.getTotalTime() << " ";
        outputStats << timers.dedispersionStepTwo.getAverageTime() << " ";
        outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl;
    }
    outputStats << "# integrationTotal integrationAvg err" << std::endl;
    outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " ";
    outputStats << timers.integration.getStandardDeviation() << std::endl;
    if (options.snrMode == SNRMode::Standard)
    {
        outputStats << "# snrTotal snrAvg err" << std::endl;
        outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " ";
        outputStats << timers.snr.getStandardDeviation() << std::endl;
    }
    else if (options.snrMode == SNRMode::Momad)
    {
        outputStats << "# maxTotal maxAvg err" << std::endl;
        outputStats << timers.max.getTotalTime() << " " << timers.max.getAverageTime() << " ";
        outputStats << timers.max.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansStepOneTotal medianOfMediansStepOneAvg err" << std::endl;
        outputStats << timers.medianOfMediansStepOne.getTotalTime() << " " << timers.medianOfMediansStepOne.getAverageTime() << " ";
        outputStats << timers.medianOfMediansStepOne.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansStepTwoTotal medianOfMediansStepTwoAvg err" << std::endl;
        outputStats << timers.medianOfMediansStepTwo.getTotalTime() << " " << timers.medianOfMediansStepTwo.getAverageTime() << " ";
        outputStats << timers.medianOfMediansStepTwo.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansAbsoluteDeviationStepOneTotal medianOfMediansAbsoluteDeviationStepOneAvg err" << std::endl;
        outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepOne.getAverageTime() << " ";
        outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getStandardDeviation() << std::endl;
        outputStats << "# medianOfMediansAbsoluteDeviationStepTwoTotal medianOfMediansAbsoluteDeviationStepTwoAvg err" << std::endl;
        outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepTwo.getAverageTime() << " ";
        outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getStandardDeviation() << std::endl;
    }
    outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl;
    outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " ";
    outputStats << timers.outputCopy.getStandardDeviation() << std::endl;
    outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl;
    outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " ";
    outputStats << timers.trigger.getStandardDeviation() << std::endl;
    outputStats.close();

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2013 Anant Kamath <kamathanant@gmail.com>
 *
 * 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 "main-options-widget.h"

#include <QtGui/QDataWidgetMapper>

#include <ModemManagerQt/manager.h>
#include <ModemManagerQt/modemgsmcardinterface.h>

#include <KCMTelepathyAccounts/ParameterEditModel>

#include "modem-combobox.h"

MainOptionsWidget::MainOptionsWidget(ParameterEditModel *model,
                                     QWidget *parent)
 : AbstractAccountParametersWidget(model, parent)
{
    m_ui = new Ui::MainOptionsWidget;
    m_ui->setupUi(this);

    handleParameter(QLatin1String("number"), QVariant::String, m_ui->numberLineEdit, m_ui->numberLabel);
    handleParameter(QLatin1String("simIdentifier"), QVariant::String, m_ui->comboBox, m_ui->modemLabel);
    QTimer::singleShot(0, m_ui->numberLineEdit, SLOT(setFocus()));
}

MainOptionsWidget::~MainOptionsWidget()
{
    delete m_ui;
}

QString MainOptionsWidget::defaultDisplayName() const
{
    return parameterModel()->data(parameterModel()->indexForParameter(parameterModel()->parameter(QLatin1String("number")))).toString();
}

#include "main-options-widget.moc"
<commit_msg>Added correct property to be mapped for modemComboBox<commit_after>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2013 Anant Kamath <kamathanant@gmail.com>
 *
 * 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 "main-options-widget.h"

#include <QtGui/QDataWidgetMapper>

#include <ModemManagerQt/manager.h>
#include <ModemManagerQt/modemgsmcardinterface.h>

#include <KCMTelepathyAccounts/ParameterEditModel>

#include "modem-combobox.h"

MainOptionsWidget::MainOptionsWidget(ParameterEditModel *model,
                                     QWidget *parent)
 : AbstractAccountParametersWidget(model, parent)
{
    m_ui = new Ui::MainOptionsWidget;
    m_ui->setupUi(this);

    handleParameter(QLatin1String("number"), QVariant::String, m_ui->numberLineEdit, m_ui->numberLabel);
    handleParameter(QLatin1String("simIdentifier"), QVariant::String, m_ui->comboBox, m_ui->modemLabel, "selectedSimIdentifier");
    QTimer::singleShot(0, m_ui->numberLineEdit, SLOT(setFocus()));
}

MainOptionsWidget::~MainOptionsWidget()
{
    delete m_ui;
}

QString MainOptionsWidget::defaultDisplayName() const
{
    return parameterModel()->data(parameterModel()->indexForParameter(parameterModel()->parameter(QLatin1String("number")))).toString();
}

#include "main-options-widget.moc"
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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.
 *
 ************************************************************************/

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

#include "osl/diagnose.h"
#include "rtl/strbuf.hxx"
#include "NeonTypes.hxx"
#include "DAVException.hxx"
#include "DAVProperties.hxx"
#include "NeonPropFindRequest.hxx"
#include "LinkSequence.hxx"
#include "LockSequence.hxx"
#include "LockEntrySequence.hxx"
#include "UCBDeadPropertyValue.hxx"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;

// -------------------------------------------------------------------
namespace
{
    // strip "DAV:" namespace from XML snippets to avoid
    // parser error (undeclared namespace) later on.
    rtl::OString stripDavNamespace( const rtl::OString & in )
    {
        const rtl::OString inXML( in.toAsciiLowerCase() );

        rtl::OStringBuffer buf;
        sal_Int32 start = 0;
        sal_Int32 end = inXML.indexOf( "dav:" );
        while ( end != -1 )
        {
            if ( inXML[ end - 1 ] == '<' ||
                 inXML[ end - 1 ] == '/' )
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start ) );
            }
            else
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start + 4 ) );
            }
            start = end + 4;
            end = inXML.indexOf( "dav:", start );
        }
        buf.append( inXML.copy( start ) );

        return rtl::OString( buf.makeStringAndClear() );
    }
}

// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
                                   const NeonPropName* pname,
                                   const char* value,
                                   const HttpStatus* status )
{
    /*
        HTTP Response Status Classes:

        - 1: Informational - Request received, continuing process

        - 2: Success - The action was successfully received,
          understood, and accepted

        - 3: Redirection - Further action must be taken in order to
          complete the request

        - 4: Client Error - The request contains bad syntax or cannot
          be fulfilled

        - 5: Server Error - The server failed to fulfill an apparently
          valid request
    */

    if ( status->klass > 2 )
        return 0; // Error getting this property. Go on.

    // Create & set the PropertyValue
    DAVPropertyValue thePropertyValue;
    thePropertyValue.IsCaseSensitive = true;

    OSL_ENSURE( pname->nspace, "NPFR_propfind_iter - No namespace!" );

    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      thePropertyValue.Name );
    bool bHasValue = false;
    if ( DAVProperties::isUCBDeadProperty( *pname ) )
    {
        // DAV dead property added by WebDAV UCP?
        if ( UCBDeadPropertyValue::createFromXML(
                 value, thePropertyValue.Value ) )
        {
            OSL_ENSURE( thePropertyValue.Value.hasValue(),
                        "NPFR_propfind_iter - No value!" );
            bHasValue = true;
        }
    }

    if ( !bHasValue )
    {
        if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "resourcetype" ) == 0 )
        {
            OString aValue( value );
            aValue = aValue.trim(); // #107358# remove leading/trailing spaces
            if ( aValue.getLength() )
            {
                aValue = stripDavNamespace( aValue ).toAsciiLowerCase();
                if ( aValue.compareTo(
                         RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
                {
                    thePropertyValue.Value
                        <<= OUString(RTL_CONSTASCII_USTRINGPARAM("collection"));
                }
            }

            if ( !thePropertyValue.Value.hasValue() )
            {
                // Take over the value exactly as supplied by the server.
                thePropertyValue.Value <<= OUString::createFromAscii( value );
            }
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "supportedlock" ) == 0 )
        {
            Sequence< LockEntry > aEntries;
            LockEntrySequence::createFromXML(
                stripDavNamespace( value ), aEntries );
            thePropertyValue.Value <<= aEntries;
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "lockdiscovery" ) == 0 )
        {
            Sequence< Lock > aLocks;
            LockSequence::createFromXML(
                stripDavNamespace( value ), aLocks );
            thePropertyValue.Value <<= aLocks;
        }
        else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
        {
            Sequence< Link > aLinks;
            LinkSequence::createFromXML(
                stripDavNamespace( value ), aLinks );
            thePropertyValue.Value <<= aLinks;
        }
        else
        {
            thePropertyValue.Value
                <<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
        }
    }

    // Add the newly created PropertyValue
    DAVResource* theResource = static_cast< DAVResource * >( userdata );
    theResource->properties.push_back( thePropertyValue );

    return 0; // Go on.
}

// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                       const ne_uri* uri,
#else
                                       const char* href,
#endif
                                       const NeonPropFindResultSet* set )
{
    // @@@ href is not the uri! DAVResource ctor wants uri!

#if NEON_VERSION >= 0x0260
    DAVResource theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResource theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    ne_propset_iterate( set, NPFR_propfind_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResource > * theResources
        = static_cast< vector< DAVResource > * >( userdata );
    theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
                                    const NeonPropName* pname,
                                    const char* /*value*/,
                                    const HttpStatus* /*status*/ )
{
    OUString aFullName;
    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      aFullName );

    DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
    theResource->properties.push_back( aFullName );
    return 0;
}

// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                        const ne_uri* uri,
#else
                                        const char* href,
#endif
                                        const NeonPropFindResultSet* results )
{
    // @@@ href is not the uri! DAVResourceInfo ctor wants uri!
    // Create entry for the resource.
#if NEON_VERSION >= 0x0260
    DAVResourceInfo theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResourceInfo theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    // Fill entry.
    ne_propset_iterate( results, NPFR_propnames_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResourceInfo > * theResources
        = static_cast< vector< DAVResourceInfo > * >( userdata );
    theResources->push_back( theResource );
}

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
                                          const char* inPath,
                                          const Depth inDepth,
                                          const vector< OUString >& inPropNames,
                                          vector< DAVResource >& ioResources,
                                          int & nError )
{
    // Generate the list of properties we're looking for
    int thePropCount = inPropNames.size();
    if ( thePropCount > 0 )
    {
        NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
        int theIndex;

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
        {
            // Split fullname into namespace and name!
            DAVProperties::createNeonPropName(
                inPropNames[ theIndex ], thePropNames[ theIndex ] );
        }
        thePropNames[ theIndex ].nspace = NULL;
        thePropNames[ theIndex ].name   = NULL;

        nError = ne_simple_propfind( inSession,
                                     inPath,
                                     inDepth,
                                     thePropNames,
                                     NPFR_propfind_results,
                                     &ioResources );

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
            free( (void *)thePropNames[ theIndex ].name );

        delete [] thePropNames;
    }
    else
    {
        // ALLPROP
        nError = ne_simple_propfind( inSession,
                                     inPath,
                                     inDepth,
                                     NULL, // 0 == allprop
                                     NPFR_propfind_results,
                                     &ioResources );
    }

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResources.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest(
                            HttpSession* inSession,
                            const char* inPath,
                            const Depth inDepth,
                            std::vector< DAVResourceInfo > & ioResInfo,
                            int & nError )
{
    nError = ne_propnames( inSession,
                           inPath,
                           inDepth,
                           NPFR_propnames_results,
                           &ioResInfo );

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResInfo.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Resolves: rhbz#668109 ne_simple_propfind can touch gcrypt as well<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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.
 *
 ************************************************************************/

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

#include "osl/diagnose.h"
#include "rtl/strbuf.hxx"
#include "NeonTypes.hxx"
#include "DAVException.hxx"
#include "DAVProperties.hxx"
#include "NeonPropFindRequest.hxx"
#include "LinkSequence.hxx"
#include "LockSequence.hxx"
#include "LockEntrySequence.hxx"
#include "UCBDeadPropertyValue.hxx"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;

// -------------------------------------------------------------------
namespace
{
    // strip "DAV:" namespace from XML snippets to avoid
    // parser error (undeclared namespace) later on.
    rtl::OString stripDavNamespace( const rtl::OString & in )
    {
        const rtl::OString inXML( in.toAsciiLowerCase() );

        rtl::OStringBuffer buf;
        sal_Int32 start = 0;
        sal_Int32 end = inXML.indexOf( "dav:" );
        while ( end != -1 )
        {
            if ( inXML[ end - 1 ] == '<' ||
                 inXML[ end - 1 ] == '/' )
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start ) );
            }
            else
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start + 4 ) );
            }
            start = end + 4;
            end = inXML.indexOf( "dav:", start );
        }
        buf.append( inXML.copy( start ) );

        return rtl::OString( buf.makeStringAndClear() );
    }
}

// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
                                   const NeonPropName* pname,
                                   const char* value,
                                   const HttpStatus* status )
{
    /*
        HTTP Response Status Classes:

        - 1: Informational - Request received, continuing process

        - 2: Success - The action was successfully received,
          understood, and accepted

        - 3: Redirection - Further action must be taken in order to
          complete the request

        - 4: Client Error - The request contains bad syntax or cannot
          be fulfilled

        - 5: Server Error - The server failed to fulfill an apparently
          valid request
    */

    if ( status->klass > 2 )
        return 0; // Error getting this property. Go on.

    // Create & set the PropertyValue
    DAVPropertyValue thePropertyValue;
    thePropertyValue.IsCaseSensitive = true;

    OSL_ENSURE( pname->nspace, "NPFR_propfind_iter - No namespace!" );

    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      thePropertyValue.Name );
    bool bHasValue = false;
    if ( DAVProperties::isUCBDeadProperty( *pname ) )
    {
        // DAV dead property added by WebDAV UCP?
        if ( UCBDeadPropertyValue::createFromXML(
                 value, thePropertyValue.Value ) )
        {
            OSL_ENSURE( thePropertyValue.Value.hasValue(),
                        "NPFR_propfind_iter - No value!" );
            bHasValue = true;
        }
    }

    if ( !bHasValue )
    {
        if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "resourcetype" ) == 0 )
        {
            OString aValue( value );
            aValue = aValue.trim(); // #107358# remove leading/trailing spaces
            if ( aValue.getLength() )
            {
                aValue = stripDavNamespace( aValue ).toAsciiLowerCase();
                if ( aValue.compareTo(
                         RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
                {
                    thePropertyValue.Value
                        <<= OUString(RTL_CONSTASCII_USTRINGPARAM("collection"));
                }
            }

            if ( !thePropertyValue.Value.hasValue() )
            {
                // Take over the value exactly as supplied by the server.
                thePropertyValue.Value <<= OUString::createFromAscii( value );
            }
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "supportedlock" ) == 0 )
        {
            Sequence< LockEntry > aEntries;
            LockEntrySequence::createFromXML(
                stripDavNamespace( value ), aEntries );
            thePropertyValue.Value <<= aEntries;
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "lockdiscovery" ) == 0 )
        {
            Sequence< Lock > aLocks;
            LockSequence::createFromXML(
                stripDavNamespace( value ), aLocks );
            thePropertyValue.Value <<= aLocks;
        }
        else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
        {
            Sequence< Link > aLinks;
            LinkSequence::createFromXML(
                stripDavNamespace( value ), aLinks );
            thePropertyValue.Value <<= aLinks;
        }
        else
        {
            thePropertyValue.Value
                <<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
        }
    }

    // Add the newly created PropertyValue
    DAVResource* theResource = static_cast< DAVResource * >( userdata );
    theResource->properties.push_back( thePropertyValue );

    return 0; // Go on.
}

// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                       const ne_uri* uri,
#else
                                       const char* href,
#endif
                                       const NeonPropFindResultSet* set )
{
    // @@@ href is not the uri! DAVResource ctor wants uri!

#if NEON_VERSION >= 0x0260
    DAVResource theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResource theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    ne_propset_iterate( set, NPFR_propfind_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResource > * theResources
        = static_cast< vector< DAVResource > * >( userdata );
    theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
                                    const NeonPropName* pname,
                                    const char* /*value*/,
                                    const HttpStatus* /*status*/ )
{
    OUString aFullName;
    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      aFullName );

    DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
    theResource->properties.push_back( aFullName );
    return 0;
}

// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                        const ne_uri* uri,
#else
                                        const char* href,
#endif
                                        const NeonPropFindResultSet* results )
{
    // @@@ href is not the uri! DAVResourceInfo ctor wants uri!
    // Create entry for the resource.
#if NEON_VERSION >= 0x0260
    DAVResourceInfo theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResourceInfo theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    // Fill entry.
    ne_propset_iterate( results, NPFR_propnames_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResourceInfo > * theResources
        = static_cast< vector< DAVResourceInfo > * >( userdata );
    theResources->push_back( theResource );
}

extern osl::Mutex aGlobalNeonMutex;

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
                                          const char* inPath,
                                          const Depth inDepth,
                                          const vector< OUString >& inPropNames,
                                          vector< DAVResource >& ioResources,
                                          int & nError )
{
    // Generate the list of properties we're looking for
    int thePropCount = inPropNames.size();
    if ( thePropCount > 0 )
    {
        NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
        int theIndex;

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
        {
            // Split fullname into namespace and name!
            DAVProperties::createNeonPropName(
                inPropNames[ theIndex ], thePropNames[ theIndex ] );
        }
        thePropNames[ theIndex ].nspace = NULL;
        thePropNames[ theIndex ].name   = NULL;

        {
            osl::Guard< osl::Mutex > theGlobalGuard( aGlobalNeonMutex );
            nError = ne_simple_propfind( inSession,
                                         inPath,
                                         inDepth,
                                         thePropNames,
                                         NPFR_propfind_results,
                                         &ioResources );
        }

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
            free( (void *)thePropNames[ theIndex ].name );

        delete [] thePropNames;
    }
    else
    {
        // ALLPROP
        osl::Guard< osl::Mutex > theGlobalGuard( aGlobalNeonMutex );
        nError = ne_simple_propfind( inSession,
                                     inPath,
                                     inDepth,
                                     NULL, // 0 == allprop
                                     NPFR_propfind_results,
                                     &ioResources );
    }

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResources.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest(
                            HttpSession* inSession,
                            const char* inPath,
                            const Depth inDepth,
                            std::vector< DAVResourceInfo > & ioResInfo,
                            int & nError )
{
    nError = ne_propnames( inSession,
                           inPath,
                           inDepth,
                           NPFR_propnames_results,
                           &ioResInfo );

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResInfo.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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.
 *
 ************************************************************************/

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

#include "osl/diagnose.h"
#include "rtl/strbuf.hxx"
#include "NeonTypes.hxx"
#include "DAVException.hxx"
#include "DAVProperties.hxx"
#include "NeonPropFindRequest.hxx"
#include "LinkSequence.hxx"
#include "LockSequence.hxx"
#include "LockEntrySequence.hxx"
#include "UCBDeadPropertyValue.hxx"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;

// -------------------------------------------------------------------
namespace
{
    // strip "DAV:" namespace from XML snippets to avoid
    // parser error (undeclared namespace) later on.
    rtl::OString stripDavNamespace( const rtl::OString & in )
    {
        const rtl::OString inXML( in.toAsciiLowerCase() );

        rtl::OStringBuffer buf;
        sal_Int32 start = 0;
        sal_Int32 end = inXML.indexOf( "dav:" );
        while ( end != -1 )
        {
            if ( inXML[ end - 1 ] == '<' ||
                 inXML[ end - 1 ] == '/' )
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start ) );
            }
            else
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start + 4 ) );
            }
            start = end + 4;
            end = inXML.indexOf( "dav:", start );
        }
        buf.append( inXML.copy( start ) );

        return rtl::OString( buf.makeStringAndClear() );
    }
}

// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
                                   const NeonPropName* pname,
                                   const char* value,
                                   const HttpStatus* status )
{
    /*
        HTTP Response Status Classes:

        - 1: Informational - Request received, continuing process

        - 2: Success - The action was successfully received,
          understood, and accepted

        - 3: Redirection - Further action must be taken in order to
          complete the request

        - 4: Client Error - The request contains bad syntax or cannot
          be fulfilled

        - 5: Server Error - The server failed to fulfill an apparently
          valid request
    */

    if ( status->klass > 2 )
        return 0; // Error getting this property. Go on.

    // Create & set the PropertyValue
    DAVPropertyValue thePropertyValue;
    thePropertyValue.IsCaseSensitive = true;

    OSL_ENSURE( pname->nspace, "NPFR_propfind_iter - No namespace!" );

    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      thePropertyValue.Name );
    bool bHasValue = false;
    if ( DAVProperties::isUCBDeadProperty( *pname ) )
    {
        // DAV dead property added by WebDAV UCP?
        if ( UCBDeadPropertyValue::createFromXML(
                 value, thePropertyValue.Value ) )
        {
            OSL_ENSURE( thePropertyValue.Value.hasValue(),
                        "NPFR_propfind_iter - No value!" );
            bHasValue = true;
        }
    }

    if ( !bHasValue )
    {
        if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "resourcetype" ) == 0 )
        {
            OString aValue( value );
            aValue = aValue.trim(); // #107358# remove leading/trailing spaces
            if ( aValue.getLength() )
            {
                aValue = stripDavNamespace( aValue ).toAsciiLowerCase();
                if ( aValue.compareTo(
                         RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
                {
                    thePropertyValue.Value
                        <<= OUString::createFromAscii( "collection" );
                }
            }

            if ( !thePropertyValue.Value.hasValue() )
            {
                // Take over the value exactly as supplied by the server.
                thePropertyValue.Value <<= OUString::createFromAscii( value );
            }
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "supportedlock" ) == 0 )
        {
            Sequence< LockEntry > aEntries;
            LockEntrySequence::createFromXML(
                stripDavNamespace( value ), aEntries );
            thePropertyValue.Value <<= aEntries;
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "lockdiscovery" ) == 0 )
        {
            Sequence< Lock > aLocks;
            LockSequence::createFromXML(
                stripDavNamespace( value ), aLocks );
            thePropertyValue.Value <<= aLocks;
        }
        else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
        {
            Sequence< Link > aLinks;
            LinkSequence::createFromXML(
                stripDavNamespace( value ), aLinks );
            thePropertyValue.Value <<= aLinks;
        }
        else
        {
            thePropertyValue.Value
                <<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
        }
    }

    // Add the newly created PropertyValue
    DAVResource* theResource = static_cast< DAVResource * >( userdata );
    theResource->properties.push_back( thePropertyValue );

    return 0; // Go on.
}

// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                       const ne_uri* uri,
#else
                                       const char* href,
#endif
                                       const NeonPropFindResultSet* set )
{
    // @@@ href is not the uri! DAVResource ctor wants uri!

#if NEON_VERSION >= 0x0260
    DAVResource theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResource theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    ne_propset_iterate( set, NPFR_propfind_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResource > * theResources
        = static_cast< vector< DAVResource > * >( userdata );
    theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
                                    const NeonPropName* pname,
                                    const char* /*value*/,
                                    const HttpStatus* /*status*/ )
{
    OUString aFullName;
    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      aFullName );

    DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
    theResource->properties.push_back( aFullName );
    return 0;
}

// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                        const ne_uri* uri,
#else
                                        const char* href,
#endif
                                        const NeonPropFindResultSet* results )
{
    // @@@ href is not the uri! DAVResourceInfo ctor wants uri!
    // Create entry for the resource.
#if NEON_VERSION >= 0x0260
    DAVResourceInfo theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResourceInfo theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    // Fill entry.
    ne_propset_iterate( results, NPFR_propnames_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResourceInfo > * theResources
        = static_cast< vector< DAVResourceInfo > * >( userdata );
    theResources->push_back( theResource );
}

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
                                          const char* inPath,
                                          const Depth inDepth,
                                          const vector< OUString >& inPropNames,
                                          vector< DAVResource >& ioResources,
                                          int & nError )
{
    // Generate the list of properties we're looking for
    int thePropCount = inPropNames.size();
    if ( thePropCount > 0 )
    {
        NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
        int theIndex;

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
        {
            // Split fullname into namespace and name!
            DAVProperties::createNeonPropName(
                inPropNames[ theIndex ], thePropNames[ theIndex ] );
        }
        thePropNames[ theIndex ].nspace = NULL;
        thePropNames[ theIndex ].name   = NULL;

        nError = ne_simple_propfind( inSession,
                                     inPath,
                                     inDepth,
                                     thePropNames,
                                     NPFR_propfind_results,
                                     &ioResources );

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
            free( (void *)thePropNames[ theIndex ].name );

        delete [] thePropNames;
    }
    else
    {
        // ALLPROP
        nError = ne_simple_propfind( inSession,
                                     inPath,
                                     inDepth,
                                     NULL, // 0 == allprop
                                     NPFR_propfind_results,
                                     &ioResources );
    }

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResources.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest(
                            HttpSession* inSession,
                            const char* inPath,
                            const Depth inDepth,
                            std::vector< DAVResourceInfo > & ioResInfo,
                            int & nError )
{
    nError = ne_propnames( inSession,
                           inPath,
                           inDepth,
                           NPFR_propnames_results,
                           &ioResInfo );

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResInfo.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Resolves: rhbz#661809 ne_simple_propfind can touch gcrypt as well<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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.
 *
 ************************************************************************/

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

#include "osl/diagnose.h"
#include "rtl/strbuf.hxx"
#include "NeonTypes.hxx"
#include "DAVException.hxx"
#include "DAVProperties.hxx"
#include "NeonPropFindRequest.hxx"
#include "LinkSequence.hxx"
#include "LockSequence.hxx"
#include "LockEntrySequence.hxx"
#include "UCBDeadPropertyValue.hxx"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;

// -------------------------------------------------------------------
namespace
{
    // strip "DAV:" namespace from XML snippets to avoid
    // parser error (undeclared namespace) later on.
    rtl::OString stripDavNamespace( const rtl::OString & in )
    {
        const rtl::OString inXML( in.toAsciiLowerCase() );

        rtl::OStringBuffer buf;
        sal_Int32 start = 0;
        sal_Int32 end = inXML.indexOf( "dav:" );
        while ( end != -1 )
        {
            if ( inXML[ end - 1 ] == '<' ||
                 inXML[ end - 1 ] == '/' )
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start ) );
            }
            else
            {
                // copy from original buffer - preserve case.
                buf.append( in.copy( start, end - start + 4 ) );
            }
            start = end + 4;
            end = inXML.indexOf( "dav:", start );
        }
        buf.append( inXML.copy( start ) );

        return rtl::OString( buf.makeStringAndClear() );
    }
}

// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
                                   const NeonPropName* pname,
                                   const char* value,
                                   const HttpStatus* status )
{
    /*
        HTTP Response Status Classes:

        - 1: Informational - Request received, continuing process

        - 2: Success - The action was successfully received,
          understood, and accepted

        - 3: Redirection - Further action must be taken in order to
          complete the request

        - 4: Client Error - The request contains bad syntax or cannot
          be fulfilled

        - 5: Server Error - The server failed to fulfill an apparently
          valid request
    */

    if ( status->klass > 2 )
        return 0; // Error getting this property. Go on.

    // Create & set the PropertyValue
    DAVPropertyValue thePropertyValue;
    thePropertyValue.IsCaseSensitive = true;

    OSL_ENSURE( pname->nspace, "NPFR_propfind_iter - No namespace!" );

    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      thePropertyValue.Name );
    bool bHasValue = false;
    if ( DAVProperties::isUCBDeadProperty( *pname ) )
    {
        // DAV dead property added by WebDAV UCP?
        if ( UCBDeadPropertyValue::createFromXML(
                 value, thePropertyValue.Value ) )
        {
            OSL_ENSURE( thePropertyValue.Value.hasValue(),
                        "NPFR_propfind_iter - No value!" );
            bHasValue = true;
        }
    }

    if ( !bHasValue )
    {
        if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "resourcetype" ) == 0 )
        {
            OString aValue( value );
            aValue = aValue.trim(); // #107358# remove leading/trailing spaces
            if ( aValue.getLength() )
            {
                aValue = stripDavNamespace( aValue ).toAsciiLowerCase();
                if ( aValue.compareTo(
                         RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
                {
                    thePropertyValue.Value
                        <<= OUString::createFromAscii( "collection" );
                }
            }

            if ( !thePropertyValue.Value.hasValue() )
            {
                // Take over the value exactly as supplied by the server.
                thePropertyValue.Value <<= OUString::createFromAscii( value );
            }
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "supportedlock" ) == 0 )
        {
            Sequence< LockEntry > aEntries;
            LockEntrySequence::createFromXML(
                stripDavNamespace( value ), aEntries );
            thePropertyValue.Value <<= aEntries;
        }
        else if ( rtl_str_compareIgnoreAsciiCase(
                                    pname->name, "lockdiscovery" ) == 0 )
        {
            Sequence< Lock > aLocks;
            LockSequence::createFromXML(
                stripDavNamespace( value ), aLocks );
            thePropertyValue.Value <<= aLocks;
        }
        else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
        {
            Sequence< Link > aLinks;
            LinkSequence::createFromXML(
                stripDavNamespace( value ), aLinks );
            thePropertyValue.Value <<= aLinks;
        }
        else
        {
            thePropertyValue.Value
                <<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
        }
    }

    // Add the newly created PropertyValue
    DAVResource* theResource = static_cast< DAVResource * >( userdata );
    theResource->properties.push_back( thePropertyValue );

    return 0; // Go on.
}

// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                       const ne_uri* uri,
#else
                                       const char* href,
#endif
                                       const NeonPropFindResultSet* set )
{
    // @@@ href is not the uri! DAVResource ctor wants uri!

#if NEON_VERSION >= 0x0260
    DAVResource theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResource theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    ne_propset_iterate( set, NPFR_propfind_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResource > * theResources
        = static_cast< vector< DAVResource > * >( userdata );
    theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
                                    const NeonPropName* pname,
                                    const char* /*value*/,
                                    const HttpStatus* /*status*/ )
{
    OUString aFullName;
    DAVProperties::createUCBPropName( pname->nspace,
                                      pname->name,
                                      aFullName );

    DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
    theResource->properties.push_back( aFullName );
    return 0;
}

// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
#if NEON_VERSION >= 0x0260
                                        const ne_uri* uri,
#else
                                        const char* href,
#endif
                                        const NeonPropFindResultSet* results )
{
    // @@@ href is not the uri! DAVResourceInfo ctor wants uri!
    // Create entry for the resource.
#if NEON_VERSION >= 0x0260
    DAVResourceInfo theResource(
        OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
    DAVResourceInfo theResource(
        OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif

    // Fill entry.
    ne_propset_iterate( results, NPFR_propnames_iter, &theResource );

    // Add entry to resources list.
    vector< DAVResourceInfo > * theResources
        = static_cast< vector< DAVResourceInfo > * >( userdata );
    theResources->push_back( theResource );
}

extern osl::Mutex aGlobalNeonMutex;

// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
                                          const char* inPath,
                                          const Depth inDepth,
                                          const vector< OUString >& inPropNames,
                                          vector< DAVResource >& ioResources,
                                          int & nError )
{
    // Generate the list of properties we're looking for
    int thePropCount = inPropNames.size();
    if ( thePropCount > 0 )
    {
        NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
        int theIndex;

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
        {
            // Split fullname into namespace and name!
            DAVProperties::createNeonPropName(
                inPropNames[ theIndex ], thePropNames[ theIndex ] );
        }
        thePropNames[ theIndex ].nspace = NULL;
        thePropNames[ theIndex ].name   = NULL;

        {
            osl::Guard< osl::Mutex > theGlobalGuard( aGlobalNeonMutex );
            nError = ne_simple_propfind( inSession,
                                         inPath,
                                         inDepth,
                                         thePropNames,
                                         NPFR_propfind_results,
                                         &ioResources );
        }

        for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
            free( (void *)thePropNames[ theIndex ].name );

        delete [] thePropNames;
    }
    else
    {
        // ALLPROP
        osl::Guard< osl::Mutex > theGlobalGuard( aGlobalNeonMutex );
        nError = ne_simple_propfind( inSession,
                                     inPath,
                                     inDepth,
                                     NULL, // 0 == allprop
                                     NPFR_propfind_results,
                                     &ioResources );
    }

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResources.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------

NeonPropFindRequest::NeonPropFindRequest(
                            HttpSession* inSession,
                            const char* inPath,
                            const Depth inDepth,
                            std::vector< DAVResourceInfo > & ioResInfo,
                            int & nError )
{
    nError = ne_propnames( inSession,
                           inPath,
                           inDepth,
                           NPFR_propnames_results,
                           &ioResInfo );

    // #87585# - Sometimes neon lies (because some servers lie).
    if ( ( nError == NE_OK ) && ioResInfo.empty() )
        nError = NE_ERROR;
}

// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#include "MapMessageTest.h"

#include <activemq/util/CMSListener.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/commands/ActiveMQMapMessage.h>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::commands;
using namespace activemq::core;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;

////////////////////////////////////////////////////////////////////////////////
MapMessageTest::MapMessageTest() {
}

////////////////////////////////////////////////////////////////////////////////
MapMessageTest::~MapMessageTest() {
}

////////////////////////////////////////////////////////////////////////////////
void MapMessageTest::testEmptyMapSendReceive() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::MapMessage> mapMessage( session->createMapMessage() );

    // Send some text messages
    producer->send( mapMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    cms::MapMessage* recvMapMessage = dynamic_cast<MapMessage*>( message.get() );
    CPPUNIT_ASSERT( recvMapMessage != NULL );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "SomeKey" ) == false );
}

////////////////////////////////////////////////////////////////////////////////
void MapMessageTest::testMapWithEmptyStringValue() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::MapMessage> mapMessage( session->createMapMessage() );

    mapMessage->setString("String1", "");
    mapMessage->setString("String2", "value");

    // Send some text messages
    producer->send( mapMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    cms::MapMessage* recvMapMessage = dynamic_cast<MapMessage*>( message.get() );
    CPPUNIT_ASSERT( recvMapMessage != NULL );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "String1" ) == true );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "String2" ) == true );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "String3" ) == false );
    CPPUNIT_ASSERT( recvMapMessage->getString( "String2" ) == string( "value" ) );
}
<commit_msg>Adds an addition test to this test case.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "MapMessageTest.h"

#include <activemq/util/CMSListener.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/commands/ActiveMQMapMessage.h>

using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::commands;
using namespace activemq::core;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;

////////////////////////////////////////////////////////////////////////////////
MapMessageTest::MapMessageTest() {
}

////////////////////////////////////////////////////////////////////////////////
MapMessageTest::~MapMessageTest() {
}

////////////////////////////////////////////////////////////////////////////////
void MapMessageTest::testEmptyMapSendReceive() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::MapMessage> mapMessage( session->createMapMessage() );

    // Send some text messages
    producer->send( mapMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    cms::MapMessage* recvMapMessage = dynamic_cast<MapMessage*>( message.get() );
    CPPUNIT_ASSERT( recvMapMessage != NULL );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "SomeKey" ) == false );
}

////////////////////////////////////////////////////////////////////////////////
void MapMessageTest::testMapWithEmptyStringValue() {

    // Create CMS Object for Comms
    cms::Session* session( cmsProvider->getSession() );
    cms::MessageConsumer* consumer = cmsProvider->getConsumer();
    cms::MessageProducer* producer = cmsProvider->getProducer();
    producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );

    auto_ptr<cms::MapMessage> mapMessage( session->createMapMessage() );

    mapMessage->setString("String1", "");
    mapMessage->setString("String2", "value");

    // Send some text messages
    producer->send( mapMessage.get() );

    auto_ptr<cms::Message> message( consumer->receive( 2000 ) );
    CPPUNIT_ASSERT( message.get() != NULL );

    cms::MapMessage* recvMapMessage = dynamic_cast<MapMessage*>( message.get() );
    CPPUNIT_ASSERT( recvMapMessage != NULL );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "String1" ) == true );
    CPPUNIT_ASSERT( recvMapMessage->getString( "String1" ) == "" );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "String2" ) == true );
    CPPUNIT_ASSERT( recvMapMessage->itemExists( "String3" ) == false );
    CPPUNIT_ASSERT( recvMapMessage->getString( "String2" ) == string( "value" ) );
}
<|endoftext|>