<commit_before>#include <iostream>
#include <cassert>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

#include "TFile.h"
#include "TTree.h"
#include "TChain.h"
#include "TBranch.h"
#include "TBasket.h"

void readandtest (const std::string & fname)
{
  TFile* inputFile = new TFile(fname.c_str(),"READ");

  std::cout << "Print file info: " << std::endl;
  inputFile->Print();
  std::cout << std::endl;

  std::cout << "List file TTree: " << std::endl;
  inputFile->ls();
  std::cout << std::endl;

  std::cout << "Print TkStubs info: " << std::endl;
  TTree* t1 = (TTree*) inputFile->Get("TkStubs");
  TChain* TT = (TChain*) inputFile->Get("TkStubs");
  t1->Print();
  std::cout << std::endl;

  std::vector<int> layerid, * p_layerid, moduleid, * p_moduleid,
    ladderid, * p_ladderid, tp, * p_tp;
  p_layerid = &layerid;
  p_ladderid = &ladderid;
  p_moduleid = &moduleid;
  p_tp = &tp;

  TT->SetBranchAddress("L1TkSTUB_layer", &p_layerid);
  TT->SetBranchAddress("L1TkSTUB_ladder", &p_ladderid);
  TT->SetBranchAddress("L1TkSTUB_module", &p_moduleid);
  TT->SetBranchAddress("L1TkSTUB_tp", &p_tp);

  std::vector<float> stubx, * p_stubx, stuby, * p_stuby, stubz, * p_stubz,
    px, * p_px, py, * p_py, x0, * p_x0, y0, * p_y0, z0, * p_z0, eta, * p_eta,
    phi, * p_phi;
  p_stubx = &stubx;
  p_stuby = &stuby;
  p_stubz = &stubz;
  p_px = &px;
  p_py = &py;
  p_x0 = &x0;
  p_y0 = &y0;
  p_z0 = &z0;
  p_eta = η
  p_phi = φ

  TT->SetBranchAddress("L1TkSTUB_x", &p_stubx);
  TT->SetBranchAddress("L1TkSTUB_y", &p_stuby);
  TT->SetBranchAddress("L1TkSTUB_z", &p_stubz);

  TT->SetBranchAddress("L1TkSTUB_pxGEN", &p_px);
  TT->SetBranchAddress("L1TkSTUB_pyGEN", &p_py);
  TT->SetBranchAddress("L1TkSTUB_X0", &p_x0);
  TT->SetBranchAddress("L1TkSTUB_Y0", &p_y0);
  TT->SetBranchAddress("L1TkSTUB_Z0", &p_z0);
  TT->SetBranchAddress("L1TkSTUB_etaGEN", &p_eta);
  TT->SetBranchAddress("L1TkSTUB_PHI0", &p_phi);

  unsigned int countevt = 0;
  Int_t nevent = t1->GetEntries();
  std::cout << "We got " << nevent << " events " << std::endl;
  std::ofstream ptfile("pt.txt");
  std::ofstream phifile("phi.txt");
  std::ofstream d0file("d0.txt");
  std::ofstream etafile("eta.txt");
  std::ofstream z0file("z0.txt");
  for (Int_t i=0; i<nevent; ++i)
  {
     //L1TkSTUB_tp tutti gli stub appartenti alla stessa traccia hanno stesso tp
     //  posso avere eventi con molte tracce devo solezionarle usando tp
     //
     //StubExtractor e' utile punto di partenza visto che contiene il codice
     //   che scrive il Tree L1Tk

     t1->GetEvent(i);
     assert (layerid.size() == ladderid.size());
     assert (layerid.size() == moduleid.size());
     assert (layerid.size() == tp.size());

     assert (layerid.size() == stubx.size());
     assert (layerid.size() == stuby.size());
     assert (layerid.size() == stubz.size());
     assert (layerid.size() == px.size());
     assert (layerid.size() == py.size());
     assert (layerid.size() == x0.size());
     assert (layerid.size() == y0.size());
     assert (layerid.size() == z0.size());
     assert (layerid.size() == eta.size());
     assert (layerid.size() == phi.size());

     /*
      *
      * pT = sqrt(pxGEN^2 + pyGEN^2)
      * Phi = PHI0
      * d0 = sqrt(X0^2 + Y0^2)
      * Eta = etaGEN
      * z0 = Z0
      *
      */

     if (layerid.size() == 6)
     {
       std::cout << "Event: " << i+1 << " size " << tp.size() << std::endl;

       for (int j=0; j<(int)layerid.size(); ++j)
       {
         std::cout << stubx[j] << " " << stuby[j] << " " <<
           stubz[j] << " ";
         std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
           phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
           << eta[j] << " " << z0[j] << " ";
         std::cout << layerid[j] << " " << ladderid[j] << " " <<
           moduleid[j] << " "  << tp[j] << std::endl;

         ptfile << i << " " << sqrt(pow(px[j],2.0) + pow(py[j],2.0))
           << std::endl;
         phifile << i << " " << phi[j] << std::endl;
         d0file << i << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0))
           << std::endl;
         etafile << i << " " << eta[j] << std::endl;
         z0file << i << " " << z0[j] << std::endl;
       }

       countevt++;

     }

     //t1->Show(i);
  }
  ptfile.close();
  phifile.close();
  d0file.close();
  etafile.close();
  z0file.close();

  std::cout << "Event with 6 layer " << countevt << std::endl;

  inputFile->Close();
}

# ifndef __CINT__
int main(int argc, char ** argv)
{
  if (argc != 2)
  {
    std::cerr << "usage: " << argv[0] << " rootfilename " << std::endl;
    return 1;
  }

  readandtest(argv[1]);

  return 0;
}
# endif
<commit_msg>rootfile out can be now used by generatepca (need to check xyz values of rootfiles)<commit_after>#include <iostream>
#include <cassert>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

#include "TFile.h"
#include "TTree.h"
#include "TChain.h"
#include "TBranch.h"
#include "TBasket.h"

void readandtest (const std::string & fname)
{
  TFile* inputFile = new TFile(fname.c_str(),"READ");

#if 0
  std::cout << "Print file info: " << std::endl;
  inputFile->Print();
  std::cout << std::endl;

  std::cout << "List file TTree: " << std::endl;
  inputFile->ls();
  std::cout << std::endl;

  std::cout << "Print TkStubs info: " << std::endl;
#endif
  TTree* t1 = (TTree*) inputFile->Get("TkStubs");
  TChain* TT = (TChain*) inputFile->Get("TkStubs");
#if 0
  t1->Print();
  std::cout << std::endl;
#endif

  std::vector<int> layerid, * p_layerid, moduleid, * p_moduleid,
    ladderid, * p_ladderid, tp, * p_tp;
  p_layerid = &layerid;
  p_ladderid = &ladderid;
  p_moduleid = &moduleid;
  p_tp = &tp;

  TT->SetBranchAddress("L1TkSTUB_layer", &p_layerid);
  TT->SetBranchAddress("L1TkSTUB_ladder", &p_ladderid);
  TT->SetBranchAddress("L1TkSTUB_module", &p_moduleid);
  TT->SetBranchAddress("L1TkSTUB_tp", &p_tp);

  std::vector<float> stubx, * p_stubx, stuby, * p_stuby, stubz, * p_stubz,
    px, * p_px, py, * p_py, x0, * p_x0, y0, * p_y0, z0, * p_z0, eta, * p_eta,
    phi, * p_phi;
  p_stubx = &stubx;
  p_stuby = &stuby;
  p_stubz = &stubz;
  p_px = &px;
  p_py = &py;
  p_x0 = &x0;
  p_y0 = &y0;
  p_z0 = &z0;
  p_eta = η
  p_phi = φ

  TT->SetBranchAddress("L1TkSTUB_x", &p_stubx);
  TT->SetBranchAddress("L1TkSTUB_y", &p_stuby);
  TT->SetBranchAddress("L1TkSTUB_z", &p_stubz);

  TT->SetBranchAddress("L1TkSTUB_pxGEN", &p_px);
  TT->SetBranchAddress("L1TkSTUB_pyGEN", &p_py);
  TT->SetBranchAddress("L1TkSTUB_X0", &p_x0);
  TT->SetBranchAddress("L1TkSTUB_Y0", &p_y0);
  TT->SetBranchAddress("L1TkSTUB_Z0", &p_z0);
  TT->SetBranchAddress("L1TkSTUB_etaGEN", &p_eta);
  TT->SetBranchAddress("L1TkSTUB_PHI0", &p_phi);

  unsigned int countevt = 0;
  Int_t nevent = t1->GetEntries();
  std::cout << "We got " << nevent << " events " << std::endl;
  std::ofstream ptfile("pt.txt");
  std::ofstream phifile("phi.txt");
  std::ofstream d0file("d0.txt");
  std::ofstream etafile("eta.txt");
  std::ofstream z0file("z0.txt");
  for (Int_t i=0; i<nevent; ++i)
  {
     //L1TkSTUB_tp tutti gli stub appartenti alla stessa traccia hanno stesso tp
     //  posso avere eventi con molte tracce devo solezionarle usando tp
     //
     //StubExtractor e' utile punto di partenza visto che contiene il codice
     //   che scrive il Tree L1Tk

     t1->GetEvent(i);
     assert (layerid.size() == ladderid.size());
     assert (layerid.size() == moduleid.size());
     assert (layerid.size() == tp.size());

     assert (layerid.size() == stubx.size());
     assert (layerid.size() == stuby.size());
     assert (layerid.size() == stubz.size());
     assert (layerid.size() == px.size());
     assert (layerid.size() == py.size());
     assert (layerid.size() == x0.size());
     assert (layerid.size() == y0.size());
     assert (layerid.size() == z0.size());
     assert (layerid.size() == eta.size());
     assert (layerid.size() == phi.size());

     /*
      *
      * pT = sqrt(pxGEN^2 + pyGEN^2)
      * Phi = PHI0
      * d0 = sqrt(X0^2 + Y0^2)
      * Eta = etaGEN
      * z0 = Z0
      *
      */

     if (layerid.size() == 6)
     {
       std::cout << i+1 << " " << tp.size() << std::endl;

       int j = 0;
       for (; j<(int)layerid.size(); ++j)
       {
         std::cout << stubx[j] << " " << stuby[j] << " " <<
           stubz[j] << " ";

#if 0
         std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
           phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
           << eta[j] << " " << z0[j] << " ";
#endif

         std::cout << layerid[j] << " " << ladderid[j] << " " <<
           moduleid[j] << " "
#if 0
         << tp[j] << std::endl;
#else
         << std::endl;
#endif

         ptfile << i << " " << sqrt(pow(px[j],2.0) + pow(py[j],2.0))
           << std::endl;
         phifile << i << " " << phi[j] << std::endl;
         d0file << i << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0))
           << std::endl;
         etafile << i << " " << eta[j] << std::endl;
         z0file << i << " " << z0[j] << std::endl;

       }
       --j;
       std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
         phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
         << eta[j] << " " << z0[j] << std::endl;

       countevt++;

     }

     //t1->Show(i);
  }
  ptfile.close();
  phifile.close();
  d0file.close();
  etafile.close();
  z0file.close();

  std::cout << "Event with 6 layer " << countevt << std::endl;

  inputFile->Close();
}

