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

#include <set>

#include "base/file_util.h"
#include "base/memory/scoped_callback_factory.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/quota/mock_quota_manager.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include "webkit/quota/mock_storage_client.h"

namespace quota {

const char kTestOrigin1[] = "http://host1:1/";
const char kTestOrigin2[] = "http://host2:1/";
const char kTestOrigin3[] = "http://host3:1/";

const GURL kOrigin1(kTestOrigin1);
const GURL kOrigin2(kTestOrigin2);
const GURL kOrigin3(kTestOrigin3);

class MockQuotaManagerTest : public testing::Test {
 public:
  MockQuotaManagerTest()
    : callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
      deletion_callback_count_(0) {
  }

  void SetUp() {
    ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
    policy_ = new MockSpecialStoragePolicy;
    manager_ = new MockQuotaManager(
        false /* is_incognito */,
        data_dir_.path(),
        base::MessageLoopProxy::CreateForCurrentThread(),
        base::MessageLoopProxy::CreateForCurrentThread(),
        policy_);
  }

  void TearDown() {
    // Make sure the quota manager cleans up correctly.
    manager_ = NULL;
    MessageLoop::current()->RunAllPending();
  }

  void GetModifiedOrigins(StorageType type, base::Time since) {
    manager_->GetOriginsModifiedSince(type, since,
        callback_factory_.NewCallback(
            &MockQuotaManagerTest::GotModifiedOrigins));
  }

  void GotModifiedOrigins(const std::set<GURL>& origins, StorageType type) {
    origins_ = origins;
    type_ = type;
  }

  void DeleteOriginData(const GURL& origin, StorageType type) {
    manager_->DeleteOriginData(origin, type,
        callback_factory_.NewCallback(
            &MockQuotaManagerTest::DeletedOriginData));
  }

  void DeletedOriginData(QuotaStatusCode status) {
    ++deletion_callback_count_;
    EXPECT_EQ(quota::kQuotaStatusOk, status);
  }

  int deletion_callback_count() const {
    return deletion_callback_count_;
  }

  MockQuotaManager* manager() const {
    return manager_.get();
  }

  const std::set<GURL>& origins() const {
    return origins_;
  }

  const StorageType type() const {
    return type_;
  }

 private:
  ScopedTempDir data_dir_;
  base::ScopedCallbackFactory<MockQuotaManagerTest> callback_factory_;
  scoped_refptr<MockQuotaManager> manager_;
  scoped_refptr<MockSpecialStoragePolicy> policy_;

  int deletion_callback_count_;

  std::set<GURL> origins_;
  StorageType type_;

  DISALLOW_COPY_AND_ASSIGN(MockQuotaManagerTest);
};

TEST_F(MockQuotaManagerTest, BasicOriginManipulation) {
  EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));

  manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));

  manager()->AddOrigin(kOrigin1, kStorageTypePersistent, base::Time::Now());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));

  manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
}

TEST_F(MockQuotaManagerTest, OriginDeletion) {
  manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
  manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());

  DeleteOriginData(kOrigin2, kStorageTypeTemporary);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(1, deletion_callback_count());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
}

TEST_F(MockQuotaManagerTest, ModifiedOrigins) {
  base::Time now = base::Time::Now();
  base::Time then = base::Time();
  base::TimeDelta an_hour = base::TimeDelta::FromMilliseconds(3600000);
  base::TimeDelta a_minute = base::TimeDelta::FromMilliseconds(60000);

  GetModifiedOrigins(kStorageTypeTemporary, then);
  MessageLoop::current()->RunAllPending();
  EXPECT_TRUE(origins().empty());

  manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, now - an_hour);

  GetModifiedOrigins(kStorageTypeTemporary, then);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(kStorageTypeTemporary, type());
  EXPECT_EQ(1UL, origins().size());
  EXPECT_EQ(1UL, origins().count(kOrigin1));
  EXPECT_EQ(0UL, origins().count(kOrigin2));

  manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, now);

  GetModifiedOrigins(kStorageTypeTemporary, then);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(kStorageTypeTemporary, type());
  EXPECT_EQ(2UL, origins().size());
  EXPECT_EQ(1UL, origins().count(kOrigin1));
  EXPECT_EQ(1UL, origins().count(kOrigin2));

  GetModifiedOrigins(kStorageTypeTemporary, now - a_minute);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(kStorageTypeTemporary, type());
  EXPECT_EQ(1UL, origins().size());
  EXPECT_EQ(0UL, origins().count(kOrigin1));
  EXPECT_EQ(1UL, origins().count(kOrigin2));
}
}  // Namespace quota
<commit_msg>Fix "Mac Clang (dbg)" build TBR=mkwst TEST=builds OK Review URL: http://codereview.chromium.org/7583004<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>

#include "base/file_util.h"
#include "base/memory/scoped_callback_factory.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/quota/mock_quota_manager.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include "webkit/quota/mock_storage_client.h"

namespace quota {

const char kTestOrigin1[] = "http://host1:1/";
const char kTestOrigin2[] = "http://host2:1/";
const char kTestOrigin3[] = "http://host3:1/";

const GURL kOrigin1(kTestOrigin1);
const GURL kOrigin2(kTestOrigin2);
const GURL kOrigin3(kTestOrigin3);

class MockQuotaManagerTest : public testing::Test {
 public:
  MockQuotaManagerTest()
    : callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
      deletion_callback_count_(0) {
  }

  void SetUp() {
    ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
    policy_ = new MockSpecialStoragePolicy;
    manager_ = new MockQuotaManager(
        false /* is_incognito */,
        data_dir_.path(),
        base::MessageLoopProxy::CreateForCurrentThread(),
        base::MessageLoopProxy::CreateForCurrentThread(),
        policy_);
  }

  void TearDown() {
    // Make sure the quota manager cleans up correctly.
    manager_ = NULL;
    MessageLoop::current()->RunAllPending();
  }

  void GetModifiedOrigins(StorageType type, base::Time since) {
    manager_->GetOriginsModifiedSince(type, since,
        callback_factory_.NewCallback(
            &MockQuotaManagerTest::GotModifiedOrigins));
  }

  void GotModifiedOrigins(const std::set<GURL>& origins, StorageType type) {
    origins_ = origins;
    type_ = type;
  }

  void DeleteOriginData(const GURL& origin, StorageType type) {
    manager_->DeleteOriginData(origin, type,
        callback_factory_.NewCallback(
            &MockQuotaManagerTest::DeletedOriginData));
  }

  void DeletedOriginData(QuotaStatusCode status) {
    ++deletion_callback_count_;
    EXPECT_EQ(quota::kQuotaStatusOk, status);
  }

  int deletion_callback_count() const {
    return deletion_callback_count_;
  }

  MockQuotaManager* manager() const {
    return manager_.get();
  }

  const std::set<GURL>& origins() const {
    return origins_;
  }

  const StorageType& type() const {
    return type_;
  }

 private:
  ScopedTempDir data_dir_;
  base::ScopedCallbackFactory<MockQuotaManagerTest> callback_factory_;
  scoped_refptr<MockQuotaManager> manager_;
  scoped_refptr<MockSpecialStoragePolicy> policy_;

  int deletion_callback_count_;

  std::set<GURL> origins_;
  StorageType type_;

  DISALLOW_COPY_AND_ASSIGN(MockQuotaManagerTest);
};

TEST_F(MockQuotaManagerTest, BasicOriginManipulation) {
  EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));

  manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));

  manager()->AddOrigin(kOrigin1, kStorageTypePersistent, base::Time::Now());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));

  manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
}

TEST_F(MockQuotaManagerTest, OriginDeletion) {
  manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
  manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());

  DeleteOriginData(kOrigin2, kStorageTypeTemporary);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(1, deletion_callback_count());
  EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
  EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
}

TEST_F(MockQuotaManagerTest, ModifiedOrigins) {
  base::Time now = base::Time::Now();
  base::Time then = base::Time();
  base::TimeDelta an_hour = base::TimeDelta::FromMilliseconds(3600000);
  base::TimeDelta a_minute = base::TimeDelta::FromMilliseconds(60000);

  GetModifiedOrigins(kStorageTypeTemporary, then);
  MessageLoop::current()->RunAllPending();
  EXPECT_TRUE(origins().empty());

  manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, now - an_hour);

  GetModifiedOrigins(kStorageTypeTemporary, then);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(kStorageTypeTemporary, type());
  EXPECT_EQ(1UL, origins().size());
  EXPECT_EQ(1UL, origins().count(kOrigin1));
  EXPECT_EQ(0UL, origins().count(kOrigin2));

  manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, now);

  GetModifiedOrigins(kStorageTypeTemporary, then);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(kStorageTypeTemporary, type());
  EXPECT_EQ(2UL, origins().size());
  EXPECT_EQ(1UL, origins().count(kOrigin1));
  EXPECT_EQ(1UL, origins().count(kOrigin2));

  GetModifiedOrigins(kStorageTypeTemporary, now - a_minute);
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(kStorageTypeTemporary, type());
  EXPECT_EQ(1UL, origins().size());
  EXPECT_EQ(0UL, origins().count(kOrigin1));
  EXPECT_EQ(1UL, origins().count(kOrigin2));
}
}  // Namespace quota
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include <list>
#include "../src/scene/Ionosphere.h"
#include "../src/tracer/Ray.h"
#include "../src/core/Config.h"
#include "../src/exporter/Data.h"
#include "../src/exporter/MatlabExporter.h"

