示例#1
0
/*
 * Hook and mod_cache callback functions
 */
static int create_entity(cache_handle_t *h, request_rec *r, const char *key, apr_off_t len)
{
    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                 &disk_cache_module);
    cache_object_t *obj;
    disk_cache_object_t *dobj;

    if (conf->cache_root == NULL) {
        return DECLINED;
    }

    /* Allocate and initialize cache_object_t and disk_cache_object_t */
    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(*obj));
    obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(*dobj));

    obj->key = apr_pstrdup(r->pool, key);

    dobj->name = obj->key;
    dobj->prefix = NULL;
    /* Save the cache root */
    dobj->root = apr_pstrndup(r->pool, conf->cache_root, conf->cache_root_len);
    dobj->root_len = conf->cache_root_len;
    dobj->datafile = data_file(r->pool, conf, dobj, key);
    dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);

    return OK;
}
void api_generator::generate_rpc_client_files(const fc::path& rpc_client_output_dir, const std::string& generated_filename_suffix)
{
  std::string client_classname = _api_classname + "_rpc_client";

  fc::path client_header_path = rpc_client_output_dir / "include" / "bts" / "rpc_stubs";
  fc::create_directories(client_header_path); // creates dirs for both header and cpp
  fc::path client_header_filename = client_header_path / (client_classname + ".hpp");
  fc::path client_cpp_filename = rpc_client_output_dir / (client_classname + ".cpp");
  fc::path method_overrides_filename = client_header_path / (_api_classname + "_overrides.ipp");
  std::ofstream header_file(client_header_filename.string() + generated_filename_suffix);
  std::ofstream cpp_file(client_cpp_filename.string() + generated_filename_suffix);
  std::ofstream method_overrides_file(method_overrides_filename.string() + generated_filename_suffix);

  write_generated_file_header(header_file);
  write_generated_file_header(method_overrides_file);
  header_file << "#pragma once\n\n";
  header_file << "#include <fc/rpc/json_connection.hpp>\n";
  header_file << "#include <bts/api/" << _api_classname << ".hpp>\n\n";
  header_file << "namespace bts { namespace rpc_stubs {\n\n";
  header_file << "  class " << client_classname << " : public bts::api::" << _api_classname << "\n";
  header_file << "  {\n";
  header_file << "  public:\n";
  header_file << "    virtual fc::rpc::json_connection_ptr get_json_connection() const = 0;\n\n";
  for (const method_description& method : _methods)
  {
    header_file << "    " << generate_signature_for_method(method, "", true) << " override;\n";
    method_overrides_file << "    " << generate_signature_for_method(method, "", true) << " override;\n";
  }

  header_file << "  };\n\n";
  header_file << "} } // end namespace bts::rpc_stubs\n";

  write_generated_file_header(cpp_file);
  cpp_file << "#include <bts/rpc_stubs/" << client_classname << ".hpp>\n";
  cpp_file << "#include <bts/api/conversion_functions.hpp>\n\n";
  cpp_file << "namespace bts { namespace rpc_stubs {\n\n";

  for (const method_description& method : _methods)
  {
    cpp_file << generate_signature_for_method(method, client_classname, false) << "\n";
    cpp_file << "{\n";

    cpp_file << "  fc::variant result = get_json_connection()->async_call(\"" << method.name << "\"";
    for (const parameter_description& parameter : method.parameters)
      cpp_file << ", " << parameter.type->convert_object_of_type_to_variant(parameter.name);
    cpp_file << ").wait();\n";

    if (!std::dynamic_pointer_cast<void_type_mapping>(method.return_type))
      cpp_file << "  return " << method.return_type->convert_variant_to_object_of_type("result") << ";\n";
    cpp_file << "}\n";
  }
  cpp_file << "\n";
  cpp_file << "} } // end namespace bts::rpc_stubs\n";
}
示例#3
0
bool HEADER_DOSYASI_YARAT( QWidget * parent )
{
    SQL_QUERY yonetim_query ( G_YONETIM_DB);
    SQL_QUERY db_query      ( DB          );

    db_query.PREPARE_SELECT     ("sql_db_info","program_id");

    if ( db_query.SELECT () EQ 0 ) {
        exit(88);
    }

    db_query.NEXT();

    int program_id = db_query.VALUE(0).toInt();

    yonetim_query.PREPARE_SELECT("ynt_veritabanlari", "veritabani_ismi","veritabani_id = :veritabani_id");
    yonetim_query.SET_VALUE(":veritabani_id", VERITABANI_ID());
    if ( yonetim_query.SELECT("veritabani_ismi") EQ 0 ) {
        return false;
    }
    yonetim_query.NEXT();
    QString db_name   = yonetim_query.VALUE(0).toString();
    QString file_path = db_name.toLower() + "_db.h";


    QFile header_file ( file_path );
    header_file.open(QIODevice::WriteOnly | QIODevice::Text);

    file_content = "#ifndef " + db_name.toUpper() + "_DB_H\n"
                   "#define " + db_name.toUpper() + "_DB_H\n\n";

    file_content += nl( "ADAK_SQL_STRUCT " + db_name + "_db" +  " = {" );
    file_content += tab (1, nl(QVariant(program_id).toString() + ","));

    TABLOLARI_YAZ ( parent );

    file_content += nl("};");


    file_content +=  "#endif // " + db_name.toUpper() + "_DB_H \n";

    header_file.write ( file_content.toLatin1() );
    header_file.close();

    return true;
}
void level_converter::generate_level_header_file()
{
    fstream header_file( output_prefix() + string(".hpp"), ios_base::out );

    header_file << "#ifndef " << output_basename << "_hpp\n"
                << "#define " << output_basename << "_hpp\n\n\n"
                << "#include \"../game_engine_stuff/level_stuff/"
                << "level_class.hpp\"\n"
                << "#include \"../game_engine_stuff/level_stuff/"
                << "sprite_level_data_stuff.hpp\"\n";

    header_file << "\n\n";

    for ( tiled_sublevel& the_tiled_sublevel : tiled_sublevel_vec )
    {
        header_file << "// " << the_tiled_sublevel.sublevel_file_name
                    << "\n";

        header_file << "extern const sublevel< "
                    << the_tiled_sublevel.the_sublevel.compressed_block_data_vec
                    .size() << ", "
                    << the_tiled_sublevel.the_sublevel.real_size_2d.x << ", "
                    << the_tiled_sublevel.the_sublevel.real_size_2d.y << ", "
                    << the_tiled_sublevel.the_sublevel.sprite_ipg_vec.size() << ", "
                    << the_tiled_sublevel.the_sublevel.sublevel_entrance_vec.size()
                    << " > " << output_basename << "_"
                    << the_tiled_sublevel.output_basename << ";\n\n";

    }


    header_file << "\nextern const level " << output_basename << ";\n";

    header_file << "\n\n";

    header_file << "#endif\t\t// " << output_basename << "_hpp";


}
void primary_widget::generate_level_header_file
	( const string& output_dirname, const string& output_basename )
{
	level& the_level = the_central_widget->the_level;
	
	fstream header_file( output_dirname + "/" + output_basename 
		+ string(".hpp"), ios_base::out );
	
	header_file << "#ifndef " << output_basename << "_hpp\n"
		<< "#define " << output_basename << "_hpp\n\n\n"
		<< "#include \"../game_engine_stuff/level_stuff/"
		<< "level_class.hpp\"\n"
		<< "#include \"../game_engine_stuff/level_stuff/"
		<< "sprite_level_data_stuff.hpp\"\n";
	
	header_file << "\n\n";
	
	for ( u32 i=0; i<the_level.sublevel_vec.size(); ++i )
	{
		sublevel& the_sublevel = the_level.sublevel_vec.at(i);
		
		header_file << "extern const sublevel< "
			<< the_sublevel.compressed_block_data_vec.size() << ", " 
			<< the_sublevel.real_size_2d.x << ", " 
			<< the_sublevel.real_size_2d.y << ", "
			<< the_sublevel.sprite_ipgws_vec_for_exporting.size() << ", "
			<< the_sublevel.sublevel_entrance_vec.size() 
			<< " > " << output_basename << "_sublevel_" << i << ";\n\n";
	}
	
	
	header_file << "\nextern const level " << output_basename << ";\n";
	
	header_file << "\n\n";
	
	header_file << "#endif\t\t// " << output_basename << "_hpp";
}
示例#6
0
static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *info)
{
    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                 &disk_cache_module);
    apr_status_t rv;
    apr_size_t amt;
    disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;

    disk_cache_info_t disk_info;
    struct iovec iov[2];

    /* This is flaky... we need to manage the cache_info differently */
    h->cache_obj->info = *info;

    if (r->headers_out) {
        const char *tmp;

        tmp = apr_table_get(r->headers_out, "Vary");

        if (tmp) {
            apr_array_header_t* varray;
            apr_uint32_t format = VARY_FORMAT_VERSION;

            /* If we were initially opened as a vary format, rollback
             * that internal state for the moment so we can recreate the
             * vary format hints in the appropriate directory.
             */
            if (dobj->prefix) {
                dobj->hdrsfile = dobj->prefix;
                dobj->prefix = NULL;
            }

            mkdir_structure(conf, dobj->hdrsfile, r->pool);

            rv = apr_file_mktemp(&dobj->tfd, dobj->tempfile,
                                 APR_CREATE | APR_WRITE | APR_BINARY | APR_EXCL,
                                 r->pool);

            if (rv != APR_SUCCESS) {
                return rv;
            }

            amt = sizeof(format);
            apr_file_write(dobj->tfd, &format, &amt);

            amt = sizeof(info->expire);
            apr_file_write(dobj->tfd, &info->expire, &amt);

            varray = apr_array_make(r->pool, 6, sizeof(char*));
            tokens_to_array(r->pool, tmp, varray);

            store_array(dobj->tfd, varray);

            apr_file_close(dobj->tfd);

            dobj->tfd = NULL;

            rv = safe_file_rename(conf, dobj->tempfile, dobj->hdrsfile,
                                  r->pool);
            if (rv != APR_SUCCESS) {
                ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server,
                    "disk_cache: rename tempfile to varyfile failed: %s -> %s",
                    dobj->tempfile, dobj->hdrsfile);
                apr_file_remove(dobj->tempfile, r->pool);
                return rv;
            }

            dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
            tmp = regen_key(r->pool, r->headers_in, varray, dobj->name);
            dobj->prefix = dobj->hdrsfile;
            dobj->hashfile = NULL;
            dobj->datafile = data_file(r->pool, conf, dobj, tmp);
            dobj->hdrsfile = header_file(r->pool, conf, dobj, tmp);
        }
    }


    rv = apr_file_mktemp(&dobj->hfd, dobj->tempfile,
                         APR_CREATE | APR_WRITE | APR_BINARY |
                         APR_BUFFERED | APR_EXCL, r->pool);

    if (rv != APR_SUCCESS) {
        return rv;
    }

    disk_info.format = DISK_FORMAT_VERSION;
    disk_info.date = info->date;
    disk_info.expire = info->expire;
    disk_info.entity_version = dobj->disk_info.entity_version++;
    disk_info.request_time = info->request_time;
    disk_info.response_time = info->response_time;
    disk_info.status = info->status;

    disk_info.name_len = strlen(dobj->name);

    iov[0].iov_base = (void*)&disk_info;
    iov[0].iov_len = sizeof(disk_cache_info_t);
    iov[1].iov_base = (void*)dobj->name;
    iov[1].iov_len = disk_info.name_len;

    rv = apr_file_writev(dobj->hfd, (const struct iovec *) &iov, 2, &amt);
    if (rv != APR_SUCCESS) {
        return rv;
    }

    if (r->headers_out) {
        apr_table_t *headers_out;

        headers_out = ap_cache_cacheable_hdrs_out(r->pool, r->headers_out,
                                                  r->server);

        if (!apr_table_get(headers_out, "Content-Type")
            && r->content_type) {
            apr_table_setn(headers_out, "Content-Type",
                           ap_make_content_type(r, r->content_type));
        }

        headers_out = apr_table_overlay(r->pool, headers_out,
                                        r->err_headers_out);
        rv = store_table(dobj->hfd, headers_out);
        if (rv != APR_SUCCESS) {
            return rv;
        }
    }

    /* Parse the vary header and dump those fields from the headers_in. */
    /* FIXME: Make call to the same thing cache_select calls to crack Vary. */
    if (r->headers_in) {
        apr_table_t *headers_in;

        headers_in = ap_cache_cacheable_hdrs_out(r->pool, r->headers_in,
                                                 r->server);
        rv = store_table(dobj->hfd, headers_in);
        if (rv != APR_SUCCESS) {
            return rv;
        }
    }

    apr_file_close(dobj->hfd); /* flush and close */

    /* Remove old file with the same name. If remove fails, then
     * perhaps we need to create the directory tree where we are
     * about to write the new headers file.
     */
    rv = apr_file_remove(dobj->hdrsfile, r->pool);
    if (rv != APR_SUCCESS) {
        mkdir_structure(conf, dobj->hdrsfile, r->pool);
    }

    rv = safe_file_rename(conf, dobj->tempfile, dobj->hdrsfile, r->pool);
    if (rv != APR_SUCCESS) {
        ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server,
                     "disk_cache: rename tempfile to hdrsfile failed: %s -> %s",
                     dobj->tempfile, dobj->hdrsfile);
        apr_file_remove(dobj->tempfile, r->pool);
        return rv;
    }

    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);

    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                 "disk_cache: Stored headers for URL %s",  dobj->name);
    return APR_SUCCESS;
}
示例#7
0
static int open_entity(cache_handle_t *h, request_rec *r, const char *key)
{
    apr_uint32_t format;
    apr_size_t len;
    const char *nkey;
    apr_status_t rc;
    static int error_logged = 0;
    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                 &disk_cache_module);
    apr_finfo_t finfo;
    cache_object_t *obj;
    cache_info *info;
    disk_cache_object_t *dobj;
    int flags;

    h->cache_obj = NULL;

    /* Look up entity keyed to 'url' */
    if (conf->cache_root == NULL) {
        if (!error_logged) {
            error_logged = 1;
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                         "disk_cache: Cannot cache files to disk without a CacheRoot specified.");
        }
        return DECLINED;
    }

    /* Create and init the cache object */
    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
    obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));

    info = &(obj->info);

    /* Open the headers file */
    dobj->prefix = NULL;

    /* Save the cache root */
    dobj->root = apr_pstrndup(r->pool, conf->cache_root, conf->cache_root_len);
    dobj->root_len = conf->cache_root_len;

    dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
    flags = APR_READ|APR_BINARY|APR_BUFFERED;
    rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
    if (rc != APR_SUCCESS) {
        return DECLINED;
    }

    /* read the format from the cache file */
    len = sizeof(format);
    apr_file_read_full(dobj->hfd, &format, len, &len);

    if (format == VARY_FORMAT_VERSION) {
        apr_array_header_t* varray;
        apr_time_t expire;

        len = sizeof(expire);
        apr_file_read_full(dobj->hfd, &expire, len, &len);

        varray = apr_array_make(r->pool, 5, sizeof(char*));
        rc = read_array(r, varray, dobj->hfd);
        if (rc != APR_SUCCESS) {
            ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
                         "disk_cache: Cannot parse vary header file: %s",
                         dobj->hdrsfile);
            return DECLINED;
        }
        apr_file_close(dobj->hfd);

        nkey = regen_key(r->pool, r->headers_in, varray, key);

        dobj->hashfile = NULL;
        dobj->prefix = dobj->hdrsfile;
        dobj->hdrsfile = header_file(r->pool, conf, dobj, nkey);

        flags = APR_READ|APR_BINARY|APR_BUFFERED;
        rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
        if (rc != APR_SUCCESS) {
            return DECLINED;
        }
    }
    else if (format != DISK_FORMAT_VERSION) {
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                     "cache_disk: File '%s' has a version mismatch. File had version: %d.",
                     dobj->hdrsfile, format);
        return DECLINED;
    }
    else {
        apr_off_t offset = 0;
        /* This wasn't a Vary Format file, so we must seek to the
         * start of the file again, so that later reads work.
         */
        apr_file_seek(dobj->hfd, APR_SET, &offset);
        nkey = key;
    }

    obj->key = nkey;
    dobj->key = nkey;
    dobj->name = key;
    dobj->datafile = data_file(r->pool, conf, dobj, nkey);
    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);

    /* Open the data file */
    flags = APR_READ|APR_BINARY;
