Example #1
0
static CPLString CPLFindLocalXSD(const char* pszXSDFilename)
{
    CPLString osTmp;
    const char *pszSchemasOpenGIS
        = CPLGetConfigOption("GDAL_OPENGIS_SCHEMAS", NULL);
    if (pszSchemasOpenGIS != NULL)
    {
        int nLen = (int)strlen(pszSchemasOpenGIS);
        if (nLen > 0 && pszSchemasOpenGIS[nLen-1] == '/')
        {
            osTmp = pszSchemasOpenGIS;
            osTmp += pszXSDFilename;
        }
        else
        {
            osTmp = pszSchemasOpenGIS;
            osTmp += "/";
            osTmp += pszXSDFilename;
        }
    }
    else if ((pszSchemasOpenGIS = CPLFindFile( "gdal", "SCHEMAS_OPENGIS_NET" )) != NULL)
    {
        osTmp = pszSchemasOpenGIS;
        osTmp += "/";
        osTmp += pszXSDFilename;
    }

    VSIStatBufL sStatBuf;
    if( VSIStatExL(osTmp, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0 )
        return osTmp;
    return "";
}
Example #2
0
OGRErr OGRSpatialReference::importFromDict( const char *pszDictFile,
                                            const char *pszCode )

{
/* -------------------------------------------------------------------- */
/*      Find and open file.                                             */
/* -------------------------------------------------------------------- */
    CPLString osDictFile(pszDictFile);
    const char *pszFilename = CPLFindFile( "gdal", pszDictFile );
    if( pszFilename == nullptr )
        return OGRERR_UNSUPPORTED_SRS;

    VSILFILE *fp = VSIFOpenL( pszFilename, "rb" );
    if( fp == nullptr )
        return OGRERR_UNSUPPORTED_SRS;

/* -------------------------------------------------------------------- */
/*      Process lines.                                                  */
/* -------------------------------------------------------------------- */
    OGRErr eErr = OGRERR_UNSUPPORTED_SRS;
    const char *pszLine = nullptr;

    while( (pszLine = CPLReadLineL(fp)) != nullptr )

    {
        if( pszLine[0] == '#' )
            continue;

        if( STARTS_WITH_CI(pszLine, "include ") )
        {
            eErr = importFromDict( pszLine + 8, pszCode );
            if( eErr != OGRERR_UNSUPPORTED_SRS )
                break;
            continue;
        }

        if( strstr(pszLine, ",") == nullptr )
            continue;

        if( EQUALN(pszLine, pszCode, strlen(pszCode))
            && pszLine[strlen(pszCode)] == ',' )
        {
            const char *pszWKT = pszLine + strlen(pszCode)+1;

            eErr = importFromWkt( pszWKT );
            if( eErr == OGRERR_NONE && osDictFile.find("esri_") == 0 )
            {
                morphFromESRI();
            }
            break;
        }
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
    VSIFCloseL( fp );

    return eErr;
}
Example #3
0
const char * GDALDefaultCSVFilename( const char *pszBasename )

{
    static char         szPath[512];
    FILE    *fp = NULL;
    const char *pszResult;
    static int bFinderInitialized = FALSE;

    pszResult = CPLFindFile( "epsg_csv", pszBasename );

    if( pszResult != NULL )
        return pszResult;

    if( !bFinderInitialized )
    {
        bFinderInitialized = TRUE;

        if( CPLGetConfigOption("GEOTIFF_CSV",NULL) != NULL )
            CPLPushFinderLocation( CPLGetConfigOption("GEOTIFF_CSV",NULL));

        if( CPLGetConfigOption("GDAL_DATA",NULL) != NULL )
            CPLPushFinderLocation( CPLGetConfigOption("GDAL_DATA",NULL) );

        pszResult = CPLFindFile( "epsg_csv", pszBasename );

        if( pszResult != NULL )
            return pszResult;
    }

    if( (fp = fopen( "csv/horiz_cs.csv", "rt" )) != NULL )
    {
        sprintf( szPath, "csv/%s", pszBasename );
    }
    else
    {
        sprintf( szPath, "/usr/local/share/epsg_csv/%s", pszBasename );
        if( (fp = fopen( szPath, "rt" )) == NULL )
            strcpy( szPath, pszBasename );
    }

    if( fp != NULL )
        fclose( fp );

    return( szPath );
}
Example #4
0
OGRErr OGRSpatialReference::importFromDict( const char *pszDictFile, 
                                            const char *pszCode )

{
    const char *pszFilename;
    FILE *fp;
    OGRErr eErr = OGRERR_UNSUPPORTED_SRS;

/* -------------------------------------------------------------------- */
/*      Find and open file.                                             */
/* -------------------------------------------------------------------- */
    pszFilename = CPLFindFile( "gdal", pszDictFile );
    if( pszFilename == NULL )
        return OGRERR_UNSUPPORTED_SRS;

    fp = VSIFOpen( pszFilename, "rb" );
    if( fp == NULL )
        return OGRERR_UNSUPPORTED_SRS;

/* -------------------------------------------------------------------- */
/*      Process lines.                                                  */
/* -------------------------------------------------------------------- */
    const char *pszLine;

    while( (pszLine = CPLReadLine(fp)) != NULL )

    {
        if( pszLine[0] == '#' )
            /* do nothing */;

        else if( EQUALN(pszLine,"include ",8) )
        {
            eErr = importFromDict( pszLine + 8, pszCode );
            if( eErr != OGRERR_UNSUPPORTED_SRS )
                break;
        }

        else if( strstr(pszLine,",") == NULL )
            /* do nothing */;

        else if( EQUALN(pszLine,pszCode,strlen(pszCode))
                 && pszLine[strlen(pszCode)] == ',' )
        {
            char *pszWKT = (char *) pszLine + strlen(pszCode)+1;

            eErr = importFromWkt( &pszWKT );
            break;
        }
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
    VSIFClose( fp );
    
    return eErr;
}
Example #5
0
void WCTSGetCapabilities( CPLXMLNode *psOperation )

{
/* -------------------------------------------------------------------- */
/*      Verify the service.                                             */
/* -------------------------------------------------------------------- */
    if( !EQUAL(CPLGetXMLValue(psOperation,"service","WCTS"),"WCTS") )
    {
        WCTSEmitServiceException( 
            CPLSPrintf( "Attempt to GetCapabilities for unsupported '%.500s'\n"
                        "service.  Only WCTS supported.",
                        CPLGetXMLValue(psOperation,"service","WCTS") ) );
    }

/* -------------------------------------------------------------------- */
/*      Search for our capabilities document.                           */
/* -------------------------------------------------------------------- */
    const char *pszCapFilename;
    FILE *fp;

    pszCapFilename = CPLFindFile( "gdal", "wcts_capabilities.xml.0.1.0" );

    if( pszCapFilename == NULL 
        || (fp = VSIFOpen( pszCapFilename, "rt")) == NULL )
    {
        WCTSEmitServiceException( "WCTS server misconfigured, "
                                  "unable to find capabilities document." );
    }

/* -------------------------------------------------------------------- */
/*      Emit the document.                                              */
/* -------------------------------------------------------------------- */
    int nLen;
    char *pszDoc;

    VSIFSeek( fp, 0, SEEK_END );
    nLen = VSIFTell( fp );
    VSIFSeek( fp, 0, SEEK_SET );
    
    pszDoc = (char *) CPLMalloc(nLen);
    VSIFRead( pszDoc, 1, nLen, fp );
    VSIFClose( fp );

    printf( "Content-type: text/xml%c%c", 10, 10 );

    VSIFWrite( pszDoc, 1, nLen, stdout );
    fflush( stdout );

    CPLFree( pszDoc );

    exit( 0 );
}
Example #6
0
int S57ClassRegistrar::FindFile( const char *pszTarget,
                                 const char *pszDirectory,
                                 int bReportErr,
                                 VSILFILE **pfp )

{
    const char *pszFilename;

    if( pszDirectory == NULL )
    {
        pszFilename = CPLFindFile( "s57", pszTarget );
        if( pszFilename == NULL )
            pszFilename = pszTarget;
    }
    else
    {
        pszFilename = CPLFormFilename( pszDirectory, pszTarget, NULL );
    }

    *pfp = VSIFOpenL( pszFilename, "rb" );

#ifdef S57_BUILTIN_CLASSES
    if( *pfp == NULL )
    {
        if( EQUAL(pszTarget, "s57objectclasses.csv") )
            papszNextLine = gpapszS57Classes;
        else
            papszNextLine = gpapszS57attributes;
    }
#else
    if( *pfp == NULL )
    {
        if( bReportErr )
            CPLError( CE_Failure, CPLE_OpenFailed,
                      "Failed to open %s.\n",
                      pszFilename );
        return FALSE;
    }
#endif

    return TRUE;
}
Example #7
0
bool GMLRegistry::Parse()
{
    if( osRegistryPath.empty() )
    {
        const char *pszFilename = CPLFindFile("gdal", "gml_registry.xml");
        if( pszFilename )
            osRegistryPath = pszFilename;
    }
    if( osRegistryPath.empty() )
        return false;
    CPLXMLNode *psRootNode = CPLParseXMLFile(osRegistryPath);
    if( psRootNode == NULL )
        return false;
    CPLXMLNode *psRegistryNode = CPLGetXMLNode(psRootNode, "=gml_registry");
    if( psRegistryNode == NULL )
    {
        CPLDestroyXMLNode(psRootNode);
        return false;
    }
    CPLXMLNode *psIter = psRegistryNode->psChild;
    while( psIter != NULL )
    {
        if( psIter->eType == CXT_Element &&
            strcmp(psIter->pszValue, "namespace") == 0 )
        {
            GMLRegistryNamespace oNameSpace;
            if( oNameSpace.Parse(osRegistryPath, psIter) )
            {
                aoNamespaces.push_back(oNameSpace);
            }
        }
        psIter = psIter->psNext;
    }
    CPLDestroyXMLNode(psRootNode);
    return true;
}
OGRLayer *OGRDGNDataSource::CreateLayer( const char *pszLayerName, 
                                         OGRSpatialReference *poSRS, 
                                         OGRwkbGeometryType eGeomType, 
                                         char **papszExtraOptions )

{
    const char *pszSeed, *pszMasterUnit = "m", *pszSubUnit = "cm";
    const char *pszValue;
    int nUORPerSU=1, nSUPerMU=100;
    int nCreationFlags = 0, b3DRequested;
    double dfOriginX = -21474836.0,  /* default origin centered on zero */
           dfOriginY = -21474836.0,  /* with two decimals of precision */
           dfOriginZ = -21474836.0;

/* -------------------------------------------------------------------- */
/*      Ensure only one layer gets created.                             */
/* -------------------------------------------------------------------- */
    if( nLayers > 0 )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "DGN driver only supports one layer will all the elements in it." );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      If the coordinate system is geographic, we should use a         */
/*      localized default origin and resolution.                        */
/* -------------------------------------------------------------------- */
    if( poSRS != NULL && poSRS->IsGeographic() )
    {
        dfOriginX = -200.0;
        dfOriginY = -200.0;
        
        pszMasterUnit = "d";
        pszSubUnit = "s";
        nSUPerMU = 3600;
        nUORPerSU = 1000;
    }

/* -------------------------------------------------------------------- */
/*      Parse out various creation options.                             */
/* -------------------------------------------------------------------- */
    CSLInsertStrings( papszOptions, 0, papszExtraOptions );

    b3DRequested = CSLFetchBoolean( papszOptions, "3D", 
                                    (((int) eGeomType) & wkb25DBit) );

    pszSeed = CSLFetchNameValue( papszOptions, "SEED" );
    if( pszSeed )
        nCreationFlags |= DGNCF_USE_SEED_ORIGIN | DGNCF_USE_SEED_UNITS;
    else if( b3DRequested )
        pszSeed = CPLFindFile( "gdal", "seed_3d.dgn" );
    else
        pszSeed = CPLFindFile( "gdal", "seed_2d.dgn" );

    if( pszSeed == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "No seed file provided, and unable to find seed_2d.dgn." );
        return NULL;
    }
    
    if( CSLFetchBoolean( papszOptions, "COPY_WHOLE_SEED_FILE", TRUE ) )
        nCreationFlags |= DGNCF_COPY_WHOLE_SEED_FILE;
    if( CSLFetchBoolean( papszOptions, "COPY_SEED_FILE_COLOR_TABLE", TRUE ) )
        nCreationFlags |= DGNCF_COPY_SEED_FILE_COLOR_TABLE;
    
    pszValue = CSLFetchNameValue( papszOptions, "MASTER_UNIT_NAME" );
    if( pszValue != NULL )
    {
        nCreationFlags &= ~DGNCF_USE_SEED_UNITS;
        pszMasterUnit = pszValue;
    }
    
    pszValue = CSLFetchNameValue( papszOptions, "SUB_UNIT_NAME" );
    if( pszValue != NULL )
    {
        nCreationFlags &= ~DGNCF_USE_SEED_UNITS;
        pszSubUnit = pszValue;
    }


    pszValue = CSLFetchNameValue( papszOptions, "SUB_UNITS_PER_MASTER_UNIT" );
    if( pszValue != NULL )
    {
        nCreationFlags &= ~DGNCF_USE_SEED_UNITS;
        nSUPerMU = atoi(pszValue);
    }

    pszValue = CSLFetchNameValue( papszOptions, "UOR_PER_SUB_UNIT" );
    if( pszValue != NULL )
    {
        nCreationFlags &= ~DGNCF_USE_SEED_UNITS;
        nUORPerSU = atoi(pszValue);
    }

    pszValue = CSLFetchNameValue( papszOptions, "ORIGIN" );
    if( pszValue != NULL )
    {
        char **papszTuple = CSLTokenizeStringComplex( pszValue, " ,", 
                                                      FALSE, FALSE );

        nCreationFlags &= ~DGNCF_USE_SEED_ORIGIN;
        if( CSLCount(papszTuple) == 3 )
        {
            dfOriginX = atof(papszTuple[0]);
            dfOriginY = atof(papszTuple[1]);
            dfOriginZ = atof(papszTuple[2]);
        }
        else if( CSLCount(papszTuple) == 2 )
        {
            dfOriginX = atof(papszTuple[0]);
            dfOriginY = atof(papszTuple[1]);
            dfOriginZ = 0.0;
        }
        else
        {
            CSLDestroy(papszTuple);
            CPLError( CE_Failure, CPLE_AppDefined, 
                      "ORIGIN is not a valid 2d or 3d tuple.\n"
                      "Separate tuple values with comma." );
            return FALSE;
        }
        CSLDestroy(papszTuple);
    }

/* -------------------------------------------------------------------- */
/*      Try creating the base file.                                     */
/* -------------------------------------------------------------------- */
    hDGN = DGNCreate( pszName, pszSeed, nCreationFlags, 
                      dfOriginX, dfOriginY, dfOriginZ, 
                      nSUPerMU, nUORPerSU, pszMasterUnit, pszSubUnit );
    if( hDGN == NULL )
        return NULL;

/* -------------------------------------------------------------------- */
/*      Create the layer object.                                        */
/* -------------------------------------------------------------------- */
    OGRDGNLayer *poLayer;

    poLayer = new OGRDGNLayer( pszLayerName, hDGN, TRUE );

/* -------------------------------------------------------------------- */
/*      Add layer to data source layer list.                            */
/* -------------------------------------------------------------------- */
    papoLayers = (OGRDGNLayer **)
        CPLRealloc( papoLayers,  sizeof(OGRDGNLayer *) * (nLayers+1) );
    papoLayers[nLayers++] = poLayer;
    
    return poLayer;
}
Example #9
0
int OGRDXFWriterDS::Open( const char * pszFilename, char **papszOptions )

{
/* -------------------------------------------------------------------- */
/*      Open the standard header, or a user provided header.            */
/* -------------------------------------------------------------------- */
    if( CSLFetchNameValue(papszOptions,"HEADER") != NULL )
        osHeaderFile = CSLFetchNameValue(papszOptions,"HEADER");
    else
    {
        const char *pszValue = CPLFindFile( "gdal", "header.dxf" );
        if( pszValue == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                      "Failed to find template header file header.dxf for reading,\nis GDAL_DATA set properly?" );
            return FALSE;
        }
        osHeaderFile = pszValue;
    }

/* -------------------------------------------------------------------- */
/*      Establish the name for our trailer file.                        */
/* -------------------------------------------------------------------- */
    if( CSLFetchNameValue(papszOptions,"TRAILER") != NULL )
        osTrailerFile = CSLFetchNameValue(papszOptions,"TRAILER");
    else
    {
        const char *pszValue = CPLFindFile( "gdal", "trailer.dxf" );
        if( pszValue != NULL )
            osTrailerFile = pszValue;
    }

/* -------------------------------------------------------------------- */
/*      What entity id do we want to start with when writing?  Small    */
/*      values run a risk of overlapping some undetected entity in      */
/*      the header or trailer despite the prescanning we do.            */
/* -------------------------------------------------------------------- */
#ifdef DEBUG
    nNextFID = 80;
#else
    nNextFID = 131072;
#endif

    if( CSLFetchNameValue( papszOptions, "FIRST_ENTITY" ) != NULL )
        nNextFID = atoi(CSLFetchNameValue( papszOptions, "FIRST_ENTITY" ));

/* -------------------------------------------------------------------- */
/*      Prescan the header and trailer for entity codes.                */
/* -------------------------------------------------------------------- */
    ScanForEntities( osHeaderFile, "HEADER" );
    ScanForEntities( osTrailerFile, "TRAILER" );

/* -------------------------------------------------------------------- */
/*      Attempt to read the template header file so we have a list      */
/*      of layers, linestyles and blocks.                               */
/* -------------------------------------------------------------------- */
    if( !oHeaderDS.Open( osHeaderFile, TRUE ) )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Create the output file.                                         */
/* -------------------------------------------------------------------- */
    fp = VSIFOpenExL( pszFilename, "w+", true );

    if( fp == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Failed to open '%s' for writing: %s",
                  pszFilename, VSIGetLastErrorMsg() );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Establish the temporary file.                                   */
/* -------------------------------------------------------------------- */
    osTempFilename = pszFilename;
    osTempFilename += ".tmp";

    fpTemp = VSIFOpenL( osTempFilename, "w" );
    if( fpTemp == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Failed to open '%s' for writing.",
                  osTempFilename.c_str() );
        return FALSE;
    }

    return TRUE;
}
int SearchCSVForWKT( const char *pszFileCSV, const char *pszTarget )
{
    const char *pszFilename = NULL;
    const char *pszWKT = NULL;
    char szTemp[1024];
    int nPos = 0;
    const char *pszTemp = NULL;

    VSILFILE *fp = NULL;
    OGRSpatialReference oSRS;
    int nCode = 0;
    int nFound = -1;

    CPLDebug( "gdalsrsinfo", 
              "SearchCSVForWKT()\nfile=%s\nWKT=%s\n",
              pszFileCSV, pszTarget);

/* -------------------------------------------------------------------- */
/*      Find and open file.                                             */
/* -------------------------------------------------------------------- */
    // pszFilename = pszFileCSV;
    pszFilename = CPLFindFile( "gdal", pszFileCSV );
    if( pszFilename == NULL )
    {
        CPLDebug( "gdalsrsinfo", "could not find support file %s",
                   pszFileCSV );
        // return OGRERR_UNSUPPORTED_SRS;
        return -1;
    }

    /* support gzipped file */
    if ( strstr( pszFileCSV,".gz") != NULL )
        sprintf( szTemp, "/vsigzip/%s", pszFilename);
    else
        sprintf( szTemp, "%s", pszFilename);

    CPLDebug( "gdalsrsinfo", "SearchCSVForWKT() using file %s",
              szTemp );

    fp = VSIFOpenL( szTemp, "r" );
    if( fp == NULL ) 
    {
        CPLDebug( "gdalsrsinfo", "could not open support file %s",
                  pszFilename );

        // return OGRERR_UNSUPPORTED_SRS;
        return -1;
    }

/* -------------------------------------------------------------------- */
/*      Process lines.                                                  */
/* -------------------------------------------------------------------- */
    const char *pszLine;

    while( (pszLine = CPLReadLine2L(fp,-1,NULL)) != NULL )

    {
        // CPLDebug( "gdalsrsinfo", "read line %s", pszLine );

        if( pszLine[0] == '#' )
            continue;
            /* do nothing */;

        // else if( EQUALN(pszLine,"include ",8) )
        // {
        //     eErr = importFromDict( pszLine + 8, pszCode );
        //     if( eErr != OGRERR_UNSUPPORTED_SRS )
        //         break;
        // }

        // else if( strstr(pszLine,",") == NULL )
        //     /* do nothing */;

        pszTemp = strstr(pszLine,",");
        if (pszTemp)
        {
            nPos = pszTemp - pszLine;

            if ( nPos == 0 )
                continue;
            
            strncpy( szTemp, pszLine, nPos );
            szTemp[nPos] = '\0';
            nCode = atoi(szTemp);

            pszWKT = (char *) pszLine + nPos +1;

            // CPLDebug( "gdalsrsinfo", 
            //           "code=%d\nWKT=\n[%s]\ntarget=\n[%s]\n",
            //           nCode,pszWKT, pszTarget );

            if ( EQUAL(pszTarget,pszWKT) )
            {
                nFound = nCode;
                CPLDebug( "gdalsrsinfo", "found EPSG:%d\n"
                          "current=%s\ntarget= %s\n",
                          nCode, pszWKT, pszTarget );
                break;
            }
        }
    }
    
    VSIFCloseL( fp );

    return nFound;

}
int OGRDXFWriterDS::Open( const char * pszFilename, char **papszOptions )