namespace {

	using namespace raytracer::exporter;
	using namespace raytracer::math;
	using namespace raytracer::scene;
	using namespace raytracer::core;

	class ValidationTest : public ::testing::Test {
	};

	TEST_F(ValidationTest, ElectronDensityProfiles) {

		list<Data> dataSet;

		Config celestialConfig = Config("config/scenario_default.json");

		double SZA = 76 * Constants::PI / 180;
		double R = 3390e3;

		int dh = 400;
		const Json::Value ionosphereConfig = celestialConfig.getArray("ionosphere");
		for (int idx = 0; idx < ionosphereConfig.size(); idx++) {

			int hS = ionosphereConfig[idx].get("start", 0).asInt();
			int hE = ionosphereConfig[idx].get("end", 0).asInt();
			double electronPeakDensity = atof(ionosphereConfig[idx].get("electronPeakDensity", "").asCString());
			double peakProductionAltitude = ionosphereConfig[idx].get("peakProductionAltitude", "").asDouble();
			Json::Value stratificationRaw = ionosphereConfig[idx].get("stratification", "");
			const char * stratificationType = stratificationRaw.asCString();
			for (int h = hS; h < hE; h += dh) {
				Vector3d N = Vector3d(sin(SZA), cos(SZA), 0).norm();
				Plane3d mesh = Plane3d(N, Vector3d((R+h)*N.x, (R+h)*N.y, (R+h)*N.z));
				mesh.size = 1000;
				Ionosphere io = Ionosphere(mesh);
				io.layerHeight = dh;
				io.setElectronPeakDensity(electronPeakDensity);
				io.setPeakProductionAltitude(peakProductionAltitude);

				ASSERT_LT(0, io.getElectronPeakDensity());
				ASSERT_LT(0, io.getPeakProductionAltitude());
				ASSERT_LT(50e3, io.getAltitude());
				ASSERT_LT(0, io.getElectronNumberDensity());

				Data d;
				d.x = mesh.centerpoint.x;
				d.y = mesh.centerpoint.y;
				d.n_e = io.getElectronNumberDensity();
				dataSet.push_back(d);
			}
		}

		MatlabExporter me;
		me.dump("Debug/data_LS270_SA75_DS0.dat", dataSet);
	}
}
<commit_msg>validationtest exports electrondensities comparable with real research situations<commit_after>#include "gtest/gtest.h"
#include <list>
#include "../src/scene/Ionosphere.h"
#include "../src/tracer/Ray.h"
#include "../src/core/Config.h"
#include "../src/exporter/Data.h"
#include "../src/exporter/MatlabExporter.h"

namespace {

	using namespace raytracer::exporter;
	using namespace raytracer::math;
	using namespace raytracer::scene;
	using namespace raytracer::core;

	class ValidationTest : public ::testing::Test {
	};

	TEST_F(ValidationTest, ElectronDensityProfiles) {

		list<Data> dataSet;

		Config celestialConfig = Config("config/scenario_LS270_SA250_DS0.json");

		double SZA = 76 * Constants::PI / 180;
		double R = 3390e3;

		int dh = 100;
		const Json::Value ionosphereConfig = celestialConfig.getArray("ionosphere");
		for (int h = 50e3; h < 250e3; h += dh) {
			Vector3d N = Vector3d(sin(SZA), cos(SZA), 0).norm();
			Plane3d mesh = Plane3d(N, Vector3d((R+h)*N.x, (R+h)*N.y, (R+h)*N.z));
			mesh.size = 1000;
			Ionosphere io = Ionosphere(mesh);
			io.layerHeight = dh;

			ASSERT_NEAR(SZA, io.getMesh().normal.angle(Vector3d::SUBSOLAR), 0.001);

			for (int idx = 0; idx < ionosphereConfig.size(); idx++) {

				double electronPeakDensity = atof(ionosphereConfig[idx].get("electronPeakDensity", "").asCString());
				double peakProductionAltitude = ionosphereConfig[idx].get("peakProductionAltitude", "").asDouble();
				double neutralScaleHeight = ionosphereConfig[idx].get("neutralScaleHeight", "").asDouble();

				ASSERT_LT(0, electronPeakDensity);
				ASSERT_LT(0, peakProductionAltitude);
				ASSERT_LT(0, neutralScaleHeight);

				io.superimposeElectronNumberDensity(electronPeakDensity, peakProductionAltitude, neutralScaleHeight);

				ASSERT_NEAR(h, io.getAltitude(), 1);
			}

			Data d;
			d.x = mesh.centerpoint.x;
			d.y = mesh.centerpoint.y;
			d.n_e = io.getElectronNumberDensity();
			dataSet.push_back(d);
		}

		MatlabExporter me;
		me.dump("Debug/data_LS270_SA75_DS0.dat", dataSet);
	}
}
<|endoftext|>


<commit_before>#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"

int main(int argc, char** argv) {
    namespace tf = tensorflow;

    tf::Session* session;
    tf::Status status = tf::NewSession(tf::SessionOptions(), &session);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        return 1;
    }

    tf::GraphDef graph_def;
    status = ReadBinaryProto(tf::Env::Default(), "graph.pb", &graph_def);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        return 1;
    }

    status = session->Create(graph_def);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        return 1;
    }

    tf::Tensor x(tf::DT_FLOAT, tf::TensorShape()), y(tf::DT_FLOAT, tf::TensorShape());
    x.scalar<float>()() = 23.0;
    y.scalar<float>()() = 19.0;

    std::vector<std::pair<tf::string, tf::Tensor>> input_tensors = {{"x", x}, {"y", y}};
    std::vector<tf::Tensor> output_tensors;

    status = session->Run(input_tensors, {"z"}, {}, &output_tensors);
    if (!status.ok()) {
        std::cout << status.ToString() << std::endl;
        return 1;
    }

    tf::Tensor output = output_tensors[0];
    std::cout << "Success: " << output.scalar<float>() << "!" << std::endl;
    session->Close();
    return 0;
}
<commit_msg>Added function to check status<commit_after>#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"

/**
 * Checks if the given status is ok.
 * If not, the status is printed and the
 * program is terminated.
 */
void checkStatus(const tensorflow::Status& status) {
  if (!status.ok()) {
    std::cout << status.ToString() << std::endl;
    exit(1);
  }
}

int main(int argc, char** argv) {
    namespace tf = tensorflow;

    tf::Session* session;
    tf::Status status = tf::NewSession(tf::SessionOptions(), &session);
    checkStatus(status);

    tf::GraphDef graph_def;
    status = ReadBinaryProto(tf::Env::Default(), "graph.pb", &graph_def);
    checkStatus(status);

    status = session->Create(graph_def);
    checkStatus(status);

    tf::Tensor x(tf::DT_FLOAT, tf::TensorShape()), y(tf::DT_FLOAT, tf::TensorShape());
    x.scalar<float>()() = 23.0;
    y.scalar<float>()() = 19.0;

    std::vector<std::pair<tf::string, tf::Tensor>> input_tensors = {{"x", x}, {"y", y}};
    std::vector<tf::Tensor> output_tensors;

    status = session->Run(input_tensors, {"z"}, {}, &output_tensors);
    checkStatus(status);

    tf::Tensor output = output_tensors[0];
    std::cout << "Success: " << output.scalar<float>() << "!" << std::endl;
    session->Close();
    return 0;
}
<|endoftext|>


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

// HACK for crbug.com/142782. I've put it all the way up here to avoid a merge
// collision
namespace base {
namespace mac {
bool IsOSSnowLeopardOrLater() { return true; }
}  // namespace mac
}  // namespace base

#include "net/socket/nss_ssl_util.h"

#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>

#include <string>

#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/nss_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#elif defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif

namespace net {

class NSSSSLInitSingleton {
 public:
  NSSSSLInitSingleton() {
    crypto::EnsureNSSInit();

    NSS_SetDomesticPolicy();

#if defined(USE_SYSTEM_SSL)
    // Use late binding to avoid scary but benign warning
    // "Symbol `SSL_ImplementedCiphers' has different size in shared object,
    //  consider re-linking"
    // TODO(wtc): Use the new SSL_GetImplementedCiphers and
    // SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
    const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
        dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
    if (pSSL_ImplementedCiphers == NULL) {
      NOTREACHED() << "Can't get list of supported ciphers";
      return;
    }
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif

    // Explicitly enable exactly those ciphers with keys of at least 80 bits
    for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
      SSLCipherSuiteInfo info;
      if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
                                 sizeof(info)) == SECSuccess) {
        SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
                                 (info.effectiveKeyBits >= 80));
      }
    }

    // Enable SSL.
    SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);

    // Disable ECDSA cipher suites on platforms that do not support ECDSA
    // signed certificates, as servers may use the presence of such
    // ciphersuites as a hint to send an ECDSA certificate.