# ifndef __CINT__
int main(int argc, char ** argv)
{
  if (argc != 2)
  {
    std::cerr << "usage: " << argv[0] << " rootfilename " << std::endl;
    return 1;
  }

  readandtest(argv[1]);

  return 0;
}
# endif
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <os>
#include <timers>

extern "C" uint32_t os_get_blocking_level();
extern "C" uint32_t os_get_highest_blocking_level();

void sleep(int i){
  static Timers::id_t timer{};

  if (not timer)
    timer = Timers::oneshot(std::chrono::seconds(i), [](auto){
        INFO("Timer", "Ticked");
        timer = 0;
        Expects(os_get_blocking_level() == 1);
      });

  while (timer) {
    OS::block();
    Expects(os_get_blocking_level() == 0);
  }

  INFO("Test", " Done");
}

void Service::start(const std::string&)
{
  INFO("Block", "Testing blocking calls.");

  static int sleeps = 0;

  Timers::oneshot(std::chrono::seconds(5), [](auto){
      INFO("Test","About half way done (%i / 10)", sleeps);
      Expects(sleeps < 10);
    });

  Timers::oneshot(std::chrono::seconds(15), [](auto){
      Expects(sleeps >= 10);
      INFO("Test","SUCCESS");
    });

  int n = 10;
  for (int i = 0; i < n; i++) {
    sleep(1);
    sleeps++;
    printf("Sleep %i/%i \n", sleeps, n);
  }

  Expects(os_get_blocking_level() == 0);
  Expects(os_get_highest_blocking_level() == 1);
}
<commit_msg>test: Wait until timers are ready in blocking test<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <os>
#include <timers>

extern "C" uint32_t os_get_blocking_level();
extern "C" uint32_t os_get_highest_blocking_level();

void sleep(int i){
  static Timers::id_t timer{};

  if (not timer)
    timer = Timers::oneshot(std::chrono::seconds(i), [](auto){
        INFO("Timer", "Ticked");
        timer = 0;
        Expects(os_get_blocking_level() == 1);
      });

  while (timer) {
    OS::block();
    Expects(os_get_blocking_level() == 0);
  }

  INFO("Test", " Done");
}

void Service::start()
{
  INFO("Block", "Testing blocking calls.");
}

void Service::ready()
{
  static int sleeps = 0;

  Timers::oneshot(std::chrono::seconds(5), [](auto){
      INFO("Test","About half way done (%i / 10)", sleeps);
      Expects(sleeps < 10);
    });

  Timers::oneshot(std::chrono::seconds(20), [](auto){
      Expects(sleeps >= 10);
    });

  int n = 10;
  for (int i = 0; i < n; i++) {
    sleep(1);
    sleeps++;
    printf("Sleep %i/%i \n", sleeps, n);
    if (sleeps == 10)
    INFO("Test", "SUCCESS");
  }

  Expects(os_get_blocking_level() == 0);
  Expects(os_get_highest_blocking_level() == 1);
}
<|endoftext|>


<commit_before>#include <random>
#include <speck/speck.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// https://eprint.iacr.org/2013/404.pdf
//
// Speck128/128
//  Key:        0f0e0d0c0b0a0908 0706050403020100
//  Plaintext:  6c61766975716520 7469206564616d20
//  Ciphertext: a65d985179783265 7860fedf5c570d18
static const uint64_t s_key[2] = {0x0706050403020100, 0x0f0e0d0c0b0a0908};
static const uint64_t s_plain_text[2] = {0x7469206564616d20, 0x6c61766975716520};
static const uint64_t s_cipher_text[2] = {0x7860fedf5c570d18, 0xa65d985179783265};
static const uint8_t s_key_stream[16] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
static const uint8_t s_plain_text_stream[16] = {
    0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x69, 0x74, 0x20, 0x65, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c,
};
static const uint8_t s_cipher_text_stream[16] = {
    0x18, 0x0d, 0x57, 0x5c, 0xdf, 0xfe, 0x60, 0x78, 0x65, 0x32, 0x78, 0x79, 0x51, 0x98, 0x5d, 0xa6,
};

#define BLOCK_SIZE 16

void generate_random_array(uint8_t *iv, size_t iv_len) {
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dis;

    for(int i=0; i<iv_len; i++) {
        iv[i] = static_cast<uint8_t>(dis(gen));
    }
}

void show_array(const char *explain, const uint8_t *array, size_t len) {
    printf("%20s ", explain);
    for(int i=len-1; i >= 0; i--) {
        printf("%02x ", array[i]);
    }
    printf("\n");
}

