void ATextGenerator::generateUniqueId(AOutputBuffer& target, size_t size /* = 32 */) { if (size < 16) ATHROW(NULL, AException::InvalidParameter); ARope rope; size_t x = ATime::getTickCount(); rope.append((const char *)&x, sizeof(size_t)); size_t bytesToAdd = size - sizeof(size_t); while(bytesToAdd >= 4) { x = ARandomNumberGenerator::get(ARandomNumberGenerator::Lecuyer).nextU4(); rope.append((const char *)&x, 4); bytesToAdd -= 4; } while(bytesToAdd > 0) { x = ARandomNumberGenerator::get(ARandomNumberGenerator::Lecuyer).nextU1(); rope.append((const char *)&x, 1); --bytesToAdd; } AASSERT(NULL, !bytesToAdd); AString str(rope.getSize() * 2, 256); ATextConverter::encode64(rope, str); AASSERT(&str, str.getSize() >= size); target.append(str, size); }
AXmlElement& AXmlElement::addContent( AXmlElement *pnode, const AString& path, // = AConstant::ASTRING_EMPTY bool insertIntoFront // = false ) { if (path.isEmpty() || path.equals(AConstant::ASTRING_SLASH)) { AASSERT(this, m_Content.size() < DEBUG_MAXSIZE_AXmlElement); //Debug only limit AASSERT(this, pnode); pnode->setParent(this); if (insertIntoFront) m_Content.push_front(pnode); else m_Content.push_back(pnode); } else { LIST_AString parts; path.split(parts, '/'); if (!parts.size()) ATHROW(this, AException::InvalidParameter); AXmlElement *pNewParent = _createAndAppend(parts, this, insertIntoFront); AASSERT_EX(this, pNewParent, path); pNewParent->addContent(pnode, AConstant::ASTRING_EMPTY, insertIntoFront); } return *this; }
AOSContext *AOSContextManager::allocate(AFile_Socket *pSocket) { AASSERT(this, pSocket); AOSContext *p = _newContext(pSocket); //a_Set logging level switch(m_DefaultEventLogLevel) { case AEventVisitor::EL_DEBUG: p->useEventVisitor().setEventThresholdLevel(AEventVisitor::EL_DEBUG); break; case AEventVisitor::EL_INFO: p->useEventVisitor().setEventThresholdLevel(AEventVisitor::EL_INFO); break; case AEventVisitor::EL_WARN: p->useEventVisitor().setEventThresholdLevel(AEventVisitor::EL_WARN); break; case AEventVisitor::EL_ERROR: p->useEventVisitor().setEventThresholdLevel(AEventVisitor::EL_ERROR); break; case AEventVisitor::EL_NONE: p->useEventVisitor().setEventThresholdLevel(AEventVisitor::EL_NONE); break; default: p->useEventVisitor().setEventThresholdLevel(AEventVisitor::EL_EVENT); } ARope rope("AOSContextManager::allocate[",28); rope.append(AString::fromPointer(p)); rope.append(", pFile=",8); rope.append(AString::fromPointer(pSocket)); rope.append("] new create",12); p->useEventVisitor().startEvent(rope); { ALock lock(m_InUseSync); AASSERT(this, p && m_InUse.end() == m_InUse.find(p)); m_InUse.insert(p); } AASSERT(this, &p->useSocket()); return p; }
u4 mythreadproc(AThread& thread) { CommonData *pData = static_cast<CommonData *>(thread.getParameter()); AASSERT(NULL, pData); u4 id = thread.getId(); thread.setRunning(true); { { ALock lock(pData->m_cs); pData->m_count++; } { ALock lock(g_ConsoleOutput); std::cout << "[" << AString::fromU4(thread.getId()) << "," << pData->m_count << "]" << std::flush; } AThread::sleep(300); } thread.setRunning(false); return 0; }
NativeEngine::NativeEngine(struct android_app *app) { OLog("NativeEngine: initializing."); mApp = app; mHasFocus = mIsVisible = mHasWindow = false; mHasGLObjects = false; mEglDisplay = EGL_NO_DISPLAY; mEglSurface = EGL_NO_SURFACE; mEglContext = EGL_NO_CONTEXT; mEglConfig = 0; mSurfWidth = mSurfHeight = 0; mApiVersion = 0; memset(&mState, 0, sizeof(mState)); mIsFirstFrame = true; if (app->savedState != NULL) { // we are starting with previously saved state -- restore it mState = *(struct NativeEngineSavedState*) app->savedState; } // only one instance of NativeEngine may exist! AASSERT(_singleton == NULL); _singleton = this; OLog("NativeEngine: querying API level."); OLog("NativeEngine: API version " << mApiVersion); }
void AOSContextQueue_IsAvailable::add(AOSContext *pContext) { AASSERT(NULL, pContext); //a_Clear these in case this is not the first trip here //a_More than one trip can result if some bytes were read but not enough pContext->useConnectionFlags().clearBit(AOSContext::CONFLAG_ISAVAILABLE_SELECT_SET); pContext->useConnectionFlags().clearBit(AOSContext::CONFLAG_ISAVAILABLE_PENDING); volatile long currentQueue = ::InterlockedIncrement(&m_currentQueue) % m_queueCount; { ALock lock(m_Queues.at(currentQueue)->sync); //a_Start timeout timer pContext->useTimeoutTimer().start(); if (pContext->useEventVisitor().isLoggingDebug()) { ARope rope(getClass()); rope.append("::add[",6); rope.append(AString::fromInt(currentQueue)); rope.append("]=",2); rope.append(AString::fromPointer(pContext)); pContext->useEventVisitor().addEvent(rope, AEventVisitor::EL_DEBUG); } m_Queues.at(currentQueue)->queue.pushBack(pContext); ++m_Queues.at(currentQueue)->count; } }
void AOSDatabaseConnectionPool::init(const AUrl& url, int count) { AASSERT(this, count > 0); //a_Create template database ADatabase *pServer = NULL; switch (url.getProtocolEnum()) { case AUrl::MYSQL: pServer = new AMySQLServer(url); break; case AUrl::ODBC: pServer = new AODBCServer(url); break; case AUrl::SQLITE: pServer = new ASQLiteServer(url); break; default: pServer = new ADatabase_NOP(url); } mp_DatabasePool = new ADatabasePool(pServer, count); m_isInitialized = true; }
void AOSContextQueue_IsAvailable::start() { for (size_t i=0; i<m_queueCount; ++i) { AASSERT(NULL, NULL == m_Queues.at(i)->pthread); m_Queues.at(i)->pthread = new AThread(_threadprocWorker, true, m_Queues.at(i), this); } }
AFragmentCounter::AFragmentCounter(u1 digits, u4 stop_value, u4 start_value, s1 step) { AASSERT(this, digits < 10); AASSERT(this, step); if (start_value > stop_value && step > 0) step = -step; if (start_value < stop_value && step < 0) step = -step; m_Digits = digits; m_StartValue = start_value; m_StopValue = stop_value; m_Step = step; reset(); }
MYSQL_RES *AMySQLServer::executeSQL(const AString& query, AString& error) { if (!isInitialized()) { error.assign("Database not intialized;"); return NULL; } if (query.isEmpty()) { AASSERT(this, 0); error = "Query is empty;"; return NULL; } int tries = 0; u4 u4Errno = 0; while (tries < 3 && mysql_real_query(mp_mydata, query.c_str(), query.getSize())) { u4Errno = mysql_errno(mp_mydata); if (CR_SERVER_GONE_ERROR == u4Errno) { //a_Connection lost, try to reconnect, clear error if reconnected if (reconnect(error)) { error.clear(); continue; //a_Try query again } ++tries; } else { error = "Error("; error += mysql_error(mp_mydata); error += ":errno="; error += AString::fromU4(u4Errno); error += ") for query("; error += query; error += ");"; return NULL; } } if (3 == tries) { error = "Unable to reconnect to database. Error("; error += mysql_error(mp_mydata); error += ":errno="; error += AString::fromU4(u4Errno); error += ") for query("; error += query; error += ");"; return NULL; } return mysql_store_result(mp_mydata); }
AXmlElement& AXmlElement::addComment(const AString& comment) { AASSERT(this, m_Content.size() < DEBUG_MAXSIZE_AXmlElement); //Debug only limit AXmlInstruction *p = new AXmlInstruction(AXmlInstruction::COMMENT, this); p->useData().assign(comment); m_Content.push_back(p); return *this; }
const AString& ATextOdometer::setInitial(const AString& strInitial) { //a_Initial must be the same or smaller in size as odometer AASSERT(this, strInitial.getSize() <= mstr_Odometer.getSize()); size_t iI = strInitial.getSize(); for (size_t iX = mstr_Odometer.getSize(); iX > 0; --iX) { if (iI) { AASSERT(this, AConstant::npos != mstr_Subset.find(strInitial.at(iI-1))); mstr_Odometer.set(strInitial.at(iI-1), iX-1); --iI; } else mstr_Odometer.set(mstr_Subset.at(0), iX-1); } return mstr_Odometer; }
AXmlElement& AXmlElement::addElement(const AString& path, const AEmittable& object, AXmlElement::Encoding encoding, bool overwrite, bool insertIntoFront) { AXmlElement *p = _addElement(path, overwrite, insertIntoFront); AASSERT(this, p); //a_Emit to rope ARope value; object.emit(value); p->addData(value, encoding); return *p; }
AXmlElement& ALog_AFile::emitXml(AXmlElement& thisRoot) const { AASSERT(this, !thisRoot.useName().isEmpty()); ALog::emitXml(thisRoot); thisRoot.addElement(ASW("current_filename",16)).addData(m_filenameRotation, AXmlElement::ENC_CDATADIRECT); thisRoot.addElement(ASW("cycle_sleep",11)).addData(AString::fromU4(m_CycleSleep)); thisRoot.addElement(ASW("file_rotation",13)).addData(m_enableLogFileRotate); thisRoot.addElement(ASW("max_file_size",13)).addData(AString::fromU4(m_logMaxFileSize)); return thisRoot; }
size_t AOutputBuffer::append(const AString& str, size_t len) { if (!len) return 0; if (AConstant::npos == len) return _append(str.c_str(), str.getSize()); else { AASSERT(this, len <= str.getSize()); return _append(str.c_str(), len); } }
void AOSContextManager::_deleteContext(AOSContext **p) { AASSERT(this, NULL != *p); if (m_FreeStore.size() >= m_FreeStoreMaxSize) delete(*p); else { (*p)->finalize(true); m_FreeStore.pushBack(*p); } p = NULL; }
AOSContextManager::AOSContextManager(AOSServices& services) : m_Services(services), m_History(new ASync_CriticalSection()), m_ErrorHistory(new ASync_CriticalSection()), m_FreeStore(new ASync_CriticalSectionSpinLock()) { m_HistoryMaxSize = services.useConfiguration().useConfigRoot().getInt("/config/server/context-manager/history-maxsize", 100); m_ErrorHistoryMaxSize = services.useConfiguration().useConfigRoot().getInt("/config/server/context-manager/error-history-maxsize", 100); m_DefaultEventLogLevel = services.useConfiguration().useConfigRoot().getInt("/config/server/context-manager/log-level", 2); AASSERT(this, m_DefaultEventLogLevel >= AEventVisitor::EL_NONE && m_DefaultEventLogLevel <= AEventVisitor::EL_DEBUG); m_FreeStoreMaxSize = services.useConfiguration().useConfigRoot().getInt("/config/server/context-manager/freestore/max-size", 500); size_t freeStoreInitialSize = services.useConfiguration().useConfigRoot().getInt("/config/server/context-manager/freestore/initial-size", 100); AASSERT(this, freeStoreInitialSize <= m_FreeStoreMaxSize && freeStoreInitialSize >= 0); m_Queues.resize(AOSContextManager::STATE_LAST, NULL); for (int i=0; i<freeStoreInitialSize; ++i) { m_FreeStore.pushBack(new AOSContext(NULL, m_Services)); } adminRegisterObject(m_Services.useAdminRegistry()); }
/*! Uses the model to determine if element exists thisfunction("<path to the AXmlElement>") lua namespace: model lua param: Path to element lua return: true if exists, false otherwise */ static int alibrary_Objects_Model_existElement(lua_State *L) { ATemplateContext *pLuaContext = static_cast<ATemplateContext *>(L->acontext); AASSERT(NULL, pLuaContext); size_t len = AConstant::npos; const char *s = luaL_checklstring(L, 1, &len); const AString& xmlpath = AString::wrap(s, len); if (pLuaContext->useModel().useRoot().exists(xmlpath)) lua_pushboolean(L, 1); else lua_pushboolean(L, 0); return 1; }
/*! Uses the model to emit content for a path thisfunction("<path to the AXmlElement to emit>", separate) lua namespace: model lua param: Path to emit lua param: if non-nil then each element found will be returned by itself lua return: Content at the given path or nil if element does not exist */ static int alibrary_Objects_Model_emitContentFromPath(lua_State *L) { ATemplateContext *pLuaContext = static_cast<ATemplateContext *>(L->acontext); AASSERT(NULL, pLuaContext); size_t len = AConstant::npos; const char *s = luaL_checklstring(L, 1, &len); const AString& xmlpath = AString::wrap(s, len); int mode = 0; if (lua_gettop(L) > 1) mode = luaL_checkint(L, 2); AXmlElement::CONST_CONTAINER nodes; size_t ret = pLuaContext->useModel().useRoot().find(xmlpath, nodes); if (mode) { //a_Return each as separate values AString str; for (AXmlElement::CONST_CONTAINER::const_iterator cit = nodes.begin(); cit != nodes.end(); ++cit) { (*cit)->emitContent(str); lua_pushlstring(L, str.c_str(), str.getSize()); str.clear(); } return (int)ret; } else { if (ret > 0) { //a_Return content concatinated ARope rope; for (AXmlElement::CONST_CONTAINER::const_iterator cit = nodes.begin(); cit != nodes.end(); ++cit) (*cit)->emitContent(rope); const AString& str = rope.toAString(); lua_pushlstring(L, str.c_str(), str.getSize()); return 1; } else return 0; } }
/*! Emits the entire model as JSON thisfunction([indent = -1]) lua namespace: model lua param: (Optional) if 0 or greater, will indent the output. Default -1 will inline it. lua return: JSON string of default AXmlDocument model */ static int alibrary_Objects_Model_emitJson(lua_State *L) { ATemplateContext *pLuaContext = static_cast<ATemplateContext *>(L->acontext); AASSERT(NULL, pLuaContext); int indent = -1; if (lua_gettop(L) > 0) { indent = luaL_checkint(L, 1); } AString str; pLuaContext->useModel().useRoot().emitJson(str, indent); lua_pushlstring(L, str.c_str(), str.getSize()); return 1; }
void AXmlElement::_addData( const AEmittable& value, AXmlElement::Encoding encoding, bool overwrite // = false ) { AASSERT(this, m_Content.size() < DEBUG_MAXSIZE_AXmlElement); //Debug only limit AXmlData *p = new AXmlData(value, encoding); p->setParent(this); //a_Overwrite clears existing content if (overwrite) clearContent(); m_Content.push_back(p); }
/*! Adds a text value to an existing element at the given path or will create element thisfunction("element path", "value") lua param: Element path lua param: Value to set lua return: nil */ static int alibrary_Objects_Model_addText(lua_State *L) { ATemplateContext *pLuaContext = static_cast<ATemplateContext *>(L->acontext); AASSERT(NULL, pLuaContext); size_t len = AConstant::npos; const char *s = luaL_checklstring(L, 1, &len); const AString& xmlpath = AString::wrap(s, len); AXmlElement &e = pLuaContext->useModel().useRoot().overwriteElement(xmlpath); if (lua_gettop(L) > 1) { s = luaL_checklstring(L, 2, &len); const AString& value = AString::wrap(s, len); e.addData(value); } return 0; }
void ATextOdometer::_dec() { size_t s = 0; size_t pos = mstr_Odometer.getSize(); AASSERT(this, pos); pos--; for (size_t i = pos; i != AConstant::npos; --i) { //a_Find the location and increment s = mstr_Subset.find(mstr_Odometer.at(i)); if (s > 0x0) { mstr_Odometer.set(mstr_Subset.at(--s), i); break; } else mstr_Odometer.set(mstr_Subset.at(mstr_Subset.getSize() - 1), i); } }
void ATextOdometer::_inc() { size_t s = 0; size_t pos = mstr_Odometer.getSize(); AASSERT(this, pos); pos--; for (size_t i = pos; i != (size_t)-1; --i) { //a_Find the location and increment s = mstr_Subset.find(mstr_Odometer.at(i)); if ((s + 0x1) < mstr_Subset.getSize()) { mstr_Odometer.set(mstr_Subset.at(++s), i); break; } else mstr_Odometer.set(mstr_Subset.at(0x0), i); } }
/*! Gets text value for a given path thisfunction("element path") lua param: Element path lua return: Text content for a given element or nil if it doesn't exist */ static int alibrary_Objects_Model_getText(lua_State *L) { ATemplateContext *pLuaContext = static_cast<ATemplateContext *>(L->acontext); AASSERT(NULL, pLuaContext); size_t len = AConstant::npos; const char *s = luaL_checklstring(L, 1, &len); const AString& xmlpath = AString::wrap(s, len); AXmlElement *pElement = pLuaContext->useModel().useRoot().findElement(xmlpath); if (!pElement) { return 0; } else { AString str; pElement->emitContent(str); lua_pushlstring(L, str.c_str(), str.getSize()); return 1; } }
NativeEngine* NativeEngine::GetInstance() { AASSERT(_singleton != NULL); return _singleton; }
u4 AOSContextQueue_IsAvailable::_threadprocWorker(AThread& thread) { AOSContextQueue_IsAvailable::QueueWithThread *pThis = dynamic_cast<AOSContextQueue_IsAvailable::QueueWithThread *>(thread.getThis()); AOSContextQueue_IsAvailable *pOwner = dynamic_cast<AOSContextQueue_IsAvailable *>(thread.getParameter()); AASSERT(&thread, pThis); AASSERT(&thread, pOwner); timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; thread.setRunning(true); fd_set sockSet; while (thread.isRun()) { try { if (pThis->queue.size() > 0) { FD_ZERO(&sockSet); int count = 0; // Convert to ABasePtrQueue ABase *p = pThis->queue.useHead(); while (count < FD_SETSIZE && p) { AOSContext *pContext = (AOSContext *)p; FD_SET((SOCKET)pContext->useSocket().getSocketInfo().m_handle, &sockSet); ++count; p = p->useNext(); } if (count > 0) { int availCount = ::select(count, &sockSet, NULL, NULL, &timeout); if (availCount > 0) { int count2 = 0; p = pThis->queue.useHead(); while (availCount > 0 && count2 <= count && p) { AOSContext *pContext = (AOSContext *)p; p = p->useNext(); if (FD_ISSET(pContext->useSocket().getSocketInfo().m_handle, &sockSet)) { pContext->useConnectionFlags().setBit(AOSContext::CONFLAG_ISAVAILABLE_SELECT_SET); //a_Attempt to read some data to check if it actually has data, if not then connection is closed size_t bytesRead = AConstant::npos; try { bytesRead = pContext->useSocket().readBlockIntoLookahead(); if (!bytesRead || AConstant::npos == bytesRead) { //a_No data to read, socket is closed pContext->useConnectionFlags().setBit(AOSContext::CONFLAG_IS_SOCKET_CLOSED); pContext->useEventVisitor().startEvent(ASW("AOSContextQueue_IsAvailable: Detected closed remote socket",58), AEventVisitor::EL_WARN); pContext->useSocket().close(); { ALock lock(pThis->sync); pThis->queue.remove(pContext); } pOwner->m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext); } else if (AConstant::unavail == bytesRead) { // Would block, keep waiting if (pContext->useTimeoutTimer().getInterval() > pOwner->m_NoDataTimeout) { AString str; str.append("AOSContextQueue_IsAvailable: No data (non-blocking) after timeout: ",67); pContext->useTimeoutTimer().emit(str); //a_We are done with this request, still no data pContext->useEventVisitor().startEvent( str, (pContext->useConnectionFlags().isSet(AOSContext::CONFLAG_IS_HTTP11_PIPELINING) ? AEventVisitor::EL_EVENT : AEventVisitor::EL_ERROR) ); { ALock lock(pThis->sync); pThis->queue.remove(pContext); } pOwner->m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext); } } else { //a_Add to next queue pContext->useConnectionFlags().setBit(AOSContext::CONFLAG_ISAVAILABLE_PENDING); if (pContext->useEventVisitor().isLogging(AEventVisitor::EL_DEBUG)) pContext->useEventVisitor().startEvent(ASW("AOSContextQueue_IsAvailable: HTTP header has more data",54), AEventVisitor::EL_DEBUG); { ALock lock(pThis->sync); pThis->queue.remove(pContext); } pOwner->m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_PRE_EXECUTE, &pContext); } } catch(AException e) { bytesRead = AConstant::npos; //a_Following switch will handle this ARope rope("AOSContextQueue_IsAvailable: Exception reading from socket",58); rope.append(e); pContext->useEventVisitor().addEvent(rope, AEventVisitor::EL_ERROR); } --availCount; } else { //a_Select called on this AOSContext and no data available if (pContext->useTimeoutTimer().getInterval() > pOwner->m_NoDataTimeout) { AString str; str.append("AOSContextQueue_IsAvailable: No data after timeout: ",52); pContext->useTimeoutTimer().emit(str); //a_We are done with this request, still no data pContext->useEventVisitor().startEvent( str, (pContext->useConnectionFlags().isSet(AOSContext::CONFLAG_IS_HTTP11_PIPELINING) ? AEventVisitor::EL_EVENT : AEventVisitor::EL_ERROR) ); { ALock lock(pThis->sync); pThis->queue.remove(pContext); } pOwner->m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext); } } ++count2; } AASSERT(pOwner, !availCount); } else { //a_Nothing has data, flag them all p = pThis->queue.useHead(); while (p) { AOSContext *pContext = (AOSContext *)p; p = p->useNext(); if (pContext->useTimeoutTimer().getInterval() > pOwner->m_NoDataTimeout) { AString str("AOSContextQueue_IsAvailable: No data after timeout: ",52); pContext->useTimeoutTimer().emit(str); //a_We are done with this request, still no data ALock lock(pThis->sync); pContext->useEventVisitor().startEvent( str, (pContext->useConnectionFlags().isSet(AOSContext::CONFLAG_IS_HTTP11_PIPELINING) ? AEventVisitor::EL_EVENT : AEventVisitor::EL_ERROR) ); pThis->queue.remove(pContext); pOwner->m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext); } } } } //a_Sleep between selects, requests in this queue are already slow AThread::sleep(pOwner->m_LoopDelay); } else AThread::sleep(pOwner->m_EmptyQueueDelay); //a_Nothing in queue, deep sleep } catch(AException& e) { pOwner->m_Services.useLog().addException(e); } catch(std::exception& e) { pOwner->m_Services.useLog().addException(e); } catch(...) { pOwner->m_Services.useLog().add(ASWNL("Unknown exception caught in AOSContextQueue_IsAvailable::threadproc"), ALog::EVENT_EXCEPTION); } } thread.setRunning(false); return 0; }
size_t AFile_Physical::getSize() const { s8 size = AFileSystem::length(m_filename); AASSERT(this, size <= SIZE_MAX); //a_If this ever happens getSize should be upgraded to s8 return (size_t)size; }
ADatabasePool& AOSDatabaseConnectionPool::useDatabasePool() { AASSERT(this, mp_DatabasePool); return *mp_DatabasePool; }
ASynchronization& AOSSessionMapHolder::useSyncObject() { AASSERT(this, mp_SyncObject); return *mp_SyncObject; }