Example #1
0
void
Link::SetPort(const nsAString &aPort)
{
  nsCOMPtr<nsIURI> uri(GetURIToMutate());
  if (!uri) {
    // Ignore failures to be compatible with NS4.
    return;
  }

  nsresult rv;
  nsAutoString portStr(aPort);

  // nsIURI uses -1 as default value.
  int32_t port = -1;
  if (!aPort.IsEmpty()) {
    port = portStr.ToInteger(&rv);
    if (NS_FAILED(rv)) {
      return;
    }
  }

  (void)uri->SetPort(port);
  SetHrefAttribute(uri);
}
void HttpClient::HttpSendPerformanceData()
{
	string url = "http://192.168.1.200:8000/postNodeStatus.php";

	Poco::URI uri(url);

	string path = uri.getPath();

	HTTPClientSession session(uri.getHost(), uri.getPort());
	session.setKeepAlive(true);

	HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
	req.setContentType("application/x-www-form-urlencoded");
	req.setKeepAlive(true);
	
	GenerateJsonData *json = new GenerateJsonData();
	Json::Value performance = json->GetPerformanceData();

	string databody = performance.toStyledString();
	string data = "data=" + databody;
	
	req.setContentLength(data.length());
	
	//ostream &myOstream = session.sendRequest(req);
	
	//myOstream <<data;

	/*HTTPResponse  rep(HTTPResponse::HTTPStatus::HTTP_OK);
	
	istream &myIstream = session.receiveResponse(rep);

	cout<<myIstream.rdbuf() << endl;
	*/

	cout << "send ok" << endl;
}
void ParserXmlVasttrafikSe::findStationsByName(const QString &stationName)
{
    qDebug() << "ParserXmlVasttrafikSe::findStationsByName(stationName" << stationName << ")";

    if (currentRequestState != FahrplanNS::noneRequest)
        return;
    currentRequestState = FahrplanNS::stationsByNameRequest;

    QUrl uri(baseRestUrl + QLatin1String("location.name"));
#if defined(BUILD_FOR_QT5)
    QUrlQuery query;
#else
    QUrl query;
#endif
    query.addQueryItem("authKey", apiKey);
    query.addQueryItem("format", "xml");
    query.addQueryItem("input", stationName);
#if defined(BUILD_FOR_QT5)
    uri.setQuery(query);
#else
    uri.setQueryItems(query.queryItems());
#endif
    sendHttpRequest(uri);
}
Example #4
0
void HTTPPostTest::testConvertTo()
{
    const auto srcPath = Util::getTempFilePath(TDOC, "hello.odt");

    Poco::URI uri("https://127.0.0.1:" + std::to_string(ClientPortNumber));
    Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort());

    Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/convert-to");
    Poco::Net::HTMLForm form;
    form.setEncoding(Poco::Net::HTMLForm::ENCODING_MULTIPART);
    form.set("format", "txt");
    form.addPart("data", new Poco::Net::FilePartSource(srcPath));
    form.prepareSubmit(request);
    // If this results in a Poco::Net::ConnectionRefusedException, loolwsd is not running.
    form.write(session.sendRequest(request));

    Poco::Net::HTTPResponse response;
    std::stringstream actualStream;
    // receiveResponse() resulted in a Poco::Net::NoMessageException.
    std::istream& responseStream = session.receiveResponse(response);
    Poco::StreamCopier::copyStream(responseStream, actualStream);

    std::ifstream fileStream(TDOC "/hello.txt");
    std::stringstream expectedStream;
    expectedStream << fileStream.rdbuf();

    // Remove the temp files.
    Util::removeFile(srcPath);

    // In some cases the result is prefixed with (the UTF-8 encoding of) the Unicode BOM
    // (U+FEFF). Skip that.
    std::string actualString = actualStream.str();
    if (actualString.size() > 3 && actualString[0] == '\xEF' && actualString[1] == '\xBB' && actualString[2] == '\xBF')
        actualString = actualString.substr(3);
    CPPUNIT_ASSERT_EQUAL(expectedStream.str(), actualString);
}
void
FTPChannelChild::DoOnStartRequest(const PRInt32& aContentLength,
                                  const nsCString& aContentType,
                                  const PRTime& aLastModified,
                                  const nsCString& aEntityID,
                                  const IPC::URI& aURI)
{
  LOG(("FTPChannelChild::RecvOnStartRequest [this=%x]\n", this));

  SetContentLength(aContentLength);
  SetContentType(aContentType);
  mLastModifiedTime = aLastModified;
  mEntityID = aEntityID;

  nsCString spec;
  nsCOMPtr<nsIURI> uri(aURI);
  uri->GetSpec(spec);
  nsBaseChannel::URI()->SetSpec(spec);

  AutoEventEnqueuer ensureSerialDispatch(mEventQ);
  nsresult rv = mListener->OnStartRequest(this, mListenerContext);
  if (NS_FAILED(rv))
    Cancel(rv);
}
Example #6
0
  URI
  XorgFunction::getURI(bool expanded) const {
    URI uri(baseuri) ;
    int i = 0 ;
    std::stringstream q ;
    if (expanded || ctrl_num!=XORG_DEFAULT_CTRL_NUM) 
      q << (i++?"&":"") << "num=" << ctrl_num ;
    if (expanded || ctrl_den!=XORG_DEFAULT_CTRL_DEN) 
      q << (i++?"&":"") << "den=" << ctrl_den ;
    if (expanded || ctrl_threshold!=XORG_DEFAULT_CTRL_THR) 
      q << (i++?"&":"") << "thr=" << ctrl_threshold ;
    if (scheme==PtrAccelPredictable) {
      if (expanded || corr_mul!=XORG_DEFAULT_PRED_CM) 
	q << (i++?"&":"") << "cm=" << corr_mul ;
      if (expanded || const_acceleration!=XORG_DEFAULT_PRED_CA) 
	q << (i++?"&":"") << "ca=" << const_acceleration ;
      if (expanded || min_acceleration!=XORG_DEFAULT_PRED_MA) 
	q << (i++?"&":"") << "ma=" << min_acceleration ;
    }
    if (expanded || normalize)
      q << (i++?"&":"") << "normalize=" << normalize ;
    uri.query = q.str() ;
    return uri ;
  }