#if defined(OS_WIN)
    if (base::win::GetVersion() < base::win::VERSION_VISTA)
      DisableECDSA();
#elif defined(OS_MACOSX)
    if (!base::mac::IsOSSnowLeopardOrLater())
      DisableECDSA();
#endif

    // All other SSL options are set per-session by SSLClientSocket and
    // SSLServerSocket.
  }

  ~NSSSSLInitSingleton() {
    // Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
    SSL_ClearSessionCache();
  }

  void DisableECDSA() {
    const PRUint16* ciphersuites = SSL_GetImplementedCiphers();
    const unsigned num_ciphersuites = SSL_GetNumImplementedCiphers();
    SECStatus rv;
    SSLCipherSuiteInfo info;

    for (unsigned i = 0; i < num_ciphersuites; i++) {
      rv = SSL_GetCipherSuiteInfo(ciphersuites[i], &info, sizeof(info));
      if (rv == SECSuccess && info.authAlgorithm == ssl_auth_ecdsa)
        SSL_CipherPrefSetDefault(ciphersuites[i], PR_FALSE);
    }
  }
};

static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton =
    LAZY_INSTANCE_INITIALIZER;

// Initialize the NSS SSL library if it isn't already initialized.  This must
// be called before any other NSS SSL functions.  This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
  // Initializing SSL causes us to do blocking IO.
  // Temporarily allow it until we fix
  //   http://code.google.com/p/chromium/issues/detail?id=59847
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  g_nss_ssl_init_singleton.Get();
}

// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
PRErrorCode MapErrorToNSS(int result) {
  if (result >=0)
    return result;

  switch (result) {
    case ERR_IO_PENDING:
      return PR_WOULD_BLOCK_ERROR;
    case ERR_ACCESS_DENIED:
    case ERR_NETWORK_ACCESS_DENIED:
      // For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
      return PR_NO_ACCESS_RIGHTS_ERROR;
    case ERR_NOT_IMPLEMENTED:
      return PR_NOT_IMPLEMENTED_ERROR;
    case ERR_SOCKET_NOT_CONNECTED:
      return PR_NOT_CONNECTED_ERROR;
    case ERR_INTERNET_DISCONNECTED:  // Equivalent to ENETDOWN.
      return PR_NETWORK_UNREACHABLE_ERROR;  // Best approximation.
    case ERR_CONNECTION_TIMED_OUT:
    case ERR_TIMED_OUT:
      return PR_IO_TIMEOUT_ERROR;
    case ERR_CONNECTION_RESET:
      return PR_CONNECT_RESET_ERROR;
    case ERR_CONNECTION_ABORTED:
      return PR_CONNECT_ABORTED_ERROR;
    case ERR_CONNECTION_REFUSED:
      return PR_CONNECT_REFUSED_ERROR;
    case ERR_ADDRESS_UNREACHABLE:
      return PR_HOST_UNREACHABLE_ERROR;  // Also PR_NETWORK_UNREACHABLE_ERROR.
    case ERR_ADDRESS_INVALID:
      return PR_ADDRESS_NOT_AVAILABLE_ERROR;
    case ERR_NAME_NOT_RESOLVED:
      return PR_DIRECTORY_LOOKUP_ERROR;
    default:
      LOG(WARNING) << "MapErrorToNSS " << result
                   << " mapped to PR_UNKNOWN_ERROR";
      return PR_UNKNOWN_ERROR;
  }
}

// The default error mapping function.
// Maps an NSS error code to a network error code.
int MapNSSError(PRErrorCode err) {
  // TODO(port): fill this out as we learn what's important
  switch (err) {
    case PR_WOULD_BLOCK_ERROR:
      return ERR_IO_PENDING;
    case PR_ADDRESS_NOT_SUPPORTED_ERROR:  // For connect.
    case PR_NO_ACCESS_RIGHTS_ERROR:
      return ERR_ACCESS_DENIED;
    case PR_IO_TIMEOUT_ERROR:
      return ERR_TIMED_OUT;
    case PR_CONNECT_RESET_ERROR:
      return ERR_CONNECTION_RESET;
    case PR_CONNECT_ABORTED_ERROR:
      return ERR_CONNECTION_ABORTED;
    case PR_CONNECT_REFUSED_ERROR:
      return ERR_CONNECTION_REFUSED;
    case PR_NOT_CONNECTED_ERROR:
      return ERR_SOCKET_NOT_CONNECTED;
    case PR_HOST_UNREACHABLE_ERROR:
    case PR_NETWORK_UNREACHABLE_ERROR:
      return ERR_ADDRESS_UNREACHABLE;
    case PR_ADDRESS_NOT_AVAILABLE_ERROR:
      return ERR_ADDRESS_INVALID;
    case PR_INVALID_ARGUMENT_ERROR:
      return ERR_INVALID_ARGUMENT;
    case PR_END_OF_FILE_ERROR:
      return ERR_CONNECTION_CLOSED;
    case PR_NOT_IMPLEMENTED_ERROR:
      return ERR_NOT_IMPLEMENTED;

    case SEC_ERROR_LIBRARY_FAILURE:
      return ERR_UNEXPECTED;
    case SEC_ERROR_INVALID_ARGS:
      return ERR_INVALID_ARGUMENT;
    case SEC_ERROR_NO_MEMORY:
      return ERR_OUT_OF_MEMORY;
    case SEC_ERROR_NO_KEY:
      return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
    case SEC_ERROR_INVALID_KEY:
    case SSL_ERROR_SIGN_HASHES_FAILURE:
      return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED;
    // A handshake (initial or renegotiation) may fail because some signature
    // (for example, the signature in the ServerKeyExchange message for an
    // ephemeral Diffie-Hellman cipher suite) is invalid.
    case SEC_ERROR_BAD_SIGNATURE:
      return ERR_SSL_PROTOCOL_ERROR;

    case SSL_ERROR_SSL_DISABLED:
      return ERR_NO_SSL_VERSIONS_ENABLED;
    case SSL_ERROR_NO_CYPHER_OVERLAP:
    case SSL_ERROR_PROTOCOL_VERSION_ALERT:
    case SSL_ERROR_UNSUPPORTED_VERSION:
      return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
    case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
    case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
    case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
      return ERR_SSL_PROTOCOL_ERROR;
    case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
      return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
    case SSL_ERROR_BAD_MAC_ALERT:
      return ERR_SSL_BAD_RECORD_MAC_ALERT;
    case SSL_ERROR_UNSAFE_NEGOTIATION:
      return ERR_SSL_UNSAFE_NEGOTIATION;
    case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY:
      return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
    case SSL_ERROR_HANDSHAKE_NOT_COMPLETED:
      return ERR_SSL_HANDSHAKE_NOT_COMPLETED;
    case SEC_ERROR_BAD_KEY:
    case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE:
    // TODO(wtc): the following errors may also occur in contexts unrelated
    // to the peer's public key.  We should add new error codes for them, or
    // map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
    // General unsupported/unknown key algorithm error.
    case SEC_ERROR_UNSUPPORTED_KEYALG:
    // General DER decoding errors.
    case SEC_ERROR_BAD_DER:
    case SEC_ERROR_EXTRA_INPUT:
      return ERR_SSL_BAD_PEER_PUBLIC_KEY;

    default: {
      if (IS_SSL_ERROR(err)) {
        LOG(WARNING) << "Unknown SSL error " << err
                     << " mapped to net::ERR_SSL_PROTOCOL_ERROR";
        return ERR_SSL_PROTOCOL_ERROR;
      }
      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
      return ERR_FAILED;
    }
  }
}

// Returns parameters to attach to the NetLog when we receive an error in
// response to a call to an NSS function.  Used instead of
// NetLogSSLErrorCallback with events of type TYPE_SSL_NSS_ERROR.
Value* NetLogSSLFailedNSSFunctionCallback(
    const char* function,
    const char* param,
    int ssl_lib_error,
    NetLog::LogLevel /* log_level */) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetString("function", function);
  if (param[0] != '\0')
    dict->SetString("param", param);
  dict->SetInteger("ssl_lib_error", ssl_lib_error);
  return dict;
}

void LogFailedNSSFunction(const BoundNetLog& net_log,
                          const char* function,
                          const char* param) {
  DCHECK(function);
  DCHECK(param);
  net_log.AddEvent(
      NetLog::TYPE_SSL_NSS_ERROR,
      base::Bind(&NetLogSSLFailedNSSFunctionCallback,
                 function, param, PR_GetError()));
}

}  // namespace net
<commit_msg>net: cleanup code to disable ECDSA<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/socket/nss_ssl_util.h"

#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>

#include <string>

#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/nss_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

