wxString frmMainConfig::GetHintString()
{
	wxArrayInt hints;
	size_t i;
	int autovacuum = 0;
	bool autovacuumPresent = false;

	for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++)
	{
		pgSettingItem *item = options[cfgList->GetText(i)];

		if (item)
		{
			wxString name = item->name;
			wxString value = item->GetActiveValue();
			if (name == wxT("listen_addresses"))
			{
				if (value.IsEmpty() || value == wxT("localhost"))
					hints.Add(HINT_LISTEN_ADDRESSES);
			}
			else if (name == wxT("autovacuum"))
			{
				autovacuumPresent = true;
				if (StrToBool(value))
					autovacuum++;
			}
			else if (name == wxT("stats_start_collector") || name == wxT("stats_row_level"))
			{
				if (StrToBool(value))
					autovacuum++;
			}
			else if (name == wxT("track_counts"))
			{
				// Double increment, because track_counts in 8.3 is worth both previous options.
				if (StrToBool(value))
					autovacuum = autovacuum + 2;
			}
		}
	}

	if (autovacuumPresent && autovacuum < 3)
		hints.Add(HINT_AUTOVACUUM_CFG);

	wxString str;
	for (i = 0 ; i < hints.GetCount() ; i++)
	{
		if (i)
			str.Append(wxT("\n\n"));
		str.Append(hintString[hints.Item(i)]);
	}

	return str;
}
Exemple #2
0
bool pgConn::IsSuperuser()
{
	wxString res = ExecuteScalar(
	                   wxT("SELECT rolsuper FROM pg_roles ")
	                   wxT("WHERE rolname='") + qtIdent(GetUser()) + wxT("'"));

	return StrToBool(res);
}
Exemple #3
0
bool pgConn::HasPrivilege(const wxString &objTyp, const wxString &objName, const wxString &priv)
{
	wxString res = ExecuteScalar(
	                   wxT("SELECT has_") + objTyp.Lower()
	                   + wxT("_privilege(") + qtDbString(objName)
	                   + wxT(", ") + qtDbString(priv) + wxT(")"));

	return StrToBool(res);
}
Exemple #4
0
void GetPrefFromDB()
{
  int i;
  Bool stat;
  char *type;
  XrmValue val;

  for( i=0; i < N_DPY_PREFS; i++ ){
       stat = XrmGetResource( pref_db.db, pref_db.dpyPrefs[i].name, 
			      pref_db.dpyPrefs[i].class, &type, &val );  
       if( stat == True && strcmp(type,STRING) == 0 ) 
	    pref_db.dpyPrefs[i].value = StrToBool( val.addr );
  }

  for( i=0; i < N_CLI_PREFS; i++ ){
       stat = XrmGetResource( pref_db.db, pref_db.cliPrefs[i].name, 
			      pref_db.cliPrefs[i].class, &type, &val );
       if( stat == True && strcmp(type,STRING) == 0 )
	    pref_db.cliPrefs[i].value = StrToBool( val.addr );              
  }

  for( i=0; i < N_WIN_PREFS; i++ ){
       stat = XrmGetResource( pref_db.db, pref_db.winPrefs[i].name, 
			      pref_db.winPrefs[i].class, &type, &val );  
       if( stat == True && strcmp(type,STRING) == 0 )
 	    pref_db.winPrefs[i].value = StrToBool( val.addr );               
  }

  for( i=0; i < N_PROP_PREFS; i++ ){
       stat = XrmGetResource( pref_db.db, pref_db.propPrefs[i].name, 
			      pref_db.propPrefs[i].class, &type, &val );  
       if( stat == True && strcmp(type,STRING) == 0 )
 	    pref_db.propPrefs[i].value = StrToBool( val.addr );               
  }
  
  for( i=0; i < N_TREE_PREFS; i++ ){
       stat = XrmGetResource( pref_db.db, pref_db.treePrefs[i].name, 
			      pref_db.treePrefs[i].class, &type, &val );  
       if( stat == True && strcmp(type,STRING) == 0 )
 	    pref_db.treePrefs[i].value = StrToBool( val.addr );               
  }


}
Exemple #5
0
// Read a boolean value
bool sysSettings::Read(const wxString &key, bool *val, bool defaultVal) const
{
	wxString actualDefault = BoolToStr(defaultVal);
	wxString str;

	// Get the default from the defaults file, in preference
	// to the hardcoded value
	if (defaultSettings)
		defaultSettings->Read(key, &actualDefault, BoolToStr(defaultVal));

	Read(key, &str, actualDefault);
	*val = StrToBool(str);
	return true;
}
Exemple #6
0
	x_va_r&					x_va_r::operator=(const uchar32* rhs)
	{
		switch (mType)
		{
		case TYPE_BOOL:		*((bool*)mRef) = StrToBool(rhs, NULL); break;
		case TYPE_UINT32:	*((u32*)mRef) = (u32)StrToS64(rhs, NULL, 10); break;
		case TYPE_INT32:	*((s32*)mRef) = (s32)StrToS64(rhs, NULL, 10); break;
		case TYPE_UINT8:	*((u8 *)mRef) = (u8)StrToS64(rhs, NULL, 10); break;
		case TYPE_INT8:		*((s8 *)mRef) = (s8)StrToS64(rhs, NULL, 10); break;
		case TYPE_UINT16:	*((u16*)mRef) = (u16)StrToS64(rhs, NULL, 10); break;
		case TYPE_INT16:	*((s16*)mRef) = (s16)StrToS64(rhs, NULL, 10); break;
		case TYPE_UINT64:	*((u64*)mRef) = (u64)StrToS64(rhs, NULL, 10); break;
		case TYPE_INT64:	*((s64*)mRef) = (s64)StrToS64(rhs, NULL, 10); break;
		case TYPE_FLOAT32:	*((f32*)mRef) = (f32)StrToF32(rhs, NULL); break;
		case TYPE_FLOAT64:	*((f64*)mRef) = (f64)StrToF64(rhs, NULL); break;
		case TYPE_PTCHAR:	break;
		case TYPE_PUCHAR32:	break;
		default:			break; // Fall through
		};

		return *this;
	}
