int FileToString( const char* filename, std::string& out_contents )
{
	FILE *fp;
	fp = fopen(filename,"r");
	if (!fp) 
	{
		printf("Unable to open file '%s' for read into string (%s, %d)\n",filename, __FILE__, __LINE__);
		return 1;
	}
	const size_t capacity_increment = 512;
	try
	{
		out_contents.clear();
		out_contents.reserve(capacity_increment);
		for (int this_char = fgetc(fp); this_char != EOF; this_char = fgetc(fp))
		{
			//embiggenate the buffer, if needed
			if(out_contents.capacity() == out_contents.size())
			{
				out_contents.reserve(out_contents.capacity() + capacity_increment);
			}
			out_contents.push_back(static_cast<char>(this_char));
		}
	}
	catch (const std::exception& e)
	{
		printf("caught exception '%s' while reading file '%s' into string (%s, %d)\n",e.what(), filename, __FILE__, __LINE__);
		return 1;
	}
	return 0;
}
void load_file(std::string& s, std::istream& is)
{
   s.erase();
   if(is.bad()) return;
   s.reserve(static_cast<std::string::size_type>(is.rdbuf()->in_avail()));
   char c;
   while(is.get(c))
   {
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);
   }
}
Example #3
0
void Dow::Handle::GetClassName (std::string & name) const
{
	// Revisit: there is better API RealGetWindowClass, but it is supported
	// only in Win98, NT 4.0 with SP3 and Win2000
	unsigned lenAvailable = 128;
	unsigned lenWritten = 0;
	do
	{
		name.reserve (lenAvailable); // could reserve more
		lenWritten = ::GetClassName (H (), writable_string (name), name.capacity ());
		lenAvailable = 2 * name.capacity ();
	} while (lenWritten + 1 == name.capacity ());
}
void load_file1(std::string& s, std::istream& is)
{
   s.erase();   //删除字符串
   	//bad() 如果出现错误则返回true 
   if(is.bad()) return;
   s.reserve(is.rdbuf()->in_avail());  //reserve 预留空间 
   char c;
   while(is.get(c))
   { //capacity 在不重新分配内存的情况下,字符串可能的大小  size 得到字符串的大小 
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);  //append 追加字符 
   }
}
Example #5
0
// original source: 
// https://github.com/facebook/folly/blob/master/folly/String.cpp
//
void vStringFormat(std::string& output, const char* format, va_list args)
{
	va_list tmpargs;

	va_copy(tmpargs,args);
	int characters_used = vsnprintf(nullptr, 0, format, tmpargs);
	va_end(tmpargs);

	if (characters_used < 0) {
		// Looks like we have an invalid format string.
		// error out.
		std::string errorMessage("Invalid format string; snprintf returned negative with format string: ");
		errorMessage.append(format);
		
		throw std::runtime_error(errorMessage);
	}
	else if ((unsigned int)characters_used > output.capacity()) {
		output.resize(characters_used+1);
		va_copy(tmpargs,args);
		characters_used = vsnprintf(&output[0], output.capacity(), format, tmpargs);
		va_end(tmpargs);

		if (characters_used < 0) {
			// We shouldn't have a format error by this point, but I can't imagine what error we
			// could have by this point. Still, error out and report it.
			std::string errorMessage("Invalid format string or unknown vsnprintf error; vsnprintf returned negative with format string: ");
			errorMessage.append(format);
		
			throw std::runtime_error(errorMessage);
		}
	} 
	else {
		output.resize(characters_used + 1);

		va_copy(tmpargs,args);
		characters_used = vsnprintf(&output[0], output.capacity(), format, tmpargs);
		va_end(tmpargs);

		if (characters_used < 0) {
			// We shouldn't have a format error by this point, but I can't imagine what error we
			// could have by this point. still error out and report it.
			std::string errorMessage("Invalid format string or unknown vsnprintf error; vsnprintf returned negative with format string: ");
			errorMessage.append(format);
		
			throw std::runtime_error(errorMessage);
		}
		
	}
}
Example #6
0
std::string escape(const std::string str, bool intag = true)
{
    std::string ret = str;

    ret.reserve(str.capacity() * 2);

    for (const char c : str) {
        if (c == '<') {
            ret += "&lt;";
        }
        else if (c == '>') {
            ret += "&gt;";
        }
        else if (c == '&') {
            ret += "&amp;";
        }
        else if (intag) {
            if (c == '\'') {
                ret += "&abuff;";
            }
            else if (c == '\"') {
                ret += "&quot;";
            }
            else {
                ret += c;
            }
        }
        else {
            ret += c;
        }
    }
    return ret;
}
Example #7
0
std::string EscapeForHTML(const std::string& str)
{
    typedef std::map<char, std::string> EscapeMap;
    static const EscapeMap kHtmlEscapeMap {
        { '<', "&lt;" },
        { '>', "&gt;" },
        { '&', "&amp;" },
        { '"', "&quot;" },
        { '\'', "&#39;" },
    };

    std::string strResult;
    strResult.reserve(str.capacity());
    for (auto v : str)
    {
        auto i = kHtmlEscapeMap.find(v);
        if (i == kHtmlEscapeMap.end())
        {
            strResult.push_back(v);
            continue;
        }
        strResult.append(i->second);
    }
    return strResult;
}
Example #8
0
void encoder::encode(std::string& s) {
    s.resize(std::max(s.capacity(), size_t(1))); // Use full capacity, ensure not empty
	size_t size = s.size();
    if (!encode(&s[0], size)) {
        s.resize(size);
        encode(&s[0], size);
    }
}
Example #9
0
void load_file(std::string& s, std::istream& is)
{
   s.erase();
   //
   // attempt to grow string buffer to match file size,
   // this doesn't always work...
   s.reserve(is.rdbuf()->in_avail());
   char c;
   while(is.get(c))
   {
      // use logarithmic growth stategy, in case
      // in_avail (above) returned zero:
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);
   }
}
Example #10
0
 void write(std::string& s, const char* from, const char* to) {
     assert(from <= to);
     const size_t addCount = to - from;
     if ( s.capacity() <= s.size() + addCount )
     {
         s.reserve( 2 * s.size() + addCount );
     }
     s.append(from, to);
 }
