CPLXMLNode *WCTSCollectRequest()

{
    if( getenv("REQUEST_METHOD") == NULL )
        WCTSEmitServiceException( "REQUEST_METHOD not set." );

    if( EQUAL(getenv("REQUEST_METHOD"),"GET") )
        return WCTSCollectKVPRequest();

/* -------------------------------------------------------------------- */
/*      Read the body of the POST message into a buffer.                */
/* -------------------------------------------------------------------- */
    int nContentLength = 0;
    char *pszXML = NULL;

    if( getenv("CONTENT_LENGTH") != NULL )
    {
        nContentLength = atoi(getenv("CONTENT_LENGTH"));

        pszXML = (char *) CPLMalloc(nContentLength+1);
        
        if( (int) fread(pszXML, 1, nContentLength, stdin) < nContentLength )
            WCTSEmitServiceException( "POST body is short." );

        pszXML[nContentLength] = '\0';
    }

    else
    {
        int nXMLMax, nXMLLen=0;

        nXMLMax = 100;
        pszXML = (char *) CPLMalloc(nXMLMax);
        
        while( !feof(stdin) )
        {
            pszXML[nXMLLen++] = fgetc(stdin);
            if( nXMLLen == nXMLMax )
            {
                nXMLMax = nXMLMax * 2;
                pszXML = (char *) CPLRealloc(pszXML, nXMLMax);
            }
        }

        pszXML[nXMLLen] = '\0';
    }

/* -------------------------------------------------------------------- */
/*      Convert into an XML document.                                   */
/* -------------------------------------------------------------------- */
    CPLErrorReset();

    CPLXMLNode *psTree = CPLParseXMLString( pszXML );
    CPLFree( pszXML );

    if( CPLGetLastErrorType() == CE_Failure )
        WCTSEmitServiceException( CPLGetLastErrorMsg() );

    return psTree;
}
Exemple #2
0
/**********************************************************************
 *                   TABRawBinBlock::CommitAsDeleted()
 *
 * Commit current block to file using block type 4 (garbage block)
 *
 * Returns 0 if successful or -1 if an error happened, in which case
 * CPLError() will have been called.
 **********************************************************************/
int     TABRawBinBlock::CommitAsDeleted(GInt32 nNextBlockPtr)
{
    CPLErrorReset();

    if ( m_pabyBuf == nullptr )
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "CommitAsDeleted(): Block has not been initialized yet!");
        return -1;
    }

    /*-----------------------------------------------------------------
     * Create deleted block header
     *----------------------------------------------------------------*/
    GotoByteInBlock(0x000);
    WriteInt16(TABMAP_GARB_BLOCK);    // Block type code
    WriteInt32(nNextBlockPtr);

    int nStatus = CPLGetLastErrorType() == CE_Failure ? -1 : 0;

    /*-----------------------------------------------------------------
     * OK, call the base class to write the block to disk.
     *----------------------------------------------------------------*/
    if (nStatus == 0)
    {
#ifdef DEBUG_VERBOSE
        CPLDebug("MITAB", "Committing GARBAGE block to offset %d", m_nFileOffset);
#endif
        nStatus = TABRawBinBlock::CommitToFile();
        m_nSizeUsed = 0;
    }

    return nStatus;
}
/**********************************************************************
 *                   TABRawBinBlock::CommitAsDeleted()
 *
 * Commit current block to file using block type 4 (garbage block)
 *
 * Returns 0 if succesful or -1 if an error happened, in which case 
 * CPLError() will have been called.
 **********************************************************************/
int     TABRawBinBlock::CommitAsDeleted(GInt32 nNextBlockPtr)
{
    int nStatus = 0;

    CPLErrorReset();

    if ( m_pabyBuf == NULL )
    {
        CPLError(CE_Failure, CPLE_AssertionFailed, 
                 "CommitAsDeleted(): Block has not been initialized yet!");
        return -1;
    }

    /*-----------------------------------------------------------------
     * Create deleted block header
     *----------------------------------------------------------------*/
    GotoByteInBlock(0x000);
    WriteInt32(nNextBlockPtr);

    if( CPLGetLastErrorType() == CE_Failure )
        nStatus = CPLGetLastErrorNo();

    /*-----------------------------------------------------------------
     * OK, call the base class to write the block to disk.
     *----------------------------------------------------------------*/
    if (nStatus == 0)
        nStatus = TABRawBinBlock::CommitToFile();

    return nStatus;
}
Exemple #4
0
int IMapInfoFile::TestUtf8Capability() const
{
    const char* pszEncoding( GetEncoding() );
    if( strlen( pszEncoding ) == 0 )
    {
        return FALSE;
    }

    CPLClearRecodeWarningFlags();
    CPLErrorReset();

    CPLPushErrorHandler(CPLQuietErrorHandler);
    char* pszTest( CPLRecode( "test", GetEncoding(), CPL_ENC_UTF8 ) );
    CPLPopErrorHandler();

    if( pszTest == nullptr )
    {
        return FALSE;
    }

    CPLFree( pszTest );

    if( CPLGetLastErrorType() != 0 )
    {
        return FALSE;
    }

    return TRUE;
}
/**********************************************************************
 *                          E00WriteOpen()
 *
 * Try to open output file, and alloc/initialize a new E00WritePtr
 * handle.
 *
 * nComprLevel must be one of:
 *       E00_COMPR_NONE, E00_COMPR_PARTIAL or E00_COMPR_FULL
 *
 * Returns the new handle, or NULL if the file could not be opened.
 * E00WriteClose() will eventually have to be called to release 
 * the resources used by the new handle.
 **********************************************************************/
