<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dxfgrprd.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:55:40 $
 *
 *  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 _DXFGRPRD_HXX
#define _DXFGRPRD_HXX

#include <svtools/fltcall.hxx>

#define DXF_MAX_STRING_LEN 256 // Max Stringlaenge (ohne die 0)

class DXFGroupReader
{

public:

    // Anmerkkung:
    // sizeof(DXFGroupReader) ist gross, also nur dynamisch anlegen!

    DXFGroupReader(SvStream & rIStream,
                   PFilterCallback pCallback, void * pCallerData,
                   USHORT nMinPercent, USHORT nMaxPercent);

    BOOL GetStatus();

    void SetError();

    USHORT Read();
        // Liesst die naechste Gruppe ein und liefert den Gruppencode zurueck.
        // Im Falle eines Fehlers liefert GetStatus() FALSE, Gruppencode wird 0
        // gesetzt, und es wird SetS(0,"EOF") ausgefuehrt.

    USHORT GetG();
        // Liefert den letzten Gruppencode (also was Read() zuletzt lieferte)

    long   GetI();
        // Liefert den Integer-Wert zur Gruppe, die vorher mit Read() gelesen wurde.
        // Dabei muss es sich um einen Gruppencode fuer den Datentyp Integer
        // gehandelt haben, wenn nicht, wird 0 gelieferet.

    double GetF();
        // Liefert den Floatingpoint-Wert zur Gruppe, die vorher mit Read() gelesen wurde.
        // Dabei muss es sich um einen Gruppencode fuer den Datentyp Floatingpoint
        // gehandelt haben, wenn nicht, wird 0 geliefert.

    const char * GetS();
        // Liefert den String zur Gruppe, die vorher mit Read() gelesen wurde.
        // Dabei muss es sich um einen Gruppencode fuer den Datentyp String
        // gehandelt haben, wenn nicht, wird NULL geliefert.

    // Folgende drei Methoden arbeiten wie die obigen, nur kann auch ein anderer als der
    // aktuelle Gruppencode angegeben werden. (DXFGroupReader speichert die Parameter
    // zu allen Gruppencodes. Dadurch ist es moeglich, dass zunaechst mit Read() einige
    // verschiedene Gruppen eingelesen werden, bevor sie ausgewertet werden.)
    long         GetI(USHORT nG);
    double       GetF(USHORT nG);
    const char * GetS(USHORT nG);

    // Mit folgenden Methoden koennen die aktuell gespeicherten Werte zu den
    // Gruppencodes veraendert werden. (z.B. um Defaultwerte zu setzen, bevor
    // 'blind' eine Menge von Gruppen eingelesen wird.)
    void SetI(USHORT nG, long nI);
    void SetF(USHORT nG, double fF);
    void SetS(USHORT nG, const char * sS); // (wird kopiert)

private:

    void   FillIBuff();
    char   ReadChar();
    void   ReadLine(char * ptgt);
    long   ReadI();
    double ReadF();
    void   ReadS(char * ptgt);

    SvStream & rIS;
    char sIBuff[1024];
    USHORT nIBuffSize,nIBuffPos;
    BOOL bStatus;
    USHORT nLastG;
    ULONG nGCount;

    PFilterCallback pCallback;
    void * pCallerData;
    ULONG nMinPercent;
    ULONG nMaxPercent;
    ULONG nLastPercent;
    ULONG nFileSize;

    char   S0_9      [10][DXF_MAX_STRING_LEN+1]; // Strings  Gruppencodes 0..9
    double F10_59    [50];      // Floats   Gruppencodes 10..59
    long   I60_79    [20];      // Integers Gruppencodes 60..79
    long   I90_99    [10];
    char   S100      [DXF_MAX_STRING_LEN+1];
    char   S102      [DXF_MAX_STRING_LEN+1];
    double F140_147  [ 8];      // Floats   Gruppencodes 140..147
    long   I170_175  [ 6];      // Integers Gruppencodes 170..175
    double F210_239  [30];      // Floats   Gruppencodes 210..239
    char   S999_1009 [11][DXF_MAX_STRING_LEN+1]; // Strings  Gruppencodes 999..1009
    double F1010_1059[50];      // Floats   Gruppencodes 1010..1059
    long   I1060_1079[20];      // Integers Gruppencodes 1060..1079

};

inline BOOL DXFGroupReader::GetStatus()
{
    return bStatus;
}

inline void DXFGroupReader::SetError()
{
    bStatus=FALSE;
}

inline USHORT DXFGroupReader::GetG()
{
    return nLastG;
}

inline long DXFGroupReader::GetI()
{
    return GetI(nLastG);
}

inline double DXFGroupReader::GetF()
{
    return GetF(nLastG);
}

inline const char * DXFGroupReader::GetS()
{
    return GetS(nLastG);
}

inline char DXFGroupReader::ReadChar()
{
    if (nIBuffPos>=nIBuffSize) FillIBuff();
    return sIBuff[nIBuffPos++];
}

#endif

<commit_msg>INTEGRATION: CWS aw024 (1.3.220); FILE MERGED 2005/09/20 04:43:08 aw 1.3.220.2: RESYNC: (1.3-1.4); FILE MERGED 2005/08/04 14:47:07 sj 1.3.220.1: #48467# using GraphicExporter component for exports, graphic filter progress now works now via xStatusIndicater instead of callback mechanism<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dxfgrprd.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 16:14:09 $
 *
 *  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 _DXFGRPRD_HXX
#define _DXFGRPRD_HXX

#include <svtools/fltcall.hxx>

#define DXF_MAX_STRING_LEN 256 // Max Stringlaenge (ohne die 0)

class DXFGroupReader
{

public:

    // Anmerkkung:
    // sizeof(DXFGroupReader) ist gross, also nur dynamisch anlegen!

    DXFGroupReader( SvStream & rIStream, USHORT nMinPercent, USHORT nMaxPercent );

    BOOL GetStatus();

    void SetError();

    USHORT Read();
        // Liesst die naechste Gruppe ein und liefert den Gruppencode zurueck.
        // Im Falle eines Fehlers liefert GetStatus() FALSE, Gruppencode wird 0
        // gesetzt, und es wird SetS(0,"EOF") ausgefuehrt.

    USHORT GetG();
        // Liefert den letzten Gruppencode (also was Read() zuletzt lieferte)

    long   GetI();
        // Liefert den Integer-Wert zur Gruppe, die vorher mit Read() gelesen wurde.
        // Dabei muss es sich um einen Gruppencode fuer den Datentyp Integer
        // gehandelt haben, wenn nicht, wird 0 gelieferet.

    double GetF();
        // Liefert den Floatingpoint-Wert zur Gruppe, die vorher mit Read() gelesen wurde.
        // Dabei muss es sich um einen Gruppencode fuer den Datentyp Floatingpoint
        // gehandelt haben, wenn nicht, wird 0 geliefert.

    const char * GetS();
        // Liefert den String zur Gruppe, die vorher mit Read() gelesen wurde.
        // Dabei muss es sich um einen Gruppencode fuer den Datentyp String
        // gehandelt haben, wenn nicht, wird NULL geliefert.

    // Folgende drei Methoden arbeiten wie die obigen, nur kann auch ein anderer als der
    // aktuelle Gruppencode angegeben werden. (DXFGroupReader speichert die Parameter
    // zu allen Gruppencodes. Dadurch ist es moeglich, dass zunaechst mit Read() einige
    // verschiedene Gruppen eingelesen werden, bevor sie ausgewertet werden.)
    long         GetI(USHORT nG);
    double       GetF(USHORT nG);
    const char * GetS(USHORT nG);

    // Mit folgenden Methoden koennen die aktuell gespeicherten Werte zu den
    // Gruppencodes veraendert werden. (z.B. um Defaultwerte zu setzen, bevor
    // 'blind' eine Menge von Gruppen eingelesen wird.)
    void SetI(USHORT nG, long nI);
    void SetF(USHORT nG, double fF);
    void SetS(USHORT nG, const char * sS); // (wird kopiert)

private:

    void   FillIBuff();
    char   ReadChar();
    void   ReadLine(char * ptgt);
    long   ReadI();
    double ReadF();
    void   ReadS(char * ptgt);

    SvStream & rIS;
    char sIBuff[1024];
    USHORT nIBuffSize,nIBuffPos;
    BOOL bStatus;
    USHORT nLastG;
    ULONG nGCount;

    ULONG nMinPercent;
    ULONG nMaxPercent;
    ULONG nLastPercent;
    ULONG nFileSize;

    char   S0_9      [10][DXF_MAX_STRING_LEN+1]; // Strings  Gruppencodes 0..9
    double F10_59    [50];      // Floats   Gruppencodes 10..59
    long   I60_79    [20];      // Integers Gruppencodes 60..79
    long   I90_99    [10];
    char   S100      [DXF_MAX_STRING_LEN+1];
    char   S102      [DXF_MAX_STRING_LEN+1];
    double F140_147  [ 8];      // Floats   Gruppencodes 140..147
    long   I170_175  [ 6];      // Integers Gruppencodes 170..175
    double F210_239  [30];      // Floats   Gruppencodes 210..239
    char   S999_1009 [11][DXF_MAX_STRING_LEN+1]; // Strings  Gruppencodes 999..1009
    double F1010_1059[50];      // Floats   Gruppencodes 1010..1059
    long   I1060_1079[20];      // Integers Gruppencodes 1060..1079

};

inline BOOL DXFGroupReader::GetStatus()
{
    return bStatus;
}

inline void DXFGroupReader::SetError()
{
    bStatus=FALSE;
}

inline USHORT DXFGroupReader::GetG()
{
    return nLastG;
}

inline long DXFGroupReader::GetI()
{
    return GetI(nLastG);
}

inline double DXFGroupReader::GetF()
{
    return GetF(nLastG);
}

inline const char * DXFGroupReader::GetS()
{
    return GetS(nLastG);
}

inline char DXFGroupReader::ReadChar()
{
    if (nIBuffPos>=nIBuffSize) FillIBuff();
    return sIBuff[nIBuffPos++];
}

