예제 #1
0
static void FindChangePattern( char *cdata,char **substs, char **keys, CPLString &ret)
{
    char **papszTokens=CSLTokenizeString2(cdata," \t\n\r",
                                           CSLT_STRIPLEADSPACES|CSLT_STRIPENDSPACES);
    ret.clear();

    int matchcount=CSLCount(substs);
    int keycount=CSLCount(keys);
    if (keycount<matchcount)
    {
        CSLDestroy(papszTokens);
        return;
    }

    // A valid string has only the keys in the substs list and none other
    for (int j=0;j<CSLCount(papszTokens);j++)
    {
        ret=papszTokens[j];  // The target string
        bool matches=true;

        for (int k=0;k<keycount && keys != NULL;k++)
        {
            const char *key=keys[k];
            int sub_number=CSLPartialFindString(substs,key);
            if (sub_number!=-1)
            { // It is a listed match
                // But is the match for the key position?
                char *found_key=NULL;
                const char *found_value=CPLParseNameValue(substs[sub_number],&found_key);
                if (found_key!=NULL && EQUAL(found_key,key))
                {  // Should exits in the request
                    if (std::string::npos==ret.find(key))
                    {
                        matches=false;
                        CPLFree(found_key);
                        break;
                    }
                    // Execute the substitution on the "ret" string
                    URLSearchAndReplace(&ret,key,"%s",found_value);
                }
                if (found_key!=NULL) CPLFree(found_key);
            }
            else
            {  // Key not in the subst list, should not match
                if (std::string::npos!=ret.find(key))
                {
                    matches=false;
                    break;
                }
            }
        } // Key loop
        if (matches)
        {
            CSLDestroy(papszTokens);
            return;  // We got the string ready, all keys accounted for and substs applied
        }
    }
    ret.clear();
    CSLDestroy(papszTokens);
}
예제 #2
0
VSIOSSHandleHelper* VSIOSSHandleHelper::BuildFromURI( const char* pszURI,
                                                      const char* pszFSPrefix,
                                                      bool bAllowNoObject,
                                                      CSLConstList papszOptions )
{
    CPLString osSecretAccessKey;
    CPLString osAccessKeyId;
    if( !GetConfiguration(papszOptions, osSecretAccessKey, osAccessKeyId) )
    {
        return nullptr;
    }

    const CPLString osEndpoint = CSLFetchNameValueDef(papszOptions,
        "OSS_ENDPOINT",
        CPLGetConfigOption("OSS_ENDPOINT", "oss-us-east-1.aliyuncs.com"));
    CPLString osBucket;
    CPLString osObjectKey;
    if( pszURI != nullptr && pszURI[0] != '\0' &&
        !GetBucketAndObjectKey(pszURI, pszFSPrefix, bAllowNoObject,
                               osBucket, osObjectKey) )
    {
        return nullptr;
    }
    const bool bUseHTTPS = CPLTestBool(CPLGetConfigOption("OSS_HTTPS", "YES"));
    const bool bIsValidNameForVirtualHosting =
        osBucket.find('.') == std::string::npos;
    const bool bUseVirtualHosting = CPLTestBool(
        CPLGetConfigOption("OSS_VIRTUAL_HOSTING",
                           bIsValidNameForVirtualHosting ? "TRUE" : "FALSE"));
    return new VSIOSSHandleHelper(osSecretAccessKey, osAccessKeyId,
                                 osEndpoint,
                                 osBucket, osObjectKey, bUseHTTPS,
                                 bUseVirtualHosting);
}
예제 #3
0
static CPLString GDALGMLJP2EvalExpr(const CPLString& osTemplate,
                                    xmlXPathContextPtr pXPathCtx,
                                    xmlDocPtr pDoc)
{
    CPLString osXMLRes;
    size_t nPos = 0;
    while( true )
    {
        // Get next expression.
        size_t nStartPos = osTemplate.find("{{{", nPos);
        if( nStartPos == std::string::npos)
        {
            // Add terminating portion of the template.
            osXMLRes += osTemplate.substr(nPos);
            break;
        }

        // Add portion of template before the expression.
        osXMLRes += osTemplate.substr(nPos, nStartPos - nPos);

        const char* pszExpr = osTemplate.c_str() + nStartPos;
        GDALGMLJP2Expr* poExpr = GDALGMLJP2Expr::Build(pszExpr, pszExpr);
        if( poExpr == nullptr )
            break;
        nPos = static_cast<size_t>(pszExpr - osTemplate.c_str());
        osXMLRes += poExpr->Evaluate(pXPathCtx,pDoc).osValue;
        delete poExpr;
    }
    return osXMLRes;
}
예제 #4
0
파일: wmsutils.cpp 프로젝트: OSGeo/gdal
// Terminates an URL base with either ? or &, so extra args can be appended
void URLPrepare(CPLString &url) {
    if (url.find("?") == std::string::npos) {
        url.append("?");
    } else {
        if (*url.rbegin() != '?' && *url.rbegin() != '&')
            url.append("&");
    }
}
예제 #5
0
void replace(CPLString& str, const char *from, const char *to) {
  if(strlen(from) == 0)
    return;
  size_t start_pos = 0;
  while((start_pos = str.find(from, start_pos)) != std::string::npos) {
    str.replace(start_pos, strlen(from), to);
    start_pos += strlen(to); // In case 'to' contains 'from', like replacing 'x' with 'yx'
  }
}
예제 #6
0
void VSIMemFilesystemHandler::NormalizePath( CPLString &oPath )