Example #11
0
void TCPSocket::Getline(std::string& buffer, bool stripCRLF)
{
  buffer.clear();
  buffer.reserve(defaultBufferSize);
  
  char ch;
  do
  {
    ch = GetcharBuffered();
    if (!stripCRLF || (ch != '\r' && ch != '\n'))
    {
      buffer += ch;
      if (buffer.length() == buffer.capacity())
        buffer.reserve((buffer.capacity() / defaultBufferSize) + 1);
    }
  }
  while (ch != '\n');
}
Example #12
0
static std::string ConvertToLower(std::string const& inString)
{
	std::string outString;
	outString.reserve(inString.capacity());
	for (uint32_t i=0; i<inString.length(); i++) {
		outString+=tolower(inString[i]);
	}
	return outString;
}
Example #13
0
void func (std::string a, std::wstring b)
{
	printf ("%s\n", a.c_str());
	printf ("%d\n", a.size());
	printf ("%d\n", a.capacity());

	wprintf (L"%s\n", b.c_str());
	printf ("%d\n", b.size());
	printf ("%d\n", b.capacity());
};
 bool ShowAndGetNewPassword(
       std::string&            strNewPassword,
       unsigned int            autoCloseMs)
 {
   strNewPassword.resize(1024);
   unsigned int size = (unsigned int)strNewPassword.capacity();
   bool ret = g_interProcess.m_Callbacks->GUI.Dialogs.Keyboard.ShowAndGetNewPassword(strNewPassword[0], size, autoCloseMs);
   strNewPassword.resize(size);
   strNewPassword.shrink_to_fit();
   return ret;
 }