namespace net {

class NSSSSLInitSingleton {
 public:
  NSSSSLInitSingleton() {
    crypto::EnsureNSSInit();

    NSS_SetDomesticPolicy();

#if defined(USE_SYSTEM_SSL)
    // Use late binding to avoid scary but benign warning
    // "Symbol `SSL_ImplementedCiphers' has different size in shared object,
    //  consider re-linking"
    // TODO(wtc): Use the new SSL_GetImplementedCiphers and
    // SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
    const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
        dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
    if (pSSL_ImplementedCiphers == NULL) {
      NOTREACHED() << "Can't get list of supported ciphers";
      return;
    }
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif

    // Disable ECDSA cipher suites on platforms that do not support ECDSA
    // signed certificates, as servers may use the presence of such
    // ciphersuites as a hint to send an ECDSA certificate.
    bool disableECDSA = false;
#if defined(OS_WIN)
    if (base::win::GetVersion() < base::win::VERSION_VISTA)
      disableECDSA = true;
#endif

    // Explicitly enable exactly those ciphers with keys of at least 80 bits
    for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
      SSLCipherSuiteInfo info;
      if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
                                 sizeof(info)) == SECSuccess) {
        SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
                                 (info.effectiveKeyBits >= 80));
        if (info.authAlgorithm == ssl_auth_ecdsa && disableECDSA)
          SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i], PR_FALSE);
      }
    }

    // Enable SSL.
    SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);

    // All other SSL options are set per-session by SSLClientSocket and
    // SSLServerSocket.
  }

  ~NSSSSLInitSingleton() {
    // Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
    SSL_ClearSessionCache();
  }
};

static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton =
    LAZY_INSTANCE_INITIALIZER;

// Initialize the NSS SSL library if it isn't already initialized.  This must
// be called before any other NSS SSL functions.  This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
  // Initializing SSL causes us to do blocking IO.
  // Temporarily allow it until we fix
  //   http://code.google.com/p/chromium/issues/detail?id=59847
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  g_nss_ssl_init_singleton.Get();
}

// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
PRErrorCode MapErrorToNSS(int result) {
  if (result >=0)
    return result;

  switch (result) {
    case ERR_IO_PENDING:
      return PR_WOULD_BLOCK_ERROR;
    case ERR_ACCESS_DENIED:
    case ERR_NETWORK_ACCESS_DENIED:
      // For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
      return PR_NO_ACCESS_RIGHTS_ERROR;
    case ERR_NOT_IMPLEMENTED:
      return PR_NOT_IMPLEMENTED_ERROR;
    case ERR_SOCKET_NOT_CONNECTED:
      return PR_NOT_CONNECTED_ERROR;
    case ERR_INTERNET_DISCONNECTED:  // Equivalent to ENETDOWN.
      return PR_NETWORK_UNREACHABLE_ERROR;  // Best approximation.
    case ERR_CONNECTION_TIMED_OUT:
    case ERR_TIMED_OUT:
      return PR_IO_TIMEOUT_ERROR;
    case ERR_CONNECTION_RESET:
      return PR_CONNECT_RESET_ERROR;
    case ERR_CONNECTION_ABORTED:
      return PR_CONNECT_ABORTED_ERROR;
    case ERR_CONNECTION_REFUSED:
      return PR_CONNECT_REFUSED_ERROR;
    case ERR_ADDRESS_UNREACHABLE:
      return PR_HOST_UNREACHABLE_ERROR;  // Also PR_NETWORK_UNREACHABLE_ERROR.
    case ERR_ADDRESS_INVALID:
      return PR_ADDRESS_NOT_AVAILABLE_ERROR;
    case ERR_NAME_NOT_RESOLVED:
      return PR_DIRECTORY_LOOKUP_ERROR;
    default:
      LOG(WARNING) << "MapErrorToNSS " << result
                   << " mapped to PR_UNKNOWN_ERROR";
      return PR_UNKNOWN_ERROR;
  }
}

// The default error mapping function.
// Maps an NSS error code to a network error code.
int MapNSSError(PRErrorCode err) {
  // TODO(port): fill this out as we learn what's important
  switch (err) {
    case PR_WOULD_BLOCK_ERROR:
      return ERR_IO_PENDING;
    case PR_ADDRESS_NOT_SUPPORTED_ERROR:  // For connect.
    case PR_NO_ACCESS_RIGHTS_ERROR:
      return ERR_ACCESS_DENIED;
    case PR_IO_TIMEOUT_ERROR:
      return ERR_TIMED_OUT;
    case PR_CONNECT_RESET_ERROR:
      return ERR_CONNECTION_RESET;
    case PR_CONNECT_ABORTED_ERROR:
      return ERR_CONNECTION_ABORTED;
    case PR_CONNECT_REFUSED_ERROR:
      return ERR_CONNECTION_REFUSED;
    case PR_NOT_CONNECTED_ERROR:
      return ERR_SOCKET_NOT_CONNECTED;
    case PR_HOST_UNREACHABLE_ERROR:
    case PR_NETWORK_UNREACHABLE_ERROR:
      return ERR_ADDRESS_UNREACHABLE;
    case PR_ADDRESS_NOT_AVAILABLE_ERROR:
      return ERR_ADDRESS_INVALID;
    case PR_INVALID_ARGUMENT_ERROR:
      return ERR_INVALID_ARGUMENT;
    case PR_END_OF_FILE_ERROR:
      return ERR_CONNECTION_CLOSED;
    case PR_NOT_IMPLEMENTED_ERROR:
      return ERR_NOT_IMPLEMENTED;

    case SEC_ERROR_LIBRARY_FAILURE:
      return ERR_UNEXPECTED;
    case SEC_ERROR_INVALID_ARGS:
      return ERR_INVALID_ARGUMENT;
    case SEC_ERROR_NO_MEMORY:
      return ERR_OUT_OF_MEMORY;
    case SEC_ERROR_NO_KEY:
      return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
    case SEC_ERROR_INVALID_KEY:
    case SSL_ERROR_SIGN_HASHES_FAILURE:
      return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED;
    // A handshake (initial or renegotiation) may fail because some signature
    // (for example, the signature in the ServerKeyExchange message for an
    // ephemeral Diffie-Hellman cipher suite) is invalid.
    case SEC_ERROR_BAD_SIGNATURE:
      return ERR_SSL_PROTOCOL_ERROR;

    case SSL_ERROR_SSL_DISABLED:
      return ERR_NO_SSL_VERSIONS_ENABLED;
    case SSL_ERROR_NO_CYPHER_OVERLAP:
    case SSL_ERROR_PROTOCOL_VERSION_ALERT:
    case SSL_ERROR_UNSUPPORTED_VERSION:
      return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
    case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
    case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
    case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
      return ERR_SSL_PROTOCOL_ERROR;
    case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
      return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
    case SSL_ERROR_BAD_MAC_ALERT:
      return ERR_SSL_BAD_RECORD_MAC_ALERT;
    case SSL_ERROR_UNSAFE_NEGOTIATION:
      return ERR_SSL_UNSAFE_NEGOTIATION;
    case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY:
      return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
    case SSL_ERROR_HANDSHAKE_NOT_COMPLETED:
      return ERR_SSL_HANDSHAKE_NOT_COMPLETED;
    case SEC_ERROR_BAD_KEY:
    case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE:
    // TODO(wtc): the following errors may also occur in contexts unrelated
    // to the peer's public key.  We should add new error codes for them, or
    // map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
    // General unsupported/unknown key algorithm error.
    case SEC_ERROR_UNSUPPORTED_KEYALG:
    // General DER decoding errors.
    case SEC_ERROR_BAD_DER:
    case SEC_ERROR_EXTRA_INPUT:
      return ERR_SSL_BAD_PEER_PUBLIC_KEY;

    default: {
      if (IS_SSL_ERROR(err)) {
        LOG(WARNING) << "Unknown SSL error " << err
                     << " mapped to net::ERR_SSL_PROTOCOL_ERROR";
        return ERR_SSL_PROTOCOL_ERROR;
      }
      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
      return ERR_FAILED;
    }
  }
}

// Returns parameters to attach to the NetLog when we receive an error in
// response to a call to an NSS function.  Used instead of
// NetLogSSLErrorCallback with events of type TYPE_SSL_NSS_ERROR.
Value* NetLogSSLFailedNSSFunctionCallback(
    const char* function,
    const char* param,
    int ssl_lib_error,
    NetLog::LogLevel /* log_level */) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetString("function", function);
  if (param[0] != '\0')
    dict->SetString("param", param);
  dict->SetInteger("ssl_lib_error", ssl_lib_error);
  return dict;
}

void LogFailedNSSFunction(const BoundNetLog& net_log,
                          const char* function,
                          const char* param) {
  DCHECK(function);
  DCHECK(param);
  net_log.AddEvent(
      NetLog::TYPE_SSL_NSS_ERROR,
      base::Bind(&NetLogSSLFailedNSSFunctionCallback,
                 function, param, PR_GetError()));
}

}  // namespace net
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cmdlinehelp.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-28 13:26:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdlib.h>
#ifdef UNX
#include <stdio.h>
#endif
#include <sal/types.h>
#include <tools/string.hxx>
#include <vcl/msgbox.hxx>
#include <rtl/bootstrap.hxx>
#include <app.hxx>

