예제 #1
0
void DistributionTables::build(const std::string& BasePath,
                               const std::string& SourcesFileName, const std::string& DistributionFileName)
{
  SourcesTable.clear();
  UnitsTable.clear();


  // Sources file

  QDomDocument Doc;
  QDomElement Root;

  std::string SourcesFilePath = BasePath+"/"+SourcesFileName;


  QFile File(QString(SourcesFilePath.c_str()));
  if (!File.open(QIODevice::ReadOnly))
  {
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
        "Error opening " + SourcesFilePath);
  }

  bool Parsed = Doc.setContent(&File);
  File.close();


  if (Parsed)
  {
    Root = Doc.documentElement();

    if (!Root.isNull())
    {
      if (Root.tagName() == QString("openfluid"))
      {
        for(QDomElement CurrNode = Root.firstChildElement(); !CurrNode.isNull();
            CurrNode = CurrNode.nextSiblingElement())
        {
          if (CurrNode.tagName() == QString("datasources"))
          {
            for(QDomElement CurrNode2 = CurrNode.firstChildElement(); !CurrNode2.isNull();
                CurrNode2 = CurrNode2.nextSiblingElement())
            {
              if (CurrNode2.tagName() == QString("filesource"))
              {
                QString xmlID = CurrNode2.attributeNode(QString("ID")).value();
                QString xmlFile = CurrNode2.attributeNode(QString("file")).value();

                if (!xmlID.isNull() && !xmlFile.isNull())
                {
                  SourcesTable[xmlID.toStdString()] = BasePath + "/" + xmlFile.toStdString();
                }
              }
            }
          }
        }
      }
      else
        throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                  "Cannot find <openfluid> tag in sources file " +
                                                  SourcesFilePath);
    }
    else
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"Wrong formatted sources file " +
                                                SourcesFilePath);
  }
  else
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"Cannot open sources file " +
                                              SourcesFilePath);


  // Units distribution file

  long UnitID;
  std::string DataSrcID;

  ColumnTextParser DistriFileParser("%");

  std::string DistributionFilePath = BasePath+"/"+DistributionFileName;

  if (openfluid::tools::Filesystem::isFile(DistributionFilePath))
  {
    if (DistriFileParser.loadFromFile(DistributionFilePath) &&
        DistriFileParser.getColsCount() == 2 &&
        DistriFileParser.getLinesCount() >0)
    {
      for (unsigned int i=0;i<DistriFileParser.getLinesCount();i++)
      {
        if (DistriFileParser.getLongValue(i,0,&UnitID) && DistriFileParser.getStringValue(i,1,&DataSrcID))
        {
          if (SourcesTable.find(DataSrcID) != SourcesTable.end())
            UnitsTable[UnitID] = DataSrcID;
          else
            throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                      "Error in distribution file " + DistributionFilePath +
                                                      ", data source ID not found");
        }
        else
          throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                    "Error in distribution file " + DistributionFilePath +
                                                    ", format error");
      }
    }
    else
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                "Error in distribution file " + DistributionFilePath +
                                                ", file not found or format error");
  }
  else
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                              "Distribution file " + DistributionFilePath + " not found");

}
예제 #2
0
bool TrussResultsManager::parseExecutionResults ( 
                                              Plugin::ExecutionResult exRes,
                                              QString& errMsg )
{
    QDomDocument doc;

    if ( exRes.status == Plugin::InternalErrStatus ) {
        errMsg = exRes.data;
        return false;       
    }

    if ( ! doc.setContent( exRes.data ) ) {
        errMsg = QString( tr("Wrong XML format of the results") );
        return false;
    }

    QDomElement pluginResElem = doc.documentElement();
    if ( pluginResElem.isNull() ) {
        errMsg = QString( tr("Wrong XML format of the results") );
        return false;
    }

    if ( ! pluginResElem.hasAttribute( "trussUUID" ) ) {
        errMsg = QString( tr("Wrong XML format of the results: truss UUID wasn't set") );
        return false;
    }
    
    QString trussID = pluginResElem.attribute( "trussUUID" );

    WindowList windows = windowMng.getTrussUnitWindowList();
    bool found = false;
    TrussUnitWindow* w = 0;
    foreach ( w, windows )
        if ( w->getUUID() == trussID ) {
            found = true;
            break;
        }

    if ( ! found ) {
        errMsg = QString( tr("Truss with the given UUID wasn't found") );
        return false;
    }

    // Create new solution results
    TrussSolutionResults* newTrussResults = &createSolutionResults();
    PluginResults& pluginRes = newTrussResults->createPluginResults();

    // Reading results XML
    try { pluginRes.loadAttributesFromXML( pluginResElem, false ); }
    catch ( ... ) {
        // Remove if there was error while reading XML
        removeSolutionResults( *newTrussResults );
        
        errMsg = QString( tr("Error while reading XML of the results") );
        return false;
    }

    // Remove old results
    TrussSolutionResults* trussResults = getResultsForTrussUnit( trussID );
    if ( trussResults )
        removeSolutionResults( *trussResults );

    newTrussResults->setTrussUnit( trussID );
    w->setCalculatedStatus( true );
    
    return true;
}
예제 #3
0
QgsVectorLayer* QgsRemoteOWSBuilder::sosLayer( const QDomElement& remoteOWSElem, const QString& url, const QString& layerName, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  //url for sos provider is: "url=... method=... xml=....
  QString method = remoteOWSElem.attribute( "method", "POST" ); //possible GET/POST/SOAP

  //search for <LayerSensorObservationConstraints> node that is sibling of remoteOSW element
  //parent element of <remoteOWS> (normally <UserLayer>)
  QDomElement parentElem = remoteOWSElem.parentNode().toElement();
  if ( parentElem.isNull() )
  {
    return 0;
  }


  //Root element of the request (can be 'GetObservation' or 'GetObservationById' at the moment, probably also 'GetFeatureOfInterest' or 'GetFeatureOfInterestTime' in the future)
  QDomElement requestRootElem;

  QDomNodeList getObservationNodeList = parentElem.elementsByTagName( "GetObservation" );
  if ( getObservationNodeList.size() > 0 )
  {
    requestRootElem = getObservationNodeList.at( 0 ).toElement();
  }
  else //GetObservationById?
  {
    QDomNodeList getObservationByIdNodeList = parentElem.elementsByTagName( "GetObservationById" );
    if ( getObservationByIdNodeList.size() > 0 )
    {
      requestRootElem = getObservationByIdNodeList.at( 0 ).toElement();
    }
  }

  if ( requestRootElem.isNull() )
  {
    return 0;
  }

  QDomDocument requestDoc;
  QDomNode newDocRoot = requestDoc.importNode( requestRootElem, true );
  requestDoc.appendChild( newDocRoot );

  QString providerUrl = "url=" + url + " method=" + method + " xml=" + requestDoc.toString();

  //check if layer is already in cache
  QgsVectorLayer* sosLayer = 0;
  if ( allowCaching )
  {
    sosLayer = dynamic_cast<QgsVectorLayer*>( QgsMSLayerCache::instance()->searchLayer( providerUrl, layerName ) );
    if ( sosLayer )
    {
      return sosLayer;
    }
  }

  sosLayer = new QgsVectorLayer( providerUrl, "Sensor layer", "SOS" );

  if ( !sosLayer->isValid() )
  {
    delete sosLayer;
    return 0;
  }
  else
  {
    if ( allowCaching )
    {
      QgsMSLayerCache::instance()->insertLayer( providerUrl, layerName, sosLayer );
    }
    else
    {
      layersToRemove.push_back( sosLayer );
    }
  }
  return sosLayer;
}
예제 #4
0
bool UPNPSubscription::ProcessRequest(HttpWorkerThread *pThread,
                                      HTTPRequest *pRequest)
{
    (void)pThread;
    if (!pRequest)
        return false;

    if (pRequest->m_sBaseUrl != "/Subscriptions")
        return false;
    if (pRequest->m_sMethod != "event")
        return false;

    LOG(VB_UPNP, LOG_DEBUG, QString("%1\n%2")
        .arg(pRequest->m_sRawRequest).arg(pRequest->m_sPayload));

    if (pRequest->m_sPayload.isEmpty())
        return true;

    pRequest->m_eResponseType = ResponseTypeHTML;

    QString nt  = pRequest->m_mapHeaders["nt"];
    QString nts = pRequest->m_mapHeaders["nts"];
    bool    no  = pRequest->m_sRawRequest.startsWith("NOTIFY");

    if (nt.isEmpty() || nts.isEmpty() || !no)
    {
        pRequest->m_nResponseStatus = 400;
        return true;
    }

    pRequest->m_nResponseStatus = 412;
    if (nt != "upnp:event" || nts != "upnp:propchange")
        return true;

    QString usn = pRequest->m_mapParams["usn"];
    QString sid = pRequest->m_mapHeaders["sid"];
    if (usn.isEmpty() || sid.isEmpty())
        return true;

    // N.B. Validating the usn and uuid here might mean blocking for some time
    // while waiting for a subscription to complete. While this operates in a
    // worker thread, worker threads are a limited resource which we could
    // rapidly overload if a number of events arrive. Instead let the
    // subscribing objects validate the usn - the uuid should be superfluous.

    QString seq = pRequest->m_mapHeaders["seq"];

    // mediatomb sends some extra character(s) at the end of the payload
    // which throw Qt, so try and trim them off
    int loc = pRequest->m_sPayload.lastIndexOf("propertyset>");
    QString payload = (loc > -1) ? pRequest->m_sPayload.left(loc + 12) :
                                   pRequest->m_sPayload;

    LOG(VB_UPNP, LOG_DEBUG, QString("Payload:\n%1").arg(payload));

    pRequest->m_nResponseStatus = 400;
    QDomDocument body;
    QString error;
    int errorCol = 0;
    int errorLine = 0;
    if (!body.setContent(payload, true, &error, &errorLine, &errorCol))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Failed to parse event: Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorCol).arg(error));
        return true;
    }

    VERBOSE(VB_UPNP|VB_EXTRA, "/n/n" + body.toString(4) + "/n/n");

    QDomNodeList properties = body.elementsByTagName("property");
    QHash<QString,QString> results;

    // this deals with both one argument per property (compliant) and mutliple
    // arguments per property as sent by mediatomb
    for (int i = 0; i < properties.size(); i++)
    {
        QDomNodeList arguments = properties.at(i).childNodes();
        for (int j = 0; j < arguments.size(); j++)
        {
            QDomElement e = arguments.at(j).toElement();
            if (!e.isNull() && !e.text().isEmpty() && !e.tagName().isEmpty())
                results.insert(e.tagName(), e.text());
        }
    }

    // using MythObservable allows multiple objects to subscribe to the same
    // service but is less efficient from an eventing perspective, especially
    // if multiple objects are subscribing
    if (!results.isEmpty())
    {
        pRequest->m_nResponseStatus = 200;
        results.insert("usn", usn);
        results.insert("seq", seq);
        MythInfoMapEvent me("UPNP_EVENT", results);
        dispatch(me);
    }

    return true;
}
예제 #5
0
/// \cond
void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    const QString type = element.attribute("type");
    for (int i = Error; i <= Probe; i++) {
        if (type == presence_types[i]) {
            d->type = static_cast<Type>(i);
            break;
        }
    }
    const QString show = element.firstChildElement("show").text();
    for (int i = Online; i <= Invisible; i++) {
        if (show == presence_shows[i]) {
            d->availableStatusType = static_cast<AvailableStatusType>(i);
            break;
        }
    }
    d->statusText = element.firstChildElement("status").text();
    d->priority = element.firstChildElement("priority").text().toInt();

    QXmppElementList extensions;
    QDomElement xElement = element.firstChildElement();
    d->vCardUpdateType = VCardUpdateNone;
    while(!xElement.isNull())
    {
        // XEP-0045: Multi-User Chat
        if(xElement.namespaceURI() == ns_muc) {
            d->mucSupported = true;
            d->mucPassword = xElement.firstChildElement("password").text();
        }
        else if(xElement.namespaceURI() == ns_muc_user)
        {
            QDomElement itemElement = xElement.firstChildElement("item");
            d->mucItem.parse(itemElement);
            QDomElement statusElement = xElement.firstChildElement("status");
            d->mucStatusCodes.clear();
            while (!statusElement.isNull()) {
                d->mucStatusCodes << statusElement.attribute("code").toInt();
                statusElement = statusElement.nextSiblingElement("status");
            }
        }
        // XEP-0153: vCard-Based Avatars
        else if(xElement.namespaceURI() == ns_vcard_update)
        {
            QDomElement photoElement = xElement.firstChildElement("photo");
            if(!photoElement.isNull())
            {
                d->photoHash = QByteArray::fromHex(photoElement.text().toLatin1());
                if(d->photoHash.isEmpty())
                    d->vCardUpdateType = VCardUpdateNoPhoto;
                else
                    d->vCardUpdateType = VCardUpdateValidPhoto;
            }
            else
            {
                d->photoHash = QByteArray();
                d->vCardUpdateType = VCardUpdateNotReady;
            }
        }
        // XEP-0115: Entity Capabilities
        else if(xElement.tagName() == "c" && xElement.namespaceURI() == ns_capabilities)
        {
            d->capabilityNode = xElement.attribute("node");
            d->capabilityVer = QByteArray::fromBase64(xElement.attribute("ver").toLatin1());
            d->capabilityHash = xElement.attribute("hash");
            d->capabilityExt = xElement.attribute("ext").split(" ", QString::SkipEmptyParts);
        }
        else if (xElement.tagName() == "addresses")
        {
        }
        else if (xElement.tagName() == "error")
        {
        }
        else if (xElement.tagName() == "show")
        {
        }
        else if (xElement.tagName() == "status")
        {
        }
        else if (xElement.tagName() == "priority")
        {
        }
        else
        {
            // other extensions
            extensions << QXmppElement(xElement);
        }
        xElement = xElement.nextSiblingElement();
    }
    setExtensions(extensions);
}