Example #7
0
QVector<QgsDataItem*> QgsSLConnectionItem::createChildren()
{
  QgsDebugMsg( "Entered" );
  QVector<QgsDataItem*> children;
  QgsSpatiaLiteConnection connection( mName );

  QgsSpatiaLiteConnection::Error err = connection.fetchTables( false ); // TODO: allow geometryless tables
  if ( err != QgsSpatiaLiteConnection::NoError )
  {
    QString msg;
    switch ( err )
    {
      case QgsSpatiaLiteConnection::NotExists: msg = tr( "Database does not exist" ); break;
      case QgsSpatiaLiteConnection::FailedToOpen: msg = tr( "Failed to open database" ); break;
      case QgsSpatiaLiteConnection::FailedToCheckMetadata: msg = tr( "Failed to check metadata" ); break;
      case QgsSpatiaLiteConnection::FailedToGetTables: msg = tr( "Failed to get list of tables" ); break;
      default: msg = tr( "Unknown error" ); break;
    }
    QString msgDetails = connection.errorMessage();
    if ( !msgDetails.isEmpty() )
      msg = QString( "%1 (%2)" ).arg( msg ).arg( msgDetails );
    children.append( new QgsErrorItem( this, msg, mPath + "/error" ) );
    return children;
  }

  QString connectionInfo = QString( "dbname='%1'" ).arg( QString( connection.path() ).replace( "'", "\\'" ) );
  QgsDataSourceURI uri( connectionInfo );

  foreach ( const QgsSpatiaLiteConnection::TableEntry& entry, connection.tables() )
  {
    uri.setDataSource( QString(), entry.tableName, entry.column, QString(), QString() );
    QgsSLLayerItem * layer = new QgsSLLayerItem( this, entry.tableName, mPath + "/" + entry.tableName, uri.uri(), _layerTypeFromDb( entry.type ) );
    children.append( layer );
  }
  return children;
}
Example #8
0
nsresult
nsImapURI2FullName(const char* rootURI, const char* hostName, const char* uriStr,
                   char **name)
{
    nsCAutoString uri(uriStr);
    nsCAutoString fullName;
    if (uri.Find(rootURI) != 0)
      return NS_ERROR_FAILURE;
    fullName = Substring(uri, strlen(rootURI));
    uri = fullName;
    PRInt32 hostStart = uri.Find(hostName);
    if (hostStart <= 0) 
      return NS_ERROR_FAILURE;
    fullName = Substring(uri, hostStart);
    uri = fullName;
    PRInt32 hostEnd = uri.FindChar('/');
    if (hostEnd <= 0) 
      return NS_ERROR_FAILURE;
    fullName = Substring(uri, hostEnd + 1);
    if (fullName.IsEmpty())
      return NS_ERROR_FAILURE;
    *name = ToNewCString(fullName);
    return NS_OK;
}
Example #9
0
bool Node::handle<UNOBSERVE>(VPackSlice const& slice) {
  if (!slice.hasKey("url")) return false;
  if (!slice.get("url").isString()) return false;
  std::string url(slice.get("url").copyString()), uri(this->uri());

  // delete in both cases a single entry (ensured above)
  // breaking the iterators is fine then
  auto ret = store().observerTable().equal_range(url);
  for (auto it = ret.first; it != ret.second; ++it) {
    if (it->second == uri) {
      store().observerTable().erase(it);
      break;
    }
  }
  ret = store().observedTable().equal_range(uri);
  for (auto it = ret.first; it != ret.second; ++it) {
    if (it->second == url) {
      store().observedTable().erase(it);
      return true;
    }
  }

  return false;
}
Example #10
0
string IRI::IRIString() const
{
    if ( !_pureIRI.empty() )
        return _pureIRI;
    
    // we'll have to reverse-engineer it, grr
    string uri(URIString());
    std::string plainHost(_url->host());
    
    url_canon::RawCanonOutputW<256> idnDecoded;
    const string16 idnSrc = string(plainHost).utf16string();
    if ( url_canon::IDNToUnicode(idnSrc.c_str(), static_cast<int>(idnSrc.size()), &idnDecoded) && idnSrc != idnDecoded.data() )
    {
        // swap out the IDN-encoded hostname
        string::size_type pos = uri.find(plainHost);
        if ( pos != string::npos )
        {
            uri.replace(pos, plainHost.size(), idnDecoded.data());
        }
    }
    
    // have to leave it all url-encoded, sadly...
    return uri;
}
nsresult
nsMsgAttachmentHandler::SnarfMsgAttachment(nsMsgCompFields *compFields)
{
  nsresult rv = NS_ERROR_INVALID_ARG;
  nsCOMPtr <nsIMsgMessageService> messageService;

  if (m_uri.Find("-message:", CaseInsensitiveCompare) != -1)
  {
    nsCOMPtr <nsIFile> tmpFile;
    rv = nsMsgCreateTempFile("nsmail.tmp", getter_AddRefs(tmpFile));
    NS_ENSURE_SUCCESS(rv, rv);
    mTmpFile = do_QueryInterface(tmpFile);
    mDeleteFile = true;
    mCompFields = compFields;
    m_type = MESSAGE_RFC822;
    m_overrideType = MESSAGE_RFC822;
    if (!mTmpFile)
    {
      rv = NS_ERROR_FAILURE;
      goto done;
    }

    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mOutFile), mTmpFile, -1, 00600);
    if (NS_FAILED(rv) || !mOutFile)
    {
      if (m_mime_delivery_state)
      {
        nsCOMPtr<nsIMsgSendReport> sendReport;
        m_mime_delivery_state->GetSendReport(getter_AddRefs(sendReport));
        if (sendReport)
        {
          nsAutoString error_msg;
          nsMsgBuildMessageWithTmpFile(mTmpFile, error_msg);
          sendReport->SetMessage(nsIMsgSendReport::process_Current, error_msg.get(), false);
        }
      }
      rv =  NS_MSG_UNABLE_TO_OPEN_TMP_FILE;
      goto done;
    }

    nsCOMPtr<nsIURLFetcher> fetcher = do_CreateInstance(NS_URLFETCHER_CONTRACTID, &rv);
    if (NS_FAILED(rv) || !fetcher)
    {
      if (NS_SUCCEEDED(rv))
        rv =  NS_ERROR_UNEXPECTED;
      goto done;
    }

    rv = fetcher->Initialize(mTmpFile, mOutFile, FetcherURLDoneCallback, this);
    rv = GetMessageServiceFromURI(m_uri, getter_AddRefs(messageService));
    if (NS_SUCCEEDED(rv) && messageService)
    {
      nsCAutoString uri(m_uri);
      uri += (uri.FindChar('?') == kNotFound) ? '?' : '&';
      uri.Append("fetchCompleteMessage=true");
      nsCOMPtr<nsIStreamListener> strListener;
      fetcher->QueryInterface(NS_GET_IID(nsIStreamListener), getter_AddRefs(strListener));

      // initialize a new stream converter, that uses the strListener as its input
      // obtain the input stream listener from the new converter,
      // and pass the converter's input stream listener to DisplayMessage

      m_mime_parser = do_CreateInstance(NS_MAILNEWS_MIME_STREAM_CONVERTER_CONTRACTID, &rv);
      if (NS_FAILED(rv))
        goto done;

      // Set us as the output stream for HTML data from libmime...
      nsCOMPtr<nsIMimeStreamConverter> mimeConverter = do_QueryInterface(m_mime_parser);
      if (mimeConverter)
      {
        mimeConverter->SetMimeOutputType(nsMimeOutput::nsMimeMessageDecrypt);
        mimeConverter->SetForwardInline(false);
        mimeConverter->SetIdentity(nsnull);
        mimeConverter->SetOriginalMsgURI(nsnull);
      }

      nsCOMPtr<nsIStreamListener> convertedListener = do_QueryInterface(m_mime_parser, &rv);
      if (NS_FAILED(rv))
        goto done;

      nsCOMPtr<nsIURI> aURL;
      rv = messageService->GetUrlForUri(uri.get(), getter_AddRefs(aURL), nsnull);
      if (aURL)
        aURL->SetSpec(nsDependentCString(uri.get()));

      rv = NS_NewInputStreamChannel(getter_AddRefs(m_converter_channel), aURL, nsnull);
      if (NS_FAILED(rv))
        goto done;

      rv = m_mime_parser->AsyncConvertData(
		    "message/rfc822",
		    "message/rfc822",
		    strListener, m_converter_channel);
      if (NS_FAILED(rv))
        goto done;

      rv = messageService->DisplayMessage(uri.get(), convertedListener, nsnull, nsnull, nsnull, nsnull);
    }
  }