#include "desktopresid.hxx"
#include "desktop.hrc"
#include "cmdlinehelp.hxx"

namespace desktop
{
    // to be able to display the help nicely in a dialog box with propotional font,
    // we need to split it in chunks...
    //  ___HEAD___
    //  LEFT RIGHT
    //  LEFT RIGHT
    //  LEFT RIGHT
    //  __BOTTOM__
    //     [OK]

    const char *aCmdLineHelp_head =
        "%PRODUCTNAME %PRODUCTVERSION %PRODUCTEXTENSION %BUILDID\n"\
        "\n"\
        "Usage: %CMDNAME [options] [documents...]\n"\
        "\n"\
        "Options:\n";
    const char *aCmdLineHelp_left =
        "-minimized    \n"\
        "-invisible    \n"\
        "-norestore    \n"\
        "-quickstart   \n"\
        "-nologo       \n"\
        "-nolockcheck  \n"\
        "-nodefault    \n"\
        "-headless     \n"\
        "-help/-h/-?   \n"\
        "-writer       \n"\
        "-calc         \n"\
        "-draw         \n"\
        "-impress      \n"\
        "-math         \n"\
        "-global       \n"\
        "-web          \n"\
        "-o            \n"\
        "-n            \n";
    const char *aCmdLineHelp_right =
        "keep startup bitmap minimized.\n"\
        "no startup screen, no default document and no UI.\n"\
        "suppress restart/restore after fatal errors.\n"\
        "starts the quickstart service\n"\
        "don't show startup screen.\n"\
        "don't check for remote instances using the installation\n"\
        "don't start with an empty document\n"\
        "like invisible but no userinteraction at all.\n"\
        "show this message and exit.\n"\
        "create new text document.\n"\
        "create new spreadsheet document.\n"\
        "create new drawing.\n"\
        "create new presentation.\n"\
        "create new formula.\n"\
        "create new global document.\n"\
        "create new HTML document.\n"\
        "open documents regardless whether they are templates or not.\n"\
        "always open documents as new files (use as template).\n";
    const char *aCmdLineHelp_bottom =
        "-display <display>\n"\
        "      Specify X-Display to use in Unix/X11 versions.\n"
        "-p <documents...>\n"\
        "      print the specified documents on the default printer.\n"\
        "-pt <printer> <documents...>\n"\
        "      print the specified documents on the specified printer.\n"\
        "-view <documents...>\n"\
        "      open the specified documents in viewer-(readonly-)mode.\n"\
        "-show <sxi-document>\n"\
        "      open the specified presentation and start it immediately\n"\
        "-accept=<accept-string>\n"\
        "      Specify an UNO connect-string to create an UNO acceptor through which\n"\
        "      other programs can connect to access the API\n"\
        "-unaccept=<accept-sring>\n"\
        "      Close an acceptor that was created with -accept=<accept-string>\n"\
        "      Use -unnaccept=all to close all open acceptors\n"\
        "Remaining arguments will be treated as filenames or URLs of documents to open.\n";

    void ReplaceStringHookProc( UniString& rStr );

    void displayCmdlineHelp()
    {
        // if you put variables in other chunks don't forget to call the replace routines
        // for those chunks...
        String aHelpMessage_head(aCmdLineHelp_head, RTL_TEXTENCODING_ASCII_US);
        String aHelpMessage_left(aCmdLineHelp_left, RTL_TEXTENCODING_ASCII_US);
        String aHelpMessage_right(aCmdLineHelp_right, RTL_TEXTENCODING_ASCII_US);
        String aHelpMessage_bottom(aCmdLineHelp_bottom, RTL_TEXTENCODING_ASCII_US);
        ReplaceStringHookProc(aHelpMessage_head);
        ::rtl::OUString aDefault;
        String aVerId( ::utl::Bootstrap::getBuildIdData( aDefault ));
        aHelpMessage_head.SearchAndReplaceAscii( "%BUILDID", aVerId );
        aHelpMessage_head.SearchAndReplaceAscii( "%CMDNAME", String( "soffice", RTL_TEXTENCODING_ASCII_US) );
#ifdef UNX
        // on unix use console for output
        fprintf(stderr, "%s\n", ByteString(aHelpMessage_head,
                    RTL_TEXTENCODING_ASCII_US).GetBuffer());
        // merge left and right column
        int n = aHelpMessage_left.GetTokenCount ('\n');
        ByteString bsLeft(aHelpMessage_left, RTL_TEXTENCODING_ASCII_US);
        ByteString bsRight(aHelpMessage_right, RTL_TEXTENCODING_ASCII_US);
        for ( int i = 0; i < n; i++ )
        {
            fprintf(stderr, "%s", bsLeft.GetToken(i, '\n').GetBuffer());
            fprintf(stderr, "%s\n", bsRight.GetToken(i, '\n').GetBuffer());
        }
        fprintf(stderr, "%s", ByteString(aHelpMessage_bottom,
                    RTL_TEXTENCODING_ASCII_US).GetBuffer());
#else
        // rest gets a dialog box
        CmdlineHelpDialog aDlg;
        aDlg.m_ftHead.SetText(aHelpMessage_head);
        aDlg.m_ftLeft.SetText(aHelpMessage_left);
        aDlg.m_ftRight.SetText(aHelpMessage_right);
        aDlg.m_ftBottom.SetText(aHelpMessage_bottom);
        aDlg.Execute();
#endif
    }

    CmdlineHelpDialog::CmdlineHelpDialog (void)
    : ModalDialog( NULL, DesktopResId( DLG_CMDLINEHELP ) )
    , m_ftHead( this, DesktopResId( TXT_DLG_CMDLINEHELP_HEADER ) )
    , m_ftLeft( this, DesktopResId( TXT_DLG_CMDLINEHELP_LEFT ) )
    , m_ftRight( this, DesktopResId( TXT_DLG_CMDLINEHELP_RIGHT ) )
    , m_ftBottom( this, DesktopResId( TXT_DLG_CMDLINEHELP_BOTTOM ) )
    , m_btOk( this, DesktopResId( BTN_DLG_CMDLINEHELP_OK ) )
    {
        FreeResource();
    }

}

<commit_msg>INTEGRATION: CWS insight01 (1.4.174); FILE MERGED 2004/07/09 13:01:24 oj 1.4.174.1: #i30597# add base to start up<commit_after>/*************************************************************************
 *
 *  $RCSfile: cmdlinehelp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 14:39:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdlib.h>
#ifdef UNX
#include <stdio.h>
#endif
#include <sal/types.h>
#include <tools/string.hxx>
#include <vcl/msgbox.hxx>
#include <rtl/bootstrap.hxx>
#include <app.hxx>

#include "desktopresid.hxx"
#include "desktop.hrc"
#include "cmdlinehelp.hxx"

namespace desktop
{
    // to be able to display the help nicely in a dialog box with propotional font,
    // we need to split it in chunks...
    //  ___HEAD___
    //  LEFT RIGHT
    //  LEFT RIGHT
    //  LEFT RIGHT
    //  __BOTTOM__
    //     [OK]

    const char *aCmdLineHelp_head =
        "%PRODUCTNAME %PRODUCTVERSION %PRODUCTEXTENSION %BUILDID\n"\
        "\n"\
        "Usage: %CMDNAME [options] [documents...]\n"\
        "\n"\
        "Options:\n";
    const char *aCmdLineHelp_left =
        "-minimized    \n"\
        "-invisible    \n"\
        "-norestore    \n"\
        "-quickstart   \n"\
        "-nologo       \n"\
        "-nolockcheck  \n"\
        "-nodefault    \n"\
        "-headless     \n"\
        "-help/-h/-?   \n"\
        "-writer       \n"\
        "-calc         \n"\
        "-draw         \n"\
        "-impress      \n"\
        "-base         \n"\
        "-math         \n"\
        "-global       \n"\
        "-web          \n"\
        "-o            \n"\
        "-n            \n";
    const char *aCmdLineHelp_right =
        "keep startup bitmap minimized.\n"\
        "no startup screen, no default document and no UI.\n"\
        "suppress restart/restore after fatal errors.\n"\
        "starts the quickstart service\n"\
        "don't show startup screen.\n"\
        "don't check for remote instances using the installation\n"\
        "don't start with an empty document\n"\
        "like invisible but no userinteraction at all.\n"\
        "show this message and exit.\n"\
        "create new text document.\n"\
        "create new spreadsheet document.\n"\
        "create new drawing.\n"\
        "create new presentation.\n"\
        "create new database.\n"\
        "create new formula.\n"\
        "create new global document.\n"\
        "create new HTML document.\n"\
        "open documents regardless whether they are templates or not.\n"\
        "always open documents as new files (use as template).\n";
    const char *aCmdLineHelp_bottom =
        "-display <display>\n"\
        "      Specify X-Display to use in Unix/X11 versions.\n"
        "-p <documents...>\n"\
        "      print the specified documents on the default printer.\n"\
        "-pt <printer> <documents...>\n"\
        "      print the specified documents on the specified printer.\n"\
        "-view <documents...>\n"\
        "      open the specified documents in viewer-(readonly-)mode.\n"\
        "-show <sxi-document>\n"\
        "      open the specified presentation and start it immediately\n"\
        "-accept=<accept-string>\n"\
        "      Specify an UNO connect-string to create an UNO acceptor through which\n"\
        "      other programs can connect to access the API\n"\
        "-unaccept=<accept-sring>\n"\
        "      Close an acceptor that was created with -accept=<accept-string>\n"\
        "      Use -unnaccept=all to close all open acceptors\n"\
        "Remaining arguments will be treated as filenames or URLs of documents to open.\n";