int encrypt_decrypt_stream_test(int block_num) {
    int r = 0;
    speck_ctx_t *ctx = NULL;
    uint8_t *plain_text_stream = NULL;
    uint8_t *crypted_text_stream = NULL;
    uint8_t *decrypted_text_stream = NULL;
    uint8_t *iv_text_stream = NULL;
    uint8_t *origin_iv_text_stream = NULL;

    plain_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!plain_text_stream) {
        r = 1;
        goto finish;
    }
    crypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!crypted_text_stream) {
        r = 1;
        goto finish;
    }
    decrypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!decrypted_text_stream) {
        r = 1;
        goto finish;
    }
    iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!iv_text_stream) {
        r = 1;
        goto finish;
    }
    origin_iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!origin_iv_text_stream) {
        r = 1;
        goto finish;
    }

    for (int i = 0; i < block_num; i++) {
        memcpy(plain_text_stream + (i * BLOCK_SIZE), s_plain_text_stream, sizeof(s_plain_text_stream));
    }
    generate_random_array(origin_iv_text_stream, BLOCK_SIZE);

    ctx = speck_init(SPECK_ENCRYPT_TYPE_128_128, s_key_stream, sizeof(s_key_stream));
    if (!ctx) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_encrypt(ctx, plain_text_stream, crypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_decrypt(ctx, crypted_text_stream, decrypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    for (int i = 0; i < BLOCK_SIZE * block_num; i++) {
        if (plain_text_stream[i] != decrypted_text_stream[i]) {
            printf("block_num:%d idx:%d  0x%02x != 0x%02x\n", block_num, i, plain_text_stream[i], decrypted_text_stream[i]);
            show_array("iv", origin_iv_text_stream, BLOCK_SIZE);
            show_array("plain", plain_text_stream, block_num * BLOCK_SIZE);
            show_array("decrypted", decrypted_text_stream, block_num * BLOCK_SIZE);
            show_array("counted iv", iv_text_stream, BLOCK_SIZE);
            printf("\n");

            r = 1;
            goto finish;
        }
    }

    finish:
    free(plain_text_stream);
    free(crypted_text_stream);
    free(origin_iv_text_stream);
    free(iv_text_stream);

    speck_finish(&ctx);
    return r;
}

int encrypt_decrypt_random_stream_test(int block_num) {
    int r = 0;
    speck_ctx_t *ctx = NULL;
    uint8_t *key_text_stream = NULL;
    uint8_t *plain_text_stream = NULL;
    uint8_t *crypted_text_stream = NULL;
    uint8_t *decrypted_text_stream = NULL;
    uint8_t *iv_text_stream = NULL;
    uint8_t *origin_iv_text_stream = NULL;

    key_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if(!key_text_stream) {
        r = 1;
        goto finish;
    }
    plain_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!plain_text_stream) {
        r = 1;
        goto finish;
    }
    crypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!crypted_text_stream) {
        r = 1;
        goto finish;
    }
    decrypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!decrypted_text_stream) {
        r = 1;
        goto finish;
    }
    iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!iv_text_stream) {
        r = 1;
        goto finish;
    }
    origin_iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!origin_iv_text_stream) {
        r = 1;
        goto finish;
    }

    generate_random_array(key_text_stream, BLOCK_SIZE);
    generate_random_array(plain_text_stream, BLOCK_SIZE * block_num);
    generate_random_array(origin_iv_text_stream, BLOCK_SIZE);

    ctx = speck_init(SPECK_ENCRYPT_TYPE_128_128, key_text_stream, BLOCK_SIZE);
    if (!ctx) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_encrypt(ctx, plain_text_stream, crypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_decrypt(ctx, crypted_text_stream, decrypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    for (int i = 0; i < BLOCK_SIZE * block_num; i++) {
        if (plain_text_stream[i] != decrypted_text_stream[i]) {
            printf("block_num:%d idx:%d  0x%02x != 0x%02x\n", block_num, i, plain_text_stream[i], decrypted_text_stream[i]);
            show_array("iv", origin_iv_text_stream, BLOCK_SIZE);
            show_array("plain", plain_text_stream, block_num * BLOCK_SIZE);
            show_array("decrypted", decrypted_text_stream, block_num * BLOCK_SIZE);
            show_array("counted iv", iv_text_stream, BLOCK_SIZE);
            printf("\n");

            r = 1;
            goto finish;
        }
    }

    finish:
    free(key_text_stream);
    free(plain_text_stream);
    free(crypted_text_stream);
    free(origin_iv_text_stream);
    free(iv_text_stream);

    speck_finish(&ctx);
    return r;
}

int main() {
    printf("test encrypt_decrypt_stream_test\n");
    for (int i = 0; i <(4*1024)/BLOCK_SIZE; i++) {
        int r = encrypt_decrypt_stream_test(i+1);
        if(r != 0) {
            return r;
        }
    }
    printf("success encrypt_decrypt_stream_test\n");

    printf("test encrypt_decrypt_random_stream_test\n");
    for (int i = 0; i <(4*1024)/BLOCK_SIZE; i++) {
        int r = encrypt_decrypt_random_stream_test(i+1);
        if(r != 0) {
            return r;
        }
    }
    printf("success encrypt_decrypt_random_stream_test\n");

    return 0;
}
<commit_msg>fix memory leak<commit_after>#include <random>
#include <speck/speck.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// https://eprint.iacr.org/2013/404.pdf
//
// Speck128/128
//  Key:        0f0e0d0c0b0a0908 0706050403020100
//  Plaintext:  6c61766975716520 7469206564616d20
//  Ciphertext: a65d985179783265 7860fedf5c570d18
static const uint64_t s_key[2] = {0x0706050403020100, 0x0f0e0d0c0b0a0908};
static const uint64_t s_plain_text[2] = {0x7469206564616d20, 0x6c61766975716520};
static const uint64_t s_cipher_text[2] = {0x7860fedf5c570d18, 0xa65d985179783265};
static const uint8_t s_key_stream[16] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
static const uint8_t s_plain_text_stream[16] = {
    0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x69, 0x74, 0x20, 0x65, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c,
};
static const uint8_t s_cipher_text_stream[16] = {
    0x18, 0x0d, 0x57, 0x5c, 0xdf, 0xfe, 0x60, 0x78, 0x65, 0x32, 0x78, 0x79, 0x51, 0x98, 0x5d, 0xa6,
};

#define BLOCK_SIZE 16

void generate_random_array(uint8_t *iv, size_t iv_len) {
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dis;

    for(int i=0; i<iv_len; i++) {
        iv[i] = static_cast<uint8_t>(dis(gen));
    }
}

void show_array(const char *explain, const uint8_t *array, size_t len) {
    printf("%20s ", explain);
    for(int i=len-1; i >= 0; i--) {
        printf("%02x ", array[i]);
    }
    printf("\n");
}

int encrypt_decrypt_stream_test(int block_num) {
    int r = 0;
    speck_ctx_t *ctx = NULL;
    uint8_t *plain_text_stream = NULL;
    uint8_t *crypted_text_stream = NULL;
    uint8_t *decrypted_text_stream = NULL;
    uint8_t *iv_text_stream = NULL;
    uint8_t *origin_iv_text_stream = NULL;

    plain_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!plain_text_stream) {
        r = 1;
        goto finish;
    }
    crypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!crypted_text_stream) {
        r = 1;
        goto finish;
    }
    decrypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!decrypted_text_stream) {
        r = 1;
        goto finish;
    }
    iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!iv_text_stream) {
        r = 1;
        goto finish;
    }
    origin_iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!origin_iv_text_stream) {
        r = 1;
        goto finish;
    }

    for (int i = 0; i < block_num; i++) {
        memcpy(plain_text_stream + (i * BLOCK_SIZE), s_plain_text_stream, sizeof(s_plain_text_stream));
    }
    generate_random_array(origin_iv_text_stream, BLOCK_SIZE);

    ctx = speck_init(SPECK_ENCRYPT_TYPE_128_128, s_key_stream, sizeof(s_key_stream));
    if (!ctx) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_encrypt(ctx, plain_text_stream, crypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_decrypt(ctx, crypted_text_stream, decrypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    for (int i = 0; i < BLOCK_SIZE * block_num; i++) {
        if (plain_text_stream[i] != decrypted_text_stream[i]) {
            printf("block_num:%d idx:%d  0x%02x != 0x%02x\n", block_num, i, plain_text_stream[i], decrypted_text_stream[i]);
            show_array("iv", origin_iv_text_stream, BLOCK_SIZE);
            show_array("plain", plain_text_stream, block_num * BLOCK_SIZE);
            show_array("decrypted", decrypted_text_stream, block_num * BLOCK_SIZE);
            show_array("counted iv", iv_text_stream, BLOCK_SIZE);
            printf("\n");

            r = 1;
            goto finish;
        }
    }

    finish:
    free(plain_text_stream);
    free(crypted_text_stream);
    free(decrypted_text_stream);
    free(iv_text_stream);
    free(origin_iv_text_stream);

    speck_finish(&ctx);
    return r;
}

int encrypt_decrypt_random_stream_test(int block_num) {
    int r = 0;
    speck_ctx_t *ctx = NULL;
    uint8_t *key_text_stream = NULL;
    uint8_t *plain_text_stream = NULL;
    uint8_t *crypted_text_stream = NULL;
    uint8_t *decrypted_text_stream = NULL;
    uint8_t *iv_text_stream = NULL;
    uint8_t *origin_iv_text_stream = NULL;

    key_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if(!key_text_stream) {
        r = 1;
        goto finish;
    }
    plain_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!plain_text_stream) {
        r = 1;
        goto finish;
    }
    crypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!crypted_text_stream) {
        r = 1;
        goto finish;
    }
    decrypted_text_stream = (uint8_t*)malloc(BLOCK_SIZE * block_num);
    if (!decrypted_text_stream) {
        r = 1;
        goto finish;
    }
    iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!iv_text_stream) {
        r = 1;
        goto finish;
    }
    origin_iv_text_stream = (uint8_t*)malloc(BLOCK_SIZE);
    if (!origin_iv_text_stream) {
        r = 1;
        goto finish;
    }

    generate_random_array(key_text_stream, BLOCK_SIZE);
    generate_random_array(plain_text_stream, BLOCK_SIZE * block_num);
    generate_random_array(origin_iv_text_stream, BLOCK_SIZE);

    ctx = speck_init(SPECK_ENCRYPT_TYPE_128_128, key_text_stream, BLOCK_SIZE);
    if (!ctx) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_encrypt(ctx, plain_text_stream, crypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    memcpy(iv_text_stream, origin_iv_text_stream, BLOCK_SIZE);
    r = speck_ctr_decrypt(ctx, crypted_text_stream, decrypted_text_stream, BLOCK_SIZE * block_num, iv_text_stream, BLOCK_SIZE);
    if (r < 0) {
        r = 1;
        goto finish;
    }
    for (int i = 0; i < BLOCK_SIZE * block_num; i++) {
        if (plain_text_stream[i] != decrypted_text_stream[i]) {
            printf("block_num:%d idx:%d  0x%02x != 0x%02x\n", block_num, i, plain_text_stream[i], decrypted_text_stream[i]);
            show_array("iv", origin_iv_text_stream, BLOCK_SIZE);
            show_array("plain", plain_text_stream, block_num * BLOCK_SIZE);
            show_array("decrypted", decrypted_text_stream, block_num * BLOCK_SIZE);
            show_array("counted iv", iv_text_stream, BLOCK_SIZE);
            printf("\n");

            r = 1;
            goto finish;
        }
    }

    finish:
    free(key_text_stream);
    free(plain_text_stream);
    free(crypted_text_stream);
    free(decrypted_text_stream);
    free(iv_text_stream);
    free(origin_iv_text_stream);

    speck_finish(&ctx);
    return r;
}

