<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"

#include <assert.h>
#include <stdlib.h>

#include <string>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "webrtc/modules/audio_coding/neteq4/mock/mock_audio_decoder.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

TEST(DecoderDatabase, CreateAndDestroy) {
  DecoderDatabase db;
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, InsertAndRemove) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(1, db.Size());
  EXPECT_FALSE(db.Empty());
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, GetDecoderInfo) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(NULL, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_FALSE(info->external);
  info = db.GetDecoderInfo(kPayloadType + 1);  // Other payload type.
  EXPECT_TRUE(info == NULL);  // Should not be found.
}

TEST(DecoderDatabase, GetRtpPayloadType) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));
  const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;
  EXPECT_EQ(expected_value,
            db.GetRtpPayloadType(kDecoderISAC));  // iSAC is not registered.
}

TEST(DecoderDatabase, DISABLED_ON_ANDROID(GetDecoder)) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderILBC));
  AudioDecoder* dec = db.GetDecoder(kPayloadType);
  ASSERT_TRUE(dec != NULL);
}

TEST(DecoderDatabase, TypeTests) {
  DecoderDatabase db;
  const uint8_t kPayloadTypePcmU = 0;
  const uint8_t kPayloadTypeCng = 13;
  const uint8_t kPayloadTypeDtmf = 100;
  const uint8_t kPayloadTypeRed = 101;
  const uint8_t kPayloadNotUsed = 102;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeRed, kDecoderRED));
  EXPECT_EQ(4, db.Size());
  // Test.
  EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));
  EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));
  EXPECT_FALSE(db.IsRed(kPayloadNotUsed));
  EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));
  EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));
  EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));
  EXPECT_TRUE(db.IsRed(kPayloadTypeRed));
}

TEST(DecoderDatabase, ExternalDecoder) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  MockAudioDecoder decoder;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,
                               &decoder));
  EXPECT_EQ(1, db.Size());
  // Get decoder and make sure we get the external one.
  EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));
  // Get the decoder info struct and check it too.
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(&decoder, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_TRUE(info->external);
  // Expect not to delete the decoder when removing it from the database, since
  // it was declared externally.
  EXPECT_CALL(decoder, Die()).Times(0);
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_TRUE(db.Empty());

  EXPECT_CALL(decoder, Die()).Times(1);  // Will be called when |db| is deleted.
}

TEST(DecoderDatabase, CheckPayloadTypes) {
  DecoderDatabase db;
  // Load a number of payloads into the database. Payload types are 0, 1, ...,
  // while the decoder type is the same for all payload types (this does not
  // matter for the test).
  const int kNumPayloads = 10;
  for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {
    EXPECT_EQ(DecoderDatabase::kOK,
              db.RegisterPayload(payload_type, kDecoderArbitrary));
  }
  PacketList packet_list;
  for (int i = 0; i < kNumPayloads + 1; ++i) {
    // Create packet with payload type |i|. The last packet will have a payload
    // type that is not registered in the decoder database.
    Packet* packet = new Packet;
    packet->header.payloadType = i;
    packet_list.push_back(packet);
  }

  // Expect to return false, since the last packet is of an unknown type.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.CheckPayloadTypes(packet_list));

  delete packet_list.back();
  packet_list.pop_back();  // Remove the unknown one.

  EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));

  // Delete all packets.
  PacketList::iterator it = packet_list.begin();
  while (it != packet_list.end()) {
    delete packet_list.front();
    it = packet_list.erase(it);
  }
}

// Test the methods for setting and getting active speech and CNG decoders.
TEST(DecoderDatabase, ActiveDecoders) {
  DecoderDatabase db;
  // Load payload types.
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));
  // Verify that no decoders are active from the start.
  EXPECT_EQ(NULL, db.GetActiveDecoder());
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Set active speech codec.
  bool changed;  // Should be true when the active decoder changed.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_TRUE(changed);
  AudioDecoder* decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Set the same again. Expect no change.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_FALSE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Change active decoder.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));
  EXPECT_TRUE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderISAC, decoder->codec_type());

  // Remove the active decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));
  EXPECT_EQ(NULL, db.GetActiveDecoder());

  // Set active CNG codec.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));
  decoder = db.GetActiveCngDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());

  // Remove the active CNG decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Try to set non-existing codecs as active.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveDecoder(17, &changed));
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveCngDecoder(17));
}
}  // namespace webrtc
<commit_msg>Re-enable NetEQ DecoderDatabase test for Android<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"

#include <assert.h>
#include <stdlib.h>

#include <string>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "webrtc/modules/audio_coding/neteq4/mock/mock_audio_decoder.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

TEST(DecoderDatabase, CreateAndDestroy) {
  DecoderDatabase db;
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, InsertAndRemove) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(1, db.Size());
  EXPECT_FALSE(db.Empty());
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_EQ(0, db.Size());
  EXPECT_TRUE(db.Empty());
}

TEST(DecoderDatabase, GetDecoderInfo) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(NULL, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_FALSE(info->external);
  info = db.GetDecoderInfo(kPayloadType + 1);  // Other payload type.
  EXPECT_TRUE(info == NULL);  // Should not be found.
}

TEST(DecoderDatabase, GetRtpPayloadType) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCMu));
  EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));
  const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;
  EXPECT_EQ(expected_value,
            db.GetRtpPayloadType(kDecoderISAC));  // iSAC is not registered.
}

TEST(DecoderDatabase, GetDecoder) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadType, kDecoderPCM16B));
  AudioDecoder* dec = db.GetDecoder(kPayloadType);
  ASSERT_TRUE(dec != NULL);
}

TEST(DecoderDatabase, TypeTests) {
  DecoderDatabase db;
  const uint8_t kPayloadTypePcmU = 0;
  const uint8_t kPayloadTypeCng = 13;
  const uint8_t kPayloadTypeDtmf = 100;
  const uint8_t kPayloadTypeRed = 101;
  const uint8_t kPayloadNotUsed = 102;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));
  EXPECT_EQ(DecoderDatabase::kOK,
            db.RegisterPayload(kPayloadTypeRed, kDecoderRED));
  EXPECT_EQ(4, db.Size());
  // Test.
  EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));
  EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));
  EXPECT_FALSE(db.IsRed(kPayloadNotUsed));
  EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));
  EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));
  EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));
  EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));
  EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));
  EXPECT_TRUE(db.IsRed(kPayloadTypeRed));
}