done:
  if (NS_FAILED(rv))
  {
      if (mOutFile)
      {
        mOutFile->Close();
        mOutFile = nsnull;
      }

      if (mTmpFile)
      {
        mTmpFile->Remove(false);
        mTmpFile = nsnull;
      }
  }

  return rv;
}
    TEST_FIXTURE(container_test_base, container_list_blobs)
    {
        m_container.create(azure::storage::blob_container_public_access_type::off, azure::storage::blob_request_options(), m_context);
        check_container_no_stale_property(m_container);
        std::map<utility::string_t, azure::storage::cloud_blob> blobs;

        for (int i = 0; i < 4; i++)
        {
            auto index = utility::conversions::print_string(i);
            auto blob = m_container.get_block_blob_reference(_XPLATSTR("blockblob") + index);
            blob.metadata()[_XPLATSTR("index")] = index;
            
            std::vector<uint8_t> buffer;
            buffer.resize(i * 16 * 1024);
            auto stream = concurrency::streams::container_stream<std::vector<uint8_t>>::open_istream(buffer);
            blob.upload_from_stream(stream, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context);
            blobs[blob.name()] = blob;
        }

        for (int i = 0; i < 3; i++)
        {
            auto index = utility::conversions::print_string(i);
            auto blob = m_container.get_page_blob_reference(_XPLATSTR("pageblob") + index);
            blob.metadata()[_XPLATSTR("index")] = index;
            
            blob.create(i * 512, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context);
            check_container_no_stale_property(m_container);
            blobs[blob.name()] = blob;
        }

        for (int i = 0; i < 3; i++)
        {
            auto index = utility::conversions::print_string(i);
            auto blob = m_container.get_append_blob_reference(_XPLATSTR("appendblob") + index);
            blob.metadata()[_XPLATSTR("index")] = index;

            blob.create_or_replace(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context);
            check_container_no_stale_property(m_container);

            std::vector<uint8_t> buffer;
            buffer.resize((i + 1) * 8 * 1024);
            fill_buffer_and_get_md5(buffer);
            auto stream = concurrency::streams::container_stream<std::vector<uint8_t>>::open_istream(buffer);
            blob.append_block(stream, utility::string_t(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context);
            blobs[blob.name()] = blob;
        }

        auto listing1 = list_all_blobs(utility::string_t(), azure::storage::blob_listing_details::all, 0, azure::storage::blob_request_options());
        for (auto iter = listing1.begin(); iter != listing1.end(); ++iter)
        {
            auto blob = blobs.find(iter->name());
            CHECK(blob != blobs.end());

            CHECK_UTF8_EQUAL(blob->second.uri().primary_uri().to_string(), iter->uri().primary_uri().to_string());
            CHECK_UTF8_EQUAL(blob->second.uri().secondary_uri().to_string(), iter->uri().secondary_uri().to_string());

            auto index_str = blob->second.metadata().find(_XPLATSTR("index"));
            CHECK(index_str != blob->second.metadata().end());
            auto index = utility::conversions::scan_string<int>(index_str->second);

            switch (iter->type())
            {
            case azure::storage::blob_type::block_blob:
                CHECK_EQUAL(index * 16 * 1024, iter->properties().size());
                break;

            case azure::storage::blob_type::page_blob:
                CHECK_EQUAL(index * 512, iter->properties().size());
                break;

            case azure::storage::blob_type::append_blob:
                CHECK_EQUAL((index + 1) * 8 * 1024, iter->properties().size());
                break;

            default:
                CHECK(false);
                break;
            }

            blobs.erase(blob);
        }

        CHECK_EQUAL(0U, blobs.size());

        auto listing2 = list_all_blobs(_XPLATSTR("block"), azure::storage::blob_listing_details::none, 10, azure::storage::blob_request_options());
        CHECK_EQUAL(4U, listing2.size());
        for (auto iter = listing2.begin(); iter != listing2.end(); ++iter)
        {
            CHECK(iter->metadata().empty());
        }
    }
Example #13
0
uri faad_decoder::get_uri() const
{
    return (source_) ? source_->get_uri() : uri();
}
// main constructor for http_request_line
http_request_line::http_request_line(const char *inrequest,
	std::map<std::string,std::string>& headers)
{
    // we expect the line to have any trailing \r or \n removed
    const char *ctr=inrequest,*savectr;
    int util;
    valid=false;

    while(*ctr!=' '&&*ctr) ctr++;
    if(*ctr=='\0'){
	// no request method or anything else
	return;
    }
    method=std::string(inrequest,ctr);
    if(!isvalidmethod()){
	return;
    }
    while(*ctr==' '&&*ctr) ctr++;
    if(*ctr=='\0'){
	// no uri
	return;
    }
    // pointing at beginning of uri
    savectr=ctr;
    while(*ctr!=' '&&*ctr) ctr++;
    if(*ctr=='\0'){
	// nothing past the request so it looks like a 0.9 request
	major_release=0;
	minor_release=9;
	// here's the problem
	theuri=uri(savectr,headers["Host"]);
	valid=true;
	return;
    }
    theuri=uri(std::string(savectr,ctr),headers["Host"]);
    // either pointing at HTTP/1.x or space
    while(*ctr==' '&&*ctr) ctr++;
    if(*ctr=='\0'){
	// once again it was a 0.9 but with trailing space
	major_release=0;
	minor_release=9;
	valid=true;
	return;
    }
    // now we should be pointing at HTTP/1.x
    savectr=ctr;
    if(strncmp("HTTP/",ctr,5)!=0){
	return;
    }
    ctr+=5;
    // now pointing at the major part of the release
    if(*ctr>='0' && *ctr<='9'){
	util=0;
	while(*ctr>='0' && *ctr<='9'){
	    util=10*util+*ctr-'0';
	    ctr++;
	}
    }else{
	// no major version so return invalid
	return;
    }
    if(*ctr!='.'){
	return;
    }
    major_release=util;
    ctr++;
    if(*ctr>='0' && *ctr<='9'){
	util=0;
	while(*ctr>='0' && *ctr<='9'){
	    util=10*util+*ctr-'0';
	    ctr++;
	}
    }else{
	// no minor version so return invalid
	return;
    }
    minor_release=util;
    valid=true;
    return;
}
Example #15
0
int main( int argc, char* argv[]){
    if ( argc != 4 ){
        std::cerr << "usage: " << argv[0] << " <ldap-uri> <cacertfile> <cacertdir>" << std::endl;
        return(-1);
    }
    std::string uri(argv[1]);
    std::string cacert(argv[2]);
    std::string cadir(argv[3]);
    TlsOptions tls;
    std::cout << "Current global settings:" << std::endl;
    std::cout << "    CaCertfile: " << tls.getStringOption( TlsOptions::CACERTFILE) << std::endl;
    std::cout << "    CaCertDir: " << tls.getStringOption( TlsOptions::CACERTDIR ) << std::endl;
    std::cout << "    Require Cert: " << tls.getIntOption( TlsOptions::REQUIRE_CERT ) << std::endl;
    std::cout << "Applying new settings:" << std::endl;
    tls.setOption( TlsOptions::CACERTFILE, cacert );
    tls.setOption( TlsOptions::REQUIRE_CERT, TlsOptions::DEMAND );
    std::cout << "    CaCertfile: " << tls.getStringOption( TlsOptions::CACERTFILE ) << std::endl;
    std::cout << "    Require Cert: " << tls.getIntOption( TlsOptions::REQUIRE_CERT ) << std::endl;
    
    try {
        // 1. connect using global options
        LDAPAsynConnection l(uri);
        try {
            l.start_tls();
            std::cout << "StartTLS successful." << std::endl;
            l.unbind();
        } catch ( LDAPException e ) {
            std::cerr << e << std::endl;
        }

        // 2. connect using connection specific option
        l = LDAPAsynConnection(uri);
        tls=l.getTlsOptions();
        std::cout << "Current connection specific settings:" << std::endl;
        std::cout << "    CaCertfile: " << tls.getStringOption( TlsOptions::CACERTFILE) << std::endl;
        std::cout << "    CaCertDir: " << tls.getStringOption( TlsOptions::CACERTDIR ) << std::endl;
        std::cout << "    Require Cert: " << tls.getIntOption( TlsOptions::REQUIRE_CERT ) << std::endl;
        std::cout << "Applying new settings:" << std::endl;
        tls.setOption( TlsOptions::CACERTDIR, cadir );
        tls.setOption( TlsOptions::REQUIRE_CERT, TlsOptions::DEMAND );
        std::cout << "    CaCertDir: " << tls.getStringOption( TlsOptions::CACERTDIR ) << std::endl;
        std::cout << "    Require Cert: " << tls.getIntOption( TlsOptions::REQUIRE_CERT ) << std::endl;
        try {
            l.start_tls();
            std::cout << "StartTLS successful." << std::endl;
            l.unbind();
        } catch ( LDAPException e ) {
            std::cerr << e << std::endl;
        }
        
        // 3. and once again using the globals
        try {
            LDAPAsynConnection l2(uri);
            TlsOptions tls2;
            std::cout << "Current global settings:" << std::endl;
            std::cout << "    CaCertfile: " << tls2.getStringOption( TlsOptions::CACERTFILE) << std::endl;
            std::cout << "    CaCertDir: " << tls2.getStringOption( TlsOptions::CACERTDIR ) << std::endl;
            std::cout << "    Require Cert: " << tls2.getIntOption( TlsOptions::REQUIRE_CERT ) << std::endl;
            l2.start_tls();
            std::cout << "StartTLS successful." << std::endl;
            l2.unbind();
        } catch ( LDAPException e ) {
            std::cerr << e << std::endl;
        }
    } catch ( LDAPException e ) {
        std::cerr << e << std::endl;
    }
}    
Example #16
0
void QgsWFSSourceSelect::buildQuery( const QModelIndex& index )
{
  if ( !index.isValid() )
  {
    return;
  }

  const QString typeName = index.sibling( index.row(), MODEL_IDX_NAME ).data().toString();

  //get available fields for wfs layer
  QgsWFSConnection connection( cmbConnections->currentText() );
  QgsWFSDataSourceURI uri( connection.uri().uri() );
  uri.setTypeName( typeName );
  QgsWFSProvider p( uri.uri(), mCaps );
  if ( !p.isValid() )
  {
    QMessageBox* box = new QMessageBox( QMessageBox::Critical, tr( "Server exception" ), tr( "DescribeFeatureType failed" ), QMessageBox::Ok, this );
    box->setAttribute( Qt::WA_DeleteOnClose );
    box->setModal( true );
    box->setObjectName( "WFSFeatureTypeErrorBox" );
    if ( !property( "hideDialogs" ).toBool() )
      box->open();

    return;
  }

  QModelIndex filterIndex = index.sibling( index.row(), MODEL_IDX_SQL );
  QString sql( filterIndex.data().toString() );
  QString displayedTypeName( typeName );
  if ( !mCaps.setAmbiguousUnprefixedTypename.contains( QgsWFSUtils::removeNamespacePrefix( typeName ) ) )
    displayedTypeName = QgsWFSUtils::removeNamespacePrefix( typeName );
  QString allSql( "SELECT * FROM " + QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) );
  if ( sql.isEmpty() )
  {
    sql = allSql;
  }

  QgsSQLComposerDialog* d = new QgsSQLComposerDialog( this );

  QgsWFSValidatorCallback* validatorCbk = new QgsWFSValidatorCallback( d, uri, allSql, mCaps );
  d->setSQLValidatorCallback( validatorCbk );

  QgsWFSTableSelectedCallback* tableSelectedCbk = new QgsWFSTableSelectedCallback( d, uri, mCaps );
  d->setTableSelectedCallback( tableSelectedCbk );

  const bool bSupportJoins = mCaps.featureTypes.size() > 1 && mCaps.supportsJoins;
  d->setSupportMultipleTables( bSupportJoins );

  QMap< QString, QString > mapTypenameToTitle;
  Q_FOREACH ( const QgsWFSCapabilities::FeatureType f, mCaps.featureTypes )
    mapTypenameToTitle[f.name] = f.title;

  QList< QgsSQLComposerDialog::PairNameTitle > tablenames;
  tablenames << QgsSQLComposerDialog::PairNameTitle(
    QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ), mapTypenameToTitle[typeName] );
  if ( bSupportJoins )
  {
    for ( int i = 0; i < mModel->rowCount(); i++ )
    {
      const QString iterTypename = mModel->index( i, MODEL_IDX_NAME ).data().toString();
      if ( iterTypename != typeName )
      {
        QString displayedIterTypename( iterTypename );
        QString unprefixedIterTypename( QgsWFSUtils::removeNamespacePrefix( iterTypename ) );
        if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixedIterTypename ) )
          displayedIterTypename = unprefixedIterTypename;

        tablenames << QgsSQLComposerDialog::PairNameTitle(
          QgsSQLStatement::quotedIdentifierIfNeeded( displayedIterTypename ), mapTypenameToTitle[iterTypename] );
      }
    }
  }
  d->addTableNames( tablenames );

  QList< QgsSQLComposerDialog::Function> functionList;
  Q_FOREACH ( const QgsWFSCapabilities::Function& f, mCaps.functionList )
  {
    QgsSQLComposerDialog::Function dialogF;
    dialogF.name = f.name;
    dialogF.returnType = f.returnType;
    dialogF.minArgs = f.minArgs;
    dialogF.maxArgs = f.maxArgs;
    Q_FOREACH ( const QgsWFSCapabilities::Argument& arg, f.argumentList )
    {
      dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type );
    }
    functionList << dialogF;
  }
  d->addFunctions( functionList );

  QList< QgsSQLComposerDialog::Function> spatialPredicateList;
  Q_FOREACH ( const QgsWFSCapabilities::Function& f, mCaps.spatialPredicatesList )
  {
    QgsSQLComposerDialog::Function dialogF;
    dialogF.name = f.name;
    dialogF.returnType = f.returnType;
    dialogF.minArgs = f.minArgs;
    dialogF.maxArgs = f.maxArgs;
    Q_FOREACH ( const QgsWFSCapabilities::Argument& arg, f.argumentList )
    {
      dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type );
    }
    spatialPredicateList << dialogF;
  }
  d->addSpatialPredicates( spatialPredicateList );

  QList< QgsSQLComposerDialog::PairNameType> fieldList;
  QString fieldNamePrefix;
  if ( bSupportJoins )
  {
    fieldNamePrefix = QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) + ".";
  }
  Q_FOREACH ( const QgsField& field, p.fields().toList() )
  {
    QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( field.name() ) );
    fieldList << QgsSQLComposerDialog::PairNameType( fieldName, field.typeName() );
  }
  if ( !p.geometryAttribute().isEmpty() )
  {
    QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( p.geometryAttribute() ) );
    fieldList << QgsSQLComposerDialog::PairNameType( fieldName, "geometry" );
  }
  fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", "" );

  d->addColumnNames( fieldList, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) );

  d->setSql( sql );

  d->setAttribute( Qt::WA_DeleteOnClose );
  d->setModal( true );
  // For testability, do not use exec()
  if ( !property( "hideDialogs" ).toBool() )
    d->open();
  connect( d, SIGNAL( accepted() ), this, SLOT( updateSql() ) );
  mSQLIndex = index;
  mSQLComposerDialog = d;
}
Example #17
0
void PaymentServer::handleURIOrFile(const QString& s)
{
    if (saveURIs)
    {
        savedPaymentRequests.append(s);
        return;
    }

    if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
    {
#if QT_VERSION < 0x050000
        QUrl uri(s);
#else
        QUrlQuery uri((QUrl(s)));
#endif
        if (uri.hasQueryItem("r")) // payment request URI
        {
            QByteArray temp;
            temp.append(uri.queryItemValue("r"));
            QString decoded = QUrl::fromPercentEncoding(temp);
            QUrl fetchUrl(decoded, QUrl::StrictMode);

            if (fetchUrl.isValid())
            {
                qDebug() << "PaymentServer::handleURIOrFile: fetchRequest(" << fetchUrl << ")";
                fetchRequest(fetchUrl);
            }
            else
            {
                qWarning() << "PaymentServer::handleURIOrFile: Invalid URL: " << fetchUrl;
                Q_EMIT message(tr("URI handling"),
                    tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
                    CClientUIInterface::ICON_WARNING);
            }

            return;
        }
        else // normal URI
        {
            SendCoinsRecipient recipient;
            if (GUIUtil::parseBitcoinURI(s, &recipient))
            {
                if (!IsValidDestinationString(recipient.address.toStdString())) {
                    Q_EMIT message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
                        CClientUIInterface::MSG_ERROR);
                }
                else
                    Q_EMIT receivedPaymentRequest(recipient);
            }
            else
                Q_EMIT message(tr("URI handling"),
                    tr("URI cannot be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters."),
                    CClientUIInterface::ICON_WARNING);

            return;
        }
    }

    if (QFile::exists(s)) // payment request file
    {
        PaymentRequestPlus request;
        SendCoinsRecipient recipient;
        if (!readPaymentRequestFromFile(s, request))
        {
            Q_EMIT message(tr("Payment request file handling"),
                tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
                CClientUIInterface::ICON_WARNING);
        }
        else if (processPaymentRequest(request, recipient))
            Q_EMIT receivedPaymentRequest(recipient);

        return;
    }
}
Example #18
0
void ExportThread::run()
{
    QList< QStringList > archived_books;
    QHash<QString, QList<QStringList> > archive_map; // archive_name => book_info
    QStringList books_ids;
    QPair<QString, QString> pair;
    QStringList bi;
    QString basename;

    foreach (int book_id, p->books) {
        pair = Eclibrus::Db::archivedBookFile(book_id);
        basename = Eclibrus::Plain::bookFileName(book_id);
        if (!archive_map.contains(pair.first)) {
            archive_map[pair.first] = QList<QStringList>();
        }
        bi.clear();
        bi << pair.second << basename;
        archive_map[pair.first] << bi;
    }

    int total_books = p->books.size();
    QString library_path = Eclibrus::Config::librusecLibraryPath() + QDir::separator();
    QString archive_path;
    QString output_path;
    QFileInfo fi;

    const int INITIAL_PROGRESS = 2;
    emit progress(INITIAL_PROGRESS);
    float ppf = (100 - INITIAL_PROGRESS) / total_books;
    int n = 0;
    int percent = 0;

    switch (p->di.devType) {
        case Eclibrus::DeviceInfo::MSD: {
            // copy books to mass storage devuce
            foreach (const QString & archive, archive_map.keys()) {
                archive_path = library_path + archive;

                foreach (const QStringList & book_info, archive_map[archive]) {
                    ++n;
                    output_path = p->outputDir + QDir::separator() + book_info[1] + ".fb2.zip";
                    fi.setFile(output_path);
                    if (true/*!fi.exists()*/) {
                        FB2::exportBookToArchive(archive_path, book_info[0], output_path);
                    } else {
                        qDebug() << "file already exists:" << output_path;
                    }
                    percent = (int)(ppf*n);
                    emit progress(percent+INITIAL_PROGRESS);
                }
            }
            break;
        }

        case Eclibrus::DeviceInfo::WEBDAV: {
            QWebDav wd;
            QUrl uri(p->di.uri);

            QString host = uri.host();
            int port = uri.port();
            if (port == -1) {
                port = 80;
            }

            wd.connectToHost(host, port, uri.path(), uri.userName(), uri.password());
            if (QWebDav::NoError != wd.lastError()) {
                qWarning() << "Failed to init WebDav link: " << p->di.uri;
                return;
            }

            // upload books to WEBDAV device
            // p->outputDir is a collection path on webdav device, files should be placed there
            foreach (const QString & archive, archive_map.keys()) {
                archive_path = library_path + archive;
                foreach (const QStringList & book_info, archive_map[archive]) {
                    ++n;

                    // export to temporary file
                    QTemporaryFile tf;
                    tf.setAutoRemove(false);
                    tf.open();
                    output_path = tf.fileName();
                    qDebug() << "filename:" << output_path;
                    tf.close();
                    FB2::exportBookToArchive(archive_path, book_info[0], output_path);

                    // now copy file "output_path" to the device
                    QString webdavName = p->outputDir + "/" + book_info[1] + ".fb2.zip";
                    qDebug() << "webdav name" << webdavName;
                    wd.put(output_path, webdavName);
                    if (QWebDav::NoError != wd.lastError()) {
                        qWarning() << "Failed to copy local file to WebDav device";
                    }
                    tf.remove();
                }
            }
            break;
        }
    /**
     * Downloads datafiles from the archives, and saves to the users save default directory.
     * @param URL :: The URL of the file to download.
     * @param fileName :: The name of the file to save to disk.
     * @return The full path to the saved file.
     */
    std::string CatalogDownloadDataFiles::doDownloadandSavetoLocalDrive(const std::string& URL,const std::string& fileName)
    {
      std::string pathToDownloadedDatafile;

      clock_t start;

      try
      {
        Poco::URI uri(URL);

        std::string path(uri.getPathAndQuery());
        start=clock();

        Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> certificateHandler = new Poco::Net::AcceptCertificateHandler(true);
        // Currently do not use any means of authentication. This should be updated IDS has signed certificate.
        const Poco::Net::Context::Ptr context = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE);
        // Create a singleton for holding the default context. E.g. any future requests to publish are made to this certificate and context.
        Poco::Net::SSLManager::instance().initializeClient(NULL, certificateHandler,context);
        Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);

        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
        session.sendRequest(request);

        // Close the request by requesting a response.
        Poco::Net::HTTPResponse response;
        // Store the response for use IF an error occurs (e.g. 404).
        std::istream& responseStream = session.receiveResponse(response);

        // Obtain the status returned by the server to verify if it was a success.
        Poco::Net::HTTPResponse::HTTPStatus HTTPStatus = response.getStatus();
        // The error message returned by the IDS (if one exists).
        std::string IDSError = CatalogAlgorithmHelper().getIDSError(HTTPStatus, responseStream);
        // Cancel the algorithm and display the message if it exists.
        if(!IDSError.empty())
        {
          // As an error occurred we must cancel the algorithm to prevent success message.
          this->cancel();
          // Output an appropriate error message from the JSON object returned by the IDS.
          g_log.error(IDSError);
          return "";
        }

        // Save the file to local disk if no errors occurred on the IDS.
        pathToDownloadedDatafile = saveFiletoDisk(responseStream,fileName);

        clock_t end=clock();
        float diff = float(end - start)/CLOCKS_PER_SEC;
        g_log.information()<<"Time taken to download file "<< fileName<<" is "<<std::fixed << std::setprecision(2) << diff <<" seconds" << std::endl;

      }
      catch(Poco::Net::SSLException& error)
      {
        throw std::runtime_error(error.displayText());
      }
      // A strange error occurs (what returns: {I/O error}, while message returns: { 9: The BIO reported an error }.
      // This bug has been fixed in POCO 1.4 and is noted - http://sourceforge.net/p/poco/bugs/403/
      // I have opted to catch the exception and do nothing as this allows the load/download functionality to work.
      // However, the port the user used to download the file will be left open.
      catch(Poco::Exception&) {}

      return pathToDownloadedDatafile;
    }
