<commit_before>#include <omp.h>
#include "dispar.h"
#include "tournament.h"

template<typename T>
matrix createRandomTournamentPool(T container,
                                  const size_t nbGroup,
                                  const size_t poolSize) {

    std::bitset<1> bs(container.size());
    matrix pools(nbGroup);

    size_t cardinality = 0;

    for (auto&& pool: pools) {
        pool.reserve(poolSize);
    }

    while(cardinality < nbGroup * poolSize) {
        //int v = rand.nextInt(container.size());
        int v = 0;
        if(!bs[v]) {
            bs[v];
            cardinality++;
            pools[cardinality / poolSize][cardinality % poolSize] = v;
        }
    }

    return pools;
}

template<typename T, typename Alloc, template <typename, typename> class TT>
std::vector<int> selection(const size_t targetSize,
                           TT<T, Alloc> container,
                           std::function<void (const T&, const T&)> comparator) {

    const size_t nbGroup = 1;
    const size_t poolSize = 5;

    std::vector<int> selected_keys;
    selected_keys.reserve(targetSize);

    matrix pools = createRandomTournamentPool(container, nbGroup, poolSize);

    #pragma omp parallel for
    for (int i = 0; i < pools.size(); i++) {
        selected_keys.push_back(tournament<TT, T>(container, pools[i], comparator));
    }

    return selected_keys;
}

<commit_msg>Use vector of bool instead of bitset that need to know their size at compile time<commit_after>#include <omp.h>
#include "dispar.h"
#include "tournament.h"

template<typename T>
matrix createRandomTournamentPool(T container,
                                  const size_t nbGroup,
                                  const size_t poolSize) {

    std::vector<bool> bs(size);
    matrix pools(nbGroup);

    size_t cardinality = 0;

    for (auto&& pool: pools) {
        pool.reserve(poolSize);
    }

    while(cardinality < nbGroup * poolSize) {
        //int v = rand.random_int(offset, size - 1);
        int v = 0;
        if(!bs[v]) {
            bs[v];
            bs[v] = true;
            pools[cardinality / poolSize][cardinality % poolSize] = v;
            cardinality++;
        }
    }

    return pools;
}

template<typename T, typename Alloc, template <typename, typename> class TT>
std::vector<int> selection(const size_t targetSize,
                           TT<T, Alloc> container,
                           std::function<void (const T&, const T&)> comparator) {

    const size_t nbGroup = 1;
    const size_t poolSize = 5;

    std::vector<int> selected_keys;
    selected_keys.reserve(targetSize);

    matrix pools = createRandomTournamentPool(container, nbGroup, poolSize);

    #pragma omp parallel for
    for (int i = 0; i < pools.size(); i++) {
        selected_keys.push_back(tournament<TT, T>(container, pools[i], comparator));
    }

    return selected_keys;
}

<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This 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.  See file COPYING.
 *
 */

#include "MonitorStore.h"
#include "common/Clock.h"

#include "config.h"

#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(dir)
static ostream& _prefix(const string& dir) {
  return *_dout << dbeginl << "store(" << dir << ") ";
}

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/file.h>

int MonitorStore::mount()
{
  char t[1024];

  dout(1) << "mount" << dendl;
  // verify dir exists
  DIR *d = ::opendir(dir.c_str());
  if (!d) {
    derr(1) << "basedir " << dir << " dne" << dendl;
    return -ENOENT;
  }
  ::closedir(d);

  // open lockfile
  snprintf(t, sizeof(t), "%s/lock", dir.c_str());
  lock_fd = ::open(t, O_CREAT|O_RDWR, 0600);
  if (lock_fd < 0)
    return -errno;
  struct flock l;
  memset(&l, 0, sizeof(l));
  l.l_type = F_WRLCK;
  l.l_whence = SEEK_SET;
  l.l_start = 0;
  l.l_len = 0;
  int r = ::fcntl(lock_fd, F_SETLK, &l);
  if (r < 0) {
    derr(0) << "failed to lock " << t << ", is another cmon still running?" << dendl;
    return -errno;
  }

  if (g_conf.chdir && g_conf.chdir[0] && dir[0] != '/') {
    // combine it with the cwd, in case fuse screws things up (i.e. fakefuse)
    string old = dir;
    char cwd[1024];
    getcwd(cwd, sizeof(cwd));
    dir = cwd;
    dir += "/";
    dir += old;
  }
  return 0;
}

int MonitorStore::umount()
{
  ::close(lock_fd);
  return 0;
}

int MonitorStore::mkfs()
{
  dout(1) << "mkfs" << dendl;

  char cmd[1024];
  snprintf(cmd, sizeof(cmd), "test -d %s && /bin/rm -r %s ; mkdir -p %s", dir.c_str(), dir.c_str(), dir.c_str());
  dout(1) << cmd << dendl;
  int r = system(cmd);
  return r;
}

void MonitorStore::sync()
{
  dout(10) << "sync" << dendl;
  ::sync();
}

version_t MonitorStore::get_int(const char *a, const char *b)
{
  char fn[1024];
  if (b)
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  else
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);

  FILE *f = ::fopen(fn, "r");
  if (!f)
    return 0;

  char buf[20];
  ::fgets(buf, 20, f);
  ::fclose(f);

  version_t val = atoi(buf);

  if (b) {
    dout(15) << "get_int " << a << "/" << b << " = " << val << dendl;
  } else {
    dout(15) << "get_int " << a << " = " << val << dendl;
  }
  return val;
}

void MonitorStore::put_int(version_t val, const char *a, const char *b, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "set_int " << a << "/" << b << " = " << val << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "set_int " << a << " = " << val << dendl;
  }

  char vs[30];
  snprintf(vs, sizeof(vs), "%lld\n", (unsigned long long)val);

  char tfn[1024];
  snprintf(tfn, sizeof(tfn), "%s.new", fn);

  int fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
  assert(fd >= 0);
  ::write(fd, vs, strlen(vs));
  if (sync)
    ::fsync(fd);
  ::close(fd);
  ::rename(tfn, fn);
}

// ----------------------------------------
// buffers

bool MonitorStore::exists_bl_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "exists_bl " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "exists_bl " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  struct stat st;
  int r = ::stat(fn, &st);
  //char buf[80];
  //dout(15) << "exists_bl stat " << fn << " r=" << r << " errno " << errno << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
  return r == 0;
}

int MonitorStore::erase_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "erase_ss " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "erase_ss " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }
  return ::unlink(fn);
}

int MonitorStore::get_bl_ss(bufferlist& bl, const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  int fd = ::open(fn, O_RDONLY);
  if (fd < 0) {
    if (b) {
      dout(15) << "get_bl " << a << "/" << b << " DNE" << dendl;
    } else {
      dout(15) << "get_bl " << a << " DNE" << dendl;
    }
    return 0;
  }

  // get size
  struct stat st;
  int rc = ::fstat(fd, &st);
  assert(rc == 0);
  __int32_t len = st.st_size;

  // read buffer
  bl.clear();
  bufferptr bp(len);
  int off = 0;
  while (off < len) {
    dout(20) << "reading at off " << off << " of " << len << dendl;
    int r = ::read(fd, bp.c_str()+off, len-off);
    if (r < 0) {
      char buf[80];
      derr(0) << "errno on read " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    }
    assert(r>0);
    off += r;
  }
  bl.append(bp);
  ::close(fd);

  if (b) {
    dout(15) << "get_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
  } else {
    dout(15) << "get_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  return len;
}

int MonitorStore::write_bl_ss(bufferlist& bl, const char *a, const char *b, bool append, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "put_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "put_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  char tfn[1024];
  int err = 0;
  int fd;
  if (append) {
    fd = ::open(fn, O_WRONLY|O_CREAT|O_APPEND, 0644);
  } else {
    snprintf(tfn, sizeof(tfn), "%s.new", fn);
    fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
  }
  assert(fd >= 0);

  // write data
  for (list<bufferptr>::const_iterator it = bl.buffers().begin();
       it != bl.buffers().end();
       it++)  {
    int r = ::write(fd, it->c_str(), it->length());
    if (r != (int)it->length())
      derr(0) << "put_bl_ss ::write() returned " << r << " not " << it->length() << dendl;
    if (r < 0) {
      char buf[80];
      derr(0) << "put_bl_ss ::write() errored out, errno is " << strerror_r(errno, buf, sizeof(buf)) << dendl;
      err = -errno;
      break;
    }
  }

  if (sync && !err)
    ::fsync(fd);
  ::close(fd);
  if (!append && !err) {
    ::rename(tfn, fn);
  }

  assert(!err);  // for now

  return err;
}

<commit_msg>mkmonfs: rm -rf, so that we kill 0600 admin_keyring.bin<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This 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.  See file COPYING.
 *
 */

#include "MonitorStore.h"
#include "common/Clock.h"

#include "config.h"

#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(dir)
static ostream& _prefix(const string& dir) {
  return *_dout << dbeginl << "store(" << dir << ") ";
}

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/file.h>

int MonitorStore::mount()
{
  char t[1024];

  dout(1) << "mount" << dendl;
  // verify dir exists
  DIR *d = ::opendir(dir.c_str());
  if (!d) {
    derr(1) << "basedir " << dir << " dne" << dendl;
    return -ENOENT;
  }
  ::closedir(d);

  // open lockfile
  snprintf(t, sizeof(t), "%s/lock", dir.c_str());
  lock_fd = ::open(t, O_CREAT|O_RDWR, 0600);
  if (lock_fd < 0)
    return -errno;
  struct flock l;
  memset(&l, 0, sizeof(l));
  l.l_type = F_WRLCK;
  l.l_whence = SEEK_SET;
  l.l_start = 0;
  l.l_len = 0;
  int r = ::fcntl(lock_fd, F_SETLK, &l);
  if (r < 0) {
    derr(0) << "failed to lock " << t << ", is another cmon still running?" << dendl;
    return -errno;
  }

  if (g_conf.chdir && g_conf.chdir[0] && dir[0] != '/') {
    // combine it with the cwd, in case fuse screws things up (i.e. fakefuse)
    string old = dir;
    char cwd[1024];
    getcwd(cwd, sizeof(cwd));
    dir = cwd;
    dir += "/";
    dir += old;
  }
  return 0;
}

int MonitorStore::umount()
{
  ::close(lock_fd);
  return 0;
}

int MonitorStore::mkfs()
{
  dout(1) << "mkfs" << dendl;

  char cmd[1024];
  snprintf(cmd, sizeof(cmd), "test -d %s && /bin/rm -rf %s ; mkdir -p %s", dir.c_str(), dir.c_str(), dir.c_str());
  dout(1) << cmd << dendl;
  int r = system(cmd);
  return r;
}

void MonitorStore::sync()
{
  dout(10) << "sync" << dendl;
  ::sync();
}

version_t MonitorStore::get_int(const char *a, const char *b)
{
  char fn[1024];
  if (b)
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  else
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);

  FILE *f = ::fopen(fn, "r");
  if (!f)
    return 0;

  char buf[20];
  ::fgets(buf, 20, f);
  ::fclose(f);

  version_t val = atoi(buf);

  if (b) {
    dout(15) << "get_int " << a << "/" << b << " = " << val << dendl;
  } else {
    dout(15) << "get_int " << a << " = " << val << dendl;
  }
  return val;
}