TEST(DecoderDatabase, ExternalDecoder) {
  DecoderDatabase db;
  const uint8_t kPayloadType = 0;
  MockAudioDecoder decoder;
  // Load into database.
  EXPECT_EQ(DecoderDatabase::kOK,
            db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,
                               &decoder));
  EXPECT_EQ(1, db.Size());
  // Get decoder and make sure we get the external one.
  EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));
  // Get the decoder info struct and check it too.
  const DecoderDatabase::DecoderInfo* info;
  info = db.GetDecoderInfo(kPayloadType);
  ASSERT_TRUE(info != NULL);
  EXPECT_EQ(kDecoderPCMu, info->codec_type);
  EXPECT_EQ(&decoder, info->decoder);
  EXPECT_EQ(8000, info->fs_hz);
  EXPECT_TRUE(info->external);
  // Expect not to delete the decoder when removing it from the database, since
  // it was declared externally.
  EXPECT_CALL(decoder, Die()).Times(0);
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
  EXPECT_TRUE(db.Empty());

  EXPECT_CALL(decoder, Die()).Times(1);  // Will be called when |db| is deleted.
}

TEST(DecoderDatabase, CheckPayloadTypes) {
  DecoderDatabase db;
  // Load a number of payloads into the database. Payload types are 0, 1, ...,
  // while the decoder type is the same for all payload types (this does not
  // matter for the test).
  const int kNumPayloads = 10;
  for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {
    EXPECT_EQ(DecoderDatabase::kOK,
              db.RegisterPayload(payload_type, kDecoderArbitrary));
  }
  PacketList packet_list;
  for (int i = 0; i < kNumPayloads + 1; ++i) {
    // Create packet with payload type |i|. The last packet will have a payload
    // type that is not registered in the decoder database.
    Packet* packet = new Packet;
    packet->header.payloadType = i;
    packet_list.push_back(packet);
  }

  // Expect to return false, since the last packet is of an unknown type.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.CheckPayloadTypes(packet_list));

  delete packet_list.back();
  packet_list.pop_back();  // Remove the unknown one.

  EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));

  // Delete all packets.
  PacketList::iterator it = packet_list.begin();
  while (it != packet_list.end()) {
    delete packet_list.front();
    it = packet_list.erase(it);
  }
}

// Test the methods for setting and getting active speech and CNG decoders.
TEST(DecoderDatabase, ActiveDecoders) {
  DecoderDatabase db;
  // Load payload types.
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));
  ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));
  // Verify that no decoders are active from the start.
  EXPECT_EQ(NULL, db.GetActiveDecoder());
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Set active speech codec.
  bool changed;  // Should be true when the active decoder changed.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_TRUE(changed);
  AudioDecoder* decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Set the same again. Expect no change.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
  EXPECT_FALSE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderPCMu, decoder->codec_type());

  // Change active decoder.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));
  EXPECT_TRUE(changed);
  decoder = db.GetActiveDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderISAC, decoder->codec_type());

  // Remove the active decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));
  EXPECT_EQ(NULL, db.GetActiveDecoder());

  // Set active CNG codec.
  EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));
  decoder = db.GetActiveCngDecoder();
  ASSERT_FALSE(decoder == NULL);  // Should get a decoder here.
  EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());

  // Remove the active CNG decoder, and verify that the active becomes NULL.
  EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));
  EXPECT_EQ(NULL, db.GetActiveCngDecoder());

  // Try to set non-existing codecs as active.
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveDecoder(17, &changed));
  EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
            db.SetActiveCngDecoder(17));
}
}  // namespace webrtc
<|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.
 */
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680

#if defined(__cplusplus)
#include "xercesc/util/XercesDefs.hpp"
#endif

#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(OS400)
#include "OS400Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#elif defined(__IBMCPP__) && defined(__TOS_LINUX__)
// This is for Linux PPC using the IBM xlC compiler.
#include "AIXDefinitions.hpp"
#else
#error Unknown compiler!
#endif

#include "XalanVersion.hpp"

#if defined(__cplusplus)

// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
    #define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
    #define XALAN_CPP_NAMESPACE_END  }
    #define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
    #define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
    #define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
    #define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
    #define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }

    namespace XALAN_CPP_NAMESPACE { }
    namespace xalanc = XALAN_CPP_NAMESPACE;
#else
    #if defined(XALAN_CPP_NAMESPACE)
    #undef XALAN_CPP_NAMESPACE
    #endif

    #define XALAN_CPP_NAMESPACE
    #define XALAN_CPP_NAMESPACE_BEGIN
    #define XALAN_CPP_NAMESPACE_END
    #define XALAN_CPP_NAMESPACE_USE
    #define XALAN_CPP_NAMESPACE_QUALIFIER
    #define XALAN_USING(NAMESPACE,NAME)
    #define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
    #define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
    #if !defined(XALAN_NO_STD_NAMESPACE)
        #define XALAN_NO_STD_NAMESPACE
    #endif
#endif

#if defined(XALAN_NO_STD_NAMESPACE)
    #define XALAN_USING_STD(NAME)
    #define XALAN_STD_QUALIFIER
#else
    #define XALAN_USING_STD(NAME) using std :: NAME;
    #define XALAN_STD_QUALIFIER  std ::
#endif

#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)

#if defined(XERCES_HAS_CPP_NAMESPACE)
    #define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)
    #define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
    #define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)
#else
    #define XERCES_CPP_NAMESPACE_QUALIFIER
    #define XERCES_CPP_NAMESPACE_BEGIN
    #define XERCES_CPP_NAMESPACE_END
    #define XERCES_CPP_NAMESPACE_USE
    #define XALAN_USING_XERCES(NAME)
    #define XALAN_DECLARE_XERCES_CLASS(NAME) class NAME;
    #define XALAN_DECLARE_XERCES_STRUCT(NAME) struct NAME;
#endif

#include <cstddef>

XALAN_CPP_NAMESPACE_BEGIN

#if XERCES_VERSION_MAJOR < 3
typedef unsigned int    XalanSize_t;
typedef unsigned int    XalanFilePos;
typedef XMLSSize_t      XalanFileLoc;
#else
typedef XMLSize_t       XalanSize_t;
typedef XMLFilePos      XalanFilePos;
typedef XMLFileLoc      XalanFileLoc;
#endif

typedef XMLCh           XalanDOMChar;
typedef unsigned int    XalanUnicodeChar;
typedef XMLSSize_t      XalanSSize_t;

template<bool value>
struct XalanCompileErrorBoolean
{
    char    foo[value];
};

XALAN_CPP_NAMESPACE_END

#if !defined(XALAN_NO_LONG_LONG)
typedef unsigned long long XALAN_UINT64;
typedef long long  XALAN_INT64;
#endif

#define XALAN_STATIC_ASSERT(expr) XALAN_CPP_NAMESPACE_QUALIFIER XalanCompileErrorBoolean<bool(expr)>()

#endif // __cplusplus

#endif  // PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>JIRA [XALANC-708] ensure that XMLCh is defined when using 'C' language API interfaces.<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.
 */

#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680