void TimeStepComputer::signal_max_cfl( common::SignalArgs& node )
{
  SignalFrame reply = node.create_reply(uri());
  SignalOptions reply_options(reply);
  reply_options.add( "return_value", max_cfl() );
}
Example #21
0
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
    QDialog(parent),
    ui(new Ui::HelpMessageDialog)
{
    ui->setupUi(this);

    QString version = tr("Beardcoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
    /* On x86 add a bit specifier to the version so that users can distinguish between
     * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
     */
#if defined(__x86_64__)
    version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
    version += " " + tr("(%1-bit)").arg(32);
#endif

    if (about)
    {
        setWindowTitle(tr("About Beardcoin Core"));

        /// HTML-format the license message from the core
        QString licenseInfo = QString::fromStdString(LicenseInfo());
        QString licenseInfoHTML = licenseInfo;
        // Make URLs clickable
        QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
        uri.setMinimal(true); // use non-greedy matching
        licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
        // Replace newlines with HTML breaks
        licenseInfoHTML.replace("\n\n", "<br><br>");

        ui->aboutMessage->setTextFormat(Qt::RichText);
        ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        text = version + "\n" + licenseInfo;
        ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
        ui->aboutMessage->setWordWrap(true);
        ui->helpMessage->setVisible(false);
    } else {
        setWindowTitle(tr("Command-line options"));
        QString header = tr("Usage:") + "\n" +
                         "  beardcoin-qt [" + tr("command-line options") + "]                     " + "\n";
        QTextCursor cursor(ui->helpMessage->document());
        cursor.insertText(version);
        cursor.insertBlock();
        cursor.insertText(header);
        cursor.insertBlock();

        QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
        text = version + "\n" + header + "\n" + coreOptions;

        QTextTableFormat tf;
        tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
        tf.setCellPadding(2);
        QVector<QTextLength> widths;
        widths << QTextLength(QTextLength::PercentageLength, 35);
        widths << QTextLength(QTextLength::PercentageLength, 65);
        tf.setColumnWidthConstraints(widths);

        QTextCharFormat bold;
        bold.setFontWeight(QFont::Bold);

        Q_FOREACH (const QString &line, coreOptions.split("\n")) {
            if (line.startsWith("  -"))
            {
                cursor.currentTable()->appendRows(1);
                cursor.movePosition(QTextCursor::PreviousCell);
                cursor.movePosition(QTextCursor::NextRow);
                cursor.insertText(line.trimmed());
                cursor.movePosition(QTextCursor::NextCell);
            } else if (line.startsWith("   ")) {
                cursor.insertText(line.trimmed()+' ');
            } else if (line.size() > 0) {
                //Title of a group
                if (cursor.currentTable())
                    cursor.currentTable()->appendRows(1);
                cursor.movePosition(QTextCursor::Down);
                cursor.insertText(line.trimmed(), bold);
                cursor.insertTable(1, 2, tf);
            }
        }

        ui->helpMessage->moveCursor(QTextCursor::Start);
        ui->scrollArea->setVisible(false);
        ui->aboutLogo->setVisible(false);
    }
}
Example #22
0
bool QgsMapLayer::readLayerXML( const QDomElement& layerElement )
{
  QgsCoordinateReferenceSystem savedCRS;
  CUSTOM_CRS_VALIDATION savedValidation;
  bool layerError;

  QDomNode mnl;
  QDomElement mne;

  // read provider
  QString provider;
  mnl = layerElement.namedItem( "provider" );
  mne = mnl.toElement();
  provider = mne.text();

  // set data source
  mnl = layerElement.namedItem( "datasource" );
  mne = mnl.toElement();
  mDataSource = mne.text();

  // TODO: this should go to providers
  if ( provider == "spatialite" )
  {
    QgsDataSourceURI uri( mDataSource );
    uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) );
    mDataSource = uri.uri();
  }
  else if ( provider == "ogr" )
  {
    QStringList theURIParts = mDataSource.split( "|" );
    theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] );
    mDataSource = theURIParts.join( "|" );
  }
  else if ( provider == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() );

    if ( !mDataSource.startsWith( "file:" ) )
    {
      QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) );
      urlSource.setScheme( "file" );
      urlSource.setPath( file.path() );
    }

    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    mDataSource = QString::fromAscii( urlDest.toEncoded() );
  }
  else if ( provider == "wms" )
  {
    // >>> BACKWARD COMPATIBILITY < 1.9
    // For project file backward compatibility we must support old format:
    // 1. mode: <url>
    //    example: http://example.org/wms?
    // 2. mode: tiled=<width>;<height>;<resolution>;<resolution>...,ignoreUrl=GetMap;GetFeatureInfo,featureCount=<count>,username=<name>,password=<password>,url=<url>
    //    example: tiled=256;256;0.703;0.351,url=http://example.org/tilecache?
    //    example: featureCount=10,http://example.org/wms?
    //    example: ignoreUrl=GetMap;GetFeatureInfo,username=cimrman,password=jara,url=http://example.org/wms?
    // This is modified version of old QgsWmsProvider::parseUri
    // The new format has always params crs,format,layers,styles and that params
    // should not appear in old format url -> use them to identify version
    if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) )
    {
      QgsDebugMsg( "Old WMS URI format detected -> converting to new format" );
      QgsDataSourceURI uri;
      if ( !mDataSource.startsWith( "http:" ) )
      {
        QStringList parts = mDataSource.split( "," );
        QStringListIterator iter( parts );
        while ( iter.hasNext() )
        {
          QString item = iter.next();
          if ( item.startsWith( "username="******"username", item.mid( 9 ) );
          }
          else if ( item.startsWith( "password="******"password", item.mid( 9 ) );
          }
          else if ( item.startsWith( "tiled=" ) )
          {
            // in < 1.9 tiled= may apper in to variants:
            // tiled=width;height - non tiled mode, specifies max width and max height
            // tiled=width;height;resolutions-1;resolution2;... - tile mode

            QStringList params = item.mid( 6 ).split( ";" );

            if ( params.size() == 2 ) // non tiled mode
            {
              uri.setParam( "maxWidth", params.takeFirst() );
              uri.setParam( "maxHeight", params.takeFirst() );
            }
            else if ( params.size() > 2 ) // tiled mode
            {
              // resolutions are no more needed and size limit is not used for tiles
              // we have to tell to the provider however that it is tiled
              uri.setParam( "tileMatrixSet", "" );
            }
          }
          else if ( item.startsWith( "featureCount=" ) )
          {
            uri.setParam( "featureCount", item.mid( 13 ) );
          }
          else if ( item.startsWith( "url=" ) )
          {
            uri.setParam( "url", item.mid( 4 ) );
          }
          else if ( item.startsWith( "ignoreUrl=" ) )
          {
            uri.setParam( "ignoreUrl", item.mid( 10 ).split( ";" ) );
          }
        }
      }
      else
      {
        uri.setParam( "url", mDataSource );
      }
      mDataSource = uri.encodedUri();
      // At this point, the URI is obviously incomplete, we add additional params
      // in QgsRasterLayer::readXml
    }
    // <<< BACKWARD COMPATIBILITY < 1.9
  }
  else
  {
    mDataSource = QgsProject::instance()->readPath( mDataSource );
  }

  // Set the CRS from project file, asking the user if necessary.
  // Make it the saved CRS to have WMS layer projected correctly.
  // We will still overwrite whatever GDAL etc picks up anyway
  // further down this function.
  mnl = layerElement.namedItem( "layername" );
  mne = mnl.toElement();

  QDomNode srsNode = layerElement.namedItem( "srs" );
  mCRS->readXML( srsNode );
  mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
  mCRS->validate();
  savedCRS = *mCRS;

  // Do not validate any projections in children, they will be overwritten anyway.
  // No need to ask the user for a projections when it is overwritten, is there?
  savedValidation = QgsCoordinateReferenceSystem::customSrsValidation();
  QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL );

  // now let the children grab what they need from the Dom node.
  layerError = !readXml( layerElement );

  // overwrite CRS with what we read from project file before the raster/vector
  // file readnig functions changed it. They will if projections is specfied in the file.
  // FIXME: is this necessary?
  QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation );
  *mCRS = savedCRS;

  // Abort if any error in layer, such as not found.
  if ( layerError )
  {
    return false;
  }

  // the internal name is just the data source basename
  //QFileInfo dataSourceFileInfo( mDataSource );
  //internalName = dataSourceFileInfo.baseName();

  // set ID
  mnl = layerElement.namedItem( "id" );
  if ( ! mnl.isNull() )
  {
    mne = mnl.toElement();
    if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
    {
      mID = mne.text();
    }
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( layerElement.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( layerElement.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( layerElement.attribute( "maximumScale" ).toFloat() );

  // set name
  mnl = layerElement.namedItem( "layername" );
  mne = mnl.toElement();
  setLayerName( mne.text() );

  //title
  QDomElement titleElem = layerElement.firstChildElement( "title" );
  if ( !titleElem.isNull() )
  {
    mTitle = titleElem.text();
  }

  //abstract
  QDomElement abstractElem = layerElement.firstChildElement( "abstract" );
  if ( !abstractElem.isNull() )
  {
    mAbstract = abstractElem.text();
  }

  //keywordList
  QDomElement keywordListElem = layerElement.firstChildElement( "keywordList" );
  if ( !keywordListElem.isNull() )
  {
    QStringList kwdList;
    for ( QDomNode n = keywordListElem.firstChild(); !n.isNull(); n = n.nextSibling() )
    {
      kwdList << n.toElement().text();
    }
    mKeywordList = kwdList.join( ", " );
  }

  //metadataUrl
  QDomElement dataUrlElem = layerElement.firstChildElement( "dataUrl" );
  if ( !dataUrlElem.isNull() )
  {
    mDataUrl = dataUrlElem.text();
    mDataUrlFormat = dataUrlElem.attribute( "format", "" );
  }

  //attribution
  QDomElement attribElem = layerElement.firstChildElement( "attribution" );
  if ( !attribElem.isNull() )
  {
    mAttribution = attribElem.text();
    mAttributionUrl = attribElem.attribute( "href", "" );
  }

  //metadataUrl
  QDomElement metaUrlElem = layerElement.firstChildElement( "metadataUrl" );
  if ( !metaUrlElem.isNull() )
  {
    mMetadataUrl = metaUrlElem.text();
    mMetadataUrlType = metaUrlElem.attribute( "type", "" );
    mMetadataUrlFormat = metaUrlElem.attribute( "format", "" );
  }

#if 0
  //read transparency level
  QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }
#endif

  readCustomProperties( layerElement );

  return true;
} // bool QgsMapLayer::readLayerXML
Example #23
0
  bool XMLConversion::ReadXML(XMLBaseFormat* pFormat, OBBase* pOb)
  {
    if(_requestedpos)
      {
        //The initial stream position was not at the start, probably because of fastsearch
        //Read and discard the first object to synchronize the reader,
        //then continue getting the requested object.
        //Assumes the objects are all at the same level in the DOM tree.
        SetOneObjectOnly(); //probably already set
        streampos SavedReqestedPos = _requestedpos;
        _requestedpos=0;//don't do this again
        ReadXML(pFormat,pOb);
        GetInStream()->seekg(SavedReqestedPos);
      }

    //**Parse
    int result=1;
    while(GetInStream()->good() && (_SkipNextRead || (result=xmlTextReaderRead(_reader))==1)) //read may not be called
    {
      _SkipNextRead=false;
      if(_LookingForNamespace)
      {
        const xmlChar* puri = xmlTextReaderConstNamespaceUri(_reader);
        if(puri)
          {
            string uri((const char*)puri);
            //Look up appropriate format class from the namespace URI
            NsMapType::iterator nsiter;
            nsiter = Namespaces().find(uri);
            if(nsiter!=Namespaces().end())
              {
                XMLBaseFormat* pNewFormat = nsiter->second;
                //Must have same target, e.g. OBMol, as current format
                if(pNewFormat->GetType() == pFormat->GetType())
                  {
                    _LookingForNamespace=false;
                    _SkipNextRead=true;
                    SetInFormat(pNewFormat);
                    pNewFormat->ReadMolecule(pOb,this);
                    return true;
                  }
              }
          }
      }

      const xmlChar* pname = xmlTextReaderConstLocalName(_reader);
      int typ = xmlTextReaderNodeType(_reader);
      if(typ==XML_READER_TYPE_SIGNIFICANT_WHITESPACE || !pname)
        continue; //Text nodes handled in format class
      string ElName((const char*)pname);

      //Pass the node on to the appropriate format class
      bool ret;
      if(typ==XML_READER_TYPE_ELEMENT)
        ret= pFormat->DoElement(ElName);
      else if(typ==XML_READER_TYPE_END_ELEMENT)
        ret= pFormat->EndElement(ElName);
      else
        continue;
      _lastpos = GetInStream()->tellg();

      if(!ret)
        //derived format callback has stopped processing by returning false;
        //leave reader intact so it can be continued to be used.
        if(!IsOption("n",OBConversion::INOPTIONS))
          {
            _LookingForNamespace = true;
            return true;
          }
      }

    if(result==-1)
    {
      xmlError* perr = xmlGetLastError();
      if(perr && perr->level!=XML_ERR_NONE)
        {
          obErrorLog.ThrowError("XML Parser " + GetInFilename(),
                                perr->message, obError);
        }
      xmlResetError(perr);
      GetInStream()->setstate(ios::eofbit);
      return false;
    }
    return GetInStream()->good() && result!=0;
  }
Example #24
0
bool QgsMapLayer::writeLayerXML( QDomElement& layerElement, QDomDocument& document )
{
  // use scale dependent visibility flag
  layerElement.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
  layerElement.setAttribute( "minimumScale", QString::number( minimumScale() ) );
  layerElement.setAttribute( "maximumScale", QString::number( maximumScale() ) );

  // ID
  QDomElement layerId = document.createElement( "id" );
  QDomText layerIdText = document.createTextNode( id() );
  layerId.appendChild( layerIdText );

  layerElement.appendChild( layerId );

  // data source
  QDomElement dataSource = document.createElement( "datasource" );

  QString src = source();

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  // TODO: what about postgres, mysql and others, they should not go through writePath()
  if ( vlayer && vlayer->providerType() == "spatialite" )
  {
    QgsDataSourceURI uri( src );
    QString database = QgsProject::instance()->writePath( uri.database() );
    uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() );
    src = uri.uri();
  }
  else if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = src.split( "|" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] );
    src = theURIParts.join( "|" );
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( src.toAscii() );
    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    src = QString::fromAscii( urlDest.toEncoded() );
  }
  else
  {
    src = QgsProject::instance()->writePath( src );
  }

  QDomText dataSourceText = document.createTextNode( src );
  dataSource.appendChild( dataSourceText );

  layerElement.appendChild( dataSource );


  // layer name
  QDomElement layerName = document.createElement( "layername" );
  QDomText layerNameText = document.createTextNode( originalName() );
  layerName.appendChild( layerNameText );

  // layer title
  QDomElement layerTitle = document.createElement( "title" ) ;
  QDomText layerTitleText = document.createTextNode( title() );
  layerTitle.appendChild( layerTitleText );

  // layer abstract
  QDomElement layerAbstract = document.createElement( "abstract" );
  QDomText layerAbstractText = document.createTextNode( abstract() );
  layerAbstract.appendChild( layerAbstractText );

  layerElement.appendChild( layerName );
  layerElement.appendChild( layerTitle );
  layerElement.appendChild( layerAbstract );

  // layer keyword list
  QStringList keywordStringList = keywordList().split( "," );
  if ( keywordStringList.size() > 0 )
  {
    QDomElement layerKeywordList = document.createElement( "keywordList" );
    for ( int i = 0; i < keywordStringList.size(); ++i )
    {
      QDomElement layerKeywordValue = document.createElement( "value" );
      QDomText layerKeywordText = document.createTextNode( keywordStringList.at( i ).trimmed() );
      layerKeywordValue.appendChild( layerKeywordText );
      layerKeywordList.appendChild( layerKeywordValue );
    }
    layerElement.appendChild( layerKeywordList );
  }

  // layer metadataUrl
  QString aDataUrl = dataUrl();
  if ( !aDataUrl.isEmpty() )
  {
    QDomElement layerDataUrl = document.createElement( "dataUrl" ) ;
    QDomText layerDataUrlText = document.createTextNode( aDataUrl );
    layerDataUrl.appendChild( layerDataUrlText );
    layerDataUrl.setAttribute( "format", dataUrlFormat() );
    layerElement.appendChild( layerDataUrl );
  }

  // layer attribution
  QString aAttribution = attribution();
  if ( !aAttribution.isEmpty() )
  {
    QDomElement layerAttribution = document.createElement( "attribution" ) ;
    QDomText layerAttributionText = document.createTextNode( aAttribution );
    layerAttribution.appendChild( layerAttributionText );
    layerAttribution.setAttribute( "href", attributionUrl() );
    layerElement.appendChild( layerAttribution );
  }

  // layer metadataUrl
  QString aMetadataUrl = metadataUrl();
  if ( !aMetadataUrl.isEmpty() )
  {
    QDomElement layerMetadataUrl = document.createElement( "metadataUrl" ) ;
    QDomText layerMetadataUrlText = document.createTextNode( aMetadataUrl );
    layerMetadataUrl.appendChild( layerMetadataUrlText );
    layerMetadataUrl.setAttribute( "type", metadataUrlType() );
    layerMetadataUrl.setAttribute( "format", metadataUrlFormat() );
    layerElement.appendChild( layerMetadataUrl );
  }

  // timestamp if supported
  if ( timestamp() > QDateTime() )
  {
    QDomElement stamp = document.createElement( "timestamp" );
    QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
    stamp.appendChild( stampText );
    layerElement.appendChild( stamp );
  }

  layerElement.appendChild( layerName );

  // zorder
  // This is no longer stored in the project file. It is superfluous since the layers
  // are written and read in the proper order.

  // spatial reference system id
  QDomElement mySrsElement = document.createElement( "srs" );
  mCRS->writeXML( mySrsElement, document );
  layerElement.appendChild( mySrsElement );