E00WritePtr  E00WriteOpen(const char *pszFname, int nComprLevel)
{
    E00WritePtr  psInfo = NULL;
    FILE        *fp;

    CPLErrorReset();

    /* Open the file 
     */
    fp = VSIFOpen(pszFname, "wt");
    if (fp == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed to open %s: %s", pszFname, strerror(errno));
        return NULL;
    }

    /* Allocate and initialize a E00ReadPtr handle.
     */
    psInfo = (E00WritePtr)CPLCalloc(1, sizeof(struct _E00WriteInfo));

    psInfo->fp = fp;
    psInfo->nComprLevel = nComprLevel;

    return psInfo;
}
void SpatialReference::setFromUserInput(std::string const& v)
{
    if (v.empty())
    {
        m_wkt.clear();
        return;
    }

    OGRSpatialReference srs(NULL);

    CPLErrorReset();
    const char* input = v.c_str();
    OGRErr err = srs.SetFromUserInput(const_cast<char *>(input));
    if (err != OGRERR_NONE)
    {
        std::ostringstream oss;
        std::string msg = CPLGetLastErrorMsg();
        if (msg.empty())
            msg = "(unknown reason)";
        oss << "Could not import coordinate system '" << input << "': " <<
            msg << ".";
        throw pdal_error(oss.str());
    }

    char *poWKT = 0;
    srs.exportToWkt(&poWKT);
    std::string tmp(poWKT);
    CPLFree(poWKT);
    setWKT(tmp);
}
GIntBig OGRESRIFeatureServiceLayer::GetFeatureCount( int bForce )
{
    GIntBig nFeatureCount = -1;
    if( m_poAttrQuery == NULL && m_poFilterGeom == NULL ) 
    {
        CPLString osNewURL = CPLURLAddKVP(poDS->GetURL(), "returnCountOnly", "true");
        CPLHTTPResult* pResult = NULL;
        CPLErrorReset();
        pResult = CPLHTTPFetch( osNewURL, NULL );
        if( pResult != NULL && pResult->nDataLen != 0 && CPLGetLastErrorNo() == 0 &&
            pResult->nStatus == 0 )
        {
            const char* pszCount = strstr((const char*)pResult->pabyData, "\"count\"");
            if( pszCount )
            {
                pszCount = strchr(pszCount, ':');
                if( pszCount )
                {
                    pszCount++;
                    nFeatureCount = CPLAtoGIntBig(pszCount);
                }
            }
        }
        CPLHTTPDestroyResult( pResult );
    }
    if( nFeatureCount < 0 )
        nFeatureCount = OGRLayer::GetFeatureCount(bForce);
    return nFeatureCount;
}
OGRErr OGRESRIFeatureServiceLayer::GetExtent(OGREnvelope *psExtent, int bForce)
{
    OGRErr eErr = OGRERR_FAILURE;
    CPLString osNewURL = CPLURLAddKVP(poDS->GetURL(), "returnExtentOnly", "true");
    osNewURL = CPLURLAddKVP(osNewURL, "f", "geojson");
    CPLErrorReset();
    CPLHTTPResult* pResult = CPLHTTPFetch( osNewURL, NULL );
    if( pResult != NULL && pResult->nDataLen != 0 && CPLGetLastErrorNo() == 0 &&
        pResult->nStatus == 0 )
    {
        const char* pszBBox = strstr((const char*)pResult->pabyData, "\"bbox\"");
        if( pszBBox )
        {
            pszBBox = strstr(pszBBox, ":[");
            if( pszBBox )
            {
                pszBBox+=2;
                char** papszTokens = CSLTokenizeString2(pszBBox, ",", 0);
                if( CSLCount(papszTokens) >= 4 )
                {
                    psExtent->MinX = CPLAtof(papszTokens[0]);
                    psExtent->MinY = CPLAtof(papszTokens[1]);
                    psExtent->MaxX = CPLAtof(papszTokens[2]);
                    psExtent->MaxY = CPLAtof(papszTokens[3]);
                    eErr = OGRERR_NONE;
                }
                CSLDestroy(papszTokens);
            }
        }
    }
    CPLHTTPDestroyResult( pResult );
    if( eErr == OGRERR_FAILURE )
        eErr = OGRLayer::GetExtent(psExtent, bForce);
    return eErr;
}
OGRFieldType GeoJSONStringPropertyToFieldType( json_object* poObject )
{
    if (poObject == NULL) {
        return OFTString;
    }
    const char* pszStr = json_object_get_string( poObject );

    OGRField sWrkField;
    CPLPushErrorHandler(CPLQuietErrorHandler);
    int bSuccess = OGRParseDate( pszStr, &sWrkField, 0 );
    CPLPopErrorHandler();
    CPLErrorReset();
    if( bSuccess )
    {
        int bHasDate = strchr( pszStr, '/' ) != NULL ||
                       strchr( pszStr, '-' ) != NULL;
        int bHasTime = strchr( pszStr, ':' ) != NULL;
        if( bHasDate && bHasTime )
            return OFTDateTime;
        else if( bHasDate )
            return OFTDate;
        else
            return OFTTime;
    }
    return OFTString;
}
Exemple #10
0
/**********************************************************************
 *                   TABSeamless::OpenNextBaseTable()
 *
 * Open the next base table in the dataset, using GetNextFeature() so that
 * the spatial filter is respected.
 *
 * m_bEOF will be set if there are no more base tables to read.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::OpenNextBaseTable(GBool bTestOpenNoError /*=FALSE*/)
{
    CPLAssert(m_poIndexTable);

    TABFeature *poIndexFeature = (TABFeature*)m_poIndexTable->GetNextFeature();
    
    if (poIndexFeature)
    {
        if (OpenBaseTable(poIndexFeature, bTestOpenNoError) != 0)
        {
            // Open Failed... an error has already been reported.
            if (bTestOpenNoError)
                CPLErrorReset();
            delete poIndexFeature;
            return -1;
        }
        delete poIndexFeature;
        m_bEOF = FALSE;
    }
    else
    {
        // Reached EOF
        m_bEOF = TRUE;
    }

    return 0;
}
Exemple #11
0
/**********************************************************************
 *                          E00ReadOpen()
 *
 * Try to open a E00 file given its filename and return a E00ReadPtr handle.
 *
 * Returns NULL if the file could not be opened or if it does not 
 * appear to be a valid E00 file.
 **********************************************************************/