{
    size_t nPos = 0;
    while( (nPos = oPath.find('\\', nPos)) != std::string::npos )
    {
        oPath[nPos] = '/';
        nPos ++;
    }
}
예제 #7
0
// This is a performance critical function, especially on geosciml schemas,
// and we make careful to not do any string copy or other memory allocation
// in it.
bool GMLASXPathMatcher::MatchesRefXPath(
                        const CPLString& osXPath,
                        const std::vector<XPathComponent>& oRefXPath) const
{
    size_t iPos = 0;
    size_t iIdxInRef = 0;

    bool bDirectChild = oRefXPath[0].m_bDirectChild;
    while( iPos < osXPath.size() && iIdxInRef < oRefXPath.size() )
    {
        bDirectChild = oRefXPath[iIdxInRef].m_bDirectChild;
        size_t iPosNextSlash = osXPath.find('/', iPos);

        bool bNodeMatch;
        if( iPosNextSlash == std::string::npos )
        {
            bNodeMatch = osXPath.compare(iPos, std::string::npos,
                                         oRefXPath[iIdxInRef].m_osValue) == 0;
        }
        else
        {
            bNodeMatch = osXPath.compare(iPos, iPosNextSlash - iPos,
                                         oRefXPath[iIdxInRef].m_osValue) == 0;
        }

        if( !bNodeMatch )
        {
            if( bDirectChild )
                return false;

            if( iPosNextSlash == std::string::npos )
                return false;
            iPos = iPosNextSlash + 1;
            continue;
        }

        if( iPosNextSlash == std::string::npos )
            iPos = osXPath.size();
        else
            iPos = iPosNextSlash + 1;
        iIdxInRef ++;
        bDirectChild = true;
    }

    return (!bDirectChild || iPos == osXPath.size()) &&
            iIdxInRef == oRefXPath.size();
}
void ACAdjustText( double dfAngle, double dfScale, OGRFeature *poFeature )

{
/* -------------------------------------------------------------------- */
/*      We only try to alter text elements (LABEL styles).              */
/* -------------------------------------------------------------------- */
    if( poFeature->GetStyleString() == NULL )
        return;

    CPLString osOldStyle = poFeature->GetStyleString();

    if( strstr(osOldStyle,"LABEL") == NULL )
        return;

/* -------------------------------------------------------------------- */
/*      Is there existing angle text?                                   */
/* -------------------------------------------------------------------- */
    double dfOldAngle = 0.0;
    CPLString osPreAngle, osPostAngle;
    size_t nAngleOff = osOldStyle.find( ",a:" );

    if( nAngleOff != std::string::npos )
    {
        size_t nEndOfAngleOff = osOldStyle.find( ",", nAngleOff + 1 );

        if( nEndOfAngleOff == std::string::npos )
            nEndOfAngleOff = osOldStyle.find( ")", nAngleOff + 1 );

        osPreAngle.assign( osOldStyle, 0, nAngleOff );
        osPostAngle.assign( osOldStyle, nEndOfAngleOff, std::string::npos );
        
        dfOldAngle = CPLAtof( osOldStyle.c_str() + nAngleOff + 3 );
    }
    else
    {
        CPLAssert( osOldStyle[osOldStyle.size()-1] == ')' );
        osPreAngle.assign( osOldStyle, 0, osOldStyle.size() - 1 );
        osPostAngle = ")";
    }

/* -------------------------------------------------------------------- */
/*      Format with the new angle.                                      */
/* -------------------------------------------------------------------- */
    CPLString osNewStyle;

    osNewStyle.Printf( "%s,a:%g%s", 
                       osPreAngle.c_str(), 
                       dfOldAngle + dfAngle,
                       osPostAngle.c_str() );

    osOldStyle = osNewStyle;

/* -------------------------------------------------------------------- */
/*      Is there existing scale text?                                   */
/* -------------------------------------------------------------------- */
    double dfOldScale = 1.0;
    CPLString osPreScale, osPostScale;
    size_t nScaleOff = osOldStyle.find( ",s:" );
    
    if( nScaleOff != std::string::npos )
    {
        size_t nEndOfScaleOff = osOldStyle.find( ",", nScaleOff + 1 );

        if( nEndOfScaleOff == std::string::npos )
            nEndOfScaleOff = osOldStyle.find( ")", nScaleOff + 1 );

        osPreScale.assign( osOldStyle, 0, nScaleOff );
        osPostScale.assign( osOldStyle, nEndOfScaleOff, std::string::npos );
        
        dfOldScale = CPLAtof( osOldStyle.c_str() + nScaleOff + 3 );
    }
    else
    {
        CPLAssert( osOldStyle[osOldStyle.size()-1] == ')' );
        osPreScale.assign( osOldStyle, 0, osOldStyle.size() - 1 );
        osPostScale = ")";
    }

/* -------------------------------------------------------------------- */
/*      Format with the new scale.                                      */
/* -------------------------------------------------------------------- */
    osNewStyle.Printf( "%s,s:%gg%s", 
                       osPreScale.c_str(), 
                       dfOldScale * dfScale,
                       osPostScale.c_str() );

    poFeature->SetStyleString( osNewStyle );
}
예제 #9
0
const char *PamAllocateProxy( const char *pszOriginal )