void MonitorStore::put_int(version_t val, const char *a, const char *b, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "set_int " << a << "/" << b << " = " << val << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "set_int " << a << " = " << val << dendl;
  }

  char vs[30];
  snprintf(vs, sizeof(vs), "%lld\n", (unsigned long long)val);

  char tfn[1024];
  snprintf(tfn, sizeof(tfn), "%s.new", fn);

  int fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
  assert(fd >= 0);
  ::write(fd, vs, strlen(vs));
  if (sync)
    ::fsync(fd);
  ::close(fd);
  ::rename(tfn, fn);
}

// ----------------------------------------
// buffers

bool MonitorStore::exists_bl_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "exists_bl " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "exists_bl " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  struct stat st;
  int r = ::stat(fn, &st);
  //char buf[80];
  //dout(15) << "exists_bl stat " << fn << " r=" << r << " errno " << errno << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
  return r == 0;
}

int MonitorStore::erase_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "erase_ss " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "erase_ss " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }
  return ::unlink(fn);
}

int MonitorStore::get_bl_ss(bufferlist& bl, const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  int fd = ::open(fn, O_RDONLY);
  if (fd < 0) {
    if (b) {
      dout(15) << "get_bl " << a << "/" << b << " DNE" << dendl;
    } else {
      dout(15) << "get_bl " << a << " DNE" << dendl;
    }
    return 0;
  }

  // get size
  struct stat st;
  int rc = ::fstat(fd, &st);
  assert(rc == 0);
  __int32_t len = st.st_size;

  // read buffer
  bl.clear();
  bufferptr bp(len);
  int off = 0;
  while (off < len) {
    dout(20) << "reading at off " << off << " of " << len << dendl;
    int r = ::read(fd, bp.c_str()+off, len-off);
    if (r < 0) {
      char buf[80];
      derr(0) << "errno on read " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    }
    assert(r>0);
    off += r;
  }
  bl.append(bp);
  ::close(fd);

  if (b) {
    dout(15) << "get_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
  } else {
    dout(15) << "get_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  return len;
}

int MonitorStore::write_bl_ss(bufferlist& bl, const char *a, const char *b, bool append, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "put_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "put_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  char tfn[1024];
  int err = 0;
  int fd;
  if (append) {
    fd = ::open(fn, O_WRONLY|O_CREAT|O_APPEND, 0644);
  } else {
    snprintf(tfn, sizeof(tfn), "%s.new", fn);
    fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
  }
  assert(fd >= 0);

  // write data
  for (list<bufferptr>::const_iterator it = bl.buffers().begin();
       it != bl.buffers().end();
       it++)  {
    int r = ::write(fd, it->c_str(), it->length());
    if (r != (int)it->length())
      derr(0) << "put_bl_ss ::write() returned " << r << " not " << it->length() << dendl;
    if (r < 0) {
      char buf[80];
      derr(0) << "put_bl_ss ::write() errored out, errno is " << strerror_r(errno, buf, sizeof(buf)) << dendl;
      err = -errno;
      break;
    }
  }

  if (sync && !err)
    ::fsync(fd);
  ::close(fd);
  if (!append && !err) {
    ::rename(tfn, fn);
  }

  assert(!err);  // for now

  return err;
}

<|endoftext|>


<commit_before>#include "Hardware.h"

#include <unistd.h>
#include <stdlib.h>
#include <iostream>

int main() {
	Hardware hand;
	hand.poise();

	stressTest(&hand, 10);
}

void stressTest(Hardware *hardware, int trials) {
	for (int i=0; i<trials; i++) {
		if (executeScaledAngles(hardware,rand()*2.0-1,rand()*2.0-1,rand()*2.0-1)) {
			std::cout << "Move executed.\n";
		} else {
			std::cout << "Move fail-safed.\n";
		} usleep(3000000);
	}
}

bool executeScaledAngles(Hardware *hardware, int i, int j, int k) {
	double iAng = Hardware::map(i, -1, 1, I_MIN_ANG, I_MAX_ANG);
	double jAng = Hardware::map(j, -1, 1, J_MIN_ANG, J_MAX_ANG);
	double kAng = Hardware::map(k, -1, 1, K_MIN_ANG, K_MAX_ANG);

	return hardware->setJoints(iAng, jAng, kAng);
}
<commit_msg>reorder for c++ sadness<commit_after>#include "Hardware.h"

#include <unistd.h>
#include <stdlib.h>
#include <iostream>

bool executeScaledAngles(Hardware *hardware, int i, int j, int k) {
	double iAng = Hardware::map(i, -1, 1, I_MIN_ANG, I_MAX_ANG);
	double jAng = Hardware::map(j, -1, 1, J_MIN_ANG, J_MAX_ANG);
	double kAng = Hardware::map(k, -1, 1, K_MIN_ANG, K_MAX_ANG);

	return hardware->setJoints(iAng, jAng, kAng);
}

void stressTest(Hardware *hardware, int trials) {
	for (int i=0; i<trials; i++) {
		if (executeScaledAngles(hardware,rand()*2.0-1,rand()*2.0-1,rand()*2.0-1)) {
			std::cout << "Move executed.\n";
		} else {
			std::cout << "Move fail-safed.\n";
		} usleep(3000000);
	}
}

int main() {
	Hardware hand;
	hand.poise();

	stressTest(&hand, 10);
}
<|endoftext|>


<commit_before>// Copyright 2008-2009, Google Inc.
// 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 Google Inc. 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.

// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code.  Currently this tests:
//  Flash
//  Real
//  QuickTime
//  Windows Media Player
//    -this includes both WMP plugins.  npdsplay.dll is the older one that
//     comes with XP.  np-mswmp.dll can be downloaded from Microsoft and
//     needs SP2 or Vista.

#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>

#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/registry.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/default_plugin/plugin_impl.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kShortWaitTimeout = 10 * 1000;
const int kLongWaitTimeout  = 30 * 1000;

class PluginTest : public UITest {
 protected:
  virtual void SetUp() {
    const testing::TestInfo* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
      // The installer adds our process names to the registry key below.  Since
      // the installer might not have run on this machine, add it manually.
      RegKey regkey;
      if (regkey.Open(HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
                      KEY_WRITE)) {
        regkey.CreateKey(L"CHROME.EXE", KEY_READ);
      }
    } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
      // When testing the old WMP plugin, we need to force Chrome to not load
      // the new plugin.
      launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
    } else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
      launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
                                              L"security_tests.dll");
    }

    UITest::SetUp();
  }

  void TestPlugin(const std::wstring& test_case,
                  int timeout,
                  bool mock_http) {
    GURL url = GetTestUrl(test_case, mock_http);
    NavigateToURL(url);
    WaitForFinish(timeout, mock_http);
  }

  // Generate the URL for testing a particular test.
  // HTML for the tests is all located in test_directory\plugin\<testcase>
  // Set |mock_http| to true to use mock HTTP server.
  GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {
    if (mock_http)
      return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case);

    FilePath path;
    PathService::Get(chrome::DIR_TEST_DATA, &path);
    path = path.AppendASCII("plugin");
    path = path.Append(FilePath::FromWStringHack(test_case));
    return net::FilePathToFileURL(path);
  }

  // Waits for the test case to finish.
  void WaitForFinish(const int wait_time, bool mock_http) {
    const int kSleepTime = 500;      // 2 times per second
    const int kMaxIntervals = wait_time / kSleepTime;

    GURL url = GetTestUrl(L"done", mock_http);
    scoped_refptr<TabProxy> tab(GetActiveTab());

    std::string done_str;
    for (int i = 0; i < kMaxIntervals; ++i) {
      Sleep(kSleepTime);

      // The webpage being tested has javascript which sets a cookie
      // which signals completion of the test.
      std::string cookieName = kTestCompleteCookie;
      tab->GetCookieByName(url, cookieName, &done_str);
      if (!done_str.empty())
        break;
    }

    EXPECT_EQ(kTestCompleteSuccess, done_str);
  }
};