    void ReplaceStringHookProc( UniString& rStr );

    void displayCmdlineHelp()
    {
        // if you put variables in other chunks don't forget to call the replace routines
        // for those chunks...
        String aHelpMessage_head(aCmdLineHelp_head, RTL_TEXTENCODING_ASCII_US);
        String aHelpMessage_left(aCmdLineHelp_left, RTL_TEXTENCODING_ASCII_US);
        String aHelpMessage_right(aCmdLineHelp_right, RTL_TEXTENCODING_ASCII_US);
        String aHelpMessage_bottom(aCmdLineHelp_bottom, RTL_TEXTENCODING_ASCII_US);
        ReplaceStringHookProc(aHelpMessage_head);
        ::rtl::OUString aDefault;
        String aVerId( ::utl::Bootstrap::getBuildIdData( aDefault ));
        aHelpMessage_head.SearchAndReplaceAscii( "%BUILDID", aVerId );
        aHelpMessage_head.SearchAndReplaceAscii( "%CMDNAME", String( "soffice", RTL_TEXTENCODING_ASCII_US) );
#ifdef UNX
        // on unix use console for output
        fprintf(stderr, "%s\n", ByteString(aHelpMessage_head,
                    RTL_TEXTENCODING_ASCII_US).GetBuffer());
        // merge left and right column
        int n = aHelpMessage_left.GetTokenCount ('\n');
        ByteString bsLeft(aHelpMessage_left, RTL_TEXTENCODING_ASCII_US);
        ByteString bsRight(aHelpMessage_right, RTL_TEXTENCODING_ASCII_US);
        for ( int i = 0; i < n; i++ )
        {
            fprintf(stderr, "%s", bsLeft.GetToken(i, '\n').GetBuffer());
            fprintf(stderr, "%s\n", bsRight.GetToken(i, '\n').GetBuffer());
        }
        fprintf(stderr, "%s", ByteString(aHelpMessage_bottom,
                    RTL_TEXTENCODING_ASCII_US).GetBuffer());
#else
        // rest gets a dialog box
        CmdlineHelpDialog aDlg;
        aDlg.m_ftHead.SetText(aHelpMessage_head);
        aDlg.m_ftLeft.SetText(aHelpMessage_left);
        aDlg.m_ftRight.SetText(aHelpMessage_right);
        aDlg.m_ftBottom.SetText(aHelpMessage_bottom);
        aDlg.Execute();
#endif
    }

    CmdlineHelpDialog::CmdlineHelpDialog (void)
    : ModalDialog( NULL, DesktopResId( DLG_CMDLINEHELP ) )
    , m_ftHead( this, DesktopResId( TXT_DLG_CMDLINEHELP_HEADER ) )
    , m_ftLeft( this, DesktopResId( TXT_DLG_CMDLINEHELP_LEFT ) )
    , m_ftRight( this, DesktopResId( TXT_DLG_CMDLINEHELP_RIGHT ) )
    , m_ftBottom( this, DesktopResId( TXT_DLG_CMDLINEHELP_BOTTOM ) )
    , m_btOk( this, DesktopResId( BTN_DLG_CMDLINEHELP_OK ) )
    {
        FreeResource();
    }

}

<|endoftext|>


<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* ScriptData
SDName: Boss_Grilek
SD%Complete: 100
SDComment:
SDCategory: Zul'Gurub
EndScriptData */

#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"

enum Spells
{
    SPELL_AVATAR                    = 24646, // Enrage Spell
    SPELL_GROUND_TREMOR             = 6524,
    SPELL_ENTANGLING_ROOTS          = 24648
};

enum Events
{
    EVENT_AVATAR                    = 1,
    EVENT_GROUND_TREMOR             = 2,
    EVENT_START_PURSUIT             = 3,
    EVENT_ENTANGLING_ROOTS          = 4
};

class boss_grilek : public CreatureScript // grilek
{
public:
    boss_grilek() : CreatureScript("boss_grilek") { }

    struct boss_grilekAI : public BossAI
    {
        boss_grilekAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS)
        {
        }

        void EnterCombat(Unit* /*who*/) override
        {
            _EnterCombat();
            events.ScheduleEvent(EVENT_AVATAR, 20s, 30s);
            events.ScheduleEvent(EVENT_GROUND_TREMOR, 15s, 25s);
            events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 5s, 15s);
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_AVATAR:
                        DoCast(me, SPELL_AVATAR);
                        DoResetThreat();
                        me->SetReactState(REACT_PASSIVE);
                        events.ScheduleEvent(EVENT_START_PURSUIT, 2s);
                        events.ScheduleEvent(EVENT_AVATAR, 45s, 50s);
                        break;
                    case EVENT_GROUND_TREMOR:
                        DoCastVictim(SPELL_GROUND_TREMOR, true);
                        events.ScheduleEvent(EVENT_GROUND_TREMOR, 12s, 16s);
                        break;
                    case EVENT_START_PURSUIT:
                        me->SetReactState(REACT_AGGRESSIVE);
                        break;
                    case EVENT_ENTANGLING_ROOTS:
                        DoCastVictim(SPELL_ENTANGLING_ROOTS);
                        events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 10s, 20s);
                        break;
                    default:
                        break;
                }
            }

            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return GetZulGurubAI<boss_grilekAI>(creature);
    }
};

void AddSC_boss_grilek()
{
    new boss_grilek();
}
<commit_msg>fix(Scripts/ZulGurub): Gri'lek should pursuit random targets. (#12194)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* ScriptData
SDName: Boss_Grilek
SD%Complete: 100
SDComment:
SDCategory: Zul'Gurub
EndScriptData */

#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"

enum Spells
{
    SPELL_AVATAR                    = 24646, // Enrage Spell
    SPELL_GROUND_TREMOR             = 6524,
    SPELL_ENTANGLING_ROOTS          = 24648
};

enum Events
{
    EVENT_AVATAR                    = 1,
    EVENT_GROUND_TREMOR             = 2,
    EVENT_START_PURSUIT             = 3,
    EVENT_STOP_PURSUIT              = 4,
    EVENT_ENTANGLING_ROOTS          = 5
};

class boss_grilek : public CreatureScript // grilek
{
public:
    boss_grilek() : CreatureScript("boss_grilek") { }

    struct boss_grilekAI : public BossAI
    {
        boss_grilekAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS)
        {
        }

        void Reset() override
        {
            _pursuitTargetGUID.Clear();
            BossAI::Reset();
        }

        void EnterCombat(Unit* /*who*/) override
        {
            _EnterCombat();
            events.ScheduleEvent(EVENT_AVATAR, 20s, 30s);
            events.ScheduleEvent(EVENT_GROUND_TREMOR, 15s, 25s);
            events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 5s, 15s);
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_AVATAR:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0))
                        {
                            _pursuitTargetGUID = target->GetGUID();
                        }
                        DoCast(me, SPELL_AVATAR);
                        me->SetReactState(REACT_PASSIVE);
                        DoResetThreat();
                        events.ScheduleEvent(EVENT_START_PURSUIT, 2s);
                        events.ScheduleEvent(EVENT_STOP_PURSUIT, 15s);
                        events.ScheduleEvent(EVENT_AVATAR, 45s, 50s);
                        break;
                    case EVENT_GROUND_TREMOR:
                        DoCastVictim(SPELL_GROUND_TREMOR, true);
                        events.ScheduleEvent(EVENT_GROUND_TREMOR, 12s, 16s);
                        break;
                    case EVENT_START_PURSUIT:
                        me->SetReactState(REACT_AGGRESSIVE);
                        if (Unit* pursuitTarget = ObjectAccessor::GetUnit(*me, _pursuitTargetGUID))
                        {
                            me->GetThreatMgr().addThreat(pursuitTarget, 1000000.f);
                        }
                        break;
                    case EVENT_STOP_PURSUIT:
                        if (Unit* pursuitTarget = ObjectAccessor::GetUnit(*me, _pursuitTargetGUID))
                        {
                            _pursuitTargetGUID.Clear();
                            me->GetThreatMgr().addThreat(pursuitTarget, -1000000.f);
                        }
                        break;
                    case EVENT_ENTANGLING_ROOTS:
                        DoCastVictim(SPELL_ENTANGLING_ROOTS);
                        events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 10s, 20s);
                        break;
                    default:
                        break;
                }
            }

            DoMeleeAttackIfReady();
        }

    private:
        ObjectGuid _pursuitTargetGUID;
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return GetZulGurubAI<boss_grilekAI>(creature);
    }
};