E00ReadPtr  E00ReadOpen(const char *pszFname)
{
    E00ReadPtr  psInfo = NULL;
    FILE        *fp;

     CPLErrorReset();

    /* Open the file 
     */

    fp = VSIFOpen(pszFname, "rt");
    if (fp == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed to open %s: %s", pszFname, strerror(errno));
        return NULL;
    }

    /* File was succesfully opened, allocate and initialize a 
     * E00ReadPtr handle and check that the file is valid.
     */
    psInfo = (E00ReadPtr)CPLCalloc(1, sizeof(struct _E00ReadInfo));

    psInfo->fp = fp;

    psInfo = _E00ReadTestOpen(psInfo);

    if (psInfo == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "%s is not a valid E00 file.", pszFname);
    }

    return psInfo;
}
Exemple #12
0
/**********************************************************************
 *                          E00WriteCallbackOpen()
 *
 * This is an alternative to E00WriteOpen() for cases where you want to
 * do all the file management yourself.  You open/close the file yourself
 * and provide a callback functions to write one line at a time to the
 * file.  pRefData is your handle on the physical file and can
 * be whatever you want... it is not used by the library, it will be
 * passed directly to your callback function when it is called.
 *
 * The callback function must have the following C prototype:
 *
 *   int    myWriteNextLine(void *pRefData, const char *pszLine);
 *
 *   Like printf() does, myWriteNextLine() should return a positive 
 *   value on success (the number of chars written) 
 *   or -1 if an error happened.
 *   The value passed by the library in pszLine will not be terminated
 *   by a '\n' character... it is assumed that the myWriteNextLine()
 *   implementation will take care of terminating the line with a
 *   '\n' if necessary.
 *
 * nComprLevel must be one of:
 *       E00_COMPR_NONE, E00_COMPR_PARTIAL or E00_COMPR_FULL
 *
 * E00WriteCallbackOpen() returns a new E00ReadWritePtr handle.
 * E00WriteClose() will eventually have to be called to release 
 * the resources used by the new handle.
 **********************************************************************/