#if defined(__cplusplus)
# include "xercesc/util/XercesDefs.hpp"
#else
/* Include xercesc autoconf to define XMLCh when using a 'C' compiler. */
# include "xercesc/util/Xerces_autoconf_config.hpp"
# include "xercesc/util/XercesVersion.hpp"
#endif

#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(OS400)
#include "OS400Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#elif defined(__IBMCPP__) && defined(__TOS_LINUX__)
// This is for Linux PPC using the IBM xlC compiler.
#include "AIXDefinitions.hpp"
#else
#error Unknown compiler!
#endif

#include "XalanVersion.hpp"

#if defined(__cplusplus)

// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
    #define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
    #define XALAN_CPP_NAMESPACE_END  }
    #define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
    #define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
    #define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
    #define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
    #define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }

    namespace XALAN_CPP_NAMESPACE { }
    namespace xalanc = XALAN_CPP_NAMESPACE;
#else
    #if defined(XALAN_CPP_NAMESPACE)
    #undef XALAN_CPP_NAMESPACE
    #endif

    #define XALAN_CPP_NAMESPACE
    #define XALAN_CPP_NAMESPACE_BEGIN
    #define XALAN_CPP_NAMESPACE_END
    #define XALAN_CPP_NAMESPACE_USE
    #define XALAN_CPP_NAMESPACE_QUALIFIER
    #define XALAN_USING(NAMESPACE,NAME)
    #define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
    #define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
    #if !defined(XALAN_NO_STD_NAMESPACE)
        #define XALAN_NO_STD_NAMESPACE
    #endif
#endif

#if defined(XALAN_NO_STD_NAMESPACE)
    #define XALAN_USING_STD(NAME)
    #define XALAN_STD_QUALIFIER
#else
    #define XALAN_USING_STD(NAME) using std :: NAME;
    #define XALAN_STD_QUALIFIER  std ::
#endif

#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)

#if defined(XERCES_HAS_CPP_NAMESPACE)
    #define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)
    #define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
    #define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)
#else
    #define XERCES_CPP_NAMESPACE_QUALIFIER
    #define XERCES_CPP_NAMESPACE_BEGIN
    #define XERCES_CPP_NAMESPACE_END
    #define XERCES_CPP_NAMESPACE_USE
    #define XALAN_USING_XERCES(NAME)
    #define XALAN_DECLARE_XERCES_CLASS(NAME) class NAME;
    #define XALAN_DECLARE_XERCES_STRUCT(NAME) struct NAME;
#endif

#include <cstddef>

XALAN_CPP_NAMESPACE_BEGIN

#if XERCES_VERSION_MAJOR < 3
typedef unsigned int    XalanSize_t;
typedef unsigned int    XalanFilePos;
typedef XMLSSize_t      XalanFileLoc;
#else
typedef XMLSize_t       XalanSize_t;
typedef XMLFilePos      XalanFilePos;
typedef XMLFileLoc      XalanFileLoc;
#endif

typedef XMLCh           XalanDOMChar;
typedef unsigned int    XalanUnicodeChar;
typedef XMLSSize_t      XalanSSize_t;

template<bool value>
struct XalanCompileErrorBoolean
{
    char    foo[value];
};

XALAN_CPP_NAMESPACE_END

#if !defined(XALAN_NO_LONG_LONG)
typedef unsigned long long XALAN_UINT64;
typedef long long  XALAN_INT64;
#endif

#define XALAN_STATIC_ASSERT(expr) XALAN_CPP_NAMESPACE_QUALIFIER XalanCompileErrorBoolean<bool(expr)>()

#endif // __cplusplus

#endif  // PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tdenum.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2004-03-25 14:48:31 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif

namespace stoc_rdbtdp
{

//__________________________________________________________________________________________________
EnumTypeDescriptionImpl::~EnumTypeDescriptionImpl()
{
    delete _pEnumNames;
    delete _pEnumValues;
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XTypeDescription
//__________________________________________________________________________________________________
TypeClass EnumTypeDescriptionImpl::getTypeClass()
    throw(::com::sun::star::uno::RuntimeException)
{
    return TypeClass_ENUM;
}
//__________________________________________________________________________________________________
OUString EnumTypeDescriptionImpl::getName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _aName;
}

// XEnumTypeDescription
//__________________________________________________________________________________________________
sal_Int32 EnumTypeDescriptionImpl::getDefaultEnumValue()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _nDefaultValue;
}
//__________________________________________________________________________________________________
Sequence< OUString > EnumTypeDescriptionImpl::getEnumNames()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pEnumNames)
    {
        RegistryTypeReaderLoader aLoader;
        RegistryTypeReader aReader(
            aLoader, (const sal_uInt8 *)_aBytes.getConstArray(),
            _aBytes.getLength(), sal_False );

        sal_uInt16 nFields = (sal_uInt16)aReader.getFieldCount();
        Sequence< OUString > * pTempEnumNames = new Sequence< OUString >( nFields );
        OUString * pEnumNames = pTempEnumNames->getArray();

        while (nFields--)
        {
            pEnumNames[nFields] = aReader.getFieldName( nFields );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pEnumNames)
        {
            aGuard.clear();
            delete pTempEnumNames;
        }
        else
        {
            _pEnumNames = pTempEnumNames;
        }
    }
    return *_pEnumNames;
}
//__________________________________________________________________________________________________
Sequence< sal_Int32 > EnumTypeDescriptionImpl::getEnumValues()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pEnumValues)
    {
        RegistryTypeReaderLoader aLoader;
        RegistryTypeReader aReader(
            aLoader, (const sal_uInt8 *)_aBytes.getConstArray(),
            _aBytes.getLength(), sal_False );

        sal_uInt16 nFields = (sal_uInt16)aReader.getFieldCount();
        Sequence< sal_Int32 > * pTempEnumValues = new Sequence< sal_Int32 >( nFields );
        sal_Int32 * pEnumValues = pTempEnumValues->getArray();

        while (nFields--)
        {
            pEnumValues[nFields] = getRTValueAsInt32( aReader.getFieldConstValue( nFields ) );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pEnumValues)
        {
            aGuard.clear();
            delete pTempEnumValues;
        }
        else
        {
            _pEnumValues = pTempEnumValues;
        }
    }
    return *_pEnumValues;
}

}

<commit_msg>INTEGRATION: CWS sb14 (1.4.104); FILE MERGED 2004/03/12 14:18:49 sb 1.4.104.1: #i21150# Adapted to modified registry type reader.<commit_after>/*************************************************************************
 *
 *  $RCSfile: tdenum.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-30 16:16:23 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif

#include "registry/reader.hxx"
#include "registry/version.h"

