From 0ba286c359b5b8ab7b1e4df9c92b7de835a6a0ac Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Sun, 15 Mar 2015 16:38:30 -0700 Subject: [PATCH] s3 error handling package --- Godeps/Godeps.json | 9 +- .../src/github.com/clbanning/x2j/LICENSE | 28 + .../src/github.com/clbanning/x2j/README | 167 +++++ .../clbanning/x2j/atomFeedString.xml | 54 ++ .../github.com/clbanning/x2j/examples/README | 196 ++++++ .../clbanning/x2j/examples/books.go | 56 ++ .../clbanning/x2j/examples/getmetrics.go | 156 +++++ .../clbanning/x2j/examples/gonuts1.go | 60 ++ .../clbanning/x2j/examples/gonuts2.go | 200 ++++++ .../clbanning/x2j/examples/gonuts3.go | 49 ++ .../clbanning/x2j/examples/gonuts4.go | 40 ++ .../github.com/clbanning/x2j/goofy_test.go | 56 ++ .../clbanning/x2j/pathTestString.xml | 20 + .../src/github.com/clbanning/x2j/reader2j.go | 105 +++ .../github.com/clbanning/x2j/reader2j_test.go | 85 +++ .../clbanning/x2j/songTextString.xml | 29 + .../src/github.com/clbanning/x2j/x2j.go | 660 ++++++++++++++++++ .../src/github.com/clbanning/x2j/x2j_bulk.go | 127 ++++ .../github.com/clbanning/x2j/x2j_findPath.go | 141 ++++ .../src/github.com/clbanning/x2j/x2j_test.go | 419 +++++++++++ .../src/github.com/clbanning/x2j/x2j_test.xml | 29 + .../github.com/clbanning/x2j/x2j_valuesAt.go | 88 +++ .../clbanning/x2j/x2j_valuesFrom.go | 125 ++++ .../github.com/clbanning/x2j/x2jat_test.go | 164 +++++ .../clbanning/x2j/x2jfindPath_test.go | 48 ++ .../github.com/clbanning/x2j/x2jpath_test.go | 169 +++++ .../clbanning/x2j/x2junmarshal_test.go | 57 ++ .../src/github.com/clbanning/x2j/x2m_bulk.go | 201 ++++++ .../src/github.com/clbanning/x2j/x2m_bulk.xml | 67 ++ Makefile | 9 + pkg/s3/bucket.go | 51 +- pkg/s3/error.go | 94 --- pkg/s3/object.go | 41 +- pkg/s3errors/errors.go | 72 ++ 34 files changed, 3721 insertions(+), 151 deletions(-) create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/LICENSE create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/README create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/atomFeedString.xml create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/README create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/books.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/getmetrics.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts1.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts2.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts3.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts4.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/goofy_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/pathTestString.xml create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/reader2j.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/reader2j_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/songTextString.xml create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j_bulk.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j_findPath.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.xml create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesAt.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesFrom.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2jat_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2jfindPath_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2jpath_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2junmarshal_test.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.go create mode 100644 Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.xml delete mode 100644 pkg/s3/error.go create mode 100644 pkg/s3errors/errors.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 3d944039..ef53802b 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,11 +1,18 @@ { "ImportPath": "github.com/minio-io/mc", - "GoVersion": "go1.4", + "GoVersion": "go1.4.1", + "Packages": [ + "./..." + ], "Deps": [ { "ImportPath": "github.com/cheggaaa/pb", "Rev": "0464652af750701d218b6dd035f0217e407caf2d" }, + { + "ImportPath": "github.com/clbanning/x2j", + "Rev": "0e45c2228aab9921ef50cc7d0bf7186082cc51a4" + }, { "ImportPath": "github.com/codegangsta/cli", "Comment": "1.2.0-87-g8ce64f1", diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/LICENSE b/Godeps/_workspace/src/github.com/clbanning/x2j/LICENSE new file mode 100644 index 00000000..38c587bb --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2012-2014 Charles Banning . +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/README b/Godeps/_workspace/src/github.com/clbanning/x2j/README new file mode 100644 index 00000000..3bf43112 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/README @@ -0,0 +1,167 @@ +x2j.go - Unmarshal arbitrary XML docs to map[string]interface{} or JSON and extract values (using wildcards, if necessary). + +NOTICE: + +AS OF 3-FEB-2014 THE x2j PACKAGE IS NO LONGER SUPPORTED. + +IT HAS BEEN DEPRECATED IN FAVOR OF mxj/x2j: https://github.com/clbanning/mxj/tree/master/x2j. + +ANNOUNCEMENTS + +23 January 2014: + +Extract path(s) for a tag/key value from an anonymous XML or map[string]interface{} value. Result can be used with ValuesForKeyPath() / ValuesAtKeyPath(). Similar to ValuesFor...() functions but PathsFor...() and PathFor...Shortest() expose the tree navigation information. + +20 December 2013: + +Non-UTF8 character sets supported via the X2jCharsetReader variable. + +12 December 2013: + +For symmetry, the package j2x has functions that marshal JSON strings and +map[string]interface{} values to XML encoded strings: http://godoc.org/github.com/clbanning/j2x. + +Also, ToTree(), ToMap(), ToJson(), ToJsonIndent(), ReaderValuesFromTagPath() and ReaderValuesForTag() use io.Reader instead of string or []byte. + +If you want to process a stream of XML messages check out XmlMsgsFromReader(). + +MOTIVATION + +I make extensive use of JSON for messaging and typically unmarshal the messages into +map[string]interface{} variables. This is easily done using json.Unmarshal from the +standard Go libraries. Unfortunately, many legacy solutions use structured +XML messages; in those environments the applications would have to be refitted to +interoperate with my components. + +The better solution is to just provide an alternative HTTP handler that receives +XML doc messages and parses it into a map[string]interface{} variable and then reuse +all the JSON-based code. The Go xml.Unmarshal() function does not provide the same +option of unmarshaling XML messages into map[string]interface{} variables. So I wrote +a couple of small functions to fill this gap. + +Of course, once the XML doc was unmarshal'd into a map[string]interface{} variable it +was just a matter of calling json.Marshal() to provide it as a JSON string. Hence 'x2j' +rather than just 'x2m'. + +USAGE + +The package is fairly well self-documented. (http://godoc.org/github.com/clbanning/x2j) +The one really useful function is: + + - Unmarshal(doc []byte, v interface{}) error + where v is a pointer to a variable of type 'map[string]interface{}', 'string', or + any other type supported by xml.Unmarshal(). + +To retrieve a value for specific tag use: + + - DocValue(doc, path string, attrs ...string) (interface{},error) + - MapValue(m map[string]interface{}, path string, attr map[string]interface{}, recast ...bool) (interface{}, error) + +The 'path' argument is a period-separated tag hierarchy - also known as dot-notation. +It is the program's responsibility to cast the returned value to the proper type; possible +types are the normal JSON unmarshaling types: string, float64, bool, []interface, map[string]interface{}. + +To retrieve all values associated with a tag occurring anywhere in the XML document use: + + - ValuesForTag(doc, tag string) ([]interface{}, error) + - ValuesForKey(m map[string]interface{}, key string) []interface{} + + Demos: http://play.golang.org/p/m8zP-cpk0O + http://play.golang.org/p/cIteTS1iSg + http://play.golang.org/p/vd8pMiI21b + +Returned values should be one of map[string]interface, []interface{}, or string. + +All the values assocated with a tag-path that may include one or more wildcard characters - +'*' - can also be retrieved using: + + - ValuesFromTagPath(doc, path string, getAttrs ...bool) ([]interface{}, error) + - ValuesFromKeyPath(map[string]interface{}, path string, getAttrs ...bool) []interface{} + + Demos: http://play.golang.org/p/kUQnZ8VuhS + http://play.golang.org/p/l1aMHYtz7G + +NOTE: care should be taken when using "*" at the end of a path - i.e., "books.book.*". See +the x2jpath_test.go case on how the wildcard returns all key values and collapses list values; +the same message structure can load a []interface{} or a map[string]interface{} (or an interface{}) +value for a tag. + +See the test cases in "x2jpath_test.go" and programs in "example" subdirectory for more. + +XML PARSING CONVENTIONS + + - Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-', + to the attribute label. + - If the element is a simple element and has attributes, the element value + is given the key '#text' for its map[string]interface{} representation. (See + the 'atomFeedString.xml' test data, below.) + +BULK PROCESSING OF MESSAGE FILES + +Sometime messages may be logged into files for transmission via FTP (e.g.) and subsequent +processing. You can use the bulk XML message processor to convert files of XML messages into +map[string]interface{} values with custom processing and error handler functions. See +the notes and test code for: + + - XmlMsgsFromFile(fname string, phandler func(map[string]interface{}) bool, ehandler func(error) bool,recast ...bool) error + +IMPLEMENTATION NOTES + +Nothing fancy here, just brute force. + + - Use xml.Decoder to parse the XML doc and build a tree. + - Walk the tree and load values into a map[string]interface{} variable, 'm', as + appropriate. + - Use json.Marshaler to convert 'm' to JSON. + +As for testing: + + - Copy an XML doc into 'x2j_test.xml'. + - Run "go test" and you'll get a full dump. + ("pathTestString.xml" and "atomFeedString.xml" are test data from "read_test.go" + in the encoding/xml directory of the standard package library.) + +USES + + - putting a XML API on our message hub middleware (http://jsonhub.net) + - loading XML data into NoSQL database, such as, mongoDB + +PERFORMANCE IMPROVEMENTS WITH GO 1.1 and 1.2 + +Upgrading to Go 1.1 environment results in performance improvements for XML and JSON +unmarshalling, in general. The x2j package gets an average performance boost of 40%. + + ----- Go 1.0.2 ----- ----------- Go 1.1 ----------- + iterations ns/op iterations ns/op % improved +Benchmark_UseXml-4 100000 18776 200000 10377 45% +Benchmark_UseX2j-4 50000 55323 50000 33958 39% +Benchmark_UseJson-4 1000000 2257 1000000 1484 34% +Benchmark_UseJsonToMap-4 1000000 2531 1000000 1566 38% +BenchmarkBig_UseXml-4 100000 28918 100000 15876 45% +BenchmarkBig_UseX2j-4 20000 86338 50000 52661 39% +BenchmarkBig_UseJson-4 500000 4448 1000000 2664 40% +BenchmarkBig_UseJsonToMap-4 200000 9076 500000 5753 37% +BenchmarkBig3_UseXml-4 50000 42224 100000 24686 42% +BenchmarkBig3_UseX2j-4 10000 147407 20000 84332 43% +BenchmarkBig3_UseJson-4 500000 5921 500000 3930 34% +BenchmarkBig3_UseJsonToMap-4 200000 13037 200000 8670 33% + +The x2j package gets an additional 15-20% performance boost going to Go 1.2. + + ------ Go 1.1 ------ ----------- Go 1.2 ----------- + iterations ns/op iterations ns/op % improved +Benchmark_UseXml-4 200000 10377 200000 11031 -6% +Benchmark_UseX2j-4 50000 33958 100000 29188 14% +Benchmark_UseJson-4 1000000 1484 1000000 1347 9% +Benchmark_UseJsonToMap-4 1000000 1566 1000000 1434 8% +BenchmarkBig_UseXml-4 100000 15876 100000 16585 -4% +BenchmarkBig_UseX2j-4 50000 52661 50000 43452 17% +BenchmarkBig_UseJson-4 1000000 2664 1000000 2523 5% +BenchmarkBig_UseJsonToMap-4 500000 5753 500000 4992 13% +BenchmarkBig3_UseXml-4 100000 24686 100000 24348 1% +BenchmarkBig3_UseX2j-4 20000 84332 50000 66736 21% +BenchmarkBig3_UseJson-4 500000 3930 500000 3733 5% +BenchmarkBig3_UseJsonToMap-4 200000 8670 200000 7810 10% + + + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/atomFeedString.xml b/Godeps/_workspace/src/github.com/clbanning/x2j/atomFeedString.xml new file mode 100644 index 00000000..474575a4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/atomFeedString.xml @@ -0,0 +1,54 @@ + +Code Review - My issueshttp://codereview.appspot.com/rietveld<>rietveld: an attempt at pubsubhubbub +2009-10-04T01:35:58+00:00email-address-removedurn:md5:134d9179c41f806be79b3a5f7877d19a + An attempt at adding pubsubhubbub support to Rietveld. +http://code.google.com/p/pubsubhubbub +http://code.google.com/p/rietveld/issues/detail?id=155 + +The server side of the protocol is trivial: + 1. add a &lt;link rel=&quot;hub&quot; href=&quot;hub-server&quot;&gt; tag to all + feeds that will be pubsubhubbubbed. + 2. every time one of those feeds changes, tell the hub + with a simple POST request. + +I have tested this by adding debug prints to a local hub +server and checking that the server got the right publish +requests. + +I can&#39;t quite get the server to work, but I think the bug +is not in my code. I think that the server expects to be +able to grab the feed and see the feed&#39;s actual URL in +the link rel=&quot;self&quot;, but the default value for that drops +the :port from the URL, and I cannot for the life of me +figure out how to get the Atom generator deep inside +django not to do that, or even where it is doing that, +or even what code is running to generate the Atom feed. +(I thought I knew but I added some assert False statements +and it kept running!) + +Ignoring that particular problem, I would appreciate +feedback on the right way to get the two values at +the top of feeds.py marked NOTE(rsc). + + +rietveld: correct tab handling +2009-10-03T23:02:17+00:00email-address-removedurn:md5:0a2a4f19bb815101f0ba2904aed7c35a + This fixes the buggy tab rendering that can be seen at +http://codereview.appspot.com/116075/diff/1/2 + +The fundamental problem was that the tab code was +not being told what column the text began in, so it +didn&#39;t know where to put the tab stops. Another problem +was that some of the code assumed that string byte +offsets were the same as column offsets, which is only +true if there are no tabs. + +In the process of fixing this, I cleaned up the arguments +to Fold and ExpandTabs and renamed them Break and +_ExpandTabs so that I could be sure that I found all the +call sites. I also wanted to verify that ExpandTabs was +not being used from outside intra_region_diff.py. + + + ` + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/README b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/README new file mode 100644 index 00000000..bc5435ad --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/README @@ -0,0 +1,196 @@ +Examples of using ValuesFromTagPath(). + +A number of interesting examples have shown up in the gonuts discussion group +that could be handled - after a fashion - using the ValuesFromTagPath() function. + +gonuts1.go - + +Here we see that the message stream has a problem with multiple tag spellings, +though the message structure remains constant. In this example we 'anonymize' +the tag with the variant spellings. + mm := x2j.ValuesFromTagPath(doc,"data.*) + where '*' is any possible spelling - "netid" or "idnet" + and the result is a list with 1 member of map[string]interface{} type. + +Once we've retrieved the map, we can parse it using the known keys - "disable", +"text1" and "word1". + + +gonuts2.go - + +This is an interesting case where there was a need to handle messages with lists +of "ClaimStatusCodeRecord" entries as well as messages with NONE. (Here we see +some of the vagaries of dealing with mixed messages that are verging on becoming +anonymous.) + + strXml - the message with two ClaimStatusCodeRecord entries + strXmlA - the message with one ClaimStatusCodeRecord entry + strXml2 - the message with NO ClaimStatusCodeRecord entries + +ValuesFromTagPath() options: + + path == "Envelope.Body.GetClaimStatusCodesResponse.GetClaimStatusCodesResult.ClaimStatusCodeRecord" + for doc == strXml: + returns: a list - []interface{} - with two values of map[string]interface{} type + for doc == strXmlA: + returns: a list - []interface{} - with one map[string]interface{} type + for doc == strXml2: + returns 'nil' - no values + + path == "*.*.*.*.*" + for doc == strXml: + returns: a list - []interface{} - with two values of map[string]interface{} type + + path == "*.*.*.*.*.Description + for doc == strXml: + returns: a list - []interface{} - with two values of string type, the individual + values from parsing the two map[string]interface{} values where key=="Description" + + path == "*.*.*.*.*.*" + for doc == strXml: + returns: a list - []interface{} - with six values of string type, the individual + values from parsing all keys in the two map[string]interface{} values + +IN GENERAL + +Think of the wildcard character "*" as anonymizing the tag in the position of the path where +it occurs. If we have a message that looks like this. + +var doc = ` + + + William H. Gaddis + The Recognitions + One of the great seminal American novels of the 20th century. + + + Austin Tappan Wright + Islandia + An example of earlier 20th century American utopian fiction. + + + John Hawkes + The Beetle Leg + A lyrical novel about the construction of Ft. Peck Dam in Montana. + + + T.E. Porter + King's Day + A magical novella. + + +` + +path == "books" + return a list with one members, map[string]interface{}, with a single key 'book' and + whose value is a list. + +path == "books.book" + return a list of four members, map[string]interface{} - each map[string]interface{} is + a 'book' entry + +path == "books.*" + return a list of four members, map[string]interface{} - each map[string]interface{} is + a 'book' entry [the same as "books.book"] + +path == "books.*.title" + return a list of four members, interface{} - interface{} is the title of a book in + the list of 'books.book' [the same as "books.book.title"] + +path == "books.*.*" + return a list of twelve members, interface{} - interface{} is the title, author, or review + of a book in the list of 'books.book' [the same as "books.book.*"] + + +NOTES. + +Attributes. + +By default interface{} values do not include attributes; though they do show up in maps. +So, if you're looking for a particular values based on attribute values, retrieve the entries +as map[string]interface{} values and parse them based on attribute key values. (Attribute +keys are have '-' prepended to their name.) + +The gonuts3.go example illustrates extracting all attribute values in a doc associated with a +specific tag value. + +Lists of entries vs. single entries. + +The gonuts2.go example highlights some of the ambiguity that must be managed when dealing with +XML messages anonymously using the x2j package. + - for strXml "ClaimStatusCodeRecord" has a []interface{} value + - for strXmlA "ClaimStatusCodeRecord" has a map[string]interface{} value + +ValuesFromTagPath() tries to normalize this by returning the []interface{} value as separate +list members rather than the absolute value in the map representation. So the same logic +could be used to parse the entries no matter how many values are returned - other than 'nil'. +"...ClaimStatusCodeRecord.*" will return all [non-attribute] values without their tags, so it's +a little hard to know what you've got. It is recommended that the wildcard - "*" - not be +used at the end of a path for that very reason. + + +EAT YOUR OWN DOG FOOD ... + +I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an +application that had 355,100 lines of code in 211 packages into CSV data sets. The report +included application-, package-, class- and method-level metrics reported in an element, +"Value", with varying attributes. + + + + + +In addition, the metrics were reported with two different "Metric" compound elements: + + + + + ... + + + ... + + + + ... + + +Using the x2j package seemed a more straightforward approach than using Go vernacular +and the standard xml package. I wrote the program getmetrics.go to do this. + +Note that the call to ValuesFromKeyPath() + + metricVals := x2j.ValuesFromKeyPath(m, "Metrics.Metric", true) + +requests that attributes be returned by including 'true' as the third argument. After that +everything is pretty straight forward. The metrics for processing over 120,000 "Value" +elements (Intel Core i7, 8 GB, OS X 10.8, Solid State drive) are as follows. + +2013-07-24 06:59:54.97486625 -0500 CDT ... File Opened: static_analysis.xml +2013-07-24 06:59:54.982837648 -0500 CDT ... File Read - size: 14863568 +2013-07-24 06:59:58.656195538 -0500 CDT ... XML Unmarshaled - len: 1 +2013-07-24 06:59:58.65622715 -0500 CDT ... ValuesFromKeyPath - len: 23 +2013-07-24 06:59:58.657157356 -0500 CDT id: VG desc: McCabe Cyclomatic Complexity len(Values): 24562 +2013-07-24 06:59:58.996143039 -0500 CDT id: PAR desc: Number of Parameters len(Values): 24562 +2013-07-24 06:59:59.333407792 -0500 CDT id: NBD desc: Nested Block Depth len(Values): 24562 +2013-07-24 06:59:59.672552235 -0500 CDT id: CA desc: Afferent Coupling len(Values): 211 +2013-07-24 06:59:59.675736869 -0500 CDT id: CE desc: Efferent Coupling len(Values): 211 +2013-07-24 06:59:59.678760375 -0500 CDT id: RMI desc: Instability len(Values): 211 +2013-07-24 06:59:59.682004251 -0500 CDT id: RMA desc: Abstractness len(Values): 211 +2013-07-24 06:59:59.684985741 -0500 CDT id: RMD desc: Normalized Distance len(Values): 211 +2013-07-24 06:59:59.688191982 -0500 CDT id: DIT desc: Depth of Inheritance Tree len(Values): 2074 +2013-07-24 06:59:59.717945046 -0500 CDT id: WMC desc: Weighted methods per Class len(Values): 2074 +2013-07-24 06:59:59.747678025 -0500 CDT id: NSC desc: Number of Children len(Values): 2074 +2013-07-24 06:59:59.778378946 -0500 CDT id: NORM desc: Number of Overridden Methods len(Values): 2074 +2013-07-24 06:59:59.80913273 -0500 CDT id: LCOM desc: Lack of Cohesion of Methods len(Values): 2074 +2013-07-24 06:59:59.838893489 -0500 CDT id: NOF desc: Number of Attributes len(Values): 2074 +2013-07-24 06:59:59.868573348 -0500 CDT id: NSF desc: Number of Static Attributes len(Values): 2074 +2013-07-24 06:59:59.89918479 -0500 CDT id: NOM desc: Number of Methods len(Values): 2074 +2013-07-24 06:59:59.92889002 -0500 CDT id: NSM desc: Number of Static Methods len(Values): 2074 +2013-07-24 06:59:59.959311932 -0500 CDT id: SIX desc: Specialization Index len(Values): 2074 +2013-07-24 06:59:59.988859435 -0500 CDT id: NOC desc: Number of Classes len(Values): 211 +2013-07-24 06:59:59.992076575 -0500 CDT id: NOI desc: Number of Interfaces len(Values): 211 +2013-07-24 06:59:59.995418021 -0500 CDT id: NOP desc: Number of Packages len(Value): 1 +2013-07-24 06:59:59.995971956 -0500 CDT id: TLOC desc: Total Lines of Code len(Value): 1 +2013-07-24 06:59:59.996635113 -0500 CDT id: MLOC desc: Method Lines of Code len(Values): 24562 + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/books.go b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/books.go new file mode 100644 index 00000000..0dae6acf --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/books.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "github.com/clbanning/x2j" +) + +var doc = ` + + + William H. Gaddis + The Recognitions + One of the great seminal American novels of the 20th century. + + + Austin Tappan Wright + Islandia + An example of earlier 20th century American utopian fiction. + + + John Hawkes + The Beetle Leg + A lyrical novel about the construction of Ft. Peck Dam in Montana. + + + T.E. Porter + King's Day + A magical novella. + + +` + +func main() { + fmt.Println(doc) + + v,_ := x2j.ValuesFromTagPath(doc,"books") + fmt.Println("path: books; len(v):",len(v)) + fmt.Printf("%+v\n\n",v) + + v,_ = x2j.ValuesFromTagPath(doc,"books.book") + fmt.Println("path: books.book; len(v):",len(v)) + fmt.Printf("%+v\n\n",v) + + v,_ = x2j.ValuesFromTagPath(doc,"books.*") + fmt.Println("path: books.*; len(v):",len(v)) + fmt.Printf("%+v\n\n",v) + + v,_ = x2j.ValuesFromTagPath(doc,"books.*.title") + fmt.Println("path: books.*.title len(v):",len(v)) + fmt.Printf("%+v\n\n",v) + + v,_ = x2j.ValuesFromTagPath(doc,"books.*.*") + fmt.Println("path: books.*.*; len(v):",len(v)) + fmt.Printf("%+v\n\n",v) +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/getmetrics.go b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/getmetrics.go new file mode 100644 index 00000000..f1efd607 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/getmetrics.go @@ -0,0 +1,156 @@ +// getmetrics.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric + +/* +I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an +application that had 355,100 lines of code in 211 packages into CSV data sets. The report +included application-, package-, class- and method-level metrics reported in an element, +"Value", with varying attributes. + + + + + +In addition, the metrics were reported with two different "Metric" compound elements: + + + + + ... + + + ... + + + + ... + +*/ + +package main + +import ( + "flag" + "fmt" + "github.com/clbanning/x2j" + "os" + "time" +) + +func main() { + var file string + flag.StringVar(&file, "file", "", "file to process") + flag.Parse() + + fh, fherr := os.Open(file) + if fherr != nil { + fmt.Println("fherr:", fherr.Error()) + return + } + defer fh.Close() + fs, _ := fh.Stat() + fmt.Println(time.Now().String(), "... File Opened:", file) + + b := make([]byte, fs.Size()) + n, frerr := fh.Read(b) + if frerr != nil { + fmt.Println("frerr:", frerr.Error()) + return + } + if int64(n) != fs.Size() { + fmt.Println("n:", n, "fs.Size():", fs.Size()) + return + } + fmt.Println(time.Now().String(), "... File Read - size:", fs.Size()) + + m := make(map[string]interface{}, 0) + merr := x2j.Unmarshal(b, &m) + if merr != nil { + fmt.Println("merr:", merr.Error()) + return + } + fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m)) + + metricVals := x2j.ValuesFromKeyPath(m, "Metrics.Metric", true) + fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals)) + + for _, v := range metricVals { + aMetricVal := v.(map[string]interface{}) + + // create file to hold csv data sets + id := aMetricVal["-id"].(string) + desc := aMetricVal["-description"].(string) + mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) + if mferr != nil { + fmt.Println("mferr:", mferr.Error()) + return + } + + fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc) + mf.WriteString(id + "," + desc + "\n") + + // rescan looking for keys with data: Values or Value + for key, val := range aMetricVal { + switch key { + case "Values": + // extract the list of "Value" from map + values := val.(map[string]interface{})["Value"].([]interface{}) + fmt.Println(" len(Values):", len(values)) + + // first line in file is the metric label values (keys) + var gotKeys bool + for _, vval := range values { + valueEntry := vval.(map[string]interface{}) + + // no guarantee that range on map will follow any sequence + lv := len(valueEntry) + type ev [2]string + list := make([]ev, lv) + var i int + for k, v := range valueEntry { + list[i][0] = k + list[i][1] = v.(string) + i++ + } + + // extract keys as column header on first pass + if !gotKeys { + // print out the keys + var gotFirstKey bool + // for kk, _ := range valueEntry { + for i := 0 ; i < lv ; i++ { + if gotFirstKey { + mf.WriteString(",") + } else { + gotFirstKey = true + } + // strip prepended hyphen + mf.WriteString((list[i][0])[1:]) + } + mf.WriteString("\n") + gotKeys = true + } + + // print out values + var gotFirstVal bool + // for _, vv := range valueEntry { + for i := 0; i < lv; i++ { + if gotFirstVal { + mf.WriteString(",") + } else { + gotFirstVal = true + } + mf.WriteString(list[i][1]) + } + + // terminate row of data + mf.WriteString("\n") + } + case "Value": + vv := val.(map[string]interface{}) + fmt.Println(" len(Value):", len(vv)) + mf.WriteString("value\n" + vv["-value"].(string) + "\n") + } + } + mf.Close() + } +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts1.go b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts1.go new file mode 100644 index 00000000..e131aaa2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts1.go @@ -0,0 +1,60 @@ +// https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ +// http://play.golang.org/p/BFFDxphKYK + +package main + +import ( + "fmt" + "github.com/clbanning/x2j" +) + +// demo how to compensate for irregular tag labels in data +// "netid" vs. "idnet" +var doc1 = ` + + + + no + default:text + default:word + + +` +var doc2 = ` + + + + yes + default:text + default:word + + +` + +func main() { + var docs = []string{doc1,doc2} + + for n,doc := range docs { + fmt.Println("\nTestValuesFromTagPath2(), iteration:",n,"\n",doc) + + m,_ := x2j.DocToMap(doc) + fmt.Println("map:",x2j.WriteMap(m)) + + v,_ := x2j.ValuesFromTagPath(doc,"data.*") + fmt.Println("\npath == data.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val) + } + mm := v[0] + for key,val := range mm.(map[string]interface{}) { + fmt.Println(key,":",val) + } + + v,_ = x2j.ValuesFromTagPath(doc,"data.*.*") + fmt.Println("\npath == data.*.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val) + } + } +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts2.go b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts2.go new file mode 100644 index 00000000..59938517 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts2.go @@ -0,0 +1,200 @@ +// https://groups.google.com/forum/#!topic/golang-nuts/V83jUKluLnM +// http://play.golang.org/p/alWGk4MDBc + +package main + +import ( + "fmt" + "github.com/clbanning/x2j" +) + +const strXml = ` + + + + +true +A +Initial Claim Review/Screening + + +true +B +Initial Contact Made w/ Provider + + + + + +` + +const strXmlA = ` + + + + +true +A +Initial Claim Review/Screening + + + + + +` + +const strXml2 = ` + + + + + + + +` + +func main() { + docs := []string{strXml, strXmlA, strXml2} + fullPath(docs) + partPath1(strXml) + partPath2(strXml) + partPath3(strXml) + partPath4(strXml) + partPath5(strXml) + partPath6(strXml) +} + +func fullPath(docs []string) { + for i, doc := range docs { + fmt.Println("\ndoc:", i) + fmt.Println(doc) + path := "Envelope.Body.GetClaimStatusCodesResponse.GetClaimStatusCodesResult.ClaimStatusCodeRecord" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + continue + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") + for _, v := range av { + switch v.(type) { + case map[string]interface{}: + fmt.Println("map[string]interface{}:", v.(map[string]interface{})) + case []map[string]interface{}: + fmt.Println("[]map[string]interface{}:", v.([]map[string]interface{})) + case []interface{}: + fmt.Println("[]interface{}:", v.([]interface{})) + case interface{}: + fmt.Println("interface{}:", v.(interface{})) + } + } + } +} + +func partPath1(doc string) { + path := "Envelope.Body.*.*.ClaimStatusCodeRecord" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + return + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") +} + +func partPath2(doc string) { + path := "Envelope.Body.*.*.*" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + return + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") +} + +func partPath3(doc string) { + path := "*.*.*.*.*" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + return + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") +} + +func partPath4(doc string) { + path := "*.*.*.*.*.Description" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + return + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") +} + +func partPath5(doc string) { + path := "*.*.*.*.*.*" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + return + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") +} + +func partPath6(doc string) { + path := "*.*.*.*.*.*.*" + av, err := x2j.ValuesFromTagPath(doc, path) + if err != nil { + fmt.Println("err:", err.Error()) + return + } + if av == nil { + fmt.Println("path:", path) + fmt.Println("No ClaimStatusCodesResult code records.") + return + } + fmt.Println("\nPath:", path) + fmt.Println("Number of code records:", len(av)) + fmt.Println("av:", av, "\n") +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts3.go b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts3.go new file mode 100644 index 00000000..6be4aeaf --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts3.go @@ -0,0 +1,49 @@ +// https://groups.google.com/forum/#!topic/golang-nuts/cok6xasvI3w +// retrieve 'src' values from 'image' tags + +package main + +import ( + "fmt" + "github.com/clbanning/x2j" +) + +var doc = ` + + + + + something else + + + + + + + +` + +func main() { + // get all image tag values - []interface{} + images,err := x2j.ValuesForTag(doc,"image") + if err != nil { + fmt.Println("error parsing doc:",err.Error()) + return + } + + sources := make([]string,0) + for _, v := range images { + // ValuesForKey requires a map[string]interface{} value + // as a starting point ... thinks its a doc + m := make(map[string]interface{},1) + m["dummy"] = v + ss := x2j.ValuesForKey(m,"-src") + for _,s := range ss { + sources = append(sources,s.(string)) + } + } + + for _,src := range sources { + fmt.Println(src) + } +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts4.go b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts4.go new file mode 100644 index 00000000..7627e8d3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/examples/gonuts4.go @@ -0,0 +1,40 @@ +// https://groups.google.com/forum/#!topic/golang-nuts/-N9Toa6qlu8 +// shows that you can extract attribute values directly from tag/key path. +// NOTE: attribute values are encoded by prepending a hyphen, '-'. + +package main + +import ( + "fmt" + "github.com/clbanning/x2j" +) + +var doc = ` + + + + + + + + + + + + + + + + + + ` + +func main() { + values, err := x2j.ValuesFromTagPath(doc, "doc.some_tag.geoInfo.country.-name") + if err != nil { + fmt.Println("err:", err.Error()) + } + for _, v := range values { + fmt.Println("v:",v) + } +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/goofy_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/goofy_test.go new file mode 100644 index 00000000..e24154bf --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/goofy_test.go @@ -0,0 +1,56 @@ +package x2j + +import ( + "encoding/json" + "fmt" + "testing" +) + +func TestGoofy(t *testing.T) { + var doc = `` + type goofy struct { + S string + Sp *string + } + g := new(goofy) + g.S = "Now is the time for" + tmp := "all good men to come to" + g.Sp = &tmp + + m, err := DocToMap(doc) + if err != nil { + fmt.Println("err:",err.Error()) + return + } + + m["goofyVal"] = interface{}(g) + m["byteVal"] = interface{}([]byte(`the aid of their country`)) + m["nilVal"] = interface{}(nil) + + fmt.Println("\nTestGoofy ... MapToDoc:",m) + var v []byte + v,err = json.Marshal(m) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("v:",string(v)) + + type goofier struct { + G *goofy + B []byte + N *string + } + gg := new(goofier) + gg.G = g + gg.B = []byte(`the tree of freedom must periodically be`) + gg.N = nil + m["goofierVal"] = interface{}(gg) + + fmt.Println("\nTestGoofier ... MapToDoc:",m) + v,err = json.Marshal(m) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("v:",string(v)) +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/pathTestString.xml b/Godeps/_workspace/src/github.com/clbanning/x2j/pathTestString.xml new file mode 100644 index 00000000..b297e9d0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/pathTestString.xml @@ -0,0 +1,20 @@ + + 1 + + + A + + + B + + + C + D + + <_> + E + + + 2 + + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/reader2j.go b/Godeps/_workspace/src/github.com/clbanning/x2j/reader2j.go new file mode 100644 index 00000000..11f08289 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/reader2j.go @@ -0,0 +1,105 @@ +// io.Reader --> map[string]interface{} or JSON string +// nothing magic - just implements generic Go case + +package x2j + +import ( + "encoding/json" + "encoding/xml" + "io" +) + +// ToTree() - parse a XML io.Reader to a tree of Nodes +func ToTree(rdr io.Reader) (*Node, error) { + p := xml.NewDecoder(rdr) + p.CharsetReader = X2jCharsetReader + n, perr := xmlToTree("", nil, p) + if perr != nil { + return nil, perr + } + + return n, nil +} + +// ToMap() - parse a XML io.Reader to a map[string]interface{} +func ToMap(rdr io.Reader, recast ...bool) (map[string]interface{}, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + n, err := ToTree(rdr) + if err != nil { + return nil, err + } + + m := make(map[string]interface{}) + m[n.key] = n.treeToMap(r) + + return m, nil +} + +// ToJson() - parse a XML io.Reader to a JSON string +func ToJson(rdr io.Reader, recast ...bool) (string, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + m, merr := ToMap(rdr, r) + if m == nil || merr != nil { + return "", merr + } + + b, berr := json.Marshal(m) + if berr != nil { + return "", berr + } + + return string(b), nil +} + +// ToJsonIndent - the pretty form of ReaderToJson +func ToJsonIndent(rdr io.Reader, recast ...bool) (string, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + m, merr := ToMap(rdr, r) + if m == nil || merr != nil { + return "", merr + } + + b, berr := json.MarshalIndent(m, "", " ") + if berr != nil { + return "", berr + } + + // NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML. + return string(b), nil +} + + +// ReaderValuesFromTagPath - io.Reader version of ValuesFromTagPath() +func ReaderValuesFromTagPath(rdr io.Reader, path string, getAttrs ...bool) ([]interface{}, error) { + var a bool + if len(getAttrs) == 1 { + a = getAttrs[0] + } + m, err := ToMap(rdr) + if err != nil { + return nil, err + } + + return ValuesFromKeyPath(m, path, a), nil +} + +// ReaderValuesForTag - io.Reader version of ValuesForTag() +func ReaderValuesForTag(rdr io.Reader, tag string) ([]interface{}, error) { + m, err := ToMap(rdr) + if err != nil { + return nil, err + } + + return ValuesForKey(m, tag), nil +} + + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/reader2j_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/reader2j_test.go new file mode 100644 index 00000000..98228df5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/reader2j_test.go @@ -0,0 +1,85 @@ +package x2j + +import ( + "bytes" + "fmt" + "testing" +) + +var doc = `barworld` + +func TestToTree(t *testing.T) { + fmt.Println("\nToTree - Read doc:",doc) + rdr := bytes.NewBufferString(doc) + n,err := ToTree(rdr) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println(n.WriteTree()) +} + +func TestToMap(t *testing.T) { + fmt.Println("\nToMap - Read doc:",doc) + rdr := bytes.NewBufferString(doc) + m,err := ToMap(rdr) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println(WriteMap(m)) +} + +func TestToJson(t *testing.T) { + fmt.Println("\nToJson - Read doc:",doc) + rdr := bytes.NewBufferString(doc) + s,err := ToJson(rdr) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("json:",s) +} + +func TestToJsonIndent(t *testing.T) { + fmt.Println("\nToJsonIndent - Read doc:",doc) + rdr := bytes.NewBufferString(doc) + s,err := ToJsonIndent(rdr) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("json:",s) +} + +func TestBulkParser(t *testing.T) { + s := doc + `an`+ doc + fmt.Println("\nBulkParser (with error) - Read doc:",s) + rdr := bytes.NewBufferString(s) + err := XmlMsgsFromReader(rdr,phandler,ehandler) + if err != nil { + fmt.Println("reader terminated:",err.Error()) + } +} + +func phandler(m map[string]interface{}) bool { + fmt.Println("phandler m:",m) + return true +} + +func ehandler(err error) bool { + fmt.Println("ehandler err:",err.Error()) + return true +} + +func TestBulkParserToJson(t *testing.T) { + s := doc + `an`+ doc + fmt.Println("\nBulkParser (with error) - Read doc:",s) + rdr := bytes.NewBufferString(s) + err := XmlMsgsFromReaderAsJson(rdr,phandlerj,ehandler) + if err != nil { + fmt.Println("reader terminated:",err.Error()) + } +} + +func phandlerj(s string) bool { + fmt.Println("phandlerj s:",s) + return true +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/songTextString.xml b/Godeps/_workspace/src/github.com/clbanning/x2j/songTextString.xml new file mode 100644 index 00000000..8c0f2bec --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/songTextString.xml @@ -0,0 +1,29 @@ + + help me! + + + + Henry was a renegade + Didn't like to play it safe + One component at a time + There's got to be a better way + Oh, people came from miles around + Searching for a steady job + Welcome to the Motor Town + Booming like an atom bomb + + + Oh, Henry was the end of the story + Then everything went wrong + And we'll return it to its former glory + But it just takes so long + + + + It's going to take a long time + It's going to take it, but we'll make it one day + It's going to take a long time + It's going to take it, but we'll make it one day + + + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j.go new file mode 100644 index 00000000..7838379a --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j.go @@ -0,0 +1,660 @@ +// Unmarshal arbitrary XML docs to map[string]interface{} or JSON and extract values (using wildcards, if necessary). +// Copyright 2012-2013 Charles Banning. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file +/* + Unmarshal dynamic / arbitrary XML docs and extract values (using wildcards, if necessary). + + NOTICE: 01-Jun-2014, package deprecated. Please see http://github.com/clbanning/mxj/x2j. + + One useful function is: + + - Unmarshal(doc []byte, v interface{}) error + where v is a pointer to a variable of type 'map[string]interface{}', 'string', or + any other type supported by xml.Unmarshal(). + + To retrieve a value for specific tag use: + + - DocValue(doc, path string, attrs ...string) (interface{},error) + - MapValue(m map[string]interface{}, path string, attr map[string]interface{}, recast ...bool) (interface{}, error) + + The 'path' argument is a period-separated tag hierarchy - also known as dot-notation. + It is the program's responsibility to cast the returned value to the proper type; possible + types are the normal JSON unmarshaling types: string, float64, bool, []interface, map[string]interface{}. + + To retrieve all values associated with a tag occurring anywhere in the XML document use: + + - ValuesForTag(doc, tag string) ([]interface{}, error) + - ValuesForKey(m map[string]interface{}, key string) []interface{} + + Demos: http://play.golang.org/p/m8zP-cpk0O + http://play.golang.org/p/cIteTS1iSg + http://play.golang.org/p/vd8pMiI21b + + Returned values should be one of map[string]interface, []interface{}, or string. + + All the values assocated with a tag-path that may include one or more wildcard characters - + '*' - can also be retrieved using: + + - ValuesFromTagPath(doc, path string, getAttrs ...bool) ([]interface{}, error) + - ValuesFromKeyPath(map[string]interface{}, path string, getAttrs ...bool) []interface{} + + Demos: http://play.golang.org/p/kUQnZ8VuhS + http://play.golang.org/p/l1aMHYtz7G + + NOTE: care should be taken when using "*" at the end of a path - i.e., "books.book.*". See + the x2jpath_test.go case on how the wildcard returns all key values and collapses list values; + the same message structure can load a []interface{} or a map[string]interface{} (or an interface{}) + value for a tag. + + See the test cases in "x2jpath_test.go" and programs in "example" subdirectory for more. + + XML PARSING CONVENTIONS + + - Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-', + to the attribute label. + - If the element is a simple element and has attributes, the element value + is given the key '#text' for its map[string]interface{} representation. (See + the 'atomFeedString.xml' test data, below.) + + io.Reader HANDLING + + ToTree(), ToMap(), ToJson(), and ToJsonIndent() provide parsing of messages from an io.Reader. + If you want to handle a message stream, look at XmlMsgsFromReader(). + + NON-UTF8 CHARACTER SETS + + Use the X2jCharsetReader variable to assign io.Reader for alternative character sets. +*/ +package x2j + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "regexp" + "strconv" + "strings" +) + +// If X2jCharsetReader != nil, it will be used to decode the doc or stream if required +// import charset "code.google.com/p/go-charset/charset" +// ... +// x2j.X2jCharsetReader = charset.NewReader +// s, err := x2j.DocToJson(doc) +var X2jCharsetReader func(charset string, input io.Reader)(io.Reader, error) + +type Node struct { + dup bool // is member of a list + attr bool // is an attribute + key string // XML tag + val string // element value + nodes []*Node +} + +// DocToJson - return an XML doc as a JSON string. +// If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible. +func DocToJson(doc string, recast ...bool) (string, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + m, merr := DocToMap(doc, r) + if m == nil || merr != nil { + return "", merr + } + + b, berr := json.Marshal(m) + if berr != nil { + return "", berr + } + + // NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML. + return string(b), nil +} + +// DocToJsonIndent - return an XML doc as a prettified JSON string. +// If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible. +// Note: recasting is only applied to element values, not attribute values. +func DocToJsonIndent(doc string, recast ...bool) (string, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + m, merr := DocToMap(doc, r) + if m == nil || merr != nil { + return "", merr + } + + b, berr := json.MarshalIndent(m, "", " ") + if berr != nil { + return "", berr + } + + // NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML. + return string(b), nil +} + +// DocToMap - convert an XML doc into a map[string]interface{}. +// (This is analogous to unmarshalling a JSON string to map[string]interface{} using json.Unmarshal().) +// If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible. +// Note: recasting is only applied to element values, not attribute values. +func DocToMap(doc string, recast ...bool) (map[string]interface{}, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + n, err := DocToTree(doc) + if err != nil { + return nil, err + } + + m := make(map[string]interface{}) + m[n.key] = n.treeToMap(r) + + return m, nil +} + +// DocToTree - convert an XML doc into a tree of nodes. +func DocToTree(doc string) (*Node, error) { + // xml.Decoder doesn't properly handle whitespace in some doc + // see songTextString.xml test case ... + reg, _ := regexp.Compile("[ \t\n\r]*<") + doc = reg.ReplaceAllString(doc, "<") + + b := bytes.NewBufferString(doc) + p := xml.NewDecoder(b) + p.CharsetReader = X2jCharsetReader + n, berr := xmlToTree("", nil, p) + if berr != nil { + return nil, berr + } + + return n, nil +} + +// (*Node)WriteTree - convert a tree of nodes into a printable string. +// 'padding' is the starting indentation; typically: n.WriteTree(). +func (n *Node) WriteTree(padding ...int) string { + var indent int + if len(padding) == 1 { + indent = padding[0] + } + + var s string + if n.val != "" { + for i := 0; i < indent; i++ { + s += " " + } + s += n.key + " : " + n.val + "\n" + } else { + for i := 0; i < indent; i++ { + s += " " + } + s += n.key + " :" + "\n" + for _, nn := range n.nodes { + s += nn.WriteTree(indent + 1) + } + } + return s +} + +// xmlToTree - load a 'clean' XML doc into a tree of *Node. +func xmlToTree(skey string, a []xml.Attr, p *xml.Decoder) (*Node, error) { + n := new(Node) + n.nodes = make([]*Node, 0) + + if skey != "" { + n.key = skey + if len(a) > 0 { + for _, v := range a { + na := new(Node) + na.attr = true + na.key = `-` + v.Name.Local + na.val = v.Value + n.nodes = append(n.nodes, na) + } + } + } + for { + t, err := p.Token() + if err != nil { + return nil, err + } + switch t.(type) { + case xml.StartElement: + tt := t.(xml.StartElement) + // handle root + if n.key == "" { + n.key = tt.Name.Local + if len(tt.Attr) > 0 { + for _, v := range tt.Attr { + na := new(Node) + na.attr = true + na.key = `-` + v.Name.Local + na.val = v.Value + n.nodes = append(n.nodes, na) + } + } + } else { + nn, nnerr := xmlToTree(tt.Name.Local, tt.Attr, p) + if nnerr != nil { + return nil, nnerr + } + n.nodes = append(n.nodes, nn) + } + case xml.EndElement: + // scan n.nodes for duplicate n.key values + n.markDuplicateKeys() + return n, nil + case xml.CharData: + tt := string(t.(xml.CharData)) + // 28-jan-14 ... clean up noise input + tt = strings.Trim(tt,"\t\r\b\n ") + if len(n.nodes) > 0 && len(tt) > 0 { + nn := new(Node) + nn.key = "#text" + nn.val = tt + n.nodes = append(n.nodes, nn) + } else { + n.val = tt + } + default: + // noop + } + } + // Logically we can't get here, but provide an error message anyway. + return nil, errors.New("Unknown parse error in xmlToTree() for: " + n.key) +} + +// (*Node)markDuplicateKeys - set node.dup flag for loading map[string]interface{}. +func (n *Node) markDuplicateKeys() { + l := len(n.nodes) + for i := 0; i < l; i++ { + if n.nodes[i].dup { + continue + } + for j := i + 1; j < l; j++ { + if n.nodes[i].key == n.nodes[j].key { + n.nodes[i].dup = true + n.nodes[j].dup = true + } + } + } +} + +// (*Node)treeToMap - convert a tree of nodes into a map[string]interface{}. +// (Parses to map that is structurally the same as from json.Unmarshal().) +// Note: root is not instantiated; call with: "m[n.key] = n.treeToMap(recast)". +func (n *Node) treeToMap(r bool) interface{} { + if len(n.nodes) == 0 { + return recast(n.val, r) + } + + m := make(map[string]interface{}, 0) + for _, v := range n.nodes { + // just a value + if !v.dup && len(v.nodes) == 0 { + m[v.key] = recast(v.val, r) + continue + } + + // a list of values + if v.dup { + var a []interface{} + if vv, ok := m[v.key]; ok { + a = vv.([]interface{}) + } else { + a = make([]interface{}, 0) + } + a = append(a, v.treeToMap(r)) + m[v.key] = interface{}(a) + continue + } + + // it's a unique key + m[v.key] = v.treeToMap(r) + } + + return interface{}(m) +} + +// recast - try to cast string values to bool or float64 +func recast(s string, r bool) interface{} { + if r { + // handle numeric strings ahead of boolean + if f, err := strconv.ParseFloat(s, 64); err == nil { + return interface{}(f) + } + // ParseBool treats "1"==true & "0"==false + if b, err := strconv.ParseBool(s); err == nil { + return interface{}(b) + } + } + return interface{}(s) +} + +// WriteMap - dumps the map[string]interface{} for examination. +// 'offset' is initial indentation count; typically: WriteMap(m). +// NOTE: with XML all element types are 'string'. +// But code written as generic for use with maps[string]interface{} values from json.Unmarshal(). +// Or it can handle a DocToMap(doc,true) result where values have been recast'd. +func WriteMap(m interface{}, offset ...int) string { + var indent int + if len(offset) == 1 { + indent = offset[0] + } + + var s string + switch m.(type) { + case nil: + return "[nil] nil" + case string: + return "[string] " + m.(string) + case float64: + return "[float64] " + strconv.FormatFloat(m.(float64), 'e', 2, 64) + case bool: + return "[bool] " + strconv.FormatBool(m.(bool)) + case []interface{}: + s += "[[]interface{}]" + for i, v := range m.([]interface{}) { + s += "\n" + for i := 0; i < indent; i++ { + s += " " + } + s += "[item: " + strconv.FormatInt(int64(i), 10) + "]" + switch v.(type) { + case string, float64, bool: + s += "\n" + default: + // noop + } + for i := 0; i < indent; i++ { + s += " " + } + s += WriteMap(v, indent+1) + } + case map[string]interface{}: + for k, v := range m.(map[string]interface{}) { + s += "\n" + for i := 0; i < indent; i++ { + s += " " + } + // s += "[map[string]interface{}] "+k+" :"+WriteMap(v,indent+1) + s += k + " :" + WriteMap(v, indent+1) + } + default: + // shouldn't ever be here ... + s += fmt.Sprintf("unknown type for: %v", m) + } + return s +} + +// ------------------------ value extraction from XML doc -------------------------- + +// DocValue - return a value for a specific tag +// 'doc' is a valid XML message. +// 'path' is a hierarchy of XML tags, e.g., "doc.name". +// 'attrs' is an OPTIONAL list of "name:value" pairs for attributes. +// Note: 'recast' is not enabled here. Use DocToMap(), NewAttributeMap(), and MapValue() calls for that. +func DocValue(doc, path string, attrs ...string) (interface{}, error) { + n, err := DocToTree(doc) + if err != nil { + return nil, err + } + + m := make(map[string]interface{}) + m[n.key] = n.treeToMap(false) + + a, aerr := NewAttributeMap(attrs...) + if aerr != nil { + return nil, aerr + } + v, verr := MapValue(m, path, a) + if verr != nil { + return nil, verr + } + return v, nil +} + +// MapValue - retrieves value based on walking the map, 'm'. +// 'm' is the map value of interest. +// 'path' is a period-separated hierarchy of keys in the map. +// 'attr' is a map of attribute "name:value" pairs from NewAttributeMap(). May be 'nil'. +// If the path can't be traversed, an error is returned. +// Note: the optional argument 'r' can be used to coerce attribute values, 'attr', if done so for 'm'. +func MapValue(m map[string]interface{}, path string, attr map[string]interface{}, r ...bool) (interface{}, error) { + // attribute values may have been recasted during map construction; default is 'false'. + if len(r) == 1 && r[0] == true { + for k, v := range attr { + attr[k] = recast(v.(string), true) + } + } + + // parse the path + keys := strings.Split(path, ".") + + // initialize return value to 'm' so a path of "" will work correctly + var v interface{} = m + var ok bool + var okey string + var isMap bool = true + if keys[0] == "" && len(attr) == 0 { + return v, nil + } + for _, key := range keys { + if !isMap { + return nil, errors.New("no keys beyond: " + okey) + } + if v, ok = m[key]; !ok { + return nil, errors.New("no key in map: " + key) + } else { + switch v.(type) { + case map[string]interface{}: + m = v.(map[string]interface{}) + isMap = true + default: + isMap = false + } + } + // save 'key' for error reporting + okey = key + } + + // match attributes; value is "#text" or nil + if attr == nil { + return v, nil + } + return hasAttributes(v, attr) +} + +// hasAttributes() - interface{} equality works for string, float64, bool +func hasAttributes(v interface{}, a map[string]interface{}) (interface{}, error) { + switch v.(type) { + case []interface{}: + // run through all entries looking one with matching attributes + for _, vv := range v.([]interface{}) { + if vvv, vvverr := hasAttributes(vv, a); vvverr == nil { + return vvv, nil + } + } + return nil, errors.New("no list member with matching attributes") + case map[string]interface{}: + // do all attribute name:value pairs match? + nv := v.(map[string]interface{}) + for key, val := range a { + if vv, ok := nv[key]; !ok { + return nil, errors.New("no attribute with name: " + key[1:]) + } else if val != vv { + return nil, errors.New("no attribute key:value pair: " + fmt.Sprintf("%s:%v", key[1:], val)) + } + } + // they all match; so return value associated with "#text" key. + if vv, ok := nv["#text"]; ok { + return vv, nil + } else { + // this happens when another element is value of tag rather than just a string value + return nv, nil + } + } + return nil, errors.New("no match for attributes") +} + +// NewAttributeMap() - generate map of attributes=value entries as map["-"+string]string. +// 'kv' arguments are "name:value" pairs that appear as attributes, name="value". +// If len(kv) == 0, the return is (nil, nil). +func NewAttributeMap(kv ...string) (map[string]interface{}, error) { + if len(kv) == 0 { + return nil, nil + } + m := make(map[string]interface{}, 0) + for _, v := range kv { + vv := strings.Split(v, ":") + if len(vv) != 2 { + return nil, errors.New("attribute not \"name:value\" pair: " + v) + } + // attributes are stored as keys prepended with hyphen + m["-"+vv[0]] = interface{}(vv[1]) + } + return m, nil +} + +//------------------------- get values for key ---------------------------- + +// ValuesForTag - return all values in doc associated with 'tag'. +// Returns nil if the 'tag' does not occur in the doc. +// If there is an error encounted while parsing doc, that is returned. +// If you want values 'recast' use DocToMap() and ValuesForKey(). +func ValuesForTag(doc, tag string) ([]interface{}, error) { + m, err := DocToMap(doc) + if err != nil { + return nil, err + } + + return ValuesForKey(m, tag), nil +} + +// ValuesForKey - return all values in map associated with 'key' +// Returns nil if the 'key' does not occur in the map +func ValuesForKey(m map[string]interface{}, key string) []interface{} { + ret := make([]interface{}, 0) + + hasKey(m, key, &ret) + if len(ret) > 0 { + return ret + } + return nil +} + +// hasKey - if the map 'key' exists append it to array +// if it doesn't do nothing except scan array and map values +func hasKey(iv interface{}, key string, ret *[]interface{}) { + switch iv.(type) { + case map[string]interface{}: + vv := iv.(map[string]interface{}) + if v, ok := vv[key]; ok { + *ret = append(*ret, v) + } + for _, v := range iv.(map[string]interface{}) { + hasKey(v, key, ret) + } + case []interface{}: + for _, v := range iv.([]interface{}) { + hasKey(v, key, ret) + } + } +} + +// ======== 2013.07.01 - x2j.Unmarshal, wraps xml.Unmarshal ============== + +// Unmarshal - wraps xml.Unmarshal with handling of map[string]interface{} +// and string type variables. +// Usage: x2j.Unmarshal(doc,&m) where m of type map[string]interface{} +// x2j.Unmarshal(doc,&s) where s of type string (Overrides xml.Unmarshal().) +// x2j.Unmarshal(doc,&struct) - passed to xml.Unmarshal() +// x2j.Unmarshal(doc,&slice) - passed to xml.Unmarshal() +func Unmarshal(doc []byte, v interface{}) error { + switch v.(type) { + case *map[string]interface{}: + m, err := ByteDocToMap(doc) + vv := *v.(*map[string]interface{}) + for k, v := range m { + vv[k] = v + } + return err + case *string: + s, err := ByteDocToJson(doc) + *(v.(*string)) = s + return err + default: + b := bytes.NewBuffer(doc) + p := xml.NewDecoder(b) + p.CharsetReader = X2jCharsetReader + return p.Decode(v) + // return xml.Unmarshal(doc, v) + } + return nil +} + +// ByteDocToJson - return an XML doc as a JSON string. +// If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible. +func ByteDocToJson(doc []byte, recast ...bool) (string, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + m, merr := ByteDocToMap(doc, r) + if m == nil || merr != nil { + return "", merr + } + + b, berr := json.Marshal(m) + if berr != nil { + return "", berr + } + + // NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML. + return string(b), nil +} + +// ByteDocToMap - convert an XML doc into a map[string]interface{}. +// (This is analogous to unmarshalling a JSON string to map[string]interface{} using json.Unmarshal().) +// If the optional argument 'recast' is 'true', then values will be converted to boolean or float64 if possible. +// Note: recasting is only applied to element values, not attribute values. +func ByteDocToMap(doc []byte, recast ...bool) (map[string]interface{}, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + n, err := ByteDocToTree(doc) + if err != nil { + return nil, err + } + + m := make(map[string]interface{}) + m[n.key] = n.treeToMap(r) + + return m, nil +} + +// ByteDocToTree - convert an XML doc into a tree of nodes. +func ByteDocToTree(doc []byte) (*Node, error) { + // xml.Decoder doesn't properly handle whitespace in some doc + // see songTextString.xml test case ... + reg, _ := regexp.Compile("[ \t\n\r]*<") + doc = reg.ReplaceAll(doc, []byte("<")) + + b := bytes.NewBuffer(doc) + p := xml.NewDecoder(b) + p.CharsetReader = X2jCharsetReader + n, berr := xmlToTree("", nil, p) + if berr != nil { + return nil, berr + } + + return n, nil +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_bulk.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_bulk.go new file mode 100644 index 00000000..bc887753 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_bulk.go @@ -0,0 +1,127 @@ +// Copyright 2012-2013 Charles Banning. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +// x2j_bulk.go: Process files with multiple XML messages. +// Extends x2m_bulk.go to work with JSON strings rather than map[string]interface{}. + +package x2j + +import ( + "bytes" + "encoding/json" + "io" + "os" + "regexp" +) + +// XmlMsgsFromFileAsJson() +// 'fname' is name of file +// 'phandler' is the JSON string processing handler. Return of 'false' stops further processing. +// 'ehandler' is the parsing error handler. Return of 'false' stops further processing and returns error. +// Note: phandler() and ehandler() calls are blocking, so reading and processing of messages is serialized. +// This means that you can stop reading the file on error or after processing a particular message. +// To have reading and handling run concurrently, pass arguments to a go routine in handler and return true. +func XmlMsgsFromFileAsJson(fname string, phandler func(string)(bool), ehandler func(error)(bool), recast ...bool) error { + var r bool + if len(recast) == 1 { + r = recast[0] + } + fi, fierr := os.Stat(fname) + if fierr != nil { + return fierr + } + fh, fherr := os.Open(fname) + if fherr != nil { + return fherr + } + defer fh.Close() + buf := make([]byte,fi.Size()) + _, rerr := fh.Read(buf) + if rerr != nil { + return rerr + } + doc := string(buf) + + // xml.Decoder doesn't properly handle whitespace in some doc + // see songTextString.xml test case ... + reg,_ := regexp.Compile("[ \t\n\r]*<") + doc = reg.ReplaceAllString(doc,"<") + b := bytes.NewBufferString(doc) + + for { + s, serr := XmlBufferToJson(b,r) + if serr != nil && serr != io.EOF { + if ok := ehandler(serr); !ok { + // caused reader termination + return serr + } + } + if s != "" { + if ok := phandler(s); !ok { + break + } + } + if serr == io.EOF { + break + } + } + return nil +} + +// XmlBufferToJson - process XML message from a bytes.Buffer +// 'b' is the buffer +// Optional argument 'recast' coerces values to float64 or bool where possible. +func XmlBufferToJson(b *bytes.Buffer,recast ...bool) (string,error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + + n,err := XmlBufferToTree(b) + if err != nil { + return "", err + } + + m := make(map[string]interface{}) + m[n.key] = n.treeToMap(r) + + j, jerr := json.Marshal(m) + return string(j), jerr +} + +// ============================= io.Reader version for stream processing ====================== + +// XmlMsgsFromReaderAsJson() - io.Reader version of XmlMsgsFromFileAsJson +// 'rdr' is an io.Reader for an XML message (stream) +// 'phandler' is the JSON string processing handler. Return of 'false' stops further processing. +// 'ehandler' is the parsing error handler. Return of 'false' stops further processing and returns error. +// Note: phandler() and ehandler() calls are blocking, so reading and processing of messages is serialized. +// This means that you can stop reading the file on error or after processing a particular message. +// To have reading and handling run concurrently, pass arguments to a go routine in handler and return true. +func XmlMsgsFromReaderAsJson(rdr io.Reader, phandler func(string)(bool), ehandler func(error)(bool), recast ...bool) error { + var r bool + if len(recast) == 1 { + r = recast[0] + } + + for { + s, serr := ToJson(rdr,r) + if serr != nil && serr != io.EOF { + if ok := ehandler(serr); !ok { + // caused reader termination + return serr + } + } + if s != "" { + if ok := phandler(s); !ok { + break + } + } + if serr == io.EOF { + break + } + } + return nil +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_findPath.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_findPath.go new file mode 100644 index 00000000..6aab1829 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_findPath.go @@ -0,0 +1,141 @@ +// x2j_findPath - utility functions to retrieve path to node in dot-notation + +package x2j + +import "strings" + +//----------------------------- find all paths to a key -------------------------------- +// Want eventually to extract shortest path and call GetValuesAtKeyPath() +// This will get all the possible paths. These can be scanned for len(path) and sequence. + +// Get all paths through the doc (in dot-notation) that terminate with the specified tag. +// Results can be used with ValuesAtTagPath() and ValuesFromTagPath(). +func PathsForTag(doc string, key string) ([]string, error) { + m, err := DocToMap(doc) + if err != nil { + return nil, err + } + + ss := PathsForKey(m, key) + return ss, nil +} + +// Extract the shortest path from all possible paths - from PathsForTag(). +// Paths are strings using dot-notation. +func PathForTagShortest(doc string, key string) (string, error) { + m, err := DocToMap(doc) + if err != nil { + return "", err + } + + s := PathForKeyShortest(m, key) + return s, nil +} + +// Get all paths through the doc (in dot-notation) that terminate with the specified tag. +// Results can be used with ValuesAtTagPath() and ValuesFromTagPath(). +func BytePathsForTag(doc []byte, key string) ([]string, error) { + m, err := ByteDocToMap(doc) + if err != nil { + return nil, err + } + + ss := PathsForKey(m, key) + return ss, nil +} + +// Extract the shortest path from all possible paths - from PathsForTag(). +// Paths are strings using dot-notation. +func BytePathForTagShortest(doc []byte, key string) (string, error) { + m, err := ByteDocToMap(doc) + if err != nil { + return "", err + } + + s := PathForKeyShortest(m, key) + return s, nil +} + +// Get all paths through the map (in dot-notation) that terminate with the specified key. +// Results can be used with ValuesAtKeyPath() and ValuesFromKeyPath(). +func PathsForKey(m map[string]interface{}, key string) []string { + breadbasket := make(map[string]bool,0) + breadcrumb := "" + + hasKeyPath(breadcrumb, m, key, breadbasket) + if len(breadbasket) == 0 { + return nil + } + + // unpack map keys to return + res := make([]string,len(breadbasket)) + var i int + for k,_ := range breadbasket { + res[i] = k + i++ + } + + return res +} + +// Extract the shortest path from all possible paths - from PathsForKey(). +// Paths are strings using dot-notation. +func PathForKeyShortest(m map[string]interface{}, key string) string { + paths := PathsForKey(m,key) + + lp := len(paths) + if lp == 0 { + return "" + } + if lp == 1 { + return paths[0] + } + + shortest := paths[0] + shortestLen := len(strings.Split(shortest,".")) + + for i := 1 ; i < len(paths) ; i++ { + vlen := len(strings.Split(paths[i],".")) + if vlen < shortestLen { + shortest = paths[i] + shortestLen = vlen + } + } + + return shortest +} + +// hasKeyPath - if the map 'key' exists append it to KeyPath.path and increment KeyPath.depth +// This is really just a breadcrumber that saves all trails that hit the prescribed 'key'. +func hasKeyPath(crumb string, iv interface{}, key string, basket map[string]bool) { + switch iv.(type) { + case map[string]interface{}: + vv := iv.(map[string]interface{}) + if _, ok := vv[key]; ok { + if crumb == "" { + crumb = key + } else { + crumb += "." + key + } + // *basket = append(*basket, crumb) + basket[crumb] = true + } + // walk on down the path, key could occur again at deeper node + for k, v := range vv { + // create a new breadcrumb, add the one we're at to the crumb-trail + var nbc string + if crumb == "" { + nbc = k + } else { + nbc = crumb + "." + k + } + hasKeyPath(nbc, v, key, basket) + } + case []interface{}: + // crumb-trail doesn't change, pass it on + for _, v := range iv.([]interface{}) { + hasKeyPath(crumb, v, key, basket) + } + } +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.go new file mode 100644 index 00000000..c0b1ee65 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.go @@ -0,0 +1,419 @@ +package x2j + +import ( + "encoding/json" + "fmt" + "os" + "testing" +) + +func TestX2j(t *testing.T) { + fi, fierr := os.Stat("x2j_test.xml") + if fierr != nil { + fmt.Println("fierr:",fierr.Error()) + return + } + fh, fherr := os.Open("x2j_test.xml") + if fherr != nil { + fmt.Println("fherr:",fherr.Error()) + return + } + defer fh.Close() + buf := make([]byte,fi.Size()) + _, nerr := fh.Read(buf) + if nerr != nil { + fmt.Println("nerr:",nerr.Error()) + return + } + doc := string(buf) + fmt.Println("\nXML doc:\n",doc) + + root, berr := DocToTree(doc) + if berr != nil { + fmt.Println("berr:",berr.Error()) + fmt.Println("root:",root) + return + } + fmt.Println("\nDocToTree():\n",root.WriteTree()) + + m := make(map[string]interface{}) + m[root.key] = root.treeToMap(false) + fmt.Println("\ntreeToMap, recast==false:\n",WriteMap(m)) + + j,jerr := json.MarshalIndent(m,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } + fmt.Println("\njson.MarshalIndent, recast==false:\n",string(j)) + + // test DocToMap() with recast + mm, mmerr := DocToMap(doc,true) + if mmerr != nil { + println("mmerr:",mmerr.Error()) + return + } + println("\nDocToMap(), recast==true:\n",WriteMap(mm)) + + // test DocToJsonIndent() with recast + s,serr := DocToJsonIndent(doc,true) + if serr != nil { + fmt.Println("serr:",serr.Error()) + } + fmt.Println("\nDocToJsonIndent, recast==true:\n",s) +} + +func TestGetValue(t *testing.T) { + // test MapValue() + doc := `barworld` + fmt.Println("\nRead doc:",doc) + fmt.Println("Looking for value: entry.vars") + mm,mmerr := DocToMap(doc) + if mmerr != nil { + fmt.Println("merr:",mmerr.Error()) + } + v,verr := MapValue(mm,"entry.vars",nil) + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + fmt.Println("Looking for value: entry.vars.foo2.hello") + v,verr = MapValue(mm,"entry.vars.foo2.hello",nil) + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + fmt.Println(v.(string)) + } + fmt.Println("Looking with error in path: entry.var") + v,verr = MapValue(mm,"entry.var",nil) + fmt.Println("verr:",verr.Error()) + + // test DocValue() + fmt.Println("DocValue() for tag path entry.vars") + v,verr = DocValue(doc,"entry.vars") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } + j,_ := json.MarshalIndent(v,""," ") + fmt.Println(string(j)) +} + + +func TestGetValueWithAttr(t *testing.T) { + doc := ` + bar + + world + universe + ` + fmt.Println("\nRead doc:",doc) + fmt.Println("Looking for value: entry.vars") + mm,mmerr := DocToMap(doc) + if mmerr != nil { + fmt.Println("merr:",mmerr.Error()) + } + v,verr := MapValue(mm,"entry.vars",nil) + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + fmt.Println("\nMapValue(): Looking for value: entry.vars.foo item=2") + a,aerr := NewAttributeMap("item:2") + if aerr != nil { + fmt.Println("aerr:",aerr.Error()) + } + v,verr = MapValue(mm,"entry.vars.foo",a) + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + fmt.Println("\nMapValue(): Looking for hello item:4") + a,_ = NewAttributeMap("item:4") + v,verr = MapValue(mm,"hello",a) + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + fmt.Println("\nDocValue(): Looking for entry.vars.foo.hello item:4") + v,verr = DocValue(doc,"entry.vars.foo.hello","item:4") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + fmt.Println("\nDocValue(): Looking for empty nil") + v,verr = DocValue(doc,"") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + // test 'recast' switch + fmt.Println("\ntesting recast switch...") + mm,mmerr = DocToMap(doc,true) + if mmerr != nil { + fmt.Println("merr:",mmerr.Error()) + } + fmt.Println("MapValue(): Looking for value: entry.vars.foo item=2") + a,aerr = NewAttributeMap("item:2") + if aerr != nil { + fmt.Println("aerr:",aerr.Error()) + } + v,verr = MapValue(mm,"entry.vars.foo",a,true) + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } +} + +func TestStuff_1(t *testing.T) { + doc := ` + val2 + val2 + val3 + ` + + fmt.Println(doc) + m,merr := DocToMap(doc) + if merr != nil { + fmt.Println("merr:",merr.Error()) + } else { + fmt.Println(WriteMap(m)) + } + + fmt.Println("\nDocValue(): tag") + v,verr := DocValue(doc,"doc.tag") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + fmt.Println("\nDocValue(): item:2 instance:2") + v,verr = DocValue(doc,"doc.tag","item:2","instance:2") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } +} + +func TestStuff_2(t *testing.T) { + doc := `val2 + val2 + val3` + + fmt.Println(doc) + m,merr := DocToMap(doc) + if merr != nil { + fmt.Println("merr:",merr.Error()) + } else { + fmt.Println(WriteMap(m)) + } + + fmt.Println("\nDocValue(): tag") + v,verr := DocValue(doc,"tag") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } + + fmt.Println("\nDocValue(): item:2 instance:2") + v,verr = DocValue(doc,"tag","item:2","instance:2") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } else { + j, jerr := json.MarshalIndent(v,""," ") + if jerr != nil { + fmt.Println("jerr:",jerr.Error()) + } else { + fmt.Println(string(j)) + } + } +} + +func procMap(m map[string]interface{}) bool { + fmt.Println("procMap:",WriteMap(m),"\n") + return true +} + +func procMapToJson(m map[string]interface{}) bool { + b,_ := json.MarshalIndent(m,""," ") + fmt.Println("procMap:",string(b),"\n") + return true +} + +func procErr(err error) bool { + fmt.Println("procError err:",err.Error()) + return true +} + +func TestBulk(t *testing.T) { + fmt.Println("\nBulk Message Processing Tests") + // if err := XmlMsgsFromFile("x2m_bulk.xml",procMap,procErr); err != nil { + if err := XmlMsgsFromFile("x2m_bulk.xml",procMapToJson,procErr); err != nil { + fmt.Println("XmlMsgsFromFile err:",err.Error()) + } +} + +func TestBulkBuffer(t *testing.T) { + fmt.Println("\nTest arbitrary XML buffer with no ending rootTag - then read from closed buffer.") + doc := `my test docmissing end element` + b := NewXmlBuffer(doc) + for { + m,merr := b.NextMap() + if merr != nil { + fmt.Println("merr:",merr.Error()) + } + if m == nil { + break + } + fmt.Println("m:",m) + } + b.Close() + _,err := b.NextMap() + fmt.Println("err:",err.Error()) +} + + +func TestTagAndKey(t *testing.T) { + var doc string + doc = ` + +
one
+
+ + two.one + two.two + +
+
+ + + +
one
+
two
+
+
+
+
` + + fmt.Println("\nTestTagAndKey()\n",doc) + v,verr := ValuesForTag(doc,"parts") + if verr != nil { + fmt.Println("verr:",verr.Error()) + } + fmt.Println("tag: parts :: len:",len(v),"v:",v) + v, _ = ValuesForTag(doc,"not_a_tag") + if v == nil { + fmt.Println("no 'not_a_tag' tag") + } else { + fmt.Println("key: not_a_tag :: len:",len(v),"v:",v) + } + + m,merr := DocToMap(doc) + if merr != nil { + fmt.Println("merr:",merr.Error()) + } + v = ValuesForKey(m,"section") + fmt.Println("key: section :: len:",len(v),"v:",v) + + v = ValuesForKey(m,"not_a_key") + if v == nil { + fmt.Println("no 'not_a_key' key") + } else { + fmt.Println("key: not_a-key :: len:",len(v),"v:",v) + } +} + +// ---------------- x2j_fast.go ---------------- +/* +func Test_F_DocToMap(t *testing.T) { + var doc string = ` + +
one
+
+ + two.one + two.two + +
+
+ + + +
one
+
two
+
+
+
+
` + fmt.Println("\nF_DocToMap()") + fmt.Println(doc) + m,err := F_DocToMap(doc) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println(WriteMap(m),"\n") +} +*/ diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.xml b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.xml new file mode 100644 index 00000000..8c0f2bec --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_test.xml @@ -0,0 +1,29 @@ + + help me! + + + + Henry was a renegade + Didn't like to play it safe + One component at a time + There's got to be a better way + Oh, people came from miles around + Searching for a steady job + Welcome to the Motor Town + Booming like an atom bomb + + + Oh, Henry was the end of the story + Then everything went wrong + And we'll return it to its former glory + But it just takes so long + + + + It's going to take a long time + It's going to take it, but we'll make it one day + It's going to take a long time + It's going to take it, but we'll make it one day + + + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesAt.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesAt.go new file mode 100644 index 00000000..5973de64 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesAt.go @@ -0,0 +1,88 @@ +// Copyright 2012-2013 Charles Banning. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +// x2j_valuesAt.go: Extract values from an arbitrary XML doc that are at same level as "key". +// Tag path can include wildcard characters. + +package x2j + +import ( + "strings" +) + +// ------------------- sweep up everything for some point in the node tree --------------------- + +// ValuesAtTagPath - deliver all values at the same level of the document as the specified key. +// See ValuesAtKeyPath(). +// If there are no values for the path 'nil' is returned. +// A return value of (nil, nil) means that there were no values and no errors parsing the doc. +// 'doc' is the XML document +// 'path' is a dot-separated path of tag nodes +// 'getAttrs' can be set 'true' to return attribute values for "*"-terminated path +// If a node is '*', then everything beyond is scanned for values. +// E.g., "doc.books' might return a single value 'book' of type []interface{}, but +// "doc.books.*" could return all the 'book' entries as []map[string]interface{}. +// "doc.books.*.author" might return all the 'author' tag values as []string - or +// "doc.books.*.author.lastname" might be required, depending on he schema. +func ValuesAtTagPath(doc, path string, getAttrs ...bool) ([]interface{}, error) { + var a bool + if len(getAttrs) == 1 { + a = getAttrs[0] + } + m, err := DocToMap(doc) + if err != nil { + return nil, err + } + + v := ValuesAtKeyPath(m, path, a) + return v, nil +} + +// ValuesAtKeyPath - deliver all values at the same depth in a map[string]interface{} value +// If v := ValuesAtKeyPath(m,"x.y.z") +// then there exists a _,vv := range v +// such that v.(map[string]interface{})[z] == ValuesFromKeyPath(m,"x.y.z") +// If there are no values for the path 'nil' is returned. +// 'm' is the map to be walked +// 'path' is a dot-separated path of key values +// 'getAttrs' can be set 'true' to return attribute values for "*"-terminated path +// If a node is '*', then everything beyond is walked. +// E.g., see ValuesFromTagPath documentation. +func ValuesAtKeyPath(m map[string]interface{}, path string, getAttrs ...bool) []interface{} { + var a bool + if len(getAttrs) == 1 { + a = getAttrs[0] + } + keys := strings.Split(path, ".") + lenKeys := len(keys) + ret := make([]interface{}, 0) + if lenKeys > 1 { + // use function in x2j_valuesFrom.go + valuesFromKeyPath(&ret, m, keys[:lenKeys-1], a) + if len(ret) == 0 { + return nil + } + } else { + ret = append(ret,interface{}(m)) + } + + // scan the value set and see if key occurs + key := keys[lenKeys-1] + // wildcard is special + if key == "*" { + return ret + } + for _, v := range ret { + switch v.(type) { + case map[string]interface{}: + if _, ok := v.(map[string]interface{})[key]; ok { + return ret + } + } + } + + // no instance of key in penultimate value set + return nil +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesFrom.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesFrom.go new file mode 100644 index 00000000..fdb6cec4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2j_valuesFrom.go @@ -0,0 +1,125 @@ +// Copyright 2012-2013 Charles Banning. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +// x2j_valuesFrom.go: Extract values from an arbitrary XML doc. Tag path can include wildcard characters. + +package x2j + +import ( + "strings" +) + +// ------------------- sweep up everything for some point in the node tree --------------------- + +// ValuesFromTagPath - deliver all values for a path node from a XML doc +// If there are no values for the path 'nil' is returned. +// A return value of (nil, nil) means that there were no values and no errors parsing the doc. +// 'doc' is the XML document +// 'path' is a dot-separated path of tag nodes +// 'getAttrs' can be set 'true' to return attribute values for "*"-terminated path +// If a node is '*', then everything beyond is scanned for values. +// E.g., "doc.books' might return a single value 'book' of type []interface{}, but +// "doc.books.*" could return all the 'book' entries as []map[string]interface{}. +// "doc.books.*.author" might return all the 'author' tag values as []string - or +// "doc.books.*.author.lastname" might be required, depending on he schema. +func ValuesFromTagPath(doc, path string, getAttrs ...bool) ([]interface{}, error) { + var a bool + if len(getAttrs) == 1 { + a = getAttrs[0] + } + m, err := DocToMap(doc) + if err != nil { + return nil, err + } + + v := ValuesFromKeyPath(m, path, a) + return v, nil +} + +// ValuesFromKeyPath - deliver all values for a path node from a map[string]interface{} +// If there are no values for the path 'nil' is returned. +// 'm' is the map to be walked +// 'path' is a dot-separated path of key values +// 'getAttrs' can be set 'true' to return attribute values for "*"-terminated path +// If a node is '*', then everything beyond is walked. +// E.g., see ValuesFromTagPath documentation. +func ValuesFromKeyPath(m map[string]interface{}, path string, getAttrs ...bool) []interface{} { + var a bool + if len(getAttrs) == 1 { + a = getAttrs[0] + } + keys := strings.Split(path, ".") + ret := make([]interface{}, 0) + valuesFromKeyPath(&ret, m, keys, a) + if len(ret) == 0 { + return nil + } + return ret +} + +func valuesFromKeyPath(ret *[]interface{}, m interface{}, keys []string, getAttrs bool) { + lenKeys := len(keys) + + // load 'm' values into 'ret' + // expand any lists + if lenKeys == 0 { + switch m.(type) { + case map[string]interface{}: + *ret = append(*ret, m) + case []interface{}: + for _, v := range m.([]interface{}) { + *ret = append(*ret, v) + } + default: + *ret = append(*ret, m) + } + return + } + + // key of interest + key := keys[0] + switch key { + case "*": // wildcard - scan all values + switch m.(type) { + case map[string]interface{}: + for k, v := range m.(map[string]interface{}) { + if string(k[:1]) == "-" && !getAttrs { // skip attributes? + continue + } + valuesFromKeyPath(ret, v, keys[1:], getAttrs) + } + case []interface{}: + for _, v := range m.([]interface{}) { + switch v.(type) { + // flatten out a list of maps - keys are processed + case map[string]interface{}: + for kk, vv := range v.(map[string]interface{}) { + if string(kk[:1]) == "-" && !getAttrs { // skip attributes? + continue + } + valuesFromKeyPath(ret, vv, keys[1:], getAttrs) + } + default: + valuesFromKeyPath(ret, v, keys[1:], getAttrs) + } + } + } + default: // key - must be map[string]interface{} + switch m.(type) { + case map[string]interface{}: + if v, ok := m.(map[string]interface{})[key]; ok { + valuesFromKeyPath(ret, v, keys[1:], getAttrs) + } + case []interface{}: // may be buried in list + for _, v := range m.([]interface{}) { + switch v.(type) { + case map[string]interface{}: + if vv, ok := v.(map[string]interface{})[key]; ok { + valuesFromKeyPath(ret, vv, keys[1:], getAttrs) + } + } + } + } + } +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2jat_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2jat_test.go new file mode 100644 index 00000000..2f3e0743 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2jat_test.go @@ -0,0 +1,164 @@ +package x2j + +import ( + "fmt" + "testing" +) + +var doc1 = ` + + + + William H. Gaddis + The Recognitions + One of the great seminal American novels of the 20th century. + + + Austin Tappan Wright + Islandia + An example of earlier 20th century American utopian fiction. + + + John Hawkes + The Beetle Leg + A lyrical novel about the construction of Ft. Peck Dam in Montana. + + + + T.E. + Porter + + King's Day + A magical novella. + + + +` +var doc2 = ` + + + + William H. Gaddis + + The Recognitions + One of the great seminal American novels of the 20th century. + + + JR + Won the National Book Award + + + + John Hawkes + + + The Beetle Leg + + + The Blood Oranges + + + + + +` +var msg1 = ` + + test + This is a long cold winter +` + +var msg2 = ` + + + test + This is a long cold winter + + + test2 + I hope we have a cool summer, though + +` + +func TestValuesAtKeyPath(t *testing.T) { + fmt.Println("\nValuesAtKeyPath ... doc1#author") + m, _ := DocToMap(doc1) + ss := PathsForKey(m,"author") + fmt.Println("ss:", ss) + for _,v := range ss { + vv := ValuesAtKeyPath(m,v,true) + fmt.Println("vv:", vv) + } + + fmt.Println("\nValuesAtKeyPath ... doc1#first_name") + // m, _ := DocToMap(doc1) + ss = PathsForKey(m,"first_name") + fmt.Println("ss:", ss) + for _,v := range ss { + vv := ValuesAtKeyPath(m,v,true) + fmt.Println("vv:", vv) + } + + fmt.Println("\nGetKeyPaths...doc2#book") + m, _ = DocToMap(doc2) + ss = PathsForKey(m,"book") + fmt.Println("ss:", ss) + for _,v := range ss { + vv := ValuesAtKeyPath(m,v,true) + fmt.Println("vv:", vv) + } + s := PathForKeyShortest(m,"book") + vv := ValuesAtKeyPath(m,s) + fmt.Println("vv,shortest_path:",vv) + + fmt.Println("\nValuesAtKeyPath ... msg1#pub") + m, _ = DocToMap(msg1) + ss = PathsForKey(m,"pub") + fmt.Println("ss:", ss) + for _,v := range ss { + vv := ValuesAtKeyPath(m,v,true) + fmt.Println("vv:", vv) + } + + fmt.Println("\nValuesAtKeyPath ... msg2#pub") + m, _ = DocToMap(msg2) + ss = PathsForKey(m,"pub") + fmt.Println("ss:", ss) + for _,v := range ss { + vv := ValuesAtKeyPath(m,v,true) + fmt.Println("vv:", vv) + } +} + +func TestValuesAtTagPath(t *testing.T) { + fmt.Println("\nValuesAtTagPath ... doc1#author") + m, _ := DocToMap(doc1) + ss := PathsForKey(m,"author") + fmt.Println("ss:", ss) + for _,v := range ss { + vv,_ := ValuesAtTagPath(doc1,v,true) + fmt.Println("vv:", vv) + } + + fmt.Println("\nValuesAtTagPath ... doc1#first_name") + // m, _ := DocToMap(doc1) + ss = PathsForKey(m,"first_name") + fmt.Println("ss:", ss) + for _,v := range ss { + vv,_ := ValuesAtTagPath(doc1,v,true) + fmt.Println("vv:", vv) + } + + fmt.Println("\nValuesAtTagPath...doc2#book") + m, _ = DocToMap(doc2) + ss = PathsForKey(m,"book") + fmt.Println("ss:", ss) + for _,v := range ss { + vv,_ := ValuesAtTagPath(doc2,v,true) + fmt.Println("vv:", vv) + } + s := PathForKeyShortest(m,"book") + vv,_ := ValuesAtTagPath(doc2,s) + fmt.Println("vv,shortest_path:",vv) +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2jfindPath_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2jfindPath_test.go new file mode 100644 index 00000000..75cf5c9d --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2jfindPath_test.go @@ -0,0 +1,48 @@ +package x2j + +import ( + "fmt" + "testing" +) + +// the basic demo/test case - a small bibliography with mixed element types +func TestPathsForKey(t *testing.T) { + fmt.Println("\nPathsForKey... doc1#author") + m, _ := DocToMap(doc1) + ss := PathsForKey(m, "author") + fmt.Println("ss:", ss) + + fmt.Println("\nPathsForKey... doc1#books") + // m, _ := DocToMap(doc1) + ss = PathsForKey(m, "books") + fmt.Println("ss:", ss) + + fmt.Println("\nPathsForKey...doc2#book") + m, _ = DocToMap(doc2) + ss = PathsForKey(m, "book") + fmt.Println("ss:", ss) + + fmt.Println("\nPathForKeyShortest...doc2#book") + m, _ = DocToMap(doc2) + s := PathForKeyShortest(m, "book") + fmt.Println("s:", s) +} + +// the basic demo/test case - a small bibliography with mixed element types +func TestPathsForTag(t *testing.T) { + fmt.Println("\nPathsForTag... doc1#author") + ss, _ := PathsForTag(doc1, "author") + fmt.Println("ss:", ss) + + fmt.Println("\nPathsForTag... doc1#books") + ss, _ = PathsForTag(doc1, "books") + fmt.Println("ss:", ss) + + fmt.Println("\nPathsForTag...doc2#book") + ss, _ = PathsForTag(doc2, "book") + fmt.Println("ss:", ss) + + fmt.Println("\nPathForTagShortest...doc2#book") + s, _ := PathForTagShortest(doc2, "book") + fmt.Println("s:", s) +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2jpath_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2jpath_test.go new file mode 100644 index 00000000..f8299e01 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2jpath_test.go @@ -0,0 +1,169 @@ +package x2j + +import ( + "fmt" + "testing" +) + +// the basic demo/test case - a small bibliography with mixed element types +func TestValuesFromTagPath(t *testing.T) { +var doc = ` + + + + William H. Gaddis + The Recognitions + One of the great seminal American novels of the 20th century. + + + Austin Tappan Wright + Islandia + An example of earlier 20th century American utopian fiction. + + + John Hawkes + The Beetle Leg + A lyrical novel about the construction of Ft. Peck Dam in Montana. + + + + T.E. + Porter + + King's Day + A magical novella. + + + +` +var doc2 = ` + + + + William H. Gaddis + The Recognitions + One of the great seminal American novels of the 20th century. + + + +` + fmt.Println("\nTestValuesFromTagPath()\n",doc) + + m,_ := DocToMap(doc) + fmt.Println("map:",WriteMap(m),"\n") + + v,_ := ValuesFromTagPath(doc,"doc.books") + fmt.Println("path == doc.books: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.books.*") + fmt.Println("path == doc.books.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.books.book") + fmt.Println("path == doc.books.book: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc2,"doc.books.book") + fmt.Println("doc == doc2 / path == doc.books.book: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.books.book.*") + fmt.Println("path == doc.books.book.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc2,"doc.books.book.*") + fmt.Println("doc == doc2 / path == doc.books.book.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.books.*.author") + fmt.Println("path == doc.books.*.author: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.*.*.author") + fmt.Println("path == doc.*.*.author: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.*.*.title") + fmt.Println("path == doc.*.*.title: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.*.*.*") + fmt.Println("path == doc.*.*.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } + + v,_ = ValuesFromTagPath(doc,"doc.*.*.*.*") + fmt.Println("path == doc.*.*.*.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val,"\n") + } +} + +// demo how to compensate for irregular tag labels in data +// "netid" vs. "idnet" +func TestValuesFromTagPath2(t *testing.T) { +var doc1 = ` + + + + no + default:text + default:word + + +` +var doc2 = ` + + + + yes + default:text + default:word + + +` + var docs = []string{doc1,doc2} + + for n,doc := range docs { + fmt.Println("\nTestValuesFromTagPath2(), iteration:",n,"\n",doc) + + m,_ := DocToMap(doc) + fmt.Println("map:",WriteMap(m)) + + v,_ := ValuesFromTagPath(doc,"data.*") + fmt.Println("\npath == data.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val) + } + for key,val := range v[0].(map[string]interface{}) { + fmt.Println("\t",key,":",val) + } + + v,_ = ValuesFromTagPath(doc,"data.*.*") + fmt.Println("\npath == data.*.*: len(v):",len(v)) + for key,val := range v { + fmt.Println(key,":",val) + } + } +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2junmarshal_test.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2junmarshal_test.go new file mode 100644 index 00000000..13addd0a --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2junmarshal_test.go @@ -0,0 +1,57 @@ +package x2j + +import ( + "fmt" + "testing" + "encoding/xml" +) + +func TestUnmarshal(t *testing.T) { + var doc = []byte(` Mayer Hawthorne A Long Time Henry was a renegade Didn't like to play it safe `) + + fmt.Println("\nUnmarshal test ... *map[string]interface{}, *string") + m := make(map[string]interface{},0) + err := Unmarshal(doc,&m) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("m:",m) + + var s string + err = Unmarshal(doc,&s) + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("s:",s) +} + +func TestStructValue(t *testing.T) { + var doc = []byte(`clbanning
unknown
`) + type Info struct { + XMLName xml.Name `xml:"info"` + Name string `xml:"name"` + Address string `xml:"address"` + } + + var myInfo Info + + fmt.Println("\nUnmarshal test ... struct:",string(doc)) + err := Unmarshal(doc,&myInfo) + if err != nil { + fmt.Println("err:",err.Error()) + } else { + fmt.Printf("myInfo: %+v\n",myInfo) + } +} + +func TestMapValue(t *testing.T) { + var doc = ` Mayer Hawthorne A Long Time Henry was a renegade Didn't like to play it safe ` + + fmt.Println("\nTestMapValue of doc.song.verse w/ len(attrs) == 0.") + fmt.Println("doc:",doc) + v,err := DocValue(doc,"doc.song.verse") + if err != nil { + fmt.Println("err:",err.Error()) + } + fmt.Println("result:",v) +} diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.go b/Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.go new file mode 100644 index 00000000..4e6c5afb --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.go @@ -0,0 +1,201 @@ +// Copyright 2012-2013 Charles Banning. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file + +// x2m_bulk.go: Process files with multiple XML messages. + +package x2j + +import ( + "bytes" + "encoding/xml" + "errors" + "io" + "os" + "regexp" + "sync" +) + +// XmlMsgsFromFile() +// 'fname' is name of file +// 'phandler' is the map processing handler. Return of 'false' stops further processing. +// 'ehandler' is the parsing error handler. Return of 'false' stops further processing and returns error. +// Note: phandler() and ehandler() calls are blocking, so reading and processing of messages is serialized. +// This means that you can stop reading the file on error or after processing a particular message. +// To have reading and handling run concurrently, pass arguments to a go routine in handler and return true. +func XmlMsgsFromFile(fname string, phandler func(map[string]interface{})(bool), ehandler func(error)(bool), recast ...bool) error { + var r bool + if len(recast) == 1 { + r = recast[0] + } + fi, fierr := os.Stat(fname) + if fierr != nil { + return fierr + } + fh, fherr := os.Open(fname) + if fherr != nil { + return fherr + } + defer fh.Close() + buf := make([]byte,fi.Size()) + _, rerr := fh.Read(buf) + if rerr != nil { + return rerr + } + doc := string(buf) + + // xml.Decoder doesn't properly handle whitespace in some doc + // see songTextString.xml test case ... + reg,_ := regexp.Compile("[ \t\n\r]*<") + doc = reg.ReplaceAllString(doc,"<") + b := bytes.NewBufferString(doc) + + for { + m, merr := XmlBufferToMap(b,r) + if merr != nil && merr != io.EOF { + if ok := ehandler(merr); !ok { + // caused reader termination + return merr + } + } + if m != nil { + if ok := phandler(m); !ok { + break + } + } + if merr == io.EOF { + break + } + } + return nil +} + +// XmlBufferToMap - process XML message from a bytes.Buffer +// 'b' is the buffer +// Optional argument 'recast' coerces map values to float64 or bool where possible. +func XmlBufferToMap(b *bytes.Buffer,recast ...bool) (map[string]interface{},error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + + n,err := XmlBufferToTree(b) + if err != nil { + return nil, err + } + + m := make(map[string]interface{}) + m[n.key] = n.treeToMap(r) + + return m,nil +} + +// BufferToTree - derived from DocToTree() +func XmlBufferToTree(b *bytes.Buffer) (*Node, error) { + p := xml.NewDecoder(b) + p.CharsetReader = X2jCharsetReader + n, berr := xmlToTree("",nil,p) + if berr != nil { + return nil, berr + } + + return n,nil +} + +// XmlBuffer - create XML decoder buffer for a string from anywhere, not necessarily a file. +type XmlBuffer struct { + cnt uint64 + str *string + buf *bytes.Buffer +} +var mtx sync.Mutex +var cnt uint64 +var activeXmlBufs = make(map[uint64]*XmlBuffer) + +// NewXmlBuffer() - creates a bytes.Buffer from a string with multiple messages +// Use Close() function to release the buffer for garbage collection. +func NewXmlBuffer(s string) *XmlBuffer { + // xml.Decoder doesn't properly handle whitespace in some doc + // see songTextString.xml test case ... + reg,_ := regexp.Compile("[ \t\n\r]*<") + s = reg.ReplaceAllString(s,"<") + b := bytes.NewBufferString(s) + buf := new(XmlBuffer) + buf.str = &s + buf.buf = b + mtx.Lock() + defer mtx.Unlock() + buf.cnt = cnt ; cnt++ + activeXmlBufs[buf.cnt] = buf + return buf +} + +// BytesNewXmlBuffer() - creates a bytes.Buffer from b with possibly multiple messages +// Use Close() function to release the buffer for garbage collection. +func BytesNewXmlBuffer(b []byte) *XmlBuffer { + bb := bytes.NewBuffer(b) + buf := new(XmlBuffer) + buf.buf = bb + mtx.Lock() + defer mtx.Unlock() + buf.cnt = cnt ; cnt++ + activeXmlBufs[buf.cnt] = buf + return buf +} + +// Close() - release the buffer address for garbage collection +func (buf *XmlBuffer)Close() { + mtx.Lock() + defer mtx.Unlock() + delete(activeXmlBufs,buf.cnt) +} + +// NextMap() - retrieve next XML message in buffer as a map[string]interface{} value. +// The optional argument 'recast' will try and coerce values to float64 or bool as appropriate. +func (buf *XmlBuffer)NextMap(recast ...bool) (map[string]interface{}, error) { + var r bool + if len(recast) == 1 { + r = recast[0] + } + if _, ok := activeXmlBufs[buf.cnt]; !ok { + return nil, errors.New("Buffer is not active.") + } + return XmlBufferToMap(buf.buf,r) +} + + +// ============================= io.Reader version for stream processing ====================== + +// XmlMsgsFromReader() - io.Reader version of XmlMsgsFromFile +// 'rdr' is an io.Reader for an XML message (stream) +// 'phandler' is the map processing handler. Return of 'false' stops further processing. +// 'ehandler' is the parsing error handler. Return of 'false' stops further processing and returns error. +// Note: phandler() and ehandler() calls are blocking, so reading and processing of messages is serialized. +// This means that you can stop reading the file on error or after processing a particular message. +// To have reading and handling run concurrently, pass arguments to a go routine in handler and return true. +func XmlMsgsFromReader(rdr io.Reader, phandler func(map[string]interface{})(bool), ehandler func(error)(bool), recast ...bool) error { + var r bool + if len(recast) == 1 { + r = recast[0] + } + + for { + m, merr := ToMap(rdr,r) + if merr != nil && merr != io.EOF { + if ok := ehandler(merr); !ok { + // caused reader termination + return merr + } + } + if m != nil { + if ok := phandler(m); !ok { + break + } + } + if merr == io.EOF { + break + } + } + return nil +} + diff --git a/Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.xml b/Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.xml new file mode 100644 index 00000000..0db72b73 --- /dev/null +++ b/Godeps/_workspace/src/github.com/clbanning/x2j/x2m_bulk.xml @@ -0,0 +1,67 @@ + + help me! + + + + Henry was a renegade + Didn't like to play it safe + One component at a time + There's got to be a better way + Oh, people came from miles around + Searching for a steady job + Welcome to the Motor Town + Booming like an atom bomb + + + Oh, Henry was the end of the story + Then everything went wrong + And we'll return it to its former glory + But it just takes so long + + + + It's going to take a long time + It's going to take it, but we'll make it one day + It's going to take a long time + It's going to take it, but we'll make it one day + + + + + help me! + + + + Henry was a renegade + Didn't like to play it safe + One component at a time + There's got to be a better way + Oh, people came from miles around + Searching for a steady job + Welcome to the Motor Town + Booming like an atom bomb + + + + + + help me! + + + It's going to take a long time + It's going to take it, but we'll make it one day + It's going to take a long time + It's going to take it, but we'll make it one day + + + + + help me! + + + It's going to take a long time + It's going to take it, but we'll make it one day + It's going to take a long time + It's going to take it, but we'll make it one day + + diff --git a/Makefile b/Makefile index 3be23022..f6094ed8 100644 --- a/Makefile +++ b/Makefile @@ -37,6 +37,15 @@ test-all: build-all @echo "Running Test Suites:" @godep go test -race ./... +save: restore + @godep save ./... + +restore: + @godep restore + +env: + @godep go env + docs-deploy: @mkdocs gh-deploy --clean diff --git a/pkg/s3/bucket.go b/pkg/s3/bucket.go index e1a708d5..83cfc2f7 100644 --- a/pkg/s3/bucket.go +++ b/pkg/s3/bucket.go @@ -47,9 +47,10 @@ import ( "time" "encoding/xml" - "io/ioutil" "net/http" "net/url" + + "github.com/minio-io/mc/pkg/s3errors" ) // bySize implements sort.Interface for []Item based on the Size field. @@ -74,8 +75,9 @@ func (c *Client) ListBuckets() ([]*Bucket, error) { defer res.Body.Close() if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("s3: Unexpected status code %d fetching bucket list", res.StatusCode) + return nil, s3errors.New(res) } + return parseListAllMyBuckets(res.Body) } @@ -92,16 +94,13 @@ func (c *Client) PutBucket(bucket string) error { if err != nil { return err } - - if res != nil && res.Body != nil { - defer res.Body.Close() - } + defer res.Body.Close() if res.StatusCode != http.StatusOK { - return fmt.Errorf("Got response code %d from s3", res.StatusCode) + return s3errors.New(res) } - return nil + return nil } // ListObjects returns 0 to maxKeys (inclusive) items from the @@ -151,31 +150,21 @@ func (c *Client) ListObjects(bucket string, startAt, prefix, delimiter string, m } return nil, nil, err } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { - if res.StatusCode < 500 { - body, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20)) - aerr := &Error{ - Op: "ListBucket", - Code: res.StatusCode, - Body: body, - Header: res.Header, - } - aerr.parseXML() - res.Body.Close() - return nil, nil, aerr - } - } else { - bres = listBucketResults{} - var logbuf bytes.Buffer - err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(&bres) - if err != nil { - fmt.Printf("Error parsing s3 XML response: %v for %q", err, logbuf.Bytes()) - } else if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker { - err = fmt.Errorf("Unexpected parse from server: %#v from: %s", bres, logbuf.Bytes()) - fmt.Print(err) - } + return nil, nil, s3errors.New(res) + } + + bres = listBucketResults{} + var logbuf bytes.Buffer + err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(&bres) + if err != nil { + fmt.Printf("Error parsing s3 XML response: %v for %q", err, logbuf.Bytes()) + } else if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker { + err = fmt.Errorf("Unexpected parse from server: %#v from: %s", bres, logbuf.Bytes()) + fmt.Print(err) } - res.Body.Close() if err != nil { if try < maxTries-1 { continue diff --git a/pkg/s3/error.go b/pkg/s3/error.go deleted file mode 100644 index 24c4fd6b..00000000 --- a/pkg/s3/error.go +++ /dev/null @@ -1,94 +0,0 @@ -// Original license // -// ---------------- // - -/* -Copyright 2011 Google Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// All other modifications and improvements // -// ---------------------------------------- // - -/* - * Mini Object Storage, (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "bytes" - "fmt" - "strings" - - "encoding/hex" - "encoding/xml" - "net/http" -) - -// Error is the type returned by some API operations. -type Error struct { - Op string - Code int // HTTP status code - Body []byte // response body - Header http.Header // response headers - - // UsedEndpoint and AmazonCode are the XML response's Endpoint and - // Code fields, respectively. - UseEndpoint string // if a temporary redirect (wrong endpoint) - AmazonCode string -} - -// xmlError is the Error response from Amazon. -type xmlError struct { - XMLName xml.Name `xml:"Error"` - Code string - Message string - RequestID string - Bucket string - Endpoint string - StringToSignBytes string -} - -func (e *Error) Error() string { - if bytes.Contains(e.Body, []byte("")) { - return fmt.Sprintf("s3.%s: status %d: %s", e.Op, e.Code, e.Body) - } - return fmt.Sprintf("s3.%s: status %d", e.Op, e.Code) -} - -func (e *Error) parseXML() { - var xe xmlError - _ = xml.NewDecoder(bytes.NewReader(e.Body)).Decode(&xe) - e.AmazonCode = xe.Code - if xe.Code == "TemporaryRedirect" { - e.UseEndpoint = xe.Endpoint - } - if xe.Code == "SignatureDoesNotMatch" { - want, _ := hex.DecodeString(strings.Replace(xe.StringToSignBytes, " ", "", -1)) - fmt.Printf("S3 SignatureDoesNotMatch. StringToSign should be %d bytes: %q (%x)", len(want), want, want) - } - -} diff --git a/pkg/s3/object.go b/pkg/s3/object.go index a3136ee6..755575b1 100644 --- a/pkg/s3/object.go +++ b/pkg/s3/object.go @@ -50,6 +50,8 @@ import ( "encoding/base64" "io/ioutil" "net/http" + + "github.com/minio-io/mc/pkg/s3errors" ) /// Object API operations @@ -77,16 +79,13 @@ func (c *Client) Put(bucket, key string, size int64, contents io.Reader) error { c.Auth.signRequest(req, c.Host) res, err := c.Transport.RoundTrip(req) - if res != nil && res.Body != nil { - defer res.Body.Close() - } - if err != nil { return err } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { - // res.Write(os.Stderr) - return fmt.Errorf("Got response code %d from s3", res.StatusCode) + return s3errors.New(res) } return nil } @@ -97,12 +96,10 @@ func (c *Client) Stat(bucket, key string) (size int64, date time.Time, reterr er req.Method = "HEAD" c.Auth.signRequest(req, c.Host) res, err := c.Transport.RoundTrip(req) - if res != nil && res.Body != nil { - defer res.Body.Close() - } if err != nil { return 0, date, err } + defer res.Body.Close() switch res.StatusCode { case http.StatusNotFound: @@ -121,7 +118,7 @@ func (c *Client) Stat(bucket, key string) (size int64, date time.Time, reterr er return size, date, nil } default: - return 0, date, fmt.Errorf("s3: Unexpected status code %d statting object %v", res.StatusCode, key) + return 0, date, s3errors.New(res) } return } @@ -132,18 +129,15 @@ func (c *Client) Get(bucket, key string) (body io.ReadCloser, size int64, err er c.Auth.signRequest(req, c.Host) res, err := c.Transport.RoundTrip(req) if err != nil { - return + return nil, 0, err } - switch res.StatusCode { - case http.StatusOK: - return res.Body, res.ContentLength, nil - case http.StatusNotFound: - res.Body.Close() - return nil, 0, os.ErrNotExist - default: - res.Body.Close() - return nil, 0, fmt.Errorf("Amazon HTTP error on GET: %d", res.StatusCode) + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return nil, 0, s3errors.New(res) } + + return res.Body, res.ContentLength, nil } // GetPartial fetches part of the s3 key object in bucket. @@ -165,15 +159,12 @@ func (c *Client) GetPartial(bucket, key string, offset, length int64) (body io.R if err != nil { return } + defer res.Body.Close() switch res.StatusCode { case http.StatusOK, http.StatusPartialContent: return res.Body, res.ContentLength, nil - case http.StatusNotFound: - res.Body.Close() - return nil, 0, os.ErrNotExist default: - res.Body.Close() - return nil, 0, fmt.Errorf("Amazon HTTP error on GET: %d", res.StatusCode) + return nil, 0, s3errors.New(res) } } diff --git a/pkg/s3errors/errors.go b/pkg/s3errors/errors.go new file mode 100644 index 00000000..93477ea4 --- /dev/null +++ b/pkg/s3errors/errors.go @@ -0,0 +1,72 @@ +/* + * Mini Object Storage, (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//Package s3errors implements client side error handling for S3 protocol +package s3errors + +import ( + "fmt" + + "io/ioutil" + "net/http" + + "github.com/clbanning/x2j" +) + +/* **** SAMPLE ERROR RESPONSE **** +s3.ListBucket: status 403: + + + AccessDenied + Access Denied + F19772218238A85A + GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD + +*/ + +// Error is the type returned by some API operations. +type Error struct { + res *http.Response // response headers + resMsg map[string]interface{} //Keys: Status, Message, RequestID, Bucket, Endpoint +} + +// New returns a new initialized S3.Error structure +func New(res *http.Response) error { + var s3Err Error + s3Err.res = res + + xmlBody, err := ioutil.ReadAll(res.Body) + if err != nil { + return err + } + + s3Err.resMsg, err = x2j.DocToMap(string(xmlBody)) + if err != nil { + return err + } + return s3Err +} + +// Error formats HTTP error string +func (e Error) Error() string { + /* + if bytes.Contains(e.Body, []byte("")) { + return fmt.Sprintf("s3.%s: status %d: %s", e.Op, e.Code, e.Body) + } + return fmt.Sprintf("%s: status %d", e.Op, e.Code) + */ + return fmt.Sprintf("%s", e.res.Status) +}