int main() {
    printf("test encrypt_decrypt_stream_test\n");
    for (int i = 0; i <(4*1024)/BLOCK_SIZE; i++) {
        int r = encrypt_decrypt_stream_test(i+1);
        if(r != 0) {
            return r;
        }
    }
    printf("success encrypt_decrypt_stream_test\n");

    printf("test encrypt_decrypt_random_stream_test\n");
    for (int i = 0; i <(4*1024)/BLOCK_SIZE; i++) {
        int r = encrypt_decrypt_random_stream_test(i+1);
        if(r != 0) {
            return r;
        }
    }
    printf("success encrypt_decrypt_random_stream_test\n");

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016, Australian Centre for Robotic Vision, ACRV
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Osnabrück University nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *  Created on: 11.07.2016
 *
 *      Authors:
 *         Trung T. Pham <trung.pham@adelaide.edu.au>
 *         Markus Eich <markus.eich@qut.edu.au>
 *
 *
 */

#include <iostream>

#include <segmentation/segmentation.hpp>

using namespace std;

using namespace APC;

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

    Segmentation seg;
    Config config;

    ///  Parse Arguments needed for computation
    pcl::console::parse (argc, argv, "-v", config.voxel_resolution);
    pcl::console::parse (argc, argv, "-s", config.seed_resolution);
    pcl::console::parse (argc, argv, "-c", config.color_importance);
    pcl::console::parse (argc, argv, "-z", config.spatial_importance);
    pcl::console::parse (argc, argv, "-n", config.normal_importance);

    pcl::console::parse (argc, argv, "-lc", config.label_cost);
    pcl::console::parse (argc, argv, "-sc", config.smooth_cost);
    pcl::console::parse (argc, argv, "-oc", config.outlier_cost);

    seg.setConfig(config);

    /// -----------------------------------|  Preparations  |-----------------------------------

    if (argc<2){
        PCL_ERROR ("ERROR: wrong number or arguments provided.\n");
        exit (-1);
    }

    PCL_INFO ("Loading pointcloud\n");
    pcl::PointCloud<PointT>::Ptr input_cloud_ptr (new pcl::PointCloud<PointT>);

    /// Get pcd path from command line
    std::string pcd_filename = argv[1];
    if (pcl::io::loadPCDFile (pcd_filename, *input_cloud_ptr))
    {
        PCL_ERROR ("ERROR: Could not read input point cloud %s.\n", pcd_filename.c_str ());
        return (3);
    }

    std::vector< int > index;
    if (!input_cloud_ptr->is_dense){
        PCL_WARN("Point data not dense, eating NaNs\n");
        pcl::removeNaNFromPointCloud<PointT>(*input_cloud_ptr,*input_cloud_ptr,index);
        PCL_INFO ("Done making cloud\n");
    }
    std::cerr << "Number of points: " << input_cloud_ptr->size() << std::endl;

    seg.setPointCloud(input_cloud_ptr);

    seg.doSegmentation();

        pcl::PointCloud<pcl::PointXYZL>::Ptr segmented_cloud_ptr;

        segmented_cloud_ptr=seg.getSegmentedPointCloud();

        bool output_specified = pcl::console::find_switch (argc, argv, "-o");
        if (output_specified)
        {
            // Check output already exists. Create outputname if not given
            std::string outputname ("");
            pcl::console::parse (argc, argv, "-o", outputname);
            // If no filename is given, get output filename from inputname (strip seperators and file extension)
            if (outputname.empty () || (outputname.at (0) == '-'))
            {
                outputname = pcd_filename;
                size_t dot = outputname.find_last_of ('.');
                if (dot != std::string::npos)
                    outputname = outputname.substr (0, dot);
            }

            outputname+="_seg.pcd";
            PCL_INFO ("Saving output\n");
            bool save_binary_pcd = false;
            pcl::io::savePCDFile (outputname, *segmented_cloud_ptr, save_binary_pcd);
        }

        /// -----------------------------------|  Visualization  |-----------------------------------
        bool show_visualization = (not pcl::console::find_switch (argc, argv, "-novis"));
        if (show_visualization)
        {
            /// Configure Visualizer
            pcl::visualization::PCLVisualizer::Ptr viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
            viewer->setBackgroundColor (0, 0, 0);
            viewer->addPointCloud (segmented_cloud_ptr, "Segmented point cloud");

            PCL_INFO ("Loading viewer\n");
            while (!viewer->wasStopped ())
            {
                viewer->spinOnce (100);
                viewer->updatePointCloud (segmented_cloud_ptr, "Segmented point cloud");
                boost::this_thread::sleep (boost::posix_time::microseconds (100000));
            }
        }
    return 0;
}
<commit_msg>added help option and parameter description for the test file.<commit_after>/*
 * Copyright (C) 2016, Australian Centre for Robotic Vision, ACRV
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Osnabrück University nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *  Created on: 11.07.2016
 *
 *      Authors:
 *         Trung T. Pham <trung.pham@adelaide.edu.au>
 *         Markus Eich <markus.eich@qut.edu.au>
 *
 *
 */

#include <iostream>

#include <segmentation/segmentation.hpp>

using namespace std;

using namespace APC;

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

    Segmentation seg;
    Config config;

    ///  Parse Arguments needed for computation
    pcl::console::parse (argc, argv, "-v", config.voxel_resolution);
    pcl::console::parse (argc, argv, "-s", config.seed_resolution);
    pcl::console::parse (argc, argv, "-c", config.color_importance);
    pcl::console::parse (argc, argv, "-z", config.spatial_importance);
    pcl::console::parse (argc, argv, "-n", config.normal_importance);

    pcl::console::parse (argc, argv, "-lc", config.label_cost);
    pcl::console::parse (argc, argv, "-sc", config.smooth_cost);
    pcl::console::parse (argc, argv, "-oc", config.outlier_cost);

    if (pcl::console::find_switch (argc, argv, "-h")){
      PCL_INFO ("Options: \n \t -v : voxel resolution\n \t -s : seed resolution\n \t -c : color importance\n \t -z : spatial importance \n \t -n : normal importance\n \t -lc : label cost\n \t -sc : smooth cost\n \t -oc : outlier cost\n");
	      exit (0);
    }

    seg.setConfig(config);

    /// -----------------------------------|  Preparations  |-----------------------------------

    if (argc<2){
        PCL_ERROR ("ERROR: wrong number or arguments provided.Use -h to show options.\n");
        exit (-1);
    }

    PCL_INFO ("Loading pointcloud\n");
    pcl::PointCloud<PointT>::Ptr input_cloud_ptr (new pcl::PointCloud<PointT>);

    /// Get pcd path from command line
    std::string pcd_filename = argv[1];
    if (pcl::io::loadPCDFile (pcd_filename, *input_cloud_ptr))
    {
        PCL_ERROR ("ERROR: Could not read input point cloud %s.\n", pcd_filename.c_str ());
        return (3);
    }

    std::vector< int > index;
    if (!input_cloud_ptr->is_dense){
        PCL_WARN("Point data not dense, eating NaNs\n");
        pcl::removeNaNFromPointCloud<PointT>(*input_cloud_ptr,*input_cloud_ptr,index);
        PCL_INFO ("Done making cloud\n");
    }
    std::cerr << "Number of points: " << input_cloud_ptr->size() << std::endl;

    seg.setPointCloud(input_cloud_ptr);

    seg.doSegmentation();

        pcl::PointCloud<pcl::PointXYZL>::Ptr segmented_cloud_ptr;

        segmented_cloud_ptr=seg.getSegmentedPointCloud();

        bool output_specified = pcl::console::find_switch (argc, argv, "-o");
        if (output_specified)
        {
            // Check output already exists. Create outputname if not given
            std::string outputname ("");
            pcl::console::parse (argc, argv, "-o", outputname);
            // If no filename is given, get output filename from inputname (strip seperators and file extension)
            if (outputname.empty () || (outputname.at (0) == '-'))
            {
                outputname = pcd_filename;
                size_t dot = outputname.find_last_of ('.');
                if (dot != std::string::npos)
                    outputname = outputname.substr (0, dot);
            }

            outputname+="_seg.pcd";
            PCL_INFO ("Saving output\n");
            bool save_binary_pcd = false;
            pcl::io::savePCDFile (outputname, *segmented_cloud_ptr, save_binary_pcd);
        }

        /// -----------------------------------|  Visualization  |-----------------------------------
        bool show_visualization = (not pcl::console::find_switch (argc, argv, "-novis"));
        if (show_visualization)
        {
            /// Configure Visualizer
            pcl::visualization::PCLVisualizer::Ptr viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
            viewer->setBackgroundColor (0, 0, 0);
            viewer->addPointCloud (segmented_cloud_ptr, "Segmented point cloud");

            PCL_INFO ("Loading viewer\n");
            while (!viewer->wasStopped ())
            {
                viewer->spinOnce (100);
                viewer->updatePointCloud (segmented_cloud_ptr, "Segmented point cloud");
                boost::this_thread::sleep (boost::posix_time::microseconds (100000));
            }
        }
    return 0;
}
<|endoftext|>


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