#endif

<|endoftext|>


<commit_before>/*
 Authorization Server code for CMPT 276, Spring 2016.
 */

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

#include <cpprest/http_listener.h>
#include <cpprest/json.h>

#include <was/common.h>
#include <was/table.h>

#include "../include/TableCache.h"
#include "../include/make_unique.h"

#include "../include/azure_keys.h"

using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_request_options;
using azure::storage::table_result;
using azure::storage::table_shared_access_policy;

using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;

using web::http::http_headers;
using web::http::http_request;
using web::http::methods;
using web::http::status_code;
using web::http::status_codes;
using web::http::uri;

using web::json::value;

using web::http::experimental::listener::http_listener;

using prop_str_vals_t = vector<pair<string,string>>;

constexpr const char* def_url = "http://localhost:34570";

const string auth_table_name {"AuthTable"};
const string auth_table_userid_partition {"Userid"};
const string auth_table_password_prop {"Password"};
const string auth_table_partition_prop {"DataPartition"};
const string auth_table_row_prop {"DataRow"};
const string data_table_name {"DataTable"};

const string get_read_token_op {"GetReadToken"};
const string get_update_token_op {"GetUpdateToken"};

/*
  Cache of opened tables
 */
TableCache table_cache {};

/*
  Convert properties represented in Azure Storage type
  to prop_str_vals_t type.
 */
prop_str_vals_t get_string_properties (const table_entity::properties_type& properties) {
  prop_str_vals_t values {};
  for (const auto v : properties) {
    if (v.second.property_type() == edm_type::string) {
      values.push_back(make_pair(v.first,v.second.string_value()));
    }
    else {
      // Force the value as string in any case
      values.push_back(make_pair(v.first, v.second.str()));
    }
  }
  return values;
}

/*
  Return true if an HTTP request has a JSON body

  This routine can be called multiple times on the same message.
 */
bool has_json_body (http_request message) {
  return message.headers()["Content-type"] == "application/json";
}

/*
  Given an HTTP message with a JSON body, return the JSON
  body as an unordered map of strings to strings.

  Note that all types of JSON values are returned as strings.
  Use C++ conversion utilities to convert to numbers or dates
  as necessary.
 */
unordered_map<string,string> get_json_body(http_request message) {
  unordered_map<string,string> results {};
  const http_headers& headers {message.headers()};
  auto content_type (headers.find("Content-Type"));
  if (content_type == headers.end() ||
      content_type->second != "application/json")
    return results;

  value json{};
  message.extract_json(true)
    .then([&json](value v) -> bool
          {
            json = v;
            return true;
          })
    .wait();

  if (json.is_object()) {
    for (const auto& v : json.as_object()) {
      if (v.second.is_string()) {
        results[v.first] = v.second.as_string();
      }
      else {
        results[v.first] = v.second.serialize();
      }
    }
  }
  return results;
}

/*
  Return a token for 24 hours of access to the specified table,
  for the single entity defind by the partition and row.

  permissions: A bitwise OR ('|')  of table_shared_access_poligy::permission
    constants.

    For read-only:
      table_shared_access_policy::permissions::read
    For read and update:
      table_shared_access_policy::permissions::read |
      table_shared_access_policy::permissions::update
 */
pair<status_code,string> do_get_token (const cloud_table& data_table,
                   const string& partition,
                   const string& row,
                   uint8_t permissions) {

  utility::datetime exptime {utility::datetime::utc_now() + utility::datetime::from_days(1)};
  try {
    string limited_access_token {
      data_table.get_shared_access_signature(table_shared_access_policy {
                                               exptime,
                                               permissions},
                                             string(), // Unnamed policy
                                             // Start of range (inclusive)
                                             partition,
                                             row,
                                             // End of range (inclusive)
                                             partition,
                                             row)
        // Following token allows read access to entire table
        //table.get_shared_access_signature(table_shared_access_policy {exptime, permissions})
      };
    cout << "Token " << limited_access_token << endl;
    return make_pair(status_codes::OK, limited_access_token);
  }
  catch (const storage_exception& e) {
    cout << "Azure Table Storage error: " << e.what() << endl;
    cout << e.result().extended_error().message() << endl;
    return make_pair(status_codes::InternalError, string{});
  }
}

/*
  Top-level routine for processing all HTTP GET requests.
 */
void handle_get(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** AuthServer GET " << path << endl;
  auto paths = uri::split_path(path);
  // Need at least an operation and userid
  if (paths.size() < 2) {
    message.reply(status_codes::BadRequest);
    return;
  }
    message.reply(status_codes::NotImplemented);
}

/*
  Top-level routine for processing all HTTP POST requests.
 */
void handle_post(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** POST " << path << endl;
}

/*
  Top-level routine for processing all HTTP PUT requests.
 */
void handle_put(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** PUT " << path << endl;
}

/*
  Top-level routine for processing all HTTP DELETE requests.
 */
void handle_delete(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** DELETE " << path << endl;
}

/*
  Main authentication server routine

  Install handlers for the HTTP requests and open the listener,
  which processes each request asynchronously.

  Note that, unlike BasicServer, AuthServer only
  installs the listeners for GET. Any other HTTP
  method will produce a Method Not Allowed (405)
  response.

  If you want to support other methods, uncomment
  the call below that hooks in a the appropriate
  listener.

  Wait for a carriage return, then shut the server down.
 */
int main (int argc, char const * argv[]) {
  cout << "AuthServer: Parsing connection string" << endl;
  table_cache.init (storage_connection_string);

  cout << "AuthServer: Opening listener" << endl;
  http_listener listener {def_url};
  listener.support(methods::GET, &handle_get);
  //listener.support(methods::POST, &handle_post);
  //listener.support(methods::PUT, &handle_put);
  //listener.support(methods::DEL, &handle_delete);
  listener.open().wait(); // Wait for listener to complete starting

  cout << "Enter carriage return to stop AuthServer." << endl;
  string line;
  getline(std::cin, line);

  // Shut it down
  listener.close().wait();
  cout << "AuthServer closed" << endl;
}
<commit_msg>Add get_json_bourne() as get_json_body() alias in AuthServer.cpp<commit_after>/*
 Authorization Server code for CMPT 276, Spring 2016.
 */

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

#include <cpprest/http_listener.h>
#include <cpprest/json.h>

#include <was/common.h>
#include <was/table.h>

#include "../include/TableCache.h"
#include "../include/make_unique.h"

#include "../include/azure_keys.h"

using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_request_options;
using azure::storage::table_result;
using azure::storage::table_shared_access_policy;

using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;

using web::http::http_headers;
using web::http::http_request;
using web::http::methods;
using web::http::status_code;
using web::http::status_codes;
using web::http::uri;

using web::json::value;

using web::http::experimental::listener::http_listener;

using prop_str_vals_t = vector<pair<string,string>>;

constexpr const char* def_url = "http://localhost:34570";

const string auth_table_name {"AuthTable"};
const string auth_table_userid_partition {"Userid"};
const string auth_table_password_prop {"Password"};
const string auth_table_partition_prop {"DataPartition"};
const string auth_table_row_prop {"DataRow"};
const string data_table_name {"DataTable"};

const string get_read_token_op {"GetReadToken"};
const string get_update_token_op {"GetUpdateToken"};

/*
  Cache of opened tables
 */
TableCache table_cache {};

/*
  Convert properties represented in Azure Storage type
  to prop_str_vals_t type.
 */
prop_str_vals_t get_string_properties (const table_entity::properties_type& properties) {
  prop_str_vals_t values {};
  for (const auto v : properties) {
    if (v.second.property_type() == edm_type::string) {
      values.push_back(make_pair(v.first,v.second.string_value()));
    }
    else {
      // Force the value as string in any case
      values.push_back(make_pair(v.first, v.second.str()));
    }
  }
  return values;
}

/*
  Return true if an HTTP request has a JSON body

  This routine can be called multiple times on the same message.
 */
bool has_json_body (http_request message) {
  return message.headers()["Content-type"] == "application/json";
}

/*
  Given an HTTP message with a JSON body, return the JSON
  body as an unordered map of strings to strings.
  get_json_body and get_json_bourne are valid and identical function calls.

  If the message has no JSON body, return an empty map.

  THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE
  (see http://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7
  for source of this limit).

  Note that all types of JSON values are returned as strings.
  Use C++ conversion utilities to convert to numbers or dates
  as necessary.
 */
unordered_map<string,string> get_json_body(http_request message) {
  unordered_map<string,string> results {};
  const http_headers& headers {message.headers()};
  auto content_type (headers.find("Content-Type"));
  if (content_type == headers.end() ||
      content_type->second != "application/json")
    return results;

  value json{};
  message.extract_json(true)
    .then([&json](value v) -> bool
          {
            json = v;
            return true;
          })
    .wait();

  if (json.is_object()) {
    for (const auto& v : json.as_object()) {
      if (v.second.is_string()) {
        results[v.first] = v.second.as_string();
      }
      else {
        results[v.first] = v.second.serialize();
      }
    }
  }
  return results;
}

unordered_map<string,string> get_json_bourne(http_request message) {
 return get_json_body(message);
}

/*
  Return a token for 24 hours of access to the specified table,
  for the single entity defind by the partition and row.

  permissions: A bitwise OR ('|')  of table_shared_access_poligy::permission
    constants.

    For read-only:
      table_shared_access_policy::permissions::read
    For read and update:
      table_shared_access_policy::permissions::read |
      table_shared_access_policy::permissions::update
 */