#ifdef APR_SENDFILE_ENABLED
    flags |= APR_SENDFILE_ENABLED;
#endif
    rc = apr_file_open(&dobj->fd, dobj->datafile, flags, 0, r->pool);
    if (rc != APR_SUCCESS) {
        /* XXX: Log message */
        return DECLINED;
    }

    rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, dobj->fd);
    if (rc == APR_SUCCESS) {
        dobj->file_size = finfo.size;
    }

    /* Read the bytes to setup the cache_info fields */
    rc = file_cache_recall_mydata(dobj->hfd, info, dobj, r);
    if (rc != APR_SUCCESS) {
        /* XXX log message */
        return DECLINED;
    }

    /* Initialize the cache_handle callback functions */
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                 "disk_cache: Recalled cached URL info header %s",  dobj->name);
    return OK;
}
示例#8
0
/*
* Recebe a resposta da requisição enviada
*/
int httpclient::read_page()
{
	ofstream out_file(webc->create_dir("webs/" + host + "/" + dir).c_str(), ofstream::binary); //Cria arquivo de saída para o conteúdo
	ofstream header_file(webc->create_dir("webs/" + host + "/" + dir + ".header").c_str(), ofstream::binary); //Cria arquivo de saída para o cabeçalho
	int tmp; //Auxiliar para controle do recebimento
	bool content = false, chunked = false;
	size_t pos; //Auxiliar para manipulação de strings
	tmp = recv(s, buffer, sizeof(buffer)-1, 0); //Solicita o recebimento de dados
	page = string("");
	header = string("");

	while (tmp > 0)
	{ //Enquanto tmp maior que 0 continua tentando receber
		if (content)
		{ //Verifica se o cabeçalho já foi todo recebido
			page.append(buffer, tmp); //Insere a parte do conteúdo recebida na string de conteúdo
		}
		else
		{ //O cabeçalho ainda não foi totalmente recebido
			char *ptr = strstr(buffer, "\r\n\r\n"); //Procura o final do cabeçalho GET HTTP/1.1
			if (ptr)
			{
				header.append(buffer, ptr - buffer + 4); //Insere na string de cabeçalho a parte deste pacote que faz parte do cabeçalho
				/* Verificação de conteúdo codificado */
				pos = str_find_ci(header, "Transfer-Encoding:"); //Procura a string que identifica a codificação de transferencia
				if (pos != string::npos)
				{ //Caso exista a codificação é analisada qual o tipo da mesma
					string encoding = header.substr(pos + 19, header.find("\r\n", pos) - (pos + 19));
					if (encoding == "chunked") //Verifica se é do tipo chunked
						chunked = true;
				}
				while (*ptr == '\r' || *ptr == '\n') ptr++;
				tmp = tmp - (ptr - buffer); //É obtido então quantos bytes do pacote atual fazem parte do corpo da mensagem
				if (tmp >= 0) //Verifica se o número de bytes de corpo remanescentes é válido
					page.append(ptr, tmp); //Insere na string de corpo a parte deste pacote que faz parte do corpo
				content = true; //Confirma que a partir deste momento todos os bytes serão de conteúdo
			}
			else
			{
				header.append(buffer, tmp); //Escreve todos os bytes recebidos na string de cabeçalho
			}
		}
		memset(buffer, 0, sizeof(buffer)-1);
		tmp = recv(s, buffer, sizeof(buffer)-1, 0); //Solicita o recebimento de dados
		buffer[tmp] = '\0';
	}

	if (errno != 0)
	{ //Verifica se houve algum erro no recv
		if (chunked)
		{ //Caso o Transfer-Encoding utilizado seja chunked
			size_t old = 0, next = 0, pos; //Auxiliares
			pos = page.find("\r\n", 0) + 2; //Procura o final da informação do chunk
			next = stoi(page, nullptr, 16); //Obtém a quantidade de bytes do chunk
			page.erase(old, pos - old); //Remove a informação do chunk do conteúdo da page
			old = next;
			while (next)
			{
				pos = page.find("\r\n", old + 2) + 2; //Procura o final da informação do chunk
				if (page[old + 2] != '0')
					next = stoi(&page[old + 2], nullptr, 16); //Obtém a quantidade de bytes do chunk
				else
					next = 0; //Chunk final
				page.erase(old, pos - old); //Remove a informação do chunk do conteúdo da page
				old += next;
			}
		}
	}
	header_file.write(page.c_str(), page.size()); //Escreve no arquivo do cabeçalho a string que contém o cabeçalho
	out_file.write(page.c_str(), page.size()); //Escreve no arquivo do corpo a string que contém o corpo

	header_file.close(); //Fecha os arquivos
	out_file.close();

	return 0;
}
示例#9
0
int main( int argc, char **argv ){
  string header_file( "header.mak" );
  string programs_file( "programs.mak" );

  // Flag indicates whether the CCFLAGS and CFLAGS output should
  // have -g debugging option omitted
  bool noDebugFlag( false );

  // Flag indicates using gnu compiler
  // bool useGCC = false;
  bool useGCC = true;

  // check gnu compiler make or sun compiler make
  // if first letter of executable is 'g' then gnu otherwise sun

  char *exename = argv[0];
  char c;

  while((c = *exename++)) {
    if(c == '/') {
      argv[0] = exename;
    }
  }
  if(argv[0][0] == 'g') {
    useGCC = true;
  }

  //
  // Process command line options
  //
  while( argc--, *++argv != 0 && **argv == '-' ){
    if( strcmp( *argv, "-header" ) == 0 && argv[ 1 ] != 0 ){
      header_file = *++argv;
      argc--;
    } else if( strcmp( *argv, "-no-header" ) == 0 ){
      header_file = "//";
    } else if( strcmp( *argv, "-programs" ) == 0 && argv[ 1 ] != 0 ){
      programs_file = *++argv;
      argc--;
    } else if( strcmp( *argv, "-no-programs" ) == 0 ){
      programs_file = "//";
    } else if(strcmp("-no-debug",*argv) == 0){
      noDebugFlag = true;
    } else {
      switch( *++*argv ){
      case 'd':
        debug = true;
        break;

      default:
        cerr << "Invalid option: -" << **argv << endl;
        exit( 1 );
      }
    }
  }

  //
  // Read the current directory (and cmd line arguments) to find 
  // file names.
  //
  DirList dirlist( argc, argv );

  //
  // Now write the makefile
  //
  Write write( dirlist, noDebugFlag, useGCC, header_file, programs_file );

  return 0;
}
void api_generator::generate_rpc_server_files(const fc::path& rpc_server_output_dir, const std::string& generated_filename_suffix)
{
  std::string server_classname = _api_classname + "_rpc_server";

  fc::path server_header_path = rpc_server_output_dir / "include" / "bts" / "rpc_stubs";
  fc::create_directories(server_header_path); // creates dirs for both header and cpp
  fc::path server_header_filename = server_header_path / (server_classname + ".hpp");
  fc::path server_cpp_filename = rpc_server_output_dir / (server_classname + ".cpp");
  std::ofstream header_file(server_header_filename.string() + generated_filename_suffix);
  std::ofstream server_cpp_file(server_cpp_filename.string() + generated_filename_suffix);

  write_generated_file_header(header_file);
  header_file << "#pragma once\n";
  header_file << "#include <bts/api/api_metadata.hpp>\n";
  header_file << "#include <bts/api/common_api.hpp>\n";
  header_file << "#include <fc/rpc/json_connection.hpp>\n\n";
  header_file << "namespace bts { namespace rpc_stubs {\n";
  header_file << "  class " << server_classname << "\n";
  header_file << "  {\n";
  header_file << "  public:\n";
  header_file << "    virtual bts::api::common_api* get_client() const = 0;\n";
  header_file << "    virtual void verify_json_connection_is_authenticated(const fc::rpc::json_connection_ptr& json_connection) const = 0;\n";
  header_file << "    virtual void verify_wallet_is_open() const = 0;\n";
  header_file << "    virtual void verify_wallet_is_unlocked() const = 0;\n";
  header_file << "    virtual void verify_connected_to_network() const = 0;\n\n";
  header_file << "    virtual void store_method_metadata(const bts::api::method_data& method_metadata) = 0;\n";
  header_file << "    fc::variant direct_invoke_positional_method(const std::string& method_name, const fc::variants& parameters);\n";
  header_file << "    void register_" << _api_classname << "_methods(const fc::rpc::json_connection_ptr& json_connection);\n\n";
  header_file << "    void register_" << _api_classname << "_method_metadata();\n\n";
  for (const method_description& method : _methods)
  {
    header_file << "    fc::variant " << method.name << "_positional(const fc::rpc::json_connection_ptr& json_connection, const fc::variants& parameters);\n";
    header_file << "    fc::variant " << method.name << "_named(const fc::rpc::json_connection_ptr& json_connection, const fc::variant_object& parameters);\n";
  }

  header_file << "  };\n\n";
  header_file << "} } // end namespace bts::rpc_stubs\n";

  write_generated_file_header(server_cpp_file);
  server_cpp_file << "#include <bts/rpc_stubs/" << server_classname << ".hpp>\n";
  server_cpp_file << "#include <bts/api/api_metadata.hpp>\n";
  server_cpp_file << "#include <bts/api/conversion_functions.hpp>\n";
  server_cpp_file << "#include <boost/bind.hpp>\n";
  write_includes_to_stream(server_cpp_file);
  server_cpp_file << "\n";
  server_cpp_file << "namespace bts { namespace rpc_stubs {\n\n";

  // Generate the method bodies
  for (const method_description& method : _methods)
  {
    generate_positional_server_implementation_to_stream(method, server_classname, server_cpp_file);
    generate_named_server_implementation_to_stream(method, server_classname, server_cpp_file);
  }

  // Generate a function that registers all of the methods with the JSON-RPC dispatcher
  server_cpp_file << "void " << server_classname << "::register_" << _api_classname << "_methods(const fc::rpc::json_connection_ptr& json_connection)\n";
  server_cpp_file << "{\n";
  server_cpp_file << "  fc::rpc::json_connection::method bound_positional_method;\n";
  server_cpp_file << "  fc::rpc::json_connection::named_param_method bound_named_method;\n";
  for (const method_description& method : _methods)
  {
    server_cpp_file << "  // register method " << method.name << "\n";
    server_cpp_file << "  bound_positional_method = boost::bind(&" << server_classname << "::" << method.name << "_positional, \n";
    server_cpp_file << "                                        this, json_connection, _1);\n";
    server_cpp_file << "  json_connection->add_method(\"" << method.name << "\", bound_positional_method);\n";
    for (const std::string& alias : method.aliases)
      server_cpp_file << "  json_connection->add_method(\"" << alias << "\", bound_positional_method);\n";
    server_cpp_file << "  bound_named_method = boost::bind(&" << server_classname << "::" << method.name << "_named, \n";
    server_cpp_file << "                                        this, json_connection, _1);\n";
    server_cpp_file << "  json_connection->add_named_param_method(\"" << method.name << "\", bound_named_method);\n";
    for (const std::string& alias : method.aliases)
      server_cpp_file << "  json_connection->add_named_param_method(\"" << alias << "\", bound_named_method);\n";
    server_cpp_file << "\n";
  }
  server_cpp_file << "}\n\n";

  // generate a function that registers all method metadata
  server_cpp_file << "void " << server_classname << "::register_" << _api_classname << "_method_metadata()\n";
  server_cpp_file << "{\n";
  for (const method_description& method : _methods)
  {
    server_cpp_file << "  // register method " << method.name << "\n";
    server_cpp_file << "  bts::api::method_data " << method.name << "_method_metadata{\"" << method.name << "\", nullptr,\n";
    server_cpp_file << "    /* description */ " << bts::utilities::escape_string_for_c_source_code(method.brief_description) << ",\n";
    server_cpp_file << "    /* returns */ \"" << method.return_type->get_type_name() << "\",\n";
    server_cpp_file << "    /* params: */ {";
    bool first_parameter = true;
    for (const parameter_description& parameter : method.parameters)
    {
      if (first_parameter)
        first_parameter = false;
      else
        server_cpp_file << ",\n  ";
      server_cpp_file << "    {\"" << parameter.name << "\", \"" << parameter.type->get_type_name() <<  "\", bts::api::";
      if (parameter.default_value)
        server_cpp_file << "optional_positional, fc::variant(fc::json::from_string(" << bts::utilities::escape_string_for_c_source_code(fc::json::to_string(parameter.default_value)) << "))}";
      else
        server_cpp_file << "required_positional, fc::ovariant()}";
    }
    server_cpp_file <<  "},\n";
    server_cpp_file << "    /* prerequisites */ (bts::api::method_prerequisites)" << (int)method.prerequisites << ", \n";
    server_cpp_file << "    /* detailed description */ " << bts::utilities::escape_string_for_c_source_code(generate_detailed_description_for_method(method)) << ",\n";
    server_cpp_file << "    /* aliases */ {";
    if (!method.aliases.empty())
    {
      bool first = true;
      for (const std::string& alias : method.aliases)
      {
        if (first)
          first = false;
        else
          server_cpp_file << ", ";
        server_cpp_file << "\"" << alias << "\"";
      }
    }
    server_cpp_file << "}};\n";
      
    server_cpp_file << "  store_method_metadata(" << method.name << "_method_metadata);\n\n";
  }
  server_cpp_file << "}\n\n";

  // generate a function for directly invoking a method, probably a stop-gap until we finish migrating all methods to this code
  server_cpp_file << "fc::variant " << server_classname << "::direct_invoke_positional_method(const std::string& method_name, const fc::variants& parameters)\n";
  server_cpp_file << "{\n";
  for (const method_description& method : _methods)
  {
    server_cpp_file << "  if (method_name == \"" << method.name << "\")\n";
    server_cpp_file << "    return " << method.name << "_positional(nullptr, parameters);\n";
  }
  server_cpp_file << "  FC_ASSERT(false, \"shouldn't happen\");\n";
  server_cpp_file << "}\n";

  server_cpp_file << "\n";
  server_cpp_file << "} } // end namespace bts::rpc_stubs\n";
}
示例#11
0
int main(int argc, char** argv)
{
    std::cout<<"exec volmesh.vtk|vtu surfmesh.vtk out_labels.txt arrayname volmesh_out.vtk scale correct_orientation(0|1)"<<std::endl;
    std::cout<<"Scale - rescale mesh by this factor, !!! for now works only for ALYA, for everything else put 1"<<std::endl;
    std::cout<<"correct_orientation - 1 or 0 whether to correct cell orientation or not"<<std::endl;
    std::cout<<"Labels must be celldata"<<std::endl;
    std::cout<<"Add extension .bsc to volmesh_out to get mesh in Alya format"<<std::endl;
    std::cout<<"Skip extension in volmesh_out to get mesh in Elmer format"<<std::endl;
    std::cout<<"out_labels.txt -- faces with labels, format: label point1 point2 point3 tetra_id"<<std::endl;
     
    
    
    if(argc<4) return -1;
    
    const char* volmesh_file = argv[1];
    const char* surfmesh_file = argv[2];
    const char* outfile = argv[3];
    const char* array_name = argv[4];
    const char* volmeshout = argv[5];
    
    float scale = atof(argv[6]);
    bool correct_orientation = atoi(argv[7])==1;
    
    
    std::cout<<"Volumetric mesh: "<<volmesh_file<<std::endl;
    std::cout<<"Surface mesh: "<<surfmesh_file<<std::endl;
    std::cout<<"Labels: "<<outfile<<std::endl;
    std::cout<<"Label array: "<<array_name<<std::endl;
    std::cout<<"Output mesh: "<<volmeshout<<std::endl;
    std::cout<<"Scale: "<<scale<<std::endl;
    if(correct_orientation)
        std::cout<<"Correcting orientation: ON"<<std::endl;
    else
        std::cout<<"Correcting orientation: OFF"<<std::endl;
    
    
    bool vtkoutput_mesh = false;
    bool alyaoutput_mesh = false;
        
    if(volmeshout!=NULL)
    {
        const char *ext = volmeshout+strlen(volmeshout)-4;
        if(strcmp(ext,".vtk")==0)  //if we are requesting .node .element volumetric mesh    
            vtkoutput_mesh = true;
        else if(strcmp(ext,".bsc")==0)
            alyaoutput_mesh = true;
    }


    vtkSmartPointer<vtkUnstructuredGrid> volmesh =     vtkSmartPointer<vtkUnstructuredGrid>::New();
    if (volmesh_file[ strlen(volmesh_file)-1 ] == 'k') //vtk
    {

        vtkSmartPointer<vtkDataSetReader> vol_rdr = vtkSmartPointer<vtkDataSetReader>::New();
        CommonTools::AssociateProgressFunction(vol_rdr);

        vol_rdr->SetFileName(volmesh_file);
        vol_rdr->Update();
        volmesh->DeepCopy( (vtkUnstructuredGrid*)vol_rdr->GetOutput() );
    }    
    else
    {
        vtkSmartPointer<vtkXMLUnstructuredGridReader> vol_rdr = vtkSmartPointer<vtkXMLUnstructuredGridReader>::New();
        CommonTools::AssociateProgressFunction(vol_rdr);

        vol_rdr->SetFileName(volmesh_file);
        vol_rdr->Update();
        volmesh->DeepCopy( (vtkUnstructuredGrid*)vol_rdr->GetOutput() );
     }


    if(volmesh->GetCell(0)->GetNumberOfPoints()<4)
    {
        std::cout<<"Supplied volumetric mesh has cells with : "<<volmesh->GetCell(0)->GetNumberOfPoints()<<" vertices"<<std::endl;
        std::cout<<"Make sure your mesh is actually volumetric"<<std::endl;
        exit(-1);
    }

    
    
    vtkSmartPointer<vtkPolyDataReader> poly_rdr = vtkSmartPointer<vtkPolyDataReader>::New();
    CommonTools::AssociateProgressFunction(poly_rdr);

    poly_rdr->SetFileName(surfmesh_file);
    poly_rdr->Update();
    vtkPolyData* surfmesh = poly_rdr->GetOutput();
    
    //read cell scalars from the surface mesh (labels)
    auto scalars = surfmesh->GetCellData()->GetArray(array_name);
    
    vtkSmartPointer<vtkPointLocator> ptloc = vtkSmartPointer<vtkPointLocator>::New();
    ptloc->SetDataSet(volmesh);
    ptloc->BuildLocator();
    
    vtkSmartPointer<vtkCellLocator> cellloc = vtkSmartPointer<vtkCellLocator>::New();
    cellloc->SetDataSet(volmesh);
    cellloc->BuildLocator();
    
    if(volmeshout!=NULL)
    {
        //create PointData array in the volumetric mesh with labels
        
        //pass the cell array with labels to point array
        vtkSmartPointer<vtkCellDataToPointData> c2pdata = vtkSmartPointer<vtkCellDataToPointData>::New();
        c2pdata->SetInputData(surfmesh);
        c2pdata->PassCellDataOn();
        c2pdata->Update();

        auto pscalars = c2pdata->GetOutput()->GetPointData()->GetArray(array_name);
        
        //to store ids with the tetra mesh points
        vtkSmartPointer<vtkShortArray> volmesh_regions = vtkSmartPointer<vtkShortArray>::New();
        volmesh_regions->SetName(array_name);
        volmesh_regions->SetNumberOfComponents(1);
        volmesh_regions->SetNumberOfValues(volmesh->GetNumberOfPoints());

        //fill the array of scalars to store with volumetric mesh
        for(vtkIdType i=0; i<volmesh->GetNumberOfPoints();i++)
        {
            volmesh_regions->SetTuple1(i,0);
        }

        //for every cell of the surface mesh
        for(vtkIdType i=0; i<surfmesh->GetNumberOfPoints(); i++)
        {
            vtkIdType ptid = ptloc->FindClosestPoint(surfmesh->GetPoint(i));
            volmesh_regions->SetTuple1(ptid, pscalars->GetTuple1(i));
        }
        
        volmesh->GetPointData()->AddArray(volmesh_regions);

        //:~ create PointData array in the volumetric mesh with labels
    }
    
    std::vector<BscEntry> labeldata;
    
    //create std::vector with information about the cell and point ids for every label
    //for every cell of the surface mesh
    std::cout<<"Looking for boundaries"<<std::endl;
    for(vtkIdType i=0; i<surfmesh->GetNumberOfCells(); i++)
    {
        if( i%10000 == 0 )
            std::cout<<"Cell "<<i<<"/"<<surfmesh->GetNumberOfCells()<<"\r"<<std::flush;
        
        vtkCell* cell = surfmesh->GetCell(i);
        BscEntry entry;
        
        //if( cell->GetNumberOfPoints()!=3 )
        //{
        //    std::cout<<"Face does not have 3 vertices. Id= "<<i<<std::endl;
        //    continue;
        //}

        entry.id = scalars->GetTuple1(i);
        entry.pt1 = ptloc->FindClosestPoint(cell->GetPoints()->GetPoint(0));
        entry.pt2 = ptloc->FindClosestPoint(cell->GetPoints()->GetPoint(1));
        entry.pt3 = ptloc->FindClosestPoint(cell->GetPoints()->GetPoint(2));
        if( cell->GetNumberOfPoints()==4 )
        {
            entry.pt4 = ptloc->FindClosestPoint(cell->GetPoints()->GetPoint(3));
            entry.nvertices=4;
        }   
        else if(cell->GetNumberOfPoints()==3)
        {
            entry.nvertices=3;
        }
        else 
        {
            cout<<"cell "<<i<<" has "<<cell->GetNumberOfPoints()<<" vertices, it is unsupported"<<endl;
            exit(-1);
        }
        


        double pt1[3];
        double pt2[3];
        double pt3[3];
        double pt4[3];
        volmesh->GetPoint(entry.pt1, pt1);
        volmesh->GetPoint(entry.pt2, pt2);
        volmesh->GetPoint(entry.pt3, pt3);
    
        if( entry.nvertices==4 )
        {
            volmesh->GetPoint(entry.pt4, pt4);            
        }
        else
        {
            pt4[0]=0;
            pt4[1]=0;
            pt4[2]=0;
        }

        double c[3];
        c[0] = (pt1[0]+pt2[0]+pt3[0]+pt4[0])/entry.nvertices;
        c[1] = (pt1[1]+pt2[1]+pt3[1]+pt4[1])/entry.nvertices;
        c[2] = (pt1[2]+pt2[2]+pt3[2]+pt4[2])/entry.nvertices;
        
        vtkIdType cellid = cellloc->FindCell(c);
        
        if(cellid==-1)
        {
            std::cout<<"Cell not found. Look for an error. Closest point:"<<c[0]<<" "<<c[1]<<" "<<c[2]<<" "<<std::endl;
        }
        entry.tet_id = cellid;
        
        labeldata.push_back(entry);
    }
    std::cout<<std::endl;
    
    
    //to store labels for cells
    vtkSmartPointer<vtkShortArray> volmesh_regions_cells = vtkSmartPointer<vtkShortArray>::New();
    volmesh_regions_cells->SetName(array_name);
    volmesh_regions_cells->SetNumberOfComponents(1);
    volmesh_regions_cells->SetNumberOfValues(volmesh->GetNumberOfCells());
    
    for(vtkIdType i1=0; i1<volmesh->GetNumberOfCells(); i1++)
    {
        volmesh_regions_cells->SetTuple1(i1,0); //reset
    }
    
    //store the labels
    std::ofstream file(outfile);
    for(vtkIdType i=0; i<labeldata.size(); i++)
    {
        BscEntry entry = labeldata[i];
        file<<entry.id<<" "<<
                entry.pt1+1<<" "<<
                entry.pt2+1<<" "<<
                entry.pt3+1<<" ";

        if( entry.nvertices==4 )
            file<<entry.pt4+1<<" ";

        file<<entry.tet_id+1<<LINEBREAK;
        
        if(volmeshout!=NULL)
        {
            volmesh_regions_cells->SetTuple1(entry.tet_id, entry.id);
        }
    
    }

    //store the labels 1
    std::ofstream file1((std::string(outfile)+".1").c_str());
    for(vtkIdType i=0; i<labeldata.size(); i++)
    {
        BscEntry entry = labeldata[i];
        file1<<i+1<<" "<<entry.id<<endl;        
    }


    
    if(volmeshout!=NULL)
    {
        volmesh->GetCellData()->AddArray(volmesh_regions_cells);
         
        
        if(vtkoutput_mesh)
        {   
            vtkSmartPointer<vtkDataSetWriter> wrwr = vtkSmartPointer<vtkDataSetWriter>::New();
            CommonTools::AssociateProgressFunction(wrwr);
            wrwr->SetFileTypeToBinary();
            wrwr->SetFileName(volmeshout);
            wrwr->SetInputData(volmesh);
            wrwr->Update();
        }
        else if(alyaoutput_mesh)
        {
            std::cout<<"Writing alya format"<<std::endl;
            CommonTools::SaveVolMeshBSC(volmesh, volmeshout, scale, correct_orientation);      
            
            //add the boundary
            char boundary_file[256];
            char boundary_elemtype_file[256];
            sprintf(boundary_file, "%s.bound", volmeshout);
            sprintf(boundary_elemtype_file, "%s.bound_type", volmeshout);
            std::ofstream file(boundary_file);
            std::ofstream file_elemtype(boundary_elemtype_file);

            for(vtkIdType i=0; i<labeldata.size(); i++)
            {
                BscEntry entry = labeldata[i];
                file<<i+1<<" "<<
                        entry.pt1+1<<" "<<
                        entry.pt2+1<<" "<<
                        entry.pt3+1<<" ";

                if( entry.nvertices==4 )
                    file<<entry.pt4+1;
        

                file<<LINEBREAK;

                file_elemtype<<i+1<<" "<<entry.nvertices<<LINEBREAK;

            }            
            


            

        }
        else //Write elmer mesh
        {
            std::cout<<"Writing elmer file"<<std::endl;
            std::string header_filename = "mesh.header";
            std::ofstream header_file(header_filename.c_str());
            header_file<<volmesh->GetNumberOfPoints()<<" "<<volmesh->GetNumberOfCells()<<" "<<labeldata.size()<<std::endl;
            header_file<<"2"<<std::endl;
            header_file<<"303 "<<labeldata.size()<<std::endl;
            header_file<<"504 "<<volmesh->GetNumberOfCells()<<std::endl;

            std::string node_filename = "mesh.nodes";
            std::ofstream node_file(node_filename.c_str());
            for(vtkIdType i=0; i<volmesh->GetNumberOfPoints(); i++)
            {
                double* pt = volmesh->GetPoint(i);
                node_file<<i+1<<" -1 "<<pt[0]<<" "<<pt[1]<<" "<<pt[2]<<std::endl;
            }

            std::string ele_filename = "mesh.elements";
            std::ofstream ele_file(ele_filename.c_str());
            for(vtkIdType i=0; i<volmesh->GetNumberOfCells(); i++)
            {
                vtkCell* cell = volmesh->GetCell(i);
                ele_file<<i+1<<" 1 504";
                for(int k=0; k<cell->GetNumberOfPoints(); k++)                
                    ele_file<<" "<<cell->GetPointId(k)+1;
                ele_file<<std::endl;
            }
            
            std::string bound_filename =  "mesh.boundary";
            std::ofstream bound_file(bound_filename.c_str());
            for(vtkIdType i=0; i<labeldata.size(); i++)
            {
                BscEntry entry = labeldata[i];
                bound_file<<i+1<<" "<<
                        entry.id<<" "<<
                        entry.tet_id+1<<" 0 303 "<<
                        entry.pt1+1<<" "<<
                        entry.pt2+1<<" "<<
                        entry.pt3+1;
                if( entry.nvertices==4 )
                    bound_file<<" "<<entry.pt4+1;

                bound_file<<std::endl;
            }
        }
    }

    return 0;
}