{
    InitProxyDB();

    if( poProxyDB == NULL )
        return NULL;

    CPLMutexHolderD( &hProxyDBLock );

    poProxyDB->CheckLoadDB();

/* -------------------------------------------------------------------- */
/*      Form the proxy filename based on the original path if           */
/*      possible, but dummy out any questionable characters, path       */
/*      delimiters and such.  This is intended to make the proxy        */
/*      name be identifiable by folks digging around in the proxy       */
/*      database directory.                                             */
/*                                                                      */
/*      We also need to be careful about length.                        */
/* -------------------------------------------------------------------- */
    CPLString osRevProxyFile;
    int   i;

    i = strlen(pszOriginal) - 1;
    while( i >= 0 && osRevProxyFile.size() < 220 )
    {
        if( i > 6 && EQUALN(pszOriginal+i-5,":::OVR",6) )
            i -= 6;

        // make some effort to break long names at path delimiters.
        if( (pszOriginal[i] == '/' || pszOriginal[i] == '\\') 
            && osRevProxyFile.size() > 200 )
            break;

        if( (pszOriginal[i] >= 'A' && pszOriginal[i] <= 'Z') 
            || (pszOriginal[i] >= 'a' && pszOriginal[i] <= 'z') 
            || (pszOriginal[i] >= '0' && pszOriginal[i] <= '9') 
            || pszOriginal[i] == '.' )
            osRevProxyFile += pszOriginal[i];
        else
            osRevProxyFile += '_';

        i--;
    }
    
    CPLString osOriginal = pszOriginal;
    CPLString osProxy;
    CPLString osCounter;

    osProxy = poProxyDB->osProxyDBDir + "/";

    osCounter.Printf( "%06d_", poProxyDB->nUpdateCounter++ );
    osProxy += osCounter;

    for( i = osRevProxyFile.size()-1; i >= 0; i-- )
        osProxy += osRevProxyFile[i];

    if( osOriginal.find(":::OVR") != CPLString::npos )
        osProxy += ".ovr";
    else
        osProxy += ".aux.xml";

/* -------------------------------------------------------------------- */
/*      Add the proxy and the original to the proxy list and resave     */
/*      the database.                                                   */
/* -------------------------------------------------------------------- */
    poProxyDB->aosOriginalFiles.push_back( osOriginal );
    poProxyDB->aosProxyFiles.push_back( osProxy );

    poProxyDB->SaveDB();

    return PamGetProxy( pszOriginal );
}
예제 #10
0
void OGROSMLayer::AddComputedAttribute(const char* pszName,
                                       OGRFieldType eType,
                                       const char* pszSQL)
{
    if( poDS->hDBForComputedAttributes == NULL )
    {
        int rc;
#ifdef HAVE_SQLITE_VFS
        rc = sqlite3_open_v2( ":memory:", &(poDS->hDBForComputedAttributes),
                              SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, NULL );
#else
        rc = sqlite3_open( ":memory:", &(poDS->hDBForComputedAttributes) );
#endif
        if( rc != SQLITE_OK )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "Cannot open temporary sqlite DB" );
            return;
        }
    }

    if( poFeatureDefn->GetFieldIndex(pszName) >= 0 )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "A field with same name %s already exists", pszName );
        return;
    }

    CPLString osSQL(pszSQL);
    std::vector<CPLString> aosAttrToBind;
    std::vector<int> anIndexToBind;
    size_t nStartSearch = 0;
    while(TRUE)
    {
        size_t nPos = osSQL.find("[", nStartSearch);
        if( nPos == std::string::npos )
            break;
        nStartSearch = nPos + 1;
        if( nPos > 0 && osSQL[nPos-1] != '\\' )
        {
            CPLString osAttr = osSQL.substr(nPos + 1);
            size_t nPos2 = osAttr.find("]");
            if( nPos2 == std::string::npos )
                break;
            osAttr.resize(nPos2);

            osSQL = osSQL.substr(0, nPos) + "?" + osSQL.substr(nPos + 1 + nPos2+1);

            aosAttrToBind.push_back(osAttr);
            anIndexToBind.push_back(poFeatureDefn->GetFieldIndex(osAttr));
        }
    }
    while(TRUE)
    {
        size_t nPos = osSQL.find("\\");
        if( nPos == std::string::npos || nPos == osSQL.size() - 1 )
            break;
        osSQL = osSQL.substr(0, nPos) + osSQL.substr(nPos + 1);
    }

    CPLDebug("OSM", "SQL : \"%s\"", osSQL.c_str());

    sqlite3_stmt  *hStmt;
    int rc = sqlite3_prepare( poDS->hDBForComputedAttributes, osSQL, -1,
                              &hStmt, NULL );
    if( rc != SQLITE_OK )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "sqlite3_prepare() failed :  %s",
                  sqlite3_errmsg(poDS->hDBForComputedAttributes) );
        return;
    }

    OGRFieldDefn oField(pszName, eType);
    poFeatureDefn->AddFieldDefn(&oField);
    oComputedAttributes.push_back(OGROSMComputedAttribute(pszName));
    oComputedAttributes[oComputedAttributes.size()-1].eType = eType;
    oComputedAttributes[oComputedAttributes.size()-1].nIndex = poFeatureDefn->GetFieldCount() - 1;
    oComputedAttributes[oComputedAttributes.size()-1].osSQL = pszSQL;
    oComputedAttributes[oComputedAttributes.size()-1].hStmt = hStmt;
    oComputedAttributes[oComputedAttributes.size()-1].aosAttrToBind = aosAttrToBind;
    oComputedAttributes[oComputedAttributes.size()-1].anIndexToBind = anIndexToBind;
}
예제 #11
0
int PDSDataset::ParseImage( CPLString osPrefix )
{
/* ------------------------------------------------------------------- */
/*	We assume the user is pointing to the label (ie. .lbl) file.  	   */
/* ------------------------------------------------------------------- */
    // IMAGE can be inline or detached and point to an image name
    // ^IMAGE = 3
    // ^IMAGE             = "GLOBAL_ALBEDO_8PPD.IMG"
    // ^IMAGE             = "MEGT90N000CB.IMG"
    // ^IMAGE		  = ("BLAH.IMG",1)	 -- start at record 1 (1 based)
    // ^IMAGE		  = ("BLAH.IMG")	 -- still start at record 1 (equiv of "BLAH.IMG")
    // ^IMAGE		  = ("BLAH.IMG", 5 <BYTES>) -- start at byte 5 (the fifth byte in the file)
    // ^IMAGE             = 10851 <BYTES>
    // ^SPECTRAL_QUBE = 5  for multi-band images

    CPLString osImageKeyword = osPrefix + "^IMAGE";
    CPLString osQube = GetKeyword( osImageKeyword, "" );
    CPLString osTargetFile = GetDescription();

    if (EQUAL(osQube,"")) {
        osImageKeyword = "^SPECTRAL_QUBE";
        osQube = GetKeyword( osImageKeyword );
    }

    int nQube = atoi(osQube);
    int nDetachedOffset = 0;
    int bDetachedOffsetInBytes = FALSE;

    if( osQube.size() && osQube[0] == '(' )
    {
        osQube = "\"";
        osQube += GetKeywordSub( osImageKeyword, 1 );
        osQube +=  "\"";
        nDetachedOffset = atoi(GetKeywordSub( osImageKeyword, 2, "1")) - 1;

        // If this is not explicitly in bytes, then it is assumed to be in
        // records, and we need to translate to bytes.
        if (strstr(GetKeywordSub(osImageKeyword,2),"<BYTES>") != NULL)
            bDetachedOffsetInBytes = TRUE;
    }

    if( osQube.size() && osQube[0] == '"' )
    {
        CPLString osTPath = CPLGetPath(GetDescription());
        CPLString osFilename = osQube;
        CleanString( osFilename );
        osTargetFile = CPLFormCIFilename( osTPath, osFilename, NULL );
        osExternalCube = osTargetFile;
    }

    GDALDataType eDataType = GDT_Byte;

    
    //image parameters
    int	nRows, nCols, nBands = 1;
    int nSkipBytes = 0;
    int itype;
    int record_bytes;
    char chByteOrder = 'M';  //default to MSB
    double dfNoData = 0.0;
 
    /* -------------------------------------------------------------------- */
    /*      Checks to see if this is raw PDS image not compressed image     */
    /*      so ENCODING_TYPE either does not exist or it equals "N/A".      */
    /*      Compressed types will not be supported in this routine          */
    /* -------------------------------------------------------------------- */
    const char *value;

    CPLString osEncodingType = GetKeyword(osPrefix+"IMAGE.ENCODING_TYPE","N/A");
    CleanString(osEncodingType);
    if ( !EQUAL(osEncodingType.c_str(),"N/A") )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "*** PDS image file has an ENCODING_TYPE parameter:\n"
                  "*** gdal pds driver does not support compressed image types\n"
                  "found: (%s)\n\n", osEncodingType.c_str() );
        return FALSE;
    } 
    /**************** end ENCODING_TYPE check ***********************/
    
    
    /***********   Grab layout type (BSQ, BIP, BIL) ************/
    //  AXIS_NAME = (SAMPLE,LINE,BAND)
    /***********   Grab samples lines band        **************/
    /** if AXIS_NAME = "" then Bands=1 and Sample and Lines   **/
    /** are there own keywords  "LINES" and "LINE_SAMPLES"    **/
    /** if not NULL then CORE_ITEMS keyword i.e. (234,322,2)  **/
    /***********************************************************/
    char szLayout[10] = "BSQ"; //default to band seq.
    value = GetKeyword( osPrefix+"IMAGE.AXIS_NAME", "" );
    if (EQUAL(value,"(SAMPLE,LINE,BAND)") ) {
        strcpy(szLayout,"BSQ");
        nCols = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",1));
        nRows = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",2));
        nBands = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",3));
    }
    else if (EQUAL(value,"(BAND,LINE,SAMPLE)") ) {
        strcpy(szLayout,"BIP");
        nBands = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",1));
        nRows = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",2));
        nCols = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",3));
    }
    else if (EQUAL(value,"(SAMPLE,BAND,LINE)") ) {
        strcpy(szLayout,"BIL");
        nCols = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",1));
        nBands = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",2));
        nRows = atoi(GetKeywordSub(osPrefix+"IMAGE.CORE_ITEMS",3));
    }
    else if ( EQUAL(value,"") ) {
        strcpy(szLayout,"BSQ");
        nCols = atoi(GetKeyword(osPrefix+"IMAGE.LINE_SAMPLES",""));
        nRows = atoi(GetKeyword(osPrefix+"IMAGE.LINES",""));
        nBands = atoi(GetKeyword(osPrefix+"IMAGE.BANDS","1"));
    }
    else {
        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "%s layout not supported. Abort\n\n", value);
        return FALSE;
    }
    
    /***********   Grab Qube record bytes  **********/
    record_bytes = atoi(GetKeyword(osPrefix+"IMAGE.RECORD_BYTES"));
    if (record_bytes == 0)
        record_bytes = atoi(GetKeyword(osPrefix+"RECORD_BYTES"));

    // this can happen with "record_type = undefined". 
    if( record_bytes == 0 )
        record_bytes = 1;

    if( nQube >0 && osQube.find("<BYTES>") != CPLString::npos )
        nSkipBytes = nQube - 1;
    else if (nQube > 0 )
        nSkipBytes = (nQube - 1) * record_bytes;
    else if( nDetachedOffset > 0 )
    {
        if (bDetachedOffsetInBytes)
            nSkipBytes = nDetachedOffset;
        else
            nSkipBytes = nDetachedOffset * record_bytes;
    }
    else
        nSkipBytes = 0;     

    nSkipBytes += atoi(GetKeyword(osPrefix+"IMAGE.LINE_PREFIX_BYTES",""));
    
    /***********   Grab SAMPLE_TYPE *****************/
    /** if keyword not found leave as "M" or "MSB" **/
    CPLString osST = GetKeyword( osPrefix+"IMAGE.SAMPLE_TYPE" );
    if( osST.size() >= 2 && osST[0] == '"' && osST[osST.size()-1] == '"' )
        osST = osST.substr( 1, osST.size() - 2 );

    if( (EQUAL(osST,"LSB_INTEGER")) || 
        (EQUAL(osST,"LSB")) || // just incase
        (EQUAL(osST,"LSB_UNSIGNED_INTEGER")) || 
        (EQUAL(osST,"LSB_SIGNED_INTEGER")) || 
        (EQUAL(osST,"UNSIGNED_INTEGER")) || 
        (EQUAL(osST,"VAX_REAL")) || 
        (EQUAL(osST,"VAX_INTEGER")) || 
        (EQUAL(osST,"PC_INTEGER")) ||  //just incase 
        (EQUAL(osST,"PC_REAL")) ) {
        chByteOrder = 'I';
    }

    /**** Grab format type - pds supports 1,2,4,8,16,32,64 (in theory) **/
    /**** I have only seen 8, 16, 32 (float) in released datasets      **/
    itype = atoi(GetKeyword(osPrefix+"IMAGE.SAMPLE_BITS",""));
    switch(itype) {
      case 8 :
        eDataType = GDT_Byte;
        dfNoData = NULL1;
        break;
      case 16 :
        if( strstr(osST,"UNSIGNED") != NULL )
            eDataType = GDT_UInt16;
        else
            eDataType = GDT_Int16;
        dfNoData = NULL2;
        break;
      case 32 :
        eDataType = GDT_Float32;
        dfNoData = NULL3;
        break;
      case 64 :
        eDataType = GDT_Float64;
        dfNoData = NULL3;
        break;
      default :
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Sample_bits of %d is not supported in this gdal PDS reader.",
                  itype); 
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Is there a specific nodata value in the file? Either the        */
/*      MISSING or MISSING_CONSTANT keywords are nodata.                */
/* -------------------------------------------------------------------- */
    if( GetKeyword( osPrefix+"IMAGE.MISSING", NULL ) != NULL )
        dfNoData = CPLAtofM( GetKeyword( osPrefix+"IMAGE.MISSING", "" ) );

    if( GetKeyword( osPrefix+"IMAGE.MISSING_CONSTANT", NULL ) != NULL )
        dfNoData = CPLAtofM( GetKeyword( osPrefix+"IMAGE.MISSING_CONSTANT",""));