pair<status_code,string> do_get_token (const cloud_table& data_table,
                   const string& partition,
                   const string& row,
                   uint8_t permissions) {

  utility::datetime exptime {utility::datetime::utc_now() + utility::datetime::from_days(1)};
  try {
    string limited_access_token {
      data_table.get_shared_access_signature(table_shared_access_policy {
                                               exptime,
                                               permissions},
                                             string(), // Unnamed policy
                                             // Start of range (inclusive)
                                             partition,
                                             row,
                                             // End of range (inclusive)
                                             partition,
                                             row)
        // Following token allows read access to entire table
        //table.get_shared_access_signature(table_shared_access_policy {exptime, permissions})
      };
    cout << "Token " << limited_access_token << endl;
    return make_pair(status_codes::OK, limited_access_token);
  }
  catch (const storage_exception& e) {
    cout << "Azure Table Storage error: " << e.what() << endl;
    cout << e.result().extended_error().message() << endl;
    return make_pair(status_codes::InternalError, string{});
  }
}

/*
  Top-level routine for processing all HTTP GET requests.
 */
void handle_get(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** AuthServer GET " << path << endl;
  auto paths = uri::split_path(path);
  // Need at least an operation and userid
  if (paths.size() < 2) {
    message.reply(status_codes::BadRequest);
    return;
  }
    message.reply(status_codes::NotImplemented);
}

/*
  Top-level routine for processing all HTTP POST requests.
 */
void handle_post(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** POST " << path << endl;
}

/*
  Top-level routine for processing all HTTP PUT requests.
 */
void handle_put(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** PUT " << path << endl;
}

/*
  Top-level routine for processing all HTTP DELETE requests.
 */
void handle_delete(http_request message) {
  string path {uri::decode(message.relative_uri().path())};
  cout << endl << "**** DELETE " << path << endl;
}

/*
  Main authentication server routine

  Install handlers for the HTTP requests and open the listener,
  which processes each request asynchronously.

  Note that, unlike BasicServer, AuthServer only
  installs the listeners for GET. Any other HTTP
  method will produce a Method Not Allowed (405)
  response.

  If you want to support other methods, uncomment
  the call below that hooks in a the appropriate
  listener.

  Wait for a carriage return, then shut the server down.
 */
int main (int argc, char const * argv[]) {
  cout << "AuthServer: Parsing connection string" << endl;
  table_cache.init (storage_connection_string);

  cout << "AuthServer: Opening listener" << endl;
  http_listener listener {def_url};
  listener.support(methods::GET, &handle_get);
  //listener.support(methods::POST, &handle_post);
  //listener.support(methods::PUT, &handle_put);
  //listener.support(methods::DEL, &handle_delete);
  listener.open().wait(); // Wait for listener to complete starting

  cout << "Enter carriage return to stop AuthServer." << endl;
  string line;
  getline(std::cin, line);

  // Shut it down
  listener.close().wait();
  cout << "AuthServer closed" << endl;
}
<|endoftext|>


<commit_before>
#include "BlockChain.hpp"

namespace Eth{

BlockChain::BlockChain(Provider &provider) :
    _provider(provider)
{}

bool BlockChain::isSyncing()
{
    Json::Value result = _provider.request("eth_isSyncing");
    if(result.isBool())
    {
        return result.asBool();
    }
    return true;
}

size_t BlockChain::getHeight()
{
    Json::Value result = _provider.request("eth_blockNumber");
    return result.asUInt();
}

Block BlockChain::getBlock(size_t number)
{
    return Block(_provider.request("eth_getBlockByNumber", Arguments(number, false)));
}

Block BlockChain::getBlock(const char *hash)
{
    return Block(_provider.request("eth_getBlockByHash", Arguments(hash, false)));
}

Block BlockChain::getUncle(const char *blockHash, size_t index)
{
    return Block(_provider.request("eth_getUncleByBlockHashAndIndex", Arguments(blockHash, index)));
}

Block BlockChain::getUncle(size_t blockNumber, size_t index)
{
    return Block(_provider.request("eth_getUncleByBlockNumberAndIndex", Arguments(blockNumber, index)));
}

Transaction BlockChain::getTransaction(const char *hash)
{
    return Transaction(_provider.request("eth_getTransactionByHash", Arguments(hash)));
}

Transaction BlockChain::getBlockTransaction(const char *blockHash, size_t index)
{
    return Transaction(_provider.request("eth_getTransactionByBlockHashAndIndex", Arguments(blockHash, index)));
}

Transaction BlockChain::getBlockTransaction(size_t blockNumber, size_t index)
{
    return Transaction(_provider.request("eth_getTransactionByBlockNumberAndIndex", Arguments(blockNumber, index)));
}

size_t BlockChain::getBlockTransactionsCount(size_t blockNumber)
{
    Json::Value result = _provider.request("eth_getBlockTransactionCountByNumber", Arguments(blockNumber));
    return result.asUInt();
}

size_t BlockChain::getBlockTransactionsCount(const char *hash)
{
    Json::Value result = _provider.request("eth_getBlockTransactionCountByHash", Arguments(hash));
    return result.asUInt();
}

size_t BlockChain::getBlockUnclesCount(size_t blockNumber)
{
    Json::Value result = _provider.request("eth_getUncleCountByBlockNumber", Arguments(blockNumber));
    return result.asUInt();
}

size_t BlockChain::getBlockUnclesCount(const char *hash)
{
    Json::Value result = _provider.request("eth_getUncleCountByBlockHash", Arguments(hash));
    return result.asUInt();
}

size_t BlockChain::getTransactionsCount(const char *address)
{
    Json::Value result = _provider.request("eth_getTransactionCount", Arguments(address));
    return result.asUInt();
}

unsigned BlockChain::setNewFilter(const char *address, size_t fromBlock, size_t toBlock)
{
    Json::Value params = Json::arrayValue, result, filter;

    if(fromBlock)
    {
        filter["fromBlock"] = (Json::Value::UInt)fromBlock;
    }

    if(toBlock)
    {
        filter["toBlock"] = (Json::Value::UInt)toBlock;
    }
    filter["address"] = Json::arrayValue;
    filter["address"].append(Json::Value(address));

    params.append(filter);

    if(!_provider.request("eth_newFilter", params, result))
    {
        throw std::runtime_error("failed to set filter");
    }

     return strtoull(result.asCString(), NULL, 16);
}

void BlockChain::removeFilter(unsigned id)
{
    _provider.request("eth_uninstallFilter", Arguments(id));
}

Collection<FilterLog> BlockChain::getFilterChanges(unsigned id)
{
    return Collection<FilterLog>(_provider.request("eth_getFilterChanges", Arguments(id)));
}

Collection<FilterLog> BlockChain::getFilterLogs(unsigned id)
{
    return Collection<FilterLog>(_provider.request("eth_getFilterLogs", Arguments(id)));
}

}
<commit_msg>using hex values<commit_after>
#include "BlockChain.hpp"