void AddSC_boss_grilek()
{
    new boss_grilek();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: updatesvc.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-19 16:18:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BACKEND_UPDATESVC_HXX
#define CONFIGMGR_BACKEND_UPDATESVC_HXX

#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_
#include "serviceinfohelper.hxx"
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#include <drafts/com/sun/star/configuration/backend/XUpdateHandler.hpp>

// -----------------------------------------------------------------------------
namespace drafts {
namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
    class XLayerHandler;
    class XLayer;
} } } } }
}
// -----------------------------------------------------------------------------

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------
        using rtl::OUString;
        namespace uno   = ::com::sun::star::uno;
        namespace lang  = ::com::sun::star::lang;
        namespace backenduno = drafts::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------

        class UpdateService : public ::cppu::WeakImplHelper3<
                                            lang::XInitialization,
                                            lang::XServiceInfo,
                                            backenduno::XUpdateHandler
                                        >
        {
        public:
            typedef uno::Reference< uno::XComponentContext > const & CreationArg;

            explicit
            UpdateService(CreationArg _xContext);

            // XInitialization
            virtual void SAL_CALL
                initialize( const uno::Sequence< uno::Any >& aArguments )
                    throw (uno::Exception, uno::RuntimeException);

            // XServiceInfo
            virtual ::rtl::OUString SAL_CALL
                getImplementationName(  )
                    throw (uno::RuntimeException);

            virtual sal_Bool SAL_CALL
                supportsService( const ::rtl::OUString& ServiceName )
                    throw (uno::RuntimeException);

            virtual uno::Sequence< ::rtl::OUString > SAL_CALL
                getSupportedServiceNames(  )
                    throw (uno::RuntimeException);

        protected:
            typedef uno::Reference< lang::XMultiServiceFactory >    ServiceFactory;
            typedef uno::Reference< backenduno::XLayer >            Layer;

            ServiceFactory getServiceFactory() const
            { return m_xServiceFactory; }

            void  checkSourceLayer() SAL_THROW( (lang::IllegalAccessException) )
            { validateSourceLayerAndCheckNotEmpty(); }

            Layer getSourceLayer()   SAL_THROW( (lang::IllegalAccessException) );

            void writeUpdatedLayer(Layer const & _xLayer);

            virtual sal_Bool setImplementationProperty(OUString const & aName, uno::Any const & aValue);

            void raiseIllegalAccessException(sal_Char const * pMsg)
                SAL_THROW( (lang::IllegalAccessException) );

        private:
            bool validateSourceLayerAndCheckNotEmpty() SAL_THROW( (lang::IllegalAccessException) );

        private:
            typedef uno::Reference< backenduno::XLayerHandler >     LayerWriter;

            ServiceFactory  m_xServiceFactory;
            Layer           m_xSourceLayer;
            LayerWriter     m_xLayerWriter;
            enum { merge, truncate, protect } m_aSourceMode;

            static ServiceInfoHelper getServiceInfo();
        };
// -----------------------------------------------------------------------------
    } // namespace xml
// -----------------------------------------------------------------------------

} // namespace configmgr
#endif

<commit_msg>INTEGRATION: CWS configapi01 (1.5.10); FILE MERGED 2003/04/10 15:47:13 jb 1.5.10.1: #1077715# Move configuration backend API out of drafts; adjust to API changes<commit_after>/*************************************************************************
 *
 *  $RCSfile: updatesvc.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-17 13:20:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BACKEND_UPDATESVC_HXX
#define CONFIGMGR_BACKEND_UPDATESVC_HXX

#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_
#include "serviceinfohelper.hxx"
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XUPDATEHANDLER_HPP_
#include <com/sun/star/configuration/backend/XUpdateHandler.hpp>
#endif

// -----------------------------------------------------------------------------

namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
    class XLayerHandler;
    class XLayer;
} } } } }

// -----------------------------------------------------------------------------

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------
        using rtl::OUString;
        namespace uno   = ::com::sun::star::uno;
        namespace lang  = ::com::sun::star::lang;
        namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------

        class UpdateService : public ::cppu::WeakImplHelper3<
                                            lang::XInitialization,
                                            lang::XServiceInfo,
                                            backenduno::XUpdateHandler
                                        >
        {
        public:
            typedef uno::Reference< uno::XComponentContext > const & CreationArg;

            explicit
            UpdateService(CreationArg _xContext);

            // XInitialization
            virtual void SAL_CALL
                initialize( const uno::Sequence< uno::Any >& aArguments )
                    throw (uno::Exception, uno::RuntimeException);

            // XServiceInfo
            virtual ::rtl::OUString SAL_CALL
                getImplementationName(  )
                    throw (uno::RuntimeException);

            virtual sal_Bool SAL_CALL
                supportsService( const ::rtl::OUString& ServiceName )
                    throw (uno::RuntimeException);

            virtual uno::Sequence< ::rtl::OUString > SAL_CALL
                getSupportedServiceNames(  )
                    throw (uno::RuntimeException);

        protected:
            typedef uno::Reference< lang::XMultiServiceFactory >    ServiceFactory;
            typedef uno::Reference< backenduno::XLayer >            Layer;

            ServiceFactory getServiceFactory() const
            { return m_xServiceFactory; }

            void  checkSourceLayer() SAL_THROW( (lang::IllegalAccessException) )
            { validateSourceLayerAndCheckNotEmpty(); }

            Layer getSourceLayer()   SAL_THROW( (lang::IllegalAccessException) );

            void writeUpdatedLayer(Layer const & _xLayer);

            virtual sal_Bool setImplementationProperty(OUString const & aName, uno::Any const & aValue);

            void raiseIllegalAccessException(sal_Char const * pMsg)
                SAL_THROW( (lang::IllegalAccessException) );

        private:
            bool validateSourceLayerAndCheckNotEmpty() SAL_THROW( (lang::IllegalAccessException) );

        private:
            typedef uno::Reference< backenduno::XLayerHandler >     LayerWriter;

            ServiceFactory  m_xServiceFactory;
            Layer           m_xSourceLayer;
            LayerWriter     m_xLayerWriter;
            enum { merge, truncate, protect } m_aSourceMode;

            static ServiceInfoHelper getServiceInfo();
        };
// -----------------------------------------------------------------------------
    } // namespace xml
// -----------------------------------------------------------------------------

} // namespace configmgr
#endif

<|endoftext|>


<commit_before>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>

#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !

std::stringstream *linestream;
std::string token = "";
const char *filename;

// return float from linestream
inline float getFloat() {
  if (!getline(*linestream, token, ',')) {
    std::cerr << "error: could not parse " << filename << std::endl ;
    exit(1);
  }
  return atof(token.c_str());
}

// return unsigned long from linestream
inline float getUlong() {
  if (!getline(*linestream, token, ',')) {
    std::cerr << "error: could not parse " << filename << std::endl ;
    exit(1);
  }
  return strtoul(token.c_str(),NULL,0);
}