#ifndef CONFIGMGR_API_FACTORYIMPL_HXX_
#define CONFIGMGR_API_FACTORYIMPL_HXX_

#include "apifactory.hxx"

namespace configmgr
{
    namespace configapi
    {
        class ApiProvider;
        // used to create UNO objects
        class ReadOnlyObjectFactory : public Factory
        {
            ApiProvider& m_rProvider;
        public:
            ReadOnlyObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry);
            ~ReadOnlyObjectFactory();

            virtual NodeElement*    doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, configuration::Template* pSetElementTemplate);
            virtual TreeElement*    doCreateAccessRoot(configuration::Tree const& aTree, configuration::Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions);
            virtual SetElement* doCreateSetElement(configuration::ElementTree const& aTree, configuration::Template* pSetElementTemplate);
        };
        // used to create UNO objects
        class UpdateObjectFactory : public Factory
        {
            ApiProvider& m_rProvider;
        public:
            UpdateObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry);
            ~UpdateObjectFactory();

            virtual NodeElement*    doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, configuration::Template* pSetElementTemplate);
            virtual TreeElement*    doCreateAccessRoot(configuration::Tree const& aTree, configuration::Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions);
            virtual SetElement* doCreateSetElement(configuration::ElementTree const& aTree, configuration::Template* pSetElementTemplate);
        private:
            bool implIsReadOnly(configuration::Tree const& aTree, configuration::NodeRef const& aNode);
        };

    }
}

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

#ifndef CONFIGMGR_API_FACTORYIMPL_HXX_
#define CONFIGMGR_API_FACTORYIMPL_HXX_

#include "apifactory.hxx"

namespace configmgr
{
    namespace configapi
    {
        class ApiProvider;
        // used to create UNO objects
        class ReadOnlyObjectFactory : public Factory
        {
            ApiProvider& m_rProvider;
        public:
            ReadOnlyObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry);
            ~ReadOnlyObjectFactory();

            virtual NodeElement*    doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, configuration::Template* pSetElementTemplate);
            virtual TreeElement*    doCreateAccessRoot(configuration::Tree const& aTree, configuration::Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions);
            virtual SetElement* doCreateSetElement(configuration::ElementTree const& aTree, configuration::Template* pSetElementTemplate);
        };
        // used to create UNO objects
        class UpdateObjectFactory : public Factory
        {
            ApiProvider& m_rProvider;
        public:
            UpdateObjectFactory(ApiProvider& rProvider,ObjectRegistryHolder pRegistry);
            ~UpdateObjectFactory();

            virtual NodeElement*    doCreateGroupMember(configuration::Tree const& aTree, configuration::NodeRef const& aNode, configuration::Template* pSetElementTemplate);
            virtual TreeElement*    doCreateAccessRoot(configuration::Tree const& aTree, configuration::Template* pSetElementTemplate, vos::ORef< OOptions >const& _xOptions);
            virtual SetElement* doCreateSetElement(configuration::ElementTree const& aTree, configuration::Template* pSetElementTemplate);
        private:
            bool implIsReadOnly(configuration::Tree const& aTree, configuration::NodeRef const& aNode);
        };

    }
}

#endif // CONFIGMGR_API_FACTORYIMPL_HXX_
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  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 Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/repo_controller.h>
#include <repo/error_codes.h>
#include "../repo_test_database_info.h"
#include "../repo_test_fileservice_info.h"
#include "../repo_test_utils.h"

using namespace repo;

static std::shared_ptr<RepoController> getController()
{
	static std::shared_ptr<RepoController> controller =
		std::make_shared<RepoController>();

	return controller;
}

TEST(RepoControllerTest, CommitScene) {
	auto controller = getController();
	auto token = initController(controller.get());
	//Try to commit a scene without setting db/project name
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	EXPECT_EQ(REPOERR_OK, errCode);
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Trying to commit a scene with empty db and project name should also fail
	scene->setDatabaseAndProjectName("", "");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("balh", "");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("", "blah");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Setting the db name and project name should allow commit successfully
	scene->setDatabaseAndProjectName("commitSceneTest", "commitCube");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene));
	EXPECT_TRUE(scene->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube"));
	EXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER);

	auto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	std::string owner = "dog";
	EXPECT_EQ(errCode, 0);
	scene2->setDatabaseAndProjectName("commitSceneTest", "commitCube2");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene2, owner));
	EXPECT_TRUE(scene2->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube2"));
	EXPECT_EQ(scene2->getOwner(), owner);

	//null pointer checks
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, nullptr));
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(nullptr, scene));
}

TEST(RepoControllerTest, LoadSceneFromFile) {
	auto controller = getController();
	auto defaultG = core::model::RepoScene::GraphType::DEFAULT;
	auto optG = core::model::RepoScene::GraphType::OPTIMIZED;

	//standard import
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	ASSERT_TRUE(scene);
	EXPECT_EQ(errCode, 0);
	ASSERT_TRUE(scene->getRoot(defaultG));
	ASSERT_TRUE(scene->getRoot(optG));
	EXPECT_FALSE(scene->isMissingTexture());
	EXPECT_FALSE(scene->isRevisioned());
	EXPECT_TRUE(dynamic_cast<core::model::TransformationNode*>(scene->getRoot(defaultG))->isIdentity());

	//Import the scene with no transformation reduction
	auto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(false));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoReduction);
	EXPECT_TRUE(sceneNoReduction->getRoot(defaultG));
	EXPECT_TRUE(sceneNoReduction->getRoot(optG));
	EXPECT_FALSE(sceneNoReduction->isMissingTexture());
	//There should be more transformations in the non-reduced scene than the standard scene
	EXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size()
			> scene->getAllTransformations(defaultG).size());

	//Import the scene with root trans rotated
	auto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(true, true, true));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneRotated);
	ASSERT_TRUE(sceneRotated->getRoot(defaultG));
	EXPECT_TRUE(sceneRotated->getRoot(optG));
	EXPECT_FALSE(sceneRotated->isMissingTexture());
	//The root transformation should not be an identity
	core::model::TransformationNode *rootTrans = dynamic_cast<core::model::TransformationNode*>(sceneRotated->getRoot(defaultG));
	EXPECT_FALSE(rootTrans->isIdentity());

	//Import the scene with non existant file
	auto sceneNoFile = controller->loadSceneFromFile("thisFileDoesntExist.obj", errCode);
	EXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ);
	EXPECT_FALSE(sceneNoFile);

	//Import the scene with bad Extension
	auto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode);
	EXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED);
	EXPECT_FALSE(sceneBadExt);

	//Import the scene with texture but not found
	auto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoTex);
	EXPECT_TRUE(sceneNoTex->getRoot(defaultG));
	EXPECT_TRUE(sceneNoTex->getRoot(optG));
	EXPECT_TRUE(sceneNoTex->isMissingTexture());

	//Import the scene with texture but not found
	auto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneTex);
	EXPECT_TRUE(sceneTex->getRoot(defaultG));
	EXPECT_TRUE(sceneTex->getRoot(optG));
	EXPECT_FALSE(sceneTex->isMissingTexture());

	//FIXME: need to test with change of config, but this is probably not trival.
}<commit_msg>ISSUE #381 fix error code<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  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 Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/repo_controller.h>
#include <repo/error_codes.h>
#include "../repo_test_database_info.h"
#include "../repo_test_fileservice_info.h"
#include "../repo_test_utils.h"

using namespace repo;

static std::shared_ptr<RepoController> getController()
{
	static std::shared_ptr<RepoController> controller =
		std::make_shared<RepoController>();

	return controller;
}

TEST(RepoControllerTest, CommitScene) {
	auto controller = getController();
	auto token = initController(controller.get());
	//Try to commit a scene without setting db/project name
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	EXPECT_EQ(REPOERR_OK, errCode);
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Trying to commit a scene with empty db and project name should also fail
	scene->setDatabaseAndProjectName("", "");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("balh", "");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	scene->setDatabaseAndProjectName("", "blah");
	EXPECT_EQ(REPOERR_UPLOAD_FAILED, controller->commitScene(token, scene));
	EXPECT_FALSE(scene->isRevisioned());

	//Setting the db name and project name should allow commit successfully
	scene->setDatabaseAndProjectName("commitSceneTest", "commitCube");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene));
	EXPECT_TRUE(scene->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube"));
	EXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER);

	auto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	std::string owner = "dog";
	EXPECT_EQ(errCode, 0);
	scene2->setDatabaseAndProjectName("commitSceneTest", "commitCube2");
	EXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene2, owner));
	EXPECT_TRUE(scene2->isRevisioned());
	EXPECT_TRUE(projectExists("commitSceneTest", "commitCube2"));
	EXPECT_EQ(scene2->getOwner(), owner);

	//null pointer checks
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, nullptr));
	EXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(nullptr, scene));
}