namespace Eth{

BlockChain::BlockChain(Provider &provider) :
    _provider(provider)
{}

bool BlockChain::isSyncing()
{
    Json::Value result = _provider.request("eth_isSyncing");
    if(result.isBool())
    {
        return result.asBool();
    }
    return true;
}

size_t BlockChain::getHeight()
{
    Json::Value result = _provider.request("eth_blockNumber");
    return result.asUInt();
}

Block BlockChain::getBlock(size_t number)
{
    return Block(_provider.request("eth_getBlockByNumber", Arguments(hex(number), false)));
}

Block BlockChain::getBlock(const char *hash)
{
    return Block(_provider.request("eth_getBlockByHash", Arguments(hash, false)));
}

Block BlockChain::getUncle(const char *blockHash, size_t index)
{
    return Block(_provider.request("eth_getUncleByBlockHashAndIndex", Arguments(blockHash, hex(index))));
}

Block BlockChain::getUncle(size_t blockNumber, size_t index)
{
    return Block(_provider.request("eth_getUncleByBlockNumberAndIndex", Arguments(hex(blockNumber), hex(index))));
}

Transaction BlockChain::getTransaction(const char *hash)
{
    return Transaction(_provider.request("eth_getTransactionByHash", Arguments(hash)));
}

Transaction BlockChain::getBlockTransaction(const char *blockHash, size_t index)
{
    return Transaction(_provider.request("eth_getTransactionByBlockHashAndIndex", Arguments(blockHash, hex(index))));
}

Transaction BlockChain::getBlockTransaction(size_t blockNumber, size_t index)
{
    return Transaction(_provider.request("eth_getTransactionByBlockNumberAndIndex", Arguments(hex(blockNumber), hex(index))));
}

size_t BlockChain::getBlockTransactionsCount(size_t blockNumber)
{
    Json::Value result = _provider.request("eth_getBlockTransactionCountByNumber", Arguments(hex(blockNumber)));
    return result.asUInt();
}

size_t BlockChain::getBlockTransactionsCount(const char *hash)
{
    Json::Value result = _provider.request("eth_getBlockTransactionCountByHash", Arguments(hash));
    return result.asUInt();
}

size_t BlockChain::getBlockUnclesCount(size_t blockNumber)
{
    Json::Value result = _provider.request("eth_getUncleCountByBlockNumber", Arguments(hex(blockNumber)));
    return result.asUInt();
}

size_t BlockChain::getBlockUnclesCount(const char *hash)
{
    Json::Value result = _provider.request("eth_getUncleCountByBlockHash", Arguments(hash));
    return result.asUInt();
}

size_t BlockChain::getTransactionsCount(const char *address)
{
    Json::Value result = _provider.request("eth_getTransactionCount", Arguments(address));
    return result.asUInt();
}

unsigned BlockChain::setNewFilter(const char *address, size_t fromBlock, size_t toBlock)
{
    Json::Value params = Json::arrayValue, result, filter;

    if(fromBlock)
    {
        filter["fromBlock"] = Json::Value(hex(fromBlock));
    }

    if(toBlock)
    {
        filter["toBlock"] = Json::Value(hex(toBlock));
    }
    filter["address"] = Json::Value(address);
//    filter["address"].append(Json::Value(address));

    params.append(filter);

    if(!_provider.request("eth_newFilter", params, result))
    {
        throw std::runtime_error("failed to set filter");
    }

     return unhex<uint32_t>(result.asCString());
}

void BlockChain::removeFilter(unsigned id)
{
    _provider.request("eth_uninstallFilter", Arguments(hex(id)));
}

Collection<FilterLog> BlockChain::getFilterChanges(unsigned id)
{
    return Collection<FilterLog>(_provider.request("eth_getFilterChanges", Arguments(hex(id))));
}

Collection<FilterLog> BlockChain::getFilterLogs(unsigned id)
{
    return Collection<FilterLog>(_provider.request("eth_getFilterLogs", Arguments(hex(id))));
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basdoc.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:54:30 $
 *
 *  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 _BASDOC_HXX
#define _BASDOC_HXX

#include <svx/ifaceids.hxx>
#include <iderid.hxx>

#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

class SfxPrinter;

class BasicDocShell: public SfxObjectShell
{
    SfxPrinter*         pPrinter;

protected:
    virtual void        FillStatusBar( StatusBar& rBar);
    virtual void    Draw( OutputDevice *, const JobSetup & rSetup,
                          USHORT nAspect = ASPECT_CONTENT );
    virtual void    FillClass( SvGlobalName * pClassName,
                               sal_uInt32 * pFormat,
                               String * pAppName,
                               String * pFullTypeName,
                               String * pShortTypeName,
                               sal_Int32 nVersion ) const;

public:
                        TYPEINFO();

                        SFX_DECL_OBJECTFACTORY();
                        SFX_DECL_INTERFACE( SVX_INTERFACE_BASIDE_DOCSH );
                        BasicDocShell( SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
                        ~BasicDocShell();

    void                Execute( SfxRequest& rReq );
    void                GetState( SfxItemSet& rSet );

    SfxPrinter*         GetPrinter( BOOL bCreate );
    void                SetPrinter( SfxPrinter* pPrinter );
};

#endif  // _BASDOC_HXX
<commit_msg>INTEGRATION: CWS ab33 (1.6.138); FILE MERGED 2007/01/10 16:34:44 ab 1.6.138.1: #i69280# Removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basdoc.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2007-01-16 16:27:34 $
 *
 *  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 _BASDOC_HXX
#define _BASDOC_HXX

#include <svx/ifaceids.hxx>
#include <iderid.hxx>

#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

class SfxPrinter;

class BasicDocShell: public SfxObjectShell
{
    SfxPrinter*         pPrinter;

protected:
    virtual void        FillStatusBar( StatusBar& rBar);
    virtual void    Draw( OutputDevice *, const JobSetup & rSetup,
                          USHORT nAspect = ASPECT_CONTENT );
    virtual void    FillClass( SvGlobalName * pClassName,
                               sal_uInt32 * pFormat,
                               String * pAppName,
                               String * pFullTypeName,
                               String * pShortTypeName,
                               sal_Int32 nVersion ) const;

public:
                        TYPEINFO();

                        using SotObject::GetInterface;
                        SFX_DECL_OBJECTFACTORY();
                        SFX_DECL_INTERFACE( SVX_INTERFACE_BASIDE_DOCSH )
                        BasicDocShell( SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
                        ~BasicDocShell();

    void                Execute( SfxRequest& rReq );
    void                GetState( SfxItemSet& rSet );

    SfxPrinter*         GetPrinter( BOOL bCreate );
    void                SetPrinter( SfxPrinter* pPrinter );
};

#endif  // _BASDOC_HXX
<|endoftext|>


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

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <drafts/com/sun/star/frame/XLayoutManager.hpp>
#endif

/*
#ifdef _BASIDE_POPUPWINDOWTBX

// class PopupWindowTbx --------------------------------------------------

class PopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    Link                aSelectLink;

    DECL_LINK( SelectHdl, void* );

public:
    PopupWindowTbx( USHORT nId, WindowAlign eAlign,
                    ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );
    ~PopupWindowTbx();

    void                    StartSelection()
                                { aTbx.GetToolBox().StartSelection(); }
    void                    Update();

    virtual SfxPopupWindow* Clone() const;
    virtual void            PopupModeEnd();
};
#endif
*/
//-------------------
// class TbxControls
//-------------------
class TbxControls : public SfxToolBoxControl
{
private:

    struct StateChangedInfo
    {
        ::com::sun::star::uno::Reference< ::drafts::com::sun::star::frame::XLayoutManager > xLayoutManager;
        bool bDisabled;
    };

    USHORT                  nLastSlot;

    DECL_STATIC_LINK( TbxControls, StateChangedHdl_Impl, StateChangedInfo* );

protected:
    virtual void            StateChanged( USHORT nSID, SfxItemState eState,
                                          const SfxPoolItem* pState );
public:
    SFX_DECL_TOOLBOX_CONTROL();

    TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~TbxControls() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();

    void                        Select( USHORT nModifier );
};

#endif // _BASIDE_TBXCTL_HXX

<commit_msg>INTEGRATION: CWS removedrafts (1.5.14); FILE MERGED 2005/02/17 12:40:10 cd 1.5.14.1: #i42557# move UNOIDL types from drafts to com<commit_after>/*************************************************************************
 *
 *  $RCSfile: tbxctl.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:19:12 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _BASIDE_TBXCTL_HXX
#define _BASIDE_TBXCTL_HXX

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <com/sun/star/frame/XLayoutManager.hpp>
#endif

/*
#ifdef _BASIDE_POPUPWINDOWTBX

// class PopupWindowTbx --------------------------------------------------

class PopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    Link                aSelectLink;

    DECL_LINK( SelectHdl, void* );

public:
    PopupWindowTbx( USHORT nId, WindowAlign eAlign,
                    ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );
    ~PopupWindowTbx();

    void                    StartSelection()
                                { aTbx.GetToolBox().StartSelection(); }
    void                    Update();

    virtual SfxPopupWindow* Clone() const;
    virtual void            PopupModeEnd();
};
#endif
*/
//-------------------
// class TbxControls
//-------------------
class TbxControls : public SfxToolBoxControl
{
private:

    struct StateChangedInfo
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;
        bool bDisabled;
    };

    USHORT                  nLastSlot;

    DECL_STATIC_LINK( TbxControls, StateChangedHdl_Impl, StateChangedInfo* );

protected:
    virtual void            StateChanged( USHORT nSID, SfxItemState eState,
                                          const SfxPoolItem* pState );
public:
    SFX_DECL_TOOLBOX_CONTROL();

    TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~TbxControls() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();

    void                        Select( USHORT nModifier );
};

#endif // _BASIDE_TBXCTL_HXX

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#include <com/sun/star/drawing/PointSequence.hpp>
#include <com/sun/star/drawing/FlagSequence.hpp>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>

#include <basegfx/tools/unotools.hxx>
#include <comphelper/sequence.hxx>

using namespace ::com::sun::star;

namespace basegfx
{
namespace unotools
{

    B2DPolyPolygon polyPolygonBezierToB2DPolyPolygon(const drawing::PolyPolygonBezierCoords& rSourcePolyPolygon)
        throw( lang::IllegalArgumentException )
    {
        const sal_Int32 nOuterSequenceCount(rSourcePolyPolygon.Coordinates.getLength());
        B2DPolyPolygon aNewPolyPolygon;

        if(rSourcePolyPolygon.Flags.getLength() != nOuterSequenceCount)
            throw lang::IllegalArgumentException();

        // get pointers to inner sequence
        const drawing::PointSequence* pInnerSequence = rSourcePolyPolygon.Coordinates.getConstArray();
        const drawing::FlagSequence* pInnerSequenceFlags = rSourcePolyPolygon.Flags.getConstArray();

        for(sal_Int32 a(0); a < nOuterSequenceCount; a++)
        {
            const sal_Int32 nInnerSequenceCount(pInnerSequence->getLength());

            if(pInnerSequenceFlags->getLength() != nInnerSequenceCount)
                throw lang::IllegalArgumentException();

            // prepare new polygon
            basegfx::B2DPolygon aNewPolygon;
            const awt::Point* pArray = pInnerSequence->getConstArray();
            const drawing::PolygonFlags* pArrayFlags = pInnerSequenceFlags->getConstArray();

            // get first point and flag
            basegfx::B2DPoint aNewCoordinatePair(pArray->X, pArray->Y); pArray++;
            drawing::PolygonFlags ePolyFlag(*pArrayFlags); pArrayFlags++;
            basegfx::B2DPoint aControlA;
            basegfx::B2DPoint aControlB;

            // first point is not allowed to be a control point
            if(drawing::PolygonFlags_CONTROL == ePolyFlag)
                throw lang::IllegalArgumentException();

            // add first point as start point
            aNewPolygon.append(aNewCoordinatePair);
            for(sal_Int32 b(1); b < nInnerSequenceCount;)
            {
                // prepare loop
                bool bControlA(false);
                bool bControlB(false);

                // get next point and flag
                aNewCoordinatePair = basegfx::B2DPoint(pArray->X, pArray->Y);
                ePolyFlag = *pArrayFlags;
                pArray++; pArrayFlags++; b++;

                if(b < nInnerSequenceCount && drawing::PolygonFlags_CONTROL == ePolyFlag)
                {
                    aControlA = aNewCoordinatePair;
                    bControlA = true;

                    // get next point and flag
                    aNewCoordinatePair = basegfx::B2DPoint(pArray->X, pArray->Y);
                    ePolyFlag = *pArrayFlags;
                    pArray++; pArrayFlags++; b++;
                }

                if(b < nInnerSequenceCount && drawing::PolygonFlags_CONTROL == ePolyFlag)
                {
                    aControlB = aNewCoordinatePair;
                    bControlB = true;

                    // get next point and flag
                    aNewCoordinatePair = basegfx::B2DPoint(pArray->X, pArray->Y);
                    ePolyFlag = *pArrayFlags;
                    pArray++; pArrayFlags++; b++;
                }

                // two or no control points are consumed, another one would be an error.
                // It's also an error if only one control point was read
                if(drawing::PolygonFlags_CONTROL == ePolyFlag || bControlA != bControlB)
                    throw lang::IllegalArgumentException();

                // the previous writes used the B2DPolyPoygon -> tools::PolyPolygon converter
                // which did not create minimal PolyPolygons, but created all control points
                // as null vectors (identical points). Because of the former P(CA)(CB)-norm of
                // B2DPolygon and it's unused sign of being the zero-vector and CA and CB being
                // relative to P, an empty edge was exported as P == CA == CB. Luckily, the new
                // export format can be read without errors by the old OOo-versions, so we need only
                // to correct here at read and do not need to export a wrong but compatible version
                // for the future.
                if(bControlA
                   && aControlA.equal(aControlB)
                   && aControlA.equal(aNewPolygon.getB2DPoint(aNewPolygon.count() - 1)))
                {
                    bControlA = bControlB = false;
                }

                if(bControlA)
                {
                    // add bezier edge
                    aNewPolygon.appendBezierSegment(aControlA, aControlB, aNewCoordinatePair);
                }
                else
                {
                    // add edge
                    aNewPolygon.append(aNewCoordinatePair);
                }
            }

            // next sequence
            pInnerSequence++;
            pInnerSequenceFlags++;

            // #i72807# API import uses old line start/end-equal definition for closed,
            // so we need to correct this to closed state here
            basegfx::tools::checkClosed(aNewPolygon);

            // add new subpolygon
            aNewPolyPolygon.append(aNewPolygon);
        }

        return aNewPolyPolygon;
    }

    void b2DPolyPolygonToPolyPolygonBezier( const basegfx::B2DPolyPolygon& rPolyPoly,
                                            drawing::PolyPolygonBezierCoords& rRetval )
    {
        rRetval.Coordinates.realloc(rPolyPoly.count());
        rRetval.Flags.realloc(rPolyPoly.count());

        drawing::PointSequence* pOuterSequence = rRetval.Coordinates.getArray();
        drawing::FlagSequence*  pOuterFlags = rRetval.Flags.getArray();

        for(sal_uInt32 a=0;a<rPolyPoly.count();a++)
        {
            const B2DPolygon& rPoly = rPolyPoly.getB2DPolygon(a);
            sal_uInt32 nCount(rPoly.count());
            const bool bClosed(rPoly.isClosed());

            // calculate input vertex count
            const sal_uInt32 nLoopCount(bClosed ? nCount : (nCount ? nCount - 1L : 0L ));

            std::vector<awt::Point> aPoints; aPoints.reserve(nLoopCount);
            std::vector<drawing::PolygonFlags> aFlags; aFlags.reserve(nLoopCount);

            if( nCount )
            {
                // prepare insert index and current point
                basegfx::B2DCubicBezier aBezier;
                aBezier.setStartPoint(rPoly.getB2DPoint(0));

                for(sal_uInt32 b(0L); b<nLoopCount; b++)
                {
                    // add current point (always) and remember StartPointIndex for evtl. later corrections
                    const awt::Point aStartPoint(fround(aBezier.getStartPoint().getX()),
                                                 fround(aBezier.getStartPoint().getY()));
                    const sal_uInt32 nStartPointIndex(aPoints.size());
                    aPoints.push_back(aStartPoint);
                    aFlags.push_back(drawing::PolygonFlags_NORMAL);

                    // prepare next segment
                    const sal_uInt32 nNextIndex((b + 1) % nCount);
                    aBezier.setEndPoint(rPoly.getB2DPoint(nNextIndex));
                    aBezier.setControlPointA(rPoly.getNextControlPoint(b));
                    aBezier.setControlPointB(rPoly.getPrevControlPoint(nNextIndex));

                    if(aBezier.isBezier())
                    {
                        // if one is used, add always two control points due to the old schema
                        aPoints.push_back( awt::Point(fround(aBezier.getControlPointA().getX()),
                                                      fround(aBezier.getControlPointA().getY())) );
                        aFlags.push_back(drawing::PolygonFlags_CONTROL);

                        aPoints.push_back( awt::Point(fround(aBezier.getControlPointB().getX()),
                                                      fround(aBezier.getControlPointB().getY())) );
                        aFlags.push_back(drawing::PolygonFlags_CONTROL);
                    }

                    // test continuity with previous control point to set flag value
                    if(aBezier.getControlPointA() != aBezier.getStartPoint() && (bClosed || b))
                    {
                        const basegfx::B2VectorContinuity eCont(rPoly.getContinuityInPoint(b));

                        if(basegfx::CONTINUITY_C1 == eCont)
                        {
                            aFlags[nStartPointIndex] = drawing::PolygonFlags_SMOOTH;
                        }
                        else if(basegfx::CONTINUITY_C2 == eCont)
                        {
                            aFlags[nStartPointIndex] = drawing::PolygonFlags_SYMMETRIC;
                        }
                    }

                    // prepare next polygon step
                    aBezier.setStartPoint(aBezier.getEndPoint());
                }

                if(bClosed)
                {
                    // add first point again as closing point due to old definition
                    aPoints.push_back( aPoints[0] );
                    aFlags.push_back(drawing::PolygonFlags_NORMAL);
                }
                else
                {
                    // add last point as closing point
                    const basegfx::B2DPoint aClosingPoint(rPoly.getB2DPoint(nCount - 1L));
                    const awt::Point aEnd(fround(aClosingPoint.getX()),
                                          fround(aClosingPoint.getY()));
                    aPoints.push_back(aEnd);
                    aFlags.push_back(drawing::PolygonFlags_NORMAL);
                }
            }

            *pOuterSequence++ = comphelper::containerToSequence(aPoints);
            *pOuterFlags++ = comphelper::containerToSequence(aFlags);
        }
    }

}
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>asan: global-buffer-overflow on fdo55736-1.docx<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#include <com/sun/star/drawing/PointSequence.hpp>
#include <com/sun/star/drawing/FlagSequence.hpp>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>

#include <basegfx/tools/unotools.hxx>
#include <comphelper/sequence.hxx>

using namespace ::com::sun::star;

namespace basegfx
{
namespace unotools
{

    B2DPolyPolygon polyPolygonBezierToB2DPolyPolygon(const drawing::PolyPolygonBezierCoords& rSourcePolyPolygon)
        throw( lang::IllegalArgumentException )
    {
        const sal_Int32 nOuterSequenceCount(rSourcePolyPolygon.Coordinates.getLength());
        B2DPolyPolygon aNewPolyPolygon;

        if(rSourcePolyPolygon.Flags.getLength() != nOuterSequenceCount)
            throw lang::IllegalArgumentException();

        // get pointers to inner sequence
        const drawing::PointSequence* pInnerSequence = rSourcePolyPolygon.Coordinates.getConstArray();
        const drawing::FlagSequence* pInnerSequenceFlags = rSourcePolyPolygon.Flags.getConstArray();

        for(sal_Int32 a(0); a < nOuterSequenceCount; a++)
        {
            const sal_Int32 nInnerSequenceCount(pInnerSequence->getLength());

            if (!nInnerSequenceCount)
                throw lang::IllegalArgumentException();

            if (pInnerSequenceFlags->getLength() != nInnerSequenceCount)
                throw lang::IllegalArgumentException();

            // prepare new polygon
            basegfx::B2DPolygon aNewPolygon;
            const awt::Point* pArray = pInnerSequence->getConstArray();
            const drawing::PolygonFlags* pArrayFlags = pInnerSequenceFlags->getConstArray();

            // get first point and flag
            basegfx::B2DPoint aNewCoordinatePair(pArray->X, pArray->Y); pArray++;
            drawing::PolygonFlags ePolyFlag(*pArrayFlags); pArrayFlags++;
            basegfx::B2DPoint aControlA;
            basegfx::B2DPoint aControlB;

            // first point is not allowed to be a control point
            if(drawing::PolygonFlags_CONTROL == ePolyFlag)
                throw lang::IllegalArgumentException();

            // add first point as start point
            aNewPolygon.append(aNewCoordinatePair);
            for(sal_Int32 b(1); b < nInnerSequenceCount;)
            {
                // prepare loop
                bool bControlA(false);
                bool bControlB(false);

                // get next point and flag
                aNewCoordinatePair = basegfx::B2DPoint(pArray->X, pArray->Y);
                ePolyFlag = *pArrayFlags;
                pArray++; pArrayFlags++; b++;

                if(b < nInnerSequenceCount && drawing::PolygonFlags_CONTROL == ePolyFlag)
                {
                    aControlA = aNewCoordinatePair;
                    bControlA = true;

                    // get next point and flag
                    aNewCoordinatePair = basegfx::B2DPoint(pArray->X, pArray->Y);
                    ePolyFlag = *pArrayFlags;
                    pArray++; pArrayFlags++; b++;
                }

                if(b < nInnerSequenceCount && drawing::PolygonFlags_CONTROL == ePolyFlag)
                {
                    aControlB = aNewCoordinatePair;
                    bControlB = true;

                    // get next point and flag
                    aNewCoordinatePair = basegfx::B2DPoint(pArray->X, pArray->Y);
                    ePolyFlag = *pArrayFlags;
                    pArray++; pArrayFlags++; b++;
                }

                // two or no control points are consumed, another one would be an error.
                // It's also an error if only one control point was read
                if(drawing::PolygonFlags_CONTROL == ePolyFlag || bControlA != bControlB)
                    throw lang::IllegalArgumentException();

                // the previous writes used the B2DPolyPoygon -> tools::PolyPolygon converter
                // which did not create minimal PolyPolygons, but created all control points
                // as null vectors (identical points). Because of the former P(CA)(CB)-norm of
                // B2DPolygon and it's unused sign of being the zero-vector and CA and CB being
                // relative to P, an empty edge was exported as P == CA == CB. Luckily, the new
                // export format can be read without errors by the old OOo-versions, so we need only
                // to correct here at read and do not need to export a wrong but compatible version
                // for the future.
                if(bControlA
                   && aControlA.equal(aControlB)
                   && aControlA.equal(aNewPolygon.getB2DPoint(aNewPolygon.count() - 1)))
                {
                    bControlA = bControlB = false;
                }

                if(bControlA)
                {
                    // add bezier edge
                    aNewPolygon.appendBezierSegment(aControlA, aControlB, aNewCoordinatePair);
                }
                else
                {
                    // add edge
                    aNewPolygon.append(aNewCoordinatePair);
                }
            }

            // next sequence
            pInnerSequence++;
            pInnerSequenceFlags++;

            // #i72807# API import uses old line start/end-equal definition for closed,
            // so we need to correct this to closed state here
            basegfx::tools::checkClosed(aNewPolygon);

            // add new subpolygon
            aNewPolyPolygon.append(aNewPolygon);
        }

        return aNewPolyPolygon;
    }

    void b2DPolyPolygonToPolyPolygonBezier( const basegfx::B2DPolyPolygon& rPolyPoly,
                                            drawing::PolyPolygonBezierCoords& rRetval )
    {
        rRetval.Coordinates.realloc(rPolyPoly.count());
        rRetval.Flags.realloc(rPolyPoly.count());

        drawing::PointSequence* pOuterSequence = rRetval.Coordinates.getArray();
        drawing::FlagSequence*  pOuterFlags = rRetval.Flags.getArray();

        for(sal_uInt32 a=0;a<rPolyPoly.count();a++)
        {
            const B2DPolygon& rPoly = rPolyPoly.getB2DPolygon(a);
            sal_uInt32 nCount(rPoly.count());
            const bool bClosed(rPoly.isClosed());

            // calculate input vertex count
            const sal_uInt32 nLoopCount(bClosed ? nCount : (nCount ? nCount - 1L : 0L ));

            std::vector<awt::Point> aPoints; aPoints.reserve(nLoopCount);
            std::vector<drawing::PolygonFlags> aFlags; aFlags.reserve(nLoopCount);

            if( nCount )
            {
                // prepare insert index and current point
                basegfx::B2DCubicBezier aBezier;
                aBezier.setStartPoint(rPoly.getB2DPoint(0));

                for(sal_uInt32 b(0L); b<nLoopCount; b++)
                {
                    // add current point (always) and remember StartPointIndex for evtl. later corrections
                    const awt::Point aStartPoint(fround(aBezier.getStartPoint().getX()),
                                                 fround(aBezier.getStartPoint().getY()));
                    const sal_uInt32 nStartPointIndex(aPoints.size());
                    aPoints.push_back(aStartPoint);
                    aFlags.push_back(drawing::PolygonFlags_NORMAL);

                    // prepare next segment
                    const sal_uInt32 nNextIndex((b + 1) % nCount);
                    aBezier.setEndPoint(rPoly.getB2DPoint(nNextIndex));
                    aBezier.setControlPointA(rPoly.getNextControlPoint(b));
                    aBezier.setControlPointB(rPoly.getPrevControlPoint(nNextIndex));

                    if(aBezier.isBezier())
                    {
                        // if one is used, add always two control points due to the old schema
                        aPoints.push_back( awt::Point(fround(aBezier.getControlPointA().getX()),
                                                      fround(aBezier.getControlPointA().getY())) );
                        aFlags.push_back(drawing::PolygonFlags_CONTROL);

                        aPoints.push_back( awt::Point(fround(aBezier.getControlPointB().getX()),
                                                      fround(aBezier.getControlPointB().getY())) );
                        aFlags.push_back(drawing::PolygonFlags_CONTROL);
                    }

                    // test continuity with previous control point to set flag value
                    if(aBezier.getControlPointA() != aBezier.getStartPoint() && (bClosed || b))
                    {
                        const basegfx::B2VectorContinuity eCont(rPoly.getContinuityInPoint(b));

                        if(basegfx::CONTINUITY_C1 == eCont)
                        {
                            aFlags[nStartPointIndex] = drawing::PolygonFlags_SMOOTH;
                        }
                        else if(basegfx::CONTINUITY_C2 == eCont)
                        {
                            aFlags[nStartPointIndex] = drawing::PolygonFlags_SYMMETRIC;
                        }
                    }

                    // prepare next polygon step
                    aBezier.setStartPoint(aBezier.getEndPoint());
                }

                if(bClosed)
                {
                    // add first point again as closing point due to old definition
                    aPoints.push_back( aPoints[0] );
                    aFlags.push_back(drawing::PolygonFlags_NORMAL);
                }
                else
                {
                    // add last point as closing point
                    const basegfx::B2DPoint aClosingPoint(rPoly.getB2DPoint(nCount - 1L));
                    const awt::Point aEnd(fround(aClosingPoint.getX()),
                                          fround(aClosingPoint.getY()));
                    aPoints.push_back(aEnd);
                    aFlags.push_back(drawing::PolygonFlags_NORMAL);
                }
            }

            *pOuterSequence++ = comphelper::containerToSequence(aPoints);
            *pOuterFlags++ = comphelper::containerToSequence(aFlags);
        }
    }

}
}

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


<commit_before>#include "ProfilingDataParser.h"

// I kept is as close as possible to the JS version, some thing could've been
// done better, but this at least looks mostly the same as the original, so
// it's easier to track changes to both
void ProfilingDataParser::walkCallGraphNode(QJsonObject& node)
{
    int id = node["id"].toInt();
    if (!routines.contains(id)) {
        routines[id] = new RoutineData(id);
    }
    routines[id]->name = node["name"].toString();
    routines[id]->file = node["file"].toString();
    routines[id]->line = node["line"].toInt();

    routines[id]->entries        += node["entries"].toInt();
    totalEntries                 += node["entries"].toInt();
    routines[id]->speshEntries   += node["spesh_entries"].toInt();
    speshEntries                 += node["spesh_entries"].toInt();
    routines[id]->inlinedEntries += node["inlined_entries"].toInt();
    inlinedEntries               += node["inlined_entries"].toInt();
    routines[id]->JITEntries     += node["jit_entries"].toInt();
    JITEntries                   += node["jit_entries"].toInt();
    routines[id]->exclusive      += node["exclusive_time"].toInt();
    totalExclusive               += node["exclusive_time"].toInt();
    routines[id]->OSR            += node["osr"].toInt();
    totalOSR                     += node["osr"].toInt();
    routines[id]->deoptOnes      += node["deopt_one"].toInt();
    totalDeoptOnes               += node["deopt_one"].toInt();
    routines[id]->deoptAlls      += node["deopt_all"].toInt();
    totalDeoptAlls               += node["deopt_all"].toInt();
    if (routines[id]->recDepth == 0) {
        routines[id]->inclusive += node["exclusive_time"].toInt();
    }
    QJsonArray callees(node["callees"].toArray());
    if (callees.count() > 0) {
        routines[id]->recDepth++;
        QJsonArray::const_iterator it;
        for (it = callees.begin(); it != callees.end(); it++) {
            QJsonObject obj = (*it).toObject();
            walkCallGraphNode(obj);
        }
        routines[id]->recDepth--;
    }
}

void ProfilingDataParser::walkGCNodes(QJsonArray& arr)
{
    QJsonArray::const_iterator it;
    for (it = arr.begin(); it != arr.end(); it++) {
        QJsonObject obj = (*it).toObject();
        if (obj["full"].toInt() != 0) {
            gcData.gcFull++;
            gcData.gcFullTime += obj["time"].toInt();
        } else {
            gcData.gcNursery++;
            gcData.gcNurseryTime += obj["time"].toInt();
        }
    }
}

QVector<RoutineListEntry*> ProfilingDataParser::buildRoutineList()
{
    QVector<RoutineListEntry*> routineList;
    QMap<int, RoutineData*>::iterator it;
    for (it = routines.begin(); it != routines.end(); it++) {
        RoutineData *rd = *it;
        RoutineListEntry *rle = new RoutineListEntry();
        rle->name    = rd->name;
        if (rd->name == "") rle->name = "<anon>";
        rle->file    = rd->file;
        rle->line    = rd->line;
        rle->entries = rd->entries;
        rle->speshEntriesPercent  = (100 * rd->speshEntries / rd->entries);
        rle->JITEntriesPercent    = (100 * rd->JITEntries   / rd->entries);
        rle->interpEntriesPercent = 100 - rle->speshEntriesPercent
                                        - rle->JITEntriesPercent;
        rle->inclusiveTime = (double)rd->inclusive / 1000;
        rle->inclusiveTimePercent = 100 * rd->inclusive / totalInclusive;
        rle->exclusiveTime = (double)rd->exclusive / 1000;
        rle->exclusiveTimePercent = 100 * rd->exclusive / totalExclusive;
        rle->OSR = rd->OSR;
        routineList.push_back(rle);
    }
    return routineList;
}

QMap<QString, QVariant> ProfilingDataParser::buildOverviewData()
{
    QMap<QString, QVariant> ret;
    // Time spent
    float gcTime        = gcData.gcNurseryTime + gcData.gcFullTime;
    float overheadTime  = speshTime + gcTime;
    float executingTime = totalTime - overheadTime;
    ret["TotalTime"]            = (float)totalTime / 1000;
    ret["OverheadTime"]         = overheadTime / 1000;
    ret["OverheadTimePercent"]  = 100 * overheadTime / totalTime;
    ret["ExecutingTime"]        = executingTime / 1000;
    ret["ExecutingTimePercent"] = 100 * executingTime / totalTime;
    ret["GCTime"]               = gcTime / 1000;
    ret["GCTimePercent"]        = 100 * gcTime / totalTime;
    ret["SpeshTime"]            = (float)speshTime / 1000;
    ret["SpeshTimePercent"]     = 100 * (float)speshTime / totalTime;
    // Routines
    int interpEntries           = totalEntries - (JITEntries + speshEntries);
    ret["EntriesWithoutInline"] = totalEntries - inlinedEntries;
    ret["EntriesInline"]        = inlinedEntries;
    ret["InlinePercent"]        = 100 * (float)inlinedEntries / totalEntries;
    ret["InterpFrames"]         = interpEntries;
    ret["InterpFramesPercent"]  = 100 * (float)interpEntries / totalEntries;
    ret["SpeshFrames"]          = speshEntries;
    ret["SpeshFramesPercent"]   = 100 * (float)speshEntries / totalEntries;
    ret["JITFrames"]            = JITEntries;
    ret["JITFramesPercent"]     = 100 * (float)JITEntries / totalEntries;

    // Garbage collection
    ret["GCRuns"]         = gcData.gcNursery + gcData.gcFull;
    ret["FullGCRuns"]     = gcData.gcFull;
    ret["NurseryAverage"] = ((float)gcData.gcNurseryTime / 1000) / gcData.gcNursery;
    ret["FullAverage"]    = ((float)gcData.gcFullTime / 1000) / gcData.gcFull;

    // Dynamic optimization
    int optimizedFrames    = speshEntries + JITEntries;
    ret["OptimizedFrames"] = optimizedFrames;
    ret["DeoptOnes"]       = totalDeoptOnes;
    ret["DeoptOnePercent"] = 100 * (float)totalDeoptOnes / (optimizedFrames || 1);
    ret["DeoptAlls"]       = totalDeoptAlls;
    ret["OSRs"]            = totalOSR;

    return ret;
}
<commit_msg>Bugfix<commit_after>#include "ProfilingDataParser.h"

// I kept is as close as possible to the JS version, some thing could've been
// done better, but this at least looks mostly the same as the original, so
// it's easier to track changes to both
void ProfilingDataParser::walkCallGraphNode(QJsonObject& node)
{
    int id = node["id"].toInt();
    if (!routines.contains(id)) {
        routines[id] = new RoutineData(id);
    }
    routines[id]->name = node["name"].toString();
    routines[id]->file = node["file"].toString();
    routines[id]->line = node["line"].toInt();

    routines[id]->entries        += node["entries"].toInt();
    totalEntries                 += node["entries"].toInt();
    routines[id]->speshEntries   += node["spesh_entries"].toInt();
    speshEntries                 += node["spesh_entries"].toInt();
    routines[id]->inlinedEntries += node["inlined_entries"].toInt();
    inlinedEntries               += node["inlined_entries"].toInt();
    routines[id]->JITEntries     += node["jit_entries"].toInt();
    JITEntries                   += node["jit_entries"].toInt();
    routines[id]->exclusive      += node["exclusive_time"].toInt();
    totalExclusive               += node["exclusive_time"].toInt();
    routines[id]->OSR            += node["osr"].toInt();
    totalOSR                     += node["osr"].toInt();
    routines[id]->deoptOnes      += node["deopt_one"].toInt();
    totalDeoptOnes               += node["deopt_one"].toInt();
    routines[id]->deoptAlls      += node["deopt_all"].toInt();
    totalDeoptAlls               += node["deopt_all"].toInt();
    if (routines[id]->recDepth == 0) {
        routines[id]->inclusive += node["inclusive_time"].toInt();
    }
    QJsonArray callees(node["callees"].toArray());
    if (callees.count() > 0) {
        routines[id]->recDepth++;
        QJsonArray::const_iterator it;
        for (it = callees.begin(); it != callees.end(); it++) {
            QJsonObject obj = (*it).toObject();
            walkCallGraphNode(obj);
        }
        routines[id]->recDepth--;
    }
}

void ProfilingDataParser::walkGCNodes(QJsonArray& arr)
{
    QJsonArray::const_iterator it;
    for (it = arr.begin(); it != arr.end(); it++) {
        QJsonObject obj = (*it).toObject();
        if (obj["full"].toInt() != 0) {
            gcData.gcFull++;
            gcData.gcFullTime += obj["time"].toInt();
        } else {
            gcData.gcNursery++;
            gcData.gcNurseryTime += obj["time"].toInt();
        }
    }
}

QVector<RoutineListEntry*> ProfilingDataParser::buildRoutineList()
{
    QVector<RoutineListEntry*> routineList;
    QMap<int, RoutineData*>::iterator it;
    for (it = routines.begin(); it != routines.end(); it++) {
        RoutineData *rd = *it;
        RoutineListEntry *rle = new RoutineListEntry();
        rle->name    = rd->name;
        if (rd->name == "") rle->name = "<anon>";
        rle->file    = rd->file;
        rle->line    = rd->line;
        rle->entries = rd->entries;
        rle->speshEntriesPercent  = (100 * rd->speshEntries / rd->entries);
        rle->JITEntriesPercent    = (100 * rd->JITEntries   / rd->entries);
        rle->interpEntriesPercent = 100 - rle->speshEntriesPercent
                                        - rle->JITEntriesPercent;
        rle->inclusiveTime = (double)rd->inclusive / 1000;
        rle->inclusiveTimePercent = 100 * rd->inclusive / totalInclusive;
        rle->exclusiveTime = (double)rd->exclusive / 1000;
        rle->exclusiveTimePercent = 100 * rd->exclusive / totalExclusive;
        rle->OSR = rd->OSR;
        routineList.push_back(rle);
    }
    return routineList;
}

QMap<QString, QVariant> ProfilingDataParser::buildOverviewData()
{
    QMap<QString, QVariant> ret;
    // Time spent
    float gcTime        = gcData.gcNurseryTime + gcData.gcFullTime;
    float overheadTime  = speshTime + gcTime;
    float executingTime = totalTime - overheadTime;
    ret["TotalTime"]            = (float)totalTime / 1000;
    ret["OverheadTime"]         = overheadTime / 1000;
    ret["OverheadTimePercent"]  = 100 * overheadTime / totalTime;
    ret["ExecutingTime"]        = executingTime / 1000;
    ret["ExecutingTimePercent"] = 100 * executingTime / totalTime;
    ret["GCTime"]               = gcTime / 1000;
    ret["GCTimePercent"]        = 100 * gcTime / totalTime;
    ret["SpeshTime"]            = (float)speshTime / 1000;
    ret["SpeshTimePercent"]     = 100 * (float)speshTime / totalTime;
    // Routines
    int interpEntries           = totalEntries - (JITEntries + speshEntries);
    ret["EntriesWithoutInline"] = totalEntries - inlinedEntries;
    ret["EntriesInline"]        = inlinedEntries;
    ret["InlinePercent"]        = 100 * (float)inlinedEntries / totalEntries;
    ret["InterpFrames"]         = interpEntries;
    ret["InterpFramesPercent"]  = 100 * (float)interpEntries / totalEntries;
    ret["SpeshFrames"]          = speshEntries;
    ret["SpeshFramesPercent"]   = 100 * (float)speshEntries / totalEntries;
    ret["JITFrames"]            = JITEntries;
    ret["JITFramesPercent"]     = 100 * (float)JITEntries / totalEntries;

    // Garbage collection
    ret["GCRuns"]         = gcData.gcNursery + gcData.gcFull;
    ret["FullGCRuns"]     = gcData.gcFull;
    ret["NurseryAverage"] = ((float)gcData.gcNurseryTime / 1000) / gcData.gcNursery;
    ret["FullAverage"]    = ((float)gcData.gcFullTime / 1000) / gcData.gcFull;

    // Dynamic optimization
    int optimizedFrames    = speshEntries + JITEntries;
    ret["OptimizedFrames"] = optimizedFrames;
    ret["DeoptOnes"]       = totalDeoptOnes;
    ret["DeoptOnePercent"] = 100 * (float)totalDeoptOnes / (optimizedFrames || 1);
    ret["DeoptAlls"]       = totalDeoptAlls;
    ret["OSRs"]            = totalOSR;

    return ret;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkSurface.h"
#include "SkCanvas.h"

static void drawContents(SkSurface* surface, SkColor fillC) {
    SkSize size = SkSize::Make(surface->width(), surface->height());
    SkAutoTUnref<SkCanvas> canvas(surface->newCanvas());

    SkScalar stroke = size.fWidth / 10;
    SkScalar radius = (size.fWidth - stroke) / 2;

    SkPaint paint;

    paint.setAntiAlias(true);
    paint.setColor(fillC);
    canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);

    paint.setStyle(SkPaint::kStroke_Style);
    paint.setStrokeWidth(stroke);
    paint.setColor(SK_ColorBLACK);
    canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);
}

static void test_surface(SkCanvas* canvas, SkSurface* surf) {
    drawContents(surf, SK_ColorRED);
    SkImage* imgR = surf->newImageShapshot();

    drawContents(surf, SK_ColorGREEN);
    SkImage* imgG = surf->newImageShapshot();

    drawContents(surf, SK_ColorBLUE);

    imgR->draw(canvas, 0, 0, NULL);
    imgG->draw(canvas, 0, 80, NULL);
    surf->draw(canvas, 0, 160, NULL);

    imgG->unref();
    imgR->unref();
}

class ImageGM : public skiagm::GM {
    void*   fBuffer;
    size_t  fBufferSize;
    SkSize  fSize;
    enum {
        W = 64,
        H = 64,
        RB = W * 4 + 8,
    };
public:
    ImageGM() {
        fBufferSize = RB * H;
        fBuffer = sk_malloc_throw(fBufferSize);
        fSize.set(SkIntToScalar(W), SkIntToScalar(H));
    }

    virtual ~ImageGM() {
        sk_free(fBuffer);
    }

protected:
    virtual SkString onShortName() {
        return SkString("image");
    }

    virtual SkISize onISize() {
        return SkISize::Make(640, 480);
    }

    virtual void onDraw(SkCanvas* canvas) {
        // since we draw into this directly, we need to start fresh
        sk_bzero(fBuffer, fBufferSize);

        SkImage::Info info;

        info.fWidth = W;
        info.fHeight = H;
        info.fColorType = SkImage::kPMColor_ColorType;
        info.fAlphaType = SkImage::kPremul_AlphaType;
        SkAutoTUnref<SkSurface> surf0(SkSurface::NewRasterDirect(info, NULL, fBuffer, RB));
        SkAutoTUnref<SkSurface> surf1(SkSurface::NewRaster(info, NULL));
        SkAutoTUnref<SkSurface> surf2(SkSurface::NewPicture(info.fWidth, info.fHeight));

        test_surface(canvas, surf0);
        canvas->translate(80, 0);
        test_surface(canvas, surf1);
        canvas->translate(80, 0);
        test_surface(canvas, surf2);
    }

private:
    typedef skiagm::GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static skiagm::GM* MyFactory(void*) { return new ImageGM; }
static skiagm::GMRegistry reg(MyFactory);

<commit_msg>update to surface.getCanvas()<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkSurface.h"
#include "SkCanvas.h"

static void drawContents(SkSurface* surface, SkColor fillC) {
    SkSize size = SkSize::Make(surface->width(), surface->height());
    SkCanvas* canvas = surface->getCanvas();

    SkScalar stroke = size.fWidth / 10;
    SkScalar radius = (size.fWidth - stroke) / 2;

    SkPaint paint;

    paint.setAntiAlias(true);
    paint.setColor(fillC);
    canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);

    paint.setStyle(SkPaint::kStroke_Style);
    paint.setStrokeWidth(stroke);
    paint.setColor(SK_ColorBLACK);
    canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);
}

static void test_surface(SkCanvas* canvas, SkSurface* surf) {
    drawContents(surf, SK_ColorRED);
    SkImage* imgR = surf->newImageShapshot();

    drawContents(surf, SK_ColorGREEN);
    SkImage* imgG = surf->newImageShapshot();

    drawContents(surf, SK_ColorBLUE);

    SkPaint paint;
//    paint.setFilterBitmap(true);
//    paint.setAlpha(0x80);

    imgR->draw(canvas, 0, 0, &paint);
    imgG->draw(canvas, 0, 80, &paint);
    surf->draw(canvas, 0, 160, &paint);

    imgG->unref();
    imgR->unref();
}

class ImageGM : public skiagm::GM {
    void*   fBuffer;
    size_t  fBufferSize;
    SkSize  fSize;
    enum {
        W = 64,
        H = 64,
        RB = W * 4 + 8,
    };
public:
    ImageGM() {
        fBufferSize = RB * H;
        fBuffer = sk_malloc_throw(fBufferSize);
        fSize.set(SkIntToScalar(W), SkIntToScalar(H));
    }

    virtual ~ImageGM() {
        sk_free(fBuffer);
    }

protected:
    virtual SkString onShortName() {
        return SkString("image");
    }

    virtual SkISize onISize() {
        return SkISize::Make(640, 480);
    }

    virtual void onDraw(SkCanvas* canvas) {
        canvas->translate(10, 10);
        canvas->scale(2, 2);

        // since we draw into this directly, we need to start fresh
        sk_bzero(fBuffer, fBufferSize);

        SkImage::Info info;

        info.fWidth = W;
        info.fHeight = H;
        info.fColorType = SkImage::kPMColor_ColorType;
        info.fAlphaType = SkImage::kPremul_AlphaType;
        SkAutoTUnref<SkSurface> surf0(SkSurface::NewRasterDirect(info, NULL, fBuffer, RB));
        SkAutoTUnref<SkSurface> surf1(SkSurface::NewRaster(info, NULL));
        SkAutoTUnref<SkSurface> surf2(SkSurface::NewPicture(info.fWidth, info.fHeight));

        test_surface(canvas, surf0);
        canvas->translate(80, 0);
        test_surface(canvas, surf1);
        canvas->translate(80, 0);
        test_surface(canvas, surf2);
    }

private:
    typedef skiagm::GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static skiagm::GM* MyFactory(void*) { return new ImageGM; }
static skiagm::GMRegistry reg(MyFactory);

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>

using std::string;
using std::cout;
using std::endl;
using std::vector;

void CheckMakeArrayPixelXList (int i, vector<int> & GlobalArray, binary_type * MyGrpArray, string str);
//void CheckMakeArrayPixelYList (int i, vector<int> & GlobalArray, binary_type * MyGrpArray);

void CheckMakeArrayPixelXList (int i, vector<int> & GlobalArray, binary_type * MyGrpArray, string str)
{

    if (str == "PIXELX")
    {
	  cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELX_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] after MakeArray_pixelX in CalculateArray is correct: " << endl;
    }
  else if (str == "PIXELY")
    {
          cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELY_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] after MakeArray_pixelY in CalculateArray is correct: " << endl;
    }
    else if (str == "PIXELYbefore")
    {
          cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELY_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] before MakeArray_pixelY in CalculateArray is correct: " << endl;
    }
    else if (str == "TBIN")
    {
	  cout << endl << "****RETRIEVER_MAKE_ARRAY_TBIN_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] after MakeArray_Tbin in CalculateArray is correct: " << endl;
    }
    else if (str == "EVERYTHING")
    {
	  cout << endl << "****RETRIEVER_EVERYTHING****************************************";
	  cout << endl << "Check if MyGrpArray["<<i<<"] in CalculateArray is correct: " << endl<<endl;
    }