Example #15
0
uint32_t
MemoryConsumption::getStringMemoryUsage(const std::string& s, uint32_t& uniqueCount) {
    ++_totalStringCount;
    const char* internalString = s.c_str();
    if (_seenStrings->find(internalString) != _seenStrings->end()) {
        return 0;
    }
    ++uniqueCount;
    _seenStrings->insert(internalString);
    return s.capacity();
}
 bool ShowAndGetInput(
       std::string&            strText,
       bool                    allowEmptyResult,
       unsigned int            autoCloseMs)
 {
   strText.resize(1024);
   unsigned int size = (unsigned int)strText.capacity();
   bool ret = g_interProcess.m_Callbacks->GUI.Dialogs.Keyboard.ShowAndGetInput(strText[0], size, allowEmptyResult, autoCloseMs);
   strText.resize(size);
   strText.shrink_to_fit();
   return ret;
 }
 bool ShowAndGetFilter(
       std::string&            strText,
       bool                    searching,
       unsigned int            autoCloseMs)
 {
   strText.resize(1024);
   unsigned int size = (unsigned int)strText.capacity();
   bool ret = g_interProcess.m_Callbacks->GUI.Dialogs.Keyboard.ShowAndGetFilter(strText[0], size, searching, autoCloseMs);
   strText.resize(size);
   strText.shrink_to_fit();
   return ret;
 }
/**
 * Like calling s.resize(n), but when growing the string does not
 * initialize new elements.  It is undefined behavior to read from
 * any element added to the string by this method unless it has been
 * written to by an operation that follows this call.
 *
 * IMPORTANT: Read the warning at the top of this header file.
 */
inline void resizeWithoutInitialization(std::string& s, std::size_t n) {
  if (n <= s.size()) {
    s.resize(n);
  } else {
    // careful not to call reserve unless necessary, as it causes
    // shrink_to_fit on many platforms
    if (n > s.capacity()) {
      s.reserve(n);
    }
    detail::unsafeStringSetLargerSize(s, n);
  }
}
 bool ShowAndVerifyNewPassword(
       std::string&            strNewPassword,
       const std::string&      strHeading,
       bool                    allowEmptyResult,
       unsigned int            autoCloseMs)
 {
   strNewPassword.resize(1024);
   unsigned int size = (unsigned int)strNewPassword.capacity();
   bool ret = g_interProcess.m_Callbacks->GUI.Dialogs.Keyboard.ShowAndGetNewPasswordWithHead(strNewPassword[0], size, strHeading.c_str(), allowEmptyResult, autoCloseMs);
   strNewPassword.resize(size);
   strNewPassword.shrink_to_fit();
   return ret;
 }
 int ShowAndVerifyPassword(
       std::string&            strPassword,
       const std::string&      strHeading,
       int                     iRetries,
       unsigned int            autoCloseMs)
 {
   strPassword.resize(1024);
   unsigned int size = (unsigned int)strPassword.capacity();
   int ret = g_interProcess.m_Callbacks->GUI.Dialogs.Keyboard.ShowAndVerifyPassword(strPassword[0], size, strHeading.c_str(), iRetries, autoCloseMs);
   strPassword.resize(size);
   strPassword.shrink_to_fit();
   return ret;
 }
Example #21
0
bool to_string(std::string& s, int val)
{
    s.resize(s.capacity());
    while (true)
    {
        size_t n2 = static_cast<size_t>(snprintf(&s[0], s.size() + 1, "%d", val));
        if (n2 <= s.size())
        {
            s.resize(n2);
            break;
        }
        s.resize(n2);
    }
    return true;
}
Example #22
0
    static void extract(const jsonpack::value &v, char* json_ptr, std::string &value)
    {
        position p = v._pos;
        if(p._type != JTK_NULL)
        {
            // pritty but slow and dangerous

//            value.resize(p._count);
//            memcpy( const_cast<char*>(value.data()), json_ptr+ p._pos, p._count); // FIX undefined behavior

//            unsigned i = 0;
//            value.erase(std::remove_if(value.begin(), value.end(),
//                        [&i, value](char c)->bool
//                        {
//                            bool esc = ( c == '\\' && (i < value.length()-1 ) && (sizeof(char) == 1 || unsigned(value[i+1]) < 256) && util::escaped[(unsigned char)value[i+1]] );
//                            i++;
//                            return esc;
//                        }),
//                        value.end() );


            //hard coded but fast and safe

            if (value.capacity() <  p._count + 1)
                value.reserve(p._count + 1);

            char* val_ptr = json_ptr + p._pos;
            for(char* i = val_ptr ; i != val_ptr + p._count ; ++i)
            {
                if( *i == '\\' )
                {
                    ++i;
                    if( (i != val_ptr + p._count) && ( sizeof(char) == 1 || unsigned(*i) < 256) && util::escaped[(unsigned char)*i] )
                        value.push_back(*i);
                }
                else
                    value.push_back(*i);
            }
        }
    }