TEST_F(PluginTest, Quicktime) {
  TestPlugin(L"quicktime.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, MediaPlayerNew) {
  TestPlugin(L"wmp_new.html", kShortWaitTimeout, false);
}

// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
  TestPlugin(L"wmp_old.html", kLongWaitTimeout, false);
}

TEST_F(PluginTest, Real) {
  TestPlugin(L"real.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Flash) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashOctetStream) {
  TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashSecurity) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
  TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true);
}

// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
  TestPlugin(L"Java.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Silverlight) {
  TestPlugin(L"silverlight.html", kShortWaitTimeout, false);
}
<commit_msg>Disable flaky plugin tests. These keep causing bogus automatic tree closures.<commit_after>// Copyright 2008-2009, Google Inc.
// 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 Google Inc. 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.

// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code.  Currently this tests:
//  Flash
//  Real
//  QuickTime
//  Windows Media Player
//    -this includes both WMP plugins.  npdsplay.dll is the older one that
//     comes with XP.  np-mswmp.dll can be downloaded from Microsoft and
//     needs SP2 or Vista.

#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>

#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/registry.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/default_plugin/plugin_impl.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kShortWaitTimeout = 10 * 1000;
const int kLongWaitTimeout  = 30 * 1000;

class PluginTest : public UITest {
 protected:
  virtual void SetUp() {
    const testing::TestInfo* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
      // The installer adds our process names to the registry key below.  Since
      // the installer might not have run on this machine, add it manually.
      RegKey regkey;
      if (regkey.Open(HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
                      KEY_WRITE)) {
        regkey.CreateKey(L"CHROME.EXE", KEY_READ);
      }
    } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
      // When testing the old WMP plugin, we need to force Chrome to not load
      // the new plugin.
      launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
    } else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
      launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
                                              L"security_tests.dll");
    }

    UITest::SetUp();
  }

  void TestPlugin(const std::wstring& test_case,
                  int timeout,
                  bool mock_http) {
    GURL url = GetTestUrl(test_case, mock_http);
    NavigateToURL(url);
    WaitForFinish(timeout, mock_http);
  }

  // Generate the URL for testing a particular test.
  // HTML for the tests is all located in test_directory\plugin\<testcase>
  // Set |mock_http| to true to use mock HTTP server.
  GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {
    if (mock_http)
      return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case);

    FilePath path;
    PathService::Get(chrome::DIR_TEST_DATA, &path);
    path = path.AppendASCII("plugin");
    path = path.Append(FilePath::FromWStringHack(test_case));
    return net::FilePathToFileURL(path);
  }

  // Waits for the test case to finish.
  void WaitForFinish(const int wait_time, bool mock_http) {
    const int kSleepTime = 500;      // 2 times per second
    const int kMaxIntervals = wait_time / kSleepTime;

    GURL url = GetTestUrl(L"done", mock_http);
    scoped_refptr<TabProxy> tab(GetActiveTab());

    std::string done_str;
    for (int i = 0; i < kMaxIntervals; ++i) {
      Sleep(kSleepTime);

      // The webpage being tested has javascript which sets a cookie
      // which signals completion of the test.
      std::string cookieName = kTestCompleteCookie;
      tab->GetCookieByName(url, cookieName, &done_str);
      if (!done_str.empty())
        break;
    }

    EXPECT_EQ(kTestCompleteSuccess, done_str);
  }
};

TEST_F(PluginTest, Quicktime) {
  TestPlugin(L"quicktime.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, MediaPlayerNew) {
  TestPlugin(L"wmp_new.html", kShortWaitTimeout, false);
}

// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
  TestPlugin(L"wmp_old.html", kLongWaitTimeout, false);
}

TEST_F(PluginTest, Real) {
  TestPlugin(L"real.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, Flash) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashOctetStream) {
  TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false);
}

TEST_F(PluginTest, FlashSecurity) {
  TestPlugin(L"flash.html", kShortWaitTimeout, false);
}

// http://crbug.com/16114
// Disabled for http://crbug.com/21538
TEST_F(PluginTest, DISABLED_FlashLayoutWhilePainting) {
  TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true);
}

// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
  TestPlugin(L"Java.html", kShortWaitTimeout, false);
}

// Disabled for http://crbug.com/22666
TEST_F(PluginTest, DISABLED_Silverlight) {
  TestPlugin(L"silverlight.html", kShortWaitTimeout, false);
}
<|endoftext|>


<commit_before>#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601

#undef WINVER
#define WINVER 0x0601

#include "keyboard-layout-observer.h"

#include <string>
#include <windows.h>

using namespace v8;

std::string ToUTF8(const std::wstring& string) {
  if (string.length() < 1) {
    return std::string();
  }

  // NB: In the pathological case, each character could expand up
  // to 4 bytes in UTF8.
  int cbLen = (string.length()+1) * sizeof(char) * 4;
  char* buf = new char[cbLen];
  int retLen = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), string.length(), buf, cbLen, NULL, NULL);
  buf[retLen] = 0;

  std::string ret;
  ret.assign(buf);
  return ret;
}

std::wstring ToWString(const std::string& string) {
  if (string.length() < 1) {
    return std::wstring();
  }

  // NB: If you got really unlucky, every character could be a two-wchar_t
  // surrogate pair
  int cchLen = (string.length()+1) * 2;
  wchar_t* buf = new wchar_t[cchLen];
  int retLen = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), strlen(string.c_str()), buf, cchLen);
  buf[retLen] = 0;

  std::wstring ret;
  ret.assign(buf);
  return ret;
}

void KeyboardLayoutObserver::Init(Handle<Object> target) {
  NanScope();
  Local<FunctionTemplate> newTemplate = NanNew<FunctionTemplate>(KeyboardLayoutObserver::New);
  newTemplate->SetClassName(NanNew<String>("KeyboardLayoutObserver"));
  newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
  Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate();

  NODE_SET_METHOD(proto, "getCurrentKeyboardLayout", KeyboardLayoutObserver::GetCurrentKeyboardLayout);
  NODE_SET_METHOD(proto, "getInstalledKeyboardLayouts", KeyboardLayoutObserver::GetInstalledKeyboardLayouts);
  target->Set(NanNew<String>("KeyboardLayoutObserver"), newTemplate->GetFunction());
}

NODE_MODULE(keyboard_layout_observer, KeyboardLayoutObserver::Init)

NAN_METHOD(KeyboardLayoutObserver::New) {
  NanScope();

  Local<Function> callbackHandle = args[0].As<Function>();
  NanCallback *callback = new NanCallback(callbackHandle);

  KeyboardLayoutObserver *observer = new KeyboardLayoutObserver(callback);
  observer->Wrap(args.This());
  NanReturnUndefined();
}

KeyboardLayoutObserver::KeyboardLayoutObserver(NanCallback *callback) : callback(callback) {
}

KeyboardLayoutObserver::~KeyboardLayoutObserver() {
  delete callback;
};

void KeyboardLayoutObserver::HandleKeyboardLayoutChanged() {
}

NAN_METHOD(KeyboardLayoutObserver::GetCurrentKeyboardLayout) {
  NanScope();

  HKL layout = GetKeyboardLayout(0 /* Current Thread */);

  wchar_t buf[LOCALE_NAME_MAX_LENGTH];
  std::wstring wstr;
  LCIDToLocaleName(MAKELCID((UINT)layout, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
  wstr.assign(buf);

  std::string str = ToUTF8(wstr);
  NanReturnValue(NanNew<String>(str.data(), str.size()));
}

NAN_METHOD(KeyboardLayoutObserver::GetInstalledKeyboardLayouts) {
  NanScope();

  int layoutCount = GetKeyboardLayoutList(0, NULL);
  HKL* layouts = new HKL[layoutCount];
  GetKeyboardLayoutList(layoutCount, layouts);

  Local<Array> result = NanNew<Array>(layoutCount);
  wchar_t buf[LOCALE_NAME_MAX_LENGTH];

  for (int i=0; i < layoutCount; i++) {
    std::wstring wstr;
    LCIDToLocaleName(MAKELCID((UINT)layouts[i], SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
    wstr.assign(buf);

    std::string str = ToUTF8(wstr);
    result->Set(i, NanNew<String>(str.data(), str.size()));
  }

  delete[] layouts;
  NanReturnValue(result);
}
<commit_msg>Fix up Windows to match<commit_after>#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601

#undef WINVER
#define WINVER 0x0601

#include "keyboard-layout-observer.h"

#include <string>
#include <windows.h>

using namespace v8;

std::string ToUTF8(const std::wstring& string) {
  if (string.length() < 1) {
    return std::string();
  }

  // NB: In the pathological case, each character could expand up
  // to 4 bytes in UTF8.
  int cbLen = (string.length()+1) * sizeof(char) * 4;
  char* buf = new char[cbLen];
  int retLen = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), string.length(), buf, cbLen, NULL, NULL);
  buf[retLen] = 0;

  std::string ret;
  ret.assign(buf);
  return ret;
}

std::wstring ToWString(const std::string& string) {
  if (string.length() < 1) {
    return std::wstring();
  }

  // NB: If you got really unlucky, every character could be a two-wchar_t
  // surrogate pair
  int cchLen = (string.length()+1) * 2;
  wchar_t* buf = new wchar_t[cchLen];
  int retLen = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), strlen(string.c_str()), buf, cchLen);
  buf[retLen] = 0;

  std::wstring ret;
  ret.assign(buf);
  return ret;
}