	  int ll = 0;
	  int mm = 0;
          cout << "   ";

	  for (int j=0; j<GlobalArray[1]*GlobalArray[2]*GlobalArray[0]; ++j)
	    {
	      cout << MyGrpArray[j] << " ";            //listing of MyGrpArray

	      if (ll == (GlobalArray[2]-1))
		{
		  cout << endl << "   ";
		  ll = 0;
		  ++mm;
		}
	      else
		{
		  ++ll;
		}
	      if (mm == (GlobalArray[1]))
		{
		  cout << endl;
		  cout << "   ";
		  mm = 0;
		}
	    }

  return;
}
<commit_msg>Added new testing function imported from retriever.cpp<commit_after>#include <iostream>
#include <vector>
#include <string>

using std::string;
using std::cout;
using std::endl;
using std::vector;

void CheckMakeArrayPixelList (int i, vector<int> & GlobalArray, binary_type * MyGrpArray, string str);
void checkMakePriorities(vector<int> & GrpPriority, int GrpPriority_size);
void checkGrpParaValue(int i, vector<Grp_parameters> & GrpPara);
void view_array(int & x, int & y, int & z, binary_type * MyGrpArray);
void checkDeclaration(vector<int> & LocalArray, vector<int> & GlobalArray);

void CheckMakeArrayPixelList (int i, vector<int> & GlobalArray, binary_type * MyGrpArray, string str)
{

    if (str == "PIXELX")
    {
	  cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELX_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] after MakeArray_pixelX in CalculateArray is correct: " << endl;
    }
  else if (str == "PIXELY")
    {
          cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELY_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] after MakeArray_pixelY in CalculateArray is correct: " << endl;
    }
    else if (str == "PIXELYbefore")
    {
          cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELY_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] before MakeArray_pixelY in CalculateArray is correct: " << endl;
    }
    else if (str == "TBIN")
    {
	  cout << endl << "****RETRIEVER_MAKE_ARRAY_TBIN_LIST****************************************"<<endl;
	  cout << endl << "Check if MyGrpArray["<<i<<"] after MakeArray_Tbin in CalculateArray is correct: " << endl;
    }
    else if (str == "EVERYTHING")
    {
	  cout << endl << "****RETRIEVER_EVERYTHING****************************************";
	  cout << endl << "Check if MyGrpArray["<<i<<"] in CalculateArray is correct: " << endl<<endl;
    }
    else if (str == "FINAL")
    {
	  cout << endl << "****RETRIEVER_FINAL_RESULT****************************************";
	  cout << endl << "Check the final NewArray: " << endl<<endl;
    }
    else if (str == "PIXELID")
    {
	  cout << endl << "****RETRIEVER_MAKE_ARRAY_PIXELID_LIST*******************************"<<endl;;
	  cout << endl << "Check if MyGrpArray in Make_PixelID is correct: " << endl;
    }

	  int ll = 0;
	  int mm = 0;
          cout << "   ";

	  for (int j=0; j<GlobalArray[1]*GlobalArray[2]*GlobalArray[0]; ++j)
	    {
	      cout << MyGrpArray[j] << " ";            //listing of MyGrpArray

	      if (ll == (GlobalArray[2]-1))
		{
		  cout << endl << "   ";
		  ll = 0;
		  ++mm;
		}
	      else
		{
		  ++ll;
		}
	      if (mm == (GlobalArray[1]))
		{
		  cout << endl;
		  cout << "   ";
		  mm = 0;
		}
	    }

  return;
}