namespace stoc_rdbtdp
{

//__________________________________________________________________________________________________
EnumTypeDescriptionImpl::~EnumTypeDescriptionImpl()
{
    delete _pEnumNames;
    delete _pEnumValues;
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XTypeDescription
//__________________________________________________________________________________________________
TypeClass EnumTypeDescriptionImpl::getTypeClass()
    throw(::com::sun::star::uno::RuntimeException)
{
    return TypeClass_ENUM;
}
//__________________________________________________________________________________________________
OUString EnumTypeDescriptionImpl::getName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _aName;
}

// XEnumTypeDescription
//__________________________________________________________________________________________________
sal_Int32 EnumTypeDescriptionImpl::getDefaultEnumValue()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _nDefaultValue;
}
//__________________________________________________________________________________________________
Sequence< OUString > EnumTypeDescriptionImpl::getEnumNames()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pEnumNames)
    {
        typereg::Reader aReader(
            _aBytes.getConstArray(), _aBytes.getLength(), false,
            TYPEREG_VERSION_1);

        sal_uInt16 nFields = aReader.getFieldCount();
        Sequence< OUString > * pTempEnumNames = new Sequence< OUString >( nFields );
        OUString * pEnumNames = pTempEnumNames->getArray();

        while (nFields--)
        {
            pEnumNames[nFields] = aReader.getFieldName( nFields );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pEnumNames)
        {
            aGuard.clear();
            delete pTempEnumNames;
        }
        else
        {
            _pEnumNames = pTempEnumNames;
        }
    }
    return *_pEnumNames;
}
//__________________________________________________________________________________________________
Sequence< sal_Int32 > EnumTypeDescriptionImpl::getEnumValues()
    throw(::com::sun::star::uno::RuntimeException)
{
    if (! _pEnumValues)
    {
        typereg::Reader aReader(
            _aBytes.getConstArray(), _aBytes.getLength(), false,
            TYPEREG_VERSION_1);

        sal_uInt16 nFields = aReader.getFieldCount();
        Sequence< sal_Int32 > * pTempEnumValues = new Sequence< sal_Int32 >( nFields );
        sal_Int32 * pEnumValues = pTempEnumValues->getArray();

        while (nFields--)
        {
            pEnumValues[nFields] = getRTValueAsInt32(
                aReader.getFieldValue( nFields ) );
        }

        ClearableMutexGuard aGuard( getMutex() );
        if (_pEnumValues)
        {
            aGuard.clear();
            delete pTempEnumValues;
        }
        else
        {
            _pEnumValues = pTempEnumValues;
        }
    }
    return *_pEnumValues;
}

}

<|endoftext|>


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

#include <stdio.h>
#include "string.hxx"

/****************************************************************************/
#if defined( UNX ) || defined( MAC )
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/****************************************************************************/
{
    if ( argc < 4 )
    {
        fprintf( stderr, "ERROR: too few parameters. \n\n");
        fprintf( stderr, "usage: txtrep.exe EnvironmentVariable Searchstring replacestring\n");
        return 1;
    }
    ByteString aText( getenv( argv[ 1 ] ));
    if ( aText.Len() == 0 )
    {
        fprintf( stderr, "ERROR: Variable not set. \n\n");
        fprintf( stderr, "usage: txtrep.exe EnvironmentVariable Searchstring replacestring\n");
        return 2;
    }
    ByteString aSearch( argv[ 2 ] );
    ByteString aReplace( argv[ 3 ] );

    ByteString aUpperText( aText );
    aUpperText.ToUpperAscii();

    ULONG nIndex;
    aSearch.ToUpperAscii();

    nIndex = aUpperText.Search( aSearch.GetBuffer(), 0);
    while ( nIndex != STRING_NOTFOUND )
    {
        aText.Replace( nIndex, aSearch.Len(), aReplace.GetBuffer());
        aUpperText.Replace( nIndex, aSearch.Len(), aReplace.GetBuffer());
        nIndex = aUpperText.Search( aSearch.GetBuffer(), nIndex + aReplace.Len());
    }

    fprintf( stdout, "%s\n", aText.GetBuffer());
    return 0;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.8); FILE MERGED 2005/10/13 13:24:21 sb 1.4.8.1: #i53898# Removed code for obsolete platforms.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: replace.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 13:22:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>
#include "string.hxx"