/* -------------------------------------------------------------------- */
/*      Did we get the required keywords?  If not we return with        */
/*      this never having been considered to be a match. This isn't     */
/*      an error!                                                       */
/* -------------------------------------------------------------------- */
    if( nRows < 1 || nCols < 1 || nBands < 1 )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "File %s appears to be a PDS file, but failed to find some required keywords.", 
                  GetDescription() );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Capture some information from the file that is of interest.     */
/* -------------------------------------------------------------------- */
    nRasterXSize = nCols;
    nRasterYSize = nRows;

/* -------------------------------------------------------------------- */
/*      Open target binary file.                                        */
/* -------------------------------------------------------------------- */
    
    if( eAccess == GA_ReadOnly )
    {
        fpImage = VSIFOpenL( osTargetFile, "rb" );
        if( fpImage == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed, 
                    "Failed to open %s.\n%s", 
                    osTargetFile.c_str(),
                    VSIStrerror( errno ) );
            return FALSE;
        }
    }
    else
    {
        fpImage = VSIFOpenL( osTargetFile, "r+b" );
        if( fpImage == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed, 
                    "Failed to open %s with write permission.\n%s", 
                    osTargetFile.c_str(),
                    VSIStrerror( errno ) );
            return FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Compute the line offset.                                        */
/* -------------------------------------------------------------------- */
    int     nItemSize = GDALGetDataTypeSize(eDataType)/8;
    int     nLineOffset = record_bytes;
    int	    nPixelOffset, nBandOffset;

    if( EQUAL(szLayout,"BIP") )
    {
        nPixelOffset = nItemSize * nBands;
        nBandOffset = nItemSize;
        nLineOffset = ((nPixelOffset * nCols + record_bytes - 1)/record_bytes)
            * record_bytes;
    }
    else if( EQUAL(szLayout,"BSQ") )
    {
        nPixelOffset = nItemSize;
        nLineOffset = ((nPixelOffset * nCols + record_bytes - 1)/record_bytes)
            * record_bytes;
        nBandOffset = nLineOffset * nRows;
    }
    else /* assume BIL */
    {
        nPixelOffset = nItemSize;
        nBandOffset = nItemSize * nCols;
        nLineOffset = ((nBandOffset * nCols + record_bytes - 1)/record_bytes)
            * record_bytes;
    }
    
/* -------------------------------------------------------------------- */
/*      Create band information objects.                                */
/* -------------------------------------------------------------------- */
    int i;

    for( i = 0; i < nBands; i++ )
    {
        RawRasterBand	*poBand;

        poBand = 
            new RawRasterBand( this, i+1, fpImage,
                               nSkipBytes + nBandOffset * i, 
                               nPixelOffset, nLineOffset, eDataType,
#ifdef CPL_LSB                               
                               chByteOrder == 'I' || chByteOrder == 'L',
#else
                               chByteOrder == 'M',
#endif        
                               TRUE );

        if( nBands == 1 )
        {
            const char* pszMin = GetKeyword(osPrefix+"IMAGE.MINIMUM", NULL);
            const char* pszMax = GetKeyword(osPrefix+"IMAGE.MAXIMUM", NULL);
            const char* pszMean = GetKeyword(osPrefix+"IMAGE.MEAN", NULL);
            const char* pszStdDev= GetKeyword(osPrefix+"IMAGE.STANDARD_DEVIATION", NULL);
            if (pszMin != NULL && pszMax != NULL &&
                pszMean != NULL && pszStdDev != NULL)
            {
                poBand->SetStatistics( CPLAtofM(pszMin),
                                       CPLAtofM(pszMax),
                                       CPLAtofM(pszMean),
                                       CPLAtofM(pszStdDev));
            }
        }
        
        poBand->SetNoDataValue( dfNoData );

        SetBand( i+1, poBand );

        // Set offset/scale values at the PAM level.
        poBand->SetOffset( 
            CPLAtofM(GetKeyword(osPrefix+"IMAGE.OFFSET","0.0")));
        poBand->SetScale( 
            CPLAtofM(GetKeyword(osPrefix+"IMAGE.SCALING_FACTOR","1.0")));
    }

    return TRUE;
}
예제 #12
0
void    GMLASXPathMatcher::SetDocumentMapURIToPrefix(
                        const std::map<CPLString,CPLString>& oMapURIToPrefix )
{
    m_aosReferenceXPaths.clear();

    // Split each reference XPath into its components
    for(size_t i = 0; i < m_aosReferenceXPathsUncompiled.size(); ++i )
    {
        const CPLString& osXPath( m_aosReferenceXPathsUncompiled[i] );

        std::vector<XPathComponent> oVector;

        size_t iPos = 0;
        bool bDirectChild = false;
        if( osXPath.size() >= 2 &&
            osXPath[0] == '/' && osXPath[1] == '/' )
        {
            iPos += 2;
        }
        else if( osXPath.size() >= 1 && osXPath[0] == '/' )
        {
            iPos += 1;
            bDirectChild = true;
        }

        while( iPos < osXPath.size() )
        {
            size_t iPosNextSlash = osXPath.find('/', iPos);

            if( iPos == iPosNextSlash )
            {
                bDirectChild = false;
                iPos ++;
                continue;
            }

            CPLString osCurNode;
            if( iPosNextSlash == std::string::npos )
                osCurNode.assign(osXPath, iPos, std::string::npos);
            else
                osCurNode.assign(osXPath, iPos, iPosNextSlash - iPos);

            // Translate the configuration prefix to the equivalent in
            // this current schema
            size_t iPosColumn = osCurNode.find(':');
            if( iPosColumn != std::string::npos )
            {
                bool bIsAttr = ( osCurNode[0] == '@' );
                CPLString osPrefix;
                CPLString osLocalname;
                osPrefix.assign(osCurNode, 
                                bIsAttr ? 1 : 0,
                                iPosColumn - (bIsAttr ? 1 : 0));
                osLocalname.assign(osCurNode, iPosColumn+1,
                                std::string::npos);

                std::map<CPLString, CPLString>::const_iterator oIter =
                    m_oMapPrefixToURIReferenceXPaths.find(osPrefix);
                if( oIter != m_oMapPrefixToURIReferenceXPaths.end() )
                {
                    const CPLString& osURI( oIter->second );
                    oIter = oMapURIToPrefix.find( osURI );
                    if( oIter == oMapURIToPrefix.end() )
                        break;
                    osPrefix.assign(oIter->second);
                }

                osCurNode.clear();
                if( bIsAttr )
                    osCurNode.append(1, '@');
                osCurNode.append(osPrefix);
                osCurNode.append(1, ':');
                osCurNode.append(osLocalname);
            }

            XPathComponent comp;
            comp.m_osValue = osCurNode;
            comp.m_bDirectChild = bDirectChild;
            oVector.push_back(comp);

            if( iPosNextSlash == std::string::npos )
                iPos = osXPath.size();
            else
                iPos = iPosNextSlash + 1;

            bDirectChild = true;
        }

        if ( iPos < osXPath.size() )
            oVector.clear();
        m_aosReferenceXPaths.push_back(oVector);
    }
}
예제 #13
0
VSIVirtualHandle *
VSIMemFilesystemHandler::Open( const char *pszFilename,
                               const char *pszAccess,
                               bool bSetError )

