void Scene::save(const QString& fn) { QDomDocument doc; doc.appendChild(doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"utf-8\"" )); QDomElement root = doc.createElement("scene"); doc.appendChild(root); root.setAttribute("width",m_worldSize.width()); root.setAttribute("height",m_worldSize.height()); for (int i=0; i<bodysCount(); ++i) { Body* b = body(i); QDomElement be = doc.createElement("body"); WriteAttributes(b,be,doc); for (int j=0; j<b->primitivesCount(); ++j) { Primitive* p = b->primitive(j); QDomElement pe = doc.createElement("primitive"); WriteAttributes(p,pe,doc); be.appendChild(pe); } root.appendChild(be); } QFile file(fn); if (file.open(QIODevice::WriteOnly)) { file.write(doc.toByteArray()); m_history->markSaved(); emit changed(); } else { } }
void URLView::CreatePerson( const BString *fullName, const BString *title ) { // Read the file defined by the path and the title. BFile *file = new BFile( fullName->String(), B_WRITE_ONLY ); // Set the file's MIME type to be a person. BNodeInfo *nodeInfo = new BNodeInfo( file ); nodeInfo->SetType( "application/x-person" ); delete nodeInfo; delete file; // Add all the attributes, both those inherrent to person files and any // the developer may have defined using AddAttribute(). DIR *d; int fd; d = fs_open_attr_dir( fullName->String() ); if( d ) { fd = open( fullName->String(), O_WRONLY ); fs_write_attr( fd, "META:name", B_STRING_TYPE, 0, title->String(), title->Length() + 1 ); BString email = GetImportantURL(); fs_write_attr( fd, "META:email", B_STRING_TYPE, 0, email.String(), email.Length() + 1 ); WriteAttributes( fd ); close( fd ); fs_close_attr_dir( d ); } }
void CXMLWriterStd::OpenElement(const char *name) { Stream() << "<" << name; WriteAttributes(); Stream() << ">\n"; m_bEmpty = true; }
void XmlMapHandler::WriteLayer(wxXmlNode* root, const Map& map, const Layer& layer) { VerboseLog("Writing a Layer"); wxXmlNode* node = new wxXmlNode(root, wxXML_ELEMENT_NODE, "Layer"); wxString layerdata = "\n"; for (unsigned int i = 0; i < layer.GetHeight(); i++) { layerdata << "\t\t\t"; for (unsigned int j = 0; j < layer.GetWidth(); j++) layerdata << layer.At(j, i) << ", "; layerdata << "\n"; } wxXmlNode* data = new wxXmlNode(node, wxXML_ELEMENT_NODE, "Data"); new wxXmlNode(data, wxXML_TEXT_NODE, "", layerdata); wxXmlNode* dimensions = new wxXmlNode(node, wxXML_ELEMENT_NODE, "Dimensions"); new wxXmlNode(dimensions, wxXML_TEXT_NODE, "", wxString::Format("%i, %i", layer.GetWidth(), layer.GetHeight())); WriteAttributes(node, layer); wxXmlNode* name = new wxXmlNode(node, wxXML_ELEMENT_NODE, "Name"); new wxXmlNode(name, wxXML_TEXT_NODE, "", layer.GetName()); VerboseLog("Done Writing a Layer"); }
nsresult nsLoggingSink::OpenNode(const char* aKind, const nsIParserNode& aNode) { WriteTabs(mOutput,++mLevel); PR_fprintf(mOutput,"<open container="); nsHTMLTag nodeType = nsHTMLTag(aNode.GetNodeType()); if ((nodeType >= eHTMLTag_unknown) && (nodeType <= nsHTMLTag(NS_HTML_TAG_MAX))) { const PRUnichar* tag = nsHTMLTags::GetStringValue(nodeType); PR_fprintf(mOutput, "\"%s\"", NS_ConvertUTF16toUTF8(tag).get()); } else { char* text = nsnull; GetNewCString(aNode.GetText(), &text); if(text) { PR_fprintf(mOutput, "\"%s\"", text); nsMemory::Free(text); } } if (WillWriteAttributes(aNode)) { PR_fprintf(mOutput, ">\n"); WriteAttributes(aNode); PR_fprintf(mOutput, "</open>\n"); } else { PR_fprintf(mOutput, ">\n"); } return NS_OK; }
nsresult nsLoggingSink::LeafNode(const nsIParserNode& aNode) { WriteTabs(mOutput,1+mLevel); nsHTMLTag nodeType = nsHTMLTag(aNode.GetNodeType()); if ((nodeType >= eHTMLTag_unknown) && (nodeType <= nsHTMLTag(NS_HTML_TAG_MAX))) { const PRUnichar* tag = nsHTMLTags::GetStringValue(nodeType); if(tag) PR_fprintf(mOutput, "<leaf tag=\"%s\"", NS_ConvertUTF16toUTF8(tag).get()); else PR_fprintf(mOutput, "<leaf tag=\"???\""); if (WillWriteAttributes(aNode)) { PR_fprintf(mOutput, ">\n"); WriteAttributes(aNode); PR_fprintf(mOutput, "</leaf>\n"); } else { PR_fprintf(mOutput, "/>\n"); } } else { PRInt32 pos; nsAutoString tmp; char* str = nsnull; switch (nodeType) { case eHTMLTag_whitespace: case eHTMLTag_text: GetNewCString(aNode.GetText(), &str); if(str) { PR_fprintf(mOutput, "<text value=\"%s\"/>\n", str); nsMemory::Free(str); } break; case eHTMLTag_newline: PR_fprintf(mOutput, "<newline/>\n"); break; case eHTMLTag_entity: tmp.Append(aNode.GetText()); tmp.Cut(0, 1); pos = tmp.Length() - 1; if (pos >= 0) { tmp.Cut(pos, 1); } PR_fprintf(mOutput, "<entity value=\"%s\"/>\n", NS_LossyConvertUTF16toASCII(tmp).get()); break; default: NS_NOTREACHED("unsupported leaf node type"); }//switch } return NS_OK; }
nsresult WritePropertiesTo(nsIRDFDataSource* aDataSource, const char* aProviderType, FILE* out) { // attempt to mimic nsXMLRDFDataSource::Flush? nsCOMPtr<nsIRDFService> rdfService = do_GetService("@mozilla.org/rdf/rdf-service;1"); nsCOMPtr<nsIRDFResource> providerRoot; nsCAutoString urn(NS_LITERAL_CSTRING(urn_prefix) + nsDependentCString(aProviderType) + NS_LITERAL_CSTRING(":root")); rdfService->GetResource(urn, getter_AddRefs(providerRoot)); nsCOMPtr<nsIRDFContainer> providerContainer = do_CreateInstance("@mozilla.org/rdf/container;1"); providerContainer->Init(aDataSource, providerRoot); nsCOMPtr<nsISimpleEnumerator> providers; providerContainer->GetElements(getter_AddRefs(providers)); PRBool hasMore; providers->HasMoreElements(&hasMore); for (; hasMore; providers->HasMoreElements(&hasMore)) { nsCOMPtr<nsISupports> supports; providers->GetNext(getter_AddRefs(supports)); nsCOMPtr<nsIRDFResource> kid = do_QueryInterface(supports); const char* providerUrn; kid->GetValueConst(&providerUrn); // remove the prefix, the provider type, and the trailing ':' // (the compiler will optimize out the -1 + 1 providerUrn += (sizeof(urn_prefix)-1) + strlen(aProviderType) + 1; WriteAttributes(aDataSource, aProviderType, providerUrn, kid, out); } return NS_OK; }
void CXMLWriterStd::WriteElement( const char * name, const char * content, bool escapeWhitespace) { m_bEmpty = false; if(content && content[0]) { OpenElement(name); Stream() << content; CloseElement(name); } else { Stream() << "<" << name; WriteAttributes(); Stream() << "/>\n"; } }
void XmlMapHandler::WriteBackground(wxXmlNode* root, const Map& map, const Background& background) { VerboseLog("Writing a Background"); float x, y; background.GetSpeed(x, y); wxXmlNode* back = new wxXmlNode(root, wxXML_ELEMENT_NODE, "Background"); WriteAttributes(back, background); wxXmlNode* speed = new wxXmlNode(back, wxXML_ELEMENT_NODE, "Speed"); new wxXmlNode(speed, wxXML_TEXT_NODE, "", wxString::Format("%f, %f", x, y)); wxXmlNode* mode = new wxXmlNode(back, wxXML_ELEMENT_NODE, "Mode"); new wxXmlNode(mode, wxXML_TEXT_NODE, "", wxString::Format("%i", background.GetMode())); wxXmlNode* filename = new wxXmlNode(back, wxXML_ELEMENT_NODE, "Filename"); new wxXmlNode(filename, wxXML_TEXT_NODE, "", background.GetFilename()); wxXmlNode* name = new wxXmlNode(back, wxXML_ELEMENT_NODE, "Name"); new wxXmlNode(name, wxXML_TEXT_NODE, "", background.GetName()); VerboseLog("Done Writing a Background"); }
void URLView::CreateBookmark( const BString *fullName, const BString *title ) { // Read the file defined by the path and the title. BFile *file = new BFile( fullName->String(), B_WRITE_ONLY ); // Set the file's MIME type to be a bookmark. BNodeInfo *nodeInfo = new BNodeInfo( file ); nodeInfo->SetType( "application/x-vnd.Be-bookmark" ); delete nodeInfo; delete file; // Add all the attributes, both those inherrent to bookmarks and any // the developer may have defined using AddAttribute(). DIR *d; int fd; d = fs_open_attr_dir( fullName->String() ); if( d ) { fd = open( fullName->String(), O_WRONLY ); fs_write_attr( fd, "META:title", B_STRING_TYPE, 0, title->String(), title->Length() + 1 ); fs_write_attr( fd, "META:url", B_STRING_TYPE, 0, url->String(), url->Length() + 1 ); WriteAttributes( fd ); close( fd ); fs_close_attr_dir( d ); } }
HDFRegionsWriter::~HDFRegionsWriter(void) { WriteAttributes(); Close(); }
int _tmain(int argc, WCHAR* argv[]) { HRESULT hr; CComPtr<IStream> pFileStream; CComPtr<IXmlReader> pReader; XmlNodeType nodetype; const WCHAR* pwszPrefix; const WCHAR* pwszLocalName; const WCHAR* pwszNamespaceUri; UINT cwchPrefix; if (argc != 2) { wprintf(L"Usage: XmlLiteNamespaceReader.exe name-of-input-file\n"); return 0; } //Open read-only input stream if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE))) { wprintf(L"Error creating file reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL))) { wprintf(L"Error creating xml reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->SetInput(pFileStream))) { wprintf(L"Error setting input for reader, error is %08.8lx", hr); return -1; } while (true) { hr = pReader->Read(&nodetype); if (S_FALSE == hr) break; if (S_OK != hr) { wprintf(L"\nXmlLite Error: %08.8lx\n", hr); return -1; } switch (nodetype) { case XmlNodeType_Element: if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix))) { wprintf(L"Error, Method: GetPrefix, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) { wprintf(L"Error, Method: GetLocalName, error is %08.8lx", hr); return -1; } if (cwchPrefix > 0) wprintf(L"%s:%s ", pwszPrefix, pwszLocalName); else wprintf(L"%s ", pwszLocalName); if (FAILED(hr = pReader->GetNamespaceUri(&pwszNamespaceUri, NULL))) { wprintf(L"Error, Method: GetNamespaceUri, error is %08.8lx", hr); return -1; } wprintf(L"Namespace=%s\n", pwszNamespaceUri); if (FAILED(hr = WriteAttributes(pReader))) { wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr); return -1; } break; } } wprintf(L"\n"); return 0; }
/** * This method gets called when a tag needs to be sent out * * @update gess 3/25/98 * @param * @return result status */ nsresult CViewSourceHTML::WriteTag(PRInt32 aTagType,const nsSubstring & aText,PRInt32 attrCount,PRBool aTagInError) { nsresult result=NS_OK; // adjust line number to what it will be after we finish writing this tag // XXXbz life here sucks. We can't use the GetNewlineCount on the token, // because Text tokens in <style>, <script>, etc lie through their teeth. // On the other hand, the parser messes up newline counting in some token // types (bug 137315). So our line numbers will disagree with the parser's // in some cases... // XXXbenjamn Shouldn't we be paying attention to the aCountLines BuildModel // parameter here? mLineNumber += aText.CountChar(PRUnichar('\n')); nsTokenAllocator* theAllocator=mTokenizer->GetTokenAllocator(); NS_ASSERTION(0!=theAllocator,"Error: no allocator"); if(0==theAllocator) return NS_ERROR_FAILURE; // Highlight all parts of all erroneous tags. if (mSyntaxHighlight && aTagInError) { CStartToken* theTagToken= static_cast<CStartToken*> (theAllocator->CreateTokenOfType(eToken_start, eHTMLTag_span, NS_LITERAL_STRING("SPAN"))); NS_ENSURE_TRUE(theTagToken, NS_ERROR_OUT_OF_MEMORY); mErrorNode.Init(theTagToken, theAllocator); AddAttrToNode(mErrorNode, theAllocator, NS_LITERAL_STRING("class"), NS_LITERAL_STRING("error")); mSink->OpenContainer(mErrorNode); IF_FREE(theTagToken, theAllocator); #ifdef DUMP_TO_FILE if (gDumpFile) { fprintf(gDumpFile, "<span class=\"error\">"); } #endif } if (kBeforeText[aTagType][0] != 0) { NS_ConvertASCIItoUTF16 beforeText(kBeforeText[aTagType]); mITextToken.SetIndirectString(beforeText); nsCParserNode theNode(&mITextToken, 0/*stack token*/); mSink->AddLeaf(theNode); } #ifdef DUMP_TO_FILE if (gDumpFile && kDumpFileBeforeText[aTagType][0]) fprintf(gDumpFile, kDumpFileBeforeText[aTagType]); #endif // DUMP_TO_FILE if (mSyntaxHighlight && aTagType != kText) { CStartToken* theTagToken= static_cast<CStartToken*> (theAllocator->CreateTokenOfType(eToken_start, eHTMLTag_span, NS_LITERAL_STRING("SPAN"))); NS_ENSURE_TRUE(theTagToken, NS_ERROR_OUT_OF_MEMORY); mStartNode.Init(theTagToken, theAllocator); AddAttrToNode(mStartNode, theAllocator, NS_LITERAL_STRING("class"), NS_ConvertASCIItoUTF16(kElementClasses[aTagType])); mSink->OpenContainer(mStartNode); //emit <starttag>... IF_FREE(theTagToken, theAllocator); #ifdef DUMP_TO_FILE if (gDumpFile) { fprintf(gDumpFile, "<span class=\""); fprintf(gDumpFile, kElementClasses[aTagType]); fprintf(gDumpFile, "\">"); } #endif // DUMP_TO_FILE } STOP_TIMER(); mITextToken.SetIndirectString(aText); //now emit the tag name... nsCParserNode theNode(&mITextToken, 0/*stack token*/); mSink->AddLeaf(theNode); #ifdef DUMP_TO_FILE if (gDumpFile) { fputs(NS_ConvertUTF16toUTF8(aText).get(), gDumpFile); } #endif // DUMP_TO_FILE if (mSyntaxHighlight && aTagType != kText) { mStartNode.ReleaseAll(); mSink->CloseContainer(eHTMLTag_span); //emit </endtag>... #ifdef DUMP_TO_FILE if (gDumpFile) fprintf(gDumpFile, "</span>"); #endif //DUMP_TO_FILE } if(attrCount){ result=WriteAttributes(aText, theAllocator, attrCount, aTagInError); } // Tokens are set in error if their ending > is not there, so don't output // the after-text if (!aTagInError && kAfterText[aTagType][0] != 0) { NS_ConvertASCIItoUTF16 afterText(kAfterText[aTagType]); mITextToken.SetIndirectString(afterText); nsCParserNode theNode(&mITextToken, 0/*stack token*/); mSink->AddLeaf(theNode); } #ifdef DUMP_TO_FILE if (!aTagInError && gDumpFile && kDumpFileAfterText[aTagType][0]) fprintf(gDumpFile, kDumpFileAfterText[aTagType]); #endif // DUMP_TO_FILE if (mSyntaxHighlight && aTagInError) { mErrorNode.ReleaseAll(); mSink->CloseContainer(eHTMLTag_span); //emit </endtag>... #ifdef DUMP_TO_FILE if (gDumpFile) fprintf(gDumpFile, "</span>"); #endif //DUMP_TO_FILE } START_TIMER(); return result; }
/** Prints the contents of each group as XML tags and values */ int SaveToSNSHistogramNexus::WriteGroup(int is_definition) { int status, dataType, dataRank, dataDimensions[NX_MAXRANK]; NXname name, theClass; void *dataBuffer; NXlink link; do { status = NXgetnextentry(inId, name, theClass, &dataType); // std::cout << name << "(" << theClass << ")\n"; if (status == NX_ERROR) return NX_ERROR; if (status == NX_OK) { if (!strncmp(theClass, "NX", 2)) { if (NXopengroup(inId, name, theClass) != NX_OK) return NX_ERROR; add_path(name); if (NXgetgroupID(inId, &link) != NX_OK) return NX_ERROR; if (!strcmp(current_path, link.targetPath)) { // Create a copy of the group if (NXmakegroup(outId, name, theClass) != NX_OK) return NX_ERROR; if (NXopengroup(outId, name, theClass) != NX_OK) return NX_ERROR; if (WriteAttributes(is_definition) != NX_OK) return NX_ERROR; if (WriteGroup(is_definition) != NX_OK) return NX_ERROR; remove_path(name); } else { remove_path(name); strcpy(links_to_make[links_count].from, current_path); strcpy(links_to_make[links_count].to, link.targetPath); strcpy(links_to_make[links_count].name, name); links_count++; if (NXclosegroup(inId) != NX_OK) return NX_ERROR; } } else if (!strncmp(theClass, "SDS", 3)) { add_path(name); if (NXopendata(inId, name) != NX_OK) return NX_ERROR; if (NXgetdataID(inId, &link) != NX_OK) return NX_ERROR; std::string data_label(name); if (!strcmp(current_path, link.targetPath)) { // Look for the bank name std::string path(current_path); std::string bank; size_t a = path.rfind('/'); if (a != std::string::npos && a > 0) { size_t b = path.rfind('/', a - 1); if (b != std::string::npos && (b < a) && (a - b - 1) > 0) { bank = path.substr(b + 1, a - b - 1); // std::cout << current_path << ":bank " << bank << "\n"; } } //--------------------------------------------------------------------------------------- if (data_label == "data" && (bank != "")) { if (this->WriteDataGroup(bank, is_definition) != NX_OK) return NX_ERROR; ; } //--------------------------------------------------------------------------------------- else if (data_label == "time_of_flight" && (bank != "")) { // Get the original info if (NXgetinfo(inId, &dataRank, dataDimensions, &dataType) != NX_OK) return NX_ERROR; // Get the X bins const MantidVec &X = inputWorkspace->readX(0); // 1 dimension, with that number of bin boundaries dataDimensions[0] = static_cast<int>(X.size()); // The output TOF axis will be whatever size in the workspace. boost::scoped_array<float> tof_data(new float[dataDimensions[0]]); // And fill it with the X data for (size_t i = 0; i < X.size(); i++) tof_data[i] = float(X[i]); if (NXcompmakedata(outId, name, dataType, dataRank, dataDimensions, NX_COMP_LZW, dataDimensions) != NX_OK) return NX_ERROR; if (NXopendata(outId, name) != NX_OK) return NX_ERROR; if (WriteAttributes(is_definition) != NX_OK) return NX_ERROR; if (NXputdata(outId, tof_data.get()) != NX_OK) return NX_ERROR; if (NXclosedata(outId) != NX_OK) return NX_ERROR; } //--------------------------------------------------------------------------------------- else { // Everything else gets copies if (NXgetinfo(inId, &dataRank, dataDimensions, &dataType) != NX_OK) return NX_ERROR; if (NXmalloc(&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK) return NX_ERROR; if (NXgetdata(inId, dataBuffer) != NX_OK) return NX_ERROR; if (NXcompmakedata(outId, name, dataType, dataRank, dataDimensions, NX_COMP_LZW, dataDimensions) != NX_OK) return NX_ERROR; if (NXopendata(outId, name) != NX_OK) return NX_ERROR; if (WriteAttributes(is_definition) != NX_OK) return NX_ERROR; if (NXputdata(outId, dataBuffer) != NX_OK) return NX_ERROR; if (NXfree(&dataBuffer) != NX_OK) return NX_ERROR; if (NXclosedata(outId) != NX_OK) return NX_ERROR; } remove_path(name); } else { // Make a link remove_path(name); strcpy(links_to_make[links_count].from, current_path); strcpy(links_to_make[links_count].to, link.targetPath); strcpy(links_to_make[links_count].name, name); links_count++; } if (NXclosedata(inId) != NX_OK) return NX_ERROR; } } else if (status == NX_EOD) { if (NXclosegroup(inId) != NX_OK) return NX_ERROR; if (NXclosegroup(outId) != NX_OK) return NX_ERROR; return NX_OK; } } while (status == NX_OK); return NX_OK; }
/** Write the group labeled "data" * * @param bank :: name of the bank * @param is_definition * @return error code */ int SaveToSNSHistogramNexus::WriteDataGroup(std::string bank, int is_definition) { int dataType, dataRank, dataDimensions[NX_MAXRANK]; NXname name; void *dataBuffer; if (NXgetinfo(inId, &dataRank, dataDimensions, &dataType) != NX_OK) return NX_ERROR; // Get the rectangular detector IComponent_const_sptr det_comp = inputWorkspace->getInstrument()->getComponentByName(std::string(bank)); RectangularDetector_const_sptr det = boost::dynamic_pointer_cast<const RectangularDetector>(det_comp); if (!det) { g_log.information() << "Detector '" + bank + "' not found, or it is not a rectangular detector!\n"; // Just copy that then. if (NXmalloc(&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK) return NX_ERROR; if (NXgetdata(inId, dataBuffer) != NX_OK) return NX_ERROR; if (NXcompmakedata(outId, name, dataType, dataRank, dataDimensions, NX_COMP_LZW, dataDimensions) != NX_OK) return NX_ERROR; if (NXopendata(outId, name) != NX_OK) return NX_ERROR; if (WriteAttributes(is_definition) != NX_OK) return NX_ERROR; if (NXputdata(outId, dataBuffer) != NX_OK) return NX_ERROR; if (NXfree(&dataBuffer) != NX_OK) return NX_ERROR; if (NXclosedata(outId) != NX_OK) return NX_ERROR; } else { // YES it is a rectangular detector. // --- Memory requirements ---- size_t memory_required = size_t(det->xpixels() * det->ypixels()) * size_t(inputWorkspace->blocksize()) * 2 * sizeof(float); Kernel::MemoryStats mem; mem.update(); size_t memory_available = mem.availMem() * 1024; std::cout << "Memory available: " << memory_available / 1024 << " kb. "; std::cout << "Memory required: " << memory_required / 1024 << " kb. "; // Give a 50% margin of error in allocating the memory memory_available = memory_available / 2; if (memory_available > static_cast<size_t>(5e9)) memory_available = static_cast<size_t>(5e9); if (memory_available < memory_required) { // Compute how large of a slab you can still use. int x_slab; x_slab = static_cast<int>( memory_available / (det->ypixels() * inputWorkspace->blocksize() * 2 * sizeof(float))); if (x_slab <= 0) x_slab = 1; // Look for a slab size that evenly divides the # of pixels. while (x_slab > 1) { if ((det->xpixels() % x_slab) == 0) break; x_slab--; } std::cout << "Saving in slabs of " << x_slab << " X pixels.\n"; if (this->WriteOutDataOrErrors(det, x_slab, "data", "data_errors", false, false, is_definition, bank) != NX_OK) return NX_ERROR; if (this->WriteOutDataOrErrors(det, x_slab, "errors", "", true, false, is_definition, bank) != NX_OK) return NX_ERROR; } else { std::cout << "Saving in one block.\n"; if (this->WriteOutDataOrErrors(det, det->xpixels(), "data", "data_errors", false, true, is_definition, bank) != NX_OK) return NX_ERROR; } } return NX_OK; }
/** Utility function to write out the * data or errors to a field in the group. * * @param det :: rectangular detector being written * @param x_pixel_slab :: size of a slab to write, in number of X pixels. *ignored if doBoth * @param field_name :: "data" field name * @param errors_field_name :: "errors" field name. * @param doErrors :: set true if you are writing the errors field this time. *field_name should be the "errors" field name * @param doBoth :: do both data and errors at once, no slabbing. * @param is_definition :: * @param bank :: name of the bank being written. * @return error code */ int SaveToSNSHistogramNexus::WriteOutDataOrErrors( Geometry::RectangularDetector_const_sptr det, int x_pixel_slab, const char *field_name, const char *errors_field_name, bool doErrors, bool doBoth, int is_definition, std::string bank) { int dataRank, dataDimensions[NX_MAXRANK]; int slabDimensions[NX_MAXRANK], slabStartIndices[NX_MAXRANK]; dataRank = 3; // Dimension 0 = the X pixels dataDimensions[0] = det->xpixels(); // Dimension 1 = the Y pixels dataDimensions[1] = det->ypixels(); // Dimension 2 = time of flight bins dataDimensions[2] = static_cast<int>(inputWorkspace->blocksize()); // ---- Determine slab size ----- // Number of pixels to collect in X before slabbing slabDimensions[0] = x_pixel_slab; slabDimensions[1] = dataDimensions[1]; slabDimensions[2] = dataDimensions[2]; if (doBoth) slabDimensions[0] = dataDimensions[0]; std::cout << "RectangularDetector " << det->getName() << " being copied. Dimensions : " << dataDimensions[0] << ", " << dataDimensions[1] << ", " << dataDimensions[2] << ".\n"; // ----- Open the data field ----------------------- if (m_compress) { if (NXcompmakedata(outId, field_name, NX_FLOAT32, dataRank, dataDimensions, NX_COMP_LZW, slabDimensions) != NX_OK) return NX_ERROR; } else { if (NXmakedata(outId, field_name, NX_FLOAT32, dataRank, dataDimensions) != NX_OK) return NX_ERROR; } if (NXopendata(outId, field_name) != NX_OK) return NX_ERROR; if (WriteAttributes(is_definition) != NX_OK) return NX_ERROR; if (!doErrors) { // Add an attribute called "errors" with value = the name of the data_errors // field. NXname attrName = "errors"; std::string attrBuffer = errors_field_name; if (NXputattr(outId, attrName, attrBuffer.c_str(), static_cast<int>(attrBuffer.size()), NX_CHAR) != NX_OK) return NX_ERROR; } // ---- Errors field ----- if (doBoth) { if (NXclosedata(outId) != NX_OK) return NX_ERROR; if (m_compress) { if (NXcompmakedata(outId, errors_field_name, NX_FLOAT32, dataRank, dataDimensions, NX_COMP_LZW, slabDimensions) != NX_OK) return NX_ERROR; } else { if (NXmakedata(outId, errors_field_name, NX_FLOAT32, dataRank, dataDimensions) != NX_OK) return NX_ERROR; } if (NXopendata(outId, errors_field_name) != NX_OK) return NX_ERROR; // NXlink * link = new NXlink; // link->linkType = 1; /* SDS data link */ // NXgetdataID(outId, link); // std::string targetPath = "/entry/" + bank + "/" + errors_field_name; // strcpy(link->targetPath, targetPath.c_str()); // if (NXmakelink(outId,link) != NX_OK) // g_log.debug() << "Error while making link to " << targetPath << // '\n'; if (WriteAttributes(is_definition) != NX_OK) return NX_ERROR; if (NXclosedata(outId) != NX_OK) return NX_ERROR; } double fillTime = 0; double saveTime = 0; // Make a buffer of floats will all the counts in that bank. auto data = new float[slabDimensions[0] * slabDimensions[1] * slabDimensions[2]]; // Only allocate an array for errors if it is needed float *errors = nullptr; if (doBoth) errors = new float[slabDimensions[0] * slabDimensions[1] * slabDimensions[2]]; for (int x = 0; x < det->xpixels(); x++) { // Which slab are we in? int slabnum = x / x_pixel_slab; // X index into the slabbed output array int slabx = x % x_pixel_slab; Timer tim1; int ypixels = static_cast<int>(det->ypixels()); PARALLEL_FOR1(inputWorkspace) for (int y = 0; y < ypixels; y++) { PARALLEL_START_INTERUPT_REGION // Get the workspace index for the detector ID at this spot size_t wi = 0; try { wi = map.find(det->getAtXY(x, y)->getID())->second; } catch (...) { std::cout << "Error finding " << bank << " x " << x << " y " << y << "\n"; } // Offset into array. size_t index = size_t(slabx) * size_t(dataDimensions[1]) * size_t(dataDimensions[2]) + size_t(y) * size_t(dataDimensions[2]); const MantidVec &Y = inputWorkspace->readY(wi); const MantidVec &E = inputWorkspace->readE(wi); for (size_t i = 0; i < Y.size(); ++i) { if (doErrors) { data[i + index] = static_cast<float>(E[i]); } else { data[i + index] = static_cast<float>(Y[i]); if (doBoth) { errors[i + index] = static_cast<float>(E[i]); } } } PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION fillTime += tim1.elapsed(); // Is this the last pixel in the slab? if (!doBoth && (x % x_pixel_slab == x_pixel_slab - 1)) { Timer tim2; // std::cout << "starting slab " << x << "\n"; // This is where the slab is in the greater data array. slabStartIndices[0] = slabnum * x_pixel_slab; slabStartIndices[1] = 0; slabStartIndices[2] = 0; if (NXputslab(outId, data, slabStartIndices, slabDimensions) != NX_OK) return NX_ERROR; saveTime += tim2.elapsed(); std::ostringstream mess; mess << det->getName() << ", " << field_name << " slab " << slabnum << " of " << det->xpixels() / x_pixel_slab; this->prog->reportIncrement(x_pixel_slab * det->ypixels(), mess.str()); } } // X loop if (doBoth) { bool returnerror = false; Timer tim2; if (NXopendata(outId, field_name) != NX_OK) returnerror = true; else if (NXputdata(outId, data) != NX_OK) returnerror = true; else if (NXclosedata(outId) != NX_OK) returnerror = true; else { this->prog->reportIncrement(det->xpixels() * det->ypixels() * 1, det->getName() + " data"); if (NXopendata(outId, errors_field_name) != NX_OK) returnerror = true; else if (NXputdata(outId, errors) != NX_OK) returnerror = true; else if (NXclosedata(outId) != NX_OK) returnerror = true; else { this->prog->reportIncrement(det->xpixels() * det->ypixels() * 1, det->getName() + " errors"); saveTime += tim2.elapsed(); } } if (returnerror) { delete[] data; delete[] errors; return NX_ERROR; } } else { if (NXclosedata(outId) != NX_OK) { delete[] data; return NX_ERROR; } } std::cout << "Filling out " << det->getName() << " took " << fillTime << " sec.\n"; std::cout << "Saving " << det->getName() << " took " << saveTime << " sec.\n"; delete[] data; if (doBoth) delete[] errors; return NX_OK; }
/** Performs the copying from the input to the output file, * while modifying the data and time_of_flight fields. */ int SaveToSNSHistogramNexus::copy_file(const char *inFile, int nx_read_access, const char *outFile, int nx_write_access) { int nx_is_definition = 0; links_count = 0; current_path[0] = '\0'; NXlink link; /* Open NeXus input file and NeXus output file */ if (NXopen(inFile, nx_read_access, &inId) != NX_OK) { printf("NX_ERROR: Can't open %s\n", inFile); return NX_ERROR; } if (NXopen(outFile, nx_write_access, &outId) != NX_OK) { printf("NX_ERROR: Can't open %s\n", outFile); return NX_ERROR; } /* Output global attributes */ if (WriteAttributes(nx_is_definition) != NX_OK) { return NX_ERROR; } /* Recursively cycle through the groups printing the contents */ if (WriteGroup(nx_is_definition) != NX_OK) { return NX_ERROR; } /* close input */ if (NXclose(&inId) != NX_OK) { return NX_ERROR; } // HDF5 only { /* now create any required links */ for (int i = 0; i < links_count; i++) { if (NXopenpath(outId, links_to_make[i].to) != NX_OK) return NX_ERROR; if (NXgetdataID(outId, &link) == NX_OK || NXgetgroupID(outId, &link) == NX_OK) { if (NXopenpath(outId, links_to_make[i].from) != NX_OK) return NX_ERROR; char *tstr = strrchr(links_to_make[i].to, '/'); if (!strcmp(links_to_make[i].name, tstr + 1)) { if (NXmakelink(outId, &link) != NX_OK) return NX_ERROR; } else { if (NXmakenamedlink(outId, links_to_make[i].name, &link) != NX_OK) return NX_ERROR; } } else { return NX_ERROR; } } } /* Close the input and output files */ if (NXclose(&outId) != NX_OK) { return NX_ERROR; } return NX_OK; }
int VmDirSendSearchEntry( PVDIR_OPERATION pOperation, PVDIR_ENTRY pSrEntry ) { int retVal = LDAP_SUCCESS; BerElementBuffer berbuf; BerElement * ber = (BerElement *) &berbuf; BOOLEAN bFreeBer = FALSE; ber_len_t iBlobSize = 0; BerValue lberBervEntryBlob = {0}; int nAttrs = 0; int nVals = 0; BOOLEAN attrMetaDataReqd = FALSE; SearchReq * sr = &(pOperation->request.searchReq); int i = 0; BOOLEAN nonTrivialAttrsInReplScope = FALSE; uint32_t iSearchReqSpecialChars = 0; PATTRIBUTE_META_DATA_NODE pAttrMetaData = NULL; int numAttrMetaData = 0; PVDIR_ATTRIBUTE pAttr = NULL; USN usnChanged = 0; PSTR pszLocalErrorMsg = NULL; if ( !pOperation || !pSrEntry ) { retVal = ERROR_INVALID_PARAMETER; BAIL_ON_VMDIR_ERROR(retVal); } pSrEntry->bSearchEntrySent = FALSE; // see if client request has "*" and/or "+" ("-" for userpassword internal to vmdir) // WEI TODO: when we have attribute level ACL check, this information will be useful // return result will depend on ACL each on each attribute client is asking before // generating a final result to send back SetSpecialReturnChar(&pOperation->request.searchReq, &iSearchReqSpecialChars); if ( pSrEntry->eId == DSE_ROOT_ENTRY_ID && pOperation->request.searchReq.attrs == NULL ) { // For ADSI, if no specific attributes requested of DSE ROOT search, // return ALL (include operational) attributes. iSearchReqSpecialChars |= LDAP_SEARCH_REQUEST_CHAR_OP; } // ACL check before processing/sending the current srEntry back retVal = VmDirSrvAccessCheck( pOperation, &pOperation->conn->AccessInfo, pSrEntry, VMDIR_RIGHT_DS_READ_PROP ); BAIL_ON_VMDIR_ERROR( retVal ); if ( pOperation->opType == VDIR_OPERATION_TYPE_INTERNAL ) { ; // no op in INTERNAL case } else { // If not replication, and showDeletedObjectsCtrl not present, => don't send back Deleted objects (tombstones). if (pOperation->syncReqCtrl == NULL && pOperation->showDeletedObjectsCtrl == NULL) { pAttr = VmDirEntryFindAttribute(ATTR_IS_DELETED, pSrEntry); if (pAttr) { if (VmDirStringCompareA((PSTR)pAttr->vals[0].lberbv.bv_val, VMDIR_IS_DELETED_TRUE_STR, FALSE) == 0) { goto cleanup; // Don't send this entry } } } // In case of replication request, skip certain updates if (pOperation->syncReqCtrl != NULL) { PVDIR_ATTRIBUTE pAttrUsnCreated = NULL; USN usnCreated = 0; USN limitUsn = 0; VMDIR_REPLICATION_AGREEMENT * replAgr = NULL; pAttr = VmDirEntryFindAttribute(ATTR_USN_CHANGED, pSrEntry); assert( pAttr != NULL ); usnChanged = VmDirStringToLA( pAttr->vals[0].lberbv.bv_val, NULL, 10); // Check if usnChanged is beyond successful replication update state limitUsn = VmDirdGetLimitLocalUsnToBeSupplied(); if (limitUsn != 0 && usnChanged >= limitUsn) { VMDIR_LOG_INFO(VMDIR_LOG_MASK_ALL, "SendSearchEntry: bug# 863244 RACE CONDITION encountered., " "usnChanged = %ld, limitLocalUsnToBeSupplied = %ld, skipping entry: %s", usnChanged, limitUsn, pSrEntry->dn.lberbv.bv_val ); goto cleanup; // Don't send this entry } // Check if usnChanged is beyond lowestPendingUncommittedUsn recorded at the beginning of replication search if (pOperation->lowestPendingUncommittedUsn != 0 && usnChanged >= pOperation->lowestPendingUncommittedUsn) { VMDIR_LOG_INFO( LDAP_DEBUG_REPL, "SendSearchEntry: usnChanged = %ld, lowestPendingUncommittedUsn = %ld, " "skipping entry: %s", usnChanged, pOperation->lowestPendingUncommittedUsn, pSrEntry->dn.lberbv.bv_val ); goto cleanup; // Don't send this entry } // Don't send (skip) modifications to my server object, and my RAs pAttrUsnCreated = VmDirEntryFindAttribute(ATTR_USN_CREATED, pSrEntry); assert( pAttrUsnCreated != NULL ); usnCreated = VmDirStringToLA( pAttrUsnCreated->vals[0].lberbv.bv_val, NULL, 10); // Only send back creation of certain objects, and not their modifications. // Check if consumer has already seen the creation. If yes, we are dealing with mods, which should be skipped // for my server object, and my RAs // Note: Skipping mods for RAs and Server Objects will cause inconsistencies with replicas. But these // two types only have local scope regarding functional effects. But if we are looking up / processing // information for these two types of objects on a replica, we need to watch out for potential // inconsistencies against the original source. if (pOperation->syncReqCtrl->value.syncReqCtrlVal.intLastLocalUsnProcessed > usnCreated) { if (strcmp(pSrEntry->dn.bvnorm_val, gVmdirServerGlobals.serverObjDN.bvnorm_val) == 0) { VMDIR_LOG_INFO( LDAP_DEBUG_REPL, "SendSearchEntry: Not sending modifications to my server object, DN: %s", gVmdirServerGlobals.serverObjDN.lberbv.bv_val ); goto cleanup; // Don't send this entry } for (replAgr = gVmdirReplAgrs; replAgr != NULL; replAgr = replAgr->next ) { if (strcmp(pSrEntry->dn.bvnorm_val, replAgr->dn.bvnorm_val) == 0) { VMDIR_LOG_INFO( LDAP_DEBUG_REPL, "SendSearchEntry: Not sending modifications to my RA object, DN: %s", replAgr->dn.bvnorm_val ); goto cleanup; // Don't send this entry } } } // do not replicate DSE Root entry, because it is a "local" entry. if (pSrEntry->eId == DSE_ROOT_ENTRY_ID) { VMDIR_LOG_INFO( LDAP_DEBUG_REPL, "SendSearchEntry: Not sending modifications to DSE Root entry, DN: %s", pSrEntry->dn.bvnorm_val ); goto cleanup; // Don't send this entry } } // Approximate calculation for the required ber size, because apart from lengths and strings, ber also includes // tags. if ( VmDirComputeEncodedEntrySize(pSrEntry, &nAttrs, &nVals, &iBlobSize) != 0 || VmDirAllocateMemory(iBlobSize, (PVOID*)&lberBervEntryBlob.bv_val) != 0 ) { retVal = LDAP_OPERATIONS_ERROR; BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, (pszLocalErrorMsg), "no memory"); } lberBervEntryBlob.bv_len = iBlobSize; ber_init2( ber, &lberBervEntryBlob, LBER_USE_DER ); // ber takes over lberBervEntryBlob.lberbv.bv_val ownership bFreeBer = TRUE; if ( ber_printf( ber, "{it{O{", pOperation->msgId, LDAP_RES_SEARCH_ENTRY, &pSrEntry->dn ) == -1) { VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "SendSearchEntry: ber_printf (to print msgId ...) failed" ); retVal = LDAP_OTHER; BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, (pszLocalErrorMsg), "Encoding msgId, RES_SEARCH_ENTRY, DN failed"); } // Determine if we need to send back the attribute metaData if ( pOperation->syncReqCtrl != NULL ) // Replication { attrMetaDataReqd = TRUE; } else // check if attrMetaData attribute has been requested explicitly. { if (sr->attrs != NULL) { for (i = 0; sr->attrs[i].lberbv.bv_val != NULL; i++) { if (VmDirStringCompareA( sr->attrs[i].lberbv.bv_val, ATTR_ATTR_META_DATA, FALSE) == 0) { attrMetaDataReqd = TRUE; break; } } } } if (attrMetaDataReqd) { if ((pOperation->pBEIF->pfnBEGetAllAttrsMetaData( pOperation->pBECtx, pSrEntry->eId, &pAttrMetaData, &numAttrMetaData )) != 0) { VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "SendSearchEntry: pfnBEGetAllAttrsMetaData failed for entryId: %ld", pSrEntry->eId); retVal = LDAP_OPERATIONS_ERROR; BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, (pszLocalErrorMsg), "pfnBEGetAllAttrsMetaData failed."); } // SJ-TBD: Following double for loop to be optimized // Copy attrMetaData to corresponding attributes for (i=0; i<numAttrMetaData; i++) { for ( pAttr = pSrEntry->attrs; pAttr != NULL; pAttr = pAttr->next) { if (pAttr->pATDesc->usAttrID == pAttrMetaData[i].attrID) { VmDirStringCpyA( pAttr->metaData, VMDIR_MAX_ATTR_META_DATA_LEN, pAttrMetaData[i].metaData ); pAttrMetaData[i].metaData[0] = '\0'; } } } } retVal = WriteAttributes( pOperation, pSrEntry, iSearchReqSpecialChars , ber, &pszLocalErrorMsg ); BAIL_ON_VMDIR_ERROR( retVal ); if (attrMetaDataReqd) { retVal = WriteMetaDataAttribute( pOperation, pSrEntry->attrs, numAttrMetaData, pAttrMetaData, ber, &nonTrivialAttrsInReplScope, &pszLocalErrorMsg ); BAIL_ON_VMDIR_ERROR( retVal ); } if (ber_printf( ber, "N}N}" ) == -1) { VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "ber_printf (to terminate the entry and the complete search result entry message ...) failed" ); retVal = LDAP_OTHER; BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, (pszLocalErrorMsg), "Encoding terminating the entry failed."); } if ( pOperation->syncReqCtrl != NULL ) // Replication, => write Sync State Control { retVal = WriteSyncStateControl( pOperation, pSrEntry->attrs, ber, &pszLocalErrorMsg ); BAIL_ON_VMDIR_ERROR( retVal ); } if (ber_printf( ber, "N}" ) == -1) { VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "ber_printf (to terminate the entry and the complete search result entry message ...) failed" );; retVal = LDAP_OTHER; BAIL_ON_VMDIR_ERROR_WITH_MSG( retVal, (pszLocalErrorMsg), "Encoding terminating the entry failed."); } if ((pOperation->syncReqCtrl == NULL) || (pOperation->syncReqCtrl != NULL && nonTrivialAttrsInReplScope )) { if (WriteBerOnSocket( pOperation->conn, ber ) != 0) { VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "SendSearchEntry: WriteBerOnSocket failed." ); retVal = LDAP_UNAVAILABLE; BAIL_ON_VMDIR_ERROR( retVal ); } pSrEntry->bSearchEntrySent = TRUE; sr->iNumEntrySent++; VMDIR_LOG_INFO( LDAP_DEBUG_REPL, "SendSearchEntry: Send entry: %s", pSrEntry->dn.lberbv.bv_val); } else { VMDIR_LOG_INFO( LDAP_DEBUG_REPL, "SendSearchEntry: NOT Sending entry: %s %p %d", pSrEntry->dn.lberbv.bv_val, pOperation->syncReqCtrl, nonTrivialAttrsInReplScope); } // record max local usnChanged in syncControlDone if (pOperation->syncReqCtrl != NULL) { if (usnChanged > pOperation->syncDoneCtrl->value.syncDoneCtrlVal.intLastLocalUsnProcessed) { pOperation->syncDoneCtrl->value.syncDoneCtrlVal.intLastLocalUsnProcessed = usnChanged; } } retVal = LDAP_SUCCESS; } cleanup: if (bFreeBer) { ber_free_buf( ber ); } VMDIR_SAFE_FREE_MEMORY( pAttrMetaData ); VMDIR_SAFE_FREE_MEMORY(pszLocalErrorMsg); return( retVal ); error: VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "SendSearchEntry failed DN=(%s), (%u)(%s)", (pSrEntry && pSrEntry->dn.lberbv.bv_val) ? pSrEntry->dn.lberbv.bv_val : "", retVal, VDIR_SAFE_STRING( pszLocalErrorMsg)); if ( !pOperation->ldapResult.pszErrMsg && pszLocalErrorMsg ) { pOperation->ldapResult.pszErrMsg = pszLocalErrorMsg; pszLocalErrorMsg = NULL; } goto cleanup; }
int _tmain(int argc, WCHAR* argv[]) { HRESULT hr; CComPtr<IStream> pFileStream; CComPtr<IXmlReader> pReader; XmlNodeType nodetype; if (argc != 2) { wprintf(L"Usage: XmlLiteChunkReader.exe name-of-input-file\n"); return 0; } //Open read-only input stream if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE))) { wprintf(L"Error creating file reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL))) { wprintf(L"Error creating xml reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->SetInput(pFileStream))) { wprintf(L"Error setting input for reader, error is %08.8lx", hr); return -1; } while (TRUE) { hr = pReader->Read(&nodetype); if (S_FALSE == hr) break; if (S_OK != hr) { wprintf(L"\nXmlLite Error: %08.8lx\n", hr); return -1; } switch (nodetype) { case XmlNodeType_Element: if (FAILED(hr = WriteAttributes(pReader))) { wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr); return -1; } break; case XmlNodeType_Text: case XmlNodeType_Whitespace: const UINT buffSize = 24; WCHAR buff[buffSize]; UINT charsRead; while (TRUE) { hr = pReader->ReadValueChunk(buff, buffSize - 1, &charsRead); if (S_FALSE == hr || 0 == charsRead) break; if (S_OK != hr) { wprintf(L"\nXmlLite Error: %08.8lx\n", hr); return -1; } buff[charsRead] = L'\0'; dotWhiteSpace(buff, charsRead); wprintf(L"element chunk size:%d >%s<\n", charsRead, buff); } break; } } wprintf(L"\n"); return 0; }
int _tmain(int argc, WCHAR* argv[]) { HRESULT hr; CComPtr<IStream> pFileStream; CComPtr<IXmlReader> pReader; CComPtr<IXmlReaderInput> pReaderInput; XmlNodeType nodetype; const WCHAR* pwszPrefix; const WCHAR* pwszLocalName; const WCHAR* pwszValue; UINT cwchPrefix; if (argc != 2) { wprintf(L"Usage: XmlLiteReadWithEncoding.exe name-of-input-file\n"); return 0; } // Open read-only input stream if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE))) { wprintf(L"Error creating file reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader),(void**) &pReader, NULL))) { wprintf(L"Error creating xml reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlReaderInputWithEncodingName(pFileStream, NULL, L"utf-16", FALSE, L"c:\temp", &pReaderInput))) { wprintf(L"Error creating xml reader with encoding code page, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->SetInput(pReaderInput))) { wprintf(L"Error setting input for reader, error is %08.8lx", hr); return -1; } while (TRUE) { hr = pReader->Read(&nodetype); if (S_FALSE == hr) break; if (S_OK != hr) { wprintf(L"\nXmlLite Error: %08.8lx\n", hr); return -1; } switch (nodetype) { case XmlNodeType_XmlDeclaration: wprintf(L"<?xml "); if (FAILED(hr = WriteAttributes(pReader))) { wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr); return -1; } wprintf(L"?>\r\n"); break; case XmlNodeType_Element: if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix))) { wprintf(L"Error, Method: GetPrefix, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) { wprintf(L"Error, Method: GetLocalName, error is %08.8lx", hr); return -1; } if (cwchPrefix > 0) wprintf(L"<%s:%s ", pwszPrefix, pwszLocalName); else wprintf(L"<%s ", pwszLocalName); if (FAILED(hr = WriteAttributes(pReader))) { wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr); return -1; } if (pReader->IsEmptyElement() ) wprintf(L"/>"); else wprintf(L">"); break; case XmlNodeType_EndElement: if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix))) { wprintf(L"Error, Method: GetPrefix, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) { wprintf(L"Error, Method: GetLocalName, error is %08.8lx", hr); return -1; } if (cwchPrefix > 0) wprintf(L"</%s:%s>", pwszPrefix, pwszLocalName); else wprintf(L"</%s>", pwszLocalName); break; case XmlNodeType_Text: case XmlNodeType_Whitespace: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error, Method: GetValue, error is %08.8lx", hr); return -1; } wprintf(L"%s", pwszValue); break; case XmlNodeType_CDATA: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error, Method: GetValue, error is %08.8lx", hr); return -1; } wprintf(L"<![CDATA[%s]]>", pwszValue); break; case XmlNodeType_ProcessingInstruction: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error, Method: GetValue, error is %08.8lx", hr); return -1; } wprintf(L"<?%s?>", pwszValue); break; case XmlNodeType_Comment: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error, Method: GetValue, error is %08.8lx", hr); return -1; } wprintf(L"<!--%s-->", pwszValue); break; case XmlNodeType_DocumentType: wprintf(L"<!-- DOCTYPE is not printed -->\r\n"); break; } } wprintf(L"\n"); return 0; }
int _tmain(int argc, WCHAR* argv[]) { HRESULT hr; CComPtr<IStream> pFileStream; CComPtr<IXmlReader> pReader; XmlNodeType nodeType; const WCHAR* pwszPrefix; const WCHAR* pwszLocalName; const WCHAR* pwszValue; UINT cwchPrefix; if (argc != 2) { wprintf(L"Usage: XmlLiteReader.exe name-of-input-file\n"); return 0; } //Open read-only input stream if (FAILED(hr = SHCreateStreamOnFile(argv[1], STGM_READ, &pFileStream))) { wprintf(L"Error creating file reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL))) { wprintf(L"Error creating xml reader, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit))) { wprintf(L"Error setting XmlReaderProperty_DtdProcessing, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->SetInput(pFileStream))) { wprintf(L"Error setting input for reader, error is %08.8lx", hr); return -1; } //read until there are no more nodes while (S_OK == (hr = pReader->Read(&nodeType))) { switch (nodeType) { case XmlNodeType_XmlDeclaration: wprintf(L"XmlDeclaration\n"); if (FAILED(hr = WriteAttributes(pReader))) { wprintf(L"Error writing attributes, error is %08.8lx", hr); return -1; } break; case XmlNodeType_Element: if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix))) { wprintf(L"Error getting prefix, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) { wprintf(L"Error getting local name, error is %08.8lx", hr); return -1; } if (cwchPrefix > 0) wprintf(L"Element: %s:%s\n", pwszPrefix, pwszLocalName); else wprintf(L"Element: %s\n", pwszLocalName); if (FAILED(hr = WriteAttributes(pReader))) { wprintf(L"Error writing attributes, error is %08.8lx", hr); return -1; } if (pReader->IsEmptyElement() ) wprintf(L" (empty)"); break; case XmlNodeType_EndElement: if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix))) { wprintf(L"Error getting prefix, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) { wprintf(L"Error getting local name, error is %08.8lx", hr); return -1; } if (cwchPrefix > 0) wprintf(L"End Element: %s:%s\n", pwszPrefix, pwszLocalName); else wprintf(L"End Element: %s\n", pwszLocalName); break; case XmlNodeType_Text: case XmlNodeType_Whitespace: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error getting value, error is %08.8lx", hr); return -1; } wprintf(L"Text: >%s<\n", pwszValue); break; case XmlNodeType_CDATA: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error getting value, error is %08.8lx", hr); return -1; } wprintf(L"CDATA: %s\n", pwszValue); break; case XmlNodeType_ProcessingInstruction: if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) { wprintf(L"Error getting name, error is %08.8lx", hr); return -1; } if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error getting value, error is %08.8lx", hr); return -1; } wprintf(L"Processing Instruction name:%S value:%S\n", pwszLocalName, pwszValue); break; case XmlNodeType_Comment: if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) { wprintf(L"Error getting value, error is %08.8lx", hr); return -1; } wprintf(L"Comment: %s\n", pwszValue); break; case XmlNodeType_DocumentType: wprintf(L"DOCTYPE is not printed\n"); break; } } return 0; }