Exemple #7
0
BOOL CIniFile::ReadBool(
	const char* pszSection, 
	const char* pszIdent, 
	BOOL        bDefault
	)
{
	char    szResult[MAX_PATH];
	BOOL    bResult   = bDefault;
	char    szDefault[MAX_PATH];
		
	BoolToStr(bDefault, szDefault);

	ReadString(
		pszSection, 
		pszIdent,
		szDefault,
		szResult
		);

	bResult = StrToBool(szResult);

	return bResult;
}
Exemple #8
0
static int _ConfFileCallback(
    const char* path,
    unsigned int line,
    char** fields,
    size_t nfields,
    void* data,
    char* err,
    size_t errSize)
{
    Options* options = (Options*)data;
    const char* name;
    const char* value;

    if (nfields != 2)
    {
        Snprintf(err, errSize, "%s(%u): expected 2 fields", path, line);
        return -1;
    }

    name = fields[0];
    value = fields[1];

    if (strcmp(name, "port") == 0)
    {
        return StrToUShort(value, &options->port);
    }
    else if (strcmp(name, "noauth") == 0)
    {
        return StrToBool(value, &options->noauth);
    }
    else if (strcmp(name, "nodaemonize") == 0)
    {
        return StrToBool(value, &options->nodaemonize);
    }
    else if (strcmp(name, "dump") == 0)
    {
        return StrToBool(value, &options->dump);
    }
    else if (strcmp(name, "sockfile") == 0)
    {
        Strlcpy(options->sockfileBuf, value, sizeof(options->sockfileBuf));
        options->sockfile = options->sockfileBuf;
        return 0;
    }
    else if (strcmp(name, "loglevel") == 0)
    {
        return LogLevelFromString(value, &__logLevel);
    }
#if defined(ENABLE_SOCKTRACE)
    else if (strcmp(name, "logsockio") == 0)
    {
        return StrToBool(value, &__sockLog);
    }
#endif
    else if (strcmp(name, "logtostdout") == 0)
    {
        unsigned char flag;

        if (StrToBool(value, &flag) != 0)
            return -1;

        if (flag)
            LogSetStream(stdout);

        return 0;
    }

    Snprintf(err, errSize, "%s(%u): unknown option", path, line);
    return -1;
}
int main() {
	std::vector< int > intCases;
	intCases.push_back(123);
	intCases.push_back(0);
	intCases.push_back(-456);
	intCases.push_back(INT_MAX);
	intCases.push_back(INT_MIN);

	std::vector< float > floatCases;
	floatCases.push_back(12.34f);
	floatCases.push_back(0.0f);
	floatCases.push_back(-3.1415926575);
	floatCases.push_back(1e20);
	floatCases.push_back(1e-20);

	std::vector< std::string > strIntCases;
	strIntCases.push_back("123");
	strIntCases.push_back("0");
	strIntCases.push_back("-456");

	std::vector< std::string > strFloatCases;
	strFloatCases.push_back("12.34");
	strFloatCases.push_back("0.0");
	strFloatCases.push_back("-3.1415926535");
	strFloatCases.push_back("123");
	strFloatCases.push_back("-456");
	strFloatCases.push_back("0");

	std::vector< std::string > strVec2Cases;
	strVec2Cases.push_back("1.2,-9.8");
	strVec2Cases.push_back("0.0,0.0");
	strVec2Cases.push_back("-1.0,2.0");
	strVec2Cases.push_back("1,2.3");
	strVec2Cases.push_back("3.141592,6");

	std::vector< std::string > strBoolCases;
	strBoolCases.push_back("true");
	strBoolCases.push_back("false");
	strBoolCases.push_back("1");
	strBoolCases.push_back("0");
	strBoolCases.push_back("TRUE");
	strBoolCases.push_back("FaLSe");

	std::vector< b2Vec2 > vec2Cases;
	vec2Cases.push_back(b2Vec2(5.5f, 10.1f));
	vec2Cases.push_back(b2Vec2(0.0f, 0.0f));
	vec2Cases.push_back(b2Vec2(-3.4f, -2.8f));
	vec2Cases.push_back(b2Vec2(1e10, 1e-10));

	std::vector< bool > boolCases;
	boolCases.push_back(false);
	boolCases.push_back(true);

	typedef std::vector< int >::const_iterator IntIterator;
	typedef std::vector< float >::const_iterator FloatIterator;
	typedef std::vector< std::string >::const_iterator StrIterator;
	typedef std::vector< b2Vec2 >::const_iterator Vec2Iterator;
	typedef std::vector< bool >::const_iterator BoolIterator;

	bool (*pIntToStr)(int, std::string *) = &YPT::ConvertIntToStr;
	bool (*pStrToInt)(const std::string &, int *) = &YPT::ConvertStrToInt;
	bool (*pStrToFloat)(const std::string &, float *) = &YPT::ConvertStrToFloat;
	bool (*pStrToVec2)(const std::string &, b2Vec2 *) = &YPT::ConvertStrToVec2;
	bool (*pStrToBool)(const std::string &, bool *) = &YPT::ConvertStrToBool;
	bool (*pFloatToStr)(float, std::string *) = &YPT::ConvertFloatToStr;
	bool (*pVec2ToStr)(const b2Vec2 &, std::string *) = &YPT::ConvertVec2ToStr;
	bool (*pBoolToStr)(bool, std::string *) = &YPT::ConvertBoolToStr;

	boost::function<bool (int, std::string *)> IntToStr(pIntToStr);
	boost::function<bool (const std::string &, int *)> StrToInt(pStrToInt);
	boost::function<bool (const std::string &, float *)> StrToFloat(pStrToFloat);
	boost::function<bool (const std::string &, b2Vec2 *)> StrToVec2(pStrToVec2);
	boost::function<bool (const std::string &, bool *)> StrToBool(pStrToBool);
	boost::function<bool (float, std::string *)> FloatToStr(pFloatToStr);
	boost::function<bool (const b2Vec2 &, std::string *)> Vec2ToStr(pVec2ToStr);
	boost::function<bool (bool, std::string *)> BoolToStr(pBoolToStr);

	// test - ConvertIntToStr
	std::cout << std::endl << "---YPT::ConvertIntToStr" << std::endl;
	for (IntIterator it = intCases.begin(); it != intCases.end(); ++it) {
		Test(IntToStr, *it);
	}

	// test - ConvertStrToInt
	std::cout << std::endl << "---YPT::ConvertStrToInt" << std::endl;
	for (StrIterator it = strIntCases.begin(); it != strIntCases.end(); ++it) {
		Test(StrToInt, *it);
	}

	// test - ConvertStrToFloat
	std::cout << std::endl << "---YPT::ConvertStrToFloat" << std::endl;
	for (StrIterator it = strFloatCases.begin(); it != strFloatCases.end(); ++it) {
		Test(StrToFloat, *it);
	}

	// test - ConvertStrToVec2
	std::cout << std::endl << "---YPT::ConvertStrToVec2" << std::endl;
	for (StrIterator it = strVec2Cases.begin(); it != strVec2Cases.end(); ++it) {
		Test(StrToVec2, *it);
	}

	// test - ConvertStrToBool
	std::cout << std::endl << "---YPT::ConvertStrToBool" << std::endl;
	for (StrIterator it = strBoolCases.begin(); it != strBoolCases.end(); ++it) {
		Test(StrToBool, *it);
	}

	// test - ConvertFloatToStr
	std::cout << std::endl << "---YPT::ConvertFloatToStr" << std::endl;
	for (FloatIterator it = floatCases.begin(); it != floatCases.end(); ++it) {
		Test(FloatToStr, *it);
	}

	// test - ConvertVec2ToStr
	std::cout << std::endl << "---YPT::ConvertVec2ToStr" << std::endl;
	for (Vec2Iterator it = vec2Cases.begin(); it != vec2Cases.end(); ++it) {
		Test(Vec2ToStr, *it);
	}

	// test - ConvertBoolToStr
	std::cout << std::endl << "---YPT::ConvertBoolToStr" << std::endl;
	for (BoolIterator it = boolCases.begin(); it != boolCases.end(); ++it) {
		Test(BoolToStr, *it);
	}

	return 0;
}
Exemple #10
0
CPLErr GDALWMSDataset::Initialize(CPLXMLNode *config) {
    CPLErr ret = CE_None;

    char* pszXML = CPLSerializeXMLTree( config );
    if (pszXML)
    {
        m_osXML = pszXML;
        CPLFree(pszXML);
    }

    // Initialize the minidriver, which can set parameters for the dataset using member functions
    CPLXMLNode *service_node = CPLGetXMLNode(config, "Service");
    if (service_node != NULL)
    {
        const CPLString service_name = CPLGetXMLValue(service_node, "name", "");
        if (!service_name.empty())
        {
            GDALWMSMiniDriverManager *const mdm = GetGDALWMSMiniDriverManager();
            GDALWMSMiniDriverFactory *const mdf = mdm->Find(service_name);
            if (mdf != NULL)
            {
                m_mini_driver = mdf->New();
                m_mini_driver->m_parent_dataset = this;
                if (m_mini_driver->Initialize(service_node) == CE_None)
                {
                    m_mini_driver_caps.m_capabilities_version = -1;
                    m_mini_driver->GetCapabilities(&m_mini_driver_caps);
                    if (m_mini_driver_caps.m_capabilities_version == -1)
                    {
                        CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Internal error, mini-driver capabilities version not set.");
                        ret = CE_Failure;
                    }
                }
                else
                {
                    delete m_mini_driver;
                    m_mini_driver = NULL;

                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Failed to initialize minidriver.");
                    ret = CE_Failure;
                }
            }
            else
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "GDALWMS: No mini-driver registered for '%s'.", service_name.c_str());
                ret = CE_Failure;
            }
        }
        else
        {
            CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: No Service specified.");
            ret = CE_Failure;
        }
    }
    else
    {
        CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: No Service specified.");
        ret = CE_Failure;
    }


    /*
      Parameters that could be set by minidriver already, based on server side information.
      If the size is set, minidriver has done this already
      A "server" side minidriver needs to set at least:
      - Blocksize (x and y)
      - Clamp flag (defaults to true)
      - DataWindow
      - Band Count
      - Data Type
      It should also initialize and register the bands and overviews.
    */

    if (m_data_window.m_sx<1)
    {
        int nOverviews = 0;

        if (ret == CE_None)
        {
            m_block_size_x = atoi(CPLGetXMLValue(config, "BlockSizeX", CPLString().Printf("%d", m_default_block_size_x)));
            m_block_size_y = atoi(CPLGetXMLValue(config, "BlockSizeY", CPLString().Printf("%d", m_default_block_size_y)));
            if (m_block_size_x <= 0 || m_block_size_y <= 0)
            {
                CPLError( CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value in BlockSizeX or BlockSizeY" );
                ret = CE_Failure;
            }
        }

        if (ret == CE_None)
        {
            m_clamp_requests = StrToBool(CPLGetXMLValue(config, "ClampRequests", "true"));
            if (m_clamp_requests<0)
            {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of ClampRequests, true/false expected.");
                ret = CE_Failure;
            }
        }

        if (ret == CE_None)
        {
            CPLXMLNode *data_window_node = CPLGetXMLNode(config, "DataWindow");
            if (data_window_node == NULL && m_bNeedsDataWindow)
            {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: DataWindow missing.");
                ret = CE_Failure;
            }
            else
            {
                CPLString osDefaultX0, osDefaultX1, osDefaultY0, osDefaultY1;
                CPLString osDefaultTileCountX, osDefaultTileCountY, osDefaultTileLevel;
                CPLString osDefaultOverviewCount;
                osDefaultX0.Printf("%.8f", m_default_data_window.m_x0);
                osDefaultX1.Printf("%.8f", m_default_data_window.m_x1);
                osDefaultY0.Printf("%.8f", m_default_data_window.m_y0);
                osDefaultY1.Printf("%.8f", m_default_data_window.m_y1);
                osDefaultTileCountX.Printf("%d", m_default_tile_count_x);
                osDefaultTileCountY.Printf("%d", m_default_tile_count_y);
                if (m_default_data_window.m_tlevel >= 0)
                    osDefaultTileLevel.Printf("%d", m_default_data_window.m_tlevel);
                if (m_default_overview_count >= 0)
                    osDefaultOverviewCount.Printf("%d", m_default_overview_count);
                const char *overview_count = CPLGetXMLValue(config, "OverviewCount", osDefaultOverviewCount);
                const char *ulx = CPLGetXMLValue(data_window_node, "UpperLeftX", osDefaultX0);
                const char *uly = CPLGetXMLValue(data_window_node, "UpperLeftY", osDefaultY0);
                const char *lrx = CPLGetXMLValue(data_window_node, "LowerRightX", osDefaultX1);
                const char *lry = CPLGetXMLValue(data_window_node, "LowerRightY", osDefaultY1);
                const char *sx = CPLGetXMLValue(data_window_node, "SizeX", "");
                const char *sy = CPLGetXMLValue(data_window_node, "SizeY", "");
                const char *tx = CPLGetXMLValue(data_window_node, "TileX", "0");
                const char *ty = CPLGetXMLValue(data_window_node, "TileY", "0");
                const char *tlevel = CPLGetXMLValue(data_window_node, "TileLevel", osDefaultTileLevel);
                const char *str_tile_count_x = CPLGetXMLValue(data_window_node, "TileCountX", osDefaultTileCountX);
                const char *str_tile_count_y = CPLGetXMLValue(data_window_node, "TileCountY", osDefaultTileCountY);
                const char *y_origin = CPLGetXMLValue(data_window_node, "YOrigin", "default");

                if (ret == CE_None)
                {
                    if ((ulx[0] != '\0') && (uly[0] != '\0') && (lrx[0] != '\0') && (lry[0] != '\0'))
                    {
                        m_data_window.m_x0 = CPLAtof(ulx);
                        m_data_window.m_y0 = CPLAtof(uly);
                        m_data_window.m_x1 = CPLAtof(lrx);
                        m_data_window.m_y1 = CPLAtof(lry);
                    }
                    else
                    {
                        CPLError(CE_Failure, CPLE_AppDefined,
                                 "GDALWMS: Mandatory elements of DataWindow missing: UpperLeftX, UpperLeftY, LowerRightX, LowerRightY.");
                        ret = CE_Failure;
                    }
                }

                m_data_window.m_tlevel = atoi(tlevel);

                if (ret == CE_None)
                {
                    if ((sx[0] != '\0') && (sy[0] != '\0'))
                    {
                        m_data_window.m_sx = atoi(sx);
                        m_data_window.m_sy = atoi(sy);
                    }
                    else if ((tlevel[0] != '\0') && (str_tile_count_x[0] != '\0') && (str_tile_count_y[0] != '\0'))
                    {
                        int tile_count_x = atoi(str_tile_count_x);
                        int tile_count_y = atoi(str_tile_count_y);
                        m_data_window.m_sx = tile_count_x * m_block_size_x * (1 << m_data_window.m_tlevel);
                        m_data_window.m_sy = tile_count_y * m_block_size_y * (1 << m_data_window.m_tlevel);
                    }
                    else
                    {
                        CPLError(CE_Failure, CPLE_AppDefined,
                                 "GDALWMS: Mandatory elements of DataWindow missing: SizeX, SizeY.");
                        ret = CE_Failure;
                    }
                }
                if (ret == CE_None)
                {
                    if ((tx[0] != '\0') && (ty[0] != '\0'))
                    {
                        m_data_window.m_tx = atoi(tx);
                        m_data_window.m_ty = atoi(ty);
                    }
                    else
                    {
                        CPLError(CE_Failure, CPLE_AppDefined,
                                 "GDALWMS: Mandatory elements of DataWindow missing: TileX, TileY.");
                        ret = CE_Failure;
                    }
                }

                if (ret == CE_None)
                {
                    if (overview_count[0] != '\0')
                    {
                        nOverviews = atoi(overview_count);
                    }
                    else if (tlevel[0] != '\0')
                    {
                        nOverviews = m_data_window.m_tlevel;
                    }
                    else
                    {
                        const int min_overview_size = MAX(32, MIN(m_block_size_x, m_block_size_y));
                        double a = log(static_cast<double>(MIN(m_data_window.m_sx, m_data_window.m_sy))) / log(2.0)
                            - log(static_cast<double>(min_overview_size)) / log(2.0);
                        nOverviews = MAX(0, MIN(static_cast<int>(ceil(a)), 32));
                    }
                }
                if (ret == CE_None)
                {
                    CPLString y_origin_str = y_origin;
                    if (y_origin_str == "top") {
                        m_data_window.m_y_origin = GDALWMSDataWindow::TOP;
                    } else if (y_origin_str == "bottom") {
                        m_data_window.m_y_origin = GDALWMSDataWindow::BOTTOM;
                    } else if (y_origin_str == "default") {
                        m_data_window.m_y_origin = GDALWMSDataWindow::DEFAULT;
                    } else {
                        CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: DataWindow YOrigin must be set to "
                                 "one of 'default', 'top', or 'bottom', not '%s'.", y_origin_str.c_str());
                        ret = CE_Failure;
                    }
                }
            }
        }

        if (ret == CE_None)
        {
            if (nBands<1)
                nBands=atoi(CPLGetXMLValue(config,"BandsCount","3"));
            if (nBands<1)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "GDALWMS: Bad number of bands.");
                ret = CE_Failure;
            }
        }

        if (ret == CE_None)
        {
            const char *data_type = CPLGetXMLValue(config, "DataType", "Byte");
            m_data_type = GDALGetDataTypeByName( data_type );
            if ( m_data_type == GDT_Unknown || m_data_type >= GDT_TypeCount )
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                          "GDALWMS: Invalid value in DataType. Data type \"%s\" is not supported.", data_type );
                ret = CE_Failure;
            }
        }

        // Initialize the bands and the overviews.  Assumes overviews are powers of two
        if (ret == CE_None)
        {
            nRasterXSize = m_data_window.m_sx;
            nRasterYSize = m_data_window.m_sy;

            if (!GDALCheckDatasetDimensions(nRasterXSize, nRasterYSize) ||
                !GDALCheckBandCount(nBands, TRUE))
            {
                return CE_Failure;
            }

            GDALColorInterp default_color_interp[4][4] = {
                { GCI_GrayIndex, GCI_Undefined, GCI_Undefined, GCI_Undefined },
                { GCI_GrayIndex, GCI_AlphaBand, GCI_Undefined, GCI_Undefined },
                { GCI_RedBand, GCI_GreenBand, GCI_BlueBand, GCI_Undefined },
                { GCI_RedBand, GCI_GreenBand, GCI_BlueBand, GCI_AlphaBand }
            };
            for (int i = 0; i < nBands; ++i)
            {
                GDALColorInterp color_interp = (nBands <= 4 && i <= 3 ? default_color_interp[nBands - 1][i] : GCI_Undefined);
                GDALWMSRasterBand *band = new GDALWMSRasterBand(this, i, 1.0);
                band->m_color_interp = color_interp;
                SetBand(i + 1, band);
                double scale = 0.5;
                for (int j = 0; j < nOverviews; ++j)
                {
                    band->AddOverview(scale);
                    band->m_color_interp = color_interp;
                    scale *= 0.5;
                }
            }
        }
    }
    
    // UserPwd 
    const char *pszUserPwd = CPLGetXMLValue(config, "UserPwd", "");
    if (pszUserPwd[0] != '\0')
        m_osUserPwd = pszUserPwd;

    const char *pszUserAgent = CPLGetXMLValue(config, "UserAgent", "");
    if (pszUserAgent[0] != '\0')
        m_osUserAgent = pszUserAgent;
    
    const char *pszReferer = CPLGetXMLValue(config, "Referer", "");
    if (pszReferer[0] != '\0')
        m_osReferer = pszReferer;
    
    if (ret == CE_None) {
        const char *pszHttpZeroBlockCodes = CPLGetXMLValue(config, "ZeroBlockHttpCodes", "");
        if(pszHttpZeroBlockCodes[0] == '\0') {
            m_http_zeroblock_codes.push_back(204);
        } else {
            char **kv = CSLTokenizeString2(pszHttpZeroBlockCodes,",",CSLT_HONOURSTRINGS);
            int nCount = CSLCount(kv);
            for(int i=0; i<nCount; i++) {
                int code = atoi(kv[i]);
                if(code <= 0) {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of ZeroBlockHttpCodes \"%s\", comma separated HTTP response codes expected.",
                             kv[i]);
                    ret = CE_Failure;
                    break;
                }
                m_http_zeroblock_codes.push_back(code);
            }
            CSLDestroy(kv);
        }
    }

    if (ret == CE_None) {
        const char *pszZeroExceptions = CPLGetXMLValue(config, "ZeroBlockOnServerException", "");
        if(pszZeroExceptions[0] != '\0') {
            m_zeroblock_on_serverexceptions = StrToBool(pszZeroExceptions);
            if (m_zeroblock_on_serverexceptions == -1) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of ZeroBlockOnServerException \"%s\", true/false expected.",
                         pszZeroExceptions);
                ret = CE_Failure;
            }
        }
    }

    if (ret == CE_None) {
        const char *max_conn = CPLGetXMLValue(config, "MaxConnections", "");
        if (max_conn[0] != '\0') {
            m_http_max_conn = atoi(max_conn);
        } else {
            m_http_max_conn = 2;
        }
    }
    if (ret == CE_None) {
        const char *timeout = CPLGetXMLValue(config, "Timeout", "");
        if (timeout[0] != '\0') {
            m_http_timeout = atoi(timeout);
        } else {
            m_http_timeout = 300;
        }
    }
    if (ret == CE_None) {
        const char *offline_mode = CPLGetXMLValue(config, "OfflineMode", "");
        if (offline_mode[0] != '\0') {
            const int offline_mode_bool = StrToBool(offline_mode);
            if (offline_mode_bool == -1) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of OfflineMode, true / false expected.");
                ret = CE_Failure;
            } else {
                m_offline_mode = offline_mode_bool;
            }
        } else {
            m_offline_mode = 0;
        }
    }

    if (ret == CE_None) {
        const char *advise_read = CPLGetXMLValue(config, "AdviseRead", "");
        if (advise_read[0] != '\0') {
            const int advise_read_bool = StrToBool(advise_read);
            if (advise_read_bool == -1) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of AdviseRead, true / false expected.");
                ret = CE_Failure;
            } else {
                m_use_advise_read = advise_read_bool;
            }
        } else {
            m_use_advise_read = 0;
        }
    }

    if (ret == CE_None) {
        const char *verify_advise_read = CPLGetXMLValue(config, "VerifyAdviseRead", "");
        if (m_use_advise_read) {
            if (verify_advise_read[0] != '\0') {
                const int verify_advise_read_bool = StrToBool(verify_advise_read);
                if (verify_advise_read_bool == -1) {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of VerifyAdviseRead, true / false expected.");
                    ret = CE_Failure;
                } else {
                    m_verify_advise_read = verify_advise_read_bool;
                }
            } else {
                m_verify_advise_read = 1;
            }
        }
    }

    // Let the local configuration override the minidriver supplied projection

    if (ret == CE_None) {
        const char *proj = CPLGetXMLValue(config, "Projection", "");
        if (proj[0] != '\0') {
            m_projection = ProjToWKT(proj);
            if (m_projection.size() == 0) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Bad projection specified.");
                ret = CE_Failure;
            }
        }
    }

    // Same for Min, Max and NoData, defined per band or per dataset
    // If they are set as null strings, they clear the server declared values
    if (ret == CE_None) {
        // Data values are attributes, they include NoData Min and Max
        // TODO: document those options
        if (0!=CPLGetXMLNode(config,"DataValues")) {
            const char *nodata=CPLGetXMLValue(config,"DataValues.NoData",NULL);
            if (nodata!=NULL) WMSSetNoDataValue(nodata);
            const char *min=CPLGetXMLValue(config,"DataValues.min",NULL);
            if (min!=NULL) WMSSetMinValue(min);
            const char *max=CPLGetXMLValue(config,"DataValues.max",NULL);
            if (max!=NULL) WMSSetMaxValue(max);
        }
    }

    if (ret == CE_None) {
        CPLXMLNode *cache_node = CPLGetXMLNode(config, "Cache");
        if (cache_node != NULL) {
            m_cache = new GDALWMSCache();
            if (m_cache->Initialize(cache_node) != CE_None) {
                delete m_cache;
                m_cache = NULL;
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Failed to initialize cache.");
                ret = CE_Failure;
            }
        }
    }
    
    if (ret == CE_None) {
    	const int v = StrToBool(CPLGetXMLValue(config, "UnsafeSSL", "false"));
    	if (v == -1) {
	    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of UnsafeSSL: true or false expected.");
	    ret = CE_Failure;
	} else {
	    m_unsafeSsl = v;
	}
    }

    if (ret == CE_None) {
        /* If we dont have projection already set ask mini-driver. */
        if (!m_projection.size()) {
            const char *proj = m_mini_driver->GetProjectionInWKT();
            if (proj != NULL) {
                m_projection = proj;
            }
        }
    }

    return ret;
}
Exemple #11
0
nsresult nsMsgFilterList::LoadTextFilters(nsIInputStream *aStream)
{
  nsresult  err = NS_OK;
  uint64_t bytesAvailable;

  nsCOMPtr<nsIInputStream> bufStream;
  err = NS_NewBufferedInputStream(getter_AddRefs(bufStream), aStream, 10240);
  NS_ENSURE_SUCCESS(err, err);

  nsMsgFilterFileAttribValue attrib;
  nsCOMPtr<nsIMsgRuleAction> currentFilterAction;
  // We'd really like to move lot's of these into the objects that they refer to.
  do
  {
    nsAutoCString value;
    nsresult intToStringResult;

    char curChar;
    curChar = LoadAttrib(attrib, bufStream);
    if (curChar == (char) -1)  //reached eof
      break;
    err = LoadValue(value, bufStream);
    if (NS_FAILED(err))
      break;

    switch(attrib)
    {
    case nsIMsgFilterList::attribNone:
      if (m_curFilter)
        m_curFilter->SetUnparseable(true);
      break;
    case nsIMsgFilterList::attribVersion:
      m_fileVersion = value.ToInteger(&intToStringResult);
      if (NS_FAILED(intToStringResult))
      {
        attrib = nsIMsgFilterList::attribNone;
        NS_ASSERTION(false, "error parsing filter file version");
      }
      break;
    case nsIMsgFilterList::attribLogging:
      m_loggingEnabled = StrToBool(value);
      m_unparsedFilterBuffer.Truncate(); //we are going to buffer each filter as we read them, make sure no garbage is there
      m_startWritingToBuffer = true; //filters begin now
      break;
    case nsIMsgFilterList::attribName:  //every filter starts w/ a name
      {
        if (m_curFilter)
        {
          int32_t nextFilterStartPos = m_unparsedFilterBuffer.RFind("name");

          nsAutoCString nextFilterPart;
          nextFilterPart = Substring(m_unparsedFilterBuffer, nextFilterStartPos, m_unparsedFilterBuffer.Length());
          m_unparsedFilterBuffer.SetLength(nextFilterStartPos);

          bool unparseableFilter;
          m_curFilter->GetUnparseable(&unparseableFilter);
          if (unparseableFilter)
          {
            m_curFilter->SetUnparsedBuffer(m_unparsedFilterBuffer);
            m_curFilter->SetEnabled(false); //disable the filter because we don't know how to apply it
          }
          m_unparsedFilterBuffer = nextFilterPart;
        }
        nsMsgFilter *filter = new nsMsgFilter;
        if (filter == nullptr)
        {
          err = NS_ERROR_OUT_OF_MEMORY;
          break;
        }
        filter->SetFilterList(static_cast<nsIMsgFilterList*>(this));
        if (m_fileVersion == k45Version)
        {
          nsAutoString unicodeStr;
          err = nsMsgI18NConvertToUnicode(nsMsgI18NFileSystemCharset(),
                                          value, unicodeStr);
          if (NS_FAILED(err))
              break;

          filter->SetFilterName(unicodeStr);
        }
        else
        {
          // ### fix me - this is silly.
          PRUnichar *unicodeString =
            nsTextFormatter::smprintf(unicodeFormatter, value.get());
          filter->SetFilterName(nsDependentString(unicodeString));
          nsTextFormatter::smprintf_free(unicodeString);
        }
        m_curFilter = filter;
        m_filters.AppendElement(filter);
      }
      break;
    case nsIMsgFilterList::attribEnabled:
      if (m_curFilter)
        m_curFilter->SetEnabled(StrToBool(value));
      break;
    case nsIMsgFilterList::attribDescription:
      if (m_curFilter)
        m_curFilter->SetFilterDesc(value);
      break;
    case nsIMsgFilterList::attribType:
      if (m_curFilter)
      {
        // Older versions of filters didn't have the ability to turn on/off the
        // manual filter context, so default manual to be on in that case
        int32_t filterType = value.ToInteger(&intToStringResult);
        if (m_fileVersion < kManualContextVersion)
          filterType |= nsMsgFilterType::Manual;
        m_curFilter->SetType((nsMsgFilterTypeType) filterType);
      }
      break;
    case nsIMsgFilterList::attribScriptFile:
      if (m_curFilter)
        m_curFilter->SetFilterScript(&value);
      break;
    case nsIMsgFilterList::attribAction:
      if (m_curFilter)
      {
        nsMsgRuleActionType actionType = nsMsgFilter::GetActionForFilingStr(value);
        if (actionType == nsMsgFilterAction::None)
          m_curFilter->SetUnparseable(true);
        else
        {
          err = m_curFilter->CreateAction(getter_AddRefs(currentFilterAction));
          NS_ENSURE_SUCCESS(err, err);
          currentFilterAction->SetType(actionType);
          m_curFilter->AppendAction(currentFilterAction);
        }
      }
      break;
    case nsIMsgFilterList::attribActionValue:
      if (m_curFilter && currentFilterAction)
      {
        nsMsgRuleActionType type;
        currentFilterAction->GetType(&type);
        if (type == nsMsgFilterAction::MoveToFolder ||
              type == nsMsgFilterAction::CopyToFolder)
          err = m_curFilter->ConvertMoveOrCopyToFolderValue(currentFilterAction, value);
        else if (type == nsMsgFilterAction::ChangePriority)
        {
          nsMsgPriorityValue outPriority;
          nsresult res = NS_MsgGetPriorityFromString(value.get(), outPriority);
          if (NS_SUCCEEDED(res))
            currentFilterAction->SetPriority(outPriority);
          else
            NS_ASSERTION(false, "invalid priority in filter file");
        }
        else if (type == nsMsgFilterAction::Label)
        {
          // upgrade label to corresponding tag/keyword
          nsresult res;
          int32_t labelInt = value.ToInteger(&res);
          if (NS_SUCCEEDED(res))
          {
            nsAutoCString keyword("$label");
            keyword.Append('0' + labelInt);
            currentFilterAction->SetType(nsMsgFilterAction::AddTag);
            currentFilterAction->SetStrValue(keyword);
          }
        }
        else if (type == nsMsgFilterAction::JunkScore)
        {
          nsresult res;
          int32_t junkScore = value.ToInteger(&res);
          if (NS_SUCCEEDED(res))
            currentFilterAction->SetJunkScore(junkScore);
        }
        else if (type == nsMsgFilterAction::Forward ||
                 type == nsMsgFilterAction::Reply ||
                 type == nsMsgFilterAction::AddTag ||
                 type == nsMsgFilterAction::Custom)
        {
          currentFilterAction->SetStrValue(value);
        }
      }
      break;
    case nsIMsgFilterList::attribCondition:
      if (m_curFilter)
      {
        if (m_fileVersion == k45Version)
        {
          nsAutoString unicodeStr;
          err = nsMsgI18NConvertToUnicode(nsMsgI18NFileSystemCharset(),
                                          value, unicodeStr);
          if (NS_FAILED(err))
              break;

          char *utf8 = ToNewUTF8String(unicodeStr);
          value.Assign(utf8);
          nsMemory::Free(utf8);
        }
        err = ParseCondition(m_curFilter, value.get());
        if (err == NS_ERROR_INVALID_ARG)
          err = m_curFilter->SetUnparseable(true);
        NS_ENSURE_SUCCESS(err, err);
      }
      break;
    case nsIMsgFilterList::attribCustomId:
      if (m_curFilter && currentFilterAction)
      {
        err = currentFilterAction->SetCustomId(value);
        NS_ENSURE_SUCCESS(err, err);
      }
      break;

    }
  } while (NS_SUCCEEDED(bufStream->Available(&bytesAvailable)));

  if (m_curFilter)
  {
    bool unparseableFilter;
    m_curFilter->GetUnparseable(&unparseableFilter);
    if (unparseableFilter)
    {
      m_curFilter->SetUnparsedBuffer(m_unparsedFilterBuffer);
      m_curFilter->SetEnabled(false);  //disable the filter because we don't know how to apply it
    }
  }

  return err;
}
Exemple #12
0
void TDataManager::KHRParse(AnsiString fileName)
{
// создаёт новую структуру КХР, разбирает все данные из xml-файла и заполняет
	// вызывает функцию контроллера AddKHR(TKHR *khr)
	// контроллер добавляет КХР в вектор элементов
	TKHR *khr = new TKHR;

	//---------------------------
	// открытие xml-файла
	string temp =  fileName.c_str();
	khr->path = temp;
	formMain->xmlReader->LoadFromFile(UnicodeString(fileName.c_str()));
	// parse xml
	try
	{
		_di_IXMLNode Root = formMain->xmlReader->DocumentElement;
		khr->szNumber 		= VARSTR(Root->Attributes["number"]);
		khr->szTitle  		= VARSTR(Root->Attributes["name"]);
		khr->dtStartDate	= StrToDate(VARSTR(Root->Attributes["begin"]));
		khr->szOrder 		= VARSTR(Root->Attributes["orderNum"]);
		khr->szFileName 	= VARSTR(Root->Attributes["file"]);
		//-----------------------------------------------------------------------------------------
		// разбираем вложенные теги КХР
		for (int i=0; i < Root->ChildNodes->Count; i++)
		{
			// работы
			if (Root->ChildNodes->Nodes[i]->NodeName == "work")
			{
				TWork *work = new TWork;
				_di_IXMLNode oneWork = Root->ChildNodes->Nodes[i];
				work->ulWorkNum = int(oneWork->Attributes["number"]);
				work->bPayment 	= StrToBool(VARSTR(oneWork->Attributes["type"]));
				work->szTitle 	= VARSTR(oneWork->Attributes["name"]);
				work->dtStart 	= StrToDate(VARSTR(oneWork->Attributes["begin"]));
				work->dtEnd 	= StrToDate(VARSTR(oneWork->Attributes["end"]));
				work->dtMoveTo 	= StrToDate(VARSTR(oneWork->Attributes["move"]));
				work->ulLength 	= int(oneWork->Attributes["length"]);
				work->havePayment 	= StrToBool(VARSTR(oneWork->Attributes["pay"]));
				work->haveStage 	= StrToBool(VARSTR(oneWork->Attributes["stage"]));
				work->eWorkState    = int(oneWork->Attributes["state"]);
				work->center.x 		= float(oneWork->Attributes["x"]);
				work->center.y		= float(oneWork->Attributes["y"]);
				// вспомогательные переменные
				int iCmdCounter = 0; // счетчик команд работы

				// вложенные теги работы
				for (int j=0; j < oneWork->ChildNodes->Count; j++)
				{
					// точки связи к доплате
					if (oneWork->ChildNodes->Nodes[j]->NodeName == "paypoint")
					{
						_di_IXMLNode point = oneWork->ChildNodes->Nodes[j];
						T2d dot;
						dot.x = float(point->Attributes["x"]);
						dot.y = float(point->Attributes["y"]);
						work->connectPayment.push_back(dot);
					}
					// исполнители
					else if (oneWork->ChildNodes->Nodes[j]->NodeName == "executor")
					{
						TWorkVolume *vol = new TWorkVolume;
						_di_IXMLNode oneEx = oneWork->ChildNodes->Nodes[j];
						vol->ulExecutor = int(oneEx->Attributes["number"]);

						for (int k=0; k < oneEx->ChildNodes->Count; k++)
						{
							if (oneEx->ChildNodes->Nodes[k]->NodeName == "quartvol")
							{
								_di_IXMLNode oneVol = oneEx->ChildNodes->Nodes[k];
								vol->ulVolume[k] = int(oneVol->Attributes["volume"]);
							}
						}
						work->WorkVolume.push_back(vol);
					}
					// зависимости
					else if (oneWork->ChildNodes->Nodes[j]->NodeName == "dependence")
					{

						TDependance *dep 	= new TDependance;
						_di_IXMLNode oneDep = oneWork->ChildNodes->Nodes[j];
						dep->bNeedToStart 	= StrToBool(VARSTR(oneDep->Attributes["need"]));
						dep->ulWork			= int(oneDep->Attributes["work"]);
						work->WorkDep.push_back(dep);
					}
					// команды
					else if (oneWork->ChildNodes->Nodes[j]->NodeName == "command")
					{
						_di_IXMLNode oneCmd = oneWork->ChildNodes->Nodes[j];
						work->eCommand[iCmdCounter++] = int(oneCmd->Attributes["code"]);
					}
				}

				khr->Works.push_back(work);
			}
			// доплаты
			else if (Root->ChildNodes->Nodes[i]->NodeName == "payment")
			{
				TWork *work = new TWork;
				_di_IXMLNode oneWork = Root->ChildNodes->Nodes[i];
				work->ulWorkNum = int(oneWork->Attributes["number"]);
				work->bPayment 	= StrToBool(VARSTR(oneWork->Attributes["type"]));
				work->szTitle 	= VARSTR(oneWork->Attributes["name"]);
				work->dtStart 	= StrToDate(VARSTR(oneWork->Attributes["begin"]));
				work->dtEnd 	= StrToDate(VARSTR(oneWork->Attributes["end"]));
				work->dtMoveTo 	= StrToDate(VARSTR(oneWork->Attributes["move"]));
				work->ulLength 	= int(oneWork->Attributes["length"]);
				work->eWorkState    = int(oneWork->Attributes["state"]);
				work->center.x 		= float(oneWork->Attributes["x"]);
				work->center.y		= float(oneWork->Attributes["y"]);
				// вспомогательные переменные
				int iCmdCounter = 0; // счетчик команд работы

				// вложенные теги доплаты
				for (int j=0; j < oneWork->ChildNodes->Count; j++)
				{
					// исполнители
					if (oneWork->ChildNodes->Nodes[j]->NodeName == "executor")
					{
						TWorkVolume *vol = new TWorkVolume;
						_di_IXMLNode oneEx = oneWork->ChildNodes->Nodes[j];
						vol->ulExecutor = int(oneEx->Attributes["number"]);

						for (int k=0; k < oneEx->ChildNodes->Count; k++)
						{
							if (oneEx->ChildNodes->Nodes[k]->NodeName == "quartvol")
							{
								_di_IXMLNode oneVol = oneEx->ChildNodes->Nodes[k];
								vol->ulVolume[k] = int(oneVol->Attributes["volume"]);
							}
						}
						work->WorkVolume.push_back(vol);
					}
					// зависимости
					else if (oneWork->ChildNodes->Nodes[j]->NodeName == "dependence")
					{

						TDependance *dep 	= new TDependance;
						_di_IXMLNode oneDep = oneWork->ChildNodes->Nodes[j];
						dep->bNeedToStart 	= StrToBool(VARSTR(oneDep->Attributes["need"]));
						dep->ulWork			= int(oneDep->Attributes["work"]);
						work->WorkDep.push_back(dep);
					}
					// команды
					else if (oneWork->ChildNodes->Nodes[j]->NodeName == "command")
					{
						_di_IXMLNode oneCmd = oneWork->ChildNodes->Nodes[j];
						work->eCommand[iCmdCounter++] = int(oneCmd->Attributes["code"]);
					}
				}

				khr->Payments.push_back(work);
			}
			// ссылки
			else if (Root->ChildNodes->Nodes[i]->NodeName == "link")
			{
				TLink *link = new TLink;
				_di_IXMLNode oneLink = Root->ChildNodes->Nodes[i];

				link->ulWorkNum = int(oneLink->Attributes["number"]);
				link->slText->Text 	= VARSTR(oneLink->Attributes["text"]);
				link->dtDate 	= StrToDate(VARSTR(oneLink->Attributes["date"]));
				link->szNumber  = VARSTR(oneLink->Attributes["khrnum"]);
				link->center.x 	= float(oneLink->Attributes["x"]);
				link->center.y 	= float(oneLink->Attributes["y"]);

				// вложенные теги ссылки
				for (int j=0; j < oneLink->ChildNodes->Count; j++)
				{
					// зависимости
					if (oneLink->ChildNodes->Nodes[j]->NodeName == "linkdependence")
					{
						TDependance *dep 	= new TDependance;
						_di_IXMLNode oneDep = oneLink->ChildNodes->Nodes[j];
						dep->bNeedToStart 	= StrToBool(VARSTR(oneDep->Attributes["need"]));
						dep->ulWork			= int(oneDep->Attributes["num"]);
						link->WorkDep.push_back(dep);
					}
				}

				khr->Links.push_back(link);
			}
			// вехи
			else if (Root->ChildNodes->Nodes[i]->NodeName == "stage")
			{
				TStage *nstage = new TStage;
				_di_IXMLNode oneStage = Root->ChildNodes->Nodes[i];
				nstage->ulStageNum = int(oneStage->Attributes["number"]);
				nstage->center.x  =  float(oneStage->Attributes["x"]);
				nstage->center.y  =  float(oneStage->Attributes["y"]);

				// вложенные теги вехи
				for(int j=0; j<oneStage->ChildNodes->Count; j++)
				{
					// точки связи
					if (oneStage->ChildNodes->Nodes[j]->NodeName == "point")
					{
						T2d point;
						_di_IXMLNode onePoint = oneStage->ChildNodes->Nodes[j];
						point.x = float(onePoint->Attributes["x"]);
						point.y = float(onePoint->Attributes["y"]);
						nstage->connect.push_back(point);
					}
				}

				khr->Stages.push_back(nstage);
			}
			// стрелки
			else if (Root->ChildNodes->Nodes[i]->NodeName == "connect")
			{
				TConnection *connect = new TConnection;
				_di_IXMLNode oneLine = Root->ChildNodes->Nodes[i];
				connect->begin = int(oneLine->Attributes["begin"]);
				connect->end = int(oneLine->Attributes["end"]);
				connect->needStart = StrToBool(VARSTR(oneLine->Attributes["need"]));

				// вложенные теги стрелки
				for(int j=0; j<oneLine->ChildNodes->Count; j++)
				{
					T2d point;
					_di_IXMLNode onePoint = oneLine->ChildNodes->Nodes[j];
					point.x = float(onePoint->Attributes["x"]);
					point.y = float(onePoint->Attributes["y"]);
					connect->connect.push_back(point);
				}

				khr->Connects.push_back(connect);
			}
			// исполнители КХР
			else if (Root->ChildNodes->Nodes[i]->NodeName == "executor")
			{
				TExecutor *exec 		= new TExecutor;
				_di_IXMLNode oneExec 	= Root->ChildNodes->Nodes[i];
				exec->id 				= int(oneExec->Attributes["id"]);
				exec->szName			= VARSTR(oneExec->Attributes["name"]);
				khr->Executors.push_back(exec);
			}
			// подписи исполнителей
			else if (Root->ChildNodes->Nodes[i]->NodeName == "signature")
			{
				TSignature *sig 	= new TSignature;
				_di_IXMLNode oneSig = Root->ChildNodes->Nodes[i];
				sig->szChair 		= VARSTR(oneSig->Attributes["chair"]);
				sig->szName  		= VARSTR(oneSig->Attributes["name"]);
				khr->Signatures.push_back(sig);
			}

			khr->selected = true;
		}
	}
	catch(EConvertError* e)
	{
		ShowMessage("Ошибка загрузки файла КХР: "+ e->ToString());
	}
	//---------------------------
	control->addKHR(khr);
}
Exemple #13
0
CPLErr GDALWMSDataset::Initialize(CPLXMLNode *config) {
    CPLErr ret = CE_None;

    if (ret == CE_None) {
        const char *max_conn = CPLGetXMLValue(config, "MaxConnections", "");
        if (max_conn[0] != '\0') {
            m_http_max_conn = atoi(max_conn);
        } else {
            m_http_max_conn = 2;
        }
    }
    if (ret == CE_None) {
        const char *timeout = CPLGetXMLValue(config, "Timeout", "");
        if (timeout[0] != '\0') {
            m_http_timeout = atoi(timeout);
        } else {
            m_http_timeout = 300;
        }
    }
    if (ret == CE_None) {
        const char *offline_mode = CPLGetXMLValue(config, "OfflineMode", "");
        if (offline_mode[0] != '\0') {
            const int offline_mode_bool = StrToBool(offline_mode);
            if (offline_mode_bool == -1) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of OfflineMode, true / false expected.");
                ret = CE_Failure;
            } else {
                m_offline_mode = offline_mode_bool;
            }
        } else {
            m_offline_mode = 0;
        }
    }
    if (ret == CE_None) {
        const char *advise_read = CPLGetXMLValue(config, "AdviseRead", "");
        if (advise_read[0] != '\0') {
            const int advise_read_bool = StrToBool(advise_read);
            if (advise_read_bool == -1) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of AdviseRead, true / false expected.");
                ret = CE_Failure;
            } else {
                m_use_advise_read = advise_read_bool;
            }
        } else {
            m_use_advise_read = 0;
        }
    }
    if (ret == CE_None) {
        const char *verify_advise_read = CPLGetXMLValue(config, "VerifyAdviseRead", "");
        if (m_use_advise_read) {
            if (verify_advise_read[0] != '\0') {
                const int verify_advise_read_bool = StrToBool(verify_advise_read);
                if (verify_advise_read_bool == -1) {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of VerifyAdviseRead, true / false expected.");
                    ret = CE_Failure;
                } else {
                    m_verify_advise_read = verify_advise_read_bool;
                }
            } else {
                m_verify_advise_read = 1;
            }
        }
    }
    if (ret == CE_None) {
        const char *block_size_x = CPLGetXMLValue(config, "BlockSizeX", "1024");
        const char *block_size_y = CPLGetXMLValue(config, "BlockSizeY", "1024");
        m_block_size_x = atoi(block_size_x);
        m_block_size_y = atoi(block_size_y);
        if (m_block_size_x <= 0 || m_block_size_y <= 0)
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "GDALWMS: Invalid value in BlockSizeX or BlockSizeY" );
            ret = CE_Failure;
        }
    }
    if (ret == CE_None)
    {
        const char *data_type = CPLGetXMLValue(config, "DataType", "Byte");
        m_data_type = GDALGetDataTypeByName( data_type );
        if ( m_data_type == GDT_Unknown || m_data_type >= GDT_TypeCount )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "GDALWMS: Invalid value in DataType. Data type \"%s\" is not supported.", data_type );
            ret = CE_Failure;
        }
    }
    if (ret == CE_None) {
    	const int clamp_requests_bool = StrToBool(CPLGetXMLValue(config, "ClampRequests", "true"));
    	if (clamp_requests_bool == -1) {
	    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Invalid value of ClampRequests, true / false expected.");
	    ret = CE_Failure;
	} else {
	    m_clamp_requests = clamp_requests_bool;
	}
    }
    if (ret == CE_None) {
        CPLXMLNode *data_window_node = CPLGetXMLNode(config, "DataWindow");
        if (data_window_node == NULL) {
            CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: DataWindow missing.");
            ret = CE_Failure;
        } else {
            const char *overview_count = CPLGetXMLValue(config, "OverviewCount", "");
            const char *ulx = CPLGetXMLValue(data_window_node, "UpperLeftX", "-180.0");
            const char *uly = CPLGetXMLValue(data_window_node, "UpperLeftY", "90.0");
            const char *lrx = CPLGetXMLValue(data_window_node, "LowerRightX", "180.0");
            const char *lry = CPLGetXMLValue(data_window_node, "LowerRightY", "-90.0");
            const char *sx = CPLGetXMLValue(data_window_node, "SizeX", "");
            const char *sy = CPLGetXMLValue(data_window_node, "SizeY", "");
            const char *tx = CPLGetXMLValue(data_window_node, "TileX", "0");
            const char *ty = CPLGetXMLValue(data_window_node, "TileY", "0");
            const char *tlevel = CPLGetXMLValue(data_window_node, "TileLevel", "");
            const char *str_tile_count_x = CPLGetXMLValue(data_window_node, "TileCountX", "1");
            const char *str_tile_count_y = CPLGetXMLValue(data_window_node, "TileCountY", "1");
            const char *y_origin = CPLGetXMLValue(data_window_node, "YOrigin", "default");

            if (ret == CE_None) {
                if ((ulx[0] != '\0') && (uly[0] != '\0') && (lrx[0] != '\0') && (lry[0] != '\0')) {
                    m_data_window.m_x0 = atof(ulx);
                    m_data_window.m_y0 = atof(uly);
                    m_data_window.m_x1 = atof(lrx);
                    m_data_window.m_y1 = atof(lry);
                } else {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Mandatory elements of DataWindow missing: UpperLeftX, UpperLeftY, LowerRightX, LowerRightY.");
                    ret = CE_Failure;
                }
            }
            if (ret == CE_None) {
                if (tlevel[0] != '\0') {
                    m_data_window.m_tlevel = atoi(tlevel);
                } else {
                    m_data_window.m_tlevel = 0;
                }
            }
            if (ret == CE_None) {
                if ((sx[0] != '\0') && (sy[0] != '\0')) {
                    m_data_window.m_sx = atoi(sx);
                    m_data_window.m_sy = atoi(sy);
                } else if ((tlevel[0] != '\0') && (str_tile_count_x[0] != '\0') && (str_tile_count_y[0] != '\0')) {
                    int tile_count_x = atoi(str_tile_count_x);
                    int tile_count_y = atoi(str_tile_count_y);
                    m_data_window.m_sx = tile_count_x * m_block_size_x * (1 << m_data_window.m_tlevel);
                    m_data_window.m_sy = tile_count_y * m_block_size_y * (1 << m_data_window.m_tlevel);
                } else {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Mandatory elements of DataWindow missing: SizeX, SizeY.");
                    ret = CE_Failure;
                }
            }
            if (ret == CE_None) {
                if ((tx[0] != '\0') && (ty[0] != '\0')) {
                    m_data_window.m_tx = atoi(tx);
                    m_data_window.m_ty = atoi(ty);
                } else {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Mandatory elements of DataWindow missing: TileX, TileY.");
                    ret = CE_Failure;
                }
            }
            if (ret == CE_None) {
                if (overview_count[0] != '\0') {
                    m_overview_count = atoi(overview_count);
                } else if (tlevel[0] != '\0') {
                    m_overview_count = m_data_window.m_tlevel;
                } else {
                    const int min_overview_size = MAX(32, MIN(m_block_size_x, m_block_size_y));
                    double a = log(static_cast<double>(MIN(m_data_window.m_sx, m_data_window.m_sy))) / log(2.0) 
                                - log(static_cast<double>(min_overview_size)) / log(2.0);
                    m_overview_count = MAX(0, MIN(static_cast<int>(ceil(a)), 32));
                }
            }
            if (ret == CE_None) {
                CPLString y_origin_str = y_origin;
                if (y_origin_str == "top") {
                    m_data_window.m_y_origin = GDALWMSDataWindow::TOP;
                } else if (y_origin_str == "bottom") {
                    m_data_window.m_y_origin = GDALWMSDataWindow::BOTTOM;
                } else if (y_origin_str == "default") {
                    m_data_window.m_y_origin = GDALWMSDataWindow::DEFAULT;
                } else {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: DataWindow YOrigin must be set to " 
                                "one of 'default', 'top', or 'bottom', not '%s'.", y_origin_str.c_str());
                    ret = CE_Failure;
                }
            }
        }
    }
    if (ret == CE_None) {
        const char *proj = CPLGetXMLValue(config, "Projection", "");
        if (proj[0] != '\0') {
            m_projection = ProjToWKT(proj);
            if (m_projection.size() == 0) {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Bad projection specified.");
                ret = CE_Failure;
            }
        }
    }
    
    const char *bands_count = CPLGetXMLValue(config, "BandsCount", "3");
    int nBandCount = atoi(bands_count);
    
    if (ret == CE_None) {
        CPLXMLNode *cache_node = CPLGetXMLNode(config, "Cache");
        if (cache_node != NULL) {
            m_cache = new GDALWMSCache();
            if (m_cache->Initialize(cache_node) != CE_None) {
                delete m_cache;
                m_cache = NULL;
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Failed to initialize cache.");
                ret = CE_Failure;
            }
        }
    }
    if (ret == CE_None) {
        CPLXMLNode *service_node = CPLGetXMLNode(config, "Service");
        if (service_node != NULL) {
            const char *service_name = CPLGetXMLValue(service_node, "name", "");
            if (service_name[0] != '\0') {
                GDALWMSMiniDriverManager *const mdm = GetGDALWMSMiniDriverManager();
                GDALWMSMiniDriverFactory *const mdf = mdm->Find(CPLString(service_name));
                if (mdf != NULL) {
                    m_mini_driver = mdf->New();
                    m_mini_driver->m_parent_dataset = this;
                    if (m_mini_driver->Initialize(service_node) == CE_None) {
                        m_mini_driver_caps.m_capabilities_version = -1;
                        m_mini_driver->GetCapabilities(&m_mini_driver_caps);
                        if (m_mini_driver_caps.m_capabilities_version == -1) {
                            CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Internal error, mini-driver capabilities version not set.");
                            ret = CE_Failure;
                        }
                    } else {
                        delete m_mini_driver;
                        m_mini_driver = NULL;

                        CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: Failed to initialize minidriver.");
                        ret = CE_Failure;
                    }
                } else {
                    CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: No mini-driver registered for '%s'.", service_name);
                    ret = CE_Failure;
                }
            } else {
                CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: No Service specified.");
                ret = CE_Failure;
            }
        } else {
            CPLError(CE_Failure, CPLE_AppDefined, "GDALWMS: No Service specified.");
            ret = CE_Failure;
        }
    }
    if (ret == CE_None) {
        nRasterXSize = m_data_window.m_sx;
        nRasterYSize = m_data_window.m_sy;

        if (!GDALCheckDatasetDimensions(nRasterXSize, nRasterYSize) ||
            !GDALCheckBandCount(nBandCount, TRUE))
        {
            return CE_Failure;
        }

        for (int i = 0; i < nBandCount; ++i) {
            GDALWMSRasterBand *band = new GDALWMSRasterBand(this, i, 1.0);
            SetBand(i + 1, band);
            double scale = 0.5;
            for (int j = 0; j < m_overview_count; ++j) {
                band->AddOverview(scale);
                scale *= 0.5;
            }
        }
    }

    if (ret == CE_None) {
        /* If we dont have projection already set ask mini-driver. */
        if (!m_projection.size()) {
            const char *proj = m_mini_driver->GetProjectionInWKT();
            if (proj != NULL) {
                m_projection = proj;
            }
        }
    }

    return ret;
}