void KeyboardLayoutObserver::Init(Handle<Object> target) {
  NanScope();
  Local<FunctionTemplate> newTemplate = NanNew<FunctionTemplate>(KeyboardLayoutObserver::New);
  newTemplate->SetClassName(NanNew<String>("KeyboardLayoutObserver"));
  newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
  Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate();

  NODE_SET_METHOD(proto, "getCurrentKeyboardLayout", KeyboardLayoutObserver::GetCurrentKeyboardLayout);
  NODE_SET_METHOD(proto, "getCurrentKeyboardLanguage", KeyboardLayoutObserver::GetCurrentKeyboardLanguage);
  NODE_SET_METHOD(proto, "getInstalledKeyboardLanguages", KeyboardLayoutObserver::GetInstalledKeyboardLanguages);
  target->Set(NanNew<String>("KeyboardLayoutObserver"), newTemplate->GetFunction());
}

NODE_MODULE(keyboard_layout_observer, KeyboardLayoutObserver::Init)

NAN_METHOD(KeyboardLayoutObserver::New) {
  NanScope();

  Local<Function> callbackHandle = args[0].As<Function>();
  NanCallback *callback = new NanCallback(callbackHandle);

  KeyboardLayoutObserver *observer = new KeyboardLayoutObserver(callback);
  observer->Wrap(args.This());
  NanReturnUndefined();
}

KeyboardLayoutObserver::KeyboardLayoutObserver(NanCallback *callback) : callback(callback) {
}

KeyboardLayoutObserver::~KeyboardLayoutObserver() {
  delete callback;
};

void KeyboardLayoutObserver::HandleKeyboardLayoutChanged() {
}

NAN_METHOD(KeyboardLayoutObserver::GetCurrentKeyboardLayout) {
  NanScope();

  char layoutName[KL_NAMELENGTH];
  if (::GetKeyboardLayoutName(layoutName))
    NanReturnValue(NanNew(layoutName));
  else
    NanReturnValue(NanUndefined());
}