#if 0
  // <transparencyLevelInt>
  QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" );
  QDomText    transparencyLevelIntText    = document.createTextNode( QString::number( getTransparency() ) );
  transparencyLevelIntElement.appendChild( transparencyLevelIntText );
  maplayer.appendChild( transparencyLevelIntElement );
#endif

  // now append layer node to map layer node

  writeCustomProperties( layerElement, document );

  return writeXml( layerElement, document );

} // bool QgsMapLayer::writeXML
bool QgsProject::createEmbeddedLayer( const QString& layerId, const QString& projectFilePath, QList<QDomNode>& brokenNodes,
                                      QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList, bool saveFlag )
{
  QFile projectFile( projectFilePath );
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return false;
  }

  QDomDocument projectDocument;
  if ( !projectDocument.setContent( &projectFile ) )
  {
    return false;
  }

  //does project store pathes absolute or relative?
  bool useAbsolutePathes = true;
  QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement absElem = propertiesElem.firstChildElement( "Paths" ).firstChildElement( "Absolute" );
    if ( !absElem.isNull() )
    {
      useAbsolutePathes = absElem.text().compare( "true", Qt::CaseInsensitive ) == 0;
    }
  }

  QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( "projectlayers" );
  if ( projectLayersElem.isNull() )
  {
    return false;
  }

  QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( "maplayer" );
  for ( int i = 0; i < mapLayerNodes.size(); ++i )
  {
    //get layer id
    QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement();
    QString id = mapLayerElem.firstChildElement( "id" ).text();
    if ( id == layerId )
    {
      //layer can be embedded only once
      if ( mapLayerElem.attribute( "embedded" ) == "1" )
      {
        return false;
      }

      mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );

      //change datasource path from relative to absolute if necessary
      if ( !useAbsolutePathes )
      {
        QDomElement provider = mapLayerElem.firstChildElement( "provider" );
        if ( provider.text() == "spatialite" )
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );

          QgsDataSourceURI uri( dsElem.text() );

          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + uri.database() );
          if ( absoluteDs.exists() )
          {
            uri.setDatabase( absoluteDs.absoluteFilePath() );
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( uri.uri() ) );
          }
        }
        else
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );
          QString debug( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          if ( absoluteDs.exists() )
          {
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( absoluteDs.absoluteFilePath() ) );
          }
        }
      }

      if ( addLayer( mapLayerElem, brokenNodes, vectorLayerList ) )
      {
        return true;
      }
      else
      {
        mEmbeddedLayers.remove( layerId );
        return false;
      }
    }
  }

  return false;
}
Example #26
0
void IONSPaymentProcessor::pay(QString address, QString fee)
{
    QString uri("iocoin:" + address + "?amount=" + fee);
    gui->handleURI(uri);
}
Example #27
0
SwiftResult<HTTPClientSession*>* Object::swiftCreateReplaceObject(std::ostream* &outputStream,
    std::vector<HTTPHeader>* _uriParams, std::vector<HTTPHeader>* _reqMap) {
  //Check Container
  if (container == nullptr)
    return returnNullError<HTTPClientSession*>("container");

  if (container->getAccount() == nullptr)
    return returnNullError<HTTPClientSession*>("account");
  Endpoint* swiftEndpoint =
      container->getAccount()->getSwiftService()->getFirstEndpoint();
  if (swiftEndpoint == nullptr)
    return returnNullError<HTTPClientSession*>("SWIFT Endpoint");

  //Create parameter map
  vector<HTTPHeader> reqParamMap;
  //Add authentication token
  string tokenID = container->getAccount()->getToken()->getId();
  HTTPHeader authHeader("X-Auth-Token", tokenID);
  reqParamMap.push_back(authHeader);
  //Push Chuncked Encoding
  HTTPHeader encHeader("Transfer-Encoding", "chunked");
  reqParamMap.push_back(encHeader);
  //Add rest of request Parameters
  if (_reqMap != nullptr && _reqMap->size() > 0) {
    for (uint i = 0; i < _reqMap->size(); i++) {
      reqParamMap.push_back(_reqMap->at(i));
    }
  }

  //Path
  string path = container->getName() + "/" + name;
  URI uri(swiftEndpoint->getPublicUrl());
  string encoded;
  URI::encode(path,"",encoded);
  path = encoded;
  uri.setPath(uri.getPath() + "/" + path);

  if (_uriParams != nullptr && _uriParams->size() > 0) {
    //Create appropriate URI
    ostringstream queryStream;
    for (uint i = 0; i < _uriParams->size(); i++) {
      if (i > 0)
        queryStream << ",";
      queryStream << _uriParams->at(i).getQueryValue();
    }
    uri.setQuery(queryStream.str());
    //cout << uri.toString() << endl;
  }

  //Creating HTTP Session
  HTTPClientSession *httpSession = nullptr;
  try {
    /** This operation does not accept a request body. **/
    httpSession = doHTTPIO(uri, HTTPRequest::HTTP_PUT, &reqParamMap, outputStream);
    //Now we should increase number of calls to SWIFT API
    container->getAccount()->increaseCallCounter();
  } catch (Exception &e) {
    SwiftResult<HTTPClientSession*> *result = new SwiftResult<HTTPClientSession*>();
    SwiftError error(SwiftError::SWIFT_EXCEPTION, e.displayText());
    result->setError(error);
    //Try to set HTTP Response as the payload
    result->setSession(httpSession);
    result->setResponse(nullptr);
    result->setPayload(nullptr);
    return result;
  }

  //Everything seems fine
  SwiftResult<HTTPClientSession*> *result = new SwiftResult<HTTPClientSession*>();
  result->setError(SWIFT_OK);
  result->setSession(httpSession);
  result->setResponse(nullptr);
  result->setPayload(httpSession);
  return result;
}
Example #28
0
/**
 * @param filenames : List of files to search
 * @param exts : List of extensions to check against
 * @return list of archive locations
 */
