static int loadMibFromXmlSource(char *mibSource) { int sourceFile; LoadMibState state; char buf[256]; int done = 0; size_t length; int result = 0; if (*mibSource == '\0') /* Use default file name. */ { mibSource = "amsmib.xml"; } sourceFile = iopen(mibSource, O_RDONLY, 0777); if (sourceFile < 0) { putSysErrmsg("Can't open MIB source file", mibSource); return -1; } memset((char *) &state, 0, sizeof state); state.abandoned = 0; state.currentOperation = LoadDormant; state.parser = XML_ParserCreate(NULL); if (state.parser == NULL) { putSysErrmsg("Can't open XML parser", NULL); close(sourceFile); return -1; } XML_SetElementHandler(state.parser, startElement, endElement); XML_SetUserData(state.parser, &state); while (!done) { length = read(sourceFile, buf, sizeof(buf)); switch (length) { case -1: putSysErrmsg("Failed reading MIB", mibSource); /* Intentional fall-through to next case. */ case 0: /* End of file. */ done = 1; break; default: done = (length < sizeof buf); } if (XML_Parse(state.parser, buf, length, done) == XML_STATUS_ERROR) { isprintf(buf, sizeof buf, "XML error at line %d.", (int) XML_GetCurrentLineNumber(state.parser)); putSysErrmsg(buf, XML_ErrorString (XML_GetErrorCode(state.parser))); result = -1; break; /* Out of loop. */ } if (state.abandoned) { writeMemo("[?] Abandoning MIB load."); result = -1; break; /* Out of loop. */ } } XML_ParserFree(state.parser); close(sourceFile); return result; }
nsExpatDriver::~nsExpatDriver() { if (mExpatParser) { XML_ParserFree(mExpatParser); } }
void * threadWorker(void *pData) { CLogWrkThreadObj *pObj = (CLogWrkThreadObj *)pData; if (NULL == pObj) { syslog(LOG_CRIT, "No thread object supplied to worker thread. Aborting!"); return NULL; } // Check pointers if (NULL == pObj->m_pLog) { syslog(LOG_CRIT, "No valid logger object suppied to worker thread. Aborting!"); return NULL; } // First log on to the host and get configuration // variables if (VSCP_ERROR_SUCCESS == pObj->m_srv.doCmdOpen(pObj->m_pLog->m_host, pObj->m_pLog->m_username, pObj->m_pLog->m_password) <= 0) { return NULL; } // Find the channel id uint32_t ChannelID; pObj->m_srv.doCmdGetChannelID(&ChannelID); // It is possible that there is configuration data the server holds // that we need to read in. // We look for // prefix_filter to find a filter. A string is expected. // prefix_mask to find a mask. A string is expected. // prefix_path to overide the file path for the log file. A string is // expected. prefix_rewrite to override the overwrite flag. A bool is // expected. // Get filter data std::string varFilter; std::string varMask; std::string strFilter = pObj->m_pLog->m_prefix + std::string("_filter"); std::string strMask = pObj->m_pLog->m_prefix + std::string("_mask"); if ((VSCP_ERROR_SUCCESS == pObj->m_srv.getRemoteVariableValue(strFilter, varFilter)) && (VSCP_ERROR_SUCCESS == pObj->m_srv.getRemoteVariableValue(strMask, varMask))) { pObj->m_srv.doCmdFilter(varFilter, varMask); } // get overriden file path std::string strPath = pObj->m_pLog->m_prefix + std::string("_path"); std::string varPath; if (VSCP_ERROR_SUCCESS == pObj->m_srv.getRemoteVariableValue(strPath, varPath)) { pObj->m_pLog->m_path = varPath; } std::string strRewrite = pObj->m_pLog->m_prefix + std::string("_rewrite"); bool bOverwrite; if (VSCP_ERROR_SUCCESS == pObj->m_srv.getRemoteVariableBool(strRewrite, &bOverwrite)) { if (bOverwrite) { pObj->m_pLog->m_flags |= LOG_FILE_OVERWRITE; } else { pObj->m_pLog->m_flags &= ~LOG_FILE_OVERWRITE; } } bool bVSCPWorksFormat; std::string strVscpWorkdFmt = pObj->m_pLog->m_prefix + std::string("_vscpworksfmt"); if (VSCP_ERROR_SUCCESS == pObj->m_srv.getRemoteVariableBool(strVscpWorkdFmt, &bVSCPWorksFormat)) { if (bVSCPWorksFormat) { pObj->m_pLog->m_flags |= LOG_FILE_VSCP_WORKS; } else { pObj->m_pLog->m_flags &= ~LOG_FILE_VSCP_WORKS; } } // XML setup std::string str; std::string strSetupXML; std::string strName = pObj->m_pLog->m_prefix + std::string("_setup"); if (VSCP_ERROR_SUCCESS == pObj->m_srv.getRemoteVariableValue(strName, strSetupXML, true)) { XML_Parser xmlParser = XML_ParserCreate("UTF-8"); XML_SetUserData(xmlParser, pObj->m_pLog); XML_SetElementHandler(xmlParser, startSetupParser, endSetupParser); int bytes_read; void *buff = XML_GetBuffer(xmlParser, XML_BUFF_SIZE); strncpy((char *)buff, strSetupXML.c_str(), strSetupXML.length()); bytes_read = strSetupXML.length(); if (!XML_ParseBuffer(xmlParser, bytes_read, bytes_read == 0)) { syslog(LOG_ERR, "Failed parse XML setup."); } XML_ParserFree(xmlParser); } // Close server connection pObj->m_srv.doCmdClose(); // Open the file if (!pObj->m_pLog->openFile()) return NULL; while (!pObj->m_pLog->m_bQuit) { // Wait for events if ((-1 == vscp_sem_wait(&pObj->m_pLog->m_semSendQueue, 500)) && errno == ETIMEDOUT) { continue; } if (pObj->m_pLog->m_sendList.size()) { pthread_mutex_lock(&pObj->m_pLog->m_mutexSendQueue); vscpEvent *pEvent = pObj->m_pLog->m_sendList.front(); pObj->m_pLog->m_sendList.pop_front(); pthread_mutex_unlock(&pObj->m_pLog->m_mutexSendQueue); if (NULL == pEvent) continue; pObj->m_pLog->writeEvent(pEvent); vscp_deleteVSCPevent(pEvent); pEvent = NULL; } // Event received } // Receive loop // Close the channel pObj->m_srv.doCmdClose(); return NULL; }
int nsExpatDriver::HandleExternalEntityRef(const char16_t *openEntityNames, const char16_t *base, const char16_t *systemId, const char16_t *publicId) { if (mInInternalSubset && !mInExternalDTD && openEntityNames) { mInternalSubset.Append(char16_t('%')); mInternalSubset.Append(nsDependentString(openEntityNames)); mInternalSubset.Append(char16_t(';')); } // Load the external entity into a buffer. nsCOMPtr<nsIInputStream> in; nsAutoString absURL; nsresult rv = OpenInputStreamFromExternalDTD(publicId, systemId, base, getter_AddRefs(in), absURL); if (NS_FAILED(rv)) { #ifdef DEBUG nsCString message("Failed to open external DTD: publicId \""); AppendUTF16toUTF8(publicId, message); message += "\" systemId \""; AppendUTF16toUTF8(systemId, message); message += "\" base \""; AppendUTF16toUTF8(base, message); message += "\" URL \""; AppendUTF16toUTF8(absURL, message); message += "\""; NS_WARNING(message.get()); #endif return 1; } nsCOMPtr<nsIUnicharInputStream> uniIn; rv = nsSimpleUnicharStreamFactory::GetInstance()-> CreateInstanceFromUTF8Stream(in, getter_AddRefs(uniIn)); NS_ENSURE_SUCCESS(rv, 1); int result = 1; if (uniIn) { XML_Parser entParser = XML_ExternalEntityParserCreate(mExpatParser, 0, kUTF16); if (entParser) { XML_SetBase(entParser, absURL.get()); mInExternalDTD = true; uint32_t totalRead; do { rv = uniIn->ReadSegments(ExternalDTDStreamReaderFunc, entParser, uint32_t(-1), &totalRead); } while (NS_SUCCEEDED(rv) && totalRead > 0); result = XML_Parse(entParser, nullptr, 0, 1); mInExternalDTD = false; XML_ParserFree(entParser); } } return result; }
int OGRSVGDataSource::Open( const char * pszFilename ) { #ifdef HAVE_EXPAT pszName = CPLStrdup( pszFilename ); /* -------------------------------------------------------------------- */ /* Try to open the file. */ /* -------------------------------------------------------------------- */ CPLString osFilename(pszFilename); if (EQUAL(CPLGetExtension(pszFilename), "svgz") && strstr(pszFilename, "/vsigzip/") == NULL) { osFilename = CPLString("/vsigzip/") + pszFilename; pszFilename = osFilename.c_str(); } VSILFILE* fp = VSIFOpenL(pszFilename, "r"); if (fp == NULL) return FALSE; eValidity = SVG_VALIDITY_UNKNOWN; XML_Parser oParser = OGRCreateExpatXMLParser(); oCurrentParser = oParser; XML_SetUserData(oParser, this); XML_SetElementHandler(oParser, ::startElementValidateCbk, NULL); XML_SetCharacterDataHandler(oParser, ::dataHandlerValidateCbk); char aBuf[BUFSIZ]; int nDone; unsigned int nLen; int nCount = 0; /* Begin to parse the file and look for the <svg> element */ /* It *MUST* be the first element of an XML file */ /* So once we have read the first element, we know if we can */ /* handle the file or not with that driver */ do { nDataHandlerCounter = 0; nLen = (unsigned int) VSIFReadL( aBuf, 1, sizeof(aBuf), fp ); nDone = VSIFEofL(fp); if (XML_Parse(oParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { if (nLen <= BUFSIZ-1) aBuf[nLen] = 0; else aBuf[BUFSIZ-1] = 0; if (strstr(aBuf, "<?xml") && strstr(aBuf, "<svg")) { CPLError(CE_Failure, CPLE_AppDefined, "XML parsing of SVG file failed : %s at line %d, column %d", XML_ErrorString(XML_GetErrorCode(oParser)), (int)XML_GetCurrentLineNumber(oParser), (int)XML_GetCurrentColumnNumber(oParser)); } eValidity = SVG_VALIDITY_INVALID; break; } if (eValidity == SVG_VALIDITY_INVALID) { break; } else if (eValidity == SVG_VALIDITY_VALID) { break; } else { /* After reading 50 * BUFSIZE bytes, and not finding whether the file */ /* is SVG or not, we give up and fail silently */ nCount ++; if (nCount == 50) break; } } while (!nDone && nLen > 0 ); XML_ParserFree(oParser); VSIFCloseL(fp); if (eValidity == SVG_VALIDITY_VALID) { if (bIsCloudmade) { nLayers = 3; papoLayers =(OGRSVGLayer **) CPLRealloc(papoLayers, nLayers * sizeof(OGRSVGLayer*)); papoLayers[0] = new OGRSVGLayer( pszFilename, "points", SVG_POINTS, this ); papoLayers[1] = new OGRSVGLayer( pszFilename, "lines", SVG_LINES, this ); papoLayers[2] = new OGRSVGLayer( pszFilename, "polygons", SVG_POLYGONS, this ); } else { CPLDebug("SVG", "%s seems to be a SVG file, but not a Cloudmade vector one.", pszFilename); } } return (nLayers > 0); #else char aBuf[256]; VSILFILE* fp = VSIFOpenL(pszFilename, "r"); if (fp) { unsigned int nLen = (unsigned int)VSIFReadL( aBuf, 1, 255, fp ); aBuf[nLen] = 0; if (strstr(aBuf, "<?xml") && strstr(aBuf, "<svg") && strstr(aBuf, "http://cloudmade.com/")) { CPLError(CE_Failure, CPLE_NotSupported, "OGR/SVG driver has not been built with read support. " "Expat library required"); } VSIFCloseL(fp); } return FALSE; #endif }
/** * @brief noticelist/req/応答メッセージ解析 * @param [IN] xml XMLファイルのフルパス * @param [IN] resp_inf CICレスポンス情報 * @param [OUT] noticeInfo お知らせ情報格納領域 * @param [IN/OUT] noticeInfo お知らせ情報格納領域数/お知らせ情報数 * @return 処理結果(E_SC_RESULT) */ E_SC_RESULT CC_NoticeListReq_XmlParse(const Char* xml, T_CC_CMN_SMS_RESPONSE_INFO* resp_inf, INT32 limit, SMNOTICEINFO* noticeInfo, INT32 *noticeInfoNum, Char *noticeNum, SMCALOPT *opt) { E_SC_RESULT ret = e_SC_RESULT_SUCCESS; NOTICELISTREQ_PARSER noticeListParser = {}; Char buf[CC_CMN_XML_PARSE_DATA_SIZE + 1] = {}; XML_Parser parser = NULL; INT32 done = 0; INT32 len = 0; INT32 parsedLen = 0; FILE *fp = NULL; SCC_LOG_DebugPrint(SC_TAG_CC, SCC_LOG_START); do { // パラメータチェック if ((NULL == opt) || (true != opt->isResOutputFile)) { if (NULL == xml) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"param error[xml], " HERE); CB_Result = e_SC_RESULT_FAIL; ret = CB_Result; break; } } // 初期化 resp_inf->sts = 0; memset(noticeInfo, 0, (sizeof(SMNOTICEINFO) * (limit))); noticeListParser.buf = (Char*)SCC_MALLOC(CC_CMN_XML_LARGE_BUF_SIZE + 1); if (NULL == noticeListParser.buf) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"SCC_MALLOC error, " HERE); CB_Result = e_SC_RESULT_MALLOC_ERR; ret = CB_Result; break; } noticeListParser.noticeListMaxNum = limit; noticeListParser.noticeInfo.noticeListNum = 0; noticeListParser.noticeInfo.noticeList = noticeInfo; noticeListParser.noticeInfo.apiStatus = &resp_inf->apiSts[0]; noticeListParser.noticeInfo.noticeNum = noticeNum; CB_Result = e_SC_RESULT_SUCCESS; // XMLパーサ生成 parser = XML_ParserCreate(NULL); if (NULL == parser) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"XML_ParserCreate error, " HERE); CB_Result = e_SC_RESULT_FAIL; ret = CB_Result; break; } // コールバック関数設定 XML_SetUserData(parser, ¬iceListParser); XML_SetElementHandler(parser, CC_NoticeListReq_StartElement, CC_NoticeListReq_EndElement); XML_SetCharacterDataHandler(parser, CC_NoticeListReq_CharacterData); if ((NULL == opt) || (true != opt->isResOutputFile)) { CB_IsXmlFile = false; } else { CB_IsXmlFile = true; fp = fopen((char*)opt->resFilePath, "r"); if (NULL == fp) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"file open error(%d)[%s], " HERE, errno, opt->resFilePath); CB_Result = e_SC_RESULT_FILE_ACCESSERR; ret = CB_Result; break; } } while (!done) { if (CC_ISCANCEL()) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"cancel, " HERE); CB_Result = e_SC_RESULT_CANCEL; ret = CB_Result; break; } if (!CB_IsXmlFile) { strncpy((char*)buf, &xml[parsedLen], (sizeof(buf) - 1)); len = (INT32)strlen(buf); parsedLen += len; if (strlen(xml) <= parsedLen) { done = 1; } else { done = 0; } } else { len = (INT32)fread(buf, 1, (sizeof(buf) - 1), fp); done = (len < (sizeof(buf) - 1)); } // XML解析 if ((XML_STATUS_ERROR == XML_Parse(parser, (const char*)buf, len, done)) || (e_SC_RESULT_SUCCESS != CB_Result)) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"XML_Parse error(0x%08x), " HERE, CB_Result); CB_Result = e_SC_RESULT_SMS_API_ERR; ret = CB_Result; break; } if (!done) { // バッファクリア memset(buf, 0, (sizeof(buf) - 1)); } } if (e_SC_RESULT_SUCCESS == CB_Result) { *noticeInfoNum = noticeListParser.noticeInfo.noticeListNum; } } while (0); if (NULL != noticeListParser.buf) { SCC_FREE(noticeListParser.buf); } if (NULL != fp) { fclose(fp); } if (NULL != parser) { XML_ParserFree(parser); } SCC_LOG_DebugPrint(SC_TAG_CC, SCC_LOG_END); return (ret); }
int QgsWFSData::getWFSData() { XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR ); XML_SetUserData( p, this ); XML_SetElementHandler( p, QgsWFSData::start, QgsWFSData::end ); XML_SetCharacterDataHandler( p, QgsWFSData::chars ); //start with empty extent if ( mExtent ) { mExtent->set( 0, 0, 0, 0 ); } //QUrl requestUrl( mUri ); QNetworkRequest request( mUri ); QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = 0; QWidget* mainWindow = findMainWindow(); if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading WFS data" ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( readData.size() > 0 ) { XML_Parse( p, readData.constData(), readData.size(), atEnd ); } QCoreApplication::processEvents(); } delete reply; delete progressDialog; if ( mExtent ) { if ( mExtent->isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } XML_ParserFree( p ); return 0; }
/** turn an xml file into a config hash */ int config_load_with_id(config_t c, const char *file, const char *id) { struct build_data bd; FILE *f; XML_Parser p; int done, len, end, i, j, attr; char buf[1024], *next; struct nad_elem_st **path; config_elem_t elem; int rv = 0; /* open the file */ f = fopen(file, "r"); if(f == NULL) { fprintf(stderr, "config_load: couldn't open %s for reading: %s\n", file, strerror(errno)); return 1; } /* new parser */ p = XML_ParserCreate(NULL); if(p == NULL) { fprintf(stderr, "config_load: couldn't allocate XML parser\n"); fclose(f); return 1; } /* nice new nad to parse it into */ bd.nad = nad_new(); bd.depth = 0; /* setup the parser */ XML_SetUserData(p, (void *) &bd); XML_SetElementHandler(p, _config_startElement, _config_endElement); XML_SetCharacterDataHandler(p, _config_charData); for(;;) { /* read that file */ len = fread(buf, 1, 1024, f); if(ferror(f)) { fprintf(stderr, "config_load: read error: %s\n", strerror(errno)); XML_ParserFree(p); fclose(f); nad_free(bd.nad); return 1; } done = feof(f); /* parse it */ if(!XML_Parse(p, buf, len, done)) { fprintf(stderr, "config_load: parse error at line %llu: %s\n", (unsigned long long) XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p))); XML_ParserFree(p); fclose(f); nad_free(bd.nad); return 1; } if(done) break; } /* done reading */ XML_ParserFree(p); fclose(f); // Put id if specified if (id) { elem = (config_elem_t)pmalloco(xhash_pool(c->hash), sizeof(struct config_elem_st)); xhash_put(c->hash, pstrdup(xhash_pool(c->hash), "id"), elem); elem->values = calloc(1, sizeof(char *)); elem->values[0] = pstrdup(xhash_pool(c->hash), id); elem->nvalues = 1; } /* now, turn the nad into a config hash */ path = NULL; len = 0, end = 0; /* start at 1, so we skip the root element */ for(i = 1; i < bd.nad->ecur && rv == 0; i++) { /* make sure we have enough room to add this element to our path */ if(end <= bd.nad->elems[i].depth) { end = bd.nad->elems[i].depth + 1; path = (struct nad_elem_st **) realloc((void *) path, sizeof(struct nad_elem_st *) * end); } /* save this path element */ path[bd.nad->elems[i].depth] = &bd.nad->elems[i]; len = bd.nad->elems[i].depth + 1; /* construct the key from the current path */ next = buf; for(j = 1; j < len; j++) { strncpy(next, bd.nad->cdata + path[j]->iname, path[j]->lname); next = next + path[j]->lname; *next = '.'; next++; } next--; *next = '\0'; /* find the config element for this key */ elem = (config_elem_t)xhash_get(c->hash, buf); if(elem == NULL) { /* haven't seen it before, so create it */ elem = (config_elem_t)pmalloco(xhash_pool(c->hash), sizeof(struct config_elem_st)); xhash_put(c->hash, pstrdup(xhash_pool(c->hash), buf), elem); } /* make room for this value .. can't easily realloc off a pool, so * we do it this way and let _config_reaper clean up */ elem->values = realloc((void *) elem->values, sizeof(char *) * (elem->nvalues + 1)); /* and copy it in */ if(NAD_CDATA_L(bd.nad, i) > 0) { // Expand values const char *val = _config_expandx(c, NAD_CDATA(bd.nad, i), NAD_CDATA_L(bd.nad, i)); if (!val) { rv = 1; break; } // Make a copy elem->values[elem->nvalues] = val; } else { elem->values[elem->nvalues] = "1"; } /* make room for the attribute lists */ elem->attrs = realloc((void *) elem->attrs, sizeof(char **) * (elem->nvalues + 1)); elem->attrs[elem->nvalues] = NULL; /* count the attributes */ for(attr = bd.nad->elems[i].attr, j = 0; attr >= 0; attr = bd.nad->attrs[attr].next, j++); /* make space */ elem->attrs[elem->nvalues] = pmalloc(xhash_pool(c->hash), sizeof(char *) * (j * 2 + 2)); /* if we have some */ if(j > 0) { /* copy them in */ j = 0; attr = bd.nad->elems[i].attr; while(attr >= 0) { elem->attrs[elem->nvalues][j] = pstrdupx(xhash_pool(c->hash), NAD_ANAME(bd.nad, attr), NAD_ANAME_L(bd.nad, attr)); elem->attrs[elem->nvalues][j + 1] = pstrdupx(xhash_pool(c->hash), NAD_AVAL(bd.nad, attr), NAD_AVAL_L(bd.nad, attr)); /* * pstrdupx(blob, 0) returns NULL - which means that later * there's no way of telling whether an attribute is defined * as empty, or just not defined. This fixes that by creating * an empty string for attributes which are defined empty */ if (NAD_AVAL_L(bd.nad, attr)==0) { elem->attrs[elem->nvalues][j + 1] = pstrdup(xhash_pool(c->hash), ""); } else { elem->attrs[elem->nvalues][j + 1] = pstrdupx(xhash_pool(c->hash), NAD_AVAL(bd.nad, attr), NAD_AVAL_L(bd.nad, attr)); } j += 2; attr = bd.nad->attrs[attr].next; } } /* do this and we can use j_attr */ elem->attrs[elem->nvalues][j] = NULL; elem->attrs[elem->nvalues][j + 1] = NULL; elem->nvalues++; } if(path != NULL) free(path); if(c->nad != NULL) nad_free(c->nad); c->nad = bd.nad; return rv; }
/** * @brief Userattr.info応答メッセージ解析 * @param [IN] xml XMLファイルのフルパス * @param [IN] resp_inf CICレスポンス情報 * @param [OUT] userInfo ユーザ属性情報格納領域 * @return 処理結果(E_SC_RESULT) */ E_SC_RESULT CC_UserattrInfo_XmlParse(const Char *xml, T_CC_CMN_SMS_RESPONSE_INFO *resp_inf, SMUSERPROFILE *userInfo, SMCALOPT *opt) { E_SC_RESULT ret = e_SC_RESULT_SUCCESS; USERINFO_PARSER userInfoParser = {}; Char buf[CC_CMN_XML_PARSE_DATA_SIZE + 1] = {}; XML_Parser parser = NULL; INT32 done = 0; INT32 len = 0; INT32 parsedLen = 0; FILE *fp = NULL; SCC_LOG_DebugPrint(SC_TAG_CC, SCC_LOG_START); do { // パラメータチェック if ((NULL == opt) || (true != opt->isResOutputFile)) { if (NULL == xml) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"param error[xml], " HERE); CB_Result = e_SC_RESULT_FAIL; ret = CB_Result; break; } } // 初期化 resp_inf->sts = 0; *(resp_inf->apiSts) = EOS; memset(userInfo, 0, sizeof(SMUSERPROFILE)); userInfoParser.buf = (Char*)SCC_MALLOC(CC_CMN_XML_LARGE_BUF_SIZE + 1); if (NULL == userInfoParser.buf) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"SCC_MALLOC error, " HERE); CB_Result = e_SC_RESULT_MALLOC_ERR; ret = CB_Result; break; } userInfoParser.userInfo.userInfo = userInfo; userInfoParser.userInfo.status = &resp_inf->sts; userInfoParser.userInfo.apiStatus = &resp_inf->apiSts[0]; CB_Result = e_SC_RESULT_SUCCESS; // XMLパーサ生成 parser = XML_ParserCreate(NULL); if (NULL == parser) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"XML_ParserCreate error, " HERE); CB_Result = e_SC_RESULT_FAIL; ret = CB_Result; break; } // コールバック関数設定 XML_SetUserData(parser, &userInfoParser); XML_SetElementHandler(parser, CC_UserattrInfo_StartElement, CC_UserattrInfo_EndElement); XML_SetCharacterDataHandler(parser, CC_UserattrInfo_CharacterData); while (!done) { if (CC_ISCANCEL()) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"cancel, " HERE); CB_Result = e_SC_RESULT_CANCEL; ret = CB_Result; break; } strncpy((char*)buf, &xml[parsedLen], (sizeof(buf) - 1)); len = (INT32)strlen(buf); parsedLen += len; if (strlen(xml) <= parsedLen) { done = 1; } else { done = 0; } // XML解析 if ((XML_STATUS_ERROR == XML_Parse(parser, (const char*)buf, len, done)) || (e_SC_RESULT_SUCCESS != CB_Result)) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"XML_Parse error(0x%08x), " HERE, CB_Result); CB_Result = e_SC_RESULT_SMS_API_ERR; ret = CB_Result; break; } if (!done) { // バッファクリア memset(buf, 0, (sizeof(buf) - 1)); } } } while (0); if (NULL != userInfoParser.buf) { SCC_FREE(userInfoParser.buf); } if (NULL != fp) { fclose(fp); } if (NULL != parser) { XML_ParserFree(parser); } SCC_LOG_DebugPrint(SC_TAG_CC, SCC_LOG_END); return (ret); }
/****f* xml_element/xml_elem_parse_buf * NAME * xml_elem_parse_buf * SYNOPSIS * xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error) * FUNCTION * parse a buffer containing XML into an xml_element in-memory tree * INPUTS * in_buf - buffer containing XML document * len - length of buffer * options - input options. optional * error - error result data. optional. check if result is null. * RESULT * void * NOTES * The returned data must be free'd by caller * SEE ALSO * xml_elem_serialize_to_string () * xml_elem_free () * SOURCE */ xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error) { xml_element* xReturn = NULL; char buf[100] = ""; static STRUCT_XML_ELEM_INPUT_OPTIONS default_opts = {encoding_utf_8}; if(!options) { options = &default_opts; } if(in_buf) { XML_Parser parser; xml_elem_data mydata = {0}; parser = XML_ParserCreate(NULL); mydata.root = xml_elem_new(); mydata.current = mydata.root; mydata.input_options = options; mydata.needs_enc_conversion = options->encoding && strcmp(options->encoding, encoding_utf_8); XML_SetElementHandler(parser, (XML_StartElementHandler)_xmlrpc_startElement, (XML_EndElementHandler)_xmlrpc_endElement); XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_xmlrpc_charHandler); /* pass the xml_elem_data struct along */ XML_SetUserData(parser, (void*)&mydata); if(!len) { len = strlen(in_buf); } /* parse the XML */ if(XML_Parse(parser, in_buf, len, 1) == 0) { enum XML_Error err_code = XML_GetErrorCode(parser); int line_num = XML_GetCurrentLineNumber(parser); int col_num = XML_GetCurrentColumnNumber(parser); long byte_idx = XML_GetCurrentByteIndex(parser); /* int byte_total = XML_GetCurrentByteCount(parser); */ const char * error_str = XML_ErrorString(err_code); if(byte_idx >= 0) { snprintf(buf, sizeof(buf), "\n\tdata beginning %ld before byte index: %s\n", byte_idx > 10 ? 10 : byte_idx, in_buf + (byte_idx > 10 ? byte_idx - 10 : byte_idx)); } /* fprintf(stderr, "expat reports error code %i\n" "\tdescription: %s\n" "\tline: %i\n" "\tcolumn: %i\n" "\tbyte index: %ld\n" "\ttotal bytes: %i\n%s ", err_code, error_str, line_num, col_num, byte_idx, byte_total, buf); */ /* error condition */ if(error) { error->parser_code = (long)err_code; error->line = line_num; error->column = col_num; error->byte_index = byte_idx; error->parser_error = error_str; } } else { xReturn = (xml_element*)Q_Head(&mydata.root->children); xReturn->parent = NULL; } XML_ParserFree(parser); xml_elem_free_non_recurse(mydata.root); } return xReturn; }
bool wxXmlDocument::Load(wxInputStream& stream, const wxString& encoding, int flags) { #if wxUSE_UNICODE (void)encoding; #else m_encoding = encoding; #endif const size_t BUFSIZE = 1024; char buf[BUFSIZE]; wxXmlParsingContext ctx; bool done; XML_Parser parser = XML_ParserCreate(NULL); ctx.root = ctx.node = NULL; ctx.encoding = wxT("UTF-8"); // default in absence of encoding="" ctx.conv = NULL; #if !wxUSE_UNICODE if ( encoding.CmpNoCase(wxT("UTF-8")) != 0 ) ctx.conv = new wxCSConv(encoding); #endif ctx.removeWhiteOnlyNodes = (flags & wxXMLDOC_KEEP_WHITESPACE_NODES) == 0; XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, StartElementHnd, EndElementHnd); XML_SetCharacterDataHandler(parser, TextHnd); XML_SetStartCdataSectionHandler(parser, StartCdataHnd); XML_SetCommentHandler(parser, CommentHnd); XML_SetDefaultHandler(parser, DefaultHnd); XML_SetUnknownEncodingHandler(parser, UnknownEncodingHnd, NULL); bool ok = true; do { size_t len = stream.Read(buf, BUFSIZE).LastRead(); done = (len < BUFSIZE); if (!XML_Parse(parser, buf, len, done)) { wxString error(XML_ErrorString(XML_GetErrorCode(parser)), *wxConvCurrent); wxLogError(_("XML parsing error: '%s' at line %d"), error.c_str(), XML_GetCurrentLineNumber(parser)); ok = false; break; } } while (!done); if (ok) { if (!ctx.version.empty()) SetVersion(ctx.version); if (!ctx.encoding.empty()) SetFileEncoding(ctx.encoding); SetRoot(ctx.root); } else { delete ctx.root; } XML_ParserFree(parser); #if !wxUSE_UNICODE if ( ctx.conv ) delete ctx.conv; #endif return ok; }
void GraphMLParser::ParseGraph(Graph *currentGraph, const char* fileName, NodeComparator nodeComparator, std::string *_errorMsg) { //We have to use expat which makes simple parsing really complicated :) std::FILE *graphFile; XML_Parser parser; int len; /* len is the number of bytes in the current buffer of data */ int done = 0; ParserUserData userData = ParserUserData(); //Create a new graph first userData.currentGraph = currentGraph; //Stores the level of the current xml-element userData.level = 0; userData.currentNode = 0; userData.readStringValue = false; userData.stringValue = 0; userData.readDoubleValue = false; userData.doubleValue = 0; userData.readIntValue = false; userData.intValue = 0; userData.nodeSet = new std::set<Node*, NodeComparator>(nodeComparator); userData.errorMsg = _errorMsg; graphFile = fopen(fileName, "rb"); parser = XML_ParserCreate(NULL); XML_SetUserData(parser, &userData); XML_SetElementHandler(parser, StartElement, EndElement); XML_SetCharacterDataHandler(parser, DataElement); //Get file length fseek(graphFile, 0, SEEK_END); const int bufferSize = ftell(graphFile); char* buffer = (char *) malloc(bufferSize + 1); fseek(graphFile, 0, SEEK_SET); do { //Read the graphml-file piece by piece len = std::fread(buffer, sizeof(char), bufferSize, graphFile); //std::cout << buffer; if (len < bufferSize) done = true; if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) { *(userData.errorMsg) += "Error during xml-parsing\n"; break; } } while (!done); XML_ParserFree(parser); fclose(graphFile); //Add all elements of the node-set to the graph for (std::set<Node*, bool (*)(Node*, Node*)>::iterator iter = userData.nodeSet->begin(); iter != userData.nodeSet->end(); iter++) { Node *node = *iter; userData.currentGraph->AddNode(node); } delete userData.nodeSet; userData.currentNode = 0; }
/** * @brief urlreq.php応答メッセージ解析 * @param [IN] xml XMLファイルのフルパス * @param [IN] resp_inf CICレスポンス情報 * @param [OUT] url OAuth認証用URL * @param [OUT] sessionId PHPセッションID * @param [OUT] opt オプション情報 * @return 処理結果(E_SC_RESULT) */ E_SC_RESULT CC_OAuthUrlReq_XmlParse(const Char *xml, T_CC_CMN_SMS_RESPONSE_INFO *resp_inf, Char *url, Char *sessionId, SMCALOPT *opt) { E_SC_RESULT ret = e_SC_RESULT_SUCCESS; OAUTHURL_PARSER oauthParser = {}; Char buf[CC_CMN_XML_PARSE_DATA_SIZE + 1] = {}; XML_Parser parser = NULL; INT32 done = 0; INT32 len = 0; INT32 parsedLen = 0; Char *ptr = NULL; Char *ptr2 = NULL; SCC_LOG_DebugPrint(SC_TAG_CC, SCC_LOG_START); do { // 初期化 resp_inf->sts = 0; oauthParser.buf = (Char*)SCC_MALLOC(CC_CMN_XML_LARGE_BUF_SIZE + 1); if (NULL == oauthParser.buf) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"SCC_MALLOC error, " HERE); CB_Result = e_SC_RESULT_MALLOC_ERR; ret = CB_Result; break; } oauthParser.urlInfo.status = &resp_inf->sts; oauthParser.urlInfo.apiStatus = &resp_inf->apiSts[0]; oauthParser.urlInfo.url = url; oauthParser.urlInfo.sessionId = sessionId; CB_Result = e_SC_RESULT_SUCCESS; // XMLパーサ生成 parser = XML_ParserCreate(NULL); if (NULL == parser) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"XML_ParserCreate error, " HERE); CB_Result = e_SC_RESULT_FAIL; ret = CB_Result; break; } // コールバック関数設定 XML_SetUserData(parser, &oauthParser); XML_SetElementHandler(parser, CC_OAuthUrlReq_StartElement, CC_OAuthUrlReq_EndElement); XML_SetCharacterDataHandler(parser, CC_OAuthUrlReq_CharacterData); while (!done) { if (CC_ISCANCEL()) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"cancel, " HERE); CB_Result = e_SC_RESULT_CANCEL; ret = CB_Result; break; } strncpy((char*)buf, &xml[parsedLen], (sizeof(buf) - 1)); len = (INT32)strlen(buf); parsedLen += len; if (strlen(xml) <= parsedLen) { done = 1; } else { done = 0; } // XML解析 if ((XML_STATUS_ERROR == XML_Parse(parser, (const char*)buf, len, done)) || (e_SC_RESULT_SUCCESS != CB_Result)) { SCC_LOG_ErrorPrint(SC_TAG_CC, (Char*)"XML_Parse error(0x%08x), " HERE, CB_Result); CB_Result = e_SC_RESULT_SMS_API_ERR; ret = CB_Result; break; } if (!done) { // バッファクリア memset(buf, 0, (sizeof(buf) - 1)); } } if(e_SC_RESULT_SUCCESS != ret) { break; } // URLからPHPセッションIDを抜き出す if (EOS == *sessionId) { ptr = (Char*)strstr((char*)url, (char*)CC_OAUTHURLREQ_PHP_SESSION_ID); if (NULL == ptr) { break; } ptr += strlen((char*)CC_OAUTHURLREQ_PHP_SESSION_ID); ptr2 = (Char*)strchr(ptr, '&'); if (NULL != ptr2) { len = (INT32)(ptr2 - ptr); ptr = ptr2; } else { len = strlen((char*)ptr); } if (CC_OAUTHURLREQ_XML_DATA_SESSION_SIZE > len) { memcpy(sessionId, ptr, len); sessionId[len] = EOS; } } } while (0); if (NULL != oauthParser.buf) { SCC_FREE(oauthParser.buf); } if (NULL != parser) { XML_ParserFree(parser); } SCC_LOG_DebugPrint(SC_TAG_CC, SCC_LOG_END); return (ret); }
int main (int argc, char *argv[]) { /* the MAIN function simply perform arguments checking */ sqlite3 *handle; int i; int next_arg = ARG_NONE; const char *gml_path = NULL; const char *db_path = NULL; const char *table = NULL; int in_memory = 0; int error = 0; char Buff[BUFFSIZE]; int done = 0; int len; XML_Parser parser; FILE *xml_file; struct gml_params params; int ret; char *err_msg = NULL; void *cache; params.db_handle = NULL; params.stmt = NULL; params.geometry_type = GEOM_NONE; params.srid = INT_MIN; params.is_feature = 0; params.is_fid = 0; params.is_point = 0; params.is_linestring = 0; params.is_polygon = 0; params.is_multi_point = 0; params.is_multi_linestring = 0; params.is_multi_polygon = 0; params.first = NULL; params.last = NULL; params.geometry = NULL; params.polygon.exterior = NULL; params.polygon.first = NULL; params.polygon.last = NULL; params.CharDataStep = 65536; params.CharDataMax = params.CharDataStep; params.CharData = malloc (params.CharDataStep); for (i = 1; i < argc; i++) { /* parsing the invocation arguments */ if (next_arg != ARG_NONE) { switch (next_arg) { case ARG_GML_PATH: gml_path = argv[i]; break; case ARG_DB_PATH: db_path = argv[i]; break; case ARG_TABLE: table = argv[i]; break; }; next_arg = ARG_NONE; continue; } if (strcasecmp (argv[i], "--help") == 0 || strcmp (argv[i], "-h") == 0) { do_help (); return -1; } if (strcmp (argv[i], "-g") == 0) { next_arg = ARG_GML_PATH; continue; } if (strcasecmp (argv[i], "--gml-path") == 0) { next_arg = ARG_GML_PATH; continue; } if (strcmp (argv[i], "-d") == 0) { next_arg = ARG_DB_PATH; continue; } if (strcasecmp (argv[i], "--db-path") == 0) { next_arg = ARG_DB_PATH; continue; } if (strcmp (argv[i], "-t") == 0) { next_arg = ARG_TABLE; continue; } if (strcasecmp (argv[i], "--table-name") == 0) { next_arg = ARG_TABLE; continue; } if (strcasecmp (argv[i], "-m") == 0) { in_memory = 1; next_arg = ARG_NONE; continue; } if (strcasecmp (argv[i], "-in-memory") == 0) { in_memory = 1; next_arg = ARG_NONE; continue; } if (strcasecmp (argv[i], "-n") == 0) { next_arg = ARG_NONE; continue; } if (strcasecmp (argv[i], "-no-spatial-index") == 0) { next_arg = ARG_NONE; continue; } fprintf (stderr, "unknown argument: %s\n", argv[i]); error = 1; } if (error) { do_help (); return -1; } /* checking the arguments */ if (!gml_path) { fprintf (stderr, "did you forget setting the --gml-path argument ?\n"); error = 1; } if (!db_path) { fprintf (stderr, "did you forget setting the --db-path argument ?\n"); error = 1; } if (!table) { fprintf (stderr, "did you forget setting the --table-name argument ?\n"); error = 1; } if (error) { do_help (); return -1; } /* opening the DB */ cache = spatialite_alloc_connection (); open_db (db_path, &handle, cache); if (!handle) return -1; params.db_handle = handle; if (in_memory) { /* loading the DB in-memory */ sqlite3 *mem_db_handle; sqlite3_backup *backup; int ret; ret = sqlite3_open_v2 (":memory:", &mem_db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); if (ret != SQLITE_OK) { fprintf (stderr, "cannot open 'MEMORY-DB': %s\n", sqlite3_errmsg (mem_db_handle)); sqlite3_close (mem_db_handle); return -1; } backup = sqlite3_backup_init (mem_db_handle, "main", handle, "main"); if (!backup) { fprintf (stderr, "cannot load 'MEMORY-DB'\n"); sqlite3_close (handle); sqlite3_close (mem_db_handle); return -1; } while (1) { ret = sqlite3_backup_step (backup, 1024); if (ret == SQLITE_DONE) break; } ret = sqlite3_backup_finish (backup); sqlite3_close (handle); handle = mem_db_handle; printf ("\nusing IN-MEMORY database\n"); spatialite_cleanup_ex (cache); cache = spatialite_alloc_connection (); spatialite_init_ex (handle, cache, 0); } /* XML parsing */ xml_file = fopen (gml_path, "rb"); if (!xml_file) { fprintf (stderr, "cannot open %s\n", gml_path); sqlite3_close (handle); return -1; } parser = XML_ParserCreate (NULL); if (!parser) { fprintf (stderr, "Couldn't allocate memory for parser\n"); sqlite3_close (handle); return -1; } XML_SetUserData (parser, ¶ms); /* XML parsing: pass I */ XML_SetElementHandler (parser, start1_tag, end1_tag); XML_SetCharacterDataHandler (parser, gmlCharData); while (!done) { len = fread (Buff, 1, BUFFSIZE, xml_file); if (ferror (xml_file)) { fprintf (stderr, "XML Read error\n"); sqlite3_close (handle); return -1; } done = feof (xml_file); if (!XML_Parse (parser, Buff, len, done)) { fprintf (stderr, "Parse error at line %d:\n%s\n", (int) XML_GetCurrentLineNumber (parser), XML_ErrorString (XML_GetErrorCode (parser))); sqlite3_close (handle); return -1; } } XML_ParserFree (parser); /* creating the DB table */ if (!create_table (¶ms, table)) goto no_table; /* XML parsing: pass II */ parser = XML_ParserCreate (NULL); if (!parser) { fprintf (stderr, "Couldn't allocate memory for parser\n"); sqlite3_close (handle); return -1; } XML_SetUserData (parser, ¶ms); XML_SetElementHandler (parser, start2_tag, end2_tag); XML_SetCharacterDataHandler (parser, gmlCharData); rewind (xml_file); params.is_feature = 0; params.is_fid = 0; params.is_point = 0; params.is_linestring = 0; params.is_polygon = 0; params.is_multi_point = 0; params.is_multi_linestring = 0; params.is_multi_polygon = 0; done = 0; while (!done) { len = fread (Buff, 1, BUFFSIZE, xml_file); if (ferror (xml_file)) { fprintf (stderr, "XML Read error\n"); sqlite3_close (handle); return -1; } done = feof (xml_file); if (!XML_Parse (parser, Buff, len, done)) { fprintf (stderr, "Parse error at line %d:\n%s\n", (int) XML_GetCurrentLineNumber (parser), XML_ErrorString (XML_GetErrorCode (parser))); sqlite3_close (handle); return -1; } } XML_ParserFree (parser); if (params.stmt != NULL) sqlite3_finalize (params.stmt); params.stmt = NULL; /* COMMITTing the still pending Transaction */ ret = sqlite3_exec (handle, "COMMIT", NULL, NULL, &err_msg); if (ret != SQLITE_OK) { fprintf (stderr, "COMMIT TRANSACTION error: %s\n", err_msg); sqlite3_free (err_msg); return 0; } no_table: free_columns (¶ms); fclose (xml_file); if (in_memory) { /* exporting the in-memory DB to filesystem */ sqlite3 *disk_db_handle; sqlite3_backup *backup; int ret; printf ("\nexporting IN_MEMORY database ... wait please ...\n"); ret = sqlite3_open_v2 (db_path, &disk_db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); if (ret != SQLITE_OK) { fprintf (stderr, "cannot open '%s': %s\n", db_path, sqlite3_errmsg (disk_db_handle)); sqlite3_close (disk_db_handle); return -1; } backup = sqlite3_backup_init (disk_db_handle, "main", handle, "main"); if (!backup) { fprintf (stderr, "Backup failure: 'MEMORY-DB' wasn't saved\n"); sqlite3_close (handle); sqlite3_close (disk_db_handle); return -1; } while (1) { ret = sqlite3_backup_step (backup, 1024); if (ret == SQLITE_DONE) break; } ret = sqlite3_backup_finish (backup); sqlite3_close (handle); handle = disk_db_handle; printf ("\tIN_MEMORY database succesfully exported\n"); } sqlite3_close (handle); spatialite_cleanup_ex (cache); return 0; }
static void expat_erl_stop(ErlDrvData handle) { XML_ParserFree(((expat_data *)handle)->parser); driver_free((char*)handle); }
BOOLEAN ReadInSectorLoadscreensStats(SECTOR_LOADSCREENS *pSectorLoadscreens, STR fileName) { HWFILE hFile; UINT32 uiBytesRead; UINT32 uiFSize; CHAR8 * lpcBuffer; XML_Parser parser = XML_ParserCreate(NULL); sectorLoadscreensParseData pData; DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading SectorLoadscreens.xml" ); // Open inventory file hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE ); if ( !hFile ) return( FALSE ); uiFSize = FileGetSize(hFile); lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1); //Read in block if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) ) { MemFree(lpcBuffer); return( FALSE ); } lpcBuffer[uiFSize] = 0; //add a null terminator FileClose( hFile ); XML_SetElementHandler(parser, sectorLoadscreensStartElementHandle, sectorLoadscreensEndElementHandle); XML_SetCharacterDataHandler(parser, sectorLoadscreensCharacterDataHandle); memset(&pData,0,sizeof(pData)); pData.curArray = pSectorLoadscreens; pData.maxArraySize = MAX_SECTOR_LOADSCREENS; XML_SetUserData(parser, &pData); if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE)) { CHAR8 errorBuf[511]; sprintf(errorBuf, "XML Parser Error in SectorLoadscreens.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); LiveMessage(errorBuf); MemFree(lpcBuffer); return FALSE; } MemFree(lpcBuffer); XML_ParserFree(parser); return( TRUE ); }
// Scan MAME ROMs folder, cross-reference against XML (if present) for // verbose descriptions, generate ncurses menu. static void find_roms(void) { FILE *fp; struct dirent **dirList; int i, nFiles; Game *g; // For traversing Game linked list WINDOW *scanWin; // Modal 'Scanning...' window if(noRomWin) { // Delete 'No ROMS' window if present delwin(noRomWin); noRomWin = NULL; werase(mainWin); box(mainWin, 0, 0); } if(items) { // Delete old ROM menu and contents, if any if(menu) { unpost_menu(menu); free_menu(menu); menu = NULL; } for(i=0; items[i]; i++) free_item(items[i]); free(items); items = NULL; } const char scanMsg[] = "Scanning ROM folder..."; scanWin = newwin(3, strlen(scanMsg) + 4, (LINES - 4) / 2 - 1, (COLS - strlen(scanMsg)) / 2 - 2); box(scanWin, 0, 0); mvwprintw(scanWin, 1, 2, scanMsg); wnoutrefresh(mainWin); wnoutrefresh(scanWin); doupdate(); delwin(scanWin); werase(mainWin); box(mainWin, 0, 0); while(gameList) { // Delete existing gameList, if any g = gameList->next; if(gameList->name) free(gameList->name); if(gameList->desc) free(gameList->desc); free(gameList); gameList = g; } i = 0; // Count number of games found & successfully alloc'd if((nFiles = scandir(rom, &dirList, sel, alphasort)) > 0) { // Copy dirent array to a Game linked list while(nFiles--) { // List is assembled in reverse if((g = (Game *)malloc(sizeof(Game)))) { g->name = strdup(dirList[nFiles]->d_name); g->desc = NULL; g->next = gameList; gameList = g; i++; // A winner is you } // dirList contents are freed as we go free(dirList[nFiles]); } free(dirList); } // Alloc, load, cross-reference XML file against ROM filenames if((fp = fopen(xml, "r"))) { fseek(fp, 0, SEEK_END); char *buf; int len = ftell(fp); if((buf = (char *)malloc(len))) { int depth = 0; fseek(fp, 0, SEEK_SET); fread(buf, 1, len, fp); XML_Parser parser = XML_ParserCreate(NULL); XML_SetUserData(parser, &depth); XML_SetElementHandler(parser, startElement, endElement); XML_SetCharacterDataHandler(parser, elementData); XML_Parse(parser, buf, len, 1); XML_ParserFree(parser); free(buf); } fclose(fp); } if((items = (ITEM**)malloc((i + 1) * sizeof(ITEM *)))) { for(i=0, g=gameList; g; g=g->next, i++) { items[i] = new_item(g->name, g->desc); set_item_userptr(items[i], g); } items[i] = NULL; menu = new_menu(items); set_menu_win(menu, mainWin); set_menu_sub(menu, derwin(mainWin, LINES-6, COLS-2, 1, 1)); set_menu_format(menu, LINES-6, 1); set_menu_mark(menu, " "); post_menu(menu); } wrefresh(mainWin); if(!menu) { // If no ROMs, throw up a message to that effect const char noRomMsg[] = "No ROMs found"; noRomWin = newwin(3, strlen(noRomMsg) + 4, (LINES - 4) / 2 - 1, (COLS - strlen(noRomMsg)) / 2 - 2); box(noRomWin, 0, 0); mvwprintw(noRomWin, 1, 2, noRomMsg); wrefresh(noRomWin); } }
int pubsub_handler(sox_conn_t *conn, sox_stanza_t *stanza, sox_userdata_t *userdata) { XML_Parser p; char *buf; size_t buflen; int set_state = 0; sox_stanza_t *actuate_stanza; char time_str[30]; char *value_on = "1"; char *value_off = "0"; static int last_state=5; static int last_state_cnt=0; if (stanza == NULL ) return -1; xmpp_stanza_to_text(stanza->xmpp_stanza, &buf, &buflen); //Creates an instance of the XML Parser to parse the event packet p = XML_ParserCreate(NULL ); if (!p) { fprintf(stderr, "Couldn't allocate memory for XML Parser\n"); return -1; } //Sets the handlers to call when parsing the start and end of an XML element XML_SetElementHandler(p, startElement, endElement); XML_SetUserData(p, &set_state); if (XML_Parse(p, buf, strlen(buf), 1) == XML_STATUS_ERROR) { fprintf(stderr, "Parse Error at line %u:\n%s\n", (unsigned int) XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p))); return -1; } XML_ParserFree(p); if(last_state_cnt>0) last_state_cnt--; if( last_state==set_state && last_state_cnt<=0) return 1; if(set_state==0 && last_state_cnt>0 ) set_state=last_state; // Check return value from XMPP parser and actuate if (set_state == 2) { sox_timestamp_create(time_str); actuate_stanza = sox_pubsub_item_data_new(conn); sox_item_transducer_value_actuate_add(actuate_stanza, NULL, "socket_state", a_id, value_on, value_on, time_str); if ((userdata->return_value = sox_item_publish_data(conn, actuate_stanza, actuate_event, userdata)) < 0) fprintf(stderr, "ERROR: Could not publish item, error code: %i\n", userdata->return_value); if(last_state!=set_state) last_state_cnt=3; last_state=set_state; set_state = 0; printf( "publishing actuate on\n"); } else if (set_state == 1) { sox_timestamp_create(time_str); actuate_stanza = sox_pubsub_item_data_new(conn); sox_item_transducer_value_actuate_add(actuate_stanza, NULL, "socket_state", a_id, value_off, value_off, time_str); if ((userdata->return_value = sox_item_publish_data(conn, actuate_stanza, actuate_event, userdata)) < 0) fprintf(stderr, "ERROR: Could not publish item, error code: %i\n", userdata->return_value); if(last_state!=set_state) last_state_cnt=3; last_state=set_state; set_state = 0; printf( "publishing actuate off\n"); } return 1; }
void rsp_ParserFree(rspParser *p) { XML_Parse(p->m_parser,&p->dummy,0,1); XML_ParserFree(p->m_parser); p->m_parser=NULL; }
static void basic_teardown(void) { if (parser != NULL) XML_ParserFree(parser); }
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent ) { mUri = uri; mWkbType = wkbType; XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR ); XML_SetUserData( p, this ); XML_SetElementHandler( p, QgsGml::start, QgsGml::end ); XML_SetCharacterDataHandler( p, QgsGml::chars ); //start with empty extent mExtent.setMinimal(); QNetworkRequest request( mUri ); QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = 0; QWidget* mainWindow = 0; QWidgetList topLevelWidgets = qApp->topLevelWidgets(); for ( QWidgetList::iterator it = topLevelWidgets.begin(); it != topLevelWidgets.end(); ++it ) { if (( *it )->objectName() == "QgisApp" ) { mainWindow = *it; break; } } if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( readData.size() > 0 ) { if ( XML_Parse( p, readData.constData(), readData.size(), atEnd ) == 0 ) { XML_Error errorCode = XML_GetErrorCode( p ); QString errorString = tr( "Error: %1 on line %2, column %3" ) .arg( XML_ErrorString( errorCode ) ) .arg( XML_GetCurrentLineNumber( p ) ) .arg( XML_GetCurrentColumnNumber( p ) ); QgsMessageLog::logMessage( errorString, tr( "WFS" ) ); } } QCoreApplication::processEvents(); } QNetworkReply::NetworkError replyError = reply->error(); QString replyErrorString = reply->errorString(); delete reply; delete progressDialog; if ( replyError ) { QgsMessageLog::logMessage( tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ), tr( "Network" ), QgsMessageLog::CRITICAL ); return 1; } if ( *mWkbType != QGis::WKBNoGeometry ) { if ( mExtent.isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } XML_ParserFree( p ); if ( extent ) *extent = mExtent; return 0; }
~ExpatPP() { if(exp_parser) XML_ParserFree(exp_parser); }
/** * Parses the given input stream and returns a DOM Document. * A NULL pointer will be returned if errors occurred */ nsresult txXMLParser::parse(istream& aInputStream, const nsAString& aUri, txXPathNode** aResultDoc) { mErrorString.Truncate(); *aResultDoc = nsnull; if (!aInputStream) { mErrorString.AppendLiteral("unable to parse xml: invalid or unopen stream encountered."); return NS_ERROR_FAILURE; } static const XML_Memory_Handling_Suite memsuite = { (void *(*)(size_t))PR_Malloc, (void *(*)(void *, size_t))PR_Realloc, PR_Free }; static const PRUnichar expatSeparator = kExpatSeparatorChar; mExpatParser = XML_ParserCreate_MM(nsnull, &memsuite, &expatSeparator); if (!mExpatParser) { return NS_ERROR_OUT_OF_MEMORY; } mDocument = new Document(); if (!mDocument) { XML_ParserFree(mExpatParser); return NS_ERROR_OUT_OF_MEMORY; } mDocument->documentBaseURI = aUri; mCurrentNode = mDocument; XML_SetReturnNSTriplet(mExpatParser, XML_TRUE); XML_SetUserData(mExpatParser, this); XML_SetElementHandler(mExpatParser, startElement, endElement); XML_SetCharacterDataHandler(mExpatParser, charData); XML_SetProcessingInstructionHandler(mExpatParser, piHandler); XML_SetCommentHandler(mExpatParser, commentHandler); #ifdef XML_DTD XML_SetParamEntityParsing(mExpatParser, XML_PARAM_ENTITY_PARSING_ALWAYS); #endif XML_SetExternalEntityRefHandler(mExpatParser, externalEntityRefHandler); XML_SetExternalEntityRefHandlerArg(mExpatParser, this); XML_SetBase(mExpatParser, (const XML_Char*)(PromiseFlatString(aUri).get())); const int bufferSize = 1024; char buf[bufferSize]; PRBool done; do { aInputStream.read(buf, bufferSize); done = aInputStream.eof(); if (!XML_Parse(mExpatParser, buf, aInputStream.gcount(), done)) { createErrorString(); done = MB_TRUE; delete mDocument; mDocument = nsnull; } } while (!done); aInputStream.clear(); // clean up XML_ParserFree(mExpatParser); // ownership to the caller *aResultDoc = txXPathNativeNode::createXPathNode(mDocument); mDocument = nsnull; return *aResultDoc ? NS_OK : NS_ERROR_OUT_OF_MEMORY; }
static int skin_load_file(SkinScreen* skin, const char *file) { FILE* skin_xml; char buffer[BUFFER_SIZE]; int done; XML_Parser parser = XML_ParserCreate(NULL); if (parser) { SkinParser parserconfig; parserconfig.skin = skin; parserconfig.layout = NULL; XML_SetUserData( parser, (void*)&parserconfig ); XML_SetElementHandler(parser, parser_start_hndl, parser_end_hndl); skin_xml = fopen(file, "r"); //printf("skin_config_c: skin_load_file = '%s'\n", file); if (!skin_xml) { fprintf(stderr, "Error opening skin file '%s'\n", file); XML_ParserFree(parser); return -1; } // Extract the path of the given XML file to be used as a default path char *p = strrchr(file, '/'); if (p) { int index = p - file + 1; p = qemu_mallocz(index + 1); strncpy(p, file, index); // last character already zeroed at malloc } else { p = qemu_mallocz(3); p[0] = '.'; p[1] = '/'; // last character already zeroed at malloc } parserconfig.filepath = p; XML_SetUserData(parser, (void*)&parserconfig); XML_SetElementHandler(parser, parser_start_hndl, parser_end_hndl); do { if (fgets(buffer, sizeof(buffer), skin_xml) == NULL) done = 1; else { done = feof(skin_xml); if (!XML_Parse(parser, buffer, strlen(buffer), done)) { fprintf(stderr, "Parse error at line %ld: %s\n", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); // Continue anyway } } } while (!done); if (done && !feof(skin_xml)) { fprintf(stderr, "Parse error, unexpected EOF\n"); // Continue anyway } XML_ParserFree(parser); qemu_free(parserconfig.filepath); // Create a buffer to store the information fclose(skin_xml); return skin_activate_layout(skin, skin->rotate); } return -1; }
int OGRGeoRSSDataSource::Open( const char * pszFilename, int bUpdateIn) { if (bUpdateIn) { CPLError(CE_Failure, CPLE_NotSupported, "OGR/GeoRSS driver does not support opening a file in update mode"); return FALSE; } #ifdef HAVE_EXPAT pszName = CPLStrdup( pszFilename ); /* -------------------------------------------------------------------- */ /* Try to open the file. */ /* -------------------------------------------------------------------- */ VSILFILE* fp = VSIFOpenL(pszFilename, "r"); if (fp == NULL) return FALSE; validity = GEORSS_VALIDITY_UNKNOWN; XML_Parser oParser = OGRCreateExpatXMLParser(); XML_SetUserData(oParser, this); XML_SetElementHandler(oParser, ::startElementValidateCbk, NULL); XML_SetCharacterDataHandler(oParser, ::dataHandlerValidateCbk); oCurrentParser = oParser; char aBuf[BUFSIZ]; int nDone; unsigned int nLen; int nCount = 0; /* Begin to parse the file and look for the <rss> or <feed> element */ /* It *MUST* be the first element of an XML file */ /* So once we have read the first element, we know if we can */ /* handle the file or not with that driver */ do { nDataHandlerCounter = 0; nLen = (unsigned int) VSIFReadL( aBuf, 1, sizeof(aBuf), fp ); nDone = VSIFEofL(fp); if (XML_Parse(oParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { if (nLen <= BUFSIZ-1) aBuf[nLen] = 0; else aBuf[BUFSIZ-1] = 0; if (strstr(aBuf, "<?xml") && (strstr(aBuf, "<rss") || strstr(aBuf, "<feed"))) { CPLError(CE_Failure, CPLE_AppDefined, "XML parsing of GeoRSS file failed : %s at line %d, column %d", XML_ErrorString(XML_GetErrorCode(oParser)), (int)XML_GetCurrentLineNumber(oParser), (int)XML_GetCurrentColumnNumber(oParser)); } validity = GEORSS_VALIDITY_INVALID; break; } if (validity == GEORSS_VALIDITY_INVALID) { break; } else if (validity == GEORSS_VALIDITY_VALID) { break; } else { /* After reading 50 * BUFSIZ bytes, and not finding whether the file */ /* is GeoRSS or not, we give up and fail silently */ nCount ++; if (nCount == 50) break; } } while (!nDone && nLen > 0 ); XML_ParserFree(oParser); VSIFCloseL(fp); if (validity == GEORSS_VALIDITY_VALID) { CPLDebug("GeoRSS", "%s seems to be a GeoRSS file.", pszFilename); nLayers = 1; papoLayers = (OGRGeoRSSLayer **) CPLRealloc(papoLayers, nLayers * sizeof(OGRGeoRSSLayer*)); papoLayers[0] = new OGRGeoRSSLayer( pszName, "georss", this, NULL, FALSE ); } return (validity == GEORSS_VALIDITY_VALID); #else char aBuf[256]; VSILFILE* fp = VSIFOpenL(pszFilename, "r"); if (fp) { unsigned int nLen = (unsigned int)VSIFReadL( aBuf, 1, 255, fp ); aBuf[nLen] = 0; if (strstr(aBuf, "<?xml") && (strstr(aBuf, "<rss") || strstr(aBuf, "<feed"))) { CPLError(CE_Failure, CPLE_NotSupported, "OGR/GeoRSS driver has not been built with read support. Expat library required"); } VSIFCloseL(fp); } return FALSE; #endif }
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent ) { mUri = uri; mWkbType = wkbType; XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR ); XML_SetUserData( p, this ); XML_SetElementHandler( p, QgsGml::start, QgsGml::end ); XML_SetCharacterDataHandler( p, QgsGml::chars ); //start with empty extent mExtent.setMinimal(); QNetworkRequest request( mUri ); QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); //find out if there is a QGIS main window. If yes, display a progress dialog QProgressDialog* progressDialog = 0; QWidget* mainWindow = qApp->activeWindow(); if ( mainWindow ) { progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow ); progressDialog->setWindowModality( Qt::ApplicationModal ); connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) ); connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) ); connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) ); progressDialog->show(); } int atEnd = 0; while ( !atEnd ) { if ( mFinished ) { atEnd = 1; } QByteArray readData = reply->readAll(); if ( readData.size() > 0 ) { XML_Parse( p, readData.constData(), readData.size(), atEnd ); } QCoreApplication::processEvents(); } delete reply; delete progressDialog; if ( *mWkbType != QGis::WKBNoGeometry ) { if ( mExtent.isEmpty() ) { //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features calculateExtentFromFeatures(); } } XML_ParserFree( p ); if ( extent ) *extent = mExtent; return 0; }
WBXML_DECLARE(WBXMLError) wbxml_tree_from_xml(WB_UTINY *xml, WB_ULONG xml_len, WBXMLTree **tree) { #if defined( HAVE_EXPAT ) const XML_Feature *feature_list = NULL; XML_Parser xml_parser = NULL; WBXMLError ret = WBXML_OK; WB_BOOL expat_utf16 = FALSE; WBXMLTreeClbCtx wbxml_tree_clb_ctx; /* First Check if Expat is outputing UTF-16 strings */ feature_list = (const XML_Feature *)XML_GetFeatureList(); if ((feature_list != NULL) && (feature_list[0].value != sizeof(WB_TINY))) { #if !defined( HAVE_ICONV ) /* Ouch, can't convert from UTF-16 to UTF-8 */ return WBXML_ERROR_XMLPARSER_OUTPUT_UTF16; #else /* Expat returns UTF-16 encoded strings in its callbacks */ expat_utf16 = TRUE; #endif /* !HAVE_ICONV */ } if (tree != NULL) *tree = NULL; /* Create Expat XML Parser */ if ((xml_parser = XML_ParserCreateNS(NULL, WBXML_NAMESPACE_SEPARATOR)) == NULL) return WBXML_ERROR_NOT_ENOUGH_MEMORY; /* Init context */ wbxml_tree_clb_ctx.current = NULL; wbxml_tree_clb_ctx.error = WBXML_OK; wbxml_tree_clb_ctx.skip_lvl = 0; wbxml_tree_clb_ctx.skip_start = 0; wbxml_tree_clb_ctx.xml_parser = xml_parser; wbxml_tree_clb_ctx.input_buff = xml; wbxml_tree_clb_ctx.expat_utf16 = expat_utf16; /* Create WBXML Tree */ //modified by [email protected] 2012-10-19 //if ((wbxml_tree_clb_ctx.tree = wbxml_tree_create(WBXML_LANG_UNKNOWN, WBXML_CHARSET_UNKNOWN)) == NULL) { if ((wbxml_tree_clb_ctx.tree = wbxml_tree_create(WBXML_LANG_ACTIVESYNC, WBXML_CHARSET_UTF_8)) == NULL) { XML_ParserFree(xml_parser); WBXML_ERROR((WBXML_PARSER, "Can't create WBXML Tree")); return WBXML_ERROR_NOT_ENOUGH_MEMORY; } /* Set Handlers Callbacks */ XML_SetXmlDeclHandler(xml_parser, wbxml_tree_clb_xml_decl); XML_SetStartDoctypeDeclHandler(xml_parser, wbxml_tree_clb_xml_doctype_decl); XML_SetElementHandler(xml_parser, wbxml_tree_clb_xml_start_element, wbxml_tree_clb_xml_end_element); XML_SetCdataSectionHandler(xml_parser, wbxml_tree_clb_xml_start_cdata, wbxml_tree_clb_xml_end_cdata); XML_SetProcessingInstructionHandler(xml_parser , wbxml_tree_clb_xml_pi); XML_SetCharacterDataHandler(xml_parser, wbxml_tree_clb_xml_characters); XML_SetUserData(xml_parser, (void*)&wbxml_tree_clb_ctx); /* Parse the XML Document to WBXML Tree */ if (XML_Parse(xml_parser, (WB_TINY*) xml, xml_len, TRUE) == 0) { WBXML_ERROR((WBXML_CONV, "xml2wbxml conversion failed - expat error %i\n" "\tdescription: %s\n" "\tline: %i\n" "\tcolumn: %i\n" "\tbyte index: %i\n" "\ttotal bytes: %i\n%s", XML_GetErrorCode(xml_parser), XML_ErrorString(XML_GetErrorCode(xml_parser)), XML_GetCurrentLineNumber(xml_parser), XML_GetCurrentColumnNumber(xml_parser), XML_GetCurrentByteIndex(xml_parser), XML_GetCurrentByteCount(xml_parser), xml)); wbxml_tree_destroy(wbxml_tree_clb_ctx.tree); ret = WBXML_ERROR_XML_PARSING_FAILED; } else { if ((ret = wbxml_tree_clb_ctx.error) != WBXML_OK) { WBXML_ERROR((WBXML_CONV, "xml2wbxml conversion failed - context error %i", ret)); wbxml_tree_destroy(wbxml_tree_clb_ctx.tree); } else *tree = wbxml_tree_clb_ctx.tree; } /* Clean-up */ XML_ParserFree(xml_parser); return ret; #else /* HAVE_EXPAT */ #if defined( HAVE_LIBXML ) /** @todo Use LibXML2 SAX interface ! */ return WBXML_ERROR_NO_XMLPARSER; #else /* HAVE_LIBXML */ /** @note You can add here another XML Parser support */ return WBXML_ERROR_NO_XMLPARSER; #endif /* HAVE_LIBXML */ #endif /* HAVE_EXPAT */ }
void KML::checkValidity() { std::size_t nDone = 0; std::size_t nLen = 0; char aBuf[BUFSIZ] = { 0 }; if(poTrunk_ != NULL) { delete poTrunk_; poTrunk_ = NULL; } if(poCurrent_ != NULL) { delete poCurrent_; poCurrent_ = NULL; } if(pKMLFile_ == NULL) { this->sError_ = "No file given"; return; } XML_Parser oParser = OGRCreateExpatXMLParser(); XML_SetUserData(oParser, this); XML_SetElementHandler(oParser, startElementValidate, NULL); XML_SetCharacterDataHandler(oParser, dataHandlerValidate); int nCount = 0; oCurrentParser = oParser; /* Parses the file until we find the first element */ do { nDataHandlerCounter = 0; nLen = (int)VSIFReadL( aBuf, 1, sizeof(aBuf), pKMLFile_ ); nDone = VSIFEofL(pKMLFile_); if (XML_Parse(oParser, aBuf, nLen, nDone) == XML_STATUS_ERROR) { if (nLen <= BUFSIZ-1) aBuf[nLen] = 0; else aBuf[BUFSIZ-1] = 0; if (strstr(aBuf, "<?xml") && strstr(aBuf, "<kml")) { CPLError(CE_Failure, CPLE_AppDefined, "XML parsing of KML file failed : %s at line %d, column %d", XML_ErrorString(XML_GetErrorCode(oParser)), (int)XML_GetCurrentLineNumber(oParser), (int)XML_GetCurrentColumnNumber(oParser)); } validity = KML_VALIDITY_INVALID; XML_ParserFree(oParser); VSIRewindL(pKMLFile_); return; } nCount ++; /* After reading 50 * BUFSIZE bytes, and not finding whether the file */ /* is KML or not, we give up and fail silently */ } while (!nDone && nLen > 0 && validity == KML_VALIDITY_UNKNOWN && nCount < 50); XML_ParserFree(oParser); VSIRewindL(pKMLFile_); poCurrent_ = NULL; }
static int static_service_group_load(StaticServiceGroup *g) { XML_Parser parser = NULL; int fd = -1; struct xml_userdata u; int r = -1; struct stat st; ssize_t n; assert(g); u.buf = NULL; u.group = g; u.service = NULL; u.current_tag = XML_TAG_INVALID; u.failed = 0; /* Cleanup old data in this service group, if available */ remove_static_service_group_from_server(g); while (g->services) static_service_free(g->services); avahi_free(g->name); avahi_free(g->chosen_name); g->name = g->chosen_name = NULL; g->replace_wildcards = 0; if (!(parser = XML_ParserCreate(NULL))) { avahi_log_error("XML_ParserCreate() failed."); goto finish; } if ((fd = open(g->filename, O_RDONLY)) < 0) { avahi_log_error("open(\"%s\", O_RDONLY): %s", g->filename, strerror(errno)); goto finish; } if (fstat(fd, &st) < 0) { avahi_log_error("fstat(): %s", strerror(errno)); goto finish; } g->mtime = st.st_mtime; XML_SetUserData(parser, &u); XML_SetElementHandler(parser, xml_start, xml_end); XML_SetCharacterDataHandler(parser, xml_cdata); do { void *buffer; #define BUFSIZE (10*1024) if (!(buffer = XML_GetBuffer(parser, BUFSIZE))) { avahi_log_error("XML_GetBuffer() failed."); goto finish; } if ((n = read(fd, buffer, BUFSIZE)) < 0) { avahi_log_error("read(): %s\n", strerror(errno)); goto finish; } if (!XML_ParseBuffer(parser, n, n == 0)) { avahi_log_error("XML_ParseBuffer() failed at line %d: %s.\n", (int) XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); goto finish; } } while (n != 0); if (!u.failed) r = 0; finish: if (fd >= 0) close(fd); if (parser) XML_ParserFree(parser); avahi_free(u.buf); return r; }
WrapExpat::~WrapExpat() { if ( p ) XML_ParserFree ( p ); }