NAN_METHOD(KeyboardLayoutObserver::GetCurrentKeyboardLanguage) {
  NanScope();

  HKL layout = GetKeyboardLayout(0 /* Current Thread */);

  wchar_t buf[LOCALE_NAME_MAX_LENGTH];
  std::wstring wstr;
  LCIDToLocaleName(MAKELCID((UINT)layout, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
  wstr.assign(buf);

  std::string str = ToUTF8(wstr);
  NanReturnValue(NanNew<String>(str.data(), str.size()));
}

NAN_METHOD(KeyboardLayoutObserver::GetInstalledKeyboardLanguages) {
  NanScope();

  int layoutCount = GetKeyboardLayoutList(0, NULL);
  HKL* layouts = new HKL[layoutCount];
  GetKeyboardLayoutList(layoutCount, layouts);

  Local<Array> result = NanNew<Array>(layoutCount);
  wchar_t buf[LOCALE_NAME_MAX_LENGTH];

  for (int i=0; i < layoutCount; i++) {
    std::wstring wstr;
    LCIDToLocaleName(MAKELCID((UINT)layouts[i], SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
    wstr.assign(buf);

    std::string str = ToUTF8(wstr);
    result->Set(i, NanNew<String>(str.data(), str.size()));
  }

  delete[] layouts;
  NanReturnValue(result);
}
<|endoftext|>


<commit_before>/*
 * endpoints_grammar_test.cpp
 *
 *  Created on: Jan 28, 2016
 *      Author: zmij
 */

#include <gtest/gtest.h>
#include <grammar/grammar_parse_test.hpp>
#include <wire/core/grammar/endpoint_parse.hpp>

namespace wire {
namespace core {
namespace test {

GRAMMAR_TEST(grammar::parse::inet_interface_grammar, InetInterface,
        ::testing::Values(
            "eth0[v4]", "lo[V6]"
        ),
        ::testing::Values(
            "eth1", "tun0[v5]", "lo["
        )
);

template < typename InputIterator >
using tcp_data_grammar =
        grammar::parse::ip_endpoint_data_grammar<
            InputIterator, detail::tcp_endpoint_data >;

GRAMMAR_TEST(tcp_data_grammar, TCPEndpoint,
        ::testing::Values(
            "127.0.0.1:10",
            "255.255.2.1:80",
            "10.0.254.1:3232",
            "192.0.2.33:7678",
            "google.com:8888",
            "www.mail.ru:765",
            "0.0.0.0:0",
            "[::8]:5678",
            "127.0.0.1:786",
            "[ffaa:1234::aadd:255.255.255.0]:567",
            "eth0[v4]:0",
            "lo[v6]:0"
        ),
        ::testing::Values(
            "255.255.2.1:456789",
            "10.0.254.1:-78",
            "192.0.2.33:bla",
            "127.0.0.256",
            "255.255.2.387",
            "400.0.254.1",
            "192.0..33"
        )
);

GRAMMAR_TEST(grammar::parse::socket_endpoint_grammar, SocketEndpoint,
    ::testing::Values(
        "/tmp/.socket", "/blabla/.123123/adfa/socket"
    ),
    ::testing::Values(
        "/", " "
    )
);

GRAMMAR_PARSE_TEST(grammar::parse::endpoint_grammar, Endpoint, endpoint,
    ::testing::Values(
        ParseEndpoint::make_test_data("tcp://localhost:5432",
                endpoint::tcp("localhost", 5432)),
        ParseEndpoint::make_test_data("tcp://0.0.0.0:0",
                endpoint::tcp("0.0.0.0", 0)),
        ParseEndpoint::make_test_data("ssl://aw.my.com:5432",
                endpoint::ssl("aw.my.com", 5432)),
        ParseEndpoint::make_test_data("udp://127.0.0.1:5432",
                endpoint::udp("127.0.0.1", 5432)),
        ParseEndpoint::make_test_data("socket:///tmp/.123.thasocket",
                endpoint::socket("/tmp/.123.thasocket"))
    )
);

template < typename InputIterator >
using endpoint_list_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_list >;
GRAMMAR_TEST(endpoint_list_grammar, EndpointList,
    ::testing::Values(
        "socket:///tmp/.socket,tcp://localhost:5432,udp://127.0.0.1:5432",
        "tcp://localhost:5432,socket:///tmp/.socket,udp://127.0.0.1:5432",
        "udp://127.0.0.1:5432,tcp://localhost:5432,socket:///tmp/.socket",
        "socket:///blabla/.123123/adfa/socket"
        "socket:///tmp/.wire.ping_pong,tcp://127.0.0.1:0"
        "tcp://eth0[v6]:0"
    ),
    ::testing::Values(
        "socket:///tmp/.socket, tcp://localhost:5432, udp://127.0.0.1:5432",
        "/", " "
    )
);

template < typename InputIterator >
using endpoint_set_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_set >;
GRAMMAR_TEST(endpoint_set_grammar, EndpointSet,
    ::testing::Values(
        "socket:///tmp/.socket,tcp://localhost:5432,udp://127.0.0.1:5432",
        "socket:///tmp/.socket,tcp://localhost:5432,udp://127.0.0.1:5432",
        "socket:///blabla/.123123/adfa/socket"
    ),
    ::testing::Values(
        "socket:///tmp/.socket, tcp://localhost:5432, udp://127.0.0.1:5432",
        "/", " "
    )
);

}  // namespace test
}  // namespace core
}  // namespace wire
<commit_msg>Fix incorrect unit test data<commit_after>/*
 * endpoints_grammar_test.cpp
 *
 *  Created on: Jan 28, 2016
 *      Author: zmij
 */

#include <gtest/gtest.h>
#include <grammar/grammar_parse_test.hpp>
#include <wire/core/grammar/endpoint_parse.hpp>

namespace wire {
namespace core {
namespace test {

GRAMMAR_TEST(grammar::parse::inet_interface_grammar, InetInterface,
        ::testing::Values(
            "eth0[v4]", "lo[V6]"
        ),
        ::testing::Values(
            "eth1", "tun0[v5]", "lo["
        )
);

template < typename InputIterator >
using tcp_data_grammar =
        grammar::parse::ip_endpoint_data_grammar<
            InputIterator, detail::tcp_endpoint_data >;

GRAMMAR_TEST(tcp_data_grammar, TCPEndpoint,
        ::testing::Values(
            "127.0.0.1:10",
            "255.255.2.1:80",
            "10.0.254.1:3232",
            "192.0.2.33:7678",
            "google.com:8888",
            "www.mail.ru:765",
            "0.0.0.0:0",
            "[::8]:5678",
            "127.0.0.1:786",
            "[ffaa:1234::aadd:255.255.255.0]:567",
            "eth0[v4]:0",
            "lo[v6]:0"
        ),
        ::testing::Values(
            "255.255.2.1:456789",
            "10.0.254.1:-78",
            "192.0.2.33:bla",
            "127.0.0.256",
            "255.255.2.387",
            "400.0.254.1",
            "192.0..33"
        )
);

GRAMMAR_TEST(grammar::parse::socket_endpoint_grammar, SocketEndpoint,
    ::testing::Values(
        "/tmp/.socket", "/blabla/.123123/adfa/socket"
    ),
    ::testing::Values(
        "/", " "
    )
);

GRAMMAR_PARSE_TEST(grammar::parse::endpoint_grammar, Endpoint, endpoint,
    ::testing::Values(
        ParseEndpoint::make_test_data("tcp://localhost:5432",
                endpoint::tcp("localhost", 5432)),
        ParseEndpoint::make_test_data("tcp://0.0.0.0:0",
                endpoint::tcp("0.0.0.0", 0)),
        ParseEndpoint::make_test_data("ssl://aw.my.com:5432",
                endpoint::ssl("aw.my.com", 5432)),
        ParseEndpoint::make_test_data("udp://127.0.0.1:5432",
                endpoint::udp("127.0.0.1", 5432)),
        ParseEndpoint::make_test_data("socket:///tmp/.123.thasocket",
                endpoint::socket("/tmp/.123.thasocket"))
    )
);

template < typename InputIterator >
using endpoint_list_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_list >;
GRAMMAR_TEST(endpoint_list_grammar, EndpointList,
    ::testing::Values(
        "socket:///tmp/.socket,tcp://localhost:5432,udp://127.0.0.1:5432",
        "tcp://localhost:5432,socket:///tmp/.socket,udp://127.0.0.1:5432",
        "udp://127.0.0.1:5432,tcp://localhost:5432,socket:///tmp/.socket",
        "socket:///blabla/.123123/adfa/socket",
        "socket:///tmp/.wire.ping_pong,tcp://127.0.0.1:0",
        "tcp://eth0[v6]:0,tcp://lo[v4]:0"
    ),
    ::testing::Values(
        "socket:///tmp/.socket, tcp://localhost:5432, udp://127.0.0.1:5432",
        "/", " "
    )
);

template < typename InputIterator >
using endpoint_set_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_set >;
GRAMMAR_TEST(endpoint_set_grammar, EndpointSet,
    ::testing::Values(
        "socket:///tmp/.socket,tcp://localhost:5432,udp://127.0.0.1:5432",
        "socket:///tmp/.socket,tcp://localhost:5432,udp://127.0.0.1:5432",
        "socket:///blabla/.123123/adfa/socket"
    ),
    ::testing::Values(
        "socket:///tmp/.socket, tcp://localhost:5432, udp://127.0.0.1:5432",
        "/", " "
    )
);

}  // namespace test
}  // namespace core
}  // namespace wire
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_PARTICLEEMITTER_HPP
#define NAZARA_PARTICLEEMITTER_HPP

#include <Nazara/Prerequesites.hpp>
#include <Nazara/Graphics/Config.hpp>
#include <Nazara/Utility/Node.hpp>

namespace Nz
{
	class ParticleMapper;
	class ParticleGroup;

	class NAZARA_GRAPHICS_API ParticleEmitter : public Node
	{
		public:
			ParticleEmitter();
			ParticleEmitter(const ParticleEmitter& emitter) = default;
			ParticleEmitter(ParticleEmitter&& emitter) = default;
			virtual ~ParticleEmitter();

			virtual void Emit(ParticleGroup& system, float elapsedTime) const;

			void EnableLagCompensation(bool enable);

			unsigned int GetEmissionCount() const;
			float GetEmissionRate() const;

			bool IsLagCompensationEnabled() const;

			void SetEmissionCount(unsigned int count);
			void SetEmissionRate(float rate);

			ParticleEmitter& operator=(const ParticleEmitter& emitter) = default;
			ParticleEmitter& operator=(ParticleEmitter&& emitter) = default;

		private:
			virtual void SetupParticles(ParticleMapper& mapper, unsigned int count) const = 0;

			bool m_lagCompensationEnabled;
			mutable float m_emissionAccumulator;
			float m_emissionRate;
			unsigned int m_emissionCount;
	};
}

#endif // NAZARA_PARTICLEEMITTER_HPP
<commit_msg>Graphics/ParticleEmitter: No longer inherit from Node<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_PARTICLEEMITTER_HPP
#define NAZARA_PARTICLEEMITTER_HPP

#include <Nazara/Prerequesites.hpp>
#include <Nazara/Graphics/Config.hpp>

namespace Nz
{
	class ParticleMapper;
	class ParticleGroup;

	class NAZARA_GRAPHICS_API ParticleEmitter
	{
		public:
			ParticleEmitter();
			ParticleEmitter(const ParticleEmitter& emitter) = default;
			ParticleEmitter(ParticleEmitter&& emitter) = default;
			virtual ~ParticleEmitter();

			virtual void Emit(ParticleGroup& system, float elapsedTime) const;

			void EnableLagCompensation(bool enable);

			unsigned int GetEmissionCount() const;
			float GetEmissionRate() const;

			bool IsLagCompensationEnabled() const;

			void SetEmissionCount(unsigned int count);
			void SetEmissionRate(float rate);

			ParticleEmitter& operator=(const ParticleEmitter& emitter) = default;
			ParticleEmitter& operator=(ParticleEmitter&& emitter) = default;

		private:
			virtual void SetupParticles(ParticleMapper& mapper, unsigned int count) const = 0;

			bool m_lagCompensationEnabled;
			mutable float m_emissionAccumulator;
			float m_emissionRate;
			unsigned int m_emissionCount;
	};
}

#endif // NAZARA_PARTICLEEMITTER_HPP
<|endoftext|>


<commit_before>#pragma once

#include <beluga/buffer/buffer_reader.hpp>

namespace beluga
{
    template <typename iterator_type>
    class protocol_reader
    {
    public:
	template <typename container_type>
	protocol_reader(const container_type& container);
	protocol_reader(iterator_type from, iterator_type to);

	virtual ~protocol_reader() = default;

	bool has_minimum_length(std::size_t length);

	buffer_reader<iterator_type>& get_reader();
	iterator_type get_to();

    private:
	buffer_reader<iterator_type> reader;
	iterator_type to;
    };
}

#include <beluga/protocol/protocol_reader.inl>
<commit_msg>changed visibility of get_reader and get_to to protected<commit_after>#pragma once

#include <beluga/buffer/buffer_reader.hpp>

namespace beluga
{
    template <typename iterator_type>
    class protocol_reader
    {
    public:
	template <typename container_type>
	protocol_reader(const container_type& container);
	protocol_reader(iterator_type from, iterator_type to);

	virtual ~protocol_reader() = default;

	bool has_minimum_length(std::size_t length);

    protected:
	buffer_reader<iterator_type>& get_reader();
	iterator_type get_to();

    private:
	buffer_reader<iterator_type> reader;
	iterator_type to;
    };
}

#include <beluga/protocol/protocol_reader.inl>
<|endoftext|>


<commit_before>#include "initializer.h"

#include <string>

#include <openssl/x509.h>
#include <boost/scoped_array.hpp>

#include "bootstrap/bootstrap.h"
#include "crypto/keymanager.h"
#include "logging/logging.h"

// Postcondition: device_id is in the storage
bool Initializer::initDeviceId() {
  // if device_id is already stored, just return
  std::string device_id;
  if (storage_->loadDeviceId(&device_id)) {
    return true;
  }

  // if device_id is specified in config, just use it, otherwise generate a  random one
  device_id = config_.device_id;
  if (device_id.empty()) {
    if (config_.mode == ProvisionMode::kAutomatic) {
      device_id = Utils::genPrettyName();
    } else if (config_.mode == ProvisionMode::kImplicit) {
      device_id = keys_.getCN();
    } else {
      LOG_ERROR << "Unknown provisioning method";
      return false;
    }
  }

  storage_->storeDeviceId(device_id);
  return true;
}
void Initializer::resetDeviceId() { storage_->clearDeviceId(); }

// Postcondition [(serial, hw_id)] is in the storage
bool Initializer::initEcuSerials() {
  EcuSerials ecu_serials;

  // TODO: the assumption now is that the set of connected ECUs doesn't change, but it might obviously
  //   not be the case. ECU discovery seems to be a big story and should be worked on accordingly.
  if (storage_->loadEcuSerials(&ecu_serials)) {
    return true;
  }

  std::string primary_ecu_serial_local = config_.primary_ecu_serial;
  if (primary_ecu_serial_local.empty()) {
    primary_ecu_serial_local = keys_.UptanePublicKey().KeyId();
  }

  std::string primary_ecu_hardware_id = config_.primary_ecu_hardware_id;
  if (primary_ecu_hardware_id.empty()) {
    primary_ecu_hardware_id = Utils::getHostname();
    if (primary_ecu_hardware_id == "") {
      return false;
    }
  }

  ecu_serials.emplace_back(Uptane::EcuSerial(primary_ecu_serial_local),
                           Uptane::HardwareIdentifier(primary_ecu_hardware_id));

  for (auto it = secondary_info_.begin(); it != secondary_info_.end(); ++it) {
    ecu_serials.emplace_back(it->second->getSerial(), it->second->getHwId());
  }

  storage_->storeEcuSerials(ecu_serials);
  return true;
}

void Initializer::resetEcuSerials() { storage_->clearEcuSerials(); }

// Postcondition: (public, private) is in the storage. It should not be stored until secondaries are provisioned
bool Initializer::initPrimaryEcuKeys() { return keys_.generateUptaneKeyPair().size() != 0u; }

void Initializer::resetEcuKeys() { storage_->clearPrimaryKeys(); }

bool Initializer::loadSetTlsCreds() {
  keys_.copyCertsToCurl(&http_client_);
  return keys_.isOk();
}

// Postcondition: TLS credentials are in the storage
InitRetCode Initializer::initTlsCreds() {
  if (loadSetTlsCreds()) {
    return InitRetCode::kOk;
  }

  if (config_.mode != ProvisionMode::kAutomatic) {
    LOG_ERROR << "Credentials not found";
    return InitRetCode::kStorageFailure;
  }

  // Autoprovision is needed and possible => autoprovision

  // set bootstrap credentials
  Bootstrap boot(config_.provision_path, config_.p12_password);
  http_client_.setCerts(boot.getCa(), CryptoSource::kFile, boot.getCert(), CryptoSource::kFile, boot.getPkey(),
                        CryptoSource::kFile);

  Json::Value data;
  std::string device_id;
  if (!storage_->loadDeviceId(&device_id)) {
    LOG_ERROR << "device_id unknown during autoprovisioning process";
    return InitRetCode::kStorageFailure;
  }
  data["deviceId"] = device_id;
  data["ttl"] = config_.expiry_days;
  HttpResponse response = http_client_.post(config_.server + "/devices", data);
  if (!response.isOk()) {
    Json::Value resp_code = response.getJson()["code"];
    if (resp_code.isString() && resp_code.asString() == "device_already_registered") {
      LOG_ERROR << "Device id" << device_id << "is occupied";
      return InitRetCode::kOccupied;
    }
    LOG_ERROR << "Autoprovisioning failed, response: " << response.body;
    return InitRetCode::kServerFailure;
  }

  std::string pkey;
  std::string cert;
  std::string ca;
  StructGuard<BIO> device_p12(BIO_new_mem_buf(response.body.c_str(), response.body.size()), BIO_vfree);
  if (!Crypto::parseP12(device_p12.get(), "", &pkey, &cert, &ca)) {
    LOG_ERROR << "Received a malformed P12 package from the server";
    return InitRetCode::kBadP12;
  }
  storage_->storeTlsCreds(ca, cert, pkey);

  // set provisioned credentials
  if (!loadSetTlsCreds()) {
    LOG_ERROR << "Failed to set provisioned credentials";
    return InitRetCode::kStorageFailure;
  }

  LOG_INFO << "Provisioned successfully on Device Gateway";
  return InitRetCode::kOk;
}

void Initializer::resetTlsCreds() {
  if (config_.mode != ProvisionMode::kImplicit) {
    storage_->clearTlsCreds();
  }
}

// Postcondition: "ECUs registered" flag set in the storage
InitRetCode Initializer::initEcuRegister() {
  if (storage_->loadEcuRegistered()) {
    return InitRetCode::kOk;
  }

  PublicKey uptane_public_key = keys_.UptanePublicKey();

  if (uptane_public_key.Type() == KeyType::kUnknown) {
    return InitRetCode::kStorageFailure;
  }

  EcuSerials ecu_serials;
  // initEcuSerials should have been called by this point
  if (!storage_->loadEcuSerials(&ecu_serials) || ecu_serials.size() < 1) {
    return InitRetCode::kStorageFailure;
  }

  Json::Value all_ecus;
  all_ecus["primary_ecu_serial"] = ecu_serials[0].first.ToString();
  all_ecus["ecus"] = Json::arrayValue;
  {
    Json::Value primary_ecu;
    primary_ecu["hardware_identifier"] = ecu_serials[0].second.ToString();
    primary_ecu["ecu_serial"] = ecu_serials[0].first.ToString();
    primary_ecu["clientKey"] = keys_.UptanePublicKey().ToUptane();
    all_ecus["ecus"].append(primary_ecu);
  }

  for (auto it = secondary_info_.cbegin(); it != secondary_info_.cend(); it++) {
    Json::Value ecu;
    auto public_key = it->second->getPublicKey();
    ecu["hardware_identifier"] = it->second->getHwId().ToString();
    ecu["ecu_serial"] = it->second->getSerial().ToString();
    ecu["clientKey"] = public_key.ToUptane();
    all_ecus["ecus"].append(ecu);
  }

  HttpResponse response = http_client_.post(config_.ecu_registration_endpoint, all_ecus);
  if (!response.isOk()) {
    Json::Value resp_code = response.getJson()["code"];
    if (resp_code.isString() &&
        (resp_code.asString() == "ecu_already_registered" || resp_code.asString() == "device_already_registered")) {
      LOG_ERROR << "Some ECU is already registered";
      return InitRetCode::kOccupied;
    }
    LOG_ERROR << "Error registering device on Uptane, response: " << response.body;
    return InitRetCode::kServerFailure;
  }
  // do not call storage_->storeEcuRegistered(), it will be called from the top-level Init function after the
  // acknowledgement
  LOG_INFO << "ECUs have been successfully registered to the server";
  return InitRetCode::kOk;
}

// Postcondition: "ECUs registered" flag set in the storage
Initializer::Initializer(
    const ProvisionConfig& config_in, std::shared_ptr<INvStorage> storage_in, HttpInterface& http_client_in,
    KeyManager& keys_in,
    const std::map<Uptane::EcuSerial, std::shared_ptr<Uptane::SecondaryInterface> >& secondary_info_in)
    : config_(config_in),
      storage_(std::move(storage_in)),
      http_client_(http_client_in),
      keys_(keys_in),
      secondary_info_(secondary_info_in) {
  success_ = false;
  for (int i = 0; i < MaxInitializationAttempts; i++) {
    if (!initDeviceId()) {
      LOG_ERROR << "Device ID generation failed, abort initialization";
      return;
    }

    InitRetCode ret_code = initTlsCreds();
    // if a device with the same ID has already been registered to the server,
    // generate a new one
    if (ret_code == InitRetCode::kOccupied) {
      resetDeviceId();
      LOG_INFO << "Device name is already registered, restart";
      continue;
    }
    if (ret_code != InitRetCode::kOk) {
      LOG_ERROR << "Autoprovisioning failed, abort initialization";
      return;
    }

    if (!initPrimaryEcuKeys()) {
      LOG_ERROR << "ECU key generation failed, abort initialization";
      return;
    }
    if (!initEcuSerials()) {
      LOG_ERROR << "ECU serial generation failed, abort initialization";
      return;
    }

    ret_code = initEcuRegister();
    // if ECUs with same ID have been registered to the server, we don't have a
    // clear remediation path right now, just ignore the error
    if (ret_code == InitRetCode::kOccupied) {
      LOG_INFO << "ECU serial is already registered";
    } else if (ret_code != InitRetCode::kOk) {
      LOG_ERROR << "ECU registration failed, abort initialization";
      return;
    }

    // TODO: acknowledge on server _before_ setting the flag
    storage_->storeEcuRegistered();
    success_ = true;
    return;
  }
  LOG_ERROR << "Initialization failed after " << MaxInitializationAttempts << " attempts";
}
<commit_msg>Better error message.<commit_after>#include "initializer.h"

#include <string>

#include <openssl/x509.h>
#include <boost/scoped_array.hpp>

#include "bootstrap/bootstrap.h"
#include "crypto/keymanager.h"
#include "logging/logging.h"

// Postcondition: device_id is in the storage
bool Initializer::initDeviceId() {
  // if device_id is already stored, just return
  std::string device_id;
  if (storage_->loadDeviceId(&device_id)) {
    return true;
  }

  // if device_id is specified in config, just use it, otherwise generate a  random one
  device_id = config_.device_id;
  if (device_id.empty()) {
    if (config_.mode == ProvisionMode::kAutomatic) {
      device_id = Utils::genPrettyName();
    } else if (config_.mode == ProvisionMode::kImplicit) {
      device_id = keys_.getCN();
    } else {
      LOG_ERROR << "Unknown provisioning method";
      return false;
    }
  }

  storage_->storeDeviceId(device_id);
  return true;
}
void Initializer::resetDeviceId() { storage_->clearDeviceId(); }

// Postcondition [(serial, hw_id)] is in the storage
bool Initializer::initEcuSerials() {
  EcuSerials ecu_serials;

  // TODO: the assumption now is that the set of connected ECUs doesn't change, but it might obviously
  //   not be the case. ECU discovery seems to be a big story and should be worked on accordingly.
  if (storage_->loadEcuSerials(&ecu_serials)) {
    return true;
  }

  std::string primary_ecu_serial_local = config_.primary_ecu_serial;
  if (primary_ecu_serial_local.empty()) {
    primary_ecu_serial_local = keys_.UptanePublicKey().KeyId();
  }

  std::string primary_ecu_hardware_id = config_.primary_ecu_hardware_id;
  if (primary_ecu_hardware_id.empty()) {
    primary_ecu_hardware_id = Utils::getHostname();
    if (primary_ecu_hardware_id == "") {
      return false;
    }
  }

  ecu_serials.emplace_back(Uptane::EcuSerial(primary_ecu_serial_local),
                           Uptane::HardwareIdentifier(primary_ecu_hardware_id));

  for (auto it = secondary_info_.begin(); it != secondary_info_.end(); ++it) {
    ecu_serials.emplace_back(it->second->getSerial(), it->second->getHwId());
  }

  storage_->storeEcuSerials(ecu_serials);
  return true;
}

void Initializer::resetEcuSerials() { storage_->clearEcuSerials(); }

// Postcondition: (public, private) is in the storage. It should not be stored until secondaries are provisioned
bool Initializer::initPrimaryEcuKeys() { return keys_.generateUptaneKeyPair().size() != 0u; }

void Initializer::resetEcuKeys() { storage_->clearPrimaryKeys(); }

bool Initializer::loadSetTlsCreds() {
  keys_.copyCertsToCurl(&http_client_);
  return keys_.isOk();
}

// Postcondition: TLS credentials are in the storage
InitRetCode Initializer::initTlsCreds() {
  if (loadSetTlsCreds()) {
    return InitRetCode::kOk;
  }

  if (config_.mode != ProvisionMode::kAutomatic) {
    LOG_ERROR << "Credentials not found";
    return InitRetCode::kStorageFailure;
  }

  // Autoprovision is needed and possible => autoprovision

  // set bootstrap credentials
  Bootstrap boot(config_.provision_path, config_.p12_password);
  http_client_.setCerts(boot.getCa(), CryptoSource::kFile, boot.getCert(), CryptoSource::kFile, boot.getPkey(),
                        CryptoSource::kFile);

  Json::Value data;
  std::string device_id;
  if (!storage_->loadDeviceId(&device_id)) {
    LOG_ERROR << "device_id unknown during autoprovisioning process";
    return InitRetCode::kStorageFailure;
  }
  data["deviceId"] = device_id;
  data["ttl"] = config_.expiry_days;
  HttpResponse response = http_client_.post(config_.server + "/devices", data);
  if (!response.isOk()) {
    Json::Value resp_code = response.getJson()["code"];
    if (resp_code.isString() && resp_code.asString() == "device_already_registered") {
      LOG_ERROR << "Device id" << device_id << "is occupied";
      return InitRetCode::kOccupied;
    }
    LOG_ERROR << "Autoprovisioning failed, response: " << response.body;
    return InitRetCode::kServerFailure;
  }

  std::string pkey;
  std::string cert;
  std::string ca;
  StructGuard<BIO> device_p12(BIO_new_mem_buf(response.body.c_str(), response.body.size()), BIO_vfree);
  if (!Crypto::parseP12(device_p12.get(), "", &pkey, &cert, &ca)) {
    LOG_ERROR << "Received a malformed P12 package from the server";
    return InitRetCode::kBadP12;
  }
  storage_->storeTlsCreds(ca, cert, pkey);

  // set provisioned credentials
  if (!loadSetTlsCreds()) {
    LOG_ERROR << "Failed to set provisioned credentials";
    return InitRetCode::kStorageFailure;
  }

  LOG_INFO << "Provisioned successfully on Device Gateway";
  return InitRetCode::kOk;
}

void Initializer::resetTlsCreds() {
  if (config_.mode != ProvisionMode::kImplicit) {
    storage_->clearTlsCreds();
  }
}

// Postcondition: "ECUs registered" flag set in the storage
InitRetCode Initializer::initEcuRegister() {
  if (storage_->loadEcuRegistered()) {
    return InitRetCode::kOk;
  }

  PublicKey uptane_public_key = keys_.UptanePublicKey();

  if (uptane_public_key.Type() == KeyType::kUnknown) {
    return InitRetCode::kStorageFailure;
  }

  EcuSerials ecu_serials;
  // initEcuSerials should have been called by this point
  if (!storage_->loadEcuSerials(&ecu_serials) || ecu_serials.size() < 1) {
    return InitRetCode::kStorageFailure;
  }

  Json::Value all_ecus;
  all_ecus["primary_ecu_serial"] = ecu_serials[0].first.ToString();
  all_ecus["ecus"] = Json::arrayValue;
  {
    Json::Value primary_ecu;
    primary_ecu["hardware_identifier"] = ecu_serials[0].second.ToString();
    primary_ecu["ecu_serial"] = ecu_serials[0].first.ToString();
    primary_ecu["clientKey"] = keys_.UptanePublicKey().ToUptane();
    all_ecus["ecus"].append(primary_ecu);
  }

  for (auto it = secondary_info_.cbegin(); it != secondary_info_.cend(); it++) {
    Json::Value ecu;
    auto public_key = it->second->getPublicKey();
    ecu["hardware_identifier"] = it->second->getHwId().ToString();
    ecu["ecu_serial"] = it->second->getSerial().ToString();
    ecu["clientKey"] = public_key.ToUptane();
    all_ecus["ecus"].append(ecu);
  }

  HttpResponse response = http_client_.post(config_.ecu_registration_endpoint, all_ecus);
  if (!response.isOk()) {
    Json::Value resp_code = response.getJson()["code"];
    if (resp_code.isString() &&
        (resp_code.asString() == "ecu_already_registered" || resp_code.asString() == "device_already_registered")) {
      LOG_ERROR << "Some ECU is already registered";
      return InitRetCode::kOccupied;
    }
    LOG_ERROR << "Error registering device on Uptane, response: " << response.body;
    return InitRetCode::kServerFailure;
  }
  // do not call storage_->storeEcuRegistered(), it will be called from the top-level Init function after the
  // acknowledgement
  LOG_INFO << "ECUs have been successfully registered to the server";
  return InitRetCode::kOk;
}

// Postcondition: "ECUs registered" flag set in the storage
Initializer::Initializer(
    const ProvisionConfig& config_in, std::shared_ptr<INvStorage> storage_in, HttpInterface& http_client_in,
    KeyManager& keys_in,
    const std::map<Uptane::EcuSerial, std::shared_ptr<Uptane::SecondaryInterface> >& secondary_info_in)
    : config_(config_in),
      storage_(std::move(storage_in)),
      http_client_(http_client_in),
      keys_(keys_in),
      secondary_info_(secondary_info_in) {
  success_ = false;
  for (int i = 0; i < MaxInitializationAttempts; i++) {
    if (!initDeviceId()) {
      LOG_ERROR << "Device ID generation failed, abort initialization";
      return;
    }

    InitRetCode ret_code = initTlsCreds();
    // if a device with the same ID has already been registered to the server,
    // generate a new one
    if (ret_code == InitRetCode::kOccupied) {
      resetDeviceId();
      LOG_INFO << "Device name is already registered, restart";
      continue;
    } else if (ret_code == InitRetCode::kStorageFailure) {
      LOG_ERROR << "Error reading existing provisioning data from storage";
      return;
    } else if (ret_code != InitRetCode::kOk) {
      LOG_ERROR << "Autoprovisioning failed, abort initialization";
      return;
    }

    if (!initPrimaryEcuKeys()) {
      LOG_ERROR << "ECU key generation failed, abort initialization";
      return;
    }
    if (!initEcuSerials()) {
      LOG_ERROR << "ECU serial generation failed, abort initialization";
      return;
    }

    ret_code = initEcuRegister();
    // if ECUs with same ID have been registered to the server, we don't have a
    // clear remediation path right now, just ignore the error
    if (ret_code == InitRetCode::kOccupied) {
      LOG_INFO << "ECU serial is already registered";
    } else if (ret_code != InitRetCode::kOk) {
      LOG_ERROR << "ECU registration failed, abort initialization";
      return;
    }

    // TODO: acknowledge on server _before_ setting the flag
    storage_->storeEcuRegistered();
    success_ = true;
    return;
  }
  LOG_ERROR << "Initialization failed after " << MaxInitializationAttempts << " attempts";
}
<|endoftext|>


<commit_before>
#include "../../expat/escape_json.h"
#include "output_csv.h"

bool Output_CSV::write_http_headers()
{
  std::cout<<"Content-type: text/csv\n";
  return true;
}

// Escape CSV output according to RFC 4180
std::string escape_csv(const std::string& input)
{
  std::string result;
  bool quotes_needed = false;

  for (int i = input.size() - 1; i >= 0; --i)
  {
    if (input[i] == '\n' || input[i] == ',')
      quotes_needed = true;
    else if (input[i] == '\"')
    {
      quotes_needed = true;
      if (result.empty())
        result = input.substr(0, i) + "\"" + input.substr(i);
      else
        result = result.substr(0, i) + "\"" + result.substr(i);
    }
  }

  if (!quotes_needed)
    return input;
  else if (result.empty())
    return std::string("\"") + input + "\"";
  else
    return std::string("\"") + result + "\"";
}

void Output_CSV::write_payload_header
    (const std::string& db_dir, const std::string& timestamp, const std::string& area_timestamp)
{
  if (csv_settings.with_headerline)
  {
    for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();
        it != csv_settings.keyfields.end(); ++it)
    {
      std::cout<<(it->second ? "@" : "")<<escape_csv(it->first);
      if (it + 1 != csv_settings.keyfields.end())
        std::cout<<csv_settings.separator;
    }
    std::cout<<'\n';
  }
}

void Output_CSV::write_footer()
{
  // Intentionally empty
}

void Output_CSV::display_remark(const std::string& text)
{
  // Intentionally empty
}

void Output_CSV::display_error(const std::string& text)
{
  // Intentionally empty
}

std::string Output_CSV::dump_config() const
{
  std::string result = "(";

  for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();
      it != csv_settings.keyfields.end(); ++it)
  {
    if (it != csv_settings.keyfields.begin())
      result += ",";

    if (it->second)
      result += "::" + it->first;
    else
      result += "\"" + escape_cstr(it->first) + "\"";
  }

  if (csv_settings.separator != "\t")
    result += std::string(";") + (csv_settings.with_headerline ? "true" : "false") + ";\""
        + escape_cstr(csv_settings.separator) + "\"";
  else if (!csv_settings.with_headerline)
    result += ";false";

  return result + ")";
}

template< typename OSM_Element_Metadata_Skeleton >
void print_meta(const std::string& keyfield,
    const OSM_Element_Metadata_Skeleton& meta, const std::map< uint32, std::string >* users)
{
  if (keyfield == "version")
    std::cout<<meta.version;
  else if (keyfield == "timestamp")
    std::cout<<Timestamp(meta.timestamp).str();
  else if (keyfield == "changeset")
    std::cout<<meta.changeset;
  else if (keyfield == "uid")
    std::cout<<meta.user_id;
  else if (users && keyfield == "user")
  {
    std::map< uint32, std::string >::const_iterator uit = users->find(meta.user_id);
    if (uit != users->end())
      std::cout<<uit->second;
  }
}

template< >
void print_meta< int >(const std::string& keyfield,
    const int& meta, const std::map< uint32, std::string >* users) {}

template< typename Id_Type, typename OSM_Element_Metadata_Skeleton >
void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaque_Geometry& geometry,
    const OSM_Element_Metadata_Skeleton* meta,
    const std::vector< std::pair< std::string, std::string> >* tags,
    const std::map< uint32, std::string >* users,
    const Csv_Settings& csv_settings,
    Output_Mode mode)
{
  std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();
  while (true)
  {
    if (!it->second)
    {
      if (tags)
      {
	for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin();
	     it_tags != tags->end(); ++it_tags)
	{
	  if (it_tags->first == it->first)
	  {
	    std::cout<<escape_csv(it_tags->second);
	    break;
	  }
	}
      }
    }
    else
    {
      if (meta)
        print_meta(it->first, *meta, users);

      if (it->first == "id")
      {
        if (mode.mode & Output_Mode::ID)
          std::cout<<id.val();
      }
      else if (it->first == "otype")
        std::cout<<otype;
      else if (it->first == "type")
	std::cout<<type;
      else if (it->first == "lat")
      {
        if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))
	    && geometry.has_center())
          std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lat();
      }
      else if (it->first == "lon")
      {
        if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))
	    && geometry.has_center())
          std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lon();
      }
    }

    if (++it == csv_settings.keyfields.end())
      break;
    std::cout<<csv_settings.separator;
  }
  std::cout<<"\n";
}

