QgsVectorLayer* QgsSentDataSourceBuilder::vectorLayerFromSentVDS( const QDomElement& sentVDSElem, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove ) const
{
  if ( sentVDSElem.attribute( "format" ) == "GML" )
  {
    QTemporaryFile* tmpFile = new QTemporaryFile();
    if ( tmpFile->open() )
    {
      filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request
      QTextStream tempFileStream( tmpFile );
      sentVDSElem.save( tempFileStream, 4 );
      tmpFile->close();
    }
    else
    {
      return 0;
    }

    QgsVectorLayer* theVectorLayer = new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), "WFS" );
    if ( !theVectorLayer || !theVectorLayer->isValid() )
    {
      QgsMSDebugMsg( "invalid maplayer" );
      return 0;
    }
    QgsMSDebugMsg( "returning maplayer" );

    layersToRemove.push_back( theVectorLayer ); //make sure the layer gets deleted after each request

    if ( !theVectorLayer || !theVectorLayer->isValid() )
    {
      return 0;
    }
    return theVectorLayer;
  }
  return 0;
}
QgsRasterLayer* QgsSentDataSourceBuilder::rasterLayerFromSentRDS( const QDomElement& sentRDSElem, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove ) const
{
  QgsMSDebugMsg( "Entering" );
  QString tempFilePath = createTempFile();
  if ( tempFilePath.isEmpty() )
  {
    return 0;
  }
  QFile tempFile( tempFilePath );

  QTemporaryFile* tmpFile = new QTemporaryFile();

  QString encoding = sentRDSElem.attribute( "encoding" );

  if ( encoding == "base64" )
  {
    if ( tmpFile->open() )
    {
      QByteArray binaryContent = QByteArray::fromBase64( sentRDSElem.text().toAscii() );
      QDataStream ds( tmpFile );
      ds.writeRawData( binaryContent.data(), binaryContent.length() );
    }
    else
    {
      delete tmpFile;
      return 0;
    }

  }
  else //assume text (e.g. ascii grid)
  {
    if ( tmpFile->open() )
    {
      QTextStream tempFileStream( tmpFile );
      tempFileStream << sentRDSElem.text();
    }
    else
    {
      delete tmpFile;
      return 0;
    }
  }

  QgsMSDebugMsg( "TempFilePath is: " + tempFilePath );
  tmpFile->close();

  QgsRasterLayer* rl = new QgsRasterLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ) );
  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
}
Esempio n. 3
0
// static
void VFSNode::safelyOverwriteFile(const VFSNode& target, Vs64 dataLength, VBinaryIOStream& dataStream, bool keepOld) {
    bool success = true;
    VString errorMessage;

    VString targetFileName = target.getName();

    VInstant now;
    VString temporaryFileName = now.getLocalString(VFSNODE_SAFE_FILE_NAME_INSTANT_FORMATTER) + "_tmp_" + targetFileName;
    VString keptFileName = now.getLocalString(VFSNODE_SAFE_FILE_NAME_INSTANT_FORMATTER) + "_ver_" + targetFileName;

    VFSNode directoryNode;
    target.getParentNode(directoryNode);
    VFSNode originalTargetNode(target);
    VFSNode temporaryFileNode(directoryNode, temporaryFileName);
    VFSNode keptFileNode(directoryNode, keptFileName);

    // Create and write to the temp file within a scope block to ensure file is closed when scope is exited.
    /* stream scope */ {
        VBufferedFileStream tempFileStream(temporaryFileNode);
        VBinaryIOStream tempOutputStream(tempFileStream);

        try {
            tempFileStream.openWrite();
        } catch (const VException& ex) {
            success = false;
            errorMessage = VSTRING_FORMAT("Unable to open temporary file '%s': %s", target.getPath().chars(), ex.what());
        }

        if (success) {
            try {
                VStream::streamCopy(dataStream, tempOutputStream, dataLength);
                tempOutputStream.flush();
            } catch (const VException& ex) {
                success = false;
                errorMessage = VSTRING_FORMAT("Unable to write to temporary file '%s': %s", target.getPath().chars(), ex.what());
            }
        }
    }

    /*
    If we succeeded, delete or rename the original file, and rename the temporary file to the original location.
    If we failed, delete the temporary file.
    Do this itself in separate phases, so that if the delete/rename fails, we still delete the temporary file.
    */
    // 1. Remove target. (It might not exist yet.)
    if (success && target.exists()) {
    
        if (keepOld) {
        
            try {
                target.renameToNode(keptFileNode);
            } catch (const VException& ex) {
                success = false;
                errorMessage = VSTRING_FORMAT("Failed renaming '%s' to '%s': %s", target.getPath().chars(), keptFileNode.getPath().chars(), ex.what());
            }

        } else {

            if (! target.rm()) {
                success = false;
                errorMessage = VSTRING_FORMAT("Unable to remove target file '%s'.", target.getPath().chars());
            }

        }
    
    }

    // 2. Rename temporary to (original) target.
    if (success) {
        try {
            temporaryFileNode.renameToNode(originalTargetNode);
        } catch (const VException& ex) {
            success = false;
            errorMessage = VSTRING_FORMAT("Failed renaming '%s' to '%s': %s", temporaryFileNode.getPath().chars(), originalTargetNode.getPath().chars(), ex.what());
        }
    }

    // 3. Remove temporary if unsuccessful.
    if (! success) {
        if (! temporaryFileNode.rm()) {
            errorMessage += VSTRING_FORMAT(" Removal of temporary file '%s' failed.", temporaryFileNode.getPath().chars());
        }
    }

    // If we failed, throw an exception with the error message we built wherever we encountered errors.
    if (! success) {
        throw VException(errorMessage);
    }
}
Esempio n. 4
0
QgsRasterLayer* QgsRemoteOWSBuilder::wcsLayerFromUrl( const QString &url,
    const QString &layerName,
    QList<QTemporaryFile*> &filesToRemove,
    QList<QgsMapLayer*> &layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( layerName );
  Q_UNUSED( allowCaching );

#if QT_VERSION < 0x050000
  QgsDebugMsg( "Entering" );

  //write server url and coverage name to a temporary file
  QString fileName = createTempFile();
  if ( fileName.isEmpty() )
  {
    return nullptr;
  }

  QFile tempFile( fileName );

  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( !tmpFile->open() )
  {
    delete tmpFile;
    return nullptr;
  }

  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request

  QgsDebugMsg( "opening successful" );
  QgsDebugMsg( "url: " + url );
  //extract server url and coverage name from string
  QStringList serverSplit = url.split( "?" );
  if ( serverSplit.size() < 2 )
  {
    QgsDebugMsg( "error, no '?' contained in url" );
    return nullptr;
  }
  QString serverUrl = serverSplit.at( 0 );
  QString request = serverSplit.at( 1 );
  QStringList parameterSplit = request.split( "&" );
  QString coverageName;
  QString format;
  for ( int i = 0; i < parameterSplit.size(); ++i )
  {
    if ( parameterSplit.at( i ).startsWith( "COVERAGE", Qt::CaseInsensitive ) )
    {
      coverageName = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
    else if ( parameterSplit.at( i ).startsWith( "FORMAT", Qt::CaseInsensitive ) )
    {
      format = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
  }

  if ( coverageName.isEmpty() )
  {
    QgsDebugMsg( "coverage name is empty" );
    return nullptr;
  }

  if ( format.isEmpty() )
  {
    format = "GeoTIFF"; //use geotiff as default
  }

  QgsDebugMsg( "wcs server url: " + serverUrl );
  QgsDebugMsg( "coverage name: " + coverageName );

  //fetch WCS layer in the current resolution as geotiff
  QString wcsRequest = serverUrl + "?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=" + coverageName + "&FORMAT=" + format;

  //CRS (or SRS)
  QString crs = mParameterMap.value( "CRS", mParameterMap.value( "SRS" ) );
  if ( crs.isEmpty() )
  {
    QgsDebugMsg( "No CRS or SRS parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&CRS=" + crs;

  //width
  QString width = mParameterMap.value( "WIDTH" );
  if ( width.isEmpty() )
  {
    QgsDebugMsg( "No WIDTH parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&WIDTH=" + width;

  //height
  QString height = mParameterMap.value( "HEIGHT" );
  if ( height.isEmpty() )
  {
    QgsDebugMsg( "No HEIGHT parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&HEIGHT=" + height;

  //bbox
  QString bbox = mParameterMap.value( "BBOX" );
  if ( bbox.isEmpty() )
  {
    QgsDebugMsg( "No BBOX parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&BBOX=" + bbox;

  QgsDebugMsg( "WCS request is: " + wcsRequest );
  //make request and store byte array into temporary file
  QgsHttpTransaction httpTransaction( wcsRequest );
  QByteArray result;
  if ( !httpTransaction.getSynchronously( result ) )
  {
    return nullptr;
  }

  QDataStream tempFileStream( &tempFile );
  tempFileStream.writeRawData( result.data(), result.size() );
  tempFile.close();

  QgsRasterLayer* rl = new QgsRasterLayer( fileName, layerNameFromUri( fileName ) );
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
#else
  Q_UNUSED( url )
  Q_UNUSED( filesToRemove )
  Q_UNUSED( layersToRemove )
  QgsDebugMsg( "remote http not supported with Qt5" );
  return nullptr;
#endif

}