/****************************************************************************/
#if defined UNX
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/****************************************************************************/
{
    if ( argc < 4 )
    {
        fprintf( stderr, "ERROR: too few parameters. \n\n");
        fprintf( stderr, "usage: txtrep.exe EnvironmentVariable Searchstring replacestring\n");
        return 1;
    }
    ByteString aText( getenv( argv[ 1 ] ));
    if ( aText.Len() == 0 )
    {
        fprintf( stderr, "ERROR: Variable not set. \n\n");
        fprintf( stderr, "usage: txtrep.exe EnvironmentVariable Searchstring replacestring\n");
        return 2;
    }
    ByteString aSearch( argv[ 2 ] );
    ByteString aReplace( argv[ 3 ] );

    ByteString aUpperText( aText );
    aUpperText.ToUpperAscii();

    ULONG nIndex;
    aSearch.ToUpperAscii();

    nIndex = aUpperText.Search( aSearch.GetBuffer(), 0);
    while ( nIndex != STRING_NOTFOUND )
    {
        aText.Replace( nIndex, aSearch.Len(), aReplace.GetBuffer());
        aUpperText.Replace( nIndex, aSearch.Len(), aReplace.GetBuffer());
        nIndex = aUpperText.Search( aSearch.GetBuffer(), nIndex + aReplace.Len());
    }

    fprintf( stdout, "%s\n", aText.GetBuffer());
    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "phrase.h"
#include "translator.h"

#include <QApplication>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QRegExp>
#include <QTextCodec>
#include <QTextStream>
#include <QXmlAttributes>
#include <QXmlDefaultHandler>
#include <QXmlParseException>

QT_BEGIN_NAMESPACE

static QString protect(const QString & str)
{
    QString p = str;
    p.replace(QLatin1Char('&'),  QLatin1String("&"));
    p.replace(QLatin1Char('\"'), QLatin1String("""));
    p.replace(QLatin1Char('>'),  QLatin1String(">"));
    p.replace(QLatin1Char('<'),  QLatin1String("<"));
    p.replace(QLatin1Char('\''), QLatin1String("'"));
    return p;
}

Phrase::Phrase()
    : shrtc(-1), m_phraseBook(0)
{
}

Phrase::Phrase(const QString &source, const QString &target,
               const QString &definition, int sc)
    : shrtc(sc), s(source), t(target), d(definition),
      m_phraseBook(0)
{
}

Phrase::Phrase(const QString &source, const QString &target,
               const QString &definition, PhraseBook *phraseBook)
    : shrtc(-1), s(source), t(target), d(definition),
      m_phraseBook(phraseBook)
{
}

void Phrase::setSource(const QString &ns)
{
    if (s == ns)
        return;
    s = ns;
    if (m_phraseBook)
        m_phraseBook->phraseChanged(this);
}

void Phrase::setTarget(const QString &nt)
{
    if (t == nt)
        return;
    t = nt;
    if (m_phraseBook)
        m_phraseBook->phraseChanged(this);
}

void Phrase::setDefinition(const QString &nd)
{
    if (d == nd)
        return;
    d = nd;
    if (m_phraseBook)
        m_phraseBook->phraseChanged(this);
}

bool operator==(const Phrase &p, const Phrase &q)
{
    return p.source() == q.source() && p.target() == q.target() &&
        p.definition() == q.definition() && p.phraseBook() == q.phraseBook();
}

class QphHandler : public QXmlDefaultHandler
{
public:
    QphHandler(PhraseBook *phraseBook)
        : pb(phraseBook), ferrorCount(0) { }

    virtual bool startElement(const QString &namespaceURI,
        const QString &localName, const QString &qName,
        const QXmlAttributes &atts);
    virtual bool endElement(const QString &namespaceURI,
        const QString &localName, const QString &qName);
    virtual bool characters(const QString &ch);
    virtual bool fatalError(const QXmlParseException &exception);

    QString language() const { return m_language; }
    QString sourceLanguage() const { return m_sourceLanguage; }

private:
    PhraseBook *pb;
    QString source;
    QString target;
    QString definition;
    QString m_language;
    QString m_sourceLanguage;

    QString accum;
    int ferrorCount;
};

bool QphHandler::startElement(const QString & /* namespaceURI */,
                              const QString & /* localName */,
                              const QString &qName,
                              const QXmlAttributes &atts)
{
    if (qName == QString(QLatin1String("QPH"))) {
        m_language = atts.value(QLatin1String("language"));
        m_sourceLanguage = atts.value(QLatin1String("sourcelanguage"));
    } else if (qName == QString(QLatin1String("phrase"))) {
        source.truncate(0);
        target.truncate(0);
        definition.truncate(0);
    }
    accum.truncate(0);
    return true;
}

bool QphHandler::endElement(const QString & /* namespaceURI */,
                            const QString & /* localName */,
                            const QString &qName)
{
    if (qName == QString(QLatin1String("source")))
        source = accum;
    else if (qName == QString(QLatin1String("target")))
        target = accum;
    else if (qName == QString(QLatin1String("definition")))
        definition = accum;
    else if (qName == QString(QLatin1String("phrase")))
        pb->m_phrases.append(new Phrase(source, target, definition, pb));
    return true;
}

bool QphHandler::characters(const QString &ch)
{
    accum += ch;
    return true;
}

bool QphHandler::fatalError(const QXmlParseException &exception)
{
    if (ferrorCount++ == 0) {
        QString msg;
        msg.sprintf("Parse error at line %d, column %d (%s).",
            exception.lineNumber(), exception.columnNumber(),
            exception.message().toLatin1().constData());
        QMessageBox::information(0,
            QObject::tr("Qt Linguist"), msg);
    }
    return false;
}

PhraseBook::PhraseBook() :
    m_changed(false),
    m_language(QLocale::C),
    m_sourceLanguage(QLocale::C),
    m_country(QLocale::AnyCountry),
    m_sourceCountry(QLocale::AnyCountry)
{
}

PhraseBook::~PhraseBook()
{
    qDeleteAll(m_phrases);
}

void PhraseBook::setLanguageAndCountry(QLocale::Language lang, QLocale::Country country)
{
    if (m_language == lang && m_country == country)
        return;
    m_language = lang;
    m_country = country;
    setModified(true);
}

void PhraseBook::setSourceLanguageAndCountry(QLocale::Language lang, QLocale::Country country)
{
    if (m_sourceLanguage == lang && m_sourceCountry == country)
        return;
    m_sourceLanguage = lang;
    m_sourceCountry = country;
    setModified(true);
}

bool PhraseBook::load(const QString &fileName, bool *langGuessed)
{
    QFile f(fileName);
    if (!f.open(QIODevice::ReadOnly))
        return false;

    m_fileName = fileName;

    QXmlInputSource in(&f);
    QXmlSimpleReader reader;
    // don't click on these!
    reader.setFeature(QLatin1String("http://xml.org/sax/features/namespaces"), false);
    reader.setFeature(QLatin1String("http://xml.org/sax/features/namespace-prefixes"), true);
    reader.setFeature(QLatin1String("http://qtsoftware.com/xml/features/report-whitespace"
                                    "-only-CharData"), false);
    QphHandler *hand = new QphHandler(this);
    reader.setContentHandler(hand);
    reader.setErrorHandler(hand);

    bool ok = reader.parse(in);
    reader.setContentHandler(0);
    reader.setErrorHandler(0);

    Translator::languageAndCountry(hand->language(), &m_language, &m_country);
    *langGuessed = false;
    if (m_language == QLocale::C) {
        QLocale sys;
        m_language = sys.language();
        m_country = sys.country();
        *langGuessed = true;
    }

    QString lang = hand->sourceLanguage();
    if (lang.isEmpty()) {
        m_sourceLanguage = QLocale::C;
        m_sourceCountry = QLocale::AnyCountry;
    } else {
        Translator::languageAndCountry(lang, &m_sourceLanguage, &m_sourceCountry);
    }

    delete hand;
    f.close();
    if (!ok) {
        qDeleteAll(m_phrases);
        m_phrases.clear();
    } else {
        emit listChanged();
    }

    return ok;
}

bool PhraseBook::save(const QString &fileName)
{
    QFile f(fileName);
    if (!f.open(QIODevice::WriteOnly))
        return false;

    m_fileName = fileName;

    QTextStream t(&f);
    t.setCodec( QTextCodec::codecForName("UTF-8") );

    t << "<!DOCTYPE QPH>\n<QPH";
    if (sourceLanguage() != QLocale::C)
        t << " sourcelanguage=\""
          << Translator::makeLanguageCode(sourceLanguage(), sourceCountry()) << '"';
    if (language() != QLocale::C)
        t << " language=\"" << Translator::makeLanguageCode(language(), country()) << '"';
    t << ">\n";
    foreach (Phrase *p, m_phrases) {
        t << "<phrase>\n";
        t << "    <source>" << protect( p->source() ) << "</source>\n";
        t << "    <target>" << protect( p->target() ) << "</target>\n";
        if (!p->definition().isEmpty())
            t << "    <definition>" << protect( p->definition() )
              << "</definition>\n";
        t << "</phrase>\n";
    }
    t << "</QPH>\n";
    f.close();
    setModified(false);
    return true;
}

void PhraseBook::append(Phrase *phrase)
{
    m_phrases.append(phrase);
    phrase->setPhraseBook(this);
    setModified(true);
    emit listChanged();
}

void PhraseBook::remove(Phrase *phrase)
{
    m_phrases.removeOne(phrase);
    phrase->setPhraseBook(0);
    setModified(true);
    emit listChanged();
}

void PhraseBook::setModified(bool modified)
 {
     if (m_changed != modified) {
         emit modifiedChanged(modified);
         m_changed = modified;
     }
}

void PhraseBook::phraseChanged(Phrase *p)
{
    Q_UNUSED(p);

    setModified(true);
}

QString PhraseBook::friendlyPhraseBookName() const
{
    if (!m_fileName.isEmpty())
        return QFileInfo(m_fileName).fileName();
    return QString();
}

QT_END_NAMESPACE
<commit_msg>one more bogus trolltech => qtsoftware rename<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "phrase.h"
#include "translator.h"

#include <QApplication>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QRegExp>
#include <QTextCodec>
#include <QTextStream>
#include <QXmlAttributes>
#include <QXmlDefaultHandler>
#include <QXmlParseException>

QT_BEGIN_NAMESPACE

static QString protect(const QString & str)
{
    QString p = str;
    p.replace(QLatin1Char('&'),  QLatin1String("&"));
    p.replace(QLatin1Char('\"'), QLatin1String("""));
    p.replace(QLatin1Char('>'),  QLatin1String(">"));
    p.replace(QLatin1Char('<'),  QLatin1String("<"));
    p.replace(QLatin1Char('\''), QLatin1String("'"));
    return p;
}

Phrase::Phrase()
    : shrtc(-1), m_phraseBook(0)
{
}

Phrase::Phrase(const QString &source, const QString &target,
               const QString &definition, int sc)
    : shrtc(sc), s(source), t(target), d(definition),
      m_phraseBook(0)
{
}

Phrase::Phrase(const QString &source, const QString &target,
               const QString &definition, PhraseBook *phraseBook)
    : shrtc(-1), s(source), t(target), d(definition),
      m_phraseBook(phraseBook)
{
}

void Phrase::setSource(const QString &ns)
{
    if (s == ns)
        return;
    s = ns;
    if (m_phraseBook)
        m_phraseBook->phraseChanged(this);
}

void Phrase::setTarget(const QString &nt)
{
    if (t == nt)
        return;
    t = nt;
    if (m_phraseBook)
        m_phraseBook->phraseChanged(this);
}

void Phrase::setDefinition(const QString &nd)
{
    if (d == nd)
        return;
    d = nd;
    if (m_phraseBook)
        m_phraseBook->phraseChanged(this);
}

bool operator==(const Phrase &p, const Phrase &q)
{
    return p.source() == q.source() && p.target() == q.target() &&
        p.definition() == q.definition() && p.phraseBook() == q.phraseBook();
}

class QphHandler : public QXmlDefaultHandler
{
public:
    QphHandler(PhraseBook *phraseBook)
        : pb(phraseBook), ferrorCount(0) { }

    virtual bool startElement(const QString &namespaceURI,
        const QString &localName, const QString &qName,
        const QXmlAttributes &atts);
    virtual bool endElement(const QString &namespaceURI,
        const QString &localName, const QString &qName);
    virtual bool characters(const QString &ch);
    virtual bool fatalError(const QXmlParseException &exception);

    QString language() const { return m_language; }
    QString sourceLanguage() const { return m_sourceLanguage; }

private:
    PhraseBook *pb;
    QString source;
    QString target;
    QString definition;
    QString m_language;
    QString m_sourceLanguage;

    QString accum;
    int ferrorCount;
};

bool QphHandler::startElement(const QString & /* namespaceURI */,
                              const QString & /* localName */,
                              const QString &qName,
                              const QXmlAttributes &atts)
{
    if (qName == QString(QLatin1String("QPH"))) {
        m_language = atts.value(QLatin1String("language"));
        m_sourceLanguage = atts.value(QLatin1String("sourcelanguage"));
    } else if (qName == QString(QLatin1String("phrase"))) {
        source.truncate(0);
        target.truncate(0);
        definition.truncate(0);
    }
    accum.truncate(0);
    return true;
}

bool QphHandler::endElement(const QString & /* namespaceURI */,
                            const QString & /* localName */,
                            const QString &qName)
{
    if (qName == QString(QLatin1String("source")))
        source = accum;
    else if (qName == QString(QLatin1String("target")))
        target = accum;
    else if (qName == QString(QLatin1String("definition")))
        definition = accum;
    else if (qName == QString(QLatin1String("phrase")))
        pb->m_phrases.append(new Phrase(source, target, definition, pb));
    return true;
}

bool QphHandler::characters(const QString &ch)
{
    accum += ch;
    return true;
}

bool QphHandler::fatalError(const QXmlParseException &exception)
{
    if (ferrorCount++ == 0) {
        QString msg;
        msg.sprintf("Parse error at line %d, column %d (%s).",
            exception.lineNumber(), exception.columnNumber(),
            exception.message().toLatin1().constData());
        QMessageBox::information(0,
            QObject::tr("Qt Linguist"), msg);
    }
    return false;
}

PhraseBook::PhraseBook() :
    m_changed(false),
    m_language(QLocale::C),
    m_sourceLanguage(QLocale::C),
    m_country(QLocale::AnyCountry),
    m_sourceCountry(QLocale::AnyCountry)
{
}

PhraseBook::~PhraseBook()
{
    qDeleteAll(m_phrases);
}

void PhraseBook::setLanguageAndCountry(QLocale::Language lang, QLocale::Country country)
{
    if (m_language == lang && m_country == country)
        return;
    m_language = lang;
    m_country = country;
    setModified(true);
}

void PhraseBook::setSourceLanguageAndCountry(QLocale::Language lang, QLocale::Country country)
{
    if (m_sourceLanguage == lang && m_sourceCountry == country)
        return;
    m_sourceLanguage = lang;
    m_sourceCountry = country;
    setModified(true);
}

bool PhraseBook::load(const QString &fileName, bool *langGuessed)
{
    QFile f(fileName);
    if (!f.open(QIODevice::ReadOnly))
        return false;

    m_fileName = fileName;

    QXmlInputSource in(&f);
    QXmlSimpleReader reader;
    // don't click on these!
    reader.setFeature(QLatin1String("http://xml.org/sax/features/namespaces"), false);
    reader.setFeature(QLatin1String("http://xml.org/sax/features/namespace-prefixes"), true);
    reader.setFeature(QLatin1String("http://trolltech.com/xml/features/report-whitespace"
                                    "-only-CharData"), false);
    QphHandler *hand = new QphHandler(this);
    reader.setContentHandler(hand);
    reader.setErrorHandler(hand);

    bool ok = reader.parse(in);
    reader.setContentHandler(0);
    reader.setErrorHandler(0);

    Translator::languageAndCountry(hand->language(), &m_language, &m_country);
    *langGuessed = false;
    if (m_language == QLocale::C) {
        QLocale sys;
        m_language = sys.language();
        m_country = sys.country();
        *langGuessed = true;
    }

    QString lang = hand->sourceLanguage();
    if (lang.isEmpty()) {
        m_sourceLanguage = QLocale::C;
        m_sourceCountry = QLocale::AnyCountry;
    } else {
        Translator::languageAndCountry(lang, &m_sourceLanguage, &m_sourceCountry);
    }

    delete hand;
    f.close();
    if (!ok) {
        qDeleteAll(m_phrases);
        m_phrases.clear();
    } else {
        emit listChanged();
    }

    return ok;
}

bool PhraseBook::save(const QString &fileName)
{
    QFile f(fileName);
    if (!f.open(QIODevice::WriteOnly))
        return false;

    m_fileName = fileName;

    QTextStream t(&f);
    t.setCodec( QTextCodec::codecForName("UTF-8") );

    t << "<!DOCTYPE QPH>\n<QPH";
    if (sourceLanguage() != QLocale::C)
        t << " sourcelanguage=\""
          << Translator::makeLanguageCode(sourceLanguage(), sourceCountry()) << '"';
    if (language() != QLocale::C)
        t << " language=\"" << Translator::makeLanguageCode(language(), country()) << '"';
    t << ">\n";
    foreach (Phrase *p, m_phrases) {
        t << "<phrase>\n";
        t << "    <source>" << protect( p->source() ) << "</source>\n";
        t << "    <target>" << protect( p->target() ) << "</target>\n";
        if (!p->definition().isEmpty())
            t << "    <definition>" << protect( p->definition() )
              << "</definition>\n";
        t << "</phrase>\n";
    }
    t << "</QPH>\n";
    f.close();
    setModified(false);
    return true;
}

void PhraseBook::append(Phrase *phrase)
{
    m_phrases.append(phrase);
    phrase->setPhraseBook(this);
    setModified(true);
    emit listChanged();
}

void PhraseBook::remove(Phrase *phrase)
{
    m_phrases.removeOne(phrase);
    phrase->setPhraseBook(0);
    setModified(true);
    emit listChanged();
}

void PhraseBook::setModified(bool modified)
 {
     if (m_changed != modified) {
         emit modifiedChanged(modified);
         m_changed = modified;
     }
}

void PhraseBook::phraseChanged(Phrase *p)
{
    Q_UNUSED(p);

    setModified(true);
}

QString PhraseBook::friendlyPhraseBookName() const
{
    if (!m_fileName.isEmpty())
        return QFileInfo(m_fileName).fileName();
    return QString();
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/* Copyright (c) 2013, AOYAMA Kazuharu
 * All rights reserved.
 *
 * This software may be used and distributed according to the terms of
 * the New BSD License, which is incorporated herein by reference.
 */

#include "mongoobjgenerator.h"
#include "global.h"
#include "projectfilegenerator.h"
#include "filewriter.h"
#include <QPair>
#include <QRegExp>
#include <unistd.h>

#define MONGOOBJECT_HEADER_TEMPLATE                                     \
    "#ifndef %1OBJECT_H\n"                                              \
    "#define %1OBJECT_H\n"                                              \
    "\n"                                                                \
    "#include <TMongoObject>\n"                                         \
    "#include <QSharedData>\n"                                          \
    "\n\n"                                                              \
    "class T_MODEL_EXPORT %2Object : public TMongoObject, public QSharedData\n" \
    "{\n"                                                               \
    "public:\n"                                                         \
    "%3"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%4"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%5\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_HEADER_UPDATE_TEMPLATE                              \
    "%3\n"                                                              \
    "%4"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%5"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%2\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_PROPERTY_TEMPLATE                \
    "    Q_PROPERTY(%1 %2 READ get%2 WRITE set%2)\n" \
    "    T_DEFINE_PROPERTY(%1, %2)\n"

MongoObjGenerator::MongoObjGenerator(const QString &model)
    : modelName(model), fields()
{ }

QString MongoObjGenerator::mongoObjectFilePath(const QString &dstDir) const
{
    return QDir(dstDir + "/mongoobjects").filePath(modelName.toLower() + "object.h");
}

QString MongoObjGenerator::generate(const QString &dstDir)
{
    QString mobjpath = mongoObjectFilePath(dstDir);

    if (QFile(mobjpath).exists()) {
        updateMongoObject(mobjpath);
    } else {
        createMongoObject(mobjpath);
    }

    return QLatin1String("mongoobjects/") + QFileInfo(mobjpath).fileName();
}

static QStringList generateCode(const QList<QPair<QString, QVariant::Type> > &fieldList)
{
    QString params, enums, macros;

    for (QListIterator<QPair<QString, QVariant::Type> > it(fieldList); it.hasNext(); ) {
        const QPair<QString, QVariant::Type> &p = it.next();
        QString typeName = QVariant::typeToName(p.second);
        params += QString("    %1 %2;\n").arg(typeName, p.first);
        macros += QString(MONGOOBJECT_PROPERTY_TEMPLATE).arg(typeName, p.first);
        QString estr = fieldNameToEnumName(p.first);
        enums  += (enums.isEmpty()) ? QString("        %1 = 0,\n").arg(estr) : QString("        %1,\n").arg(estr);
    }

    return QStringList() << params << enums << macros;
}

bool MongoObjGenerator::createMongoObject(const QString &path)
{
    fields << qMakePair(QString("_id"), QVariant::String)
           << qMakePair(QString("createdAt"), QVariant::DateTime)
           << qMakePair(QString("updatedAt"), QVariant::DateTime)
           << qMakePair(QString("lockRevision"), QVariant::Int);

    QStringList code = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_TEMPLATE).arg(modelName.toUpper(), fieldNameToEnumName(modelName), code[0], code[1], modelName, code[2]);
    // Writes to a file
    return FileWriter(path).write(output, false);
}

static QList<QPair<QString, QVariant::Type> > getFieldList(const QString &filePath)
{
    QList<QPair<QString, QVariant::Type> > ret;
    QRegExp rxfst("\\s*QString\\s+_id\\s*;", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp rxend("(\\n[\\t\\r ]*\\n|\\senum\\s)", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp rx("\\s*([a-zA-Z0-9_<>]+)\\s+([a-zA-Z0-9_]+)\\s*;", Qt::CaseSensitive, QRegExp::RegExp2);

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("file open error: %s", qPrintable(filePath));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    int pos = rxfst.indexIn(src, 0);
    if (pos < 0) {
        qCritical("parse error");
        _exit(1);
    }

    int end = rxend.indexIn(src, pos);
    while ((pos = rx.indexIn(src, pos)) > 0 && pos < end) {
        QVariant::Type type = QVariant::nameToType(rx.cap(1).toLatin1().data());
        QString var = rx.cap(2);
        if (type != QVariant::Invalid && var.toLower() != "id")
            ret << QPair<QString, QVariant::Type>(var, type);
        pos += rx.matchedLength();
    }
    return ret;
}

bool MongoObjGenerator::updateMongoObject(const QString &path)
{
    QRegExp rxfst("\\s*QString\\s+_id\\s*;", Qt::CaseSensitive, QRegExp::RegExp2);
    QFile file(path);

    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("file open error: %s", qPrintable(path));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    QString headerpart;

    int pos = rxfst.indexIn(src, 0);
    if (pos > 0)
        headerpart = src.mid(0, pos);

    fields = getFieldList(path);
    QStringList prop = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_UPDATE_TEMPLATE).arg(modelName.toUpper(), modelName, headerpart, prop[0], prop[1], prop[2]);
    // Writes to a file
    return FileWriter(path).write(output, true);
}

int MongoObjGenerator::primaryKeyIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        if (fields[i].first == "_id")
            return i;
    }
    return -1;
}