void Output_CSV::print_item(const Node_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta,
      const std::map< uint32, std::string >* users,
      Output_Mode mode,
      const Feature_Action& action,
      const Node_Skeleton* new_skel,
      const Opaque_Geometry* new_geometry,
      const std::vector< std::pair< std::string, std::string > >* new_tags,
      const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta)
{
  process_csv_line(1, "node", skel.id, geometry, meta, tags, users, csv_settings, mode);
}

void Output_CSV::print_item(const Way_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta,
      const std::map< uint32, std::string >* users,
      Output_Mode mode,
      const Feature_Action& action,
      const Way_Skeleton* new_skel,
      const Opaque_Geometry* new_geometry,
      const std::vector< std::pair< std::string, std::string > >* new_tags,
      const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta)
{
  process_csv_line(2, "way", skel.id, geometry, meta, tags, users, csv_settings, mode);
}

void Output_CSV::print_item(const Relation_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta,
      const std::map< uint32, std::string >* roles,
      const std::map< uint32, std::string >* users,
      Output_Mode mode,
      const Feature_Action& action,
      const Relation_Skeleton* new_skel,
      const Opaque_Geometry* new_geometry,
      const std::vector< std::pair< std::string, std::string > >* new_tags,
      const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta)
{
  process_csv_line(3, "relation", skel.id, geometry, meta, tags, users, csv_settings, mode);
}