E00WritePtr  E00WriteCallbackOpen(void *pRefData,
                                 int (*pfnWriteNextLine)(void *, const char *),
                                 int nComprLevel)
{
    E00WritePtr  psInfo = NULL;

    CPLErrorReset();

    /* Make sure we received a valid function pointer
     */
    if (pfnWriteNextLine == NULL)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "Invalid function pointer!");
        return NULL;
    }

    /* Allocate and initialize a E00ReadPtr handle.
     */
    psInfo = (E00WritePtr)CPLCalloc(1, sizeof(struct _E00WriteInfo));

    psInfo->pRefData = pRefData;
    psInfo->pfnWriteNextLine = pfnWriteNextLine;
    psInfo->nComprLevel = nComprLevel;

    return psInfo;
}
Exemple #13
0
void QgsNewOgrConnection::testConnection()
{
  QString uri;
  uri = createDatabaseURI( cmbDatabaseTypes->currentText(),
                           txtHost->text(),
                           txtDatabase->text(),
                           txtPort->text(),
                           mAuthSettingsDatabase->configId(),
                           mAuthSettingsDatabase->username(),
                           mAuthSettingsDatabase->password(),
                           true );
  QgsDebugMsg( "Connecting using uri = " + uri );
  OGRRegisterAll();
  OGRDataSourceH       poDS;
  OGRSFDriverH         pahDriver;
  CPLErrorReset();
  poDS = OGROpen( uri.toUtf8().constData(), false, &pahDriver );
  if ( !poDS )
  {
    QMessageBox::information( this, tr( "Test Connection" ), tr( "Connection failed - Check settings and try again.\n\nExtended error information:\n%1" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
  }
  else
  {
    QMessageBox::information( this, tr( "Test Connection" ), tr( "Connection to %1 was successful." ).arg( uri ) );
    OGRReleaseDataSource( poDS );
  }
}
void OGRESRIJSONReader::ReadLayers( OGRGeoJSONDataSource* poDS,
                                    GeoJSONSourceType eSourceType )
{
    CPLAssert( nullptr == poLayer_ );

    if( nullptr == poGJObject_ )
    {
        CPLDebug( "ESRIJSON",
                  "Missing parsed ESRIJSON data. Forgot to call Parse()?" );
        return;
    }

    OGRSpatialReference* poSRS = OGRESRIJSONReadSpatialReference( poGJObject_ );

    const char* pszName = "ESRIJSON";
    if( eSourceType == eGeoJSONSourceFile )
    {
        pszName = poDS->GetDescription();
        if( STARTS_WITH_CI(pszName, "ESRIJSON:") )
            pszName += strlen("ESRIJSON:");
        pszName = CPLGetBasename(pszName);
    }

    auto eGeomType = OGRESRIJSONGetGeometryType(poGJObject_);
    if( eGeomType == wkbNone && poSRS != nullptr )
    {
        eGeomType = wkbUnknown;
    }

    poLayer_ = new OGRGeoJSONLayer( pszName, poSRS,
                                    eGeomType,
                                    poDS, nullptr );
    if( poSRS != nullptr )
        poSRS->Release();

    if( !GenerateLayerDefn() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Layer schema generation failed." );

        delete poLayer_;
        return;
    }

    OGRGeoJSONLayer *poThisLayer = ReadFeatureCollection( poGJObject_ );
    if( poThisLayer == nullptr )
    {
        delete poLayer_;
        return;
    }

    CPLErrorReset();

    poLayer_->DetectGeometryType();
    poDS->AddLayer(poLayer_);
}
CPLErr VRTSourcedRasterBand::XMLInit( CPLXMLNode * psTree, 
                                      const char *pszVRTPath )

{
    CPLErr eErr;

    eErr = VRTRasterBand::XMLInit( psTree, pszVRTPath );
    if( eErr != CE_None )
        return eErr;
    
/* -------------------------------------------------------------------- */
/*      Validate a bit.                                                 */
/* -------------------------------------------------------------------- */
    if( psTree == NULL || psTree->eType != CXT_Element
        || (!EQUAL(psTree->pszValue,"VRTSourcedRasterBand") 
            && !EQUAL(psTree->pszValue,"VRTRasterBand")
	    && !EQUAL(psTree->pszValue,"VRTDerivedRasterBand")) )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Invalid node passed to VRTSourcedRasterBand::XMLInit()." );
        return CE_Failure;
    }

/* -------------------------------------------------------------------- */
/*      Process sources.                                                */
/* -------------------------------------------------------------------- */
    CPLXMLNode  *psChild;
    VRTDriver *poDriver = (VRTDriver *) GDALGetDriverByName( "VRT" );
    
    for( psChild = psTree->psChild; 
         psChild != NULL && poDriver != NULL; 
         psChild = psChild->psNext)
    {
        VRTSource *poSource;

        if( psChild->eType != CXT_Element )
            continue;

        CPLErrorReset();
        poSource = poDriver->ParseSource( psChild, pszVRTPath );
        if( poSource != NULL )
            AddSource( poSource );
        else if( CPLGetLastErrorType() != CE_None )
            return CE_Failure;
    }

/* -------------------------------------------------------------------- */
/*      Done.                                                           */
/* -------------------------------------------------------------------- */
    if( nSources == 0 )
        CPLDebug( "VRT", "No valid sources found for band in VRT file:\n%s",
                  pszVRTPath );

    return CE_None;
}
Exemple #16
0
/**********************************************************************
 *                          E00ReadClose()
 *
 * Close input file and release any memory used by the E00ReadPtr.
 **********************************************************************/
void    E00ReadClose(E00ReadPtr psInfo)
{
    CPLErrorReset();

    if (psInfo)
    {
        if (psInfo->fp)
            VSIFClose(psInfo->fp);
        CPLFree(psInfo);
    }
}
Exemple #17
0
// *************************************************************
//		RemoveStyle()
// *************************************************************
bool OgrStyleHelper::RemoveStyle(GDALDataset* dataset, CStringW styleTableName, CStringW layerName, CStringW styleName)
{
	USES_CONVERSION;
	CStringW sql;
	sql.Format(L"DELETE FROM %s WHERE layername = '%s' AND stylename = '%s'", styleTableName, layerName, styleName);

	CPLErrorReset();
	OGRLayer* layer = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	return CPLGetLastErrorNo() == OGRERR_NONE;
}
OGRLayer * OGRCARTODBDataSource::ExecuteSQL( const char *pszSQLCommand,
                                        OGRGeometry *poSpatialFilter,
                                        const char *pszDialect )

{
    /* Skip leading spaces */
    while(*pszSQLCommand == ' ')
        pszSQLCommand ++;

/* -------------------------------------------------------------------- */
/*      Use generic implementation for recognized dialects              */
/* -------------------------------------------------------------------- */
    if( IsGenericSQLDialect(pszDialect) )
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                          poSpatialFilter,
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Special case DELLAYER: command.                                 */
/* -------------------------------------------------------------------- */
    if( EQUALN(pszSQLCommand,"DELLAYER:",9) )
    {
        const char *pszLayerName = pszSQLCommand + 9;

        while( *pszLayerName == ' ' )
            pszLayerName++;
        
        for( int iLayer = 0; iLayer < nLayers; iLayer++ )
        {
            if( EQUAL(papoLayers[iLayer]->GetName(), 
                      pszLayerName ))
            {
                DeleteLayer( iLayer );
                break;
            }
        }
        return NULL;
    }

    OGRCARTODBResultLayer* poLayer = new OGRCARTODBResultLayer( this, pszSQLCommand );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );

    CPLErrorReset();
    poLayer->GetLayerDefn();
    if( CPLGetLastErrorNo() != 0 )
    {
        delete poLayer;
        return NULL;
    }

    return poLayer;
}
OGRLayer * OGRWalkDataSource::ExecuteSQL( const char *pszSQLCommand,
                                          OGRGeometry *poSpatialFilter,
                                          const char *pszDialect )

{
/* -------------------------------------------------------------------- */
/*      Use generic implementation for recognized dialects              */
/* -------------------------------------------------------------------- */
    if( IsGenericSQLDialect(pszDialect) )
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                          poSpatialFilter,
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Execute normal SQL statement in Walk.                           */
/*      Table_name = Layer_name + Postfix                               */
/*      Postfix: "Features", "Annotations" or "Styles"                  */
/* -------------------------------------------------------------------- */
    CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );

    CPLDebug( "Walk", "ExecuteSQL(%s) called.", pszSQLCommand );
    poStmt->Append( pszSQLCommand );
    if( !poStmt->ExecuteSQL() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "%s", oSession.GetLastError() );
        delete poStmt;
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Are there result columns for this statement?                    */
/* -------------------------------------------------------------------- */
    if( poStmt->GetColCount() == 0 )
    {
        delete poStmt;
        CPLErrorReset();
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Create a results layer.  It will take ownership of the          */
/*      statement.                                                      */
/* -------------------------------------------------------------------- */
    OGRWalkSelectLayer *poLayer = NULL;

    poLayer = new OGRWalkSelectLayer( this, poStmt );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );

    return poLayer;
}
Exemple #20
0
static OGRLayer* GetLayerAndOverwriteIfNecessary(GDALDataset *poDstDS,
                                                 const char* pszNewLayerName,
                                                 int bOverwrite,
                                                 int* pbErrorOccured)
{
    if( pbErrorOccured )
        *pbErrorOccured = FALSE;

    /* GetLayerByName() can instanciate layers that would have been */
    /* 'hidden' otherwise, for example, non-spatial tables in a */
    /* Postgis-enabled database, so this apparently useless command is */
    /* not useless... (#4012) */
    CPLPushErrorHandler(CPLQuietErrorHandler);
    OGRLayer* poDstLayer = poDstDS->GetLayerByName(pszNewLayerName);
    CPLPopErrorHandler();
    CPLErrorReset();

    int iLayer = -1;
    if (poDstLayer != NULL)
    {
        int nLayerCount = poDstDS->GetLayerCount();
        for( iLayer = 0; iLayer < nLayerCount; iLayer++ )
        {
            OGRLayer        *poLayer = poDstDS->GetLayer(iLayer);
            if (poLayer == poDstLayer)
                break;
        }

        if (iLayer == nLayerCount)
            /* shouldn't happen with an ideal driver */
            poDstLayer = NULL;
    }

/* -------------------------------------------------------------------- */
/*      If the user requested overwrite, and we have the layer in       */
/*      question we need to delete it now so it will get recreated      */
/*      (overwritten).                                                  */
/* -------------------------------------------------------------------- */
    if( poDstLayer != NULL && bOverwrite )
    {
        if( poDstDS->DeleteLayer( iLayer ) != OGRERR_NONE )
        {
            fprintf( stderr,
                     "DeleteLayer() failed when overwrite requested.\n" );
            if( pbErrorOccured )
                *pbErrorOccured = TRUE;
        }
        poDstLayer = NULL;
    }

    return poDstLayer;
}
Exemple #21
0
GDALDatasetH gv_manager_get_dataset( GvManager *manager, const char * filename)

{
    int       i;
    GvDataset *ds;
    GDALDatasetH dataset;

    /*
     * Check for dataset in existing list of open files.  Note that our
     * filename check does not account for different possible names for
     * one dataset.
     */
    for( i = 0; i < manager->datasets->len; i++ )
    {
        ds = (GvDataset *) g_ptr_array_index(manager->datasets, i);

        if( EQUAL(GDALGetDescription(ds->dataset),filename) )
        {
            return ds->dataset;
        }
    }

    /*
     * Try to open the dataset, preferably with update access.  We don't
     * want to report update access errors so we supress error reporting
     * temporarily. 
     */
    
    CPLErrorReset();
    CPLPushErrorHandler( CPLQuietErrorHandler );
    dataset = GDALOpen( filename, GA_Update );
    CPLPopErrorHandler();

    if( dataset == NULL )
    {
        dataset = GDALOpen( filename, GA_ReadOnly );
    }

    if( dataset == NULL )
        return NULL;

    /* 
     * Add the dataset to the list of managed datasets. 
     */
    ds = g_new(GvDataset,1);
    ds->dataset = dataset;
    ds->rasters = g_new0(GvRaster *, GDALGetRasterCount(dataset));
    
    g_ptr_array_add( manager->datasets, ds );

    return dataset;
}
Exemple #22
0
/**********************************************************************
 *                   TABSeamless::OpenBaseTable()
 *
 * Open the base table for specified IndexFeature.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::OpenBaseTable(int nTableId, GBool bTestOpenNoError /*=FALSE*/)
{

    if (nTableId == -1)
    {
        // Open first table from dataset
        m_poIndexTable->ResetReading();
        if (OpenNextBaseTable(bTestOpenNoError) != 0)
        {
            // Open Failed... an error has already been reported.
            if (bTestOpenNoError)
                CPLErrorReset();
            return -1;
        }
    }
    else if (nTableId == m_nCurBaseTableId && m_poCurBaseTable != NULL)
    {
        // The right table is already opened.  Not much to do!
        m_poCurBaseTable->ResetReading();
        return 0;
    }
    else
    {
        TABFeature *poIndexFeature = m_poIndexTable->GetFeatureRef(nTableId);
    
        if (poIndexFeature)
        {
            if (OpenBaseTable(poIndexFeature, bTestOpenNoError) != 0)
            {
                // Open Failed... an error has already been reported.
                if (bTestOpenNoError)
                    CPLErrorReset();
                return -1;
            }
        }
    }

    return 0;
}
Exemple #23
0
SEXP
RGDAL_OpenDataset(SEXP filename, SEXP read_only, SEXP silent) {

  const char *fn = asString(filename);

  GDALAccess RWFlag;

  if (asLogical(read_only))
    RWFlag = GA_ReadOnly;
  else
    RWFlag = GA_Update;

/* Modification suggested by Even Rouault, 2009-08-08: */

  CPLErrorReset();
  if (asLogical(silent))
    CPLPushErrorHandler(CPLQuietErrorHandler);
  else
     installErrorHandler();

  GDALDataset *pDataset = (GDALDataset *) GDALOpen(fn, RWFlag);

  if (pDataset == NULL)
    error("%s\n", CPLGetLastErrorMsg());

  if (asLogical(silent))
    CPLPopErrorHandler();
  else
    uninstallErrorHandlerAndTriggerError();

/* Similarly to SWIG bindings, the following lines will cause
RGDAL_OpenDataset() to fail on - uncleared - errors even if pDataset is not
NULL. They could also be just removed. While pDataset != NULL, there's some
hope ;-) */

/*  CPLErr eclass = CPLGetLastErrorType();

  if (pDataset != NULL && eclass == CE_Failure) {
    GDALClose(pDataset);
    pDataset = NULL;
    __errorHandler(eclass, CPLGetLastErrorNo(), CPLGetLastErrorMsg());
  }*/


  SEXP sxpHandle = R_MakeExternalPtr((void *) pDataset,
				     mkChar("GDAL Dataset"),
				     R_NilValue);

  return(sxpHandle);

}
Exemple #24
0
/**********************************************************************
 *                          E00ReadNextLine()
 *
 * Return the next line of input from the E00 file or NULL if we reached EOF.
 *
 * Returns a reference to an internal buffer whose contents will be valid
 * only until the next call to this function.
 **********************************************************************/
const char *E00ReadNextLine(E00ReadPtr psInfo)
{
    const char *pszLine = NULL;
    char *pszPtr;

    CPLErrorReset();

    if (psInfo && !psInfo->bEOF)
    {
        if (!psInfo->bIsCompressed)
        {
            /* Uncompressed file... return line directly. 
             */
            _ReadNextSourceLine(psInfo);
            pszLine = psInfo->szInBuf;
        }
        else if (psInfo->bIsCompressed && psInfo->nInputLineNo == 0)
        {
            /* Header line in a compressed file... return line 
             * after replacing "EXP  1" with "EXP  0".  E00ReadOpen()
             * has already verified that this line starts with "EXP "
             */
            _ReadNextSourceLine(psInfo);
            if ( (pszPtr = strstr(psInfo->szInBuf, " 1")) != NULL)
                pszPtr[1] = '0';
            pszLine = psInfo->szInBuf;
        }
        else
        {
            if (psInfo->nInputLineNo == 1)
            {
                /* We just read the header line... reload the input buffer
                 */
                _ReadNextSourceLine(psInfo);
            }

            /* Uncompress the next line of input and return it 
             */
            pszLine = _UncompressNextLine(psInfo);
        }

        /* If we just reached EOF then make sure we don't add an extra
         * empty line at the end of the uncompressed oputput.
         */
        if (psInfo->bEOF && strlen(pszLine) == 0)
            pszLine = NULL;
    }

    return pszLine;
}
Exemple #25
0
OGRLayer * OGRODBCDataSource::ExecuteSQL( const char *pszSQLCommand,
                                          OGRGeometry *poSpatialFilter,
                                          const char *pszDialect )

{
/* -------------------------------------------------------------------- */
/*      Use generic implementation for recognized dialects              */
/* -------------------------------------------------------------------- */
    if( IsGenericSQLDialect(pszDialect) )
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                          poSpatialFilter,
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Execute statement.                                              */
/* -------------------------------------------------------------------- */
    CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );

    CPLDebug( "ODBC", "ExecuteSQL(%s) called.", pszSQLCommand );
    poStmt->Append( pszSQLCommand );
    if( !poStmt->ExecuteSQL() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "%s", oSession.GetLastError() );
        delete poStmt;
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Are there result columns for this statement?                    */
/* -------------------------------------------------------------------- */
    if( poStmt->GetColCount() == 0 )
    {
        delete poStmt;
        CPLErrorReset();
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Create a results layer.  It will take ownership of the          */
/*      statement.                                                      */
/* -------------------------------------------------------------------- */

    OGRODBCSelectLayer* poLayer = new OGRODBCSelectLayer( this, poStmt );

    if( poSpatialFilter != nullptr )
        poLayer->SetSpatialFilter( poSpatialFilter );

    return poLayer;
}
Exemple #26
0
// *************************************************************
//		SaveStyle()
// *************************************************************
bool OgrStyleHelper::SaveStyle(GDALDataset* dataset, CStringW xml, CStringW layerName, CStringW styleName)
{
	xml.Replace(L"\n", L"");
	xml.Replace(L"'", L"''''");
	if (xml.GetLength() == 0) return false;

	CStringW sql;
	sql.Format(L"INSERT INTO %s(layername, stylename, style) VALUES ('%s', '%s', '%s')", GetStyleTableName(layerName),
		layerName, styleName, xml);

	CPLErrorReset();
	OGRLayer* layer = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	return CPLGetLastErrorNo() == OGRERR_NONE;
}
OGRLayer * OGRGeomediaDataSource::ExecuteSQL( const char *pszSQLCommand,
                                          OGRGeometry *poSpatialFilter,
                                          const char *pszDialect )

{
/* -------------------------------------------------------------------- */
/*      Use generic imlplementation for OGRSQL dialect.                 */
/* -------------------------------------------------------------------- */
    if( pszDialect != NULL && EQUAL(pszDialect,"OGRSQL") )
        return OGRDataSource::ExecuteSQL( pszSQLCommand, 
                                          poSpatialFilter, 
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Execute statement.                                              */
/* -------------------------------------------------------------------- */
    CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );

    poStmt->Append( pszSQLCommand );
    if( !poStmt->ExecuteSQL() )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "%s", oSession.GetLastError() );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Are there result columns for this statement?                    */
/* -------------------------------------------------------------------- */
    if( poStmt->GetColCount() == 0 )
    {
        delete poStmt;
        CPLErrorReset();
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Create a results layer.  It will take ownership of the          */
/*      statement.                                                      */
/* -------------------------------------------------------------------- */
    OGRGeomediaSelectLayer *poLayer = NULL;
        
    poLayer = new OGRGeomediaSelectLayer( this, poStmt );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );
    
    return poLayer;
}
Exemple #28
0
// *************************************************************
//		CreateStyleTable()
// *************************************************************
int OgrStyleHelper::CreateStyleTable(GDALDataset* dataset, CStringW layerName)
{
	if (OgrHelper::IsPostGisDatasource(dataset))
	{
		CPLErrorReset();
		CStringW schemaName = GetDbSchemeName(layerName, true);
		CStringW sql;
		sql.Format(L"CREATE Table %s (StyleId serial primary key, LayerName varchar(128), StyleName varchar(128), Style text, CONSTRAINT layer_style_unique UNIQUE (LayerName,StyleName));", GetStyleTableName());
		OGRLayer* lyr = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
		return CPLGetLastErrorNo() == OGRERR_NONE ? tkNO_ERROR : tkOGR_FAILED_TO_CREATE_STYLE_TABLE;
	}
	else {
		return tkOGR_NO_STYLE_TABLE_CREATION;
	}
}
Exemple #29
0
/**********************************************************************
 *                          E00ReadRewind()
 *
 * Rewind the E00ReadPtr.  Allows to start another read pass on the 
 * input file.
 **********************************************************************/
void    E00ReadRewind(E00ReadPtr psInfo)
{
    CPLErrorReset();

    psInfo->szInBuf[0] = psInfo->szOutBuf[0] = '\0';
    psInfo->iInBufPtr = 0;

    psInfo->nInputLineNo = 0;

    if (psInfo->pfnReadRewind == NULL)
        VSIRewind(psInfo->fp);
    else
        psInfo->pfnReadRewind(psInfo->pRefData);

    psInfo->bEOF = 0;
}
Exemple #30
0
/**********************************************************************
 *                          E00WriteClose()
 *
 * Close output file and release any memory used by the E00WritePtr.
 **********************************************************************/
void    E00WriteClose(E00WritePtr psInfo)
{
    CPLErrorReset();

    if (psInfo)
    {
        /* Flush output buffer before closing file.
         */
        if (psInfo->iOutBufPtr > 0)
            _WriteNextCompressedLine(psInfo, 1);

        if (psInfo->fp)
            fclose(psInfo->fp);

        CPLFree(psInfo);
    }
}