TEST(RepoControllerTest, LoadSceneFromFile) {
	auto controller = getController();
	auto defaultG = core::model::RepoScene::GraphType::DEFAULT;
	auto optG = core::model::RepoScene::GraphType::OPTIMIZED;

	//standard import
	uint8_t errCode;
	auto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);
	ASSERT_TRUE(scene);
	EXPECT_EQ(errCode, 0);
	ASSERT_TRUE(scene->getRoot(defaultG));
	ASSERT_TRUE(scene->getRoot(optG));
	EXPECT_FALSE(scene->isMissingTexture());
	EXPECT_FALSE(scene->isRevisioned());
	EXPECT_TRUE(dynamic_cast<core::model::TransformationNode*>(scene->getRoot(defaultG))->isIdentity());

	//Import the scene with no transformation reduction
	auto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(false));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoReduction);
	EXPECT_TRUE(sceneNoReduction->getRoot(defaultG));
	EXPECT_TRUE(sceneNoReduction->getRoot(optG));
	EXPECT_FALSE(sceneNoReduction->isMissingTexture());
	//There should be more transformations in the non-reduced scene than the standard scene
	EXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size()
			> scene->getAllTransformations(defaultG).size());

	//Import the scene with root trans rotated
	auto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(true, true, true));
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneRotated);
	ASSERT_TRUE(sceneRotated->getRoot(defaultG));
	EXPECT_TRUE(sceneRotated->getRoot(optG));
	EXPECT_FALSE(sceneRotated->isMissingTexture());
	//The root transformation should not be an identity
	core::model::TransformationNode *rootTrans = dynamic_cast<core::model::TransformationNode*>(sceneRotated->getRoot(defaultG));
	EXPECT_FALSE(rootTrans->isIdentity());

	//Import the scene with non existant file
	auto sceneNoFile = controller->loadSceneFromFile("thisFileDoesntExist.obj", errCode);
	EXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ);
	EXPECT_FALSE(sceneNoFile);

	//Import the scene with bad Extension
	auto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode);
	EXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED);
	EXPECT_FALSE(sceneBadExt);

	//Import the scene with texture but not found
	auto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneNoTex);
	EXPECT_TRUE(sceneNoTex->getRoot(defaultG));
	EXPECT_TRUE(sceneNoTex->getRoot(optG));
	EXPECT_TRUE(sceneNoTex->isMissingTexture());

	//Import the scene with texture but not found
	auto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode);
	EXPECT_EQ(errCode, 0);
	EXPECT_TRUE(sceneTex);
	EXPECT_TRUE(sceneTex->getRoot(defaultG));
	EXPECT_TRUE(sceneTex->getRoot(optG));
	EXPECT_FALSE(sceneTex->isMissingTexture());

	//FIXME: need to test with change of config, but this is probably not trival.
}<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// interface header
#include "BZWReader.h"

// implementation-specific system headers
#include <fstream>
#include <sstream>

// implementation-specific bzflag headers
#include "URLManager.h"
#include "BZDBCache.h"

// implementation-specific bzfs-specific headers
#include "TeamBases.h"
#include "WorldFileObject.h"
#include "CustomGroup.h"
#include "CustomBox.h"
#include "CustomPyramid.h"
#include "CustomGate.h"
#include "CustomLink.h"
#include "CustomBase.h"
#include "CustomWeapon.h"
#include "CustomWorld.h"
#include "CustomZone.h"
#include "CustomTetra.h"
#include "CustomMesh.h"
#include "CustomArc.h"
#include "CustomCone.h"
#include "CustomSphere.h"
#include "CustomWaterLevel.h"
#include "CustomDynamicColor.h"
#include "CustomTextureMatrix.h"
#include "CustomMaterial.h"
#include "CustomPhysicsDriver.h"
#include "CustomMeshTransform.h"

// common headers
#include "ObstacleMgr.h"
#include "BaseBuilding.h"

// FIXME - external dependancies (from bzfs.cxx)
extern BasesList bases;

BZWReader::BZWReader(std::string filename) : location(filename), input(NULL)
{
  static const std::string httpProtocol("http://");
  static const std::string ftpProtocol("ftp://");
  static const std::string fileProtocol("file:/");

  errorHandler = new BZWError(location);

  if ((filename.substr(0, httpProtocol.size()) == httpProtocol)
      || (filename.substr(0, ftpProtocol.size()) == ftpProtocol)
      || (filename.substr(0, fileProtocol.size()) == fileProtocol)) {
    URLManager::instance().getURL(location, httpData);
    input = new std::istringstream(httpData);
  } else {
    input = new std::ifstream(filename.c_str(), std::ios::in);
  }

  // .BZW is the official worldfile extension, warn for others
  if ((filename.length() > 4) &&
  (strcasecmp(filename.substr(filename.length() - 4, 4).c_str(), ".bzw") != 0))  {
    errorHandler->warning(std::string("world file extension is not .bzw, trying to load anyway"), 0);
  }

  if (input->peek() == EOF) {
    errorHandler->fatalError(std::string("could not find bzflag world file"), 0);
  }
}

BZWReader::~BZWReader()
{
  // clean up
  delete errorHandler;
  delete input;
}

void BZWReader::readToken(char *buffer, int n)
{
  int c = -1;

  // skip whitespace
  while (input->good() && (c = input->get()) != -1 && isspace(c) && c != '\n')
    ;

  // read up to whitespace or n - 1 characters into buffer
  int i = 0;
  if (c != -1 && c != '\n') {
    buffer[i++] = c;
    while (input->good() && i < n - 1 && (c = input->get()) != -1 && !isspace(c))
      buffer[i++] = (char)c;
  }

  // terminate string
  buffer[i] = 0;

  // put back last character we didn't use
  if (c != -1 && isspace(c))
    input->putback(c);
}