void Output_CSV::print_item(const Derived_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      Output_Mode mode)
{
  process_csv_line< Derived_Skeleton::Id_Type, int >(
      4, skel.type_name, skel.id, geometry, 0, tags, 0, csv_settings, mode);
}
<commit_msg>Fix CSV output for out count<commit_after>
#include "../../expat/escape_json.h"
#include "output_csv.h"

bool Output_CSV::write_http_headers()
{
  std::cout<<"Content-type: text/csv\n";
  return true;
}

// Escape CSV output according to RFC 4180
std::string escape_csv(const std::string& input)
{
  std::string result;
  bool quotes_needed = false;

  for (int i = input.size() - 1; i >= 0; --i)
  {
    if (input[i] == '\n' || input[i] == ',')
      quotes_needed = true;
    else if (input[i] == '\"')
    {
      quotes_needed = true;
      if (result.empty())
        result = input.substr(0, i) + "\"" + input.substr(i);
      else
        result = result.substr(0, i) + "\"" + result.substr(i);
    }
  }

  if (!quotes_needed)
    return input;
  else if (result.empty())
    return std::string("\"") + input + "\"";
  else
    return std::string("\"") + result + "\"";
}

void Output_CSV::write_payload_header
    (const std::string& db_dir, const std::string& timestamp, const std::string& area_timestamp)
{
  if (csv_settings.with_headerline)
  {
    for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();
        it != csv_settings.keyfields.end(); ++it)
    {
      std::cout<<(it->second ? "@" : "")<<escape_csv(it->first);
      if (it + 1 != csv_settings.keyfields.end())
        std::cout<<csv_settings.separator;
    }
    std::cout<<'\n';
  }
}

