Catmandu-Importer-getJSON-0.50000755001750001750 012526612422 15021 5ustar00vojvoj000000000000README100644001750001750 1213312526612422 16002 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50NAME Catmandu::Importer::getJSON - load JSON-encoded data from a server using a GET HTTP request SYNOPSIS The following three examples are equivalent: Catmandu::Importer::getJSON->new( file => \"http://example.org/alice.json\nhttp://example.org/bob.json" )->each(sub { my ($record) = @_; ... ); Catmandu::Importer::getJSON->new( url => "http://example.org", file => \"/alice.json\n/bob.json" )->each(sub { my ($record) = @_; ... ); Catmandu::Importer::getJSON->new( url => "http://example.org/{name}.json", file => \"{\"name\":\"alice\"}\n{\"name\":\"bob\"}" )->each(sub { my ($record) = @_; ... ); For more convenience the catmandu command line client can be used: echo http://example.org/alice.json | catmandu convert getJSON to YAML catmandu convert getJSON --from http://example.org/alice.json to YAML catmandu convert getJSON --dry 1 --url http://{domain}/robots.txt < domains DESCRIPTION This Catmandu::Importer performs a HTTP GET request to load JSON-encoded data from a server. The importer expects a line-separated input. Each line corresponds to a HTTP request that is mapped to a JSON-record on success. The following input formats are accepted: plain URL A line that starts with ""http://"" or ""https://"" is used as plain URL. URL path A line that starts with ""/"" is appended to the configured url parameter. variables A JSON object with variables to be used with an URL template or as HTTP query parameters. For instance the input line "{"name":"Karl Marx"}" with URL "http://api.lobid.org/person" or the input line "{"entity":"person","name":"Karl Marx"}" with URL template "http://api.lobid.org/{entity}{?id}{?name}{?q}" are both expanded to . If the JSON data returned in a HTTP response is a JSON array, its elements are imported as multiple items. If a JSON object is returned, it is imported as one item. CONFIGURATION url An URI or an URI templates (URI::Template) as defined by RFC 6570 to load JSON from. If no url is configured, plain URLs must be provided as input or option "from" must be used instead. from A plain URL to load JSON without reading any input lines. timeout / agent / proxy / headers Optional HTTP client settings. client Instance of a Furl HTTP client to perform requests with. dry Don't do any HTTP requests but return URLs that data would be queried from. file / fh Input to read lines from (see Catmandu::Importer). Defaults to STDIN. fix An optional fix to be applied on every item (see Catmandu::Fix). wait Number of seconds to wait between requests. cache Cache JSON response of URLs to not request the same URL twice. HTTP error codes in the 4xx range (e.g. 404) are also cached but 5xx errors are not. The value of this option can be any objects that implements method "get" and "set" (e.g. "CHI"), an existing directory for file caching, a true value to enable global in-memory-caching, or a false value to disable caching (default). File caching uses file names based on MD5 of an URL so for instance "http://example.org/" is cached as "4389382917e51695b759543fdfd5f690.json". METHODS time Returns the UNIX timestamp right before the last request. This can be used for instance to add timestamps or the measure how fast requests were responded. construct_url( [ $base_url, ] $vars_url_or_path ) Returns an URL given a hash reference with variables, a plain URL or an URL path. The optional first argument can be used to override option "url". $importer->construct_url( %query_vars ) $importer->construct_url( $importer->url, %query_vars ) # equivalent request($url) Perform a HTTP GET request of a given URL including logging, caching, request hook etc. Returns a hash/array reference or "undef". EXTENDING This importer provides two methods to filter requests and responses, respectively. See Catmandu::Importer::Wikidata for an example. request_hook Gets a whitespace-trimmed input line and is expected to return an unblessed hash reference, an URL, or undef. Errors are catched and treated equal to undef. response_hook Gets the queried response object and is expected to return an object. LOGGING URLs are emitted before each request on DEBUG log level. LIMITATIONS Future versions of this module may also support asynchronous HTTP fetching modules such as HTTP::Async, for retrieving multiple URLs at the same time. SEE ALSO Catmandu::Fix::get_json provides this importer as fix function. COPYRIGHT AND LICENSE Copyright Jakob Voß, 2014- This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Changes100644001750001750 161112526612422 16374 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50Changelog for Catmandu-Importer-getJSON 0.50 2015-05-19 12:48:46 CEST - more powerful get_json fix function - new public methods request and construct_url - proceed on URL errors when reading URLs from stream - made in-memory cache global 0.43 2015-05-10 22:12:01 CEST - added caching 0.42 2015-04-06 16:52:48 CEST - fix dependencies and URI::Template changes 0.41 2014-10-26 10:35:49 CET - migrated to Dist::Milla - include missing version (issue #9) 0.40 2014-05-16T09:08:44 - document Catmandu::Fix::get_json - enable logging and option 'wait' - bump version - cpanfile [vpeil] - get_json fix added [vpeil] 0.3 2014-04-23T19:28:43 - fix option 'from' 0.2 2014-04-22T18:08:25 - version number - introduced request and response hooks - new option --dry - option --from closes issue #1 - minor documentation changes 0.1 2014-01-21T11:08:38 - use UTF-8 - initial version LICENSE100644001750001750 4361712526612422 16142 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50This software is copyright (c) 2014- by -. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2014- by -. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2014- by -. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End cpanfile100644001750001750 30212526612422 16561 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50requires 'perl', '5.10.1'; requires 'Catmandu', '0.9'; requires 'Furl', '3.0'; requires 'Moo', '1.0'; requires 'URI::Template', '0.18'; requires 'JSON', '2.90'; requires 'Scalar::Util', '1.41'; dist.ini100644001750001750 3312526612422 16502 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50author=Jakob Voß [@Milla] META.yml100644001750001750 177212526612422 16362 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50--- abstract: 'load JSON-encoded data from a server using a GET HTTP request' author: - 'Jakob Voß' build_requires: {} configure_requires: Module::Build::Tiny: '0.039' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.035, Dist::Milla version v1.0.8, CPAN::Meta::Converter version 2.150001' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Catmandu-Importer-getJSON no_index: directory: - t - xt - inc - share - eg - examples requires: Catmandu: '0.9' Furl: '3.0' JSON: '2.90' Moo: '1.0' Scalar::Util: '1.41' URI::Template: '0.18' perl: v5.10.1 resources: bugtracker: https://github.com/nichtich/Catmandu-Importer-getJSON/issues homepage: https://github.com/nichtich/Catmandu-Importer-getJSON repository: https://github.com/nichtich/Catmandu-Importer-getJSON.git version: '0.50' x_contributors: - 'Jakob Voß ' - 'Vitali Peil ' - 'bayashi ' MANIFEST100644001750001750 46712526612422 16222 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.035. Build.PL Changes LICENSE MANIFEST META.json META.yml README cpanfile dist.ini lib/Catmandu/Fix/get_json.pm lib/Catmandu/Importer/getJSON.pm t/00_compile.t t/10_import.t t/15_cache.t t/20_fix.t t/MockFurl.pm t/release-pod-syntax.t Build.PL100644001750001750 24312526612422 16355 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50# This Build.PL for Catmandu-Importer-getJSON was generated by Dist::Zilla::Plugin::ModuleBuildTiny 0.006. use v5.10.1; use Module::Build::Tiny 0.039; Build_PL(); META.json100644001750001750 336612526612422 16533 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50{ "abstract" : "load JSON-encoded data from a server using a GET HTTP request", "author" : [ "Jakob Voß" ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.035, Dist::Milla version v1.0.8, CPAN::Meta::Converter version 2.150001", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Catmandu-Importer-getJSON", "no_index" : { "directory" : [ "t", "xt", "inc", "share", "eg", "examples" ] }, "prereqs" : { "configure" : { "requires" : { "Module::Build::Tiny" : "0.039" } }, "develop" : { "requires" : { "Dist::Milla" : "v1.0.8", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "Catmandu" : "0.9", "Furl" : "3.0", "JSON" : "2.90", "Moo" : "1.0", "Scalar::Util" : "1.41", "URI::Template" : "0.18", "perl" : "v5.10.1" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/nichtich/Catmandu-Importer-getJSON/issues" }, "homepage" : "https://github.com/nichtich/Catmandu-Importer-getJSON", "repository" : { "type" : "git", "url" : "https://github.com/nichtich/Catmandu-Importer-getJSON.git", "web" : "https://github.com/nichtich/Catmandu-Importer-getJSON" } }, "version" : "0.50", "x_contributors" : [ "Jakob Voß ", "Vitali Peil ", "bayashi " ] } t000755001750001750 012526612422 15205 5ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.5020_fix.t100644001750001750 415112526612422 16622 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/tuse strict; use Test::More; use Catmandu::Fix::get_json; sub get_dry { Catmandu::Fix::get_json->new(@_, dry => 1) } is_deeply get_dry("http://example.com/json") ->fix({}), {url => "http://example.com/json"}, 'plain URL'; is_deeply get_dry("http://example.com/json") ->fix({foo => "bar"}), {url => "http://example.com/json"}, 'plain URL, override'; is_deeply get_dry("http://example.com/json", path => "tmp.test") ->fix({foo => "bar"}), {foo => "bar", tmp => {test => {url => "http://example.com/json"}}}, 'plain URL, path'; is_deeply get_dry("http://example.com/{name}.json", vars => 'path') ->fix({path => { name => 'foo', foo => 'bar' }}), { url => "http://example.com/foo.json" }, 'URL template with variables'; is_deeply get_dry("http://example.com/{name}.json", vars => 'path') ->fix({path => "http://example.org/1" }), { }, 'URL template n/a variables'; is_deeply get_dry("http://example.com/", vars => 'path') ->fix({path => { name => 'foo' }}), { url => "http://example.com/?name=foo" }, 'URL with query variables'; is_deeply get_dry("http://example.com/some", vars => 'path') ->fix({path => "/path" }), { url => 'http://example.com/some/path' }, 'URL with path'; is_deeply get_dry("http://example.com/{name}.json", vars => 'path') ->fix({path => "/path" }), { url => 'http://example.com/%7Bname%7D.json/path' }, 'URL template with path'; is_deeply get_dry("my") ->fix({my => "http://example.org/" }), { my => { url => "http://example.org/" } }, 'URL from field'; is_deeply get_dry("my", vars => 'q', path => '') ->fix({ my => "http://example.org/", q => '/path' }), { url => "http://example.org/path" }, 'URL from field, with path'; is_deeply get_dry("my", vars => 'q', path => '') ->fix({ my => "http://example.org/", q => { some => 42 } }), { url => "http://example.org/?some=42" }, 'URL from field, with vars'; is_deeply get_dry("my", vars => 'q', path => '') ->fix({ my => "http://example.org/{some}", q => { some => 42 } }), { url => "http://example.org/42" }, 'URL template from field'; done_testing; 15_cache.t100644001750001750 236412526612422 17107 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/tuse strict; use Test::More; use lib 't'; use MockFurl; use File::Temp; use Digest::MD5 qw(md5_hex); use Encode; use Catmandu::Importer::getJSON; my $dir = File::Temp::tempdir(CLEANUP=>1); my $counter = 0; my %args = ( client => MockFurl::new( content => sub { '{"'.encode_utf8('ä').'":'.$counter++.'}' } ), file => \"http://example.org\nhttp://example.com\nhttp://example.org", ); my $importer = Catmandu::Importer::getJSON->new(%args); my $a = $importer->to_array; note explain $a; is_deeply $a, [{'ä'=>0},{'ä'=>1},{'ä'=>2}], 'cache off'; $importer = Catmandu::Importer::getJSON->new(%args, cache => 1); note explain $Catmandu::Importer::getJSON::CACHE; is_deeply $importer->to_array, [{'ä'=>3},{'ä'=>4},{'ä'=>3}], 'in-memory cache'; note explain $Catmandu::Importer::getJSON::CACHE; $importer = Catmandu::Importer::getJSON->new(%args, cache => $dir); is_deeply $importer->to_array, [{'ä'=>5},{'ä'=>6},{'ä'=>5}], 'file cache'; my $file = $dir.'/'.md5_hex("http://example.org").'.json'; open my $fh, "<:utf8", $file; is <$fh>, '{"ä":5}', 'cache file'; $importer = Catmandu::Importer::getJSON->new(%args, cache => 1); is_deeply $importer->to_array, [{'ä'=>3},{'ä'=>4},{'ä'=>3}], 'in-memory cache is global'; done_testing; 10_import.t100644001750001750 435512526612422 17353 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/tuse strict; use Test::More; use lib 't'; use MockFurl; use Catmandu::Importer::getJSON; sub test_importer(@) { ##no critic my ($url, $requests, $content, $expect, $msg) = @_; my $importer = Catmandu::Importer::getJSON->new( file => \ do { join "\n", map { $_->[0] } @$requests }, client => MockFurl::new( content => $content ), ); $importer->url($url) if defined $url; $expect = [ map { $expect } @$requests ] if ref $expect ne 'ARRAY'; is_deeply $importer->to_array, $expect, $msg; is_deeply $importer->client->urls, [ map { $_->[1] } @$requests ]; } my @requests = ( [ '{ } ' => 'http://example.org/' ], [ '{"q":"&"}' => 'http://example.org/?q=%26' ], [ '/path?q=%20 ' => 'http://example.org/path?q=%20' ], ); test_importer 'http://example.org/', \@requests, '{"x":"\u2603"}' => {x=>"\x{2603}"}, 'URI'; test_importer 'http://example.{tdl}/{?foo}{?bar}', [ [ 'http://example.org' => 'http://example.org' ], [ '{"tdl":"com"}' => 'http://example.com/' ], [ '{"tdl":"com","bar":"doz"}' => 'http://example.com/?bar=doz' ], ], '{}' => { }, 'URI::Template'; is_deeply(Catmandu::Importer::getJSON->new( client => MockFurl::new( content => '{"hello":"World"}' ), from => 'http://example.org', )->to_array, [{hello=>"World"}], '--from'); is_deeply(Catmandu::Importer::getJSON->new( dry => 1, url => 'http://example.{tdl}/', file => \'{"tdl":"org"}' )->to_array, [{url=>"http://example.org/"}],'--dry'); test_importer undef, [ ["http://example.info" => "http://example.info" ] ], '[{"n":1},{"n":2}]' => [{"n"=>1},{"n"=>2}], 'JSON array response'; my $importer = Catmandu::Importer::getJSON->new( client => MockFurl::new( content => '[{"n":1},{"n":2}]' ), from => 'http://example.org', ); is_deeply $importer->first, {n => 1}, 'array response 1/2'; is_deeply $importer->rest->first, { n => 2}, 'array response 2/2'; { my $warning; local $SIG{__WARN__} = sub { $warning = shift }; is_deeply(Catmandu::Importer::getJSON->new( file => \"x\n\nhttp://example.org/", dry => 1, )->to_array, [{ url => "http://example.org/" }]); is $warning, "failed to construct URL: x\n", "warning"; } done_testing; MockFurl.pm100644001750001750 41212526612422 17402 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/tpackage MockFurl; sub new { bless { @_ }, 'MockFurl' } sub decoded_content { my $content = $_[0]->{content}; ref $content ? $content->() : $content; } sub urls { $_[0]->{urls} // [] } sub get { push @{$_[0]->{urls}}, $_[1]; $_[0] } sub is_success { 1 } 1; 00_compile.t100644001750001750 20312526612422 17434 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/tuse strict; use warnings; use Test::More; use_ok 'Catmandu::Importer::getJSON'; # use_ok 'Catmandu::Fix::getJSON'; done_testing; release-pod-syntax.t100644001750001750 45612526612422 21243 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/t#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Fix000755001750001750 012526612422 17772 5ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/lib/Catmanduget_json.pm100644001750001750 1127112526612422 22322 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/lib/Catmandu/Fixpackage Catmandu::Fix::get_json; our $VERSION = '0.50'; use Catmandu::Sane; use Catmandu::Util; use Moo; use Catmandu::Fix::Has; use Catmandu::Importer::getJSON; with "Catmandu::Fix::Base"; has url => (fix_arg => 1, default => sub {"url"}); has dry => (fix_opt => 1); has cache => (fix_opt => 1); has timeout => (fix_opt => 1, default => sub { 10 } ); has agent => (fix_opt => 1); has proxy => (fix_opt => 1); has wait => (fix_opt => 1); has vars => (fix_opt => 1); has path => (fix_opt => 1); has importer => (is => 'ro', lazy => 1, builder => 1); sub _build_importer { my ($self) = @_; my %options = ( dry => $self->dry, cache => $self->cache, timeout => $self->timeout, agent => $self->agent, proxy => $self->proxy, wait => $self->wait, ); # URL template or plain URL if ( $self->url =~ qr{^https?://} ) { $options{ $self->vars ? 'url' : 'from' } = $self->url; } Catmandu::Importer::getJSON->new(%options); } sub BUILD { my ($self) = @_; unless (defined $self->path) { $self->{path} = $self->url =~ qr{^https?://} ? '' : $self->url; } } sub emit { my ($self, $fixer) = @_; my $path = $fixer->split_path($self->path); my $importer = $fixer->capture($self->importer); # plain URL if ($self->importer->from) { return $fixer->emit_create_path($fixer->var, $path, sub { sprintf '%s = %s->request(%s->from) // { };', shift, $importer, $importer; }); } # URL template or base URL if ($self->importer->url) { my $tpl = $fixer->split_path($self->vars); my $url = $fixer->generate_var; return $fixer->emit_create_path($fixer->var, $tpl, sub { my $tpl = shift; "my $url;". "if (is_hash_ref($tpl) or is_string($tpl) and $tpl !~ qr{^https?://}) {". " $url = ${importer}->construct_url($tpl) ". "}". $fixer->emit_create_path($fixer->var, $path, sub { sprintf '%s = %s ? %s->request(%s) // {} : {};', shift, $url, $importer, $url; }) }); } # URL from field my $url = $fixer->split_path($self->url); return $fixer->emit_create_path($fixer->var, $url, sub { if ($self->vars) { my $base = shift; my $tpl = $fixer->split_path($self->vars); my $url = $fixer->generate_var; return $fixer->emit_create_path($fixer->var, $tpl, sub { my $tpl = shift; "my $url;". "if (is_hash_ref($tpl) or is_string($tpl) and $tpl !~ qr{^https?://}) {". " $url = ${importer}->construct_url($base, $tpl); ". "}". $fixer->emit_create_path($fixer->var, $path, sub { sprintf '%s = %s ? %s->request(%s) // {} : {};', shift, $url, $importer, $url; }) }); } else { my $url = shift; return $fixer->emit_create_path($fixer->var, $path, sub { sprintf '%s = %s->request(%s) // { };', shift, $importer, $url; }); } }); } 1; __END__ =head1 NAME Catmandu::Fix::get_json - get JSON data from an URL as fix function =head1 SYNOPSIS # fetches a hash or array get_json("http://example.com/json") # stores it in path.key get_json("http://example.com/json", path: path.key) # add URL query parameters or URL path from config get_json("http://example.com/", vars: config) # fill URL template fields from config get_json("http://example.com/{name}.json", vars: config) # get URL or URL template from a field get_json(field.name) =head1 DESCRIPTION This L provides a method to fetch JSON data from an URL. The response is added as new item or to a field of the current item. =head1 OPTIONS The first argument must be an URL, an URL template, or a field where to take an URL or URL template from. Additional options include: =over =item path Field to store result JSON in. If not given or set to the empty string, the whole item is replaced by the fetched JSON response. If the first argument is a field, the same field is used as C by default. =item vars Field to get URL template variables, URL query parameters or an URL path expression from. This option is required if the first argument is an URL template. =back The fix function also supports options C, C, C, C, C, and C as documented in L. Options C, C, and C are not supported. =cut Importer000755001750001750 012526612422 21045 5ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/lib/CatmandugetJSON.pm100644001750001750 2555012526612422 23043 0ustar00vojvoj000000000000Catmandu-Importer-getJSON-0.50/lib/Catmandu/Importerpackage Catmandu::Importer::getJSON; our $VERSION = '0.50'; our $CACHE; use Catmandu::Sane; use Moo; use JSON; use Furl; use Scalar::Util qw(blessed); use URI::Template; with 'Catmandu::Importer'; has url => ( is => 'rw', trigger => sub { $_[0]->{url} = _url_template_or_url($_[1]) } ); has from => ( is => 'ro'); has timeout => ( is => 'ro', default => sub { 10 } ); has agent => ( is => 'ro' ); has proxy => ( is => 'ro' ); has dry => ( is => 'ro' ); has headers => ( is => 'ro', default => sub { [ 'Accept' => 'application/json' ] } ); has wait => ( is => 'ro' ); has cache => ( is => 'ro', trigger => 1 ); has client => ( is => 'ro', lazy => 1, builder => sub { Furl->new( map { $_ => $_[0]->{$_} } grep { defined $_[0]->{$_} } qw(timeout agent proxy), ) } ); has json => ( is => 'ro', default => sub { JSON->new->utf8(1) } ); has time => ( is => 'rw' ); has warn => ( is => 'ro', default => sub { 1 } ); sub _url_template_or_url { my ($url) = @_; if (!blessed $url) { $url = URI::Template->new($url); } if ($url->isa('URI::Template')) { unless ( my @variables = $url->variables ) { $url = URI->new("$url"); } } return $url; } { package Importer::getJSON::MemoryCache; use JSON; our $JSON = JSON->new->utf8; sub new { bless {}, $_[0] } sub get { eval { $JSON->decode($_[0]->{$_[1]}) } } sub set { $_[0]->{$_[1]} = ref $_[2] ? $JSON->encode($_[2]) : '' } } $CACHE = Importer::getJSON::MemoryCache->new; { package Importer::getJSON::FileCache; use JSON; use Catmandu::Util qw(read_json); use Digest::MD5 qw(md5_hex); our $JSON = JSON->new->utf8; sub new { my ($class, $dir) = @_; $dir =~ s{/$}{}; bless { dir => $dir }, $class } sub file { my ($self, $url) = @_; $self->{dir}.'/'.md5_hex($url).'.json'; } sub get { eval { read_json($_[0]->file($_[1])) } } sub set { my ($self, $url, $data) = @_; open my $fh, ">", $self->file($url); print $fh (ref $data ? $JSON->encode($data) : ''); } } sub _trigger_cache { my ($self, $cache) = @_; if (blessed $cache and $cache->can('get') and $cache->can('set')) { # use cache object } elsif ($cache and -d $cache) { $cache = Importer::getJSON::FileCache->new($cache); } elsif ($cache) { $cache = $CACHE; } $self->{cache} = $cache; } sub generator { my ($self) = @_; if ($self->from) { return sub { state $data = do { my $r = $self->request($self->from); (ref $r // '') eq 'ARRAY' ? $r : [$r]; }; return shift @$data; } } sub { state $fh = $self->fh; state $data; if ( $data and ref $data eq 'ARRAY' and @$data ) { return shift @$data; } my $url; until ( $url ) { my $line = <$fh> // return; chomp $line; $line =~ s/^\s+|\s+$//g; next if $line eq ''; # ignore empty lines my $request = eval { $self->request_hook($line) }; $url = $self->construct_url($request); warn "failed to construct URL: $line\n" if !$url and $self->warn; } $data = $self->request($url); return (ref $data // '') eq 'ARRAY' ? shift @$data : $data; } } sub request_hook { my ($self, $line) = @_; return $line =~ /^\s*{/ ? $self->json->decode($line) : $line; } sub construct_url { my $self = shift; my $url = @_ > 1 ? _url_template_or_url(shift) : $self->url; my $request = shift; # Template or query variables if (ref $request and not blessed $request) { return unless blessed $url; if ($url->isa('URI::Template')) { $url = $url->process($request); } else { $url = $url->clone; $url->query_form($request); } return $url; } elsif (blessed $request and $request->isa('URI::URL')) { return $request; } elsif ( $request =~ /^https?:\/\// ) { # plain URL return URI->new($request); } elsif ( $request =~ /^\// ) { # URL path (and optional query) $url = "$url"; $url =~ s{/$}{}; $request =~ s{\s+$}{}; return URI->new($url . $request); } return; } sub request { my ($self, $url) = @_; $self->log->debug($url); my $json = ''; if ( $self->dry ) { return { url => "$url" }; } if ( $self->cache ) { $json = $self->cache->get($url); if (defined $json) { return ref $json ? $json : undef; } } if ( $self->wait and $self->time ) { my $elapsed = ($self->time // time) - time; sleep( $self->wait - $elapsed ); } $self->time(time); my $response = $self->client->get($url, $self->headers); if ($response->is_success) { my $content = $response->decoded_content; my $data = $self->json->decode($content); $json = $self->response_hook($data); } else { warn "request failed: $url\n" unless !$self->warn; if ($response->status =~ /^4/) { $json = ''; } else { return; } } if ( $self->cache ) { $self->cache->set($url, $json); } return ref $json ? $json : undef; } sub response_hook { $_[1] } 1; __END__ =head1 NAME Catmandu::Importer::getJSON - load JSON-encoded data from a server using a GET HTTP request =begin markdown # STATUS [![Build Status](https://travis-ci.org/nichtich/Catmandu-Importer-getJSON.png)](https://travis-ci.org/nichtich/Catmandu-Importer-getJSON) [![Coverage Status](https://coveralls.io/repos/nichtich/Catmandu-Importer-getJSON/badge.png)](https://coveralls.io/r/nichtich/Catmandu-Importer-getJSON) [![Kwalitee Score](http://cpants.cpanauthors.org/dist/Catmandu-Importer-getJSON.png)](http://cpants.cpanauthors.org/dist/Catmandu-Importer-getJSON) =end markdown =head1 SYNOPSIS The following three examples are equivalent: Catmandu::Importer::getJSON->new( file => \"http://example.org/alice.json\nhttp://example.org/bob.json" )->each(sub { my ($record) = @_; ... ); Catmandu::Importer::getJSON->new( url => "http://example.org", file => \"/alice.json\n/bob.json" )->each(sub { my ($record) = @_; ... ); Catmandu::Importer::getJSON->new( url => "http://example.org/{name}.json", file => \"{\"name\":\"alice\"}\n{\"name\":\"bob\"}" )->each(sub { my ($record) = @_; ... ); For more convenience the L command line client can be used: echo http://example.org/alice.json | catmandu convert getJSON to YAML catmandu convert getJSON --from http://example.org/alice.json to YAML catmandu convert getJSON --dry 1 --url http://{domain}/robots.txt < domains =head1 DESCRIPTION This L performs a HTTP GET request to load JSON-encoded data from a server. The importer expects a line-separated input. Each line corresponds to a HTTP request that is mapped to a JSON-record on success. The following input formats are accepted: =over =item plain URL A line that starts with "C" or "C" is used as plain URL. =item URL path A line that starts with "C" is appended to the configured B parameter. =item variables A JSON object with variables to be used with an URL template or as HTTP query parameters. For instance the input line C<< {"name":"Karl Marx"} >> with URL C or the input line C<< {"entity":"person","name":"Karl Marx"} >> with URL template C are both expanded to L. =back If the JSON data returned in a HTTP response is a JSON array, its elements are imported as multiple items. If a JSON object is returned, it is imported as one item. =head1 CONFIGURATION =over =item url An L or an URI templates (L) as defined by L to load JSON from. If no B is configured, plain URLs must be provided as input or option C must be used instead. =item from A plain URL to load JSON without reading any input lines. =item timeout / agent / proxy / headers Optional HTTP client settings. =item client Instance of a L HTTP client to perform requests with. =item dry Don't do any HTTP requests but return URLs that data would be queried from. =item file / fh Input to read lines from (see L). Defaults to STDIN. =item fix An optional fix to be applied on every item (see L). =item wait Number of seconds to wait between requests. =item cache Cache JSON response of URLs to not request the same URL twice. HTTP error codes in the 4xx range (e.g. 404) are also cached but 5xx errors are not. The value of this option can be any objects that implements method C and C (e.g. C), an existing directory for file caching, a true value to enable global in-memory-caching, or a false value to disable caching (default). File caching uses file names based on MD5 of an URL so for instance C is cached as C<4389382917e51695b759543fdfd5f690.json>. =back =head1 METHODS =head2 time Returns the UNIX timestamp right before the last request. This can be used for instance to add timestamps or the measure how fast requests were responded. =head2 construct_url( [ $base_url, ] $vars_url_or_path ) Returns an URL given a hash reference with variables, a plain URL or an URL path. The optional first argument can be used to override option C. $importer->construct_url( %query_vars ) $importer->construct_url( $importer->url, %query_vars ) # equivalent =head2 request($url) Perform a HTTP GET request of a given URL including logging, caching, request hook etc. Returns a hash/array reference or C. =head1 EXTENDING This importer provides two methods to filter requests and responses, respectively. See L for an example. =head2 request_hook Gets a whitespace-trimmed input line and is expected to return an unblessed hash reference, an URL, or undef. Errors are catched and treated equal to undef. =head2 response_hook Gets the queried response object and is expected to return an object. =head1 LOGGING URLs are emitted before each request on DEBUG log level. =head1 LIMITATIONS Future versions of this module may also support asynchronous HTTP fetching modules such as L, for retrieving multiple URLs at the same time. =head1 SEE ALSO L provides this importer as fix function. =encoding utf8 =head1 COPYRIGHT AND LICENSE Copyright Jakob Voß, 2014- This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut