Exemple #1
0
void AOSDatabaseConnectionPool::adminEmitXml(AXmlElement& eBase, const AHTTPRequestHeader& request)
{ 
  AOSAdminInterface::adminEmitXml(eBase, request);

  adminAddProperty(eBase, ASW("isInitialized",13), (m_isInitialized ? AConstant::ASTRING_TRUE : AConstant::ASTRING_FALSE));
  if (mp_DatabasePool)
    adminAddProperty(eBase, ASW("DatabasePool",12), *mp_DatabasePool);
}
Exemple #2
0
void ATemplateNodeHandler_DADA::_loadStaticData()
{
  AXmlElement::CONST_CONTAINER nodes;

  m_Services.useConfiguration().getConfigRoot().find("AOS_DadaData/dataset", nodes);
  AXmlElement::CONST_CONTAINER::iterator it;
  for (it = nodes.begin(); it != nodes.end(); ++it)
  {
    AString strSet;
    (*it)->getAttributes().get(ASW("name",4), strSet);
    if (strSet.isEmpty())
      ATHROW_EX(*it, AException::InvalidData, ASWNL("AOS_DadaData/dataset missing 'name' parameter"));

    ADadaDataHolder *pddh = new ADadaDataHolder();
    pddh->readData(m_Services, *it);
    m_Objects.insert(strSet, pddh, true);
  }

  nodes.clear();
  m_Services.useConfiguration().getConfigRoot().find(ASW("AOS_DadaData/template",21), nodes);
  it = nodes.begin();
  while (it != nodes.end())
  {
    AString str;
    (*it)->emitContent(str);
    
    AString strName;
    if ((*it)->getAttributes().get(ASW("name",4), strName))
    {
      AFilename filename(m_Services.useConfiguration().getAosBaseDataDirectory(), str, false);
      if (AFileSystem::exists(filename))
      {
        AFile_Physical file(filename, ASW("r", 1));
        file.open();

        str.clear();
        while (AConstant::npos != file.readLine(str))
        {
          if ('#' != str.at(0, '\x0'))
          {
            m_Templates[strName].push_back(str);
          }
          str.clear();
        }
      }
      else
        m_Services.useLog().add(ARope("AOS_DadaData: Missing file: ")+filename, ALog::EVENT_WARNING);
    }
    else
      m_Services.useLog().add(ASWNL("AOS_DadaData: AOS_DadaData/template missing 'name' attribute"), ALog::EVENT_FAILURE);

    ++it;
  }
}
Exemple #3
0
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;
}
Exemple #4
0
void AOSAdminCommand_list::_process(AOSAdminCommandContext& context)
{
  //a_Display list of objects
  LIST_AString objectNames;
  m_Services.useAdminRegistry().listAdminObjects(objectNames);

  LIST_AString::iterator it = objectNames.begin();
  while (it != objectNames.end())
  {
    AXmlElement& e = context.useModel().useRoot().addElement(ASW("object",6));
    e.addAttribute(ASW("name",4), *it);

    ++it;
  }
}
Exemple #5
0
void AMySQLServer::emit(AXmlElement& target) const
{
  if (target.useName().isEmpty())
    target.useName().assign("AMySQLServer", 12);

  ADatabase::emitXml(target);

  target.addElement(ASW("client",6)).addData(mysql_get_client_info());
  if (mp_mydata)
  {
    target.addElement(ASW("stat",4)).addData(mysql_stat(mp_mydata)); 
    target.addElement(ASW("server",6)).addData(mysql_get_server_info(mp_mydata)); 
    target.addElement(ASW("host",4)).addData(mysql_get_host_info(mp_mydata)); 
  }
}
Exemple #6
0
void ATemplateNodeHandler_RESOURCE::Node::process(ATemplateContext& ctx, AOutputBuffer& output)
{
  AAutoPtr<AEventVisitor::ScopedEvent> scoped;
  if (ctx.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
  {
    scoped.reset(new AEventVisitor::ScopedEvent(ctx.useEventVisitor(), ASW("ATemplateNodeHandler_RESOURCE",28), m_BlockData, AEventVisitor::EL_DEBUG));
  }

  if (m_BlockData.isEmpty())
    return;

  // Get resource
  AOSContext *pContext = ctx.useObjects().useAsPtr<AOSContext>(AOSContext::OBJECTNAME);
  if (!pContext)
  {
    ARope rope("Must have AOSContext object named: ",35);
    rope.append(AOSContext::OBJECTNAME);
    ATHROW_EX(this, AException::NotFound, rope);
  }

  LIST_AString languages;
  pContext->useRequestHeader().getAcceptLanguageList(languages);
  const AXmlDocument *pDoc = pContext->useServices().useResourceManager().getResources(languages);
  if (!pDoc)
  {
    if (pContext->useEventVisitor().isLogging(AEventVisitor::EL_WARN))
    {
      pContext->useEventVisitor().startEvent(ASW("Unable to find resource container for locales in Accept-Languages",65), AEventVisitor::EL_WARN);
    }
    return;
  }
  
  const AXmlElement *pElement = pDoc->getRoot().findElement(m_BlockData);
  if (pElement)
  {
    //a_Found object
    pElement->emitContent(output);
  }
  else
  {
    if (pContext->useEventVisitor().isLogging(AEventVisitor::EL_WARN))
    {
      ARope rope("Unable to find resource element: ",33);
      rope.append(m_BlockData);
      pContext->useEventVisitor().startEvent(rope, AEventVisitor::EL_WARN);
    }
  }
}
Exemple #7
0
void AOSOutputExecutor::registerOutputGenerator(AOSOutputGeneratorInterface *pGenerator)
{
  if (!pGenerator)
    ATHROW(this, AException::InvalidParameter);

  const AString& command = pGenerator->getClass();

  {
    AString str("  Output Generator Registered: ");
    str.append(command);
    AOS_DEBUGTRACE(str.c_str(), NULL);
  }

  OutputGeneratorContainer::iterator it = m_OutputGenerators.find(command);
  if (it != m_OutputGenerators.end())
  {
    //a_Command already has this processor
    m_Services.useLog().add(ASWNL("AOSOutputExecutor::registerOutputGenerator:replacing output generator"), (*it).first, command, ALog::EVENT_WARNING);
    delete (*it).second;
    (*it).second = pGenerator;
  }
  else
  {
    //a_Add new command
    m_Services.useLog().add(ASWNL("AOSOutputExecutor::registerOutputGenerator"), command, ALog::EVENT_INFO);
    m_OutputGenerators[command] = pGenerator;
  }

  //a_Initialize it
  pGenerator->init();

  //a_Register the module's admin interface
  pGenerator->adminRegisterObject(m_Services.useAdminRegistry(), ASW("AOSOutputExecutor",17));
}
void ATemplateNodeHandler_MODEL::Node::process(ATemplateContext& context, AOutputBuffer& output)
{
  AAutoPtr<AEventVisitor::ScopedEvent> scoped;
  if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
  {
    scoped.reset(new AEventVisitor::ScopedEvent(context.useEventVisitor(), ASW("ATemplateNodeHandler_MODEL",26), m_BlockData, AEventVisitor::EL_DEBUG));
  }

  if (m_BlockData.isEmpty())
    return;

  AXmlElement *pElement = context.useModel().useRoot().findElement(m_BlockData);
  if (pElement)
  {
    //a_Found object
    pElement->emitContent(output);
  }
  else
  {
    ARope rope("<!--Unable to find element for '",32); 
    rope.append(m_BlockData);
    rope.append("'-->",4); 
    output.append(rope);
  }
}
Exemple #9
0
AOSContextQueue_IsAvailable::AOSContextQueue_IsAvailable(
  AOSServices& services,
  size_t queueCount  // = 1
) :
  AOSContextQueueInterface(services),
  m_queueCount(queueCount),
  m_currentQueue(0)
{
  m_Queues.resize(m_queueCount);
  for (size_t i=0; i<m_queueCount; ++i)
    m_Queues.at(i) = new AOSContextQueue_IsAvailable::QueueWithThread();

  m_NoDataTimeout = m_Services.useConfiguration().getConfigRoot().getInt(ASW("/config/server/context-queue/is-available/no-data-timeout",57), 60000);
  m_EmptyQueueDelay = m_Services.useConfiguration().getConfigRoot().getInt(ASW("/config/server/context-queue/is-available/empty-queue-sleep-delay",65), 20);
  m_LoopDelay = m_Services.useConfiguration().getConfigRoot().getInt(ASW("/config/server/context-queue/is-available/loop-delay",52), 5);

  adminRegisterObject(services.useAdminRegistry());
}
Exemple #10
0
void AOSOutputExecutor::adminEmitXml(AXmlElement& eBase, const AHTTPRequestHeader& request)
{
  AOSAdminInterface::adminEmitXml(eBase, request);

  OutputGeneratorContainer::const_iterator cit = m_OutputGenerators.begin();
  while (cit != m_OutputGenerators.end())
  {
    adminAddProperty(eBase, ASW("generator",9), (*cit).second->getClass());
    ++cit;
  }
}
Exemple #11
0
AOSContext::ReturnCode AOSOutput_JSON::execute(AOSContext& context)
{
  AXmlElement::CONST_CONTAINER paths;
  AXmlElement::CONST_CONTAINER nodes;
  if (context.getOutputParams().find(AOS_BaseModules_Constants::PATH, paths))
  {
    // Get the path fragments and convert into nodes
    for (AXmlElement::CONST_CONTAINER::const_iterator cit = paths.begin(); cit != paths.end(); ++cit)
    {
      // Get path and find associated nodes
      AString path;
      (*cit)->emitContent(path);
      context.useModel().find(path, nodes);
    }
  }

  if (nodes.size() > 0)
  {
    if (nodes.size() > 1)
    {
      // Array
      context.useOutputBuffer().append("[\r\n",3);
      AXmlElement::CONST_CONTAINER::const_iterator cit = nodes.begin();
      while(cit != nodes.end())
      {
        (*cit)->emitJson(context.useOutputBuffer(),1); 
        ++cit;
        if (cit != nodes.end())
          context.useOutputBuffer().append("\r\n,\r\n",5);
      }
      context.useOutputBuffer().append("\r\n]",3);
    }
    else
    {
      // Single object
      nodes.front()->emitJson(context.useOutputBuffer(),0);
    }
  }
  else
  {
    // Entire context model to JSON
    if (context.useEventVisitor().isLoggingDebug())
    {
      context.useEventVisitor().addEvent(ASWNL("Emitting the entire model as JSON object"), AEventVisitor::EL_DEBUG);
    }
    context.useModel().emitJson(context.useOutputBuffer(),0);
  }
  
  // Set the correct content type for XML extension
  m_Services.useConfiguration().setMimeTypeFromExt(ASW("json",4), context);

  return AOSContext::RETURN_OK;
}
Exemple #12
0
void AOSAdminCommand_modify::_process(AOSAdminCommandContext& context)
{
  AString objectName;
  if (!context.useRequestHeader().useUrl().useParameterPairs().get(ASW("object",6), objectName))
  {
    context.useModel().useRoot().addElement(ASW("error",5), ASW("Please specify which 'object=' to modify",40));
  }
  else
  {
    //a_Display object specific list
    AOSAdminInterface *pAdminObject = m_Services.useAdminRegistry().getAdminObject(objectName);
    
    //a_Add methods if any
    if (pAdminObject)
    {
      AXmlElement& eObject = context.useModel().useRoot().addElement(ASW("object",6)).addAttribute(ASW("name",4), objectName);
      pAdminObject->adminProcessAction(eObject, context.useRequestHeader());
      pAdminObject->adminEmitXml(eObject, context.useRequestHeader());
    }
    else
    {
      context.useModel().useRoot().addElement(ASW("error",5), ASW("Unknown object",14));
    }
  }
}
Exemple #13
0
void AFilename::emitPath(AOutputBuffer& target, AFilename::FTYPE ftype, bool noTrailingSlash) const
{
  char sep = '/';
  if (FTYPE_MSDOS == ftype)
    sep = '\\';

  //a_Drive
  if (m_Drive)
  {
    switch (ftype)
    {
      case FTYPE_UNIX: 
      break;

      case FTYPE_CYGWIN:
        target.append(ASW("/cygdrive/",10));
        target.append(m_Drive);
      break;
      
      default:
        if (!m_RelativePath)
        {
          target.append(m_Drive);
          target.append(':');
        }
    }
  }

  //a_Add slash is not a relative path
  if (!m_RelativePath)
    target.append(sep);
  else if (0 == m_PathNames.size())
  {
    //a_Special case, relative and no path, default to . or ./ (depends on noTailingSlash flag)
    target.append(AConstant::ASTRING_PERIOD);
    if (!noTrailingSlash)
      target.append(sep);

    return;
  }

  //a_Path
  LIST_AString::const_iterator cit = m_PathNames.begin();
  while (cit != m_PathNames.end())
  {
    target.append(*cit);
    ++cit;

    if (cit != m_PathNames.end() || !noTrailingSlash)
      target.append(sep);
  }
}
Exemple #14
0
void AOSAdminCommand_display::_insertStylesheet(AOSAdminCommandContext& context)
{
  AString stylesheet("/xsl/_command/display",21);
  AString objectName;
  if (context.useRequestHeader().useUrl().useParameterPairs().get("object", objectName))
  {
    stylesheet.append('_');
    stylesheet.append(objectName);
  }
  stylesheet.append(".xsl",4);

  AFilename fn(m_Services.useConfiguration().getAdminBaseHttpDir(), stylesheet, false);
  if (!AFileSystem::exists(fn))
  {
    //a_Fallback on default
    stylesheet.assign("/xsl/_command/display.xsl",25);
  }

  context.useModel().addInstruction(AXmlInstruction::XML_STYLESHEET)
    .addAttribute(ASW("type",4), ASW("text/xsl",8))
    .addAttribute(ASW("href",4), stylesheet);
}
Exemple #15
0
void AOSContextQueue_IsAvailable::adminEmitXml(AXmlElement& eBase, const AHTTPRequestHeader& request)
{
  AOSContextQueueInterface::adminEmitXml(eBase, request);

  adminAddProperty(
    eBase,
    ASW("CurrentQueue",12),
    AString::fromInt(m_currentQueue % m_queueCount)
  );

  adminAddProperty(
    eBase,
    ASW("NoDataTimeout",13),
    AString::fromInt(m_NoDataTimeout)
  );

  adminAddProperty(
    eBase,
    ASW("EmptyQueueDelay",15),
    AString::fromInt(m_EmptyQueueDelay)
  );

  adminAddProperty(
    eBase,
    ASW("LoopDelay",9),
    AString::fromInt(m_LoopDelay)
  );

  adminAddProperty(
    eBase,
    ASW("Queues.size",11),
    AString::fromSize_t(m_queueCount)
  );

  for (size_t i=0; i<m_Queues.size(); ++i)
  {
    QueueWithThread *p = m_Queues.at(i);
    AString str("queue[",6);
    str.append(AString::fromSize_t(i));

    adminAddProperty(
      eBase,
      str+ASW("].count",7),
      AString::fromSize_t(p->count)
    );

    adminAddProperty(
      eBase,
      str+ASW("].size",6),
      AString::fromSize_t(p->queue.size())
    );
  }
}
Exemple #16
0
ALog_AFile::ALog_AFile(
  ASynchronization *pSynch,
  const AFilename& baseFilename,
  ALog::EVENT_MASK mask // = ALog::DEFAULT
) :
  ALog(pSynch, mask),
  mp_File(NULL),
  m_CycleSleep(DEFAULT_CYCLE_SLEEP),
  m_LoggerThread(ALog_AFile::threadprocLogger, false),
  m_logMaxFileSize(DEFAULT_MAX_FILE_SIZE),
  m_enableLogFileRotate(true),
  m_DeleteFileObject(true),
  m_enableSeparateFilesForErrors(true)
{
  //a_Base filename
  AFilename f(baseFilename);
  AString newFilename;
  f.emitFilenameNoExt(newFilename);
  
  //a_Timestamp of when the process was started
  ATime timeNow;
  newFilename.append('.');
  timeNow.emitYYYY_MM_DD_HHMMSS(newFilename);
  
  //a_Counter
  newFilename.append(".(6).",5);
  f.emitExtension(newFilename);
  m_filenameRotation.parse(newFilename);

  //a_Find the last file used for logging
  AString filename(1024, 256);
  f.useFilename().clear();
  m_filenameRotation.next(f.useFilename());
  while (AFileSystem::exists(f))
  {
    f.clear();
    m_filenameRotation.next(f.useFilename());
  }
  
  mp_File = new AFile_Physical(f, ASW("ab+",3));
  
  //a_Initialize thread
  m_LoggerThread.setThis(this);
  m_LoggerThread.start();
}
Exemple #17
0
void ATemplateNodeHandler_LUA::Node::process(ATemplateContext& context, AOutputBuffer& output)
{
  AAutoPtr<AEventVisitor::ScopedEvent> scoped;
  if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG)) 
  {
    scoped.reset(new AEventVisitor::ScopedEvent(context.useEventVisitor(), ASW("ATemplateNodeHandler_LUA",24), m_BlockData, AEventVisitor::EL_DEBUG));
  }

  if (m_BlockData.isEmpty())
    return;

  ALuaTemplateContext *pLuaTemplateContext = dynamic_cast<ALuaTemplateContext *>(&context);
  if (pLuaTemplateContext)
  {
    //a_Have a Lua context with its own interpreter
    if (!pLuaTemplateContext->useLua().execute(m_BlockData, context, output))
    {
      output.append(" block(context)={{{\r\n",21);
      output.append(m_BlockData);
      output.append("}}}\r\n",5);
      context.useEventVisitor().addEvent(output, AEventVisitor::EL_ERROR);
    }
  }
  else
  {
    //a_Create a temporary interpreter, this is the less efficient way of doing it
    ALuaEmbed lua;
    if (!lua.execute(m_BlockData, context, output))
    {
      output.append(" block(local)={{{\r\n",19);
      output.append(m_BlockData);
      output.append("}}}\r\n",5);
      context.useEventVisitor().addEvent(output, AEventVisitor::EL_ERROR);
    }
  }
}
Exemple #18
0
AXmlElement& AFilename::emitXml(AXmlElement& thisRoot) const
{
  thisRoot.addAttribute(ASW("os", 2), AString::fromInt(m_Type));

  //a_Drive
  if (m_Drive)
    thisRoot.addElement(ASW("drive",5)).addData(m_Drive);

  //a_Path
  AXmlElement& basePath = thisRoot.addElement(ASW("path",4));
  for (LIST_AString::const_iterator cit = m_PathNames.begin(); cit != m_PathNames.end(); ++cit)
  {
    basePath.addElement(ASW("dir",3)).addData(*cit);
  }

  //a_Filename
  if (!m_Filename.isEmpty())
    thisRoot.addElement(ASW("name",4)).addData(m_Filename);

  thisRoot.addElement(ASW("full",4)).addData(*this);
  
  return thisRoot;
}
Exemple #19
0
int ut_AString_Access()
{
  std::cerr << "ut_AString_Access" << std::endl;

  int iRet = 0x0;

  //a_Peeking
  AString strPeek;
  AString str0 = "SomethingNew";
  str0.peek(strPeek, 0);
  ASSERT_UNIT_TEST(strPeek == "SomethingNew", "AString::peek", "0", iRet);

  strPeek.clear();
  str0.peek(strPeek, 0, 9);
  ASSERT_UNIT_TEST(strPeek == "Something", "AString::peek", "1", iRet);

  strPeek.clear();
  str0.peek(strPeek, 9, 3);
  ASSERT_UNIT_TEST(strPeek == "New", "AString::peek", "2", iRet);
  ASSERT_UNIT_TEST(str0.peek(4) == 't', "AString::peek", "3", iRet);

  int pos0 = 0;
  str0 = "path0/path1/path2";
  strPeek.clear();
  pos0 = str0.peekUntil(strPeek, pos0, '/');
  ASSERT_UNIT_TEST(strPeek.equals("path0"), "AString::peekUntil", "0", iRet);

  strPeek.clear();
  pos0 = str0.peekUntil(strPeek, pos0+1, '/');
  ASSERT_UNIT_TEST(strPeek.equals("path1"), "AString::peekUntil", "1", iRet);

  strPeek.clear();
  pos0 = str0.peekUntil(strPeek, pos0+1, '/');
  ASSERT_UNIT_TEST(strPeek.equals("path2"), "AString::peekUntil", "2", iRet);
  ASSERT_UNIT_TEST(AConstant::npos == pos0, "AString::peekUntil", "3", iRet);

  //a_Set
  AString strSource0 = AString("New"), strSource1("Newer"), strSource2("123Now");
  str0 = "This is old";
  str0.set(strSource0, 8);
  ASSERT_UNIT_TEST(str0.equals("This is New"), "AString::set", "0", iRet);

  str0.set(strSource1, 8);
  ASSERT_UNIT_TEST(str0.equals("This is Newer"), "AString::set", "1", iRet);

  str0.set(strSource2, 8, 3, 3);
  ASSERT_UNIT_TEST(str0.equals("This is Now"), "AString::set", "2", iRet);

  str0.set('n', 8);
  ASSERT_UNIT_TEST(str0.equals("This is now"), "AString::set", "3", iRet);

  //a_Use
  str0.use(10) = 't';
  ASSERT_UNIT_TEST(str0.peek(10) == 't', "AString::use", "0", iRet);

  //a_Get
  AString strGet;
  str0 = "YetMoreStuff!";
  str0.get(strGet, 0, 3);
  ASSERT_UNIT_TEST(strGet.equals("Yet"), "AString::get", "0", iRet);

  str0.get(strGet, 0, 4);
  ASSERT_UNIT_TEST(strGet.equals("More"), "AString::get", "1", iRet);

  str0.get(strGet, 0, 5);
  ASSERT_UNIT_TEST(strGet.equals("Stuff"), "AString::get", "2", iRet);

  str0.get(strGet, 0, 0);
  ASSERT_UNIT_TEST(strGet.isEmpty(), "AString::get", "3", iRet);

  char cX = str0.get();
  ASSERT_UNIT_TEST(cX == '!', "AString::get", "4", iRet);
  ASSERT_UNIT_TEST(strGet.isEmpty(), "AString::get", "5", iRet);

  str0 = "SomeMoreStuff!";
  str0.get(strGet, 0);
  ASSERT_UNIT_TEST(strGet.equals("SomeMoreStuff!"), "AString::get", "6", iRet);
  ASSERT_UNIT_TEST(str0.isEmpty(), "AString::get", "7", iRet);
 
  str0 = "SomeMoreStuff!";
  str0.get(strGet, 0, 0);
  ASSERT_UNIT_TEST(str0.equals("SomeMoreStuff!"), "AString::get", "8", iRet);
  ASSERT_UNIT_TEST(strGet.isEmpty(), "AString::get", "9", iRet);

  str0 = "path0/path1/path2";
  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(strGet.equals("path0"), "AString::getUntil", "0", iRet);

  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(strGet.equals("path1"), "AString::getUntil", "1", iRet);

  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(strGet.equals("path2"), "AString::getUntil", "2", iRet);

  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(str0.isEmpty(), "AString::getUntil", "3", iRet);

  AString str1;
  str0="find_file_1";
  str0.peekUntil(str1, 2, "1");
  ASSERT_UNIT_TEST(!str1.compare("nd_file_"), "AString::peekUntil", "0", iRet);

  str0.getUntil(str1, "_", true);
  ASSERT_UNIT_TEST((!str1.compare("find") && !str0.compare("file_1")), "AString::getUntil", "4", iRet);

  str0="find_file_1";
  str0.getUntilOneOf(str1, ASW("_",1), false);
  ASSERT_UNIT_TEST((!str1.compare("find") && !str0.compare("_file_1")), "AString::getUntil", "5", iRet);

  str0.remove(1);
  str1.clear();
  str0.getUntil(str1, ASW("_",1));
  ASSERT_UNIT_TEST((!str1.compare("file") && !str0.compare("1")), "AString::getUntil", "6", iRet);

  return iRet;
}
Exemple #20
0
AOSContext::ReturnCode AOSModule_Wiki_ViewFromFileSystem::execute(AOSContext& context, const AXmlElement& moduleParams)
{
    //a_Get base path
    AString basePath;
    if (!moduleParams.emitString(AOS_Wiki_Constants::PARAM_BASE_PATH, basePath))
    {
        context.addError(getClass(), ASWNL("Unable to find module/base-path parameter"));
        return AOSContext::RETURN_ERROR;
    }
    AFilename wikifile(m_Services.useConfiguration().getAosBaseDataDirectory());
    wikifile.join(basePath, true);

    //a_Get relative wiki path
    AString str;
    context.useRequestParameterPairs().get(ASW("wikipath",8), str);
    wikifile.join(str, false);

    u4 type = AFileSystem::getType(wikifile);
    //a_Directory only will get default index.html
    if (type & AFileSystem::Directory)
    {
        //a_Directory name specified
        wikifile.useFilename().assign(ASW("index.html",10));
    }
    else
        wikifile.setExtension(ASW(".html",5));

    AString strData;
    if (context.useRequestParameterPairs().get(ASW("wiki.newdata",12), strData))
    {
        //a_Check if authentication passed
        if (
            moduleParams.exists(AOS_Wiki_Constants::PARAM_SECURE)
            && !context.useModel().exists(ASW("wiki/Authenticated",18))
        )
        {
            context.useModel().overwriteElement(ASW("wiki/AuthFailed",15));
            return AOSContext::RETURN_OK;
        }

        //a_New data submitted
        u4 type = AFileSystem::getType(wikifile);
        if (AFileSystem::DoesNotExist != type)
        {
            //a_New data submitted, old file exists
            AFilename newwikifile(wikifile);

            //a_Temporary filename to use during the swap
            AFilename tempwikifile(newwikifile);
            tempwikifile.setExtension(ASW("_temporary_rename_",19));

            //a_Generate temporary filename
            AFileSystem::generateTemporaryFilename(newwikifile);

            //a_Save new data to temp filename
            AFile_Physical file(newwikifile, "wb");
            file.open();
            file.write(strData);
            file.close();

            //a_Add to context so it can ve viewed after save
            context.useModel().overwriteElement(AOS_Wiki_Constants::ELEMENT_DATA).addData(strData, AXmlElement::ENC_CDATADIRECT);

            //a_Rename temp to current
            AFileSystem::rename(wikifile, tempwikifile);
            AFileSystem::rename(newwikifile, wikifile);
            AFileSystem::remove(tempwikifile);
        }
        else
        {
            //a_Does not exist yet
            //a_Make sure directories exist
            AFileSystem::createDirectories(wikifile);

            //a_Save new data
            AFile_Physical file(wikifile, "wb");
            file.open();
            file.write(strData);
            file.close();

            //a_Add to context so it can ve viewed after save
            context.useModel().overwriteElement(AOS_Wiki_Constants::ELEMENT_DATA).addData(strData, AXmlElement::ENC_CDATADIRECT);
        }
    }
    else
    {
        u4 type = AFileSystem::getType(wikifile);
        if (AFileSystem::DoesNotExist != type)
        {
            AFile_Physical file(wikifile);
            file.open();
            context.useModel().overwriteElement(AOS_Wiki_Constants::ELEMENT_DATA).addData(file, AXmlElement::ENC_CDATADIRECT);
        }
        else
        {
            //a_Signal that the wiki file does not exist
            context.useModel().overwriteElement(AOS_Wiki_Constants::ELEMENT_DOES_NOT_EXIST);
        }

        if (moduleParams.exists(AOS_Wiki_Constants::PARAM_SECURE))
        {
            context.useModel().overwriteElement(AOS_Wiki_Constants::ELEMENT_SECURE_EDIT);
        }

    }

    return AOSContext::RETURN_OK;
}
Exemple #21
0
void AXmlElement::fromAFile(AFile& file)
{
  AString str(1024, 256);

  //a_Find <
  if (AConstant::npos == file.skipUntilOneOf('<'))
    return;

  //a_Skip over whitespace between < and tagname
  file.skipUntilNotOneOf();

  //a_Extract name and skip over whitespace
  m_Name.clear();
  file.readUntilOneOf(m_Name, AXmlElement::sstr_EndOrWhitespace, false);
  file.skipUntilNotOneOf();
  
  //a_Find /> or >
  char c = ' ';
  if (0 == m_Name.find(ASW("!--",3)))
  {
    if (m_Name.rfind("--", 2) == m_Name.getSize() - 2)  //TODO:
    //a_Special case for comment, must end with '-->' and may contain '>' inside
    file.readUntil(str, AXmlElement::sstr_EndComment);
    addComment(str);
    return;
  }
  else
    file.readUntilOneOf(str, AXmlElement::sstr_End);

  if (!str.isEmpty() && str.at(str.getSize() - 1) == '/')
  {
    c = '/';  //a_Singular mode
    str.setSize(str.getSize() - 1);
  }
  str.stripTrailing();

  //a_Parse attributes
  if (!str.isEmpty())
    m_Attributes.parse(str);

  bool boolEndTagFound = (c == '/');
  while (!boolEndTagFound)
  {
    //a_Read data until next tag starts
    file.skipUntilNotOneOf();                //a_Skip over whitespace
    str.clear();
    if (AConstant::npos == file.readUntilOneOf(str, AXmlElement::sstr_Start))
      break;

    str.stripTrailing();
    if (!str.isEmpty())
    {
      addData(str);
    }

    //a_Skip over whitespace between < and start of the tag name
    file.skipUntilNotOneOf();

    file.peek(c);
    switch(c)
    {
      case '/':
      {
        //a_End of tag found
        file.read(c);
        str.clear();
        file.readUntilOneOf(str, AXmlElement::sstr_EndOrWhitespace);
        file.skipUntilNotOneOf(AXmlElement::sstr_EndOrWhitespace);                //a_Skip over whitespace and >
        if (str != m_Name)
          ATHROW_EX(&file, AException::InvalidData, AString("Close tag </")+str+"> does not match opened tag <"+m_Name+">");
        
        boolEndTagFound = true;
      }
      break;

      //a_Handle embedded CDATA, comments and such
      case '!':
      {
        file.putBack('<');
        str.clear();
        
        file.peek(str, 9);    //a_ either "<!--*--"  or "<![CDATA["
        if (0 == str.findNoCase(AXmlData::sstr_StartCDATA))
        {
          //a_CDATA found
          file.skip(AXmlData::sstr_StartCDATA.getSize());

          AString data;
          file.readUntil(data, AXmlData::sstr_EndCDATA, true, true);
          addData(data, AXmlElement::ENC_CDATADIRECT);
        }
        else if (0 == str.findNoCase(AXmlElement::sstr_StartComment))
        {
          //a_Comment (!--) found
          file.skip(AXmlElement::sstr_StartComment.getSize());

          AString comment;
          file.readUntil(comment, AXmlElement::sstr_EndComment, true, true);
          addComment(comment);
        }
        else
        {
          addData(str);
        }
      }
      break;

      default:
      {
        //a_Put the start tag back
        file.putBack('<');

        //a_Another element
        AAutoPtr<AXmlElement> psubElement(new AXmlElement(), true);
        psubElement->fromAFile(file);
        psubElement.setOwnership(false);
        addContent(psubElement.use());
      }
      break;
    }
  }
}
Exemple #22
0
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;
}
Exemple #23
0
AOSContext::ReturnCode AOSModule_Template::execute(AOSContext& context, const AXmlElement& params)
{
  const AXmlElement *pNode = params.findElement(ASW("template",8));
  AAutoPtr<ATemplate> pTemplate(NULL, false);
  AAutoPtr<AFile> pFile(NULL, false);
  if (pNode)
  {
    //a_Element contains script
    pTemplate.reset(m_Services.createTemplate(), true);
    
    //a_Parse template
    AFile_AString strfile;
    pNode->emitContent(strfile);
    pTemplate->fromAFile(strfile);
  }
  else
  {
    //a_Filename provided, use the cache
    pNode = params.findElement(AOS_BaseModules_Constants::FILENAME);
    if (pNode)
    {
      AString relativePath;
      pNode->emitContent(relativePath);

      //a_File to be used (may need caching for it, but for now keep it dynamic)
      AFilename filename(m_Services.useConfiguration().getAosBaseDataDirectory(), true);
      filename.join(relativePath, false);
      if (ACacheInterface::NOT_FOUND == m_Services.useCacheManager().getTemplate(context, filename, pTemplate))
      {
        //a_Not found, return error
        ARope rope;
        rope.append(getClass());
        rope.append(": Unable to find a template file: ",34);
        rope.append(filename);
        context.useEventVisitor().startEvent(rope, AEventVisitor::EL_ERROR);
        return AOSContext::RETURN_ERROR;
      }
    }
    else
    {
      context.addError(getClass(), ASWNL("Unable to find module/template nor module/filename, Template module did not execute, params"));
      return AOSContext::RETURN_ERROR;  //a_Did not find either module/template or module/filename
    }
  }  

  //a_Process and save output
  ARope ropeOutput;
  pTemplate->process(context.useLuaTemplateContext(), ropeOutput);
  
  //a_Add template to debug
  if (context.getDumpContextLevel() > 0)
  {
    AString str("debug/",6);
    str.append(getClass());
    str.append("/template",9);
    AXmlElement& base = context.useModel().addElement(str);
    pTemplate->emitXml(base);
  }

  //a_Insert output into outpath (if any)
  pNode = params.findElement(AOS_BaseModules_Constants::PATH);
  if (pNode)
  {
    AString xmlpath;
    pNode->emitContent(xmlpath);
    if (!xmlpath.isEmpty())
    {
      //a_Add output as CDATA
      context.useModel().addElement(xmlpath).addData(ropeOutput, AXmlElement::ENC_CDATADIRECT);
    }
  }
  else
  {
    context.useEventVisitor().addEvent(ASWNL("Unable to find module/path, output from template discarded"), AEventVisitor::EL_WARN);
  }
  return AOSContext::RETURN_OK;
}
Exemple #24
0
AXmlElement& AXmlElement::setData(const char value)
{
  _addData(ASW(&value,1), AXmlElement::ENC_NONE, true);
  return *this;
}
Exemple #25
0
u4 AOSContextQueue_ErrorExecutor::_threadproc(AThread& thread)
{
  AOSContextQueue_ErrorExecutor *pThis = dynamic_cast<AOSContextQueue_ErrorExecutor *>(thread.getThis());
  AASSERT(&thread, pThis);
  AOSContext *pContext = NULL;

  thread.setRunning(true);
  while(thread.isRun())
  {
    try
    {
      while (pContext = pThis->_nextContext()) 
      {
#ifndef NDEBUG
        if (!ADebugDumpable::isPointerValid(pContext))
        {
          AString error("AOSContext pointer is invalid: ");
          error.append(AString::fromPointer(pContext));
          AASSERT_EX(NULL, false, error);
          continue;
        }
#endif
        pContext->useEventVisitor().startEvent(ASW("AOSContextQueue_ErrorExecutor: Processing error condition", 57));

        //a_Should only be here if an error occured, if status not set >200, then assume 500
        if (pContext->useResponseHeader().getStatusCode() == AHTTPResponseHeader::SC_200_Ok)
          pContext->useResponseHeader().setStatusCode(AHTTPResponseHeader::SC_500_Internal_Server_Error);

        //a_Check is socket was closed, if so do nothing else, we are done
        if (pContext->useConnectionFlags().isSet(AOSContext::CONFLAG_IS_SOCKET_ERROR))
        {
          //a_Proceed
          m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext);
          continue;
        }

        if (
             pContext->useContextFlags().isSet(AOSContext::CTXFLAG_IS_RESPONSE_HEADER_SENT)
          || pContext->useContextFlags().isSet(AOSContext::CTXFLAG_IS_OUTPUT_SENT)
        )
        {
          //a_Log to file, output is done already
          m_Services.useLog().add(pContext->useEventVisitor(), ALog::EVENT_FAILURE);
        }
        else
        {          

          //a_Add XSLT stylesheet for the error XML
          //if (m_Services.useConfiguration().exists(ASW("/config/server/error-stylesheet",31)))
          //{
          //  AString errorStylesheet;
          //  m_Services.useConfiguration().emitString(ASW("/config/server/error-stylesheet",31), errorStylesheet);
          //  pContext->useModelXmlDocument().addInstruction(AXmlInstruction::XML_STYLESHEET)
          //    .addAttribute(ASW("type",4), ASW("text/xsl",8))
          //    .addAttribute(ASW("href",4), errorStylesheet);
          //}

          //a_Add request header to result XML
          if (!pContext->useModel().exists(ASW("REQUEST",7)))
            pContext->useRequestHeader().emitXml(pContext->useModel().overwriteElement(ASW("REQUEST",7)));
          pContext->useResponseHeader().emitXml(pContext->useModel().overwriteElement(ASW("RESPONSE",8)));

          //a_Check if dumpContext is specified to override and emit XML
          int dumpContextLevel = pContext->getDumpContextLevel();
          pContext->dumpContext(dumpContextLevel);
          if (dumpContextLevel > 0)
          {
            //a_Write contents of the output XML instead of output buffer
            m_Services.useConfiguration().setMimeTypeFromExt(ASW("xml",3), *pContext);
            pContext->useResponseHeader().setStatusCode(AHTTPResponseHeader::SC_200_Ok);
            pContext->writeOutputBuffer(true);
          }
          else
          {
            //a_Set the current content type as text/html
            pContext->useResponseHeader().set(AHTTPHeader::HT_ENT_Content_Type, ASW("text/html; charset=utf-8",24));

            int statusCode = pContext->useResponseHeader().getStatusCode();
            
            AAutoPtr<ATemplate> pTemplate(NULL, false);  //a_Call to cache manager will set a template
            pContext->clearOutputBuffer();
            if (m_Services.useCacheManager().getStatusTemplate(statusCode, pTemplate))
            {
              //a_Template for this status code is found, so process and emit into output buffer
              pTemplate->process(pContext->useLuaTemplateContext(), pContext->useOutputBuffer());
              if (pContext->useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
              {
                ARope rope("Using error template for status ");
                rope.append(AString::fromInt(statusCode));
                pContext->useEventVisitor().startEvent(rope, AEventVisitor::EL_DEBUG);
              }
            }
            else
            {
              if (pContext->useEventVisitor().isLogging(AEventVisitor::EL_WARN))
              {
                ARope rope("Did not find error template for status ");
                rope.append(AString::fromInt(statusCode));
                pContext->useEventVisitor().startEvent(rope, AEventVisitor::EL_WARN);
              }
            }

            if (pContext->isOutputBufferEmpty())
            {
              AString strError(1024, 256);
              strError.assign("Error ",6);
              strError.append(AString::fromInt(pContext->useResponseHeader().getStatusCode()));
              strError.append(": ", 2);
              strError.append(pContext->useResponseHeader().getStatusCodeReasonPhrase(pContext->useResponseHeader().getStatusCode()));

              //a_Put some generic stuff since there is no error template
              pContext->useOutputBuffer().append("<html><head><title>",19);
              pContext->useOutputBuffer().append(strError);
              pContext->useOutputBuffer().append("</title></head>",15);
              pContext->useOutputBuffer().append("<body>",6);
              pContext->useOutputBuffer().append(strError);
              pContext->useOutputBuffer().append("</body></html>",14);
            }

            try
            {
              pContext->writeOutputBuffer();
            }
            catch(ASocketException& ex)
            {
              pContext->useEventVisitor().addEvent(ex, AEventVisitor::EL_ERROR);
              pContext->useConnectionFlags().setBit(AOSContext::CONFLAG_IS_SOCKET_ERROR);
              m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext);
              continue;
            }
          }
        }

        //a_Close connection
        pContext->useSocket().close();

        //a_Proceed
        m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext);
        continue;
      }
      AThread::sleep(pThis->m_SleepDelay);  //a_Empty queue, avoid thrashing
    }
    catch(AException& e)
    {
      pContext->useEventVisitor().addEvent(e, AEventVisitor::EL_ERROR);
      m_Services.useLog().add(pContext->useEventVisitor(), ALog::EVENT_FAILURE);
      m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext);
    }
    catch(std::exception& e)
    {
      pContext->useEventVisitor().addEvent(ASWNL(e.what()), AEventVisitor::EL_ERROR);
      m_Services.useLog().add(pContext->useEventVisitor(), ALog::EVENT_FAILURE);
      m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext);
    }
    catch(...)
    {
      m_Services.useLog().add(pContext->useEventVisitor(), ALog::EVENT_FAILURE);
      pContext->useEventVisitor().addEvent(ASWNL("Unknown exception caught in AOSContextQueue_ErrorExecutor::_threadproc"), AEventVisitor::EL_ERROR);
      m_Services.useContextManager().changeQueueState(AOSContextManager::STATE_TERMINATE, &pContext);
      break;
    }
  }

  thread.setRunning(false);
  return 0;
}
Exemple #26
0
AOSContext::ReturnCode AOSOutput_Template::execute(AOSContext& context)
{
  //a_See if extension for mime type set for the template(s)
  AString ext;
  if (context.getOutputParams().emitContentFromPath(AOS_BaseModules_Constants::MIME_EXTENSION, ext))
  {
    m_Services.useConfiguration().setMimeTypeFromExt(ext, context);
  }
  else
  {
    //a_Set content type based on request URL extension
    m_Services.useConfiguration().setMimeTypeFromExt(context.useRequestUrl().getExtension(), context);
  }
  
  // Iterate parameters and build the template
  const AXmlElement::CONTAINER& container = context.getOutputParams().getContentContainer();
  for (AXmlElement::CONTAINER::const_iterator cit = container.begin(); cit != container.end(); ++cit)
  {
    //a_Check "if" condition
    AString ifElement;
    if ((*cit)->getAttributes().get(ASW("if",2), ifElement))
    {
      if (ifElement.getSize() > 0)
      {
        //a_Check condition, if not met continue with next template
        if (!context.useModel().exists(ifElement))
        {
          if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
            context.useEventVisitor().startEvent(ARope("Skipping conditional file template IF ")+ifElement, AEventVisitor::EL_DEBUG);
          continue;
        }
      }
    }
    //a_Check "ifnot" condition
    ifElement.clear();
    if ((*cit)->getAttributes().get(ASW("ifnot",5), ifElement))
    {
      if (ifElement.getSize() > 0)
      {
        //a_Check condition, if not met continue with next template
        if (context.useModel().exists(ifElement))
        {
          if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
            context.useEventVisitor().startEvent(ARope("Skipping conditional file template IFNOT ")+ifElement, AEventVisitor::EL_DEBUG);
          continue;
        }
      }
    }

    //
    // Now we check if this is inlined or filename
    //
    AString str(1024, 512);
    if ((*cit)->getName().equals(AOS_BaseModules_Constants::TEMPLATE))
    {
      if (context.useEventVisitor().isLoggingDebug())
      {
        context.useEventVisitor().startEvent(getClass() + ": Creating new inline template", AEventVisitor::EL_DEBUG);
      }
      // Create a new template
      AAutoPtr<ATemplate> pTemplate(m_Services.createTemplate(), true);

      // Add inline template
      str.clear();
      (*cit)->emitContent(str);
      AFile_AString strfile(str);
      pTemplate->clear();
      pTemplate->fromAFile(strfile);
      pTemplate->process(context.useLuaTemplateContext(), context.useOutputBuffer());
    }
    else if ((*cit)->getName().equals(AOS_BaseModules_Constants::FILENAME))
    {
      // Add filename based template
      AFilename filename(m_Services.useConfiguration().getAosBaseDataDirectory());
      str.clear();
      (*cit)->emitContent(str);
      filename.join(str, false);

      if (context.useEventVisitor().isLoggingDebug())
      {
        context.useEventVisitor().startEvent(getClass()+": Fetching/parsing template for: "+filename, AEventVisitor::EL_DEBUG);
      }
      AAutoPtr<ATemplate> pT(NULL, false);
      if (ACacheInterface::NOT_FOUND == m_Services.useCacheManager().getTemplate(context, filename, pT))
      {
        //a_Not found add error and continue
        if (context.useEventVisitor().isLogging(AEventVisitor::EL_WARN))
          context.useEventVisitor().startEvent(ARope(getClass())+ASWNL(": Unable to find a template file: ")+filename+ASWNL(", ignoring and continuing"), AEventVisitor::EL_WARN);
        continue;
      }

      //a_Parse template
      if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
      {
        context.useEventVisitor().startEvent(getClass()+"Processing template file: "+filename, AEventVisitor::EL_DEBUG);
      }
      AASSERT(this, pT.isNotNull());
      pT->process(context.useLuaTemplateContext(), context.useOutputBuffer());
    }
  }

  return AOSContext::RETURN_OK;
}
Exemple #27
0
void AOSContextManager::adminProcessAction(AXmlElement& eBase, const AHTTPRequestHeader& request)
{
  AString str;
  if (request.getUrl().getParameterPairs().get(ASW("property",8), str))
  {
    if (str.equals(ASWNL("AOSContextManager.log_level")))
    {
      str.clear();
      if (request.getUrl().getParameterPairs().get(ASW("Set",3), str))
      {
        int level = str.toInt();
        if (level >= AEventVisitor::EL_NONE && level <= AEventVisitor::EL_DEBUG)
        {
          m_DefaultEventLogLevel = level;
        }
        else
        {
          adminAddError(eBase, ASWNL("Invalid log level, must be (0-5)"));
        }
      }
    }
    else if (str.equals(ASWNL("AOSContextManager.clear_history")))
    {
      str.clear();
      if (request.getUrl().getParameterPairs().get(ASW("Clear",5), str))
      {
        int level = str.toInt();
        switch(level)
        {
          case 0:
            _clearHistory();
            _clearErrorHistory();
          break;

          case 1:
            _clearHistory();
          break;

          case 2:
            _clearErrorHistory();
          break;

          default:
            adminAddError(eBase, ASWNL("Invalid level for history clearing, must be (0,1,2)"));
        }
      }
    }
    else if (str.equals(ASWNL("AOSContextManager.history.max_size")))
    {
      str.clear();
      if (request.getUrl().getParameterPairs().get(ASW("Set",3), str))
      {
        int i = str.toInt();
        if (i >= 0)
        {
          m_HistoryMaxSize = i;
        }
        else
        {
          adminAddError(eBase, ASWNL("Invalid maximum size, must be >=0"));
        }
      }
    }
    else if (str.equals(ASWNL("AOSContextManager.error_history.max_size")))
    {
      str.clear();
      if (request.getUrl().getParameterPairs().get(ASW("Set",3), str))
      {
        int i = str.toInt();
        if (i >= 0)
        {
          m_ErrorHistoryMaxSize = i;
        }
        else
        {
          adminAddError(eBase, ASWNL("Invalid maximum size, must be >=0"));
        }
      }
    }
    else if (str.equals(ASWNL("AOSContextManager.freestore.max_size")))
    {
      str.clear();
      if (request.getUrl().getParameterPairs().get(ASW("Set",3), str))
      {
        int i = str.toInt();
        if (i >= 0)
        {
          m_FreeStoreMaxSize = i;
        }
        else
        {
          adminAddError(eBase, ASWNL("Invalid maximum size, must be >=0"));
        }
      }
    }
  }
}
Exemple #28
0
void AOSContextManager::adminEmitXml(AXmlElement& eBase, const AHTTPRequestHeader& request)
{
  AOSAdminInterface::adminEmitXml(eBase, request);

  //a_Check if specific context is required
  AString contextId;
  if (request.getUrl().getParameterPairs().get(ASW("contextId",9), contextId))
  {
    //a_Find the specific context
    {
      ALock lock(m_InUseSync);
      for (CONTEXT_INUSE::const_iterator cit = m_InUse.begin(); cit != m_InUse.end(); ++cit)
      {
        if (contextId == AString::fromPointer(*cit))
        {
          adminAddProperty(eBase, ASW("contextDetail",7), *(*cit), AXmlElement::ENC_CDATADIRECT);
          return;
        }
      }
    }
    
    {
      ALock lock(m_ErrorHistory.useSync());
      for (ABase *p = m_ErrorHistory.useTail(); p; p = p->usePrev())
      {
        AOSContext *pContext = dynamic_cast<AOSContext *>(p);
        if (contextId == AString::fromPointer(pContext))
        {
          adminAddProperty(eBase, ASW("contextDetail",7), *pContext, AXmlElement::ENC_CDATADIRECT);
          return;
        }
      }
    }

    {
      ALock lock(m_History.useSync());
      for (ABase *p = m_History.useTail(); p; p = p->usePrev())
      {
        AOSContext *pContext = dynamic_cast<AOSContext *>(p);
        if (contextId == AString::fromPointer(pContext))
        {
          adminAddProperty(eBase, ASW("contextDetail",7), *pContext, AXmlElement::ENC_CDATADIRECT);
          return;
        }
      }
    }

	  //a_Context no longer available
    adminAddError(eBase, ASWNL("AOSContext no longer available"));
  }
  else
  {
    //a_Display context summary
    for (size_t i=0; i < m_Queues.size(); ++i)
    {
      AOSContextQueueInterface *pQueue = m_Queues.at(i);
      if (pQueue)
        adminAddProperty(eBase, AString::fromSize_t(i), pQueue->getClass());
      else
        adminAddProperty(eBase, AString::fromSize_t(i), AConstant::ASTRING_NULL);
    }

    adminAddPropertyWithAction(
      eBase,
      ASW("log_level",9), 
      AString::fromInt(m_DefaultEventLogLevel),
      ASW("Update",6), 
      ASWNL("Maximum event to log 0:Disabled 1:Error, 2:Event, 3:Warning, 4:Info, 5:Debug"),
      ASW("Set",3)
    );

    {
      AString str;
      str.assign('[');
      str.append(AString::fromSize_t(m_History.size()));
      str.append('/');
      str.append(AString::fromSize_t(m_HistoryMaxSize));
      str.append(']');

      AXmlElement& eHistory = eBase.addElement("object").addAttribute("name", "history");
      adminAddPropertyWithAction(eHistory, ASWNL("max_size"), str, ASW("Set",3), ASWNL("Set maximum AOSContext history size (objects not immediately deleted)"), ASW("Set",3));
    }
    
    adminAddPropertyWithAction(
      eBase,
      ASW("clear_history",13), 
      AConstant::ASTRING_EMPTY,
      ASW("Clear",5), 
      ASWNL("Clear context history: 0:all  1:history  2:error history"),
      ASW("Clear",5) 
    );
      
    {
      AString str;
      str.assign('[');
      str.append(AString::fromSize_t(m_ErrorHistory.size()));
      str.append('/');
      str.append(AString::fromSize_t(m_ErrorHistoryMaxSize));
      str.append(']');

      AXmlElement& eErrorHistory = eBase.addElement("object").addAttribute("name", "error_history");
      adminAddPropertyWithAction(eErrorHistory, ASWNL("max_size"), str, ASW("Set",3), ASWNL("Set maximum AOSContext error history size (objects not immediately deleted)"), ASW("Set",3));
    }

    {
      AString str;
      str.assign('[');
      str.append(AString::fromSize_t(m_FreeStore.size()));
      str.append('/');
      str.append(AString::fromSize_t(m_FreeStoreMaxSize));
      str.append(']');

      AXmlElement& eFreestore = eBase.addElement("object").addAttribute("name", "freestore");
      adminAddPropertyWithAction(eFreestore, ASWNL("max_size"), str, ASW("Set",3), ASWNL("Set maximum AOSContext freestore size (objects not immediately deleted)"), ASW("Set",3));
    }

    AXmlElement& eInUse = eBase.addElement("object");
    eInUse.addAttribute("name", "InUse");
    eInUse.addAttribute("size", AString::fromSize_t(m_InUse.size()));
    CONTEXT_INUSE::const_iterator citU = m_InUse.begin();
    if (citU != m_InUse.end())
    {
      ALock lock(m_InUseSync);
      while(citU != m_InUse.end())
      {
        AXmlElement& eProp = adminAddProperty(eInUse, ASW("context",7), (*citU)->useEventVisitor(), AXmlElement::ENC_CDATADIRECT);
        eProp.addAttribute(ASW("errors",6), AString::fromSize_t((*citU)->useEventVisitor().getErrorCount()));
        eProp.addElement(ASW("url",3)).addData((*citU)->useEventVisitor().useName(), AXmlElement::ENC_CDATADIRECT);
        eProp.addElement(ASW("contextId",9)).addData(AString::fromPointer(*citU), AXmlElement::ENC_CDATADIRECT);
        ++citU;
      }
    }

    {
      AXmlElement& eHistory = eBase.addElement("object").addAttribute("name", "history");
      ALock lock(m_History.useSync());
      for (ABase *p = m_History.useTail(); p; p = p->usePrev())
      {
        AOSContext *pContext = dynamic_cast<AOSContext *>(p);
        if (pContext)
        {
          AXmlElement& eProp = adminAddProperty(eHistory, ASW("context",7), pContext->useEventVisitor(), AXmlElement::ENC_CDATADIRECT);
          eProp.addAttribute(ASW("errors",6), AString::fromSize_t(pContext->useEventVisitor().getErrorCount()));
          eProp.addElement(ASW("url",3), pContext->useEventVisitor().useName(), AXmlElement::ENC_CDATADIRECT);
          eProp.addElement(ASW("contextId",3)).addData(AString::fromPointer(pContext), AXmlElement::ENC_CDATADIRECT);
        }
        else
          ATHROW(this, AException::InvalidObject);
      }
    }

    {
      AXmlElement& eErrorHistory = eBase.addElement("object").addAttribute("name", "error_history");
      ALock lock(m_ErrorHistory.useSync());
      for (ABase *p = m_ErrorHistory.useTail(); p; p = p->usePrev())
      {
        AOSContext *pContext = dynamic_cast<AOSContext *>(p);
        if (pContext)
        {
          AXmlElement& eProp = adminAddProperty(eErrorHistory, ASW("context",7), pContext->useEventVisitor(), AXmlElement::ENC_CDATADIRECT);
          eProp.addAttribute(ASW("errors",6), AString::fromSize_t(pContext->useEventVisitor().getErrorCount()));
          eProp.addElement(ASW("url",3), pContext->useEventVisitor().useName(), AXmlElement::ENC_CDATADIRECT);
          eProp.addElement(ASW("contextId",3)).addData(AString::fromPointer(pContext), AXmlElement::ENC_CDATADIRECT);
        }
        else
          ATHROW(this, AException::InvalidObject);
      }
    }
  }
}
Exemple #29
0
void AOSAdminCommand_list::_insertStylesheet(AOSAdminCommandContext& context)
{
  context.useModel().addInstruction(AXmlInstruction::XML_STYLESHEET)
    .addAttribute(ASW("type",4), ASW("text/xsl",8))
    .addAttribute(ASW("href",4), ASW("/xsl/_command/list.xsl",22));
}
Exemple #30
0
void AOSOutputExecutor::execute(AOSContext& context)
{
  AString command;
  if (
    context.useRequestParameterPairs().exists(OVERRIDE_OUTPUT)
    && m_Services.useConfiguration().isOutputOverrideAllowed()
  )
  {
    //a_Override requested and allowed
    context.useRequestParameterPairs().get(OVERRIDE_OUTPUT, command);
  }
  else
  {
    command = context.getOutputCommand();
    if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
    {
      ARope rope("Default output generator overridden to: ",40);
      rope.append(command);
      context.useEventVisitor().startEvent(rope, AEventVisitor::EL_DEBUG);
    }
  }

  if (command.equals("NOP"))
  {
    //a_If NOP was used force XML
    m_Services.useConfiguration().setMimeTypeFromExt(ASW("xml",3), context);
    if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
      context.useEventVisitor().startEvent(ASWNL("NOP detected, defaulting to XML output"), AEventVisitor::EL_DEBUG);
  }

  if (command.isEmpty())
  {
    if (!m_Services.useConfiguration().getAosDefaultOutputGenerator().isEmpty())
    {
      command.assign(m_Services.useConfiguration().getAosDefaultOutputGenerator());
      if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
      {
        ARope rope("No output generator specified, defaulting to: ",46);
        rope.append(command);
        context.useEventVisitor().startEvent(rope, AEventVisitor::EL_DEBUG);
      }
    }
    else
    {
      if (context.useEventVisitor().isLogging(AEventVisitor::EL_DEBUG))
        context.useEventVisitor().startEvent(ASW("No output generator, defaulting to XML",38), AEventVisitor::EL_DEBUG);
      return;
    }
  }

  try
  {
    //a_Find input command, if not found execute the default
    OutputGeneratorContainer::iterator it = m_OutputGenerators.find(command);
    if (it == m_OutputGenerators.end())
    {
      if (context.useEventVisitor().isLogging(AEventVisitor::EL_WARN))
      {
        ARope rope("Skipping unknown output generator: ",35);
        rope.append(command);
        context.useEventVisitor().startEvent(rope, AEventVisitor::EL_WARN);
      }
    }
    else
    {
      ATimer timer(true);

      //a_Generate output
      if (context.useEventVisitor().isLogging(AEventVisitor::EL_INFO))
      {
        ARope rope("Generating output: ",19);
        rope.append((*it).first);
        context.useEventVisitor().startEvent(rope, AEventVisitor::EL_INFO);
      }

      if (context.useContextFlags().isClear(AOSContext::CTXFLAG_IS_AJAX))
      {
        context.useModel().overwriteElement(ASW("execute/output", 14)).addData(command);

        //a_Publish timers
        context.getRequestTimer().emitXml(context.useModel().overwriteElement(ASW("request_time",12)));
        context.getContextTimer().emitXml(context.useModel().overwriteElement(ASW("context_time",12)));
      }

      //a_Generate output
      AOSContext::ReturnCode ret = (*it).second->execute(context);
      switch (ret)
      {
        case AOSContext::RETURN_OK:
        break;

        case AOSContext::RETURN_REDIRECT:
          if (context.useEventVisitor().isLogging(AEventVisitor::EL_INFO))
          {
            context.useEventVisitor().startEvent(ASWNL("Output generator has done a redirect"), AEventVisitor::EL_DEBUG);
          }
        break;
      
        default:
          context.addError((*it).second->getClass(), ASWNL("Output generator returned neither OK nor REDIRECT"));
        return;
      }

      //a_Event over
      context.useEventVisitor().endEvent();

      //a_Add execution time
      (*it).second->addExecutionTimeSample(timer.getInterval());
    }
  }
  catch(AException& ex)
  {
    AString strWhere("AOSOutputExecutor::execute(", 27);
    strWhere.append(command);
    strWhere.append(')');
    context.addError(strWhere, ex.what());

    AXmlElement& element = context.useModel().addElement("output_error");
    element.addElement("where", strWhere);
    element.addElement("exception", ex);
  }
  catch(...)
  {
    AString strWhere("AOSOutputExecutor::execute(", 27);
    strWhere.append(command);
    strWhere.append(')');
    context.addError(strWhere, ASWNL("Unknown Exception"));

    context.useModel().addElement("output_error").addData("Unknown Exception");
  }
}