void Output_CSV::write_footer()
{
  // Intentionally empty
}

void Output_CSV::display_remark(const std::string& text)
{
  // Intentionally empty
}

void Output_CSV::display_error(const std::string& text)
{
  // Intentionally empty
}

std::string Output_CSV::dump_config() const
{
  std::string result = "(";

  for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();
      it != csv_settings.keyfields.end(); ++it)
  {
    if (it != csv_settings.keyfields.begin())
      result += ",";

    if (it->second)
      result += "::" + it->first;
    else
      result += "\"" + escape_cstr(it->first) + "\"";
  }

  if (csv_settings.separator != "\t")
    result += std::string(";") + (csv_settings.with_headerline ? "true" : "false") + ";\""
        + escape_cstr(csv_settings.separator) + "\"";
  else if (!csv_settings.with_headerline)
    result += ";false";

  return result + ")";
}

template< typename OSM_Element_Metadata_Skeleton >
void print_meta(const std::string& keyfield,
    const OSM_Element_Metadata_Skeleton& meta, const std::map< uint32, std::string >* users)
{
  if (keyfield == "version")
    std::cout<<meta.version;
  else if (keyfield == "timestamp")
    std::cout<<Timestamp(meta.timestamp).str();
  else if (keyfield == "changeset")
    std::cout<<meta.changeset;
  else if (keyfield == "uid")
    std::cout<<meta.user_id;
  else if (users && keyfield == "user")
  {
    std::map< uint32, std::string >::const_iterator uit = users->find(meta.user_id);
    if (uit != users->end())
      std::cout<<uit->second;
  }
}

template< >
void print_meta< int >(const std::string& keyfield,
    const int& meta, const std::map< uint32, std::string >* users) {}

std::string get_count_tag(const std::vector< std::pair< std::string, std::string> >* tags, std::string tag)
{
  if (tags)
    for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin();
         it_tags != tags->end(); ++it_tags)
      if (it_tags->first == tag)
        return it_tags->second;
  return "0";
}

template< typename Id_Type, typename OSM_Element_Metadata_Skeleton >
void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaque_Geometry& geometry,
    const OSM_Element_Metadata_Skeleton* meta,
    const std::vector< std::pair< std::string, std::string> >* tags,
    const std::map< uint32, std::string >* users,
    const Csv_Settings& csv_settings,
    Output_Mode mode)
{
  std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();
  while (true)
  {
    if (!it->second)
    {
      if (tags)
      {
	for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin();
	     it_tags != tags->end(); ++it_tags)
	{
	  if (it_tags->first == it->first)
	  {
	    std::cout<<escape_csv(it_tags->second);
	    break;
	  }
	}
      }
    }
    else
    {
      if (meta)
        print_meta(it->first, *meta, users);

      if (it->first == "id")
      {
        if (mode.mode & Output_Mode::ID)
          std::cout<<id.val();
      }
      else if (it->first == "otype")
        std::cout<<otype;
      else if (it->first == "type")
	std::cout<<type;
      else if (it->first == "lat")
      {
        if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))
	    && geometry.has_center())
          std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lat();
      }
      else if (it->first == "lon")
      {
        if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))
	    && geometry.has_center())
          std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lon();
      }
      if (type == "count")
      {
        if (it->first == "count")
          std::cout << get_count_tag(tags, "total");
        else if (it->first == "count:nodes")
          std::cout << get_count_tag(tags, "nodes");
        else if (it->first == "count:ways")
          std::cout << get_count_tag(tags, "ways");
        else if (it->first == "count:relations")
          std::cout << get_count_tag(tags, "relations");
        else if (it->first == "count:areas")
          std::cout << get_count_tag(tags, "areas");
      }
    }

    if (++it == csv_settings.keyfields.end())
      break;
    std::cout<<csv_settings.separator;
  }
  std::cout<<"\n";
}

void Output_CSV::print_item(const Node_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta,
      const std::map< uint32, std::string >* users,
      Output_Mode mode,
      const Feature_Action& action,
      const Node_Skeleton* new_skel,
      const Opaque_Geometry* new_geometry,
      const std::vector< std::pair< std::string, std::string > >* new_tags,
      const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta)
{
  process_csv_line(1, "node", skel.id, geometry, meta, tags, users, csv_settings, mode);
}

void Output_CSV::print_item(const Way_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta,
      const std::map< uint32, std::string >* users,
      Output_Mode mode,
      const Feature_Action& action,
      const Way_Skeleton* new_skel,
      const Opaque_Geometry* new_geometry,
      const std::vector< std::pair< std::string, std::string > >* new_tags,
      const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta)
{
  process_csv_line(2, "way", skel.id, geometry, meta, tags, users, csv_settings, mode);
}

void Output_CSV::print_item(const Relation_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta,
      const std::map< uint32, std::string >* roles,
      const std::map< uint32, std::string >* users,
      Output_Mode mode,
      const Feature_Action& action,
      const Relation_Skeleton* new_skel,
      const Opaque_Geometry* new_geometry,
      const std::vector< std::pair< std::string, std::string > >* new_tags,
      const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta)
{
  process_csv_line(3, "relation", skel.id, geometry, meta, tags, users, csv_settings, mode);
}

void Output_CSV::print_item(const Derived_Skeleton& skel,
      const Opaque_Geometry& geometry,
      const std::vector< std::pair< std::string, std::string > >* tags,
      Output_Mode mode)
{
  process_csv_line< Derived_Skeleton::Id_Type, int >(
      4, skel.type_name, skel.id, geometry, 0, tags, 0, csv_settings, mode);
}
<|endoftext|>