{
/* -------------------------------------------------------------------- */
/*      Open the standard header, or a user provided header.            */
/* -------------------------------------------------------------------- */
    CPLString osHeaderFile;

    if( CSLFetchNameValue(papszOptions,"HEADER") != NULL )
        osHeaderFile = CSLFetchNameValue(papszOptions,"HEADER");
    else
    {
        const char *pszValue = CPLFindFile( "gdal", "header.dxf" );
        if( pszValue == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed, 
                      "Failed to find template header file header.dxf for reading,\nis GDAL_DATA set properly?" );
            return FALSE;
        }
        osHeaderFile = pszValue;
    }

/* -------------------------------------------------------------------- */
/*      Create the output file.                                         */
/* -------------------------------------------------------------------- */
    fp = VSIFOpenL( pszFilename, "w" );

    if( fp == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "Failed to open '%s' for writing.", 
                  pszFilename );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Open the template file.                                         */
/* -------------------------------------------------------------------- */
    FILE *fpSrc = VSIFOpenL( osHeaderFile, "r" );
    if( fpSrc == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "Failed to open template header file '%s' for reading.", 
                  osHeaderFile.c_str() );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Copy into our DXF file.                                         */
/* -------------------------------------------------------------------- */
    const char *pszLine;

    while( (pszLine = CPLReadLineL(fpSrc)) != NULL )
    {
        VSIFWriteL( pszLine, 1, strlen(pszLine), fp );
        VSIFWriteL( "\n", 1, 1, fp );
    }

    VSIFCloseL( fpSrc );