Example #23
0
bool ImGui::InputTextM(const char* label, std::string& text)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)	
	bool ret = InputTextEx(label, &text[0], text.capacity(), ImVec2(0, 0), 0, 0, nullptr);
	return ret;
#else
	ImGuiWindow* window = GetCurrentWindow();
	if (window->SkipItems)
		return false;

	ImGuiContext& g = *GImGui;
	const ImGuiIO& io = g.IO;
	const ImGuiStyle& style = g.Style;
	//============================================
	const ImGuiID id = window->GetID(label);
	const ImVec2 label_size = CalcTextSize(label, NULL, true);
	ImVec2 size = CalcItemSize(ImVec2(0, 0), CalcItemWidth(), label_size.y + style.FramePadding.y*2.0f);
	const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
	const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
	//============================================
	ItemSize(total_bb, style.FramePadding.y);
	if (!ItemAdd(total_bb, &id))
		return false;

	const bool hovered = IsHovered(frame_bb, id);
	if (hovered)
	{
		SetHoveredID(id);
		g.MouseCursor = ImGuiMouseCursor_TextInput;
	}
	ImGuiTextEditState& edit_state = g.InputTextState;
	const bool user_clicked = hovered && io.MouseClicked[0];
	if (user_clicked)
	{
		if (g.ActiveId != id)
		{
			edit_state.CursorAnimReset();
		}
		SetActiveID(id, window);
		FocusWindow(window);
	}
	else if (io.MouseClicked[0])
	{
		// Release focus when we click outside
		if (g.ActiveId == id)
			SetActiveID(0, NULL);
	}

	if (g.ActiveId == id)
	{
		//window->DrawList->AddRectFilled(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_TextSelectedBg), style.FrameRounding);
		RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_TextSelectedBg), true, style.FrameRounding);
		ImRect frame_select(frame_bb);
		frame_select.Reduce(ImVec2(2, 2));
		RenderFrame(frame_select.Min, frame_select.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
	}else
	{
		RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
	}

	//============================================
	int w = snprintf(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s", text.c_str());
	int tempSize = IM_ARRAYSIZE(g.TempBuffer);
	g.TempBuffer[tempSize - 1] = 0;
	const char* text_end = g.TempBuffer + ((w == -1) ? tempSize : w);

	// Render Text
	const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
	ImVec2 render_pos = frame_bb.Min + style.FramePadding;
	window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), g.TempBuffer, text_end, 0.0f, &clip_rect);

	if (label_size.x > 0)
		RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);

	return user_clicked;
