bool JustRenderIt::ResourceManager::GetResourcePath(STRING& filename, STRING folderName) { Trim(filename); Trim(folderName); if(folderName[folderName.length()-1] == '/' || folderName[folderName.length()-1] == '\\' ) folderName = folderName.substr(0, folderName.length()-1); if(folderName[0] == '/') folderName = folderName.substr(1, folderName.length()-1); if(!FileExists(filename)) { STRING newfilename = "../resources/"; newfilename += folderName + "/" + filename; if(!FileExists(newfilename)) { char str[256]; sprintf(str, "Couldn't open \"%s\"", filename.c_str()); LOG_ERROR1(str); return false; } filename = newfilename; } return true; }
// Immediate concatenation ( += ) operator{} // This operator will be overloaded to // work with a right hand value of either type STRING, type char* or type char. STRING STRING::operator += (const STRING &right_argument) { unsigned newLength = this->len + right_argument.length(); int new_length = this->len; char* temp = new char[new_length]; // Copy the left hand argument into a temporary char array // so we can delete its contents and reallocate more memory for(unsigned i = 0; i < this->len; i++) temp[i] = this->contents[i]; delete[] this->contents; this->contents = new char[newLength]; unsigned i = 0; // Copy the first string's contents back in. // Must be a while loop for proper scoping of i. while (i < this->len) { this->contents[i] = temp[i]; i++; } // Copy the second string's contents in. for (unsigned j = 0; j < right_argument.length(); j++) this->contents[i + j] = right_argument.contents[j]; this->len = newLength; return *this; }
// Break up a string composed of multiple sections in parentheses into a collection // of sub-strings. Sample input string: (Hello)(World1,World2) MgStringCollection* WfsGetFeatureParams::GetParenthesisedList(CREFSTRING sourceString) { MgStringCollection* stringList = new MgStringCollection(); if(sourceString.length() > 0) { // Create a collection of strings STRING remaining = MgUtil::Trim(sourceString); while(remaining.length() > 0) { STRING::size_type openParenthesis = remaining.find_first_of(L"("); if(openParenthesis != string::npos) { STRING::size_type closeParenthesis = remaining.find_first_of(L")"); if(closeParenthesis != string::npos) { STRING thisString = remaining.substr(openParenthesis + 1, closeParenthesis - openParenthesis - 1); stringList->Add(thisString); remaining = remaining.substr(closeParenthesis + 1); } } else { stringList->Add(remaining); break; } } } return stringList; }
CKT::CVersion::CVersion(STRING version) { int iPoint = version.find('.'); STRING sTemp = version.substr(0, iPoint); m_byMajor = (BYTE)toInt(sTemp.c_str()); sTemp = version.substr(iPoint + 1, version.length() - iPoint); m_byMinor = (BYTE)toInt(sTemp.c_str()); }
///////////////////////////////////////// // Write feature information as XML document. // MgByteReader* MgFeatureInformation::ToXml() { STRING xml; STRING xmlSelection = m_selection? m_selection->ToXml(false): L""; // TODO: define a schema for this XML xml.append(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<FeatureInformation>\n"); size_t len = xmlSelection.length(); if(len > 0) { xml.reserve(len + 2048); xml.append(xmlSelection); } else { xml.reserve(2048); xml.append(L"<FeatureSet />\n"); } if(m_tooltip.length() > 0) { xml.append(L"<Tooltip>"); xml.append(MgUtil::ReplaceEscapeCharInXml(m_tooltip)); xml.append(L"</Tooltip>\n"); } else xml.append(L"<Tooltip />\n"); if(m_hyperlink.length() > 0) { xml.append(L"<Hyperlink>"); xml.append(MgUtil::ReplaceEscapeCharInXml(m_hyperlink)); xml.append(L"</Hyperlink>\n"); } else xml.append(L"<Hyperlink />\n"); if(m_properties != NULL) { for(int i = 0; i < m_properties->GetCount(); i++) { Ptr<MgStringProperty> prop = (MgStringProperty*)m_properties->GetItem(i); xml.append(L"<Property name=\""); xml.append(MgUtil::ReplaceEscapeCharInXml(prop->GetName())); xml.append(L"\" value=\""); xml.append(MgUtil::ReplaceEscapeCharInXml(prop->GetValue())); xml.append(L"\" />\n"); } } xml.append(L"</FeatureInformation>\n"); string xmlDoc = MgUtil::WideCharToMultiByte(xml); STRING mimeType = L"text/xml"; return MgUtil::GetByteReader(xmlDoc, &mimeType); }
void testEmptyConst() { char desc[] = "Empty Constructor"; printTestHeader(desc); STRING s; cout << "STRING contains '"; STRdisplay(s); cout << "'.\n" << "STRING length is " << s.length() << ".\n" << "isEmpty returns " << (s.isEmpty() ? "True" : "False") << ".\n"; printTestFooter(desc); }
/* * Remove the path from a file name, perserving folders. * preserveFrom should carry a trailing \. */ STRING removePath(const STRING str, const STRING preserveFrom) { const int pos = str.find(preserveFrom); if (pos != str.npos) { return str.substr(pos + preserveFrom.length()); } // Return the path unaltered, since it didn't contain the // default folder and any other folders should be subfolders // (although a different default folder may be present). return str; }
///////////////////////////////////////// // Deserialize from a stream // void MgFeatureInformation::Deserialize(MgStream* stream) { STRING xml; stream->GetString(xml); if(xml.length() > 0) { m_selection = new MgSelection(); m_selection->FromXml(xml); } stream->GetString(m_tooltip); stream->GetString(m_hyperlink); m_properties = (MgPropertyCollection*)stream->GetObject(); }
void testSingleCharConst() { char desc[] = "Single Character Constructor"; printTestHeader(desc); char c = 'd'; cout << "Assigned char is '" << c << "'. \n"; STRING s (c); cout << "STRING contains '"; STRdisplay(s); cout << "'.\n" << "STRING length is " << s.length() << ".\n"; printTestFooter(desc); }
// Build OGC filter XML stirngs based on the provided input filters. void WfsGetFeatureParams::BuildFilterStrings(CREFSTRING filters, CREFSTRING featureIds, CREFSTRING bbox) { // Create the required feature filters m_filterStrings = GetParenthesisedList(filters); if(m_filterStrings->GetCount() == 0) { // If no FILTER was specified, look for a BBOX if(bbox.length() > 0) { // Build a filter from the bounding box Ptr<MgStringCollection> bboxCoords = MgStringCollection::ParseCollection(bbox, L","); if(bboxCoords->GetCount() >= 4) { // TODO: Look into using StringStream and XmlElementEmitter for simplified generation // of these elements. STRING filterString = L"<ogc:Filter><ogc:BBOX><ogc:PropertyName>%MG_GEOM_PROP%</ogc:PropertyName><gml:Box><gml:coordinates>"; filterString.append(MgUtil::Trim(bboxCoords->GetItem(0))); filterString.append(L","); filterString.append(MgUtil::Trim(bboxCoords->GetItem(1))); filterString.append(L" "); filterString.append(MgUtil::Trim(bboxCoords->GetItem(2))); filterString.append(L","); filterString.append(MgUtil::Trim(bboxCoords->GetItem(3))); filterString.append(L"</gml:coordinates></gml:Box></ogc:BBOX></ogc:Filter>"); m_filterStrings->Add(filterString); } } // If no FILTER or BBOX, look for FEATUREID else if(featureIds.length() > 0) { // Build a filter from the list of feature Ids Ptr<MgStringCollection> featureIdList = MgStringCollection::ParseCollection(featureIds, L","); if(featureIdList->GetCount() > 0) { STRING filterString = L"<ogc:Filter>"; for(int i = 0; i < featureIdList->GetCount(); i++) { STRING thisFeatureId = MgUtil::Trim(featureIdList->GetItem(i)); if(thisFeatureId.length() > 0) { filterString.append(L"<ogc:GmlObjectId gml:id="); filterString.append(thisFeatureId); filterString.append(L"/>"); } } filterString.append(L"</ogc:Filter>"); m_filterStrings->Add(filterString); } } } }
void testNullcstr() { char desc[] = "Null Char* Constructor"; printTestHeader(desc); char* cstr = NULL; if (cstr == NULL) cout << "The contents of the C-String are: \n\t'" << "NULL" << "'.\n"; STRING s (cstr); cout << s.length() << endl; cout << "The contents of STRING are: \n\t'"; STRdisplay(s); cout << "'.\n"; cout << "Success.\n"; printTestFooter(desc); }
// Returns the null terminated UTF-8 encoded text string for the current // object at the given level. Use delete [] to free after use. char* LTRResultIterator::GetUTF8Text(PageIteratorLevel level) const { if (it_->word() == NULL) return NULL; // Already at the end! STRING text; PAGE_RES_IT res_it(*it_); WERD_CHOICE* best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); if (level == RIL_SYMBOL) { text = res_it.word()->BestUTF8(blob_index_, false); } else if (level == RIL_WORD) { text = best_choice->unichar_string(); } else { bool eol = false; // end of line? bool eop = false; // end of paragraph? do { // for each paragraph in a block do { // for each text line in a paragraph do { // for each word in a text line best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); text += best_choice->unichar_string(); text += " "; res_it.forward(); eol = res_it.row() != res_it.prev_row(); } while (!eol); text.truncate_at(text.length() - 1); text += line_separator_; eop = res_it.block() != res_it.prev_block() || res_it.row()->row->para() != res_it.prev_row()->row->para(); } while (level != RIL_TEXTLINE && !eop); if (eop) text += paragraph_separator_; } while (level == RIL_BLOCK && res_it.block() == res_it.prev_block()); } int length = text.length() + 1; char* result = new char[length]; strncpy(result, text.string(), length); return result; }
const std::vector <STRING> OSInterface::ExtractFilesFromDirectory(const STRING& aRootDir,const STRING& aExtension) { STRING pathOfFile; STRING patternOfString; WIN32_FIND_DATA fileInfo; patternOfString = aRootDir + _T("\\*.*") ; HANDLE hToFile = ::FindFirstFile(patternOfString.c_str(), &fileInfo); std::vector<STRING> aDirFiles; if(hToFile != INVALID_HANDLE_VALUE) { do { if(fileInfo.cFileName[0] != '.') { pathOfFile.erase(); pathOfFile = aRootDir + _T("\\")+ fileInfo.cFileName; STRING file = fileInfo.cFileName; STRING extOfString = file.substr(file.rfind(_T(".")) + 1); if(aExtension.length()) { if(extOfString == aExtension) { aDirFiles.push_back(pathOfFile); } } else { bool valid = IsInteger(file); if(valid) { aDirFiles.push_back(pathOfFile); } } } }while(::FindNextFile(hToFile , &fileInfo)); ::FindClose(hToFile); } return aDirFiles; }
/** * Returns the null terminated UTF-8 encoded text string for the current * object at the given level. Use delete [] to free after use. */ char* ResultIterator::GetUTF8Text(PageIteratorLevel level) const { if (it_->word() == NULL) return NULL; // Already at the end! STRING text; switch (level) { case RIL_BLOCK: { ResultIterator pp(*this); do { pp.AppendUTF8ParagraphText(&text); } while (pp.Next(RIL_PARA) && pp.it_->block() == it_->block()); } break; case RIL_PARA: AppendUTF8ParagraphText(&text); break; case RIL_TEXTLINE: { ResultIterator it(*this); it.MoveToLogicalStartOfTextline(); it.IterateAndAppendUTF8TextlineText(&text); } break; case RIL_WORD: AppendUTF8WordText(&text); break; case RIL_SYMBOL: { bool reading_direction_is_ltr = current_paragraph_is_ltr_ ^ in_minor_direction_; if (at_beginning_of_minor_run_) { text += reading_direction_is_ltr ? kLRM : kRLM; } text = it_->word()->BestUTF8(blob_index_, !reading_direction_is_ltr); if (IsAtFinalSymbolOfWord()) AppendSuffixMarks(&text); } break; } int length = text.length() + 1; char* result = new char[length]; strncpy(result, text.string(), length); return result; }
bool ParseAuth(char* auth, MgHttpRequestParam* params) { bool bGotAuth = false; //////////////////////////////////////////////////////////////////////////// //Bypass the standard authentication handling for OGC (WMS and WFS) requests. //For these requests, use predefined credentials // // OGC requests do not use OPERATION= parameter... STRING op = params->GetParameterValue(MgHttpResourceStrings::reqOperation); if(op.length() == 0 && IsOgcRequest(params)) return AuthenticateOgcRequest(params); //////////////////////////////////////////////////////////////////////////// const char* basic = MapAgentStrings::BasicAuth; if (NULL != auth && NULL != strstr(auth, basic)) { char* base64 = strstr(auth, basic) + strlen(basic); unsigned long origLen = (unsigned long) strlen(base64); unsigned long len = Base64::GetDecodedLength(origLen); if (len < 128) { char buf[128]; memset(buf, 0, 128); Base64::Decode((unsigned char*)buf, base64, origLen); char* split = strchr(buf, ':'); // NOXLATE if (NULL != split) { *split++ = '\0'; string username = buf; string password = split; params->AddParameter(MgHttpResourceStrings::reqUsername, MgUtil::MultiByteToWideChar(username)); params->AddParameter(MgHttpResourceStrings::reqPassword, MgUtil::MultiByteToWideChar(password)); bGotAuth = true; } } } return bGotAuth; }
// Parse a Filter element bool WfsGetFeatureParams::ParseFilterElement(MgOgcWfsServer& oServer,MgXmlParser& parser,MgXmlNamespaceManager& oNamespaces) { MgXmlSynchronizeOnNamespaceElement oFilterElement(parser, _("http://www.opengis.net/ogc:Filter"), oNamespaces); MgXmlBeginElement* pBegin; // Not at a Filter element? Unexpected; get out. if(!oFilterElement.AtBegin(&pBegin)) return false; if(!pBegin->IsEmpty()) { STRING filterString = GetElementContents(parser); if(filterString.length() > 0) { m_filterStrings->Add(oServer.ProcessArgumentAs(_("filter"),filterString.c_str())); } } // It's a filter element, and we "processed" it, but // it's possible that it contributed nothing to the filter list. return true; }
/*! // \param char * str : // \param int offset : // \param SDL_Surface* screen : */ void cCredits::draw_textFontM(char* pstrLine, int offset, SDL_Surface* screen) { ASSERT(m_pMainFont); int tx, ty; TTF_SizeText(m_pMainFont,pstrLine, &tx, &ty); int iY = screen->h - (offset * ty); SDL_Rect trect; STRING strLayout = pstrLine; STRING strRes = strLayout; size_t iLen = strRes.length(); if (pstrLine[0] == '-') { // highlight // eat '-' strRes = strLayout.substr(1,iLen - 1); trect.y= iY - 2; //trect.x = (screen->w/2 - ((int)strRes.size()*tx + 3)/2) - 4; trect.x = (screen->w - tx)/ 2; //trect.w = (int)strRes.size()*tx + 8; trect.w = tx; trect.h = ty + 4; SDL_Rect rctBox = trect; rctBox.x -= 4; rctBox.w += 4; Uint32 tcolor = SDL_MapRGBA(screen->format, 128, 0, 0,255); SDL_FillRect(screen,&rctBox,tcolor); } else { trect.y= iY - 2; trect.x = (screen->w - tx)/ 2; } GFX_UTIL::DrawString(screen, strRes.c_str(), trect.x, trect.y, m_colCurrent, m_pMainFont,false); }
// OGC requests come in two flavors: GET method, and POST method. // // GET-method requests follow the SERVICE= and REQUEST= paradigm, // so they're fairly self-announcing. // // POST-method requests don't have parameter values as such, and // their content types vary (often owing to sloppy implementation of the // client), but their actual payload content is always XML. bool IsOgcRequest(MgHttpRequestParam* params) { // Here we do just a crude triage. // // First up, the GET-method check: look for parameters STRING requestValue = params->GetParameterValue(MgHttpResourceStrings::reqWmsRequest); if(requestValue.length() != 0) return true; else { // plan B: the POST method check. // TODO: someday MapGuide other than just OGC may use POST with XML data; // at that time, further disambiguation will be necessary. if(params->GetXmlPostData().length() != 0) return true; } MgConfiguration* cfg = MgConfiguration::GetInstance(); bool bCITEWfsEnabled = false; cfg->GetBoolValue(MgConfigProperties::OgcPropertiesSection, MgConfigProperties::CITEWfsEnabled, bCITEWfsEnabled, MgConfigProperties::DefaultCITEWfsEnabled); bool bCITEWmsEnabled = false; cfg->GetBoolValue(MgConfigProperties::OgcPropertiesSection, MgConfigProperties::CITEWmsEnabled, bCITEWmsEnabled, MgConfigProperties::DefaultCITEWmsEnabled); return (bCITEWfsEnabled || bCITEWmsEnabled); }
/* * Trim whitespace from the sides of a string. * * str (in) - string to trim * return (out) - trimmed string */ STRING parser::trim(const STRING &str) { const int len = str.length(); if (len == 0) return _T(""); int start = -1, end = -1; for (int i = 0; i < len; i++) { if (str[i] != _T(' ') && str[i] != _T('\t')) { start = i; break; } } if (start == -1) return _T(""); for (int j = len - 1; j >= 0; j--) { if (str[j] != _T(' ') && str[j] != _T('\t')) { end = j + 1 - start; break; } } return str.substr(start, end); }
void CgiResponseHandler::SendResponse(MgHttpResponse* response) { MG_TRY() Ptr<MgHttpResult> result = response->GetResult(); STATUS status = result->GetStatusCode(); if (status != 200) { STRING statusMessage = result->GetHttpStatusMessage(); if (statusMessage == MapAgentStrings::FailedAuth1 || statusMessage == MapAgentStrings::FailedAuth2) { RequestAuth(); } else { //TODO: Use a resource for the HTML error message STRING shortError = result->GetErrorMessage(); STRING longError = result->GetDetailedErrorMessage(); printf(MapAgentStrings::StatusHeader, status, MG_WCHAR_TO_CHAR(statusMessage)); printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, ""); printf("\r\n" "<html>\n<head>\n" "<title>%s</title>\n" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" "</head>\n" "<body>\n<h2>%s</h2>\n%s\n</body>\n</html>\n", MG_WCHAR_TO_CHAR(statusMessage), MG_WCHAR_TO_CHAR(shortError), MG_WCHAR_TO_CHAR(longError)); DumpMessage(MG_WCHAR_TO_CHAR(longError)); } } else { DumpMessage(MapAgentStrings::StatusOkHeader); // Status was ok. Send the real result back. STRING contentType = result->GetResultContentType(); STRING stringVal; printf(MapAgentStrings::StatusOkHeader); if (contentType.length() > 0) { // If we are returning text, state that it is utf-8. string charSet = ""; if (contentType.find(L"text") != contentType.npos) //NOXLATE { charSet = MapAgentStrings::Utf8Text; } printf(MapAgentStrings::ContentTypeHeader, MG_WCHAR_TO_CHAR(contentType), charSet.c_str()); } else { printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text); } Ptr<MgByteReader> outputReader; Ptr<MgDisposable> resultObj = result->GetResultObject(); MgDisposable* pResultObj = (MgDisposable*)resultObj; if (NULL != dynamic_cast<MgByteReader*>(pResultObj)) { outputReader = (MgByteReader*) SAFE_ADDREF(pResultObj); } else if (NULL != dynamic_cast<MgStringCollection*>(pResultObj)) { outputReader = ((MgStringCollection*)pResultObj)->ToXml(); } else if (NULL != dynamic_cast<MgSpatialContextReader*>(pResultObj)) { outputReader = ((MgSpatialContextReader*)pResultObj)->ToXml(); } else if (NULL != dynamic_cast<MgLongTransactionReader*>(pResultObj)) { outputReader = ((MgLongTransactionReader*)pResultObj)->ToXml(); } else if (NULL != dynamic_cast<MgHttpPrimitiveValue*>(pResultObj)) { stringVal = ((MgHttpPrimitiveValue*)pResultObj)->ToString(); } if (stringVal.length() > 0) { string utf8 = MG_WCHAR_TO_CHAR(stringVal); printf(MapAgentStrings::ContentLengthHeader, utf8.length()); printf("\r\n%s",utf8.c_str()); } else if (outputReader != NULL) { Ptr<MgHttpHeader> respHeader = response->GetHeader(); //Check for chunking hint if (respHeader->GetHeaderValue(MgHttpResourceStrings::hrhnTransfer_Encoding) == MgHttpResourceStrings::hrhnChunked) { CgiReaderStreamer crs(outputReader); crs.StreamResult(); } else { INT64 outLen = outputReader->GetLength(); printf(MapAgentStrings::ContentLengthHeader,(INT32)outLen); printf("\r\n"); unsigned char buf[4096]; int nBytes = outputReader->Read(buf,4096); while (nBytes > 0) { fwrite(buf, 1, nBytes, stdout); nBytes = outputReader->Read(buf,4096); } } } else { printf(MapAgentStrings::ContentLengthHeader, 0); printf("\r\n"); } } MG_CATCH_AND_THROW(L"CgiResponseHandler.SendResponse"); }
void Socket::ReceiveRaw(STRING filename, int len) { string data = ""; OSTREAM ss; size_t bytesRecv = 0; time_t startTime = time(NULL); size_t written; int total=0; pl_data buf[255]; peel::File pf(filename.c_str(), filename.length()); pf.open("wb"); if(!pf.okay()) throw SocketException(_T("Could not create file"),0); #ifdef _WIN32 u_long arg = 1; ioctlsocket(m_socket, FIONBIO, &arg); #else int x; x=fcntl(m_socket,F_GETFL,0); fcntl(m_socket,F_SETFL,x | O_NONBLOCK); #endif while(total<len) { if(difftime(time(NULL),startTime) > TIMEOUT) throw SocketException(_T("Timeout"),0); bytesRecv = recv( m_socket, (char*)buf, 255, 0 ); if(bytesRecv == SOCKET_ERROR) { int err = GetError(); if(err == SOCKET_WOULDBLOCK) continue; pf.close(); throw SocketException(_T("Receive File Error"), err); } #ifdef _WIN32 if ( bytesRecv == 0 || bytesRecv == SOCKET_CONNRESET ) #else if ( bytesRecv == 0) #endif { pf.close(); throw SocketException(_T("Connection Closed"),0); } if( bytesRecv > 0 ) { pf.write(&buf[0], bytesRecv, &written); if(written == bytesRecv) { pf.close(); ss.str(_T("")); ss << _T("Could not write to file ") << GetError(); throw SocketException(ss.str(),0); } total+= written; } } if(total!=len) { pf.close(); ss.str(_T("")); ss << total << _T(" of ") << len << _T(" recieved."); throw SocketException(ss.str(),0); } pf.close(); return; }
bool AuthenticateOgcRequest(MgHttpRequestParam* params) { bool isWms = false; bool isWfs = false; // Determine with the optional service parameter if the request is WMS or WFS // If the service is present and specifies something else than WMS or WFS, refuse // authentication as MapGuide only supports these 2 services. // // First, check for SERVICE= parameter, indicative of a GET-method request STRING serviceValue = MgUtil::ToUpper(params->GetParameterValue(MgHttpResourceStrings::reqWmsService)); if(serviceValue.length() != 0) { if(serviceValue == L"WFS") isWfs = true; else if(serviceValue == L"WMS") isWms = true; } else // Look for possible POST-method with content payload. { string sContents = params->GetXmlPostData(); if(sContents.length() > 0) { // Look for the service attribute using a light-weight scan of the contents. // No need to invoke a full XML parsing for what's essentially pattern-matching. // (too bad there's no Perl-like RegExp nearby, though... ) bool bWfs = sContents.find("service=\"WFS\"") != string::npos // NOXLATE ||sContents.find("service='WFS'") != string::npos; // NOXLATE bool bWms = sContents.find("service=\"WMS\"") != string::npos // NOXLATE ||sContents.find("service='WMS'") != string::npos; // NOXLATE // No determination made. if(!bWfs && !bWms) { // Tolerance and forgiveness? Look for key namespace declarations before quitting? // Some requests forget the (required!!!) service= attribute, but do everything else // right, relying on the root element to carry the day. // No. If we've gotten here, it's possibly a WMS request, since SERVICE= // isn't always required for them. TODO: this form of authentication should // run past the individual OGC objects to see if they concur. return isWms; } else if(bWfs && bWms) // which is it? this is not good. return false; // abandon the authentication attempt isWms = bWms; isWfs = bWfs; } } MgConfiguration* cfg = MgConfiguration::GetInstance(); // OGC CITE: Test wfs:wfs-1.1.0-Basic-GetCapabilities-tc16.2 (s0012/d1e34887_1/d1e732_1/d1e25171_1/d1e903_1) // Assertion: // In the event that a GetCapabilities request cannot be processed for any reason, // the response entity shall include an exception report. The exception code must // be one of those listed in Table 5. if(!isWms && !isWfs) { cfg->GetBoolValue(MgConfigProperties::OgcPropertiesSection, MgConfigProperties::CITEWfsEnabled, isWfs, MgConfigProperties::DefaultCITEWfsEnabled); cfg->GetBoolValue(MgConfigProperties::OgcPropertiesSection, MgConfigProperties::CITEWmsEnabled, isWms, MgConfigProperties::DefaultCITEWmsEnabled); } // Get WMS/WFS password from configuration. STRING username, password; if(isWms) { username = MgUser::WmsUser; cfg->GetStringValue(MgConfigProperties::OgcPropertiesSection, MgConfigProperties::WmsPassword, password, L""); } else if(isWfs) { username = MgUser::WfsUser; cfg->GetStringValue(MgConfigProperties::OgcPropertiesSection, MgConfigProperties::WfsPassword, password, L""); } else { return false; } //feed these values in as parameters params->AddParameter(MgHttpResourceStrings::reqUsername, username); params->AddParameter(MgHttpResourceStrings::reqPassword, password); return true; }
// 字符串相关 INT KLU_ConvertStringToVector(LPCTSTR strStrintgSource, std::vector< STRING >& vRet, LPCTSTR szKey, BOOL bOneOfKey, BOOL bIgnoreEmpty) { vRet.clear(); //------------------------------------------------------------ //合法性 if(!strStrintgSource || strStrintgSource[0] == '\0') return 0; STRING strSrc = strStrintgSource; //------------------------------------------------------------ //查找第一个分割点 STRING::size_type nLeft = 0; STRING::size_type nRight; if(bOneOfKey) { nRight = strSrc.find_first_of(szKey); } else { nRight = strSrc.find(szKey); } if(nRight == std::string::npos) { nRight = strSrc.length(); } while(TRUE) { STRING strItem = strSrc.substr(nLeft, nRight-nLeft); if(strItem.length() > 0 || !bIgnoreEmpty) { vRet.push_back(strItem); } if(nRight == strSrc.length()) { break; } nLeft = nRight + (bOneOfKey ? 1 : _tcslen(szKey)); if(bOneOfKey) { STRING strTemp = strSrc.substr(nLeft); nRight = strTemp.find_first_of(szKey); if(nRight != STRING::npos) nRight += nLeft; } else { nRight = strSrc.find(szKey, nLeft); } if(nRight == std::string::npos) { nRight = strSrc.length(); } } return (INT)vRet.size(); }
void ParseCommandLineFlags(const char* usage, int* argc, char*** argv, const bool remove_flags) { if (*argc == 1) { tprintf("USAGE: %s\n", usage); PrintCommandLineFlags(); exit(0); } unsigned int i = 1; for (i = 1; i < *argc; ++i) { const char* current_arg = (*argv)[i]; // If argument does not start with a hyphen then break. if (current_arg[0] != '-') { break; } // Position current_arg after startings hyphens. We treat a sequence of // consecutive hyphens of any length identically. while (*current_arg == '-') { ++current_arg; } // If this is asking for usage, print the help message and abort. if (!strcmp(current_arg, "help") || !strcmp(current_arg, "helpshort")) { tprintf("USAGE: %s\n", usage); PrintCommandLineFlags(); exit(0); } // Find the starting position of the value if it was specified in this // string. const char* equals_position = strchr(current_arg, '='); const char* rhs = NULL; if (equals_position != NULL) { rhs = equals_position + 1; } // Extract the flag name. STRING lhs; if (equals_position == NULL) { lhs = current_arg; } else { lhs.assign(current_arg, equals_position - current_arg); } if (!lhs.length()) { tprintf("ERROR: Bad argument: %s\n", (*argv)[i]); exit(1); } // Find the flag name in the list of global flags. // inT32 flag inT32 int_val; if (IntFlagExists(lhs.string(), &int_val)) { if (rhs != NULL) { if (!strlen(rhs)) { // Bad input of the format --int_flag= tprintf("ERROR: Bad argument: %s\n", (*argv)[i]); exit(1); } if (!SafeAtoi(rhs, &int_val)) { tprintf("ERROR: Could not parse int from %s in flag %s\n", rhs, (*argv)[i]); exit(1); } } else { // We need to parse the next argument if (i + 1 >= *argc) { tprintf("ERROR: Could not find value argument for flag %s\n", lhs.string()); exit(1); } else { ++i; if (!SafeAtoi((*argv)[i], &int_val)) { tprintf("ERROR: Could not parse inT32 from %s\n", (*argv)[i]); exit(1); } } } SetIntFlagValue(lhs.string(), int_val); continue; } // double flag double double_val; if (DoubleFlagExists(lhs.string(), &double_val)) { if (rhs != NULL) { if (!strlen(rhs)) { // Bad input of the format --double_flag= tprintf("ERROR: Bad argument: %s\n", (*argv)[i]); exit(1); } if (!SafeAtod(rhs, &double_val)) { tprintf("ERROR: Could not parse double from %s in flag %s\n", rhs, (*argv)[i]); exit(1); } } else { // We need to parse the next argument if (i + 1 >= *argc) { tprintf("ERROR: Could not find value argument for flag %s\n", lhs.string()); exit(1); } else { ++i; if (!SafeAtod((*argv)[i], &double_val)) { tprintf("ERROR: Could not parse double from %s\n", (*argv)[i]); exit(1); } } } SetDoubleFlagValue(lhs.string(), double_val); continue; } // Bool flag. Allow input forms --flag (equivalent to --flag=true), // --flag=false, --flag=true, --flag=0 and --flag=1 bool bool_val; if (BoolFlagExists(lhs.string(), &bool_val)) { if (rhs == NULL) { // --flag form bool_val = true; } else { if (!strlen(rhs)) { // Bad input of the format --bool_flag= tprintf("ERROR: Bad argument: %s\n", (*argv)[i]); exit(1); } if (!strcmp(rhs, "false") || !strcmp(rhs, "0")) { bool_val = false; } else if (!strcmp(rhs, "true") || !strcmp(rhs, "1")) { bool_val = true; } else { tprintf("ERROR: Could not parse bool from flag %s\n", (*argv)[i]); exit(1); } } SetBoolFlagValue(lhs.string(), bool_val); continue; } // string flag const char* string_val; if (StringFlagExists(lhs.string(), &string_val)) { if (rhs != NULL) { string_val = rhs; } else { // Pick the next argument if (i + 1 >= *argc) { tprintf("ERROR: Could not find string value for flag %s\n", lhs.string()); exit(1); } else { string_val = (*argv)[++i]; } } SetStringFlagValue(lhs.string(), string_val); continue; } // Flag was not found. Exit with an error message. tprintf("ERROR: Non-existent flag %s\n", (*argv)[i]); exit(1); } // for each argv if (remove_flags) { (*argv)[i - 1] = (*argv)[0]; (*argv) += (i - 1); (*argc) -= (i - 1); } }
/// <summary> /// Initializes the parameters of the request from an XML document /// (ie, from an HTTP POST request) /// </summary> /// <param name="xmlParams">Input /// This contains the XML document to parse /// </param> /// <returns> /// nothing /// </returns> WfsGetFeatureParams::WfsGetFeatureParams(MgOgcWfsServer& oServer,CREFSTRING xmlRequestString) : m_maxFeatures(-1) , m_filterStrings(new MgStringCollection()) , m_featureTypeList(new MgStringCollection()) , m_pNamespaces(new MgXmlNamespaceManager()) { MgXmlParser parser(xmlRequestString.c_str()); MgXmlNamespaceManager oNamespaces; // Set parsing options parser.SetOptions(keSkipWhitespace|keSkipComments|keSkipProcessingInstructions); parser.Next(); MgXmlSynchronizeOnNamespaceElement oGetFeatureElement(parser, _("http://www.opengis.net/wfs:GetFeature"), oNamespaces); // Some "Tolerance and Forgiveness" FixupMissingWfsNamespaceForGetFeature(oGetFeatureElement,parser,oNamespaces); MgXmlBeginElement* pBegin; if(oGetFeatureElement.AtBegin(&pBegin)) { // Sanity check: this is the same code as the IsValidXmlRequest code, // and theoretically has already been done. If we can rest assured that // the IsValid... call has always already been done, we can dispense with // this redundancy. // ------------------------------------------------------------------------ // While strictly speaking service="WFS" should be present, it isn't always. // In general, if there's a namespace defined "http://www.opengis.net/wfs" // then you can be forgiving, (secretly wagging your finger at the person // who forgot to put that into their request... ;-) STRING sService; if( (pBegin->GetAttribute(_("service"), sService) && _wcsicmp(sService.c_str(), _("WFS")) == 0) || oNamespaces.HasNamespace(_("http://www.opengis.net/wfs")) ) { STRING sMaxFeatures; if(pBegin->GetAttribute(_("maxFeatures"), sMaxFeatures) && sMaxFeatures.length() > 0) m_maxFeatures = (int)MgUtil::StringToInt32(sMaxFeatures); else m_maxFeatures = -1; STRING sVersion; if(pBegin->GetAttribute(_("version"), sVersion) && sVersion.length() > 0) m_version = sVersion; STRING sOutputFormat; if(pBegin->GetAttribute(_("outputFormat"), sOutputFormat) && sOutputFormat.length() > 0) m_outputFormat = oServer.ProcessArgumentAs(_("OutputFormat"),sOutputFormat.c_str()); // We want to hang onto the namespaces that are // defined in the GetFeature request, since that will // likely contain namespaces that help us track feature type // names. m_pNamespaces->TrackBeginElement(*pBegin); /* int i=0,iTotalNamespaces = oNamespaces.TotalCount(); for(int i=0;i<iTotalNamespaces;i++) { if(!oNamespaces.IsEclipsed(i)) { } } */ // We've gotten all we need out of the <GetFeature> begin-element // so now let's dig into its contents: queries... parser.Next(); while(!oGetFeatureElement.AtEnd()) { ParseQueryElement(oServer,parser,oNamespaces); }; } } }
/// <summary> /// Initializes the parameters of the request from a set of pre-parsed parameters /// (ie, from an HTTP GET request) /// </summary> /// <param name="requestParams">Input /// This contains all the parameters of the request. /// </param> /// <returns> /// nothing /// </returns> WfsGetFeatureParams::WfsGetFeatureParams(MgOgcWfsServer& oServer/*MgHttpRequestParam* params*/) : m_maxFeatures(-1) , m_filterStrings(new MgStringCollection()) , m_featureTypeList(new MgStringCollection()) , m_pNamespaces(new MgXmlNamespaceManager()) { // Get the required properties STRING propertyNames = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsPropertyName); m_requiredPropertiesList = GetParenthesisedList(propertyNames); // Get the requested feature types STRING featureTypes = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsTypeName); if(featureTypes.length() > 0) { m_featureTypeList = MgStringCollection::ParseCollection(featureTypes, L","); } else { m_featureTypeList = NULL; } // Get the requested feature IDs STRING featureIds = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsFeatureId); // Get the requested filter STRING filters = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsFilter); // Get the requested bounding box STRING bbox = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsBbox); // Build the filter strings from the feature IDs, filters or bounding box BuildFilterStrings(filters, featureIds, bbox); // Get the requested SRS value m_srs = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsSrsName); if(m_srs.empty()) { m_srs = GetSRSFromBbox(bbox); } // Get the SRS in WKT form STRING srsWkt; if(!m_srs.empty()) { MgWmsMapUtil::SrsToWktMapping(oServer,m_srs,srsWkt); if(!srsWkt.empty()) { m_srs = srsWkt; } } // Get the maximum number of features to return string maxFeaturesParam = MgUtil::WideCharToMultiByte(GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsMaxFeatures)); if(maxFeaturesParam.length() > 0) { m_maxFeatures = atoi(maxFeaturesParam.c_str()); } else { // Return all features by default m_maxFeatures = -1; } // Get the requested output format m_outputFormat = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsOutputFormat); // Get the wfs version m_version = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsVersion); // Get the sortby property name m_sortCriteria = GetRequestParameter(oServer,MgHttpResourceStrings::reqWfsSortBy); }
bool MgWmsLayerDefinitions::GetMetadataDefinitions(MgUtilDictionary& Dictionary) { // STRING sDebug = m_xmlParser->Current().Contents(); // We're looking for a <ResourceDocumentHeader ...> MgXmlSynchronizeOnElement ElementResourceDocumentHeader(*m_xmlParser,_("ResourceDocumentHeader")); if(!ElementResourceDocumentHeader.AtBegin()) return false; // And inside that, there's a <Metadata ...> MgXmlSynchronizeOnElement ElementMetadata(*m_xmlParser,_("Metadata")); if(!ElementMetadata.AtBegin()) return false; // And inside *that*, we hope there's a <Simple...> MgXmlSynchronizeOnElement ElementSimple(*m_xmlParser,_("Simple")); if(!ElementSimple.AtBegin()) return false; // And once we're here, we hope to find a grunch of <Property...> elements while(!ElementSimple.AtEnd()) { MgXmlSynchronizeOnElement ElementProperty(*m_xmlParser,_("Property")); if(ElementProperty.AtBegin()) { // Each of which consist of <Name> and <Value> pairs... STRING sName; STRING sValue; if(GetElementContents(_("Name"),sName) && GetElementContents(_("Value"),sValue)) { STRING sDefinitionName = _("Layer."); // Present the names slightly differently than internal representation. // System-defined metadata is published with an underscore prefix. We // publish this without the underscore: "_Bounds" -> "Layer.Bounds". // User-defined metadata will not have the underscore, and we present // this for consumption as "Layer.user.Whatever" -- just to make sure // that the user and system namespaces remain distinct. if(sName[0] == '_') sDefinitionName += sName.substr(1); else sDefinitionName += _("user.") + sName; //---------------------------------------------------------------------- // If it starts and ends with escaped angled brackets, let's assume it's // "corrupted" XML that simply needs unescaping. // // TODO: This is not meant to be a long-term solution; it just overcomes // a current schema restriction on metadata consisting of mixed content. STRING::size_type iLt =sValue.find(_("<")); STRING::size_type iGt = sValue.rfind(_(">")); STRING::size_type iLen = sValue.length(); if(sValue.find(_("<")) == 0 && sValue.rfind(_(">")) == sValue.length() - 4) { STRING::size_type iPos; while((iPos = sValue.find(_("<"))) != STRING::npos) sValue = sValue.substr(0,iPos) + _("<") + sValue.substr(iPos+4); while((iPos = sValue.find(_(">"))) != STRING::npos) sValue = sValue.substr(0,iPos) + _(">") + sValue.substr(iPos+4); while((iPos = sValue.find(_("\x201d"))) != STRING::npos) sValue = sValue.substr(0,iPos) + _("\"") + sValue.substr(iPos+1); } //---------------------------------------------------------------------- Dictionary.AddDefinition(sDefinitionName,sValue); } } } return true; }
void c_FeatureReaderToHtml::ToTemplate(bool IsKml,c_RestDataReader* Reader, c_RestRequest* RestRequest , const string& FullUri,const string& UriBase ,string& HtmlStr,int StartIndex,int MaxCount) { Ptr<MgClassDefinition> classdef; // classdef = if( FeatureReader ) FeatureReader->GetClassDefinition() ; classdef = RestRequest->m_DataClassDef; if( !classdef ) return; //const c_CfgDataLayer* cfgdata = MgRest_MapNameToResourceId::GetCfgDataForClass(classfullname); const c_CfgDataResource* cfgresource = RestRequest->m_CfgDataResource; if( !cfgresource ) return; // error ; class has to be in configuration file const c_CfgRepTemplate* templatedata; if( RestRequest->m_CfgRepresentation->GetType() != c_CfgRepresentation::e_Template ) { return; } templatedata = (c_CfgRepTemplate*)RestRequest->m_CfgRepresentation; string rest_uri_part; if( cfgresource->m_RestUriPart.length() > 0 ) { MgUtil::WideCharToMultiByte(cfgresource->m_RestUriPart,rest_uri_part); } else { rest_uri_part = "/rest/data/"; } //ctemplate::Template::SetTemplateRootDirectory(g_HtmlTemplatePath); ctemplate::Template::SetTemplateRootDirectory(RestRequest->m_CfgDataResource->m_TemplateFolder); // get identity property name; STRING identname; if( classdef ) { Ptr<MgPropertyDefinitionCollection> idents = classdef->GetIdentityProperties(); if( idents->GetCount() == 1) { int ind=0; Ptr<MgPropertyDefinition> identprop = idents->GetItem(ind); identname = identprop->GetName(); } else { identname = L""; } } ctemplate::TemplateDictionary dict_main("KING.MGREST"); // now fill in request parameters if( RestRequest ) { Ptr<c_RestUriRequestParam> req_param = RestRequest->GetRequestParam(); MgStringPropertyCollection* params = req_param->GetParameters(); if( params && (params->GetCount()>0) ) { string dictkey; string param_name,param_val; string keyprefix = "REST_PARAM_"; for(int ind=0;ind<params->GetCount();ind++) { Ptr<MgStringProperty> param = params->GetItem(ind); MgUtil::WideCharToMultiByte(param->GetName(),param_name); ReplaceSpaces(param_name); // google ctemplate doesn't allow spaces MgUtil::WideCharToMultiByte(param->GetValue(),param_val); dict_main.SetValue(keyprefix+param_name,param_val); } } } string resturiparam; bool ismorerecords=false; int featurecount=0; if( (classdef != NULL) && (Reader!=NULL) ) { STRING wresturiparam = cfgresource->m_UriTag; MgUtil::WideCharToMultiByte(wresturiparam,resturiparam); bool isnext=true; int skipstart = StartIndex; if( skipstart > 0 ) { while ( (skipstart>0) && (isnext=Reader->ReadNext())==true ) { skipstart--; } } if( isnext ) { string dictname; // = mb_classname; MgUtil::WideCharToMultiByte(templatedata->m_HtmlTemp_Section,dictname); string nameprefix; // = mb_classname + "_"; MgUtil::WideCharToMultiByte(templatedata->m_HtmlTemp_Prefix,nameprefix); while ( Reader->ReadNext() ) { if( MaxCount >= 0 ) { if( featurecount >= MaxCount ) { ismorerecords=true; break; // go out } } ctemplate::TemplateDictionary* dict_section = dict_main.AddSectionDictionary(dictname); FillDictionary(dict_section,nameprefix,Reader); if( identname.length() > 0 ) { STRING strval; string mb_strval; GetPropertyAsString(Reader,identname,strval); MgUtil::WideCharToMultiByte(strval,mb_strval); // string dictkey = nameprefix + "REST_PNG"; string val = UriBase + rest_uri_part + resturiparam + "/" + mb_strval + ".png"; dict_section->SetValue(dictkey,val); dictkey = nameprefix + "REST_HTML"; val = UriBase + rest_uri_part + resturiparam + "/" + mb_strval + ".html"; dict_section->SetValue(dictkey,val); dictkey = nameprefix + "REST_KML"; val = UriBase + rest_uri_part + resturiparam + "/" + mb_strval + ".kml"; dict_section->SetValue(dictkey,val); dictkey = nameprefix + "REST_KMZ"; val = UriBase + rest_uri_part + resturiparam + "/" + mb_strval + ".kmz"; dict_section->SetValue(dictkey,val); dictkey = nameprefix + "REST_XML"; val = UriBase + rest_uri_part + resturiparam + "/" + mb_strval + ".xml"; dict_section->SetValue(dictkey,val); dictkey = nameprefix + "REST_JSON"; val = UriBase + rest_uri_part + resturiparam + "/" + mb_strval + ".json"; dict_section->SetValue(dictkey,val); // create feature identifier value as base64 coded string ident_base64; GetPropertyAsBase64(Reader,identname,ident_base64); dictkey = nameprefix + "REST_IDENT_BASE64"; dict_section->SetValue(dictkey,ident_base64); } featurecount++; } } // Now check additional data to be fetched for html template // it applies only to single feature templates if( featurecount==1 && templatedata->GetCountHtmlExtraData() > 0 ) { int count = templatedata->GetCountHtmlExtraData(); for(int ind=0;ind<count;ind++) { const c_CfgRepTemplateExtraData* extradata = templatedata->GetHtmlExtraData(ind); if( extradata->m_FetchUri.length() > 0 ) { // generate template unique name std::string filename,mb_str; MgUtil::WideCharToMultiByte(cfgresource->m_UriTag,filename); MgUtil::WideCharToMultiByte(extradata->m_HtmlTemp_Prefix,mb_str); filename += mb_str; MgUtil::WideCharToMultiByte(extradata->m_FetchUri,mb_str); filename=""; ctemplate::Template * temp = ctemplate::Template::StringToTemplate(mb_str,ctemplate::STRIP_WHITESPACE); /* ctemplate::Template * temp = ctemplate::Template::RegisterStringAsTemplate(filename, ctemplate::STRIP_WHITESPACE,ctemplate::TC_MANUAL,mb_str); */ std::string uristr; temp->Expand(&uristr,&dict_main); // Now use uristr to fetch data std::string mb_str2,mb_str3,mb_str4; MgUtil::WideCharToMultiByte(extradata->m_HtmlTemp_Section,mb_str2); MgUtil::WideCharToMultiByte(extradata->m_HtmlTemp_DataSection,mb_str3); MgUtil::WideCharToMultiByte(extradata->m_HtmlTemp_Prefix,mb_str4); c_RestFetchSource::FetchFeaturesToDictionary( uristr,&dict_main,mb_str2,mb_str3,mb_str4 ); delete temp; } } } // now add in dictionary values for next and previous if( ismorerecords || StartIndex>0 ) { Poco::URI uri_parser(FullUri); std::string query = uri_parser.getQuery(); c_RestUriRequestParam params; c_RestUri::ParseQuery(query.c_str(),¶ms); if( StartIndex>0 ) { int newstart = StartIndex - MaxCount; if( newstart < 0 ) newstart=0; newstart++; wchar_t strstart[20]; ::swprintf(&strstart[0],L"%d",newstart); if( params.ContainsParameter(L"Start") ) { params.SetParameterValue(L"Start",strstart); } else { params.AddParameter(L"Start",strstart); } wstring wuriquery; params.GetAsUriQuery(wuriquery); string uriquery; MgUtil::WideCharToMultiByte(wuriquery,uriquery); //string prev_uri = UriBase + rest_uri_part + resturiparam + "/" + ".html" + "?" + uriquery; string prev_uri = "?" + uriquery; // use only query part so link will be correct in case of url rewrites ctemplate::TemplateDictionary* dict_section = dict_main.AddSectionDictionary("PREVIOUS_PAGE_SECTION"); string dictkey = "PREVIOUS_PAGE"; dict_section->SetValue(dictkey,prev_uri); } else { // no previous link //string dictkey = nameprefix + "PREVIOUS_PAGE"; //dict_main.SetEscapedValue(,); } if( ismorerecords>0 ) { int newstart = StartIndex + MaxCount; if( newstart < 0 ) newstart=0; newstart++; wchar_t strstart[20]; ::swprintf(&strstart[0],L"%d",newstart); if( params.ContainsParameter(L"Start") ) { params.SetParameterValue(L"Start",strstart); } else { params.AddParameter(L"Start",strstart); } wstring wuriquery; params.GetAsUriQuery(wuriquery); string uriquery; MgUtil::WideCharToMultiByte(wuriquery,uriquery); //string next_uri = UriBase + rest_uri_part + resturiparam + "/" + ".html" + "?" + uriquery; string next_uri = "?" + uriquery; // use only query part so link will be correct in case of url rewrites ctemplate::TemplateDictionary* dict_section = dict_main.AddSectionDictionary("NEXT_PAGE_SECTION"); string dictkey = "NEXT_PAGE"; dict_section->SetValue(dictkey,next_uri); } else { // no previous link //string dictkey = nameprefix + "NEXT_PAGE"; //dict_main.SetEscapedValue(,); } } } string tmpl; // name of template to use if(Reader) { if( featurecount == 1 ) MgUtil::WideCharToMultiByte(templatedata->m_HtmlTemp_Single,tmpl); else { if( featurecount == 0 ) MgUtil::WideCharToMultiByte(templatedata->m_HtmlTemp_Zero,tmpl); else MgUtil::WideCharToMultiByte(templatedata->m_HtmlTemp_Many,tmpl); } } else { // if there was no feature reader MgUtil::WideCharToMultiByte(templatedata->m_HtmlTemp_Error,tmpl); if(RestRequest->m_RestResultObjectStatus == c_RestRequest::e_BBox_OutOfRange ) dict_main.ShowSection("EXCEPTION_BBOX_LIMIT"); if(RestRequest->m_RestResultObjectStatus == c_RestRequest::e_Count_OutOfRange ) dict_main.ShowSection("EXCEPTION_COUNT_LIMIT"); } /* string tmpl = mb_classname; // if there is only one feature then use different template // name of that template for class "parcel" is parcel.tpl , added "1" to end of class name if( count <= 1 ) { tmpl.append("1"); } tmpl.append(".tpl"); */ ctemplate::Template::ReloadAllIfChanged(); ctemplate::TemplateContext tc; if( IsKml ) tc = ctemplate::TC_XML; else tc = ctemplate::TC_HTML; //ctemplate::Template* tpl = ctemplate::Template::GetTemplateWithAutoEscaping(tmpl,ctemplate::DO_NOT_STRIP,tc); ctemplate::Template* tpl = ctemplate::Template::GetTemplate(tmpl,ctemplate::DO_NOT_STRIP); if( !tpl ) { //Ptr<MgStringCollection> scol = new MgStringCollection(); std::wstring wsarg; MgUtil::MultiByteToWideChar(tmpl,wsarg); //scol->Add(wsarg); std::wstring errmsg = L"Unable to load Template file '"; errmsg = errmsg.append(wsarg); errmsg = errmsg.append(L"'. Check config file and template file location!"); throw new MgRuntimeException(L"c_FeatureReaderToHtml::ToTemplate",__LINE__, __WFILE__, NULL, errmsg, NULL); } tpl->Expand(&HtmlStr,&dict_main); }//end of c_FeatureReaderToHtml::ToTemplate
/** * word_display() Word Processor * * Display a word according to its display modes */ BOOL8 Tesseract::word_display(BLOCK* block, ROW* row, WERD_RES* word_res) { WERD* word = word_res->word; TBOX word_bb; // word bounding box int word_height; // ht of word BB BOOL8 displayed_something = FALSE; float shift; // from bot left C_BLOB_IT c_it; // cblob iterator if (color_mode != CM_RAINBOW && word_res->box_word != NULL) { BoxWord* box_word = word_res->box_word; int length = box_word->length(); if (word_res->fontinfo == NULL) return false; const FontInfo& font_info = *word_res->fontinfo; for (int i = 0; i < length; ++i) { ScrollView::Color color = ScrollView::GREEN; switch (color_mode) { case CM_SUBSCRIPT: if (box_word->BlobPosition(i) == SP_SUBSCRIPT) color = ScrollView::RED; break; case CM_SUPERSCRIPT: if (box_word->BlobPosition(i) == SP_SUPERSCRIPT) color = ScrollView::RED; break; case CM_ITALIC: if (font_info.is_italic()) color = ScrollView::RED; break; case CM_BOLD: if (font_info.is_bold()) color = ScrollView::RED; break; case CM_FIXEDPITCH: if (font_info.is_fixed_pitch()) color = ScrollView::RED; break; case CM_SERIF: if (font_info.is_serif()) color = ScrollView::RED; break; case CM_SMALLCAPS: if (word_res->small_caps) color = ScrollView::RED; break; case CM_DROPCAPS: if (box_word->BlobPosition(i) == SP_DROPCAP) color = ScrollView::RED; break; // TODO(rays) underline is currently completely unsupported. case CM_UNDERLINE: default: break; } image_win->Pen(color); TBOX box = box_word->BlobBox(i); image_win->Rectangle(box.left(), box.bottom(), box.right(), box.top()); } return true; } /* Note the double coercions of(COLOUR)((inT32)editor_image_word_bb_color) etc. are to keep the compiler happy. */ // display bounding box if (word->display_flag(DF_BOX)) { word->bounding_box().plot(image_win, (ScrollView::Color)((inT32) editor_image_word_bb_color), (ScrollView::Color)((inT32) editor_image_word_bb_color)); ScrollView::Color c = (ScrollView::Color) ((inT32) editor_image_blob_bb_color); image_win->Pen(c); c_it.set_to_list(word->cblob_list()); for (c_it.mark_cycle_pt(); !c_it.cycled_list(); c_it.forward()) c_it.data()->bounding_box().plot(image_win); displayed_something = TRUE; } // display edge steps if (word->display_flag(DF_EDGE_STEP)) { // edgesteps available word->plot(image_win); // rainbow colors displayed_something = TRUE; } // display poly approx if (word->display_flag(DF_POLYGONAL)) { // need to convert TWERD* tword = TWERD::PolygonalCopy(word); tword->plot(image_win); delete tword; displayed_something = TRUE; } // Display correct text and blamer information. STRING text; STRING blame; if (word->display_flag(DF_TEXT) && word->text() != NULL) { text = word->text(); } if (word->display_flag(DF_BLAMER) && !(word_res->blamer_bundle != NULL && word_res->blamer_bundle->incorrect_result_reason == IRR_CORRECT)) { text = ""; const BlamerBundle *blamer_bundle = word_res->blamer_bundle; if (blamer_bundle == NULL) { text += "NULL"; } else { for (int i = 0; i < blamer_bundle->truth_text.length(); ++i) { text += blamer_bundle->truth_text[i]; } } text += " -> "; STRING best_choice_str; if (word_res->best_choice == NULL) { best_choice_str = "NULL"; } else { word_res->best_choice->string_and_lengths(&best_choice_str, NULL); } text += best_choice_str; IncorrectResultReason reason = (blamer_bundle == NULL) ? IRR_PAGE_LAYOUT : blamer_bundle->incorrect_result_reason; ASSERT_HOST(reason < IRR_NUM_REASONS) blame += " ["; blame += BlamerBundle::IncorrectReasonName(reason); blame += "]"; } if (text.length() > 0) { word_bb = word->bounding_box(); image_win->Pen(ScrollView::RED); word_height = word_bb.height(); int text_height = 0.50 * word_height; if (text_height > 20) text_height = 20; image_win->TextAttributes("Arial", text_height, false, false, false); shift = (word_height < word_bb.width()) ? 0.25 * word_height : 0.0f; image_win->Text(word_bb.left() + shift, word_bb.bottom() + 0.25 * word_height, text.string()); if (blame.length() > 0) { image_win->Text(word_bb.left() + shift, word_bb.bottom() + 0.25 * word_height - text_height, blame.string()); } displayed_something = TRUE; } if (!displayed_something) // display BBox anyway word->bounding_box().plot(image_win, (ScrollView::Color)((inT32) editor_image_word_bb_color), (ScrollView::Color)((inT32) editor_image_word_bb_color)); return TRUE; }
MgByteReader* MgHtmlController::CollectQueryMapFeaturesResult(MgResourceService* resourceService, INT32 requestData, MgFeatureInformation* featInfo, MgSelection* selectionSet, MgBatchPropertyCollection* attributes, MgByteReader* inlineSelection) { STRING xml; STRING tooltip; STRING hyperlink; STRING xmlSelection = selectionSet? selectionSet->ToXml(false): L""; if (NULL != featInfo) { tooltip = featInfo->GetTooltip(); hyperlink = featInfo->GetHyperlink(); } // TODO: Stil haven't defined a schema for v2.6. Should we? xml.append(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<FeatureInformation>\n"); size_t len = xmlSelection.length(); if(len > 0) { xml.reserve(len + 2048); xml.append(xmlSelection); } else { xml.reserve(2048); xml.append(L"<FeatureSet />\n"); } if (((requestData & REQUEST_TOOLTIP) == REQUEST_TOOLTIP) && !tooltip.empty()) { xml.append(L"<Tooltip>"); xml.append(MgUtil::ReplaceEscapeCharInXml(tooltip)); xml.append(L"</Tooltip>\n"); } else xml.append(L"<Tooltip />\n"); if (((requestData & REQUEST_HYPERLINK) == REQUEST_HYPERLINK) && !hyperlink.empty()) { xml.append(L"<Hyperlink>"); xml.append(MgUtil::ReplaceEscapeCharInXml(hyperlink)); xml.append(L"</Hyperlink>\n"); } else xml.append(L"<Hyperlink />\n"); if (((requestData & REQUEST_INLINE_SELECTION) == REQUEST_INLINE_SELECTION) && NULL != inlineSelection) { xml.append(L"<InlineSelectionImage>\n"); xml.append(L"<MimeType>"); xml.append(inlineSelection->GetMimeType()); xml.append(L"</MimeType>\n"); xml.append(L"<Content>"); MgByteSink sink(inlineSelection); Ptr<MgByte> bytes = sink.ToBuffer(); Ptr<MgMemoryStreamHelper> streamHelper = new MgMemoryStreamHelper((INT8*) bytes->Bytes(), bytes->GetLength(), false); std::string b64 = streamHelper->ToBase64(); STRING wb64 = MgUtil::MultiByteToWideChar(b64); xml.append(wb64); xml.append(L"</Content>\n"); xml.append(L"</InlineSelectionImage>\n"); } else xml.append(L"<InlineSelectionImage />\n"); if (((requestData & REQUEST_ATTRIBUTES) == REQUEST_ATTRIBUTES) && NULL != attributes) { xml.append(L"<SelectedFeatures>\n"); WriteSelectedFeatureAttributes(resourceService, selectionSet, attributes, xml); xml.append(L"</SelectedFeatures>\n"); } else xml.append(L"<SelectedFeatures />\n"); xml.append(L"</FeatureInformation>\n"); string xmlDoc = MgUtil::WideCharToMultiByte(xml); STRING mimeType = L"text/xml"; return MgUtil::GetByteReader(xmlDoc, &mimeType); }