/* -------------------------------------------------------------------- */
/*      Establish the name for our trailer file.                        */
/* -------------------------------------------------------------------- */
    if( CSLFetchNameValue(papszOptions,"TRAILER") != NULL )
        osTrailerFile = CSLFetchNameValue(papszOptions,"TRAILER");
    else
    {
        const char *pszValue = CPLFindFile( "gdal", "trailer.dxf" );
        if( pszValue != NULL )
            osTrailerFile = pszValue;
    }

    return TRUE;
}
Example #12
0
const char * GDALDefaultCSVFilename( const char *pszBasename )

{
/* -------------------------------------------------------------------- */
/*      Do we already have this file accessed?  If so, just return      */
/*      the existing path without any further probing.                  */
/* -------------------------------------------------------------------- */
    CSVTable **ppsCSVTableList;

    ppsCSVTableList = (CSVTable **) CPLGetTLS( CTLS_CSVTABLEPTR );
    if( ppsCSVTableList != NULL )
    {
        CSVTable *psTable;
        int nBasenameLen = strlen(pszBasename);

        for( psTable = *ppsCSVTableList; 
             psTable != NULL; 
             psTable = psTable->psNext )
        {
            int nFullLen = strlen(psTable->pszFilename);

            if( nFullLen > nBasenameLen 
                && strcmp(psTable->pszFilename+nFullLen-nBasenameLen,
                          pszBasename) == 0 
                && strchr("/\\",psTable->pszFilename[+nFullLen-nBasenameLen-1])
                          != NULL )
            {
                return psTable->pszFilename;
            }
        }
    }
                
/* -------------------------------------------------------------------- */
/*      Otherwise we need to look harder for it.                        */
/* -------------------------------------------------------------------- */
    DefaultCSVFileNameTLS* pTLSData =
            (DefaultCSVFileNameTLS *) CPLGetTLS( CTLS_CSVDEFAULTFILENAME );
    if (pTLSData == NULL)
    {
        pTLSData = (DefaultCSVFileNameTLS*) CPLCalloc(1, sizeof(DefaultCSVFileNameTLS));
        CPLSetTLS( CTLS_CSVDEFAULTFILENAME, pTLSData, TRUE );
    }

    FILE    *fp = NULL;
    const char *pszResult;

    pszResult = CPLFindFile( "epsg_csv", pszBasename );

    if( pszResult != NULL )
        return pszResult;

    if( !pTLSData->bCSVFinderInitialized )
    {
        pTLSData->bCSVFinderInitialized = TRUE;

        if( CPLGetConfigOption("GEOTIFF_CSV",NULL) != NULL )
            CPLPushFinderLocation( CPLGetConfigOption("GEOTIFF_CSV",NULL));
            
        if( CPLGetConfigOption("GDAL_DATA",NULL) != NULL )
            CPLPushFinderLocation( CPLGetConfigOption("GDAL_DATA",NULL) );

        pszResult = CPLFindFile( "epsg_csv", pszBasename );

        if( pszResult != NULL )
            return pszResult;
    }
            
    if( (fp = fopen( "csv/horiz_cs.csv", "rt" )) != NULL )
    {
        strcpy( pTLSData->szPath, "csv/" );
        CPLStrlcat( pTLSData->szPath, pszBasename, sizeof(pTLSData->szPath) );
    }
    else
    {
#ifdef GDAL_PREFIX
  #ifdef MACOSX_FRAMEWORK
        strcpy( pTLSData->szPath, GDAL_PREFIX "/Resources/epsg_csv/" );
        CPLStrlcat( pTLSData->szPath, pszBasename, sizeof(pTLSData->szPath) );
  #else
        strcpy( pTLSData->szPath, GDAL_PREFIX "/share/epsg_csv/" );
        CPLStrlcat( pTLSData->szPath, pszBasename, sizeof(pTLSData->szPath) );
  #endif
#else
        strcpy( pTLSData->szPath, "/usr/local/share/epsg_csv/" );
        CPLStrlcat( pTLSData->szPath, pszBasename, sizeof(pTLSData->szPath) );
#endif
        if( (fp = fopen( pTLSData->szPath, "rt" )) == NULL )
            CPLStrlcpy( pTLSData->szPath, pszBasename, sizeof(pTLSData->szPath) );
    }

    if( fp != NULL )
        fclose( fp );
        
    return( pTLSData->szPath );
}
Example #13
0
bool GMLASConfiguration::Load(const char* pszFilename)
{
    // Allow configuration to be inlined
    CPLXMLNode* psRoot = STARTS_WITH(pszFilename, "<Configuration>") ?
                                CPLParseXMLString(pszFilename) :
                                CPLParseXMLFile(pszFilename);
    if( psRoot == NULL )
    {
        Finalize();
        return false;
    }
    CPLXMLTreeCloser oCloser(psRoot);

    // Validate the configuration file
    if( CPLTestBool(CPLGetConfigOption("GDAL_XML_VALIDATION", "YES")) )
    {
        const char* pszXSD = CPLFindFile( "gdal", "gmlasconf.xsd" );
        if( pszXSD != NULL )
        {
            std::vector<CPLString> aosErrors;
            const CPLErr eErrClass = CPLGetLastErrorType();
            const CPLErrorNum nErrNum = CPLGetLastErrorNo();
            const CPLString osErrMsg = CPLGetLastErrorMsg();
            CPLPushErrorHandlerEx(GMLASConfigurationErrorHandler, &aosErrors);
            int bRet = CPLValidateXML(pszFilename, pszXSD, NULL);
            CPLPopErrorHandler();
            if( !bRet && aosErrors.size() > 0 &&
                strstr(aosErrors[0].c_str(), "missing libxml2 support") == NULL )
            {
                for(size_t i = 0; i < aosErrors.size(); i++)
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "%s", aosErrors[i].c_str());
                }
            }
            else
            {
                CPLErrorSetState(eErrClass, nErrNum, osErrMsg);
            }
        }
    }

    m_bAllowRemoteSchemaDownload = CPLGetXMLBoolValue(psRoot,
                                "=Configuration.AllowRemoteSchemaDownload",
                                ALLOW_REMOTE_SCHEMA_DOWNLOAD_DEFAULT );

    m_bAllowXSDCache = CPLGetXMLBoolValue( psRoot,
                                           "=Configuration.SchemaCache.enabled",
                                           ALLOW_XSD_CACHE_DEFAULT );
    if( m_bAllowXSDCache )
    {
        m_osXSDCacheDirectory =
            CPLGetXMLValue(psRoot, "=Configuration.SchemaCache.Directory",
                           "");
    }

    m_bValidate = CPLGetXMLBoolValue( psRoot,
                                      "=Configuration.Validation.enabled",
                                      VALIDATE_DEFAULT );

    if( m_bValidate )
    {
        m_bFailIfValidationError = CPLGetXMLBoolValue(psRoot,
                                        "=Configuration.Validation.FailIfError",
                                        FAIL_IF_VALIDATION_ERROR_DEFAULT );
    }

    m_bExposeMetadataLayers = CPLGetXMLBoolValue( psRoot,
                                      "=Configuration.ExposeMetadataLayers",
                                      EXPOSE_METADATA_LAYERS_DEFAULT );

    m_bAlwaysGenerateOGRId = CPLGetXMLBoolValue( psRoot,
                                "=Configuration.LayerBuildingRules.AlwaysGenerateOGRId",
                                ALWAYS_GENERATE_OGR_ID_DEFAULT );

    m_bRemoveUnusedLayers = CPLGetXMLBoolValue( psRoot,
                                "=Configuration.LayerBuildingRules.RemoveUnusedLayers",
                                REMOVE_UNUSED_LAYERS_DEFAULT );

    m_bRemoveUnusedFields = CPLGetXMLBoolValue( psRoot,
                                "=Configuration.LayerBuildingRules.RemoveUnusedFields",
                                REMOVE_UNUSED_FIELDS_DEFAULT );

    m_bUseArrays = CPLGetXMLBoolValue( psRoot,
                                "=Configuration.LayerBuildingRules.UseArrays",
                                USE_ARRAYS_DEFAULT );
    m_bIncludeGeometryXML = CPLGetXMLBoolValue( psRoot,
                       "=Configuration.LayerBuildingRules.GML.IncludeGeometryXML",
                       INCLUDE_GEOMETRY_XML_DEFAULT );
    m_bInstantiateGMLFeaturesOnly = CPLGetXMLBoolValue( psRoot,
                "=Configuration.LayerBuildingRules.GML.InstantiateGMLFeaturesOnly",
                INSTANTIATE_GML_FEATURES_ONLY_DEFAULT );
    m_nIdentifierMaxLength = atoi( CPLGetXMLValue( psRoot,
                "=Configuration.LayerBuildingRules.IdentifierMaxLength",
                "0" ) );
    m_bCaseInsensitiveIdentifier = CPLGetXMLBoolValue( psRoot,
                "=Configuration.LayerBuildingRules.CaseInsensitiveIdentifier",
                CASE_INSENSITIVE_IDENTIFIER_DEFAULT );

    CPLXMLNode* psIgnoredXPaths = CPLGetXMLNode(psRoot,
                                            "=Configuration.IgnoredXPaths");
    if( psIgnoredXPaths )
    {
        const bool bGlobalWarnIfIgnoredXPathFound = CPLGetXMLBoolValue(
                       psIgnoredXPaths,
                       "WarnIfIgnoredXPathFoundInDocInstance",
                       WARN_IF_EXCLUDED_XPATH_FOUND_DEFAULT );

        CPLXMLNode* psNamespaces = CPLGetXMLNode(psIgnoredXPaths,
                                                 "Namespaces");
        if( psNamespaces != NULL )
        {
            for( CPLXMLNode* psIter = psNamespaces->psChild;
                             psIter != NULL;
                             psIter = psIter->psNext )
            {
                if( psIter->eType == CXT_Element &&
                    EQUAL(psIter->pszValue, "Namespace") )
                {
                    CPLString osPrefix = CPLGetXMLValue(psIter, "prefix", "");
                    CPLString osURI = CPLGetXMLValue(psIter, "uri", "");
                    if( !osPrefix.empty() && !osURI.empty() )
                    {
                        if( m_oMapPrefixToURIIgnoredXPaths.find(osPrefix) ==
                            m_oMapPrefixToURIIgnoredXPaths.end() )
                        {
                            m_oMapPrefixToURIIgnoredXPaths[osPrefix] = osURI;
                        }
                        else
                        {
                            CPLError(CE_Warning, CPLE_AppDefined,
                                     "Prefix %s was already mapped to %s. "
                                     "Attempt to map it to %s ignored",
                                     osPrefix.c_str(),
                                     m_oMapPrefixToURIIgnoredXPaths[osPrefix].
                                                                        c_str(),
                                     osURI.c_str());
                        }
                    }
                }
            }
        }

        for( CPLXMLNode* psIter = psIgnoredXPaths->psChild;
                         psIter != NULL;
                         psIter = psIter->psNext )
        {
            if( psIter->eType == CXT_Element &&
                EQUAL(psIter->pszValue, "XPath") )
            {
                const CPLString& osXPath( CPLGetXMLValue(psIter, "", "") );
                if( IsValidXPath(osXPath) )
                {
                    m_aosIgnoredXPaths.push_back( osXPath );

                    const bool bWarnIfIgnoredXPathFound = CPLGetXMLBoolValue(
                                psIter,
                                "warnIfIgnoredXPathFoundInDocInstance",
                                bGlobalWarnIfIgnoredXPathFound );
                    m_oMapIgnoredXPathToWarn[ osXPath ] = bWarnIfIgnoredXPathFound;
                }
                else
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "XPath syntax %s not supported",
                             osXPath.c_str());
                }
            }
        }
    }

    CPLXMLNode* psXLinkResolutionNode = CPLGetXMLNode( psRoot,
                                            "=Configuration.XLinkResolution");
    if( psXLinkResolutionNode != NULL )
        m_oXLinkResolution.LoadFromXML( psXLinkResolutionNode );

    Finalize();

    return true;
}
Example #14
0
OGRDataSource *OGRVRTDriver::Open( const char * pszFilename,
                                   int bUpdate )
{
    OGRVRTDataSource     *poDS;
    char *pszXML = NULL;

/* -------------------------------------------------------------------- */
/*      Are we being passed the XML definition directly?                */
/*      Skip any leading spaces/blanks.                                 */
/* -------------------------------------------------------------------- */
    const char *pszTestXML = pszFilename;
    while( *pszTestXML != '\0' && isspace( (unsigned char)*pszTestXML ) )
        pszTestXML++;

    if( EQUALN(pszTestXML,"<OGRVRTDataSource>",18) )
    {
        pszXML = CPLStrdup(pszTestXML);
    }

/* -------------------------------------------------------------------- */
/*      Open file and check if it contains appropriate XML.             */
/* -------------------------------------------------------------------- */
    else
    {
        VSILFILE *fp;
        char achHeader[512];

        fp = VSIFOpenL( pszFilename, "rb" );

        if( fp == NULL )
            return NULL;

        memset( achHeader, 0, sizeof(achHeader) );
        VSIFReadL( achHeader, 1, sizeof(achHeader)-1, fp );

        if( strstr(achHeader,"<OGRVRTDataSource") == NULL )
        {
            VSIFCloseL( fp );
            return NULL;
        }

        VSIStatBufL sStatBuf;
        if ( VSIStatL( pszFilename, &sStatBuf ) != 0 ||
             sStatBuf.st_size > 1024 * 1024 )
        {
            CPLDebug( "VRT", "Unreasonable long file, not likely really VRT" );
            VSIFCloseL( fp );
            return NULL;
        }

/* -------------------------------------------------------------------- */
/*      It is the right file, now load the full XML definition.         */
/* -------------------------------------------------------------------- */
        int nLen = (int) sStatBuf.st_size;

        VSIFSeekL( fp, 0, SEEK_SET );

        pszXML = (char *) VSIMalloc(nLen+1);
        if (pszXML == NULL)
        {
            VSIFCloseL( fp );
            return NULL;
        }
        pszXML[nLen] = '\0';
        if( ((int) VSIFReadL( pszXML, 1, nLen, fp )) != nLen )
        {
            CPLFree( pszXML );
            VSIFCloseL( fp );

            return NULL;
        }
        VSIFCloseL( fp );
    }

/* -------------------------------------------------------------------- */
/*      Parse the XML.                                                  */
/* -------------------------------------------------------------------- */
    CPLXMLNode *psTree = CPLParseXMLString( pszXML );

    if( psTree == NULL )
    {
        CPLFree( pszXML );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      XML Validation.                                                 */
/* -------------------------------------------------------------------- */
    if( CSLTestBoolean(CPLGetConfigOption("GDAL_XML_VALIDATION", "YES")) )
    {
        const char* pszXSD = CPLFindFile( "gdal", "ogrvrt.xsd" );
        if( pszXSD != NULL )
        {
            std::vector<CPLString> aosErrors;
            CPLPushErrorHandlerEx(OGRVRTErrorHandler, &aosErrors);
            int bRet = CPLValidateXML(pszXML, pszXSD, NULL);
            CPLPopErrorHandler();
            if( !bRet )
            {
                if( aosErrors.size() > 0 &&
                    strstr(aosErrors[0].c_str(), "missing libxml2 support") == NULL )
                {
                    for(size_t i = 0; i < aosErrors.size(); i++)
                    {
                        CPLError(CE_Warning, CPLE_AppDefined, "%s", aosErrors[i].c_str());
                    }
                }
            }
            CPLErrorReset();
        }
    }
    CPLFree( pszXML );

/* -------------------------------------------------------------------- */
/*      Create a virtual datasource configured based on this XML input. */
/* -------------------------------------------------------------------- */
    poDS = new OGRVRTDataSource();
    poDS->SetDriver(this);
    /* psTree is owned by poDS */
    if( !poDS->Initialize( psTree, pszFilename, bUpdate ) )
    {
        delete poDS;
        return NULL;
    }

    return poDS;
}
Example #15
0
static
xmlParserInputPtr CPLExternalEntityLoader (const char * URL,
        const char * ID,
        xmlParserCtxtPtr context)
{
    //CPLDebug("CPL", "CPLExternalEntityLoader(%s)", URL);
    CPLString osURL;

    /* Use libxml2 catalog mechanism to resolve the URL to something else */
    xmlChar* pszResolved = xmlCatalogResolveSystem((const xmlChar*)URL);
    if (pszResolved == NULL)
        pszResolved = xmlCatalogResolveURI((const xmlChar*)URL);
    if (pszResolved)
    {
        CPLDebug("CPL", "Resolving %s in %s", URL, (const char*)pszResolved );
        osURL = (const char*)pszResolved;
        URL = osURL.c_str();
        xmlFree(pszResolved);
        pszResolved = NULL;
    }

    if (STARTS_WITH(URL, "http://"))
    {
        /* Make sure to use http://schemas.opengis.net/ */
        /* when gml/2 or gml/3 is detected */
        const char* pszGML = strstr(URL, "gml/2");
        if (pszGML == NULL)
            pszGML = strstr(URL, "gml/3");
        if (pszGML != NULL)
        {
            osURL = "http://schemas.opengis.net/";
            osURL += pszGML;
            URL = osURL.c_str();
        }
        else if (strcmp(URL, "http://www.w3.org/2001/xml.xsd") == 0)
        {
            CPLString osTmp = CPLFindLocalXSD("xml.xsd");
            if( osTmp.size() != 0 )
            {
                osURL = osTmp;
                URL = osURL.c_str();
            }
            else
            {
                CPLDebug("CPL", "Resolving %s to local definition", "http://www.w3.org/2001/xml.xsd");
                return xmlNewStringInputStream(context, (const xmlChar*) szXML_XSD);
            }
        }
        else if (strcmp(URL, "http://www.w3.org/1999/xlink.xsd") == 0)
        {
            CPLString osTmp = CPLFindLocalXSD("xlink.xsd");
            if( osTmp.size() != 0 )
            {
                osURL = osTmp;
                URL = osURL.c_str();
            }
            else
            {
                CPLDebug("CPL", "Resolving %s to local definition", "http://www.w3.org/1999/xlink.xsd");
                return xmlNewStringInputStream(context, (const xmlChar*) szXLINK_XSD);
            }
        }
        else if (!STARTS_WITH(URL, "http://schemas.opengis.net/"))        {
            CPLDebug("CPL", "Loading %s", URL);
            return pfnLibXMLOldExtranerEntityLoader(URL, ID, context);
        }
    }
    else if (STARTS_WITH(URL, "ftp://"))
    {
        return pfnLibXMLOldExtranerEntityLoader(URL, ID, context);
    }
    else if (STARTS_WITH(URL, "file://"))
    {
        /* Parse file:// URI so as to be able to open them with VSI*L API */
        if (STARTS_WITH(URL, "file://localhost/"))
            URL += 16;
        else
            URL += 7;
        if (URL[0] == '/' && URL[1] != '\0' && URL[2] == ':' && URL[3] == '/') /* Windows */
            URL ++;
        else if (URL[0] == '/') /* Unix */
            ;
        else
            return pfnLibXMLOldExtranerEntityLoader(URL, ID, context);
    }

    CPLString osModURL;
    if (STARTS_WITH(URL, "/vsizip/vsicurl/http%3A//"))    {
        osModURL = "/vsizip/vsicurl/http://";
        osModURL += URL + strlen("/vsizip/vsicurl/http%3A//");
    }
    else if (STARTS_WITH(URL, "/vsicurl/http%3A//"))    {
        osModURL = "vsicurl/http://";
        osModURL += URL + strlen("/vsicurl/http%3A//");
    }
    else if (STARTS_WITH(URL, "http://schemas.opengis.net/"))    {
        const char *pszAfterOpenGIS =
            URL + strlen("http://schemas.opengis.net/");

        const char *pszSchemasOpenGIS;

        pszSchemasOpenGIS = CPLGetConfigOption("GDAL_OPENGIS_SCHEMAS", NULL);
        if (pszSchemasOpenGIS != NULL)
        {
            int nLen = (int)strlen(pszSchemasOpenGIS);
            if (nLen > 0 && pszSchemasOpenGIS[nLen-1] == '/')
            {
                osModURL = pszSchemasOpenGIS;
                osModURL += pszAfterOpenGIS;
            }
            else
            {
                osModURL = pszSchemasOpenGIS;
                osModURL += "/";
                osModURL += pszAfterOpenGIS;
            }
        }
        else if ((pszSchemasOpenGIS = CPLFindFile( "gdal", "SCHEMAS_OPENGIS_NET" )) != NULL)
        {
            osModURL = pszSchemasOpenGIS;
            osModURL += "/";
            osModURL += pszAfterOpenGIS;
        }
        else if ((pszSchemasOpenGIS = CPLFindFile( "gdal", "SCHEMAS_OPENGIS_NET.zip" )) != NULL)
        {
            osModURL = "/vsizip/";
            osModURL += pszSchemasOpenGIS;
            osModURL += "/";
            osModURL += pszAfterOpenGIS;
        }
        else
        {
            osModURL = "/vsizip/vsicurl/http://schemas.opengis.net/SCHEMAS_OPENGIS_NET.zip/";
            osModURL += pszAfterOpenGIS;
        }
    }
    else
    {
        osModURL = URL;
    }

    xmlChar* pszBuffer = (xmlChar*)CPLLoadSchemaStr(osModURL);
    if (pszBuffer == NULL)
        return NULL;

    xmlParserInputPtr poInputStream = xmlNewStringInputStream(context, pszBuffer);
    if (poInputStream != NULL)
        poInputStream->free = CPLLibXMLInputStreamCPLFree;
    return poInputStream;
}