int MongoObjGenerator::autoValueIndex() const
{
    return primaryKeyIndex();
}

int MongoObjGenerator::lockRevisionIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        QString var = fieldNameToVariableName(fields[i].first);
        if (var == "lockRevision")
            return i;
    }
    return -1;

}
<commit_msg>modified regular expressions in mongo genetator.<commit_after>/* Copyright (c) 2013, AOYAMA Kazuharu
 * All rights reserved.
 *
 * This software may be used and distributed according to the terms of
 * the New BSD License, which is incorporated herein by reference.
 */

#include "mongoobjgenerator.h"
#include "global.h"
#include "projectfilegenerator.h"
#include "filewriter.h"
#include <QPair>
#include <QRegExp>
#include <unistd.h>

#define MONGOOBJECT_HEADER_TEMPLATE                                     \
    "#ifndef %1OBJECT_H\n"                                              \
    "#define %1OBJECT_H\n"                                              \
    "\n"                                                                \
    "#include <TMongoObject>\n"                                         \
    "#include <QSharedData>\n"                                          \
    "\n\n"                                                              \
    "class T_MODEL_EXPORT %2Object : public TMongoObject, public QSharedData\n" \
    "{\n"                                                               \
    "public:\n"                                                         \
    "%3"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%4"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%5\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_HEADER_UPDATE_TEMPLATE                              \
    "%3\n"                                                              \
    "%4"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%5"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%2\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_PROPERTY_TEMPLATE                \
    "    Q_PROPERTY(%1 %2 READ get%2 WRITE set%2)\n" \
    "    T_DEFINE_PROPERTY(%1, %2)\n"