{
    CPLMutexHolder oHolder( &hMutex );
    CPLString osFilename = pszFilename;
    NormalizePath( osFilename );
    if( osFilename.empty() )
        return nullptr;

    vsi_l_offset nMaxLength = GUINTBIG_MAX;
    const size_t iPos = osFilename.find("||maxlength=");
    if( iPos != std::string::npos )
    {
        nMaxLength = static_cast<vsi_l_offset>(CPLAtoGIntBig(
                    osFilename.substr(iPos + strlen("||maxlength=")).c_str()));
    }

/* -------------------------------------------------------------------- */
/*      Get the filename we are opening, create if needed.              */
/* -------------------------------------------------------------------- */
    VSIMemFile *poFile = nullptr;
    if( oFileList.find(osFilename) != oFileList.end() )
        poFile = oFileList[osFilename];

    // If no file and opening in read, error out.
    if( strstr(pszAccess, "w") == nullptr
        && strstr(pszAccess, "a") == nullptr
        && poFile == nullptr )
    {
        if( bSetError )
        {
            VSIError(VSIE_FileError, "No such file or directory");
        }
        errno = ENOENT;
        return nullptr;
    }

    // Create.
    if( poFile == nullptr )
    {
        poFile = new VSIMemFile;
        poFile->osFilename = osFilename;
        oFileList[poFile->osFilename] = poFile;
        CPLAtomicInc(&(poFile->nRefCount));  // For file list.
        poFile->nMaxLength = nMaxLength;
    }
    // Overwrite
    else if( strstr(pszAccess, "w") )
    {
        poFile->SetLength(0);
        poFile->nMaxLength = nMaxLength;
    }

    if( poFile->bIsDirectory )
    {
        errno = EISDIR;
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Setup the file handle on this file.                             */
/* -------------------------------------------------------------------- */
    VSIMemHandle *poHandle = new VSIMemHandle;

    poHandle->poFile = poFile;
    poHandle->m_nOffset = 0;
    poHandle->bEOF = false;
    poHandle->bUpdate =
        strstr(pszAccess, "w") ||
        strstr(pszAccess, "+") ||
        strstr(pszAccess, "a");

    CPLAtomicInc(&(poFile->nRefCount));

    if( strstr(pszAccess, "a") )
        poHandle->m_nOffset = poFile->nLength;

    return poHandle;
}
예제 #14
0
static CPLString GetProj4Filename(const char* pszFilename)
{
    CPLString osFilename;

    /* or fixed path: /name, ./name or ../name */
    if ( !CPLIsFilenameRelative(pszFilename) || *pszFilename == '.' )
    {
        return pszFilename;
    }

#if defined(PROJ_STATIC) && PROJ_VERSION >= 5
    PJ_GRID_INFO info = proj_grid_info(pszFilename);
    if( info.filename[0] )
    {
        osFilename = info.filename;
    }
#elif defined(PROJ_STATIC) && PJ_VERSION > 493
    osFilename.resize(2048);
    projCtx ctx = pj_ctx_alloc();
    if( pj_find_file(ctx, pszFilename, &osFilename[0], osFilename.size()) )
    {
        osFilename.resize( strlen(osFilename) );
    }
    else
    {
        osFilename.clear();
    }
    pj_ctx_free(ctx);
#else
    // Transpose some of the proj.4 pj_open_lib() logic...

    /* check if ~/name */
    char* pszSysname;
    if (*pszFilename == '~' &&
        (pszFilename[1] == '/' || pszFilename[1] == '\\') )
    {
        if ((pszSysname = getenv("HOME")) != nullptr)
        {
            osFilename = CPLFormFilename(pszSysname, pszFilename + 1, nullptr);
        }
        return osFilename;
    }

    /* or is environment PROJ_LIB defined */
    else if ((pszSysname = getenv("PROJ_LIB")) != nullptr)
    {
        osFilename = CPLFormFilename(pszSysname, pszFilename, nullptr);
        VSIStatBufL sStat;
        if( VSIStatL(osFilename, &sStat) == 0 )
            return osFilename;
        osFilename.clear();
    }


#if defined(PROJ_STATIC) && PJ_VERSION >= 490
    // Super messy. proj.4 up to 4.9.3 had no public API to return the full
    // path to a resource file, so we rely on the fact that it emits a log
    // message with it...
    // Basically this is needed in the case where the file is in the
    // resource installation directory of proj.4, which we have no way to
    // know otherwise.
    CPLString osMsg;
    projCtx ctx = pj_ctx_alloc();
    pj_ctx_set_app_data(ctx, &osMsg);
    pj_ctx_set_debug(ctx, PJ_LOG_DEBUG_MAJOR);
    pj_ctx_set_logger(ctx, my_proj4_logger);
    PAFile f = pj_open_lib(ctx, pszFilename, "rb");
    if( f )
    {
        pj_ctx_fclose(ctx, f);
        size_t nPos = osMsg.find("fopen(");
        if( nPos != std::string::npos )
        {
            osFilename = osMsg.substr(nPos + strlen("fopen("));
            nPos = osFilename.find(")");
            if( nPos != std::string::npos )
                osFilename = osFilename.substr(0, nPos);
        }
    }
    pj_ctx_free(ctx);
#endif
#endif
    return osFilename;
}