bool BZWReader::readWorldStream(std::vector<WorldFileObject*>& wlist)
{
  int line = 1;
  char buffer[1024];
  WorldFileObject* object = NULL;
  WorldFileObject* newObject = NULL;
  WorldFileObject* const fakeObject = (WorldFileObject*)((char*)NULL + 1);
  GroupDefinition* const worldDef = (GroupDefinition*)OBSTACLEMGR.getWorld();
  GroupDefinition* groupDef = worldDef;

  bool gotWorld = false;

  while (!input->eof() && !input->fail() && input->good())
  {
    // watch out for starting a new object when one is already in progress
    if (newObject) {
      if (object) {
	errorHandler->warning(
	  std::string("discarding incomplete object"), line);
	if (object != fakeObject) {
	  delete object;
        }
      }
      object = newObject;
      newObject = NULL;
    }

    // read first token but do not skip newlines
    readToken(buffer, sizeof(buffer));
    if (strcmp(buffer, "") == 0) {
      // ignore blank line
    } else if (buffer[0] == '#') {
      // ignore comment

    } else if (strcasecmp(buffer, "end") == 0) {
      if (object) {
	if (object != fakeObject) {
	  if (object->usesManager()) {
	    object->writeToManager();
	    delete object;
	  } else if (object->usesGroupDef()) {
	    object->writeToGroupDef(groupDef);
	    delete object;
	  } else {
	    wlist.push_back(object);
	  }
	}
	object = NULL;
      } else {
	errorHandler->fatalError(
	  std::string("unexpected \"end\" token"), line);
	return false;
      }

    } else if (strcasecmp(buffer, "define") == 0) {
      if (groupDef != worldDef) {
        errorHandler->warning(
          std::string("group definitions can not be nested \"") +
          std::string(buffer) + std::string("\" - skipping"), line);
      } else {
        readToken(buffer, sizeof(buffer));
        if (strlen(buffer) > 0) {
          if (OBSTACLEMGR.findGroupDef(buffer) != NULL) {
            errorHandler->warning(
              std::string("duplicate group definition \"") +
              std::string(buffer) + std::string("\" - using newest"), line);
          }
          groupDef = new GroupDefinition(buffer);
        } else {
          errorHandler->warning(
            std::string("missing group definition name"), line);
        }
      }

    } else if (strcasecmp(buffer, "enddef") == 0) {
      if (groupDef == worldDef) {
        errorHandler->warning(
          std::string("enddef without define - skipping"), line);
      } else {
        OBSTACLEMGR.addGroupDef(groupDef);
        groupDef = worldDef;
      }

    } else if (strcasecmp(buffer, "group") == 0) {
      readToken(buffer, sizeof(buffer));
      if (strlen(buffer) <= 0) {
        errorHandler->warning(
          std::string("missing group definition reference"), line);
      }
      newObject = new CustomGroup(buffer);

    } else if (strcasecmp(buffer, "box") == 0) {
      newObject = new CustomBox;
    } else if (strcasecmp(buffer, "pyramid") == 0) {
      newObject = new CustomPyramid();
    } else if (strcasecmp(buffer, "base") == 0) {
      newObject = new CustomBase;
    } else if (strcasecmp(buffer, "teleporter") == 0) {
      newObject = new CustomGate();
    } else if (strcasecmp(buffer, "link") == 0) {
      newObject = new CustomLink();
    } else if (strcasecmp(buffer, "mesh") == 0) {
      newObject = new CustomMesh;
    } else if (strcasecmp(buffer, "arc") == 0) {
      newObject = new CustomArc(false);
    } else if (strcasecmp(buffer, "meshbox") == 0) {
      newObject = new CustomArc(true);
    } else if (strcasecmp(buffer, "cone") == 0) {
      newObject = new CustomCone(false);
    } else if (strcasecmp(buffer, "meshpyr") == 0) {
      newObject = new CustomCone(true);
    } else if (strcasecmp(buffer, "sphere") == 0) {
      newObject = new CustomSphere;
    } else if (strcasecmp(buffer, "tetra") == 0) {
      newObject = new CustomTetra();
    } else if (strcasecmp(buffer, "weapon") == 0) {
      newObject = new CustomWeapon;
    } else if (strcasecmp(buffer, "zone") == 0) {
      newObject = new CustomZone;
    } else if (strcasecmp(buffer, "waterLevel") == 0) {
      newObject = new CustomWaterLevel;
    } else if (strcasecmp(buffer, "dynamicColor") == 0) {
      newObject = new CustomDynamicColor;
    } else if (strcasecmp(buffer, "textureMatrix") == 0) {
      newObject = new CustomTextureMatrix;
    } else if (strcasecmp(buffer, "material") == 0) {
      newObject = new CustomMaterial;
    } else if (strcasecmp(buffer, "physics") == 0) {
      newObject = new CustomPhysicsDriver;
    } else if (strcasecmp(buffer, "transform") == 0) {
      newObject = new CustomMeshTransform;
    } else if (strcasecmp(buffer, "options") == 0) {
      newObject = fakeObject;

    } else if (strcasecmp(buffer, "world") == 0) {
      if (!gotWorld) {
	newObject = new CustomWorld();
	gotWorld = true;
      } else {
	errorHandler->warning(
	  std::string("multiple \"world\" sections found"), line);
      }

    } else if (object) {
      if (object != fakeObject) {
	if (!object->read(buffer, *input)) {
	  // unknown token
	  errorHandler->warning(
	    std::string("unknown object parameter \"") +
	    std::string(buffer) + std::string("\" - skipping"), line);
	  // delete object;
	  // return false;
	}
      }

    } else { // filling the current object
      // unknown token
      errorHandler->warning(
        std::string("invalid object type \"") +
        std::string(buffer) + std::string("\" - skipping"), line);
      if (object != fakeObject)
	delete object;
     // return false;
    }

    // discard remainder of line
    while (input->good() && input->peek() != '\n')
      input->get(buffer, sizeof(buffer));
    input->getline(buffer, sizeof(buffer));
    ++line;
  }

  bool retval = true;
  if (object) {
    errorHandler->fatalError(std::string("missing \"end\" parameter"), line);
    if (object != fakeObject) {
      delete object;
    }
    retval = false;
  }
  if (groupDef != worldDef) {
    errorHandler->fatalError(std::string("missing \"enddef\" parameter"), line);
    delete groupDef;
    retval = false;
  }
  return retval;
}