void checkMakePriorities(vector<int> & GrpPriority, int GrpPriority_size)
{
    cout << endl << "****RETRIEVER_MAKE_PRIORITIES***************************"<<endl;

      for (int j=0; j<GrpPriority_size;j++)
	{
	  if (GrpPriority[j]>-1)
	    {
	      cout << "   Grp["<<j<<"]/Pri#"<<GrpPriority[j];
	    }
	  else
	    {
	      cout << "   Grp["<<j<<"]/Pri#"<<GrpPriority[j]+1<<" ==>Done!"<<endl;
	    }
	}

      cout << endl;

  return;
}

void checkGrpParaValue(int i, vector<Grp_parameters> & GrpPara)
{
  cout << endl << "Def["<<i<<"], list of values from list of identifiers: " << endl;

   for (int j=0; j<GrpPara[i].value.size(); j++)
    {
      cout << "   GrpPara.value["<<i<<"]= " << GrpPara[i].value[j]<<endl;
    }

  return;
}

/*******************************************
/Print array for testing purpose
/*******************************************/
void view_array(int & x, int & y, int & z, binary_type * MyGrpArray)
{
   for (int a=0; a<y;++a)
	{
	  for (int b=0; b<x;++b)
	    {
	      for (int c=0; c<z;++c)
		{
		  cout << MyGrpArray[c+b*y*z+a*z];

		  cout << " ";
		}
	      cout << "\t";
	    }
	  cout << endl;
	}
      cout << endl;

      return;
}

void checkDeclaration(vector<int> & LocalArray, vector<int> & GlobalArray)
{
  cout << endl << "Parsing of values: " << endl;
  cout << "   Local array" << endl;

  for (int j=0; j<LocalArray.size();j++)
    {
      cout << "      LocalArray["<<j<<"]= "<<LocalArray[j];
    }

  cout << endl <<"   Global array" << endl;

  for (int k=0; k<GlobalArray.size();++k)
    {
      cout << "      GlobalArray["<<k<<"]= "<<GlobalArray[k];
    }
  return;
}
<|endoftext|>