// skip value from linestream
inline float skip() {
  if (!getline(*linestream, token, ',')) {
    std::cerr << "error: could not parse " << filename << std::endl ;
    exit(1);
  }
}

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

  std::string line = "";
  unsigned int index;
  float depth, theta, phi, mn95_x, mn95_y, mn95_z;
  int lon, lat;
  float r=150.0; // webgl sphere radius
  float fx,fy,fz;
  std::list<uint32_t> sector[360][180];
  float step=M_PI/180.0;
  uint32_t point_index=0;
  unsigned long nb_points=0;

  if (argc!=2) {
    std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
    return 1;
  }

  // open json
  filename=argv[1];
  std::ifstream fs(filename);
  if (!fs.is_open()) {
    std::cerr << "could not open " << filename << std::endl ;
    return 1;
  }

  // extract "nb_points" from json
  while (getline(fs, line)) {
    if (const char *pos=strstr(line.c_str(),"nb_points")) {
      nb_points=strtoul(strchr(pos,':')+1,NULL,0);
      break;
    }
  }
  if (!nb_points) {
    std::cerr << "error: could not parse" << filename << std::endl ;
    return 1;
  }

  // remove input filename extension
  std::string fname=std::string(filename);
  fname.erase(fname.find_last_of("."),std::string::npos);

  // create .bin output file
  std::string outfname=fname+".bin";
  std::ofstream outf;
  outf.open(outfname.c_str());
  if (!outf.is_open()) {
    std::cerr << "could not open " << outfname << std::endl ;
    return 1;
  }

  std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;

  // 1. parse lines beginning with [0-9] as a csv formatted as:
  // "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
  // 2. store cartesian coordinates in "sector" array as:
  // float x, float y, float z

  float *mn95=new float[nb_points*3];
  float *positions=new float[nb_points*3];

  while (getline(fs, line)) {

      // skip line not beginning with [0-9]
      if (line[0]<'0' || line[0]>'9') continue;

      if (point_index>= nb_points) {
        std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
        return 1;
      }

      // read line
      linestream=new std::stringstream(line);

      // extract fields
      depth=getFloat();
      index=getUlong();
      theta=getFloat();
      phi=getFloat();
      mn95_x=getFloat();
      mn95_y=getFloat();
      mn95_z=getFloat();

      // compute sector location
      lon=((int)round(theta/step)+180)%360;
      lat=round(phi/step);
      if (lat<0) lat+=180;
      lat=(180-lat)%180;

      // reference particle in sector lon,lat
      sector[lon][lat].push_back(point_index);

      // compute cartesian webgl coordinates
      phi=(phi-M_PI/2);
      theta=theta-M_PI/2;
      fx=depth*sin(phi)*cos(theta);
      fz=depth*sin(phi)*sin(theta);
      fy=-depth*cos(phi);

      // store cartesian coordinates
      unsigned long k=point_index*3;
      positions[k]=fx;
      positions[k+1]=fy;
      positions[k+2]=fz;

      // store mn95 coordinates
      mn95[k]=mn95_x;
      mn95[k+1]=mn95_y;
      mn95[k+2]=mn95_z;

      ++point_index;
  }

  if (point_index!=nb_points) {
    std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
    return 1;
  }

  // output file marker and version number
  outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
  outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));

  std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;

  long int data_offset=outf.tellp();

  // output positions formatted as list of x,y,z for each [lon][lat] pair
  // and prepare a 360x180 array index formatted as offset,count

  std::list<uint32_t> array_index;

  for (lat=0; lat<180; ++lat) {
    for (lon=0; lon<360; ++lon) {

      std::list<uint32_t> *_sector=&sector[lon][lat];

      // update array index
      uint32_t particle_count=_sector->size();
      if (particle_count) {
        // particles in this sector: store offset and particle count
        array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
        array_index.push_back(particle_count);
      } else {
        // no particles here
        array_index.push_back(0);
        array_index.push_back(0);
        continue;
      }

      // output particle positions for sector[lon][lat]
      for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
        uint32_t index=*it;
        outf.write((char*)&positions[index],sizeof(*positions)*3);
      }
    }
  }

  // check integrity
  unsigned long positions_byteCount=outf.tellp()-data_offset;
  int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
  std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
  if (failure) {
    return 1;
  }

  // output mn95 coordinates
  for (lat=0; lat<180; ++lat) {
    for (lon=0; lon<360; ++lon) {

      std::list<uint32_t> *_sector=&sector[lon][lat];

      if (!_sector->size()) {
        continue;
      }

      // output mn95 positions for sector[lon][lat]
      for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
        uint32_t index=*it;
        outf.write((char*)&mn95[index],sizeof(*mn95)*3);
      }
    }
  }

  // check integrity
  long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
  failure=(mn95_byteCount!=positions_byteCount);
  std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
  if (failure) {
    return 1;
  }

  // output index formatted as:
  // offset, particle_count
  for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
    uint32_t value=*it;
    outf.write((char*)&value,sizeof(value));
  }

  // check integrity
  flush(outf);
  long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
  failure=(index_byteCount%4);
  std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
  if (failure) {
    return 1;
  }

  outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
  outf.close();

  if (mn95_byteCount!=positions_byteCount) {
    std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
    return 1;
  }

  return 0;

}

<commit_msg>json2bin.cpp: fix index<commit_after>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>

#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !

std::stringstream *linestream;
std::string token = "";
const char *filename;

// return float from linestream
inline float getFloat() {
  if (!getline(*linestream, token, ',')) {
    std::cerr << "error: could not parse " << filename << std::endl ;
    exit(1);
  }
  return atof(token.c_str());
}

// return unsigned long from linestream
inline float getUlong() {
  if (!getline(*linestream, token, ',')) {
    std::cerr << "error: could not parse " << filename << std::endl ;
    exit(1);
  }
  return strtoul(token.c_str(),NULL,0);
}

// skip value from linestream
inline float skip() {
  if (!getline(*linestream, token, ',')) {
    std::cerr << "error: could not parse " << filename << std::endl ;
    exit(1);
  }
}

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

  std::string line = "";
  unsigned int index;
  float depth, theta, phi, mn95_x, mn95_y, mn95_z;
  int lon, lat;
  float r=150.0; // webgl sphere radius
  float fx,fy,fz;
  std::list<uint32_t> sector[360][180];
  float step=M_PI/180.0;
  uint32_t point_index=0;
  unsigned long nb_points=0;

  if (argc!=2) {
    std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
    return 1;
  }

  // open json
  filename=argv[1];
  std::ifstream fs(filename);
  if (!fs.is_open()) {
    std::cerr << "could not open " << filename << std::endl ;
    return 1;
  }

  // extract "nb_points" from json
  while (getline(fs, line)) {
    if (const char *pos=strstr(line.c_str(),"nb_points")) {
      nb_points=strtoul(strchr(pos,':')+1,NULL,0);
      break;
    }
  }
  if (!nb_points) {
    std::cerr << "error: could not parse" << filename << std::endl ;
    return 1;
  }

  // remove input filename extension
  std::string fname=std::string(filename);
  fname.erase(fname.find_last_of("."),std::string::npos);

  // create .bin output file
  std::string outfname=fname+".bin";
  std::ofstream outf;
  outf.open(outfname.c_str());
  if (!outf.is_open()) {
    std::cerr << "could not open " << outfname << std::endl ;
    return 1;
  }

  std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;

  // 1. parse lines beginning with [0-9] as a csv formatted as:
  // "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
  // 2. store cartesian coordinates in "sector" array as:
  // float x, float y, float z

  float *mn95=new float[nb_points*3];
  float *positions=new float[nb_points*3];

  while (getline(fs, line)) {

      // skip line not beginning with [0-9]
      if (line[0]<'0' || line[0]>'9') continue;

      if (point_index>= nb_points) {
        std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
        return 1;
      }

      // read line
      linestream=new std::stringstream(line);

      // extract fields
      depth=getFloat();
      index=getUlong();
      theta=getFloat();
      phi=getFloat();
      mn95_x=getFloat();
      mn95_y=getFloat();
      mn95_z=getFloat();

      // compute sector location
      lon=((int)round(theta/step)+180)%360;
      lat=round(phi/step);
      if (lat<0) lat+=180;
      lat=(180-lat)%180;

      // reference particle in sector lon,lat
      unsigned long k=point_index*3;
      sector[lon][lat].push_back(k);

      // compute cartesian webgl coordinates
      phi=(phi-M_PI/2);
      theta=theta-M_PI/2;
      fx=depth*sin(phi)*cos(theta);
      fz=depth*sin(phi)*sin(theta);
      fy=-depth*cos(phi);

      // store cartesian coordinates
      positions[k]=fx;
      positions[k+1]=fy;
      positions[k+2]=fz;

      // store mn95 coordinates
      mn95[k]=mn95_x;
      mn95[k+1]=mn95_y;
      mn95[k+2]=mn95_z;

      ++point_index;
  }

  if (point_index!=nb_points) {
    std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
    return 1;
  }

  // output file marker and version number
  outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
  outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));

  std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;

  long int data_offset=outf.tellp();

  // output positions formatted as list of x,y,z for each [lon][lat] pair
  // and prepare a 360x180 array index formatted as offset,count

  std::list<uint32_t> array_index;

  for (lat=0; lat<180; ++lat) {
    for (lon=0; lon<360; ++lon) {

      std::list<uint32_t> *_sector=&sector[lon][lat];

      // update array index
      uint32_t particle_count=_sector->size();
      if (particle_count) {
        // particles in this sector: store offset and particle count
        array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
        array_index.push_back(particle_count);
      } else {
        // no particles here
        array_index.push_back(0);
        array_index.push_back(0);
        continue;
      }

      // output particle positions for sector[lon][lat]
      for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
        uint32_t index=*it;
        outf.write((char*)&positions[index],sizeof(*positions)*3);
      }
    }
  }

  // check integrity
  unsigned long positions_byteCount=outf.tellp()-data_offset;
  int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
  std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
  if (failure) {
    return 1;
  }

  // output mn95 coordinates
  for (lat=0; lat<180; ++lat) {
    for (lon=0; lon<360; ++lon) {

      std::list<uint32_t> *_sector=&sector[lon][lat];

      if (!_sector->size()) {
        continue;
      }
      // output mn95 positions for sector[lon][lat]
      for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
        uint32_t index=*it;
        outf.write((char*)&mn95[index],sizeof(*mn95)*3);
      }
    }
  }

  // check integrity
  long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
  failure=(mn95_byteCount!=positions_byteCount);
  std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
  if (failure) {
    return 1;
  }

  // output index formatted as:
  // offset, particle_count
  for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
    uint32_t value=*it;
    outf.write((char*)&value,sizeof(value));
  }

  // check integrity
  flush(outf);
  long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
  failure=(index_byteCount%4);
  std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
  if (failure) {
    return 1;
  }

  outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
  outf.close();

  if (mn95_byteCount!=positions_byteCount) {
    std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
    return 1;
  }

  return 0;

}

<|endoftext|>