#endif
}
Example #24
0
void insert_objects(MYSQL* conn, const char* table_name, time_t epoch, uint index, std::vector<Libpair>& lddA,
                    std::string& syshost, Table& rmapT)
{

  //************************************************************
  // build SELECT obj_id INTO xalt_object stmt
  //************************************************************

  const char* stmt_sql_s = "SELECT obj_id FROM xalt_object WHERE hash_id=? AND object_path=? AND syshost=? limit 1";

  MYSQL_STMT *stmt_s = mysql_stmt_init(conn);
  if (!stmt_s)
    {
      print_stmt_error(stmt_s, "mysql_stmt_init(), out of memmory",__FILE__,__LINE__);
      exit(1);
    }

  if (mysql_stmt_prepare(stmt_s, stmt_sql_s, strlen(stmt_sql_s)))
    {
      print_stmt_error(stmt_s, "Could not prepare stmt_s for select obj_id",__FILE__,__LINE__);
      exit(1);
    }

  MYSQL_BIND param_s[3], result_s[1];
  memset((void *) param_s,  0, sizeof(param_s));
  memset((void *) result_s, 0, sizeof(result_s));

  const int hash_id_sz = 41;
  char hash_id[hash_id_sz];

  const int objSz = 2048;
  char object_path[objSz];

  // STRING PARAM_S[0] hash_id;
  std::string::size_type len_hash_id = 0;          // set length later in loop.
  param_s[0].buffer_type   = MYSQL_TYPE_STRING;
  param_s[0].buffer        = (void *) &hash_id[0];
  param_s[0].buffer_length = hash_id_sz;
  param_s[0].length        = &len_hash_id;

  // STRING PARAM_S[1] object_path
  std::string::size_type len_object_path = 0;      // set length later in loop.
  param_s[1].buffer_type   = MYSQL_TYPE_STRING;
  param_s[1].buffer        = (void *) &object_path[0];
  param_s[1].buffer_length = objSz;
  param_s[1].length        = &len_object_path;

  // STRING PARAM_S[2] syshost
  std::string::size_type len_syshost = syshost.size();
  param_s[2].buffer_type   = MYSQL_TYPE_STRING;
  param_s[2].buffer        = (void *) syshost.c_str();
  param_s[2].buffer_length = syshost.capacity();
  param_s[2].length        = &len_syshost;

  if (mysql_stmt_bind_param(stmt_s, param_s))
    {
      print_stmt_error(stmt_s, "Could not bind paramaters for selecting obj_id(1)",__FILE__,__LINE__);
      exit(1);
    }
      
  // UNSIGNED INT RESULT_S obj_id;
  uint obj_id;
  result_s[0].buffer_type   = MYSQL_TYPE_LONG;
  result_s[0].buffer        = (void *) &obj_id;
  result_s[0].is_unsigned   = 1;
  result_s[0].length        = 0;

  if (mysql_stmt_bind_result(stmt_s, result_s))
    {
      print_stmt_error(stmt_s, "Could not bind paramaters for selecting obj_id(2)",__FILE__,__LINE__);
      exit(1);
    }

  //************************************************************
  // build INSERT into xalt_object stmt
  //************************************************************

  const char* stmt_sql_i = "INSERT INTO xalt_object VALUES (NULL,?,?,?,?,?,?)";
  MYSQL_STMT *stmt_i = mysql_stmt_init(conn);
  if (!stmt_i)
    {
      print_stmt_error(stmt_i, "mysql_stmt_init(), out of memmory(2)",__FILE__,__LINE__);
      exit(1);
    }

  if (mysql_stmt_prepare(stmt_i, stmt_sql_i, strlen(stmt_sql_i)))
    {
      print_stmt_error(stmt_i, "Could not prepare stmt_i for insert into xalt_object",__FILE__,__LINE__);
      exit(1);
    }

  MYSQL_BIND param_i[6];
  memset((void *) param_i,  0, sizeof(param_i));

  // STRING PARAM_I[0] object_path
  param_i[0].buffer_type   = MYSQL_TYPE_STRING;
  param_i[0].buffer        = (void *) &object_path[0];
  param_i[0].buffer_length = objSz;
  param_i[0].length        = &len_object_path;

  // STRING PARAM_I[1] syshost
  param_i[1].buffer_type   = MYSQL_TYPE_STRING;
  param_i[1].buffer        = (void *) syshost.c_str();
  param_i[1].buffer_length = syshost.capacity();
  param_i[1].length        = &len_syshost;

  // STRING PARAM_I[2] hash_id
  param_i[2].buffer_type   = MYSQL_TYPE_STRING;
  param_i[2].buffer        = (void *) &hash_id[0];
  param_i[2].buffer_length = hash_id_sz;
  param_i[2].length        = &len_hash_id;

  // STRING PARAM_I[3] module_name
  const int                  module_name_sz = 64;
  char                       module_name[module_name_sz];
  std::string::size_type     len_module_name = 0;      // set length in loop
  my_bool                    module_name_null_flag;
  param_i[3].buffer_type   = MYSQL_TYPE_STRING;
  param_i[3].buffer        = (void *) &module_name[0];
  param_i[3].buffer_length = module_name_sz;
  param_i[3].is_null       = &module_name_null_flag;
  param_i[3].length        = &len_module_name;

  // TIMESTAMP PARAM_I[4] timestamp
  MYSQL_TIME my_datetime;
  time_t clock;
  (void ) time(&clock);
  struct tm* curr_time    = localtime(&clock);
  my_datetime.year        = curr_time->tm_year + 1900;
  my_datetime.month       = curr_time->tm_mon  + 1;
  my_datetime.day         = curr_time->tm_mday;
  my_datetime.hour        = curr_time->tm_hour;
  my_datetime.minute      = curr_time->tm_min;
  my_datetime.second      = curr_time->tm_sec;
  my_datetime.second_part = 0;
  param_i[4].buffer_type  = MYSQL_TYPE_DATETIME;
  param_i[4].buffer       = &my_datetime;

  // STRING PARAM_I[5] lib_type
  const int lib_type_sz = 3;
  char lib_type[lib_type_sz];

  std::string::size_type len_lib_type = 0;      // set length in loop.
  param_i[5].buffer_type   = MYSQL_TYPE_STRING;
  param_i[5].buffer        = (void *) &lib_type[0];
  param_i[5].buffer_length = lib_type_sz;
  param_i[5].length        = &len_lib_type;

  if (mysql_stmt_bind_param(stmt_i, param_i))
    {
      print_stmt_error(stmt_i, "Could not bind paramaters for inserting into xalt_object",__FILE__,__LINE__);
      exit(1);
    }
      

  //************************************************************
  // "INSERT into <TABLE_NAME> VALUES (NULL, ?, ?, ?)"
  //************************************************************

  std::string s2("INSERT INTO ");
  s2.append(table_name);
  s2.append(" VALUES (NULL,?,?,?)");
  const char* stmt_sql_ii = s2.c_str();

  MYSQL_STMT *stmt_ii     = mysql_stmt_init(conn);
  if (!stmt_ii)
    {
      print_stmt_error(stmt_ii, "mysql_stmt_init(), out of memmory(3)",__FILE__,__LINE__);
      exit(1);
    }

  if (mysql_stmt_prepare(stmt_ii, stmt_sql_ii, strlen(stmt_sql_ii)))
    {
      print_stmt_error(stmt_ii, "Could not prepare stmt_ii for insert into <table_name>",__FILE__,__LINE__);
      exit(1);
    }

  MYSQL_BIND param_ii[3];
  memset((void *) param_ii,  0, sizeof(param_ii));

  // UINT PARAM_II[0] obj_id
  param_ii[0].buffer_type   = MYSQL_TYPE_LONG;
  param_ii[0].buffer        = (void *) &obj_id;
  param_ii[0].buffer_length = 0;
  param_ii[0].is_unsigned   = 1;

  // UINT PARAM_II[1] index
  param_ii[1].buffer_type   = MYSQL_TYPE_LONG;
  param_ii[1].buffer        = (void *) &index;
  param_ii[1].buffer_length = 0;
  param_ii[1].is_unsigned   = 1;

  // DATE PARAM_II[2] date
  MYSQL_TIME my_date;
  curr_time                 = localtime(&epoch);
  my_date.year              = curr_time->tm_year + 1900;
  my_date.month             = curr_time->tm_mon  + 1;
  my_date.day               = curr_time->tm_mday;
  my_date.hour              = 0;
  my_date.minute            = 0;
  my_date.second            = 0;
  my_date.second_part       = 0;
  param_ii[2].buffer_type   = MYSQL_TYPE_DATE;
  param_ii[2].buffer        = &my_date;

  if (mysql_stmt_bind_param(stmt_ii, param_ii))
    {
      print_stmt_error(stmt_ii, "Could not bind paramaters for inserting into xalt_object",__FILE__,__LINE__);
      exit(1);
    }
      
  for ( auto const & it : lddA)
    {
      len_object_path =   it.lib.size();
      strcpy(object_path, it.lib.c_str());

      len_hash_id     = it.sha1.size();
      strcpy(hash_id,   it.sha1.c_str());

      // "SELECT obj_id ..."
      if (mysql_stmt_execute(stmt_s))
        {
          print_stmt_error(stmt_s, "Could not execute stmt for selecting obj_id",__FILE__,__LINE__);
          exit(1);
        }
      if (mysql_stmt_store_result(stmt_s))
        {
          print_stmt_error(stmt_s, "Could not mysql_stmt_store_result() selecting obj_id",__FILE__,__LINE__);
          exit(1);
        }
      


      // mysql_stmt_fetch(stmt_s) will return 0 if successful.  That means it found obj_id
      if (mysql_stmt_fetch(stmt_s) != 0)  
        {
          // If here then the object is NOT in the db so store it and compute obj_id
          if (path2module(object_path, rmapT, module_name, module_name_sz))
            {
              module_name_null_flag = 0;
              len_module_name = strlen(module_name);
            }
          else
            {
              module_name_null_flag = 1;
              len_module_name = 0;
            }

          object_type(object_path, &lib_type[0]);
          len_lib_type = strlen(lib_type);

          // "INSERT INTO xalt_object ..."
          if (mysql_stmt_execute(stmt_i))
            {
              print_stmt_error(stmt_i, "Could not execute stmt for inserting into xalt_object",__FILE__,__LINE__);
              exit(1);
            }
          obj_id = (uint)  mysql_stmt_insert_id(stmt_i);
        }

      // "INSERT INTO <table_name>"
      if (mysql_stmt_execute(stmt_ii))
        {
          print_stmt_error(stmt_ii, "Could not execute stmt for inserting into <table_name>",__FILE__,__LINE__);
          exit(1);
        }
    }
          
  mysql_stmt_free_result(stmt_s);
  if (mysql_stmt_close(stmt_s))
    {
      print_stmt_error(stmt_s, "Could not close stmt for selecting obj_id",__FILE__,__LINE__);
      exit(1);
    }
  if (mysql_stmt_close(stmt_i))
    {
      print_stmt_error(stmt_i, "Could not close stmt for inserting into xalt_object",__FILE__,__LINE__);
      exit(1);
    }
  if (mysql_stmt_close(stmt_ii))
    {
      print_stmt_error(stmt_ii, "Could not close stmt for inserting into <table_name>",__FILE__,__LINE__);
      exit(1);
    }
}
Example #25
0
bool SQL_RAW::callProtocol(std::string input_str, std::string &result, const bool async_method, const unsigned int unique_id)
{
	try
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->info("extDB2: SQL_RAW: Trace: Input: {0}", input_str);
		#endif
		#ifdef DEBUG_LOGGING
			extension_ptr->logger->info("extDB2: SQL_RAW: Trace: Input: {0}", input_str);
		#endif

		Poco::Data::Session session = extension_ptr->getDBSession_mutexlock(*database_ptr);
		Poco::Data::RecordSet rs(session, input_str);

		result = "[1,[";
		std::string temp_str;
		temp_str.reserve(result.capacity());

		std::size_t cols = rs.columnCount();
		if (cols >= 1)
		{
			result += "[";
			bool more = rs.moveFirst();
			while (more)
			{
				for (std::size_t col = 0; col < cols; ++col)
				{
					if (rs[col].isEmpty())
					{
						temp_str.clear();
					}
					else
					{
						temp_str = rs[col].convert<std::string>();
					}
				
					auto datatype = rs.columnType(col);
					if ((datatype == Poco::Data::MetaColumn::FDT_DATE) || (datatype == Poco::Data::MetaColumn::FDT_TIME) || (datatype == Poco::Data::MetaColumn::FDT_TIMESTAMP))
					{
						if (temp_str.empty())
						{
							result += "\"\"";
						}
						else
						{
							boost::erase_all(temp_str, "\"");
							result += "\"" + temp_str + "\"";
						}
					}
					else if ((stringDataTypeCheck) && (rs.columnType(col) == Poco::Data::MetaColumn::FDT_STRING))
					{
						if (temp_str.empty())
						{
							result += ("\"\"");
						}
						else
						{
							boost::erase_all(temp_str, "\"");
							result += "\"" + temp_str + "\"";
						}
					}
					else
					{
						if (temp_str.empty())
						{
							result += "\"\"";
						}
						else
						{
							result += temp_str;
						}
					}

					if (col < (cols - 1))
					{
						result += ",";
					}
				}
				more = rs.moveNext();
				if (more)
				{
					result += "],[";
				}
			}
			result += "]";
		}
		result += "]]";
		#ifdef DEBUG_TESTING
			extension_ptr->console->info("extDB2: SQL_RAW: Trace: Result: {0}", result);
		#endif
		#ifdef DEBUG_LOGGING
			extension_ptr->logger->info("extDB2: SQL_RAW: Trace: Result: {0}", result);
		#endif
	}
	catch (Poco::InvalidAccessException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error InvalidAccessException: {0}", e.displayText());
			extension_ptr->console->error("extDB2: SQL_RAW: Error InvalidAccessException: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error InvalidAccessException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error InvalidAccessException: SQL: {0}", input_str);
		result = "[0,\"Error DBLocked Exception\"]";
	}
	catch (Poco::Data::NotConnectedException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error NotConnectedException: {0}", e.displayText());
			extension_ptr->console->error("extDB2: SQL_RAW: Error NotConnectedException: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error NotConnectedException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error NotConnectedException: SQL: {0}", input_str);
		result = "[0,\"Error DBLocked Exception\"]";
	}
	catch (Poco::NotImplementedException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error NotImplementedException: {0}", e.displayText());
			extension_ptr->console->error("extDB2: SQL_RAW: Error NotImplementedException: SQL: {0}", input_str);

		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error NotImplementedException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error NotImplementedException: SQL: {0}", input_str);
		result = "[0,\"Error DBLocked Exception\"]";
	}
	catch (Poco::Data::SQLite::DBLockedException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error DBLockedException: {0}", e.displayText());
			extension_ptr->logger->error("extDB2: SQL_RAW: Error DBLockedException: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error DBLockedException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error DBLockedException: SQL: {0}", input_str);
		result = "[0,\"Error DBLocked Exception\"]";
	}
	catch (Poco::Data::MySQL::ConnectionException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error ConnectionException: {0}", e.displayText());
			extension_ptr->logger->error("extDB2: SQL_RAW: Error ConnectionException: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error ConnectionException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error ConnectionException: SQL: {0}", input_str);
		result = "[0,\"Error Connection Exception\"]";
	}
	catch(Poco::Data::MySQL::StatementException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error StatementException: {0}", e.displayText());
			extension_ptr->logger->error("extDB2: SQL_RAW: Error StatementException: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error StatementException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error StatementException: SQL: {0}", input_str);
		result = "[0,\"Error Statement Exception\"]";
	}
	catch (Poco::Data::ConnectionFailedException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error ConnectionFailedException: {0}", e.displayText());
			extension_ptr->console->error("extDB2: SQL_RAW: Error ConnectionFailedException: SQL {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error ConnectionFailedException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error ConnectionFailedException: SQL {0}", input_str);
		result = "[0,\"Error ConnectionFailedException\"]";
	}
	catch (Poco::Data::DataException& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error DataException: {0}", e.displayText());
			extension_ptr->logger->error("extDB2: SQL_RAW: Error DataException: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error DataException: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error DataException: SQL: {0}", input_str);
		result = "[0,\"Error Data Exception\"]";
	}
	catch (Poco::Exception& e)
	{
		#ifdef DEBUG_TESTING
			extension_ptr->console->error("extDB2: SQL_RAW: Error Exception: {0}", e.displayText());
			extension_ptr->console->error("extDB2: SQL_RAW: Error Exception: SQL: {0}", input_str);
		#endif
		extension_ptr->logger->error("extDB2: SQL_RAW: Error Exception: {0}", e.displayText());
		extension_ptr->logger->error("extDB2: SQL_RAW: Error Exception: SQL: {0}", input_str);
		result = "[0,\"Error Exception\"]";
	}
	return true;
}
Example #26
0
	size_t GetCapacity() { return m_Data->capacity(); }
void quasardb_facade::blob_get_noalloc(const std::string & alias, std::string & content)
{
    std::size_t result_size = content.capacity();
    INVOKE(qdb_blob_get_noalloc, _handle, alias.c_str(), const_cast<char *>(content.data()), &result_size);
    content.resize(result_size);
}