const QRegExp rxstart("\\{\\s*public\\s*:", Qt::CaseSensitive, QRegExp::RegExp2);

MongoObjGenerator::MongoObjGenerator(const QString &model)
    : modelName(model), fields()
{ }

QString MongoObjGenerator::mongoObjectFilePath(const QString &dstDir) const
{
    return QDir(dstDir + "/mongoobjects").filePath(modelName.toLower() + "object.h");
}

QString MongoObjGenerator::generate(const QString &dstDir)
{
    QString mobjpath = mongoObjectFilePath(dstDir);

    if (QFile(mobjpath).exists()) {
        updateMongoObject(mobjpath);
    } else {
        createMongoObject(mobjpath);
    }

    return QLatin1String("mongoobjects/") + QFileInfo(mobjpath).fileName();
}

static QStringList generateCode(const QList<QPair<QString, QVariant::Type> > &fieldList)
{
    QString params, enums, macros;

    for (QListIterator<QPair<QString, QVariant::Type> > it(fieldList); it.hasNext(); ) {
        const QPair<QString, QVariant::Type> &p = it.next();
        QString typeName = QVariant::typeToName(p.second);
        params += QString("    %1 %2;\n").arg(typeName, p.first);
        macros += QString(MONGOOBJECT_PROPERTY_TEMPLATE).arg(typeName, p.first);
        QString estr = fieldNameToEnumName(p.first);
        enums  += (enums.isEmpty()) ? QString("        %1 = 0,\n").arg(estr) : QString("        %1,\n").arg(estr);
    }

    return QStringList() << params << enums << macros;
}