WorldInfo* BZWReader::defineWorldFromFile()
{
  // make sure input is valid
  if (input->peek() == EOF) {
    errorHandler->fatalError(std::string("unexpected EOF"), 0);
    return NULL;
  }

  // create world object
  WorldInfo *world = new WorldInfo;
  if (!world) {
    errorHandler->fatalError(std::string("WorldInfo failed to initialize"), 0);
    return NULL;
  }

  // read file
  std::vector<WorldFileObject*> list;
  if (!readWorldStream(list)) {
    emptyWorldFileObjectList(list);
    errorHandler->fatalError(std::string("world file failed to load."), 0);
    delete world;
    return NULL;
  }

  // make walls
  float wallHeight = BZDB.eval(StateDatabase::BZDB_WALLHEIGHT);
  float worldSize = BZDBCache::worldSize;
  world->addWall(0.0f, 0.5f * worldSize, 0.0f, (float)(1.5 * M_PI), 0.5f * worldSize, wallHeight);
  world->addWall(0.5f * worldSize, 0.0f, 0.0f, (float)M_PI, 0.5f * worldSize, wallHeight);
  world->addWall(0.0f, -0.5f * worldSize, 0.0f, (float)(0.5 * M_PI), 0.5f * worldSize, wallHeight);
  world->addWall(-0.5f * worldSize, 0.0f, 0.0f, 0.0f, 0.5f * worldSize, wallHeight);

  // generate group instances
  OBSTACLEMGR.makeWorld();

  // make local bases
  unsigned int i;
  const float safety[] = { 0.0f, 0.0f, 0.0f };
  const ObstacleList& baseList = OBSTACLEMGR.getBases();
  for (i = 0; i < baseList.size(); i++) {
    const BaseBuilding* base = (const BaseBuilding*) baseList[i];
    TeamColor color = (TeamColor)base->getTeam();
    if (bases.find(color) == bases.end()) {
      bases[color] = TeamBases((TeamColor)color);
    }
    bases[color].addBase(base->getPosition(), base->getSize(),
                         base->getRotation(), safety);
  }

  // make defaults links
  const ObstacleList& teles = OBSTACLEMGR.getTeles();
  for (i = 0; i < teles.size(); i++) {
    const int side1 = i * 2;
    const int side2 = (i * 2) + 1;
    world->addLink(side1, side2);
    world->addLink(side2, side1);
  }

  // add objects
  const int n = list.size();
  for (int i = 0; i < n; ++i) {
    list[i]->writeToWorld(world);
  }

  // clean up
  emptyWorldFileObjectList(list);
  world->finishWorld();

  return world;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>split-up the long parsing function<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// interface header
#include "BZWReader.h"

// implementation-specific system headers
#include <fstream>
#include <sstream>

// implementation-specific bzflag headers
#include "URLManager.h"
#include "BZDBCache.h"

// implementation-specific bzfs-specific headers
#include "TeamBases.h"
#include "WorldFileObject.h"
#include "CustomGroup.h"
#include "CustomBox.h"
#include "CustomPyramid.h"
#include "CustomGate.h"
#include "CustomLink.h"
#include "CustomBase.h"
#include "CustomWeapon.h"
#include "CustomWorld.h"
#include "CustomZone.h"
#include "CustomTetra.h"
#include "CustomMesh.h"
#include "CustomArc.h"
#include "CustomCone.h"
#include "CustomSphere.h"
#include "CustomWaterLevel.h"
#include "CustomDynamicColor.h"
#include "CustomTextureMatrix.h"
#include "CustomMaterial.h"
#include "CustomPhysicsDriver.h"
#include "CustomMeshTransform.h"

// common headers
#include "ObstacleMgr.h"
#include "BaseBuilding.h"

// FIXME - external dependancies (from bzfs.cxx)
extern BasesList bases;

BZWReader::BZWReader(std::string filename) : location(filename), input(NULL)
{
  static const std::string httpProtocol("http://");
  static const std::string ftpProtocol("ftp://");
  static const std::string fileProtocol("file:/");

  errorHandler = new BZWError(location);

  if ((filename.substr(0, httpProtocol.size()) == httpProtocol)
      || (filename.substr(0, ftpProtocol.size()) == ftpProtocol)
      || (filename.substr(0, fileProtocol.size()) == fileProtocol)) {
    URLManager::instance().getURL(location, httpData);
    input = new std::istringstream(httpData);
  } else {
    input = new std::ifstream(filename.c_str(), std::ios::in);
  }

  // .BZW is the official worldfile extension, warn for others
  if ((filename.length() > 4) &&
  (strcasecmp(filename.substr(filename.length() - 4, 4).c_str(), ".bzw") != 0))  {
    errorHandler->warning(std::string("world file extension is not .bzw, trying to load anyway"), 0);
  }

  if (input->peek() == EOF) {
    errorHandler->fatalError(std::string("could not find bzflag world file"), 0);
  }
}

BZWReader::~BZWReader()
{
  // clean up
  delete errorHandler;
  delete input;
}

void BZWReader::readToken(char *buffer, int n)
{
  int c = -1;

  // skip whitespace
  while (input->good() && (c = input->get()) != -1 && isspace(c) && c != '\n')
    ;

  // read up to whitespace or n - 1 characters into buffer
  int i = 0;
  if (c != -1 && c != '\n') {
    buffer[i++] = c;
    while (input->good() && i < n - 1 && (c = input->get()) != -1 && !isspace(c))
      buffer[i++] = (char)c;
  }

  // terminate string
  buffer[i] = 0;

  // put back last character we didn't use
  if (c != -1 && isspace(c))
    input->putback(c);
}

static bool parseNormalObject(const char* token, WorldFileObject** object)
{
  WorldFileObject* tmpObj = NULL;

  if (strcasecmp(token, "box") == 0) {
    tmpObj = new CustomBox;
  } else if (strcasecmp(token, "pyramid") == 0) {
    tmpObj = new CustomPyramid();
  } else if (strcasecmp(token, "base") == 0) {
    tmpObj = new CustomBase;
  } else if (strcasecmp(token, "teleporter") == 0) {
    tmpObj = new CustomGate();
  } else if (strcasecmp(token, "link") == 0) {
    tmpObj = new CustomLink();
  } else if (strcasecmp(token, "mesh") == 0) {
    tmpObj = new CustomMesh;
  } else if (strcasecmp(token, "arc") == 0) {
    tmpObj = new CustomArc(false);
  } else if (strcasecmp(token, "meshbox") == 0) {
    tmpObj = new CustomArc(true);
  } else if (strcasecmp(token, "cone") == 0) {
    tmpObj = new CustomCone(false);
  } else if (strcasecmp(token, "meshpyr") == 0) {
    tmpObj = new CustomCone(true);
  } else if (strcasecmp(token, "sphere") == 0) {
    tmpObj = new CustomSphere;
  } else if (strcasecmp(token, "tetra") == 0) {
    tmpObj = new CustomTetra();
  } else if (strcasecmp(token, "weapon") == 0) {
    tmpObj = new CustomWeapon;
  } else if (strcasecmp(token, "zone") == 0) {
    tmpObj = new CustomZone;
  } else if (strcasecmp(token, "waterLevel") == 0) {
    tmpObj = new CustomWaterLevel;
  } else if (strcasecmp(token, "dynamicColor") == 0) {
    tmpObj = new CustomDynamicColor;
  } else if (strcasecmp(token, "textureMatrix") == 0) {
    tmpObj = new CustomTextureMatrix;
  } else if (strcasecmp(token, "material") == 0) {
    tmpObj = new CustomMaterial;
  } else if (strcasecmp(token, "physics") == 0) {
    tmpObj = new CustomPhysicsDriver;
  } else if (strcasecmp(token, "transform") == 0) {
    tmpObj = new CustomMeshTransform;
  }

  if (tmpObj != NULL) {
    *object = tmpObj;
    return true;
  } else {
    return false;
  }
}

bool BZWReader::readWorldStream(std::vector<WorldFileObject*>& wlist)
{
  int line = 1;
  char buffer[1024];
  WorldFileObject* object = NULL;
  WorldFileObject* newObject = NULL;
  WorldFileObject* const fakeObject = (WorldFileObject*)((char*)NULL + 1);
  GroupDefinition* const worldDef = (GroupDefinition*)OBSTACLEMGR.getWorld();
  GroupDefinition* groupDef = worldDef;

  bool gotWorld = false;

  while (!input->eof() && !input->fail() && input->good())
  {
    // watch out for starting a new object when one is already in progress
    if (newObject) {
      if (object) {
	errorHandler->warning(
	  std::string("discarding incomplete object"), line);
	if (object != fakeObject) {
	  delete object;
        }
      }
      object = newObject;
      newObject = NULL;
    }

    // read first token but do not skip newlines
    readToken(buffer, sizeof(buffer));
    if (strcmp(buffer, "") == 0) {
      // ignore blank line
    } else if (buffer[0] == '#') {
      // ignore comment

    } else if (strcasecmp(buffer, "end") == 0) {
      if (object) {
	if (object != fakeObject) {
	  if (object->usesManager()) {
	    object->writeToManager();
	    delete object;
	  } else if (object->usesGroupDef()) {
	    object->writeToGroupDef(groupDef);
	    delete object;
	  } else {
	    wlist.push_back(object);
	  }
	}
	object = NULL;
      } else {
	errorHandler->fatalError(
	  std::string("unexpected \"end\" token"), line);
	return false;
      }

    } else if (parseNormalObject(buffer, &newObject)) {
      // newObject has already been assigned

    } else if (strcasecmp(buffer, "define") == 0) {
      if (groupDef != worldDef) {
        errorHandler->warning(
          std::string("group definitions can not be nested \"") +
          std::string(buffer) + std::string("\" - skipping"), line);
      } else {
        readToken(buffer, sizeof(buffer));
        if (strlen(buffer) > 0) {
          if (OBSTACLEMGR.findGroupDef(buffer) != NULL) {
            errorHandler->warning(
              std::string("duplicate group definition \"") +
              std::string(buffer) + std::string("\" - using newest"), line);
          }
          groupDef = new GroupDefinition(buffer);
        } else {
          errorHandler->warning(
            std::string("missing group definition name"), line);
        }
      }

    } else if (strcasecmp(buffer, "enddef") == 0) {
      if (groupDef == worldDef) {
        errorHandler->warning(
          std::string("enddef without define - skipping"), line);
      } else {
        OBSTACLEMGR.addGroupDef(groupDef);
        groupDef = worldDef;
      }

    } else if (strcasecmp(buffer, "group") == 0) {
      readToken(buffer, sizeof(buffer));
      if (strlen(buffer) <= 0) {
        errorHandler->warning(
          std::string("missing group definition reference"), line);
      }
      newObject = new CustomGroup(buffer);

    } else if (strcasecmp(buffer, "options") == 0) {
      newObject = fakeObject;

    } else if (strcasecmp(buffer, "world") == 0) {
      if (!gotWorld) {
	newObject = new CustomWorld();
	gotWorld = true;
      } else {
	errorHandler->warning(
	  std::string("multiple \"world\" sections found"), line);
      }

    } else if (object) {
      if (object != fakeObject) {
	if (!object->read(buffer, *input)) {
	  // unknown token
	  errorHandler->warning(
	    std::string("unknown object parameter \"") +
	    std::string(buffer) + std::string("\" - skipping"), line);
	  // delete object;
	  // return false;
	}
      }

    } else { // filling the current object
      // unknown token
      errorHandler->warning(
        std::string("invalid object type \"") +
        std::string(buffer) + std::string("\" - skipping"), line);
      if (object != fakeObject)
	delete object;
     // return false;
    }

    // discard remainder of line
    while (input->good() && input->peek() != '\n')
      input->get(buffer, sizeof(buffer));
    input->getline(buffer, sizeof(buffer));
    ++line;
  }

  bool retval = true;
  if (object) {
    errorHandler->fatalError(std::string("missing \"end\" parameter"), line);
    if (object != fakeObject) {
      delete object;
    }
    retval = false;
  }
  if (groupDef != worldDef) {
    errorHandler->fatalError(std::string("missing \"enddef\" parameter"), line);
    delete groupDef;
    retval = false;
  }
  return retval;
}

WorldInfo* BZWReader::defineWorldFromFile()
{
  // make sure input is valid
  if (input->peek() == EOF) {
    errorHandler->fatalError(std::string("unexpected EOF"), 0);
    return NULL;
  }

  // create world object
  WorldInfo *world = new WorldInfo;
  if (!world) {
    errorHandler->fatalError(std::string("WorldInfo failed to initialize"), 0);
    return NULL;
  }

  // read file
  std::vector<WorldFileObject*> list;
  if (!readWorldStream(list)) {
    emptyWorldFileObjectList(list);
    errorHandler->fatalError(std::string("world file failed to load."), 0);
    delete world;
    return NULL;
  }

  // make walls
  float wallHeight = BZDB.eval(StateDatabase::BZDB_WALLHEIGHT);
  float worldSize = BZDBCache::worldSize;
  world->addWall(0.0f, 0.5f * worldSize, 0.0f, (float)(1.5 * M_PI), 0.5f * worldSize, wallHeight);
  world->addWall(0.5f * worldSize, 0.0f, 0.0f, (float)M_PI, 0.5f * worldSize, wallHeight);
  world->addWall(0.0f, -0.5f * worldSize, 0.0f, (float)(0.5 * M_PI), 0.5f * worldSize, wallHeight);
  world->addWall(-0.5f * worldSize, 0.0f, 0.0f, 0.0f, 0.5f * worldSize, wallHeight);

  // generate group instances
  OBSTACLEMGR.makeWorld();

  // make local bases
  unsigned int i;
  const float safety[] = { 0.0f, 0.0f, 0.0f };
  const ObstacleList& baseList = OBSTACLEMGR.getBases();
  for (i = 0; i < baseList.size(); i++) {
    const BaseBuilding* base = (const BaseBuilding*) baseList[i];
    TeamColor color = (TeamColor)base->getTeam();
    if (bases.find(color) == bases.end()) {
      bases[color] = TeamBases((TeamColor)color);
    }
    bases[color].addBase(base->getPosition(), base->getSize(),
                         base->getRotation(), safety);
  }

  // make defaults links
  const ObstacleList& teles = OBSTACLEMGR.getTeles();
  for (i = 0; i < teles.size(); i++) {
    const int side1 = i * 2;
    const int side2 = (i * 2) + 1;
    world->addLink(side1, side2);
    world->addLink(side2, side1);
  }

  // add objects
  const int n = list.size();
  for (int i = 0; i < n; ++i) {
    list[i]->writeToWorld(world);
  }

  // clean up
  emptyWorldFileObjectList(list);
  world->finishWorld();

  return world;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>