std::string SNSDataArchive::getArchivePath(const std::set<std::string>& filenames, const std::vector<std::string>& exts) const
{
  std::set<std::string>::const_iterator iter = filenames.begin();
  std::string filename = *iter;

  //ICAT4 web service take upper case filename such as HYSA_2662
  std::transform(filename.begin(),filename.end(),filename.begin(),toupper);

  std::vector<std::string>::const_iterator iter2 = exts.begin();
  for(; iter2!=exts.end(); ++iter2)
  {
    g_log.debug() << *iter2 << ";";
  }
  g_log.debug()  << "\n";

  std::string baseURL("http://icat.sns.gov:8080/icat-rest-ws/datafile/filename/");

  std::string URL(baseURL + filename);
  g_log.debug() << "URL: " << URL << "\n";

  Poco::URI uri(URL);
  std::string path(uri.getPathAndQuery());

  Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
  Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
  session.sendRequest(req);

  Poco::Net::HTTPResponse res;
  std::istream& rs = session.receiveResponse(res);
  g_log.debug() << "res.getStatus(): " << res.getStatus() << "\n";

  // Create a DOM document from the response.
  Poco::XML::DOMParser parser;
  Poco::XML::InputSource source(rs);
  Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);

  std::vector<std::string> locations;

  // If everything went fine, return the XML document.
  // Otherwise look for an error message in the XML document.
  if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
  {
    std::string location;
    Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("location");
    for(unsigned long i = 0 ; i < pList->length(); i++)
    {
      location = pList->item(i)->innerText();
      g_log.debug() << "location: " << location << "\n";
      locations.push_back(location);
    }
  }
  else
  {
    std::string error(res.getReason());
    throw Poco::ApplicationException("HTTPRequest Error", error);
  }

  std::vector<std::string>::const_iterator ext = exts.begin();
  for (; ext != exts.end(); ++ext)
  {
    std::string datafile = filename + *ext;
    std::vector<std::string>::const_iterator iter = locations.begin();
    for(; iter!=locations.end(); ++iter)
    {
      if (boost::algorithm::ends_with((*iter), datafile))
      {
        return *iter;
      } // end if
    } // end for iter

  }  // end for ext
  return "";
}
NS_IMETHODIMP
nsHTMLURIRefObject::GetNextURI(nsAString & aURI)
{
  NS_ENSURE_TRUE(mNode, NS_ERROR_NOT_INITIALIZED);

  nsAutoString tagName;
  nsresult rv = mNode->GetNodeName(tagName);
  NS_ENSURE_SUCCESS(rv, rv);

  // Loop over attribute list:
  if (!mAttributes)
  {
    nsCOMPtr<nsIDOMElement> element (do_QueryInterface(mNode));
    NS_ENSURE_TRUE(element, NS_ERROR_INVALID_ARG);

    mCurAttrIndex = 0;
    element->GetAttributes(getter_AddRefs(mAttributes));
    NS_ENSURE_TRUE(mAttributes, NS_ERROR_NOT_INITIALIZED);

    rv = mAttributes->GetLength(&mAttributeCnt);
    NS_ENSURE_SUCCESS(rv, rv);
    NS_ENSURE_TRUE(mAttributeCnt, NS_ERROR_FAILURE);
    mCurAttrIndex = 0;
  }

  while (mCurAttrIndex < mAttributeCnt)
  {
    nsCOMPtr<nsIDOMAttr> attrNode;
    rv = mAttributes->Item(mCurAttrIndex++, getter_AddRefs(attrNode));
    NS_ENSURE_SUCCESS(rv, rv);
    NS_ENSURE_ARG_POINTER(attrNode);
    nsString curAttr;
    rv = attrNode->GetName(curAttr);
    NS_ENSURE_SUCCESS(rv, rv);

    // href >> A, AREA, BASE, LINK
    if (MATCHES(curAttr, "href"))
    {
      if (!MATCHES(tagName, "a") && !MATCHES(tagName, "area")
          && !MATCHES(tagName, "base") && !MATCHES(tagName, "link"))
        continue;
      rv = attrNode->GetValue(aURI);
      NS_ENSURE_SUCCESS(rv, rv);
      nsString uri (aURI);
      // href pointing to a named anchor doesn't count
      if (aURI.First() != char16_t('#'))
        return NS_OK;
      aURI.Truncate();
      return NS_ERROR_INVALID_ARG;
    }
    // src >> FRAME, IFRAME, IMG, INPUT, SCRIPT
    else if (MATCHES(curAttr, "src"))
    {
      if (!MATCHES(tagName, "img")
          && !MATCHES(tagName, "frame") && !MATCHES(tagName, "iframe")
          && !MATCHES(tagName, "input") && !MATCHES(tagName, "script"))
        continue;
      return attrNode->GetValue(aURI);
    }
    //<META http-equiv="refresh" content="3,http://www.acme.com/intro.html">
    else if (MATCHES(curAttr, "content"))
    {
      if (!MATCHES(tagName, "meta"))
        continue;
    }
    // longdesc >> FRAME, IFRAME, IMG
    else if (MATCHES(curAttr, "longdesc"))
    {
      if (!MATCHES(tagName, "img")
          && !MATCHES(tagName, "frame") && !MATCHES(tagName, "iframe"))
        continue;
    }
    // usemap >> IMG, INPUT, OBJECT
    else if (MATCHES(curAttr, "usemap"))
    {
      if (!MATCHES(tagName, "img")
          && !MATCHES(tagName, "input") && !MATCHES(tagName, "object"))
        continue;
    }
    // action >> FORM
    else if (MATCHES(curAttr, "action"))
    {
      if (!MATCHES(tagName, "form"))
        continue;
    }
    // background >> BODY
    else if (MATCHES(curAttr, "background"))
    {
      if (!MATCHES(tagName, "body"))
        continue;
    }
    // codebase >> OBJECT, APPLET
    else if (MATCHES(curAttr, "codebase"))
    {
      if (!MATCHES(tagName, "meta"))
        continue;
    }
    // classid >> OBJECT
    else if (MATCHES(curAttr, "classid"))
    {
      if (!MATCHES(tagName, "object"))
        continue;
    }
    // data >> OBJECT
    else if (MATCHES(curAttr, "data"))
    {
      if (!MATCHES(tagName, "object"))
        continue;
    }
    // cite >> BLOCKQUOTE, DEL, INS, Q
    else if (MATCHES(curAttr, "cite"))
    {
      if (!MATCHES(tagName, "blockquote") && !MATCHES(tagName, "q")
          && !MATCHES(tagName, "del") && !MATCHES(tagName, "ins"))
        continue;
    }
    // profile >> HEAD
    else if (MATCHES(curAttr, "profile"))
    {
      if (!MATCHES(tagName, "head"))
        continue;
    }
    // archive attribute on APPLET; warning, it contains a list of URIs.
    else if (MATCHES(curAttr, "archive"))
    {
      if (!MATCHES(tagName, "applet"))
        continue;
    }
  }
  // Return a code to indicate that there are no more,
  // to distinguish that case from real errors.
  return NS_ERROR_NOT_AVAILABLE;
}
int arVrmlLoadFile(const char *file)
{
  
    FILE             *fp;
    openvrml::browser * myBrowser = 0;
    char             buf[256], buf1[256];
    char             buf2[256];
    int              id;
    int              i;

    if( init ) {
        for( i = 0; i < AR_VRML_MAX; i++ ) viewer[i] = NULL;
        init = 0;
    }
    for( i = 0; i < AR_VRML_MAX; i++ ) {
        if( viewer[i] == NULL ) break;
    }
    if( i == AR_VRML_MAX ) return -1;
    id = i;


    if( (fp=fopen(file, "r")) == NULL ) return -1;

    get_buff(buf, 256, fp);
    if( sscanf(buf, "%s", buf1) != 1 ) {fclose(fp); return -1;}
    for( i = 0; file[i] != '\0'; i++ ) buf2[i] = file[i];
    for( ; i >= 0; i-- ) {
        if( buf2[i] == '/' ) break;
    }
    buf2[i+1] = '\0';
    sprintf(buf, "%s%s", buf2, buf1);

    myBrowser = new openvrml::browser(std::cout, std::cerr);
    if( !myBrowser) {fclose(fp); return -1;}

    std::vector<std::string> uri(1, buf);
    std::vector<std::string> parameter; 
    myBrowser->load_url(uri, parameter);

    viewer[id] = new arVrmlViewer(*myBrowser);
    if(!viewer[id]) 
    {
        delete myBrowser;
        fclose(fp);
        return -1;
    }
    strcpy( viewer[id]->filename, buf );
    
    get_buff(buf, 256, fp);
    if( sscanf(buf, "%lf %lf %lf", &viewer[id]->translation[0], 
        &viewer[id]->translation[1], &viewer[id]->translation[2]) != 3 ) {
        delete viewer[id];
        viewer[id] = NULL;
        fclose(fp);
        return -1;
    }

    get_buff(buf, 256, fp);
    if( sscanf(buf, "%lf %lf %lf %lf", &viewer[id]->rotation[0],
        &viewer[id]->rotation[1], &viewer[id]->rotation[2], &viewer[id]->rotation[3]) != 4 ) {
        delete viewer[id];
        viewer[id] = NULL;
        fclose(fp);
        return -1;
    }

    get_buff(buf, 256, fp);
    if( sscanf(buf, "%lf %lf %lf", &viewer[id]->scale[0], &viewer[id]->scale[1],
               &viewer[id]->scale[2]) != 3 ) {
        delete viewer[id];
        viewer[id] = NULL;
        fclose(fp);
        return -1;
    }
    fclose(fp);

    return id;
}