bool MongoObjGenerator::createMongoObject(const QString &path)
{
    fields << qMakePair(QString("_id"), QVariant::String)
           << qMakePair(QString("createdAt"), QVariant::DateTime)
           << qMakePair(QString("updatedAt"), QVariant::DateTime)
           << qMakePair(QString("lockRevision"), QVariant::Int);

    QStringList code = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_TEMPLATE).arg(modelName.toUpper(), fieldNameToEnumName(modelName), code[0], code[1], modelName, code[2]);
    // Writes to a file
    return FileWriter(path).write(output, false);
}

static QList<QPair<QString, QVariant::Type> > getFieldList(const QString &filePath)
{
    QList<QPair<QString, QVariant::Type> > ret;
    QRegExp rxend("(\\n[\\t\\r ]*\\n|\\senum\\s)", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp rx("\\s([a-zA-Z0-9_<>]+)\\s+([a-zA-Z0-9_]+)\\s*;", Qt::CaseSensitive, QRegExp::RegExp2);

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("file open error: %s", qPrintable(filePath));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    int pos = rxstart.indexIn(src, 0);
    if (pos < 0) {
        qCritical("parse error");
        _exit(1);
    }
    pos += rxstart.matchedLength();

    int end = rxend.indexIn(src, pos);
    while ((pos = rx.indexIn(src, pos)) > 0 && pos < end) {
        QVariant::Type type = QVariant::nameToType(rx.cap(1).toLatin1().data());
        QString var = rx.cap(2);
        if (type != QVariant::Invalid && var.toLower() != "id")
            ret << QPair<QString, QVariant::Type>(var, type);
        pos += rx.matchedLength();
    }
    return ret;
}

bool MongoObjGenerator::updateMongoObject(const QString &path)
{
    QFile file(path);

    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("file open error: %s", qPrintable(path));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    QString headerpart;

    int pos = rxstart.indexIn(src, 0);
    if (pos > 0) {
        pos += rxstart.matchedLength();
        headerpart = src.mid(0, pos);
    }

    fields = getFieldList(path);
    QStringList prop = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_UPDATE_TEMPLATE).arg(modelName.toUpper(), modelName, headerpart, prop[0], prop[1], prop[2]);
    // Writes to a file
    return FileWriter(path).write(output, true);
}

int MongoObjGenerator::primaryKeyIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        if (fields[i].first == "_id")
            return i;
    }
    return -1;
}

int MongoObjGenerator::autoValueIndex() const
{
    return primaryKeyIndex();
}

int MongoObjGenerator::lockRevisionIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        QString var = fieldNameToVariableName(fields[i].first);
        if (var == "lockRevision")
            return i;
    }
    return -1;

}
<|endoftext|>