pax_global_header 0000666 0000000 0000000 00000000064 14447725663 0014534 g ustar 00root root 0000000 0000000 52 comment=d9ab19b9741a96c756a1f39b6b24986ea8ca975d
Wikidata-Toolkit-0.14.6/ 0000775 0000000 0000000 00000000000 14447725663 0015004 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/.github/ 0000775 0000000 0000000 00000000000 14447725663 0016344 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/.github/dependabot.yml 0000664 0000000 0000000 00000000646 14447725663 0021202 0 ustar 00root root 0000000 0000000 # Documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
# For openrefine java deps
- package-ecosystem: "maven"
directory: "/"
schedule:
interval: "daily"
open-pull-requests-limit: 10
# For github actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
Wikidata-Toolkit-0.14.6/.github/workflows/ 0000775 0000000 0000000 00000000000 14447725663 0020401 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/.github/workflows/ci.yml 0000664 0000000 0000000 00000001463 14447725663 0021523 0 ustar 00root root 0000000 0000000 name: Java CI
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: [ 8, 11, 17 ]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: zulu
java-version: ${{ matrix.java }}
- uses: actions/cache@v3
with:
path: ~/.m2
key: ${{ runner.os }}-${{ matrix.java }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-${{ matrix.java }}-m2
- run: mvn --batch-mode --update-snapshots -Dgpg.skip=true jacoco:prepare-agent verify jacoco:report
- uses: codecov/codecov-action@v3
with:
file: ./**/target/site/jacoco/jacoco.xml
name: codecov
Wikidata-Toolkit-0.14.6/.github/workflows/codeql-analysis.yml 0000664 0000000 0000000 00000000603 14447725663 0024213 0 ustar 00root root 0000000 0000000 name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
schedule:
- cron: '32 21 * * 4'
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: github/codeql-action/init@v2
with:
languages: java
- uses: github/codeql-action/autobuild@v2
- uses: github/codeql-action/analyze@v2
Wikidata-Toolkit-0.14.6/.github/workflows/deploy.yml 0000664 0000000 0000000 00000001747 14447725663 0022431 0 ustar 00root root 0000000 0000000 name: Maven Release
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: zulu
java-version: 8
server-id: ossrh
server-username: MAVEN_USERNAME
server-password: MAVEN_PASSWORD
- name: Import GPG Key
run: |
mkdir -p ~/.gnupg/
echo "$MAVEN_SIGNING_KEY" | gpg --import -
env:
MAVEN_SIGNING_KEY: ${{ secrets.MAVEN_SIGNING_KEY }}
- name: Maven Deploy
run: mvn -B -V deploy -Ddeploy
env:
MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
- name: Generate javadocs
run: mvn compile javadoc:aggregate
- name: Publish javadocs
uses: JamesIves/github-pages-deploy-action@v4.4.2
with:
branch: gh-pages
folder: target/site/apidocs
Wikidata-Toolkit-0.14.6/.gitignore 0000664 0000000 0000000 00000001204 14447725663 0016771 0 ustar 00root root 0000000 0000000 *.class
# Package Files #
*.jar
*.war
*.ear
# IntelliJ
.idea/
*.iml
*.ipr
*.iws
# Eclipse
.classpath
.project
.metadata
.settings/
local.properties
# NetBeans
nbbuild/
nbdist/
nbproject/
nb-configuration.xml
nbactions.xml
# Maven, etc.
out/
target/
# WDTK dumpfile download directory
dumpfiles/
# WDTK example result directory
results/
# Don't apply the above to src/ where Java requires
# subdirectories named according to package names.
# We do not want to forbid things like "dumpfiles" in
# package names.
!src/
# Use as directory for local testing code
**/src/local/
# General
*.pyc
*~
*.bak
*.sw[o,p]
*.tmp
.DS_Store
Thumbs.db
Wikidata-Toolkit-0.14.6/LICENSE.txt 0000664 0000000 0000000 00000026135 14447725663 0016636 0 ustar 00root root 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
Wikidata-Toolkit-0.14.6/README.md 0000664 0000000 0000000 00000007724 14447725663 0016275 0 ustar 00root root 0000000 0000000 Wikidata Toolkit
================

[](https://codecov.io/gh/Wikidata/Wikidata-Toolkit)
[](http://search.maven.org/#search|ga|1|g%3A%22org.wikidata.wdtk%22)
[](https://www.openhub.net/p/Wikidata-Toolkit)
Wikidata Toolkit is a Java library for accessing Wikidata and other Wikibase installations. It can be used to create bots, to perform data extraction tasks (e.g., convert all data in Wikidata to a new format), and to do large-scale analyses that are too complex for using a simple SPARQL query service.
Documentation
-------------
* [Wikidata Toolkit homepage](https://www.mediawiki.org/wiki/Wikidata_Toolkit): project homepage with basic user documentation, including guidelines on how to setup your Java IDE for using Maven and git.
* [Wikidata Toolkit examples](https://github.com/Wikidata/Wikidata-Toolkit-Examples): stand-alone Java project that shows how to use Wikidata Toolkit as a library for your own code.
* [Wikidata Toolkit Javadocs](http://wikidata.github.io/Wikidata-Toolkit/): API documentation
License and Credits
-------------------
Authors: [Markus Kroetzsch](http://korrekt.org), [Julian Mendez](https://julianmendez.github.io/), [Fredo Erxleben](https://github.com/fer-rum), [Michael Guenther](https://github.com/guenthermi), [Markus Damm](https://github.com/mardam), [Antonin Delpeuch](http://antonin.delpeuch.eu/), [Thomas Pellissier Tanon](https://thomas.pellissier-tanon.fr/) and [other contributors](https://github.com/Wikidata/Wikidata-Toolkit/graphs/contributors)
License: [Apache 2.0](LICENSE.txt)
The development of Wikidata Toolkit has been partially funded by the Wikimedia Foundation under the [Wikibase Toolkit Individual Engagement Grant](https://meta.wikimedia.org/wiki/Grants:IEG/Wikidata_Toolkit), and by the German Research Foundation (DFG) under [Emmy Noether grant KR 4381/1-1 "DIAMOND"](https://ddll.inf.tu-dresden.de/web/DIAMOND/en).
How to make a release
---------------------
During development, the version number in the `pom.xml` files should be the next version number assuming that the next version is a patch release, followed by `-SNAPSHOT`. For instance, if the last version to have been released was `1.2.3`, then the `pom.xml` files should contain `1.2.4-SNAPSHOT`.
1. Pick the version number for the new release you want to publish, following SemVer. If this is going to be a patch release, it should be the version currently in `pom.xml` without the `-SNAPSHOT` suffix. In the following steps, we will assume this new version is `1.2.4`.
2. Write the new version number in the `pom.xml` files with `mvn versions:set -DnewVersion=1.2.4`
3. Add some release notes in the `RELEASE-NOTES.md` file at the root of the repository
4. Commit the changes: `git commit -am "Set version to 1.2.4"`
5. Add a tag for the version: `git tag -a v1.2.4 -m "Version 1.2.4"`
6. Write the next version number in the `pom.xml` file, by incrementing the patch release number: `mvn versions:set -DnewVersion=1.2.5-SNAPSHOT`
7. Commit the changes: `git commit -am "Set version to 1.2.5-SNAPSHOT"`
8. Push commits and tags: `git push --tags && git push`
9. In GitHub's UI, create a release by going to https://github.com/Wikidata/Wikidata-Toolkit/releases/new. Pick the tag you just created, give a title to the release and quickly describe the changes since the previous release (see existing releases for examples).
10. Update the version number mentioned in https://www.mediawiki.org/wiki/Wikidata_Toolkit
The library is automatically packaged and uploaded to Maven Central by the continuous deployment (with GitHub Actions). So is the HTML version of the javadoc (to GitHub Pages).
Wikidata-Toolkit-0.14.6/RELEASE-NOTES.md 0000664 0000000 0000000 00000041476 14447725663 0017310 0 ustar 00root root 0000000 0000000 Wikidata Toolkit Release Notes
==============================
Version 0.14.6
--------------
Small improvement:
* The new Wikibase editing API returns the id of the revision of the last edit made (#795)
Version 0.14.5
--------------
Bug fixes:
* fetching of MediaInfo entities by title, when they contain a dash (#777)
* clear the CSRF editing token if it is no longer valid (#442)
Version 0.14.4
--------------
Bug fixes:
* fix deserialization of lexemes, workaround for https://phabricator.wikimedia.org/T305660
Version 0.14.3
--------------
Bug fixes:
* fix fetching of Mids from filenames in the case where multiple filenames do not exist (#745)
Version 0.14.2
--------------
Bug fixes:
* add `uselang` as optional parameter for wbsearchentities action (#239)
Version 0.14.1
--------------
Bug fixes:
* fix error handling in newly supported clientLogin method
* fix error in deserialization of properties with unknown datatypes
Deprecations:
* the IRI representation of datatypes in `wdtk-datamodel` is deprecated.
If you rely on it, then use it in `wdtk-rdf`, since this is specific to the RDF
serialization of the datamodel. Use the strings found in the JSON serialization
of properties to identify datatypes instead.
Version 0.14.0
--------------
New feature:
* login to Wikibase via the recommended API for normal login/password login
Bug fixes:
* add explicit dependency to okhttp, to avoid linkage issues
* upgrade to okhttp 4.10.0
Version 0.13.5
--------------
* downgraded okhttp to 4.2.2 to solve a linkage error (issue #600). We anticipate that this will be reverted once a stable version of okhttp 5 is available and a viable way to avoid such a linkage error is found.
Version 0.13.4
--------------
* updated okhttp to 5.0.0-alpha.10 in the hope that it solves a linkage error
* registered the EDTF datatype
Version 0.13.3
--------------
* fixed media type when uploading files to a MediaWiki API endpoint
Version 0.13.2
--------------
* new method to create an EntityDocument independently of its type
* new utility method to execute an authenticated HTTP method which posts files
Version 0.13.1
--------------
Minor changes to the CI configuration for artifact deployment in Maven Central, no changes in the library itself.
Version 0.13.0
--------------
New features:
* New API to edit Wikibase entities
Bug fixes:
* Fetching of non-existent Mids on Commons
* Support for missing entity types in DatamodelConverter
* Store QuantityValue units as ItemIdValue instead of String.
* Allow lexeme lemma list to be empty.
Version 0.12.1
--------------
Bug fixes:
* Allows empty representation list in `FormDocument` to parse the most recent Wikidata dumps.
Version 0.12.0
--------------
Bug fixes:
* Allows empty gloss list in `SenseDocument` to parse the most recent Wikidata dumps.
New features:
* Allows fetching MediaInfo entities using `WikibaseDataFetcher`.
* `WikibaseRevisionProcessor` now parses and exposes redirections between entities.
* `OAuthApiConnection` to connect to Wikibase API using OAuth.
* Allows to fetch the Wikibase edit lag.
* Dump file compression is automatically guessed from the file name extensions.
Incompatible changes:
* More API client errors are now exposed as exception, allowing the API users to act on them.
* `OkHTTP` is now used in wikibaseapi-client and big revamp of the client internals with small breaking changes.
* Deprecated methods removal across the codebase.
Dependency upgrades:
* Dropped unused Apache HTTP client dependency
* Bump RDF4J to 3.6.4, Jackson to 2.12.3, Apache Commons IO to 2.8, Apache Commons Lang3 to 3.12.
Version 0.11.1
--------------
Bug fixes:
* Fixes API connection bug due to lower-case set-cookie header sent from Wikidata
* Upgrades dependencies to latest version
Version 0.11.0
--------------
New features:
* Adds basic MediaInfo representation, API retrieval and editing.
* Adds support of tags when editing using the API.
* Adds UnsupportedValue and UnsupportedEntityIdValue to properly represent unsupported values and entity ids.
* RDF: Fixes datatype lookup for entity ids
RDF: Adds support of Quantity and MonolingualText to the SomeValueSnak and NoValueSnak converters.
* Wikibase API: Throw an exception when credentials have expired.
* Updates RDF4J to 2.5.2, Apache Commons Lang to 3.9 and Apache Commons Compress to 1.18.
* Properly deserialize and store the Reference hash.
* Adds edit methods to Lexeme, Form and Sense.
* Adds timeout options to HTTP calls.
* Adds exponential back-off for maxlag errors.
Incompatible changes:
* Removes the wikibase-client package.
* Makes Statement.getBestStatements return null if there are no best statements.
* Makes RDF output format closer to the one used by Wikibase.
* Throw MediaWikiApiErrorException instead of NullPointerException if the edit token is not found.
Bug fixes:
* Removes main snak value serialization from statement serialization.
* Use CSRF token for logout following MediaWiki API change.
Version 0.10.0
--------------
Security fixes:
* Update Jackson to 2.9.9, fixing [vulnerabilities that might lead to remote code execution](https://www.cvedetails.com/vulnerability-list.php?vendor_id=15866&product_id=42991&version_id=238358&page=1&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=0&cvssscoremax=0&year=0&cweid=0&order=1&trc=12&sha=1a71cae633886fb92e024fafb20c582c9e5b072d).
New features:
* RDF: Adds support of Quantity and MonolingualText to the SomeValueSnak and NoValueSnak converters.
* Wikibase API: Throw an exception when credentials have expired.
* Updates RDF4J to 2.5.2, Apache Commons Lang to 3.9 and Apache Commons Compress to 1.18.
Incompatible changes:
* Propagate IOException properly in the Wikibase API module.
Version 0.9.0
-------------
New features:
* Compatibility with JDK 10
* Compatibility with Android except for the RDF component. It requires Gradle Android plugin 3.0+.
* Addition of basic support for Wikibase Lexemes (including forms and senses)
* The RDF default output is now the same as query.wikidata.org and specified at https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format except normalized values that are not supported.
* Migration from Sesame to RDF4J
* Most of DataModel classes has now with* methods to do easily modification of objects while keeping immutability
* parentRevisionId is now provided by the XML dump files reader
* WikimediaLanguageCodes.fixLanguageCodeIfDeprecated allows to fix deprecated language codes
* StatementGroup (resp. SnakGroup) implements Collection (resp. Collection)
* EntityRedirectDocument object in order to easily represent redirections between entities
* StatementGroup::getBestStatements utility method to retrieve quickly the best statements of the group
* GuidGenerator and an implementation to generate statements uuid easily
* When editing entities, the implementation attempts to use the most granular API call to perform the edit, which makes more informative edit summaries.
* Addition of QuantityValue.getUnitItemId, TimeValue.getCalendarItemId and GlobeCoordinatesValue.getGlobeItemId to get easily ItemIdValue objects for these three fields
* Introduction of DatamodelFilter to split out the filtering capabilities of DatamodelConverter
* ApiConnection was changed to an interface, implemented by BasicApiConnection for normal login and (in the future) OAuthApiConnection for OAuth. BasicApiConnection was made serializable with Jackson so that a connection can be saved and restored.
Bug fixes:
* Retrieval of redirected entities using WbGetEntitiesAction should work
* StatementUpdate avoids to do null edits except if intentionally asked so
* The WikimediaLanguageCodes lists have been updated
* Proper RDF serialization of the Commons GeoShape and Commons Data datatypes
Incompatible changes:
* Support for JDK 7 is dropped.
* The simple data model implementation has been dropped. The Jackson based implementation is now the only one provided by the library. It allows to avoid to maintain two implementations and the cost of conversion between the two representations. The jackson implementation has been moved to the former one package.
* Migration from Sesame to RDF4J in the RDF component interface
* Updates of various dependencies
* The utility classes related to JSON (de)serialization are now private
* SiteLink badges are now ItemIdValue and not String
* The internal encoding of uniteless QuantityValue unit is now "1" and not "" for consistency with Wikibase
* The default value for the "after" parameter of TimeValues is no 0 for compatibility with Wikibase
* DatatypeIdValue is not implementing Value anymore. It improves type safety because Wikibase does not allow to use DatatypeIdValue as snak value.
* The DatamodelConverter class does not do shallow copy anymore. Please use DatamodelFilter for filtering
* The constraint TemplateParser related code have been removed. Constraints are now encoded as statements in Wikidata, making this code only usable in old dumps
* The TimeValue timestamps are now serializing years with at least 4 digits and not 11. This replicates a change in Wikibase and make the output timestamps more similar to the ISO/XSD ones.
Version 0.8.0
-------------
New features:
* Compatibility with JDK 9
* Allow to edit labels, descriptions and aliases using the WikibaseDataEditor (this is a work in progress that is likely to change)
* Allow to use the wbEntitySearch API action using WikibaseDataFetcher
* Quantities bounds are now optional following the change in Wikibase
* Add the "id" field to entity id JSON serialization following the change in Wikibase
Bug fixes:
* Do not fail when logging in
* Do not fail when reading redirections in daily XML dumps
* Do not fail when new datatypes are introduced in Wikibase
* Make sure that API warnings are read for all requests
* Do not fail when reading a bz2 compressed dump when a gzip dump was expected
* WikibaseDataFetcher is now able to retrieve more than 50 entities at once
* Switch to the new way of retrieving MediaWiki API tokens
Version 0.7.0
-------------
New features:
* Add a new client action "sqid" that analyses dumps to create the statistics
JSON files that are the basis for the SQID Wikidata Browser that is found at
https://tools.wmflabs.org/sqid/
Bug fixes:
* Fix JavaDoc errors to enable build using Java 8 (with doclint)
* Make JSON parser more tolerant towards unknown keys; avoids breaking on recent API changes
* Update Wikimedia dump location to https so that dump downloads work again
Version 0.6.0
-------------
A new stand-alone example project is now showing how to use WDTK as a library:
https://github.com/Wikidata/Wikidata-Toolkit-Examples
New features:
* Support for new Wikidata property type "external identifier"
* Support for new Wikidata property type "math"
* Bots: support maxlag parameter and edit-rate throttling
* Bots: better Wikidata API error handling
* Bots: several real-world bot examples
* New convenience methods for accessing Wikidata Java objects, for simpler code
* full compatibility with Java 8
Bug fixes:
* Fix NullPointerException when trying to establish API connection (issue #217)
* Avoid test failures on some platforms (based on too strict assumptions)
Version 0.5.0
-------------
New features:
* Support for reading and writing live entity data from wikidata.org or any other Wikibase site (issue #162)
* New examples for illustrating read/write API support
* Support for quantities with units of measurement (new feature in Wikibase; still beta)
* New builder classes to simplify construction of EntityDocuments, Statements, and References
* Support processing of local dump files by file name in code and command-line client (issue #136)
* New example WorldMapProcessor that shows the generation of maps from geographic data
* Improved output file naming for examples, taking dump date into account
* RDF export uses property register for fewer Web requests during export
* RDF export supports P1921 URI patterns to create links to external RDF datasets
Bug fixes:
* JSON conversion action of the command-line client was forgetting start of entity list.
* Update URLs to use https instead of http
* Support URLs in sites table that are not protocol-relative (issue #163)
Incompatible changes:
* EntityDocumentProcessorFilter has a modified constructor that requires a filter object
to be given. The direct set methods to define the filter are no longer available.
Version 0.4.0
-------------
New features:
* Support statements on property documents
* More robust JSON parsing: recover after errors to process remaining file
* Improved JSON serialization + an example program showing how to do it
* Standard (POJO) datamodel implementation now is Serializable
* Deep copy functionality for changing between datamodel implementations (DatamodelConverter)
* Support for filtering data during copying (e.g., to keep only some languages/properties/sites).
* Support arbitrary precision values in globe coordinates
* Dependency on JSON.org has been removed to use the faster Jackson library everywhere
Bug fixes:
* Support RDF export of Monolingual Text Value data in statements.
* Significant performance improvements in RDF export of taxonomy data.
* Support new Wikimedia Foundation dump file index HTML format (Issue #114)
Incompatible changes:
* The datatype of all values in GlobeCoordinateValue (latitude, longitude, precision) has
changed from long (fixed precision number) to double (floating point number) to match the JSON.
* The JSON serializer class org.wikidata.wdtk.datamodel.json.JsonSerializer has vanished. It is
replaced by the org.wikidata.wdtk.datamodel.json.jackson.JsonSerializer (almost same interface).
Version 0.3.0
-------------
New features:
* Added full support for reading data from the API JSON format (now used in all dumps);
reading JSON dumps also became much faster with this change
* Improved examples (more, faster, easier-to-read programs); documentation on each
example is now found in the Readme.md file in the example package
* Added iterator access to all statements of an item document, all statements in a statement
group, all qualifiers in a claim, all snaks in a snak group, and all snaks in a reference
* Dump files are downloaded to temporary files first to prevent incomplete downloads
from causing errors
* Datamodel objects can now be constructed using the static methods of Datamodel. This makes
object creation more convenient.
Minor changes:
* ItemIdValue and PropertyIdValue objects now have a "site IRI" that can be retrieved.
This was called "base IRI" in earlier releases and was only used to construct the full
IRI. The new concept is that this IRI is actually the identifier for the site that the
entity comes from. It is important to make it retrievable since it is needed (like in
previous versions) to construct the object using the factory.
* A new helper package in the datamodel module contains common hashCode(), equals(), and
toString() methods that can be used by any datamodel implementation.
Bug fixes:
* Fix grouping of Statements when reading data from dumps (Issue #78)
Version 0.2.0
-------------
New features:
* Support for serializing Wikibase data in RDF (as illustrated in new example);
see http://korrekt.org/page/Introducing_Wikidata_to_the_Linked_Data_Web for details
* Simplified code for dump file processing: new helper class DumpProcessingController
* Support for resolving site links, based on information from the sites table dump
(as demonstrated in a new example program)
* Support for SnakGroups (data model updated to group Snaks by property in all lists)
* Support for serializing Wikibase data in JSON (as illustrated in new example)
Bug fixes:
* Support changed Wikimedia dump HTML page format, which caused download to fail (Issue #70)
* Support processing of property documents when parsing dumps (Issue #67)
* Support SomeValueSnak and NoValueSnak in references (Issue #44)
* Use correct site links when importing data from dumps (Issue #37)
* Do not attempt to download unfinished dump files (Issue #63)
Incompatible changes:
* The processing of dumpfiles was simplified, using a new class DumpProcessingController.
The former method WmfDumpFileManager#processRecentRevisionDumps() was replaced by
DumpProcessingController#processAllRecentRevisionDumps(). See the examples for example
code.
* Dump files no longer support the retrieval of the maximal revision id, since this
information is no longer published for the main dumps on the Wikimedia site.
Version 0.1.0
-------------
New features:
* Initial Java implementation of Wikibase datamodel
* Support for downloading Wikimedia dumpfiles
* Support for parsing MediaWiki XML dumps
* Support for parsing Wikibase dump contents to get entity data
* Example Java program shows how to process Wikidata dump files
Bug fixes:
* not applicable; this is the very first release
Know issues:
* Entities loaded from dump get wrong base IRI (issue #43)
* URLs for sitelinks are missing (issue #37)
Wikidata-Toolkit-0.14.6/pom.xml 0000664 0000000 0000000 00000022620 14447725663 0016323 0 ustar 00root root 0000000 0000000
4.0.0org.wikidata.wdtkwdtk-parent0.14.6pomWikidata ToolkitA Java-based library for working with Wikidata and Wikibasehttps://www.mediawiki.org/wiki/Wikidata_Toolkitwdtk-datamodelwdtk-dumpfileswdtk-storagewdtk-wikibaseapiwdtk-utilwdtk-testingwdtk-exampleswdtk-distributionwdtk-rdfApache License, Version 2.0http://www.apache.org/licenses/LICENSE-2.0.txt2014Wikidata Toolkit DevelopersmarkusMarkus Kroetzschmarkus@semantic-mediawiki.orgjulianJulian Mendezjulian.mendez@tu-dresden.defer-rumFredo Erxlebenfredo.erxleben@tu-dresden.demichaelMichael Güntherguenthermi50@yahoo.detptThomas Pellissier Tanonthomas@pellissier-tanon.frwetnebAntonin Delpeuchantonin@delpeuch.euUTF-81.23.03.12.02.13.02.15.24.13.22.24.11.03.7.72.0.71.7.21.1.04.11.0junitjunit${junitVersion}testorg.hamcresthamcrest-core${hamcrestVersion}testorg.mockitomockito-core${mockitoVersion}testorg.slf4jslf4j-api${slf4jVersion}org.apache.commonscommons-lang3${apacheCommonsLangVersion}org.codehaus.mojolicense-maven-plugin2.1.0firstupdate-file-headerupdate-project-licenseprocess-sourcesapache_v2src/main/javasrc/test/javaorg.eclipse.m2elifecycle-mapping1.0.0org.codehaus.mojolicense-maven-plugin[1.2,)update-project-licenseupdate-file-headerorg.codehaus.mojolicense-maven-pluginorg.apache.maven.pluginsmaven-compiler-plugin3.11.088org.eluder.coverallscoveralls-maven-plugin4.3.0javax.xml.bindjaxb-api2.3.1org.jacocojacoco-maven-plugin0.8.10prepare-agentprepare-agentorg.apache.maven.pluginsmaven-source-plugin3.3.0attach-sourcesjar-no-forkorg.apache.maven.pluginsmaven-javadoc-plugin3.5.0
Wikidata Toolkit homepage]]>8attach-javadocsjarorg.sonatype.pluginsnexus-staging-maven-plugin1.6.13trueossrhhttps://oss.sonatype.org/trueorg.apache.maven.pluginsmaven-gpg-plugin3.1.0sign-artifactsverifysignorg.apache.maven.pluginsmaven-scm-publish-plugin3.2.1${project.build.directory}/scmpublishPublishing javadoc for ${project.artifactId}:${project.version}${project.reporting.outputDirectory}/apidocsscm:git:https://github.com/Wikidata/Wikidata-Toolkit.gitgh-pageshttps://github.com/Wikidata/Wikidata-Toolkit.gitscm:git:https://github.com/Wikidata/Wikidata-Toolkit.gitscm:git:https://github.com/Wikidata/Wikidata-Toolkit.gitossrhhttps://oss.sonatype.org/content/repositories/snapshotsossrhCentral Repository OSSRHhttps://oss.sonatype.org/service/local/staging/deploy/maven2/
Wikidata-Toolkit-0.14.6/wdtk-datamodel/ 0000775 0000000 0000000 00000000000 14447725663 0017705 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/LICENSE.txt 0000664 0000000 0000000 00000026135 14447725663 0021537 0 ustar 00root root 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
Wikidata-Toolkit-0.14.6/wdtk-datamodel/pom.xml 0000664 0000000 0000000 00000004020 14447725663 0021216 0 ustar 00root root 0000000 0000000 4.0.0org.wikidata.wdtkwdtk-parent0.14.6wdtk-datamodeljarWikidata Toolkit Data ModelJava implementation of the Wikibase data model${project.groupId}wdtk-testing${project.version}test${project.groupId}wdtk-util${project.version}com.fasterxml.jackson.corejackson-annotations${jacksonVersion}com.fasterxml.jackson.corejackson-core${jacksonVersion}com.fasterxml.jackson.corejackson-databind${jacksonVersion}com.fasterxml.jackson.datatypejackson-datatype-jdk8${jacksonVersion}org.threetenthreeten-extra${threetenVersion}commons-iocommons-io${apacheCommonsIOVersion}testsrc/test/resources
Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/ 0000775 0000000 0000000 00000000000 14447725663 0020474 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/ 0000775 0000000 0000000 00000000000 14447725663 0021420 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/ 0000775 0000000 0000000 00000000000 14447725663 0022341 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/ 0000775 0000000 0000000 00000000000 14447725663 0023130 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/ 0000775 0000000 0000000 00000000000 14447725663 0024725 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/ 0000775 0000000 0000000 00000000000 14447725663 0025676 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/ 0000775 0000000 0000000 00000000000 14447725663 0027630 5 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/ 0000775 0000000 0000000 00000000000 14447725663 0031272 5 ustar 00root root 0000000 0000000 AbstractDataObjectBuilder.java 0000664 0000000 0000000 00000004012 14447725663 0037046 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
import org.wikidata.wdtk.datamodel.implementation.DataObjectFactoryImpl;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import org.wikidata.wdtk.datamodel.interfaces.DataObjectFactory;
/**
* Abstract base class for all builder objects that create data model objects.
*
* @author Markus Kroetzsch
*
* @param
* the type of the eventual concrete builder implementation
* @param
* the type of the object that is being built
*/
public abstract class AbstractDataObjectBuilder, O> {
static DataObjectFactory factory = new DataObjectFactoryImpl();
private boolean isBuilt = false;
/**
* Returns the object that has been built.
*
* @return constructed object
* @throws IllegalStateException
* if the object was built already
*/
public abstract O build();
/**
* Checks if the object has already been built, and throws an exception if
* yes. If no, then the object is recorded as having been built.
*
* @throws IllegalStateException
* if the object was built already
*/
protected void prepareBuild() {
if (this.isBuilt) {
throw new IllegalStateException("The entity has been built");
}
this.isBuilt = true;
}
/**
* Returns the current object with the correct builder type.
*
* @return this
*/
abstract protected T getThis();
}
AliasUpdateBuilder.java 0000664 0000000 0000000 00000020520 14447725663 0035560 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
/**
* Builder for incremental construction of {@link AliasUpdate} objects.
*/
public class AliasUpdateBuilder {
private String languageCode;
private final List base;
private List recreated;
private final List added = new ArrayList<>();
private final Set removed = new HashSet<>();
private AliasUpdateBuilder(List base) {
if (base != null) {
for (MonolingualTextValue alias : base) {
Objects.requireNonNull(alias, "Base document aliases cannot be null.");
}
Validate.isTrue(
base.stream().map(v -> v.getLanguageCode()).distinct().count() <= 1,
"Base document aliases must have the same language code.");
Validate.isTrue(base.stream().distinct().count() == base.size(), "Base document aliases must be unique.");
this.base = new ArrayList<>(base);
languageCode = base.stream().map(v -> v.getLanguageCode()).findFirst().orElse(null);
} else
this.base = null;
}
/**
* Creates new builder object for constructing alias update.
*
* @return update builder object
*/
public static AliasUpdateBuilder create() {
return new AliasUpdateBuilder(null);
}
/**
* Creates new builder object for constructing update of given base revision
* aliases. Provided aliases will be used to check correctness of changes.
*
* Since all changes will be checked after the {@link AliasUpdate} is passed to
* {@link TermedDocumentUpdateBuilder} anyway, it is usually unnecessary to use
* this method. It is simpler to initialize the builder with {@link #create()}.
*
* @param aliases
* aliases from base revision of the document
* @return update builder object
* @throws NullPointerException
* if {@code aliases} or any of its items is {@code null}
* @throws IllegalArgumentException
* if there are duplicate items in {@code aliases}
*/
public static AliasUpdateBuilder forAliases(List aliases) {
Objects.requireNonNull(aliases, "Base document alias collection cannot be null.");
return new AliasUpdateBuilder(aliases);
}
/**
* Adds new alias. This operation can be repeated to add multiple aliases in one
* update. It can be combined with {@link #remove(MonolingualTextValue)}.
* Attempt to add the same alias twice or to add alias already present in base
* document (if available) is silently ignored. Adding previously removed alias
* cancels the removal. If {@link #recreate(List)} was called before, this
* method will add the alias to the end of the new alias list.
*
* @param alias
* new alias
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code alias} is {@code null}
* @throws IllegalArgumentException
* if the alias has language code inconsistent with other aliases
*/
public AliasUpdateBuilder add(MonolingualTextValue alias) {
Objects.requireNonNull(alias, "Alias cannot be null.");
if (languageCode != null) {
Validate.isTrue(languageCode.equals(alias.getLanguageCode()), "Inconsistent language codes.");
}
if (recreated != null) {
if (!recreated.contains(alias)) {
recreated.add(alias);
if (recreated.equals(base)) {
recreated = null;
}
}
} else if (removed.contains(alias)) {
removed.remove(alias);
} else if (!added.contains(alias) && (base == null || !base.contains(alias))) {
added.add(alias);
}
languageCode = alias.getLanguageCode();
return this;
}
/**
* Removed existing alias. This operation can be repeated to remove multiple
* aliases in one update. It can be combined with
* {@link #add(MonolingualTextValue)}. Attempt to remove the same alias twice or
* to remove alias not present in base document (if available) is silently
* ignored. Removing previously added alias cancels the addition. If
* {@link #recreate(List)} was called before, this method will remove the alias
* from the new alias list.
*
* @param alias
* removed alias
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code alias} is {@code null}
* @throws IllegalArgumentException
* if the alias has language code inconsistent with other aliases
*/
public AliasUpdateBuilder remove(MonolingualTextValue alias) {
Objects.requireNonNull(alias, "Alias cannot be null.");
if (languageCode != null) {
Validate.isTrue(languageCode.equals(alias.getLanguageCode()), "Inconsistent language codes.");
}
if (recreated != null) {
recreated.remove(alias);
if (recreated.equals(base)) {
recreated = null;
}
} else if (added.contains(alias)) {
added.remove(alias);
} else if (!removed.contains(alias) && (base == null || base.contains(alias))) {
removed.add(alias);
}
languageCode = alias.getLanguageCode();
return this;
}
/**
* Replaces current alias list with completely new alias list. Any previous
* changes are discarded. To remove all aliases, pass empty list to this method.
* If the new alias list is identical (including order) to base document alias
* list (if provided), the update will be empty.
*
* @param aliases
* new list of aliases
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code aliases} or any of its items is {@code null}
* @throws IllegalArgumentException
* if some alias has inconsistent language code or there are
* duplicates
*/
public AliasUpdateBuilder recreate(List aliases) {
Objects.requireNonNull(aliases, "Alias list cannot be null.");
for (MonolingualTextValue alias : aliases) {
Objects.requireNonNull(alias, "Aliases cannot be null.");
}
Validate.isTrue(
aliases.stream().map(v -> v.getLanguageCode()).distinct().count() <= 1,
"Aliases must have the same language code.");
Validate.isTrue(
aliases.stream().map(v -> v.getText()).distinct().count() == aliases.size(),
"All aliases must be unique.");
if (languageCode != null && !aliases.isEmpty()) {
Validate.isTrue(languageCode.equals(aliases.get(0).getLanguageCode()), "Inconsistent language codes.");
}
added.clear();
removed.clear();
if (!aliases.equals(base)) {
recreated = new ArrayList<>(aliases);
} else {
recreated = null;
}
if (!aliases.isEmpty()) {
languageCode = aliases.get(0).getLanguageCode();
}
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes are
* performed as if by calling {@link #add(MonolingualTextValue)},
* {@link #remove(MonolingualTextValue)}, and {@link #recreate(List)} methods.
*
* @param update
* alias update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public AliasUpdateBuilder append(AliasUpdate update) {
Objects.requireNonNull(update, "Alias update cannot be null.");
update.getRecreated().ifPresent(this::recreate);
for (MonolingualTextValue alias : update.getRemoved()) {
remove(alias);
}
for (MonolingualTextValue alias : update.getAdded()) {
add(alias);
}
return this;
}
/**
* Creates new {@link AliasUpdate} object with contents of this builder object.
*
* @return constructed object
*/
public AliasUpdate build() {
return Datamodel.makeAliasUpdate(recreated, added, removed);
}
}
DataFormatter.java 0000664 0000000 0000000 00000004466 14447725663 0034625 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import java.math.BigDecimal;
import java.text.DecimalFormat;
import org.wikidata.wdtk.datamodel.interfaces.TimeValue;
/**
* This class contains static methods to create string notations for values of
* several datatypes and classes.
*
* @author Michael Günther
*
*/
public class DataFormatter {
final static String FORMAT_YEAR = "00000000000";
final static String FORMAT_OTHER = "00";
/**
* Returns a representation of the date from the value attributes as ISO
* 8601 encoding.
*
* @param value
* @return ISO 8601 value (String)
*/
public static String formatTimeISO8601(TimeValue value) {
StringBuilder builder = new StringBuilder();
DecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR);
DecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER);
if (value.getYear() > 0) {
builder.append("+");
}
builder.append(yearForm.format(value.getYear()));
builder.append("-");
builder.append(timeForm.format(value.getMonth()));
builder.append("-");
builder.append(timeForm.format(value.getDay()));
builder.append("T");
builder.append(timeForm.format(value.getHour()));
builder.append(":");
builder.append(timeForm.format(value.getMinute()));
builder.append(":");
builder.append(timeForm.format(value.getSecond()));
builder.append("Z");
return builder.toString();
}
/**
* Returns a signed string representation of the given number.
*
* @param number
* @return String for BigDecimal value
*/
public static String formatBigDecimal(BigDecimal number) {
if (number.signum() != -1) {
return "+" + number.toString();
} else {
return number.toString();
}
}
}
Datamodel.java 0000664 0000000 0000000 00000134377 14447725663 0033767 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.wikidata.wdtk.datamodel.implementation.DataObjectFactoryImpl;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.Claim;
import org.wikidata.wdtk.datamodel.interfaces.DataObjectFactory;
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormUpdate;
import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemUpdate;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LexemeUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyUpdate;
import org.wikidata.wdtk.datamodel.interfaces.QuantityValue;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SenseUpdate;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
import org.wikidata.wdtk.datamodel.interfaces.Snak;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.interfaces.StatementRank;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StringValue;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TimeValue;
import org.wikidata.wdtk.datamodel.interfaces.Value;
import org.wikidata.wdtk.datamodel.interfaces.ValueSnak;
/**
* This class contains static methods to create WDTK data objects. This is the
* preferred way of creating data objects in WDTK.
*
* @author Markus Kroetzsch
*/
public class Datamodel {
/**
* The site IRI of Wikidata.
*/
static final public String SITE_WIKIDATA = "http://www.wikidata.org/entity/";
/**
* The site IRI of Wikimedia Commons.
*/
static final public String SITE_WIKIMEDIA_COMMONS = "http://commons.wikimedia.org/entity/";
private final static DataObjectFactory factory = new DataObjectFactoryImpl();
/**
* Creates an {@link ItemIdValue}.
*
* @param id
* a string of the form Qn... where n... is the string
* representation of a positive integer number
* @param siteIri
* IRI to identify the site, usually the first part of the entity
* IRI of the site this belongs to, e.g.,
* "http://www.wikidata.org/entity/"
* @return an {@link ItemIdValue} corresponding to the input
*/
public static ItemIdValue makeItemIdValue(String id, String siteIri) {
return factory.getItemIdValue(id, siteIri);
}
/**
* Creates an {@link ItemIdValue} for Wikidata.
*
* @param id
* a string of the form Qn... where n... is the string
* representation of a positive integer number
* @return an {@link ItemIdValue} corresponding to the input
*/
public static ItemIdValue makeWikidataItemIdValue(String id) {
return factory.getItemIdValue(id, SITE_WIKIDATA);
}
/**
* Creates a {@link PropertyIdValue}.
*
* @param id
* a string of the form Pn... where n... is the string
* representation of a positive integer number
* @param siteIri
* IRI to identify the site, usually the first part of the entity
* IRI of the site this belongs to, e.g.,
* "http://www.wikidata.org/entity/"
* @return a {@link PropertyIdValue} corresponding to the input
*/
public static PropertyIdValue makePropertyIdValue(String id, String siteIri) {
return factory.getPropertyIdValue(id, siteIri);
}
/**
* Creates a {@link PropertyIdValue}.
*
* @param id
* a string of the form Pn... where n... is the string
* representation of a positive integer number
* @return a {@link PropertyIdValue} corresponding to the input
*/
public static PropertyIdValue makeWikidataPropertyIdValue(String id) {
return factory.getPropertyIdValue(id, SITE_WIKIDATA);
}
/**
* Creates an {@link LexemeIdValue}.
*
* @param id
* a string of the form Ln... where n... is the string
* representation of a positive integer number
* @param siteIri
* IRI to identify the site, usually the first part of the entity
* IRI of the site this belongs to, e.g.,
* "http://www.wikidata.org/entity/"
* @return an {@link LexemeIdValue} corresponding to the input
*/
public static LexemeIdValue makeLexemeIdValue(String id, String siteIri) {
return factory.getLexemeIdValue(id, siteIri);
}
/**
* Creates an {@link LexemeIdValue} for Wikidata.
*
* @param id
* a string of the form Ln... where n... is the string
* representation of a positive integer number
* @return an {@link LexemeIdValue} corresponding to the input
*/
public static LexemeIdValue makeWikidataLexemeIdValue(String id) {
return factory.getLexemeIdValue(id, SITE_WIKIDATA);
}
/**
* Creates an {@link FormIdValue}.
*
* @param id
* a string of the form Ln...-Fm... where n... and m... are the string
* representation of a positive integer number
* @param siteIri
* IRI to identify the site, usually the first part of the entity
* IRI of the site this belongs to, e.g.,
* "http://www.wikidata.org/entity/"
* @return an {@link FormIdValue} corresponding to the input
*/
public static FormIdValue makeFormIdValue(String id, String siteIri) {
return factory.getFormIdValue(id, siteIri);
}
/**
* Creates an {@link FormIdValue} for Wikidata.
*
* @param id
* a string of the form Ln...-F... where n... and m... are the string
* representation of a positive integer number
* @return an {@link FormIdValue} corresponding to the input
*/
public static FormIdValue makeWikidataFormIdValue(String id) {
return factory.getFormIdValue(id, SITE_WIKIDATA);
}
/**
* Creates an {@link SenseIdValue}.
*
* @param id
* a string of the form Ln...-Sm... where n... and m... are the string
* representation of a positive integer number
* @param siteIri
* IRI to identify the site, usually the first part of the entity
* IRI of the site this belongs to, e.g.,
* "http://www.wikidata.org/entity/"
* @return an {@link SenseIdValue} corresponding to the input
*/
public static SenseIdValue makeSenseIdValue(String id, String siteIri) {
return factory.getSenseIdValue(id, siteIri);
}
/**
* Creates an {@link SenseIdValue} for Wikidata.
*
* @param id
* a string of the form Ln...-S... where n... and m... are the string
* representation of a positive integer number
* @return an {@link SenseIdValue} corresponding to the input
*/
public static SenseIdValue makeWikidataSenseIdValue(String id) {
return factory.getSenseIdValue(id, SITE_WIKIDATA);
}
/**
* Creates an {@link MediaInfoIdValue}.
*
* @param id
* a string of the form Mn... where n... is the string
* representation of a positive integer number
* @param siteIri
* IRI to identify the site, usually the first part of the entity
* IRI of the site this belongs to, e.g.,
* "http://www.wikidata.org/entity/"
* @return an {@link MediaInfoIdValue} corresponding to the input
*/
public static MediaInfoIdValue makeMediaInfoIdValue(String id, String siteIri) {
return factory.getMediaInfoIdValue(id, siteIri);
}
/**
* Creates an {@link MediaInfoIdValue} for Wikimedia Commons.
*
* @param id
* a string of the form Mn... where n... is the string
* representation of a positive integer number
* @return an {@link MediaInfoIdValue} corresponding to the input
*/
public static MediaInfoIdValue makeWikimediaCommonsMediaInfoIdValue(String id) {
return factory.getMediaInfoIdValue(id, SITE_WIKIMEDIA_COMMONS);
}
/**
* Creates a {@link DatatypeIdValue}. The datatype IRI is usually one of the
* constants defined in {@link DatatypeIdValue}, but this is not enforced,
* since there might be extensions that provide additional types.
*
* @param id
* the IRI string that identifies the datatype
* @return a {@link DatatypeIdValue} corresponding to the input
* @deprecated use {@link #makeDatatypeIdValueFromJsonString(String)}
*/
public static DatatypeIdValue makeDatatypeIdValue(String id) {
return factory.getDatatypeIdValue(id);
}
/**
* Creates a {@link DatatypeIdValue}. The string is an identifier used in
* the JSON serialization of properties to identify the datatype, and is one
* of the constants defined in {@link DatatypeIdValue}, but this is not enforced,
* since there are extensions that provide additional types.
*
* @param jsonString
* the string that identifies the datatype
* @return a {@link DatatypeIdValue} corresponding to the input
*/
public static DatatypeIdValue makeDatatypeIdValueFromJsonString(String jsonString) {
return factory.getDatatypeIdValueFromJsonId(jsonString);
}
/**
* Creates a {@link TimeValue}.
*
* @param year
* a year number, where 0 refers to 1BCE
* @param month
* a month number between 1 and 12
* @param day
* a day number between 1 and 31
* @param hour
* an hour number between 0 and 23
* @param minute
* a minute number between 0 and 59
* @param second
* a second number between 0 and 60 (possible leap second)
* @param precision
* a value in the range of {@link TimeValue#PREC_DAY}, ...,
* {@link TimeValue#PREC_1GY}
* @param beforeTolerance
* non-negative integer tolerance before the value; see
* {@link TimeValue#getBeforeTolerance()}
* @param afterTolerance
* non-zero, positive integer tolerance before the value; see
* {@link TimeValue#getAfterTolerance()}
* @param timezoneOffset
* offset in minutes that should be applied when displaying this
* time
* @param calendarModel
* the IRI of the calendar model preferred when displaying the
* date; usually {@link TimeValue#CM_GREGORIAN_PRO} or
* {@link TimeValue#CM_JULIAN_PRO}
* @return a {@link TimeValue} corresponding to the input
*/
public static TimeValue makeTimeValue(long year, byte month, byte day,
byte hour, byte minute, byte second, byte precision,
int beforeTolerance, int afterTolerance, int timezoneOffset,
String calendarModel) {
return factory.getTimeValue(year, month, day, hour, minute, second,
precision, beforeTolerance, afterTolerance, timezoneOffset,
calendarModel);
}
/**
* Creates a {@link TimeValue} for a given date and time. The precision is
* automatically set to {@link TimeValue#PREC_SECOND}.
*
* @param year
* a year number, where 0 refers to 1BCE
* @param month
* a month number between 1 and 12
* @param day
* a day number between 1 and 31
* @param hour
* an hour number between 0 and 23
* @param minute
* a minute number between 0 and 59
* @param second
* a second number between 0 and 60 (possible leap second)
* @param timezoneOffset
* offset in minutes that should be applied when displaying this
* time
* @param calendarModel
* the IRI of the calendar model preferred when displaying the
* date; usually {@link TimeValue#CM_GREGORIAN_PRO} or
* {@link TimeValue#CM_JULIAN_PRO}
* @return a {@link TimeValue} corresponding to the input
*/
public static TimeValue makeTimeValue(long year, byte month, byte day,
byte hour, byte minute, byte second, int timezoneOffset,
String calendarModel) {
return factory.getTimeValue(year, month, day, hour, minute, second,
TimeValue.PREC_SECOND, 0, 0, timezoneOffset, calendarModel);
}
/**
* Creates a {@link TimeValue} for a given date. The precision is
* automatically set to {@link TimeValue#PREC_DAY}.
*
* @param year
* a year number, where 0 refers to 1BCE
* @param month
* a month number between 1 and 12
* @param day
* a day number between 1 and 31
* @param calendarModel
* the IRI of the calendar model preferred when displaying the
* date; usually {@link TimeValue#CM_GREGORIAN_PRO} or
* {@link TimeValue#CM_JULIAN_PRO}
* @return a {@link TimeValue} corresponding to the input
*/
public static TimeValue makeTimeValue(long year, byte month, byte day,
String calendarModel) {
return factory.getTimeValue(year, month, day, (byte) 0, (byte) 0,
(byte) 0, TimeValue.PREC_DAY, 0, 0, 0, calendarModel);
}
/**
* Creates a {@link GlobeCoordinatesValue}.
*
* @param latitude
* the latitude of the coordinates in degrees
* @param longitude
* the longitude of the coordinates in degrees
* @param precision
* the precision of the coordinates in degrees
* @param globeIri
* IRI specifying the celestial objects of the coordinates
* @return a {@link GlobeCoordinatesValue} corresponding to the input
*/
public static GlobeCoordinatesValue makeGlobeCoordinatesValue(
double latitude, double longitude, double precision, String globeIri) {
return factory.getGlobeCoordinatesValue(latitude, longitude, precision,
globeIri);
}
/**
* Creates a {@link StringValue}.
*
* @param string
* @return a {@link StringValue} corresponding to the input
*/
public static StringValue makeStringValue(String string) {
return factory.getStringValue(string);
}
/**
* Creates a {@link MonolingualTextValue}.
*
* @param text
* the text of the value
* @param languageCode
* the language code of the value
* @return a {@link MonolingualTextValue} corresponding to the input
*/
public static MonolingualTextValue makeMonolingualTextValue(String text,
String languageCode) {
return factory.getMonolingualTextValue(text, languageCode);
}
/**
* Creates a {@link QuantityValue}.
*
* @param numericValue
* the numeric value of this quantity
* @param lowerBound
* the lower bound of the numeric value of this quantity
* @param upperBound
* the upper bound of the numeric value of this quantity
* @param unit
* the unit identifier to use for this quantity
* @return a {@link QuantityValue} corresponding to the input
*/
public static QuantityValue makeQuantityValue(BigDecimal numericValue,
BigDecimal lowerBound, BigDecimal upperBound, ItemIdValue unit) {
return factory.getQuantityValue(numericValue, lowerBound, upperBound,
unit);
}
/**
* Creates a {@link QuantityValue} without bounds.
*
* @param numericValue
* the numeric value of this quantity
* @param unit
* the unit identifier to use for this quantity
* @return a {@link QuantityValue} corresponding to the input
*/
public static QuantityValue makeQuantityValue(BigDecimal numericValue, ItemIdValue unit) {
return factory.getQuantityValue(numericValue, unit);
}
/**
* Creates a {@link QuantityValue} with an empty unit.
*
* @param numericValue
* the numeric value of this quantity
* @param lowerBound
* the lower bound of the numeric value of this quantity
* @param upperBound
* the upper bound of the numeric value of this quantity
* @return a {@link QuantityValue} corresponding to the input
*/
public static QuantityValue makeQuantityValue(BigDecimal numericValue,
BigDecimal lowerBound, BigDecimal upperBound) {
return factory.getQuantityValue(numericValue, lowerBound, upperBound);
}
/**
* Creates a {@link QuantityValue} with an empty unit and without bounds.
*
* @param numericValue
* the numeric value of this quantity
* @return a {@link QuantityValue} corresponding to the input
*/
public static QuantityValue makeQuantityValue(BigDecimal numericValue) {
return factory.getQuantityValue(numericValue);
}
/**
* Creates a {@link QuantityValue} from long numbers.
*
* @param numericValue
* the numeric value of this quantity
* @param lowerBound
* the lower bound of the numeric value of this quantity
* @param upperBound
* the upper bound of the numeric value of this quantity
* @return a {@link QuantityValue} corresponding to the input
*/
public static QuantityValue makeQuantityValue(long numericValue,
long lowerBound, long upperBound) {
return factory.getQuantityValue(new BigDecimal(numericValue),
new BigDecimal(lowerBound), new BigDecimal(upperBound));
}
/**
* Creates a {@link ValueSnak}.
*
* @param propertyId
* @param value
* @return a {@link ValueSnak} corresponding to the input
*/
public static ValueSnak makeValueSnak(PropertyIdValue propertyId,
Value value) {
return factory.getValueSnak(propertyId, value);
}
/**
* Creates a {@link SomeValueSnak}.
*
* @param propertyId
* @return a {@link SomeValueSnak} corresponding to the input
*/
public static SomeValueSnak makeSomeValueSnak(PropertyIdValue propertyId) {
return factory.getSomeValueSnak(propertyId);
}
/**
* Creates a {@link NoValueSnak}.
*
* @param propertyId
* @return a {@link NoValueSnak} corresponding to the input
*/
public static NoValueSnak makeNoValueSnak(PropertyIdValue propertyId) {
return factory.getNoValueSnak(propertyId);
}
/**
* Creates a {@link SnakGroup}.
*
* @param snaks
* a non-empty list of snaks that use the same property
* @return a {@link SnakGroup} corresponding to the input
*/
public static SnakGroup makeSnakGroup(List extends Snak> snaks) {
return factory.getSnakGroup(snaks);
}
/**
* Creates a {@link Claim}. It might be more convenient to use
* {@link #makeStatement} directly if you want to build a statement.
*
* @param subject
* the subject the Statement refers to
* @param mainSnak
* the main Snak of the Statement
* @param qualifiers
* the qualifiers of the Statement, grouped in SnakGroups
* @return a {@link Claim} corresponding to the input
*/
public static Claim makeClaim(EntityIdValue subject, Snak mainSnak,
List qualifiers) {
return factory.getClaim(subject, mainSnak, qualifiers);
}
/**
* Creates a {@link Reference}. It might be more convenient to use the
* {@link ReferenceBuilder} instead.
*
* @param snakGroups
* list of snak groups
* @return a {@link Reference} corresponding to the input
*/
public static Reference makeReference(List snakGroups) {
return factory.getReference(snakGroups);
}
/**
* Creates a {@link Statement}. It might be more convenient to use the
* {@link StatementBuilder} instead.
*
* The string id is used mainly for communication with a Wikibase site, in
* order to refer to statements of that site. When creating new statements
* that are not on any site, the empty string can be used.
*
* @param subject
* the subject the Statement refers to
* @param mainSnak
* the main Snak of the Statement
* @param qualifiers
* the qualifiers of the Statement, grouped in SnakGroups
* @param references
* the references for the Statement
* @param rank
* the rank of the Statement
* @param statementId
* the string id of the Statement
* @return a {@link Statement} corresponding to the input
*/
public static Statement makeStatement(EntityIdValue subject, Snak mainSnak,
List qualifiers, List references,
StatementRank rank, String statementId) {
return factory.getStatement(subject, mainSnak, qualifiers, references, rank, statementId);
}
/**
* Creates a {@link Statement}. It might be more convenient to use the
* {@link StatementBuilder} instead.
*
* The string id is used mainly for communication with a Wikibase site, in
* order to refer to statements of that site. When creating new statements
* that are not on any site, the empty string can be used.
*
* @param claim
* the main claim the Statement refers to
* @param references
* the references for the Statement
* @param rank
* the rank of the Statement
* @param statementId
* the string id of the Statement
* @return a {@link Statement} corresponding to the input
*/
public static Statement makeStatement(Claim claim,
List references, StatementRank rank,
String statementId) {
return factory.getStatement(claim, references, rank, statementId);
}
/**
* Creates a {@link StatementGroup}.
*
* @param statements
* a non-empty list of statements that use the same subject and
* main-snak property in their claim
* @return a {@link StatementGroup} corresponding to the input
*/
public static StatementGroup makeStatementGroup(List statements) {
return factory.getStatementGroup(statements);
}
/**
* Creates a {@link SiteLink}.
*
* @param title
* the title string of the linked page, including namespace
* prefixes if any
* @param siteKey
* the string key of the site of the linked article
* @param badges
* the list of badges of the linked article
* @return a {@link SiteLink} corresponding to the input
*/
public static SiteLink makeSiteLink(String title, String siteKey,
List badges) {
return factory.getSiteLink(title, siteKey, badges);
}
/**
* Creates a {@link SiteLink} without badges.
*
* @param title
* the title string of the linked page, including namespace
* prefixes if any
* @param siteKey
* the string key of the site of the linked article
* @return a {@link SiteLink} corresponding to the input
*/
public static SiteLink makeSiteLink(String title, String siteKey) {
return factory.getSiteLink(title, siteKey, Collections.emptyList());
}
/**
* Creates an empty {@link PropertyDocument}.
*
* @param propertyId
* the id of the property that data is about
* @param datatypeId
* the datatype of that property
* @return a {@link PropertyDocument} corresponding to the input
*/
public static PropertyDocument makePropertyDocument(PropertyIdValue propertyId, DatatypeIdValue datatypeId) {
return makePropertyDocument(propertyId, Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(), datatypeId);
}
/**
* Creates a {@link PropertyDocument} with empty revision id. It might be
* more convenient to use the {@link PropertyDocumentBuilder} instead.
*
* @param propertyId
* the id of the property that data is about
* @param labels
* the list of labels of this property, with at most one label
* for each language code
* @param descriptions
* the list of descriptions of this property, with at most one
* description for each language code
* @param aliases
* the list of aliases of this property
* @param statementGroups
* the list of statement groups of this item; all of them must
* have the given itemIdValue as their subject
* @param datatypeId
* the datatype of that property
* @return a {@link PropertyDocument} corresponding to the input
*/
public static PropertyDocument makePropertyDocument(
PropertyIdValue propertyId, List labels,
List descriptions,
List aliases,
List statementGroups, DatatypeIdValue datatypeId) {
return makePropertyDocument(propertyId, labels, descriptions, aliases,
statementGroups, datatypeId, 0);
}
/**
* Creates a {@link PropertyDocument}. It might be more convenient to use
* the {@link PropertyDocumentBuilder} instead.
*
* @param propertyId
* the id of the property that data is about
* @param labels
* the list of labels of this property, with at most one label
* for each language code
* @param descriptions
* the list of descriptions of this property, with at most one
* description for each language code
* @param aliases
* the list of aliases of this property
* @param statementGroups
* the list of statement groups of this item; all of them must
* have the given itemIdValue as their subject
* @param datatypeId
* the datatype of that property
* @param revisionId
* the revision ID or 0 if not known; see
* {@link EntityDocument#getRevisionId()}
* @return a {@link PropertyDocument} corresponding to the input
*/
public static PropertyDocument makePropertyDocument(
PropertyIdValue propertyId, List labels,
List descriptions,
List aliases,
List statementGroups, DatatypeIdValue datatypeId,
long revisionId) {
return factory.getPropertyDocument(propertyId, labels, descriptions,
aliases, statementGroups, datatypeId, revisionId);
}
/**
* Creates an empty{@link ItemDocument}.
*
* @param itemIdValue
* the id of the item that data is about
* @return an {@link ItemDocument} corresponding to the input
*/
public static ItemDocument makeItemDocument(ItemIdValue itemIdValue) {
return makeItemDocument(itemIdValue, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyMap(), 0);
}
/**
* Creates an {@link ItemDocument} with empty revision id. It might be more
* convenient to use the {@link ItemDocumentBuilder} instead.
*
* @param itemIdValue
* the id of the item that data is about
* @param labels
* the list of labels of this item, with at most one label for
* each language code
* @param descriptions
* the list of descriptions of this item, with at most one
* description for each language code
* @param aliases
* the list of aliases of this item
* @param statementGroups
* the list of statement groups of this item; all of them must
* have the given itemIdValue as their subject
* @param siteLinks
* the sitelinks of this item by site key
* @return an {@link ItemDocument} corresponding to the input
*/
public static ItemDocument makeItemDocument(ItemIdValue itemIdValue,
List labels,
List descriptions,
List aliases,
List statementGroups,
Map siteLinks) {
return makeItemDocument(itemIdValue, labels, descriptions, aliases,
statementGroups, siteLinks, 0);
}
/**
* Creates an {@link ItemDocument}. It might be more convenient to use the
* {@link ItemDocumentBuilder} instead.
*
* @param itemIdValue
* the id of the item that data is about
* @param labels
* the list of labels of this item, with at most one label for
* each language code
* @param descriptions
* the list of descriptions of this item, with at most one
* description for each language code
* @param aliases
* the list of aliases of this item
* @param statementGroups
* the list of statement groups of this item; all of them must
* have the given itemIdValue as their subject
* @param siteLinks
* the sitelinks of this item by site key
* @param revisionId
* the revision ID or 0 if not known; see
* {@link EntityDocument#getRevisionId()}
* @return an {@link ItemDocument} corresponding to the input
*/
public static ItemDocument makeItemDocument(ItemIdValue itemIdValue,
List labels,
List descriptions,
List aliases,
List statementGroups,
Map siteLinks, long revisionId) {
return factory.getItemDocument(itemIdValue, labels, descriptions,
aliases, statementGroups, siteLinks, revisionId);
}
/**
* Creates an empty {@link LexemeDocument}.
*
* @param lexemeIdValue
* the id of the lexeme that data is about
* @param lexicalCategory
* the lexical category to which the lexeme belongs
* (noun, verb...)
* @param language
* the language to which the lexeme belongs
* (French, British English...)
* @param lemmas
* the human readable representations of the lexeme
* @return a {@link LexemeDocument} corresponding to the input
*/
public static LexemeDocument makeLexemeDocument(LexemeIdValue lexemeIdValue,
ItemIdValue lexicalCategory, ItemIdValue language, List lemmas) {
return makeLexemeDocument(lexemeIdValue, lexicalCategory, language,
lemmas, Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
}
/**
* Creates a {@link LexemeDocument}.
*
* @param lexemeIdValue
* the id of the lexeme that data is about
* @param lexicalCategory
* the lexical category to which the lexeme belongs
* (noun, verb...)
* @param language
* the language to which the lexeme belongs
* (French, British English...)
* @param lemmas
* the human readable representations of the lexeme
* @param statementGroups
* the list of statement groups of this lexeme; all of them must
* have the given lexemeIdValue as their subject
* @param forms
* the forms of the lexeme
* @param senses
* the senses of the lexeme
* @return a {@link LexemeDocument} corresponding to the input
*/
public static LexemeDocument makeLexemeDocument(LexemeIdValue lexemeIdValue,
ItemIdValue lexicalCategory,
ItemIdValue language,
List lemmas,
List statementGroups,
List forms,
List senses) {
return factory.getLexemeDocument(lexemeIdValue, lexicalCategory, language, lemmas, statementGroups, forms, senses, 0);
}
/**
* Creates a {@link FormDocument}.
*
* If you plan to add this form to a specific lexeme,
* it might be easier to use {@link LexemeDocument#createForm(List)}.
*
* @param formIdValue
* the id of the form that data is about
* @param representations
* the list of representations of this lexeme, with at most one
* lemma for each language code
* @param grammaticalFeatures
* the grammatical features of the lexeme
* @param statementGroups
* the list of statement groups of this lexeme; all of them must
* have the given lexemeIdValue as their subject
* @return a {@link LexemeDocument} corresponding to the input
*/
public static FormDocument makeFormDocument(FormIdValue formIdValue,
List representations,
List grammaticalFeatures,
List statementGroups) {
return factory.getFormDocument(formIdValue, representations, grammaticalFeatures, statementGroups, 0);
}
/**
* Creates a {@link SenseDocument}.
*
* If you plan to add this sense to a specific lexeme,
* it might be easier to use {@link LexemeDocument#createSense(List)} )}.
*
* @param senseIdValue
* the id of the form that data is about
* @param glosses
* the list of glosses of this lexeme, with at most one
* gloss for each language code
* @param statementGroups
* the list of statement groups of this lexeme; all of them must
* have the given lexemeIdValue as their subject
* @return a {@link SenseDocument} corresponding to the input
*/
public static SenseDocument makeSenseDocument(SenseIdValue senseIdValue,
List glosses,
List statementGroups) {
return factory.getSenseDocument(senseIdValue, glosses, statementGroups, 0);
}
/**
* Creates an empty {@link MediaInfoDocument}.
*
* @param mediaInfoIdValue
* the id of the media that data is about
* @return an {@link MediaInfoDocument} corresponding to the input
*/
public static MediaInfoDocument makeMediaInfoDocument(MediaInfoIdValue mediaInfoIdValue) {
return makeMediaInfoDocument(mediaInfoIdValue, Collections.emptyList(), Collections.emptyList());
}
/**
* Creates a {@link MediaInfoDocument}.
*
* @param mediaInfoIdValue
* the id of the media that data is about
* @param labels
* the list of labels of this media, with at most one label for
* each language code
* @param statementGroups
* the list of statement groups of this media info; all of them must
* have the given mediaInfoIdValue as their subject
* @return an {@link MediaInfoDocument} corresponding to the input
*/
public static MediaInfoDocument makeMediaInfoDocument(MediaInfoIdValue mediaInfoIdValue,
List labels,
List statementGroups) {
return factory.getMediaInfoDocument(mediaInfoIdValue, labels, statementGroups, 0);
}
/**
* Creates new {@link TermUpdate}. It might be more convenient to
* use {@link TermUpdateBuilder}.
*
* @param modified
* added or changed values
* @param removed
* language codes of removed values
* @return new {@link TermUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static TermUpdate makeTermUpdate(
Collection modified,
Collection removed) {
return factory.getTermUpdate(modified, removed);
}
/**
* Creates new {@link AliasUpdate}. Callers should specify either
* {@code recreated} parameter or {@code added} and {@code removed} parameters,
* because combination of the two update approaches is not possible. To remove
* all aliases, pass empty list in {@code recreated} parameter.
*
* In most cases, it is more convenient to use {@link #makeAliasUpdate(List)},
* {@link #makeAliasUpdate(List, Collection)}, or {@link AliasUpdateBuilder}.
*
* @param recreated
* new list of aliases that completely replaces the old ones or
* {@code null} to not recreate aliases
* @param added
* aliases added in this update or empty collection for no additions
* @param removed
* aliases removed in this update or empty collection for no removals
* @return new {@link AliasUpdate}
* @throws NullPointerException
* if {@code added}, {@code removed}, or any alias is {@code null}
* @throws IllegalArgumentException
* if given invalid combination of parameters
*/
public static AliasUpdate makeAliasUpdate(
List recreated,
List added,
Collection removed) {
return factory.getAliasUpdate(recreated, added, removed);
}
/**
* Creates new {@link AliasUpdate} that completely replaces all aliases.
*
* @param recreated
* new list of aliases that completely replaces the old ones
* @return new {@link AliasUpdate}
* @throws NullPointerException
* if the parameter or any alias is {@code null}
* @throws IllegalArgumentException
* if language codes are inconsistent or there are alias duplicates
*/
public static AliasUpdate makeAliasUpdate(List recreated) {
Objects.requireNonNull(recreated, "New list of aliases must be provided.");
return factory.getAliasUpdate(recreated, Collections.emptyList(), Collections.emptyList());
}
/**
* Creates new {@link AliasUpdate} that adds and/or removes some of the aliases.
* It might be more convenient to use {@link AliasUpdateBuilder}.
*
* @param added
* aliases to add
* @param removed
* aliases to remove
* @return new {@link AliasUpdate}
* @throws NullPointerException
* if any parameter or any alias is {@code null}
* @throws IllegalArgumentException
* if language codes are inconsistent or there are alias duplicates
*/
public static AliasUpdate makeAliasUpdate(
List added,
Collection removed) {
return factory.getAliasUpdate(null, added, removed);
}
/**
* Creates new {@link StatementUpdate}. It might be more convenient to use
* {@link StatementUpdateBuilder}.
*
* @param added
* added statements
* @param replaced
* replaced statements
* @param removed
* IDs of removed statements
* @return new {@link StatementUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static StatementUpdate makeStatementUpdate(
Collection added,
Collection replaced,
Collection removed) {
return factory.getStatementUpdate(added, replaced, removed);
}
/**
* Creates new {@link SenseUpdate}. It might be more convenient to use
* {@link SenseUpdateBuilder}.
*
* @param entityId
* ID of the sense that is to be updated
* @param revisionId
* base sense revision to be updated or zero if not available
* @param glosses
* changes in sense glosses or {@code null} for no change
* @param statements
* changes in entity statements, possibly empty
* @return new {@link SenseUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static SenseUpdate makeSenseUpdate(
SenseIdValue entityId,
long revisionId,
TermUpdate glosses,
StatementUpdate statements) {
return factory.getSenseUpdate(entityId, revisionId, glosses, statements);
}
/**
* Creates new {@link FormUpdate}. It might be more convenient to use
* {@link FormUpdateBuilder}.
*
* @param entityId
* ID of the form that is to be updated
* @param revisionId
* base form revision to be updated or zero if not available
* @param representations
* changes in form representations or {@code null} for no change
* @param grammaticalFeatures
* new grammatical features of the form or {@code null} for no change
* @param statements
* changes in entity statements, possibly empty
* @return new {@link FormUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static FormUpdate makeFormUpdate(
FormIdValue entityId,
long revisionId,
TermUpdate representations,
Collection grammaticalFeatures,
StatementUpdate statements) {
return factory.getFormUpdate(entityId, revisionId, representations, grammaticalFeatures, statements);
}
/**
* Creates new {@link LexemeUpdate}. It might be more convenient to use
* {@link LexemeUpdateBuilder}.
*
* @param entityId
* ID of the lexeme that is to be updated
* @param revisionId
* base lexeme revision to be updated or zero if not available
* @param language
* new lexeme language or {@code null} for no change
* @param lexicalCategory
* new lexical category of the lexeme or {@code null} for no change
* @param lemmas
* changes in lemmas or {@code null} for no change
* @param statements
* changes in entity statements, possibly empty
* @param addedSenses
* added senses
* @param updatedSenses
* updated senses
* @param removedSenses
* IDs of removed senses
* @param addedForms
* added forms
* @param updatedForms
* updated forms
* @param removedForms
* IDs of removed forms
* @return new {@link LexemeUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static LexemeUpdate makeLexemeUpdate(
LexemeIdValue entityId,
long revisionId,
ItemIdValue language,
ItemIdValue lexicalCategory,
TermUpdate lemmas,
StatementUpdate statements,
Collection addedSenses,
Collection updatedSenses,
Collection removedSenses,
Collection addedForms,
Collection updatedForms,
Collection removedForms) {
return factory.getLexemeUpdate(entityId, revisionId, language, lexicalCategory, lemmas, statements,
addedSenses, updatedSenses, removedSenses, addedForms, updatedForms, removedForms);
}
/**
* Creates new {@link MediaInfoUpdate}. It might be more convenient to use
* {@link MediaInfoUpdateBuilder}.
*
* @param entityId
* ID of the media that is to be updated
* @param revisionId
* base media revision to be updated or zero if not available
* @param labels
* changes in entity labels or {@code null} for no change
* @param statements
* changes in entity statements, possibly empty
* @return new {@link MediaInfoUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static MediaInfoUpdate makeMediaInfoUpdate(
MediaInfoIdValue entityId,
long revisionId,
TermUpdate labels,
StatementUpdate statements) {
return factory.getMediaInfoUpdate(entityId, revisionId, labels, statements);
}
/**
* Creates new {@link ItemUpdate}. It might be more convenient to use
* {@link ItemUpdateBuilder}.
*
* @param entityId
* ID of the item that is to be updated
* @param revisionId
* base item revision to be updated or zero if not available
* @param labels
* changes in entity labels or {@code null} for no change
* @param descriptions
* changes in entity descriptions or {@code null} for no change
* @param aliases
* changes in entity aliases, possibly empty
* @param statements
* changes in entity statements, possibly empty
* @param modifiedSiteLinks
* added or replaced site links
* @param removedSiteLinks
* site keys of removed site links
* @return new {@link ItemUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static ItemUpdate makeItemUpdate(
ItemIdValue entityId,
long revisionId,
TermUpdate labels,
TermUpdate descriptions,
Map aliases,
StatementUpdate statements,
Collection modifiedSiteLinks,
Collection removedSiteLinks) {
return factory.getItemUpdate(entityId, revisionId, labels, descriptions, aliases,
statements, modifiedSiteLinks, removedSiteLinks);
}
/**
* Creates new {@link PropertyUpdate}. It might be more convenient to use
* {@link PropertyUpdateBuilder}.
*
* @param entityId
* ID of the property entity that is to be updated
* @param revisionId
* base property revision to be updated or zero if not available
* @param labels
* changes in entity labels or {@code null} for no change
* @param descriptions
* changes in entity descriptions or {@code null} for no change
* @param aliases
* changes in entity aliases, possibly empty
* @param statements
* changes in entity statements, possibly empty
* @return new {@link PropertyUpdate}
* @throws NullPointerException
* if any required parameter is {@code null}
* @throws IllegalArgumentException
* if any parameters or their combination is invalid
*/
public static PropertyUpdate makePropertyUpdate(
PropertyIdValue entityId,
long revisionId,
TermUpdate labels,
TermUpdate descriptions,
Map aliases,
StatementUpdate statements) {
return factory.getPropertyUpdate(entityId, revisionId, labels, descriptions, aliases, statements);
}
}
DatamodelConverter.java 0000664 0000000 0000000 00000047031 14447725663 0035645 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wikidata.wdtk.datamodel.interfaces.Claim;
import org.wikidata.wdtk.datamodel.interfaces.DataObjectFactory;
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.QuantityValue;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
import org.wikidata.wdtk.datamodel.interfaces.Snak;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.datamodel.interfaces.SnakVisitor;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.interfaces.StringValue;
import org.wikidata.wdtk.datamodel.interfaces.TimeValue;
import org.wikidata.wdtk.datamodel.interfaces.UnsupportedValue;
import org.wikidata.wdtk.datamodel.interfaces.Value;
import org.wikidata.wdtk.datamodel.interfaces.ValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.ValueVisitor;
/**
* Class to re-create data model objects using a specified factory. This is
* provided in place of having copy constructors in each and every
* implementation of the data model. Note that data model objects are usually
* immutable and do not need to be copied. The use of this class is to convert
* data objects to a specific implementation, as might be needed for some
* specialized purpose (e.g., for JSON export).
*
* @author Markus Kroetzsch
*
*/
public class DatamodelConverter implements SnakVisitor,
ValueVisitor {
static final Logger logger = LoggerFactory
.getLogger(DatamodelConverter.class);
/**
* The factory to use for copying.
*/
private final DataObjectFactory dataObjectFactory;
/**
* Constructor.
*
* @param dataObjectFactory
* the factory to use for creating new objects
*/
public DatamodelConverter(DataObjectFactory dataObjectFactory) {
this.dataObjectFactory = dataObjectFactory;
}
/**
* Copies an {@link ItemIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public ItemIdValue copy(ItemIdValue object) {
return dataObjectFactory.getItemIdValue(object.getId(), object.getSiteIri());
}
/**
* Copies a {@link PropertyIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public PropertyIdValue copy(PropertyIdValue object) {
return dataObjectFactory.getPropertyIdValue(object.getId(), object.getSiteIri());
}
/**
* Copies a {@link LexemeIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public LexemeIdValue copy(LexemeIdValue object) {
return dataObjectFactory.getLexemeIdValue(object.getId(), object.getSiteIri());
}
/**
* Copies a {@link FormIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public FormIdValue copy(FormIdValue object) {
return dataObjectFactory.getFormIdValue(object.getId(), object.getSiteIri());
}
/**
* Copies a {@link SenseIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public SenseIdValue copy(SenseIdValue object) {
return dataObjectFactory.getSenseIdValue(object.getId(), object.getSiteIri());
}
/**
* Copies a {@link MediaInfoIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public MediaInfoIdValue copy(MediaInfoIdValue object) {
return dataObjectFactory.getMediaInfoIdValue(object.getId(), object.getSiteIri());
}
/**
* Copies a {@link DatatypeIdValue}.
*
* @param object
* object to copy
* @return copied object
*/
public DatatypeIdValue copy(DatatypeIdValue object) {
return dataObjectFactory.getDatatypeIdValueFromJsonId(object.getJsonString());
}
/**
* Copies a {@link TimeValue}.
*
* @param object
* object to copy
* @return copied object
*/
public TimeValue copy(TimeValue object) {
return dataObjectFactory.getTimeValue(object.getYear(),
object.getMonth(), object.getDay(), object.getHour(),
object.getMinute(), object.getSecond(), object.getPrecision(),
object.getBeforeTolerance(), object.getAfterTolerance(),
object.getTimezoneOffset(), object.getPreferredCalendarModel());
}
/**
* Copies a {@link GlobeCoordinatesValue}.
*
* @param object
* object to copy
* @return copied object
*/
public GlobeCoordinatesValue copy(GlobeCoordinatesValue object) {
return dataObjectFactory.getGlobeCoordinatesValue(
object.getLatitude(), object.getLongitude(),
object.getPrecision(), object.getGlobe());
}
/**
* Copies a {@link StringValue}.
*
* @param object
* object to copy
* @return copied object
*/
public StringValue copy(StringValue object) {
return dataObjectFactory.getStringValue(object.getString());
}
/**
* Copies a {@link MonolingualTextValue}
* @param object
* object to copy
* @return copied object
*/
public MonolingualTextValue copy(MonolingualTextValue object) {
return dataObjectFactory.getMonolingualTextValue(object.getText(), object.getLanguageCode());
}
/**
* Copies a {@link QuantityValue}.
*
* @param object
* object to copy
* @return copied object
*/
public QuantityValue copy(QuantityValue object) {
return dataObjectFactory.getQuantityValue(
object.getNumericValue(), object.getLowerBound(),
object.getUpperBound(), object.getUnitItemId());
}
/**
* Copies an {@link UnsupportedValue}.
*
* @param object
* object to copy
* @return copied object
*/
public UnsupportedValue copy(UnsupportedValue object) {
// unsupported values cannot be copied!
return object;
}
/**
* Copies a {@link Snak}.
*
* @param snak
* object to copy
* @return the copied object
*/
private Snak copy(Snak snak) {
if (snak instanceof ValueSnak) {
return copy((ValueSnak) snak);
} else if (snak instanceof NoValueSnak) {
return copy((NoValueSnak) snak);
} else if (snak instanceof SomeValueSnak) {
return copy((SomeValueSnak) snak);
} else {
throw new IllegalArgumentException(
"I don't know how to copy snaks of type " + snak.getClass());
}
}
/**
* Copies a {@link ValueSnak}.
*
* @param object
* object to copy
* @return copied object
*/
public ValueSnak copy(ValueSnak object) {
return dataObjectFactory.getValueSnak(copy(object.getPropertyId()), copyValue(object.getValue()));
}
/**
* Copies a {@link SomeValueSnak}.
*
* @param object
* object to copy
* @return copied object
*/
public SomeValueSnak copy(SomeValueSnak object) {
return dataObjectFactory.getSomeValueSnak(copy(object.getPropertyId()));
}
/**
* Copies a {@link NoValueSnak}.
*
* @param object
* object to copy
* @return copied object
*/
public NoValueSnak copy(NoValueSnak object) {
return dataObjectFactory.getNoValueSnak(copy(object.getPropertyId()));
}
/**
* Copies a {@link SnakGroup}.
*
* @param object
* object to copy
* @return copied object
*/
public SnakGroup copy(SnakGroup object) {
List snaks = new ArrayList<>(object.size());
for (Snak snak : object) {
snaks.add(copy(snak));
}
return dataObjectFactory.getSnakGroup(snaks);
}
/**
* Copies a {@link Claim}.
*
* @param object
* object to copy
* @return copied object
*/
public Claim copy(Claim object) {
return dataObjectFactory.getClaim(
(EntityIdValue) visit(object.getSubject()),
copy(object.getMainSnak()),
copy(object.getQualifiers()));
}
/**
* Copies a {@link Reference}.
*
* @param object
* object to copy
* @return copied object
*/
public Reference copy(Reference object) {
return dataObjectFactory.getReference(copy(object.getSnakGroups()));
}
/**
* Copies a {@link Statement}.
*
* @param object
* object to copy
* @return copied object
*/
public Statement copy(Statement object) {
return dataObjectFactory.getStatement(
(EntityIdValue) visit(object.getSubject()),
copy(object.getMainSnak()),
copy(object.getQualifiers()),
copyReferences(object.getReferences()),
object.getRank(), object.getStatementId());
}
/**
* Copies a {@link StatementGroup}.
* @param object
* object to copy
* @return copied object
*/
public StatementGroup copy(StatementGroup object) {
List statements = new ArrayList<>(object.getStatements().size());
for (Statement statement : object.getStatements()) {
statements.add(copy(statement));
}
return dataObjectFactory.getStatementGroup(statements);
}
/**
* Copies a {@link SiteLink}.
*
* @param object
* object to copy
* @return copied object
*/
public SiteLink copy(SiteLink object) {
return dataObjectFactory.getSiteLink(object.getPageTitle(),
object.getSiteKey(), object.getBadges());
}
/**
* Copies a {@link PropertyDocument}.
*
* @param object
* object to copy
* @return copied object
*/
public PropertyDocument copy(PropertyDocument object) {
return dataObjectFactory.getPropertyDocument(
copy(object.getEntityId()),
copyMonoLingualTextValues(object.getLabels().values()),
copyMonoLingualTextValues(object.getDescriptions().values()),
copyAliasMap(object.getAliases()),
copyStatementGroups(object.getStatementGroups()),
copy(object.getDatatype()),
object.getRevisionId());
}
/**
* Copies an {@link ItemDocument}.
*
* @param object
* object to copy
* @return copied object
*/
public ItemDocument copy(ItemDocument object) {
return dataObjectFactory.getItemDocument(
copy(object.getEntityId()),
copyMonoLingualTextValues(object.getLabels().values()),
copyMonoLingualTextValues(object.getDescriptions().values()),
copyAliasMap(object.getAliases()),
copyStatementGroups(object.getStatementGroups()),
copySiteLinks(object.getSiteLinks()),
object.getRevisionId());
}
/**
* Copies a {@link MediaInfoDocument}.
*
* @param object
* object to copy
* @return copied object
*/
public MediaInfoDocument copy(MediaInfoDocument object) {
return dataObjectFactory.getMediaInfoDocument(
copy(object.getEntityId()),
copyMonoLingualTextValues(object.getLabels().values()),
copyStatementGroups(object.getStatementGroups()),
object.getRevisionId());
}
/**
* Copies a {@link LexemeDocument}.
*
* @param object
* object to copy
* @return copied object
*/
public LexemeDocument copy(LexemeDocument object) {
return dataObjectFactory.getLexemeDocument(
copy(object.getEntityId()),
copy(object.getLexicalCategory()),
copy(object.getLanguage()),
copyMonoLingualTextValues(object.getLemmas().values()),
copyStatementGroups(object.getStatementGroups()),
copyFormDocuments(object.getForms()),
copySenseDocuments(object.getSenses()),
object.getRevisionId());
}
/**
* Copies a {@link FormDocument}.
*
* @param object
* object to copy
* @return copied object
*/
public FormDocument copy(FormDocument object) {
return dataObjectFactory.getFormDocument(
copy(object.getEntityId()),
copyMonoLingualTextValues(object.getRepresentations().values()),
copyItemIds(object.getGrammaticalFeatures()),
copyStatementGroups(object.getStatementGroups()),
object.getRevisionId());
}
/**
* Copies a {@link SenseDocument}.
*
* @param object
* object to copy
* @return copied object
*/
public SenseDocument copy(SenseDocument object) {
return dataObjectFactory.getSenseDocument(
copy(object.getEntityId()),
copyMonoLingualTextValues(object.getGlosses().values()),
copyStatementGroups(object.getStatementGroups()),
object.getRevisionId());
}
/**
* Copies a {@link Snak}.
*
* @param snak
* object to copy
* @return copied object
*/
public Snak copySnak(Snak snak) {
return snak.accept(this);
}
@Override
public Snak visit(ValueSnak snak) {
return copy(snak);
}
@Override
public Snak visit(SomeValueSnak snak) {
return copy(snak);
}
@Override
public Snak visit(NoValueSnak snak) {
return copy(snak);
}
/**
* Copies a {@link Value}.
*
* @param value
* object to copy
* @return copied object
*/
public Value copyValue(Value value) {
return value.accept(this);
}
@Override
public Value visit(EntityIdValue value) {
if (value instanceof ItemIdValue) {
return copy((ItemIdValue) value);
} else if (value instanceof PropertyIdValue) {
return copy((PropertyIdValue) value);
} else if (value instanceof LexemeIdValue) {
return copy((LexemeIdValue) value);
} else if (value instanceof FormIdValue) {
return copy((FormIdValue) value);
} else if (value instanceof SenseIdValue) {
return copy((SenseIdValue) value);
} else if (value instanceof MediaInfoIdValue) {
return copy((MediaInfoIdValue) value);
} else {
throw new UnsupportedOperationException(
"Cannot convert entity id value: " + value.getClass());
}
}
@Override
public Value visit(GlobeCoordinatesValue value) {
return copy(value);
}
@Override
public Value visit(MonolingualTextValue value) {
return copy(value);
}
@Override
public Value visit(QuantityValue value) {
return copy(value);
}
@Override
public Value visit(StringValue value) {
return copy(value);
}
@Override
public Value visit(TimeValue value) {
return copy(value);
}
@Override
public Value visit(UnsupportedValue value) {
return copy(value);
}
/**
* Converts a map of language keys to lists of {@link MonolingualTextValue}
* objects to a flat list of such objects, as required for the factory
* methods, where the values in the flat lists are new copies of the
* original values.
*
* @param aliasMap
* the map to convert
* @return the flattened list with copied values
*/
private List copyAliasMap(
Map> aliasMap) {
List aliases = new ArrayList<>();
for (Entry> langAliases : aliasMap.entrySet()) {
for (MonolingualTextValue mtv : langAliases.getValue()) {
aliases.add(copy(mtv));
}
}
return aliases;
}
/**
* Copies a list of {@link SnakGroup} objects.
*
* @param snakGroups
* object to copy
* @return the copied object
*/
private List copy(List snakGroups) {
List result = new ArrayList<>(snakGroups.size());
for (SnakGroup snakGroup : snakGroups) {
result.add(copy(snakGroup));
}
return result;
}
/**
* Copies a list of {@link Reference} objects.
*
* @param references
* object to copy
* @return the copied object
*/
private List copyReferences(List references) {
List result = new ArrayList<>(references.size());
for (Reference reference : references) {
result.add(dataObjectFactory
.getReference(copy(reference.getSnakGroups())));
}
return result;
}
/**
* Copies a list of {@link StatementGroup} objects.
*
* @param statementGroups
* object to copy
* @return the copied object
*/
private List copyStatementGroups(List statementGroups) {
List result = new ArrayList<>(statementGroups.size());
for (StatementGroup statementGroup : statementGroups) {
result.add(copy(statementGroup));
}
return result;
}
/**
* Copies a collection of {@link MonolingualTextValue} objects
*
* @param monoLingualTextValues
* object to copy
* @return the copied object
*/
private List copyMonoLingualTextValues(Collection monoLingualTextValues) {
List result = new ArrayList<>(monoLingualTextValues.size());
for (MonolingualTextValue mtv : monoLingualTextValues) {
result.add(copy(mtv));
}
return result;
}
/**
* Copies a map of {@link SiteLink} objects.
*
* @param siteLinks
* object to copy
* @return the copied object
*/
private Map copySiteLinks(Map siteLinks) {
Map result = new HashMap<>(siteLinks.size());
for (Entry entry : siteLinks.entrySet()) {
result.put(entry.getKey(), copy(entry.getValue()));
}
return result;
}
/**
* Copies a list of item ids.
*
* @param ids
* @return
*/
private List copyItemIds(List ids) {
return ids.stream()
.map(id -> copy(id))
.collect(Collectors.toList());
}
/**
* Copies a list of sense documents.
*
* @param senses
* @return
*/
private List copySenseDocuments(List senses) {
return senses.stream()
.map(sense -> copy(sense))
.collect(Collectors.toList());
}
/**
* Copies a list of form documents.
*
* @param forms
* @return
*/
private List copyFormDocuments(List forms) {
return forms.stream()
.map(form -> copy(form))
.collect(Collectors.toList());
}
}
DatamodelFilter.java 0000664 0000000 0000000 00000012773 14447725663 0035130 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2018 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import org.wikidata.wdtk.datamodel.interfaces.*;
import java.util.*;
/**
* This is a utility class that allows to filter {@link EntityDocument}
* using the data declared in a {@link DocumentDataFilter}.
*/
public class DatamodelFilter {
private final DataObjectFactory dataObjectFactory;
private final DocumentDataFilter filter;
public DatamodelFilter(DataObjectFactory dataObjectFactory, DocumentDataFilter filter) {
this.dataObjectFactory = dataObjectFactory;
this.filter = filter;
}
public ItemDocument filter(ItemDocument item) {
return dataObjectFactory.getItemDocument(
item.getEntityId(),
filterMonoLingualTextValues(item.getLabels().values()),
filterMonoLingualTextValues(item.getDescriptions().values()),
filterMonoLingualTextValues(flatten(item.getAliases().values())),
filterStatementGroups(item.getStatementGroups()),
filterSiteLinks(item.getSiteLinks()),
item.getRevisionId()
);
}
public PropertyDocument filter(PropertyDocument property) {
return dataObjectFactory.getPropertyDocument(
property.getEntityId(),
filterMonoLingualTextValues(property.getLabels().values()),
filterMonoLingualTextValues(property.getDescriptions().values()),
filterMonoLingualTextValues(flatten(property.getAliases().values())),
filterStatementGroups(property.getStatementGroups()),
property.getDatatype(),
property.getRevisionId()
);
}
public MediaInfoDocument filter(MediaInfoDocument mediaInfo) {
return dataObjectFactory.getMediaInfoDocument(
mediaInfo.getEntityId(),
filterMonoLingualTextValues(mediaInfo.getLabels().values()),
filterStatementGroups(mediaInfo.getStatementGroups()),
mediaInfo.getRevisionId()
);
}
public LexemeDocument filter(LexemeDocument lexeme) {
return dataObjectFactory.getLexemeDocument(
lexeme.getEntityId(),
lexeme.getLexicalCategory(),
lexeme.getLanguage(),
filterMonoLingualTextValues(lexeme.getLemmas().values()),
filterStatementGroups(lexeme.getStatementGroups()),
filterForms(lexeme.getForms()),
filterSenses(lexeme.getSenses()),
lexeme.getRevisionId()
);
}
public FormDocument filter(FormDocument form) {
return dataObjectFactory.getFormDocument(
form.getEntityId(),
filterMonoLingualTextValues(form.getRepresentations().values()),
form.getGrammaticalFeatures(),
filterStatementGroups(form.getStatementGroups()),
form.getRevisionId()
);
}
public SenseDocument filter(SenseDocument sense) {
return dataObjectFactory.getSenseDocument(
sense.getEntityId(),
filterMonoLingualTextValues(sense.getGlosses().values()),
filterStatementGroups(sense.getStatementGroups()),
sense.getRevisionId()
);
}
private List filterForms(List forms) {
List filtered = new ArrayList<>(forms.size());
for(FormDocument form : forms) {
filtered.add(filter(form));
}
return filtered;
}
private List filterSenses(List senses) {
List filtered = new ArrayList<>(senses.size());
for(SenseDocument sense : senses) {
filtered.add(filter(sense));
}
return filtered;
}
private List flatten(Collection> values) {
List flattened = new ArrayList<>();
for(Collection part : values) {
flattened.addAll(part);
}
return flattened;
}
private List filterMonoLingualTextValues(Collection values) {
if (filter.getLanguageFilter() == null) {
return new ArrayList<>(values);
}
if (filter.getLanguageFilter().isEmpty()) {
return Collections.emptyList();
}
List output = new ArrayList<>();
for(MonolingualTextValue value : values) {
if (filter.getLanguageFilter().contains(value.getLanguageCode())) {
output.add(value);
}
}
return output;
}
private List filterStatementGroups(List statementGroups) {
if (filter.getPropertyFilter() == null) {
return statementGroups;
}
if (filter.getPropertyFilter().isEmpty()) {
return Collections.emptyList();
}
List output = new ArrayList<>(statementGroups.size());
for(StatementGroup statementGroup : statementGroups) {
if(filter.getPropertyFilter().contains(statementGroup.getProperty())) {
output.add(statementGroup);
}
}
return output;
}
private Map filterSiteLinks(Map siteLinks) {
if (filter.getSiteLinkFilter() == null) {
return siteLinks;
}
if (filter.getSiteLinkFilter().isEmpty()) {
return Collections.emptyMap();
}
Map result = new HashMap<>(siteLinks.size());
for (Map.Entry entry : siteLinks.entrySet()) {
if (filter.getSiteLinkFilter().contains(entry.getKey())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
}
DatamodelMapper.java 0000664 0000000 0000000 00000003216 14447725663 0035117 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2018 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
/**
* Same as Jackson's celebrated ObjectMapper, except
* that we add injections necessary to fill fields not
* represented in JSON.
*
* @author antonin
*
*/
public class DatamodelMapper extends ObjectMapper {
private static final long serialVersionUID = -236841297410109272L;
/**
* Constructs a mapper with the given siteIri. This IRI
* will be used to fill all the siteIris of the entity ids
* contained in the payloads.
*
* @param siteIri
* the ambient IRI of the Wikibase site
*/
public DatamodelMapper(String siteIri) {
super();
InjectableValues injection = new InjectableValues.Std()
.addValue("siteIri", siteIri);
this.setInjectableValues(injection);
/*
* Support for Optional properties.
*/
registerModule(new Jdk8Module());
}
}
EntityDocumentBuilder.java 0000664 0000000 0000000 00000015004 14447725663 0036340 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.interfaces.TermedStatementDocument;
/**
* Abstract base class for builders that construct {@link EntityDocument}
* objects.
*
* @author Markus Kroetzsch
*
* @param
* the type of the eventual concrete builder implementation
* @param
* the type of the object that is being built
*/
public abstract class EntityDocumentBuilder, O extends TermedStatementDocument>
extends AbstractDataObjectBuilder {
EntityIdValue entityIdValue;
final ArrayList labels = new ArrayList<>();
final ArrayList descriptions = new ArrayList<>();
final ArrayList aliases = new ArrayList<>();
final HashMap> statements = new HashMap<>();
long revisionId = 0;
protected EntityDocumentBuilder(EntityIdValue entityIdValue) {
this.entityIdValue = entityIdValue;
}
/**
* Starts constructing an EntityDocument from an initial version
* of this document.
*
* @param initialDocument
* the initial version of the document to use
*/
protected EntityDocumentBuilder(O initialDocument) {
this.entityIdValue = initialDocument.getEntityId();
this.revisionId = initialDocument.getRevisionId();
for(MonolingualTextValue label : initialDocument.getLabels().values()) {
withLabel(label);
}
for(MonolingualTextValue description : initialDocument.getDescriptions().values()) {
withDescription(description);
}
for(List aliases : initialDocument.getAliases().values()) {
for(MonolingualTextValue alias : aliases) {
withAlias(alias);
}
}
Iterator iterator = initialDocument.getAllStatements();
while(iterator.hasNext()) {
withStatement(iterator.next());
}
}
/**
* Sets the revision id for the constructed document. See
* {@link EntityDocument#getRevisionId()}.
*
* @param revisionId
* the revision id
* @return builder object to continue construction
*/
public T withRevisionId(long revisionId) {
this.revisionId = revisionId;
return getThis();
}
/**
* Changes the entity value id for the constructed document.
* See {@link EntityDocument#getEntityId()}.
*
* @param entityId
* the entity id
* @return builder object to continue construction
*/
public T withEntityId(EntityIdValue entityId) {
this.entityIdValue = entityId;
return getThis();
}
/**
* Adds an additional label to the constructed document.
*
* @param mtv
* the additional label
* @return builder object to continue construction
*/
public T withLabel(MonolingualTextValue mtv) {
this.labels.add(mtv);
return getThis();
}
/**
* Adds an additional label to the constructed document.
*
* @param text
* the text of the label
* @param languageCode
* the language code of the label
* @return builder object to continue construction
*/
public T withLabel(String text, String languageCode) {
withLabel(factory.getMonolingualTextValue(text, languageCode));
return getThis();
}
/**
* Adds an additional description to the constructed document.
*
* @param mtv
* the additional description
* @return builder object to continue construction
*/
public T withDescription(MonolingualTextValue mtv) {
this.descriptions.add(mtv);
return getThis();
}
/**
* Adds an additional description to the constructed document.
*
* @param text
* the text of the description
* @param languageCode
* the language code of the description
* @return builder object to continue construction
*/
public T withDescription(String text, String languageCode) {
withDescription(factory.getMonolingualTextValue(text, languageCode));
return getThis();
}
/**
* Adds an additional alias to the constructed document.
*
* @param mtv
* the additional alias
* @return builder object to continue construction
*/
public T withAlias(MonolingualTextValue mtv) {
this.aliases.add(mtv);
return getThis();
}
/**
* Adds an additional alias to the constructed document.
*
* @param text
* the text of the alias
* @param languageCode
* the language code of the alias
* @return builder object to continue construction
*/
public T withAlias(String text, String languageCode) {
withAlias(factory.getMonolingualTextValue(text, languageCode));
return getThis();
}
/**
* Adds an additional statement to the constructed document.
*
* @param statement
* the additional statement
* @return builder object to continue construction
*/
public T withStatement(Statement statement) {
PropertyIdValue pid = statement.getMainSnak().getPropertyId();
if(!statements.containsKey(pid)) {
statements.put(pid, new ArrayList<>());
}
ArrayList pidStatements = statements.get(pid);
pidStatements.add(statement);
return getThis();
}
/**
* Returns a list of {@link StatementGroup} objects for the currently stored
* statements.
*
* @return
*/
protected List getStatementGroups() {
ArrayList result = new ArrayList<>(
this.statements.size());
for (ArrayList statementList : this.statements.values()) {
result.add(factory.getStatementGroup(statementList));
}
return result;
}
}
EntityUpdateBuilder.java 0000664 0000000 0000000 00000016435 14447725663 0036015 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityUpdate;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseIdValue;
import org.wikidata.wdtk.datamodel.interfaces.StatementDocument;
/**
* Builder for incremental construction of {@link EntityUpdate} objects.
*/
public abstract class EntityUpdateBuilder {
private final EntityIdValue entityId;
private final long baseRevisionId;
private final EntityDocument baseRevision;
/**
* Initializes new builder object for constructing update of entity with given
* ID.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is as placeholder ID
*/
protected EntityUpdateBuilder(EntityIdValue entityId, long revisionId) {
Objects.requireNonNull(entityId, "Entity ID cannot be null.");
Validate.isTrue(!entityId.isPlaceholder(), "Cannot create update for placeholder entity ID.");
this.entityId = entityId;
this.baseRevisionId = revisionId;
baseRevision = null;
}
/**
* Initializes new builder object for constructing update of given base entity
* revision.
*
* @param revision
* base entity revision to be updated
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has a placeholder ID
*/
protected EntityUpdateBuilder(EntityDocument revision) {
Objects.requireNonNull(revision, "Base entity revision cannot be null.");
Validate.isTrue(!revision.getEntityId().isPlaceholder(), "Cannot create update for placeholder entity ID.");
entityId = revision.getEntityId();
baseRevision = revision;
baseRevisionId = baseRevision.getRevisionId();
}
/**
* Creates new builder object for constructing update of entity with given
* revision ID.
*
* Supported entity IDs include {@link ItemIdValue}, {@link PropertyIdValue},
* {@link LexemeIdValue}, {@link FormIdValue}, {@link SenseIdValue}, and
* {@link MediaInfoIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it's a placeholder
* ID
*/
public static EntityUpdateBuilder forBaseRevisionId(EntityIdValue entityId, long revisionId) {
return StatementDocumentUpdateBuilder.forBaseRevisionId(entityId, revisionId);
}
/**
* Creates new builder object for constructing update of entity with given ID.
*
* Supported entity IDs include {@link ItemIdValue}, {@link PropertyIdValue},
* {@link LexemeIdValue}, {@link FormIdValue}, {@link SenseIdValue}, and
* {@link MediaInfoIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it's a placeholder
* ID
*/
public static EntityUpdateBuilder forEntityId(EntityIdValue entityId) {
return forBaseRevisionId(entityId, 0);
}
/**
* Creates new builder object for constructing update of given base entity
* revision. Provided entity document might not represent the latest revision of
* the entity as currently stored in Wikibase. It will be used for validation in
* builder methods. If the document has revision ID, it will be used to detect
* edit conflicts.
*
* Supported entity types include {@link ItemDocument},
* {@link PropertyDocument}, {@link LexemeDocument}, {@link FormDocument},
* {@link SenseDocument}, and {@link MediaInfoDocument}.
*
* @param revision
* base entity revision to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} is of unrecognized type or its ID is a
* placeholder ID
*/
public static EntityUpdateBuilder forBaseRevision(EntityDocument revision) {
Objects.requireNonNull(revision, "Base entity revision cannot be null.");
if (revision instanceof StatementDocument) {
return StatementDocumentUpdateBuilder.forBaseRevision((StatementDocument) revision);
}
throw new IllegalArgumentException("Unrecognized entity document type.");
}
/**
* Returns ID of the entity that is being updated.
*
* @return ID of the updated entity
*/
EntityIdValue getEntityId() {
return entityId;
}
/**
* Returns base entity revision, upon which this update is built. If no base
* revision was provided when this builder was constructed, this method returns
* {@code null}.
*
* @return base entity revision that is being updated
*/
EntityDocument getBaseRevision() {
return baseRevision;
}
/**
* Returns base entity revision ID, upon which this update is built. If no base
* revision nor base revision ID was provided when this builder was constructed,
* this method returns zero.
*
* @return base entity revision ID
*/
long getBaseRevisionId() {
return baseRevisionId;
}
/**
* Creates new {@link EntityUpdate} object with contents of this builder object.
*
* @return constructed object
*/
public abstract EntityUpdate build();
}
Equality.java 0000664 0000000 0000000 00000070753 14447725663 0033667 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import org.wikidata.wdtk.datamodel.interfaces.*;
import java.util.Objects;
/**
* Static class for checking the equality of arbitrary data objects using only
* their interfaces. This can be used to implement the equals() method of
* arbitrary interface implementations. More efficient solutions might exist if
* the object that implements an interface is of a specific known type, but the
* methods here could always be used as a fallback or default.
*
* Note that it is desired that different implementations of the same interface
* are treated as equal if they contain the same data.
*
* @author Markus Kroetzsch
*
*/
public class Equality {
/**
* Returns {@code true} if the parameters are two {@link EntityIdValue} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsEntityIdValue(EntityIdValue o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof EntityIdValue)) {
return false;
}
EntityIdValue other = (EntityIdValue) o2;
return o1.getId().equals(other.getId())
&& o1.getSiteIri().equals(other.getSiteIri())
&& o1.getEntityType().equals(other.getEntityType());
}
/**
* Returns {@code true} if the parameters are two {@link DatatypeIdValue} objects
* with exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsDatatypeIdValue(DatatypeIdValue o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof DatatypeIdValue
&& o1.getIri().equals(((DatatypeIdValue) o2).getIri())
&& o1.getJsonString().equals(((DatatypeIdValue) o2).getJsonString());
}
/**
* Returns {@code true} if the parameters are two {@link TimeValue} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsTimeValue(TimeValue o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof TimeValue)) {
return false;
}
TimeValue other = (TimeValue) o2;
return o1.getYear() == other.getYear()
&& o1.getMonth() == other.getMonth()
&& o1.getDay() == other.getDay()
&& o1.getHour() == other.getHour()
&& o1.getMinute() == other.getMinute()
&& o1.getSecond() == other.getSecond()
&& o1.getPrecision() == other.getPrecision()
&& o1.getBeforeTolerance() == other.getBeforeTolerance()
&& o1.getAfterTolerance() == other.getAfterTolerance()
&& o1.getTimezoneOffset() == other.getTimezoneOffset()
&& o1.getPreferredCalendarModel().equals(
other.getPreferredCalendarModel());
}
/**
* Returns {@code true} if the parameters are two {@link GlobeCoordinatesValue}
* objects with exactly the same data. It does not matter if they are
* different implementations of the interface as long as their content is
* the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsGlobeCoordinatesValue(GlobeCoordinatesValue o1,
Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof GlobeCoordinatesValue)) {
return false;
}
GlobeCoordinatesValue other = (GlobeCoordinatesValue) o2;
return o1.getLatitude() == other.getLatitude()
&& o1.getLongitude() == other.getLongitude()
&& o1.getPrecision() == other.getPrecision()
&& o1.getGlobe().equals(other.getGlobe());
}
/**
* Returns {@code true} if the parameters are two {@link StringValue} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsStringValue(StringValue o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof StringValue
&& o1.getString().equals(((StringValue) o2).getString());
}
/**
* Returns {@code true} if the parameters are two {@link MonolingualTextValue}
* objects with exactly the same data. It does not matter if they are
* different implementations of the interface as long as their content is
* the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsMonolingualTextValue(MonolingualTextValue o1,
Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof MonolingualTextValue)) {
return false;
}
MonolingualTextValue other = (MonolingualTextValue) o2;
return o1.getText().equals(other.getText())
&& o1.getLanguageCode().equals(other.getLanguageCode());
}
/**
* Returns {@code true} if the parameters are two {@link QuantityValue} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsQuantityValue(QuantityValue o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof QuantityValue)) {
return false;
}
QuantityValue other = (QuantityValue) o2;
return o1.getNumericValue().equals(other.getNumericValue())
&& Objects.equals(o1.getLowerBound(), other.getLowerBound())
&& Objects.equals(o1.getUpperBound(), other.getUpperBound())
&& o1.getUnit().equals(other.getUnit());
}
/**
* Returns {@code true} if the parameters are two {@link ValueSnak} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsValueSnak(ValueSnak o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof ValueSnak
&& o1.getPropertyId().equals(((ValueSnak) o2).getPropertyId())
&& o1.getValue().equals(((ValueSnak) o2).getValue());
}
/**
* Returns {@code true} if the parameters are two {@link SomeValueSnak} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsSomeValueSnak(SomeValueSnak o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof SomeValueSnak
&& o1.getPropertyId().equals(((SomeValueSnak) o2).getPropertyId());
}
/**
* Returns {@code true} if the parameters are two {@link NoValueSnak} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsNoValueSnak(NoValueSnak o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof NoValueSnak
&& o1.getPropertyId().equals(((NoValueSnak) o2).getPropertyId());
}
/**
* Returns {@code true} if the parameters are two {@link SnakGroup} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsSnakGroup(SnakGroup o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof SnakGroup
&& o1.getSnaks().equals(((SnakGroup) o2).getSnaks());
}
/**
* Returns {@code true} if the parameters are two {@link Claim} objects with exactly
* the same data. It does not matter if they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsClaim(Claim o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof Claim)) {
return false;
}
Claim other = (Claim) o2;
return o1.getSubject().equals(other.getSubject())
&& o1.getMainSnak().equals(other.getMainSnak())
&& o1.getQualifiers().equals(other.getQualifiers());
}
/**
* Returns {@code true} if the parameters are two {@link Reference} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsReference(Reference o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof Reference
&& o1.getSnakGroups().equals(((Reference) o2).getSnakGroups());
}
/**
* Returns {@code true} if the parameters are two {@link Statement} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsStatement(Statement o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof Statement)) {
return false;
}
Statement other = (Statement) o2;
return o1.getSubject().equals(other.getSubject())
&& o1.getMainSnak().equals(other.getMainSnak())
&& o1.getQualifiers().equals(other.getQualifiers())
&& o1.getReferences().equals(other.getReferences())
&& o1.getRank() == other.getRank()
&& o1.getStatementId().equals(other.getStatementId());
}
/**
* Returns {@code true} if the parameters are two {@link StatementGroup} objects
* with exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
* Note that this includes the statement id, so that two statement objects
* that "say the same thing" might still be unequal if they have different
* ids.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsStatementGroup(StatementGroup o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
return o2 instanceof StatementGroup
&& o1.getStatements().equals(((StatementGroup) o2).getStatements());
}
/**
* Returns {@code true} if the parameters are two {@link SiteLink} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsSiteLink(SiteLink o1, Object o2) {
if (o2 == null) {
return false;
}
if (o2 == o1) {
return true;
}
if (!(o2 instanceof SiteLink)) {
return false;
}
SiteLink other = (SiteLink) o2;
return o1.getPageTitle().equals(other.getPageTitle())
&& o1.getSiteKey().equals(other.getSiteKey())
&& o1.getBadges().equals(other.getBadges());
}
/**
* Returns {@code true} if the parameters are two {@link PropertyDocument} objects
* with exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsPropertyDocument(PropertyDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof PropertyDocument)) {
return false;
}
PropertyDocument other = (PropertyDocument) o2;
// Note: property id already compared by equalsTermedDocument()
return equalsTermedDocument(o1, other)
&& o1.getDatatype().equals(other.getDatatype())
&& o1.getStatementGroups().equals(other.getStatementGroups());
}
/**
* Returns {@code true} if the parameters are two {@link ItemDocument} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsItemDocument(ItemDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof ItemDocument)) {
return false;
}
ItemDocument other = (ItemDocument) o2;
// Note: item id already compared by equalsTermedDocument()
return equalsTermedDocument(o1, other)
&& o1.getSiteLinks().equals(other.getSiteLinks())
&& o1.getStatementGroups().equals(other.getStatementGroups());
}
/**
* Returns {@code true} if the parameters are two {@link LexemeDocument} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsLexemeDocument(LexemeDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof LexemeDocument)) {
return false;
}
LexemeDocument other = (LexemeDocument) o2;
return o1.getEntityId().equals(other.getEntityId())
&& o1.getLanguage().equals(other.getLanguage())
&& o1.getLexicalCategory().equals(other.getLexicalCategory())
&& o1.getLemmas().equals(other.getLemmas())
&& o1.getStatementGroups().equals(other.getStatementGroups())
&& o1.getForms().equals(other.getForms())
&& o1.getSenses().equals(other.getSenses())
&& (o1.getRevisionId() == other.getRevisionId());
}
/**
* Returns {@code true} if the parameters are two {@link FormDocument} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsFormDocument(FormDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof FormDocument)) {
return false;
}
FormDocument other = (FormDocument) o2;
return o1.getEntityId().equals(other.getEntityId())
&& o1.getGrammaticalFeatures().equals(other.getGrammaticalFeatures())
&& o1.getRepresentations().equals(other.getRepresentations())
&& o1.getStatementGroups().equals(other.getStatementGroups())
&& (o1.getRevisionId() == other.getRevisionId());
}
/**
* Returns {@code true} if the parameters are two {@link SenseDocument} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsSenseDocument(SenseDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof SenseDocument)) {
return false;
}
SenseDocument other = (SenseDocument) o2;
return o1.getEntityId().equals(other.getEntityId())
&& o1.getGlosses().equals(other.getGlosses())
&& o1.getStatementGroups().equals(other.getStatementGroups())
&& (o1.getRevisionId() == other.getRevisionId());
}
/**
* Returns {@code true} if the parameters are two {@link MediaInfoDocument} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsMediaInfoDocument(MediaInfoDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof MediaInfoDocument)) {
return false;
}
MediaInfoDocument other = (MediaInfoDocument) o2;
return o1.getEntityId().equals(other.getEntityId())
&& o1.getLabels().equals(other.getLabels())
&& o1.getStatementGroups().equals(other.getStatementGroups())
&& (o1.getRevisionId() == other.getRevisionId());
}
private static boolean equalsTermedDocument(TermedDocument o1, TermedDocument other) {
return o1.getEntityId().equals(other.getEntityId())
&& o1.getAliases().equals(other.getAliases())
&& o1.getDescriptions().equals(other.getDescriptions())
&& o1.getLabels().equals(other.getLabels())
&& (o1.getRevisionId() == other.getRevisionId());
}
/**
* Returns {@code true} if the parameters are two {@link EntityRedirectDocument} objects with
* exactly the same data. It does not matter if they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsEntityRedirectDocument(EntityRedirectDocument o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof EntityRedirectDocument)) {
return false;
}
EntityRedirectDocument other = (EntityRedirectDocument) o2;
return o1.getEntityId().equals(other.getEntityId())
&& o1.getTargetId().equals(other.getTargetId())
&& o1.getRevisionId() == other.getRevisionId();
}
/**
* Returns {@code true} if the two {@link TermUpdate} objects contain exactly
* the same data. It does not matter whether they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsTermUpdate(TermUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof TermUpdate)) {
return false;
}
TermUpdate other = (TermUpdate) o2;
return Objects.equals(o1.getModified(), other.getModified())
&& Objects.equals(o1.getRemoved(), other.getRemoved());
}
/**
* Returns {@code true} if the two {@link AliasUpdate} objects contain exactly
* the same data. It does not matter whether they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsAliasUpdate(AliasUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof AliasUpdate)) {
return false;
}
AliasUpdate other = (AliasUpdate) o2;
return Objects.equals(o1.getRecreated(), other.getRecreated())
&& Objects.equals(o1.getAdded(), other.getAdded())
&& Objects.equals(o1.getRemoved(), other.getRemoved());
}
/**
* Returns {@code true} if the two {@link StatementUpdate} objects contain
* exactly the same data. It does not matter whether they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsStatementUpdate(StatementUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof StatementUpdate)) {
return false;
}
StatementUpdate other = (StatementUpdate) o2;
return Objects.equals(o1.getAdded(), other.getAdded())
&& Objects.equals(o1.getReplaced(), other.getReplaced())
&& Objects.equals(o1.getRemoved(), other.getRemoved());
}
private static boolean equalsEntityUpdate(EntityUpdate o1, EntityUpdate o2) {
return Objects.equals(o1.getEntityId(), o2.getEntityId())
&& o1.getBaseRevisionId() == o2.getBaseRevisionId();
}
private static boolean equalsStatementDocumentUpdate(StatementDocumentUpdate o1, StatementDocumentUpdate o2) {
return equalsEntityUpdate(o1, o2)
&& Objects.equals(o1.getStatements(), o2.getStatements());
}
private static boolean equalsLabeledStatementDocumentUpdate(
LabeledStatementDocumentUpdate o1, LabeledStatementDocumentUpdate o2) {
return equalsStatementDocumentUpdate(o1, o2)
&& Objects.equals(o1.getLabels(), o2.getLabels());
}
private static boolean equalsTermedStatementDocumentUpdate(
TermedStatementDocumentUpdate o1, TermedStatementDocumentUpdate o2) {
return equalsLabeledStatementDocumentUpdate(o1, o2)
&& Objects.equals(o1.getDescriptions(), o2.getDescriptions())
&& Objects.equals(o1.getAliases(), o2.getAliases());
}
/**
* Returns {@code true} if the two {@link MediaInfoUpdate} objects contain
* exactly the same data. It does not matter whether they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsMediaInfoUpdate(MediaInfoUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof MediaInfoUpdate)) {
return false;
}
MediaInfoUpdate other = (MediaInfoUpdate) o2;
return equalsLabeledStatementDocumentUpdate(o1, other);
}
/**
* Returns {@code true} if the two {@link ItemUpdate} objects contain exactly
* the same data. It does not matter whether they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsItemUpdate(ItemUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof ItemUpdate)) {
return false;
}
ItemUpdate other = (ItemUpdate) o2;
return equalsTermedStatementDocumentUpdate(o1, other)
&& Objects.equals(o1.getModifiedSiteLinks(), other.getModifiedSiteLinks())
&& Objects.equals(o1.getRemovedSiteLinks(), other.getRemovedSiteLinks());
}
/**
* Returns {@code true} if the two {@link PropertyUpdate} objects contain
* exactly the same data. It does not matter whether they are different
* implementations of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsPropertyUpdate(PropertyUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof PropertyUpdate)) {
return false;
}
PropertyUpdate other = (PropertyUpdate) o2;
return equalsTermedStatementDocumentUpdate(o1, other);
}
/**
* Returns {@code true} if the two {@link SenseUpdate} objects contain exactly
* the same data. It does not matter whether they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsSenseUpdate(SenseUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof SenseUpdate)) {
return false;
}
SenseUpdate other = (SenseUpdate) o2;
return equalsStatementDocumentUpdate(o1, other)
&& Objects.equals(o1.getGlosses(), other.getGlosses());
}
/**
* Returns {@code true} if the two {@link FormUpdate} objects contain exactly
* the same data. It does not matter whether they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsFormUpdate(FormUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof FormUpdate)) {
return false;
}
FormUpdate other = (FormUpdate) o2;
return equalsStatementDocumentUpdate(o1, other)
&& Objects.equals(o1.getRepresentations(), other.getRepresentations())
&& Objects.equals(o1.getGrammaticalFeatures(), other.getGrammaticalFeatures());
}
/**
* Returns {@code true} if the two {@link LexemeUpdate} objects contain exactly
* the same data. It does not matter whether they are different implementations
* of the interface as long as their content is the same.
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return {@code true} if both objects are equal
*/
public static boolean equalsLexemeUpdate(LexemeUpdate o1, Object o2) {
if (o2 == o1) {
return true;
}
if (!(o2 instanceof LexemeUpdate)) {
return false;
}
LexemeUpdate other = (LexemeUpdate) o2;
return equalsStatementDocumentUpdate(o1, other)
&& Objects.equals(o1.getLanguage(), other.getLanguage())
&& Objects.equals(o1.getLexicalCategory(), other.getLexicalCategory())
&& Objects.equals(o1.getLemmas(), other.getLemmas())
&& Objects.equals(o1.getAddedSenses(), other.getAddedSenses())
&& Objects.equals(o1.getUpdatedSenses(), other.getUpdatedSenses())
&& Objects.equals(o1.getRemovedSenses(), other.getRemovedSenses())
&& Objects.equals(o1.getAddedForms(), other.getAddedForms())
&& Objects.equals(o1.getUpdatedForms(), other.getUpdatedForms())
&& Objects.equals(o1.getRemovedForms(), other.getRemovedForms());
}
}
FormUpdateBuilder.java 0000664 0000000 0000000 00000016030 14447725663 0035433 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormUpdate;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link FormUpdate} objects.
*/
public class FormUpdateBuilder extends StatementDocumentUpdateBuilder {
private TermUpdate representations = TermUpdate.EMPTY;
private Set grammaticalFeatures;
private FormUpdateBuilder(FormIdValue formId, long revisionId) {
super(formId, revisionId);
}
private FormUpdateBuilder(FormDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of form entity with given
* revision ID.
*
* @param formId
* ID of the form that is to be updated
* @param revisionId
* ID of the base form revision to be updated or zero if not
* available
* @return update builder object
* @throws NullPointerException
* if {@code formId} is {@code null}
* @throws IllegalArgumentException
* if {@code formId} is a placeholder ID
*/
public static FormUpdateBuilder forBaseRevisionId(FormIdValue formId, long revisionId) {
return new FormUpdateBuilder(formId, revisionId);
}
/**
* Creates new builder object for constructing update of form entity with given
* ID.
*
* @param formId
* ID of the form that is to be updated
* @return update builder object
* @throws NullPointerException
* if {@code formId} is {@code null}
* @throws IllegalArgumentException
* if {@code formId} is a placeholder ID
*/
public static FormUpdateBuilder forEntityId(FormIdValue formId) {
return new FormUpdateBuilder(formId, 0);
}
/**
* Creates new builder object for constructing update of given base form entity
* revision. Provided form document might not represent the latest revision of
* the form entity as currently stored in Wikibase. It will be used for
* validation in builder methods. If the document has revision ID, it will be
* used to detect edit conflicts.
*
* @param revision
* base form entity revision to be updated
* @return update builder object
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
public static FormUpdateBuilder forBaseRevision(FormDocument revision) {
return new FormUpdateBuilder(revision);
}
@Override
FormIdValue getEntityId() {
return (FormIdValue) super.getEntityId();
}
@Override
FormDocument getBaseRevision() {
return (FormDocument) super.getBaseRevision();
}
@Override
public FormUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
/**
* Updates form representations. If this method is called multiple times,
* changes are accumulated. If base entity revision was provided, redundant
* changes are silently ignored, resulting in empty update.
*
* @param update
* changes in form representations
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public FormUpdateBuilder updateRepresentations(TermUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
TermUpdateBuilder combined = getBaseRevision() != null
? TermUpdateBuilder.forTerms(getBaseRevision().getRepresentations().values())
: TermUpdateBuilder.create();
combined.append(representations);
combined.append(update);
representations = combined.build();
return this;
}
/**
* Sets grammatical features of the form. Any previously assigned grammatical
* features are removed. To remove all grammatical features without replacement,
* call this method with empty collection. If base entity revision was provided,
* attempt to replace grammatical features with identical set is silently
* ignored, resulting in empty update.
*
* @param features
* new grammatical features of the form
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code features} or any of its items is {@code null}
* @throws IllegalArgumentException
* if any item ID in {@code features} is a placeholder ID or if
* there are duplicate features
*/
public FormUpdateBuilder setGrammaticalFeatures(Collection features) {
Objects.requireNonNull(features, "Collection of grammatical features cannot be null.");
for (ItemIdValue id : features) {
Objects.requireNonNull(id, "Grammatical feature IDs must not be null.");
Validate.isTrue(!id.isPlaceholder(), "Grammatical feature ID cannot be a placeholder ID.");
}
Set set = new HashSet<>(features);
Validate.isTrue(set.size() == features.size(), "Every grammatical feature must be unique.");
if (getBaseRevision() != null && set.equals(new HashSet<>(getBaseRevision().getGrammaticalFeatures()))) {
grammaticalFeatures = null;
return this;
}
grammaticalFeatures = new HashSet<>(features);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes from
* the update are added on top of changes already present in this builder
* object.
*
* @param update
* form update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if {@code update} cannot be applied to base entity revision (if
* available)
*/
public FormUpdateBuilder append(FormUpdate update) {
super.append(update);
updateRepresentations(update.getRepresentations());
if (update.getGrammaticalFeatures().isPresent()) {
setGrammaticalFeatures(update.getGrammaticalFeatures().get());
}
return this;
}
@Override
public FormUpdate build() {
return Datamodel.makeFormUpdate(getEntityId(), getBaseRevisionId(),
representations, grammaticalFeatures, statements);
}
}
Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/Hash.java 0000664 0000000 0000000 00000042610 14447725663 0033023 0 ustar 00root root 0000000 0000000 /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Objects;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.Claim;
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityRedirectDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityUpdate;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormUpdate;
import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemUpdate;
import org.wikidata.wdtk.datamodel.interfaces.LabeledStatementDocumentUpdate;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyUpdate;
import org.wikidata.wdtk.datamodel.interfaces.QuantityValue;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseUpdate;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementDocumentUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StringValue;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermedDocument;
import org.wikidata.wdtk.datamodel.interfaces.TermedStatementDocumentUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TimeValue;
import org.wikidata.wdtk.datamodel.interfaces.ValueSnak;
/**
* Static class for computing a hashcode of arbitrary data objects using only
* their interfaces. This can be used to implement the hashCode() method of
* arbitrary interface implementations. More efficient solutions might exist if
* the object that implements an interface is of a specific known type, but the
* methods here could always be used as a fallback or default.
*
* @author Markus Kroetzsch
*
*/
public class Hash {
/**
* Prime number used to build hashes.
*/
private static final int PRIME = 31;
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(EntityIdValue o) {
int result;
result = o.getId().hashCode();
result = PRIME * result + o.getSiteIri().hashCode();
result = PRIME * result + o.getEntityType().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(DatatypeIdValue o) {
return o.getIri().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(TimeValue o) {
int result;
result = Long.hashCode(o.getYear());
result = PRIME * result + o.getMonth();
result = PRIME * result + o.getDay();
result = PRIME * result + o.getHour();
result = PRIME * result + o.getMinute();
result = PRIME * result + o.getSecond();
result = PRIME * result + o.getPrecision();
result = PRIME * result + o.getBeforeTolerance();
result = PRIME * result + o.getAfterTolerance();
result = PRIME * result + o.getTimezoneOffset();
result = PRIME * result + o.getPreferredCalendarModel().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(GlobeCoordinatesValue o) {
int result;
result = o.getGlobe().hashCode();
long value;
value = Double.valueOf(o.getLatitude()).hashCode();
result = PRIME * result + (int) (value ^ (value >>> 32));
value = Double.valueOf(o.getLongitude()).hashCode();
result = PRIME * result + (int) (value ^ (value >>> 32));
value = Double.valueOf(o.getPrecision()).hashCode();
result = PRIME * result + (int) (value ^ (value >>> 32));
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(StringValue o) {
return o.getString().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(MonolingualTextValue o) {
int result;
result = o.getLanguageCode().hashCode();
result = PRIME * result + o.getText().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(QuantityValue o) {
int result;
result = o.getNumericValue().hashCode();
result = PRIME * result + o.getUnit().hashCode();
if(o.getLowerBound() != null) {
result = PRIME * result + o.getLowerBound().hashCode();
}
if(o.getUpperBound() != null) {
result = PRIME * result + o.getUpperBound().hashCode();
}
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(ValueSnak o) {
int result;
result = o.getValue().hashCode();
result = PRIME * result + o.getPropertyId().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SomeValueSnak o) {
return o.getPropertyId().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(NoValueSnak o) {
return o.getPropertyId().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SnakGroup o) {
return o.getSnaks().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(Claim o) {
int result;
result = o.getSubject().hashCode();
result = PRIME * result + o.getMainSnak().hashCode();
result = PRIME * result + o.getQualifiers().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(Reference o) {
return o.getSnakGroups().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(Statement o) {
int result;
result = o.getSubject().hashCode();
result = PRIME * result + o.getMainSnak().hashCode();
result = PRIME * result + o.getQualifiers().hashCode();
result = PRIME * result + o.getReferences().hashCode();
result = PRIME * result + o.getRank().hashCode();
result = PRIME * result + o.getStatementId().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(StatementGroup o) {
return o.getStatements().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SiteLink o) {
int result;
result = o.getBadges().hashCode();
result = PRIME * result + o.getPageTitle().hashCode();
result = PRIME * result + o.getSiteKey().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(PropertyDocument o) {
int result;
result = hashCodeForTermedDocument(o);
result = PRIME * result + o.getStatementGroups().hashCode();
result = PRIME * result + o.getDatatype().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(ItemDocument o) {
int result;
result = hashCodeForTermedDocument(o);
result = PRIME * result + o.getStatementGroups().hashCode();
result = PRIME * result + o.getSiteLinks().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(LexemeDocument o) {
int result;
result = o.getLexicalCategory().hashCode();
result = PRIME * result + o.getLanguage().hashCode();
result = PRIME * result + o.getLemmas().hashCode();
result = PRIME * result + Long.hashCode(o.getRevisionId());
result = PRIME * result + o.getStatementGroups().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(FormDocument o) {
int result;
result = o.getGrammaticalFeatures().hashCode();
result = PRIME * result + o.getRepresentations().hashCode();
result = PRIME * result + Long.hashCode(o.getRevisionId());
result = PRIME * result + o.getStatementGroups().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SenseDocument o) {
int result;
result = o.getGlosses().hashCode();
result = PRIME * result + Long.hashCode(o.getRevisionId());
result = PRIME * result + o.getStatementGroups().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(MediaInfoDocument o) {
int result;
result = o.getLabels().hashCode();
result = PRIME * result + o.getStatementGroups().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
private static int hashCodeForTermedDocument(TermedDocument o) {
int result;
result = o.getAliases().hashCode();
result = PRIME * result + o.getDescriptions().hashCode();
result = PRIME * result + o.getLabels().hashCode();
result = PRIME * result + Long.hashCode(o.getRevisionId());
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(EntityRedirectDocument o) {
int result;
result = o.getEntityId().hashCode();
result = PRIME * result + o.getTargetId().hashCode();
result = PRIME * result + Long.hashCode(o.getRevisionId());
return result;
}
/**
* Calculates hash code for given {@link TermUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(TermUpdate o) {
return Objects.hash(o.getModified(), o.getRemoved());
}
/**
* Calculates hash code for given {@link AliasUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(AliasUpdate o) {
return Objects.hash(o.getRecreated(), o.getAdded(), o.getRemoved());
}
/**
* Calculates hash code for given {@link StatementUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(StatementUpdate o) {
return Objects.hash(o.getAdded(), o.getReplaced(), o.getRemoved());
}
private static int hashCodeForEntityUpdate(EntityUpdate o) {
return Objects.hash(o.getEntityId(), o.getBaseRevisionId());
}
private static int hashCodeForStatementDocumentUpdate(StatementDocumentUpdate o) {
return hashCodeForEntityUpdate(o) * PRIME + Objects.hash(o.getStatements());
}
private static int hashCodeForLabeledStatementDocumentUpdate(LabeledStatementDocumentUpdate o) {
return hashCodeForStatementDocumentUpdate(o) * PRIME + Objects.hash(o.getLabels());
}
private static int hashCodeForTermedStatementDocumentUpdate(TermedStatementDocumentUpdate o) {
return hashCodeForLabeledStatementDocumentUpdate(o) * PRIME + Objects.hash(o.getDescriptions(), o.getAliases());
}
/**
* Calculates hash code for given {@link MediaInfoUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(MediaInfoUpdate o) {
return hashCodeForLabeledStatementDocumentUpdate(o);
}
/**
* Calculates hash code for given {@link ItemUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(ItemUpdate o) {
return hashCodeForTermedStatementDocumentUpdate(o) * PRIME
+ Objects.hash(o.getModifiedSiteLinks(), o.getRemovedSiteLinks());
}
/**
* Calculates hash code for given {@link PropertyUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(PropertyUpdate o) {
return hashCodeForTermedStatementDocumentUpdate(o);
}
/**
* Calculates hash code for given {@link SenseUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(SenseUpdate o) {
return hashCodeForStatementDocumentUpdate(o) * PRIME + Objects.hash(o.getGlosses());
}
/**
* Calculates hash code for given {@link FormUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(FormUpdate o) {
return hashCodeForStatementDocumentUpdate(o) * PRIME
+ Objects.hash(o.getRepresentations(), o.getGrammaticalFeatures());
}
/**
* Calculates hash code for given {@link LexemeUpdate} object.
*
* @see Object#hashCode()
* @param o
* the object to create a hash for
* @return object's hash code
*/
public static int hashCode(LexemeUpdate o) {
return hashCodeForStatementDocumentUpdate(o) * PRIME + Objects.hash(
o.getLanguage(),
o.getLexicalCategory(),
o.getLemmas(),
o.getAddedSenses(),
o.getUpdatedSenses(),
o.getRemovedSenses(),
o.getAddedForms(),
o.getUpdatedForms(),
o.getRemovedForms());
}
}
ItemDocumentBuilder.java 0000664 0000000 0000000 00000010350 14447725663 0035761 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import java.util.Arrays;
import java.util.HashMap;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
/**
* Builder class to construct {@link ItemDocument} objects.
*
* @author Markus Kroetzsch
*
*/
public class ItemDocumentBuilder extends
EntityDocumentBuilder {
private final HashMap siteLinks = new HashMap<>();
/**
* Constructor to start the build from a blank item.
*
* @param itemIdValue
*/
protected ItemDocumentBuilder(ItemIdValue itemIdValue) {
super(itemIdValue);
}
/**
* Constructor to start the build from an existing item.
*
* @param initialDocument
* the item to start the build from
*/
protected ItemDocumentBuilder(ItemDocument initialDocument) {
super(initialDocument);
for(SiteLink siteLink : initialDocument.getSiteLinks().values()) {
withSiteLink(siteLink);
}
}
/**
* Starts the construction of an {@link ItemDocument} with the given id.
*
* @param itemIdValue
* id of the newly constructed item document
* @return builder object to continue construction
*/
public static ItemDocumentBuilder forItemId(ItemIdValue itemIdValue) {
return new ItemDocumentBuilder(itemIdValue);
}
/**
* Starts the construction of an {@link ItemDocument} from an existing value.
*
* @param initialDocument
* the item to start the construction from
* @return builder object to continue construction
*/
public static ItemDocumentBuilder fromItemDocument(ItemDocument initialDocument) {
return new ItemDocumentBuilder(initialDocument);
}
/**
* Returns the {@link ItemDocument} that has been built.
*
* @return constructed item document
* @throws IllegalStateException
* if the object was built already
*/
@Override
public ItemDocument build() {
prepareBuild();
return factory.getItemDocument((ItemIdValue) this.entityIdValue,
this.labels, this.descriptions, this.aliases,
getStatementGroups(), this.siteLinks, this.revisionId);
}
/**
* Adds an additional site link to the constructed document.
*
* @param siteLink
* the additional site link
*/
public ItemDocumentBuilder withSiteLink(SiteLink siteLink) {
this.siteLinks.put(siteLink.getSiteKey(), siteLink);
return this;
}
/**
* Adds an additional site link to the constructed document.
*
* @param title
* the title of the linked page
* @param siteKey
* identifier of the site, e.g., "enwiki"
* @param badges
* one or more badges
*/
public ItemDocumentBuilder withSiteLink(String title, String siteKey,
ItemIdValue... badges) {
withSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges)));
return this;
}
/**
* Changes the entity value id for the constructed document.
* See {@link EntityDocument#getEntityId()}.
*
* @param entityId
* the entity id, which must be an ItemIdValue
* @return builder object to continue construction
*/
@Override
public ItemDocumentBuilder withEntityId(EntityIdValue entityId) {
if (!(entityId instanceof ItemIdValue)) {
throw new IllegalArgumentException("The entity id of an ItemDocument must be an ItemIdValue.");
}
return super.withEntityId(entityId);
}
@Override
protected ItemDocumentBuilder getThis() {
return this;
}
}
ItemUpdateBuilder.java 0000664 0000000 0000000 00000016661 14447725663 0035440 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemUpdate;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link ItemUpdate} objects.
*/
public class ItemUpdateBuilder extends TermedDocumentUpdateBuilder {
private final Map modifiedSiteLinks = new HashMap<>();
private final Set removedSiteLinks = new HashSet<>();
private ItemUpdateBuilder(ItemIdValue itemId, long revisionId) {
super(itemId, revisionId);
}
private ItemUpdateBuilder(ItemDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of item entity with given
* revision ID.
*
* @param itemId
* ID of the item entity that is to be updated
* @param revisionId
* ID of the base item revision to be updated or zero if not
* available
* @return update builder object
* @throws NullPointerException
* if {@code itemId} is {@code null}
* @throws IllegalArgumentException
* if {@code itemId} is a placeholder ID
*/
public static ItemUpdateBuilder forBaseRevisionId(ItemIdValue itemId, long revisionId) {
return new ItemUpdateBuilder(itemId, revisionId);
}
/**
* Creates new builder object for constructing update of item entity with given
* ID.
*
* @param itemId
* ID of the item entity that is to be updated
* @return update builder object
* @throws NullPointerException
* if {@code itemId} is {@code null}
* @throws IllegalArgumentException
* if {@code itemId} is a placeholder ID
*/
public static ItemUpdateBuilder forEntityId(ItemIdValue itemId) {
return new ItemUpdateBuilder(itemId, 0);
}
/**
* Creates new builder object for constructing update of given base item entity
* revision. Provided item document might not represent the latest revision of
* the item entity as currently stored in Wikibase. It will be used for
* validation in builder methods. If the document has revision ID, it will be
* used to detect edit conflicts.
*
* @param revision
* base item entity revision to be updated
* @return update builder object
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
public static ItemUpdateBuilder forBaseRevision(ItemDocument revision) {
return new ItemUpdateBuilder(revision);
}
@Override
ItemIdValue getEntityId() {
return (ItemIdValue) super.getEntityId();
}
@Override
ItemDocument getBaseRevision() {
return (ItemDocument) super.getBaseRevision();
}
@Override
public ItemUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
@Override
public ItemUpdateBuilder updateLabels(TermUpdate update) {
super.updateLabels(update);
return this;
}
@Override
public ItemUpdateBuilder updateDescriptions(TermUpdate update) {
super.updateDescriptions(update);
return this;
}
@Override
public ItemUpdateBuilder updateAliases(String language, AliasUpdate update) {
super.updateAliases(language, update);
return this;
}
/**
* Adds or replaces site link. If there is no site link for the site key, new
* site link is added. If a site link with this site key already exists, it is
* replaced. Site links with other site keys are not touched. Calling this
* method overrides any previous changes made with the same site key by this
* method or {@link #removeSiteLink(String)}.
*
* If base entity revision was provided, attempt to overwrite some site link
* with identical site link will be silently ignored, resulting in empty update.
*
* @param link
* new or replacement site link
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code link} is {@code null}
*/
public ItemUpdateBuilder putSiteLink(SiteLink link) {
Objects.requireNonNull(link, "Site link cannot be null.");
if (getBaseRevision() != null) {
SiteLink original = getBaseRevision().getSiteLinks().get(link.getSiteKey());
if (link.equals(original)) {
modifiedSiteLinks.remove(link.getSiteKey());
removedSiteLinks.remove(link.getSiteKey());
return this;
}
}
modifiedSiteLinks.put(link.getSiteKey(), link);
removedSiteLinks.remove(link.getSiteKey());
return this;
}
/**
* Removes site link. Site links with other site keys are not touched. Calling
* this method overrides any previous changes made with the same site key by
* this method or {@link #putSiteLink(SiteLink)}.
*
* If base entity revision was provided, attempts to remove missing site links
* will be silently ignored, resulting in empty update.
*
* @param site
* site key of the removed site link
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code site} is {@code null}
* @throws IllegalArgumentException
* if {@code site} is blank
*/
public ItemUpdateBuilder removeSiteLink(String site) {
Validate.notBlank(site, "Site key cannot be null.");
if (getBaseRevision() != null && !getBaseRevision().getSiteLinks().containsKey(site)) {
modifiedSiteLinks.remove(site);
return this;
}
removedSiteLinks.add(site);
modifiedSiteLinks.remove(site);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes from
* the update are added on top of changes already present in this builder
* object.
*
* @param update
* item update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if {@code update} cannot be applied to base entity revision (if
* available)
*/
public ItemUpdateBuilder append(ItemUpdate update) {
super.append(update);
for (SiteLink link : update.getModifiedSiteLinks().values()) {
putSiteLink(link);
}
for (String site : update.getRemovedSiteLinks()) {
removeSiteLink(site);
}
return this;
}
@Override
public ItemUpdate build() {
return Datamodel.makeItemUpdate(getEntityId(), getBaseRevisionId(), labels, descriptions, aliases, statements,
modifiedSiteLinks.values(), removedSiteLinks);
}
}
JsonDeserializer.java 0000664 0000000 0000000 00000011701 14447725663 0035332 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*-
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2020 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import org.wikidata.wdtk.datamodel.implementation.EntityDocumentImpl;
import org.wikidata.wdtk.datamodel.implementation.EntityRedirectDocumentImpl;
import org.wikidata.wdtk.datamodel.implementation.ItemDocumentImpl;
import org.wikidata.wdtk.datamodel.implementation.LexemeDocumentImpl;
import org.wikidata.wdtk.datamodel.implementation.MediaInfoDocumentImpl;
import org.wikidata.wdtk.datamodel.implementation.PropertyDocumentImpl;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityRedirectDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectReader;
/**
* Helper to deserialize datamodel objects from their
* JSON representation.
*
* We accept empty arrays as empty maps since there has
* been a confusion in the past between the two:
* https://phabricator.wikimedia.org/T138104
*
* @author Antonin Delpeuch
*/
public class JsonDeserializer {
private ObjectReader entityDocumentReader;
private ObjectReader itemReader;
private ObjectReader propertyReader;
private ObjectReader lexemeReader;
private ObjectReader mediaInfoReader;
private ObjectReader entityRedirectReader;
/**
* Constructs a new JSON deserializer for the
* designated site.
*
* @param siteIri
* Root IRI of the site to deserialize for
*/
public JsonDeserializer(String siteIri) {
DatamodelMapper mapper = new DatamodelMapper(siteIri);
entityDocumentReader = mapper.readerFor(EntityDocumentImpl.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
itemReader = mapper.readerFor(ItemDocumentImpl.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
propertyReader = mapper.readerFor(PropertyDocumentImpl.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
lexemeReader = mapper.readerFor(LexemeDocumentImpl.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
mediaInfoReader = mapper.readerFor(MediaInfoDocumentImpl.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
entityRedirectReader = mapper.readerFor(EntityRedirectDocumentImpl.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
}
/**
* Deserializes a JSON string into an {@link ItemDocument}.
* @throws JsonProcessingException
if the JSON payload is invalid
*/
public ItemDocument deserializeItemDocument(String json) throws JsonProcessingException {
return itemReader.readValue(json);
}
/**
* Deserializes a JSON string into a {@link PropertyDocument}.
* @throws JsonProcessingException
if the JSON payload is invalid
*/
public PropertyDocument deserializePropertyDocument(String json) throws JsonProcessingException {
return propertyReader.readValue(json);
}
/**
* Deserializes a JSON string into a {@link LexemeDocument}.
* @throws JsonProcessingException
if the JSON payload is invalid
*/
public LexemeDocument deserializeLexemeDocument(String json) throws JsonProcessingException {
return lexemeReader.readValue(json);
}
/**
* Deserializes a JSON string into a {@link MediaInfoDocument}.
* @throws JsonProcessingException
if the JSON payload is invalid
*/
public MediaInfoDocument deserializeMediaInfoDocument(String json) throws JsonProcessingException {
return mediaInfoReader.readValue(json);
}
/**
* Deserializes a JSON string into a {@link EntityDocument}.
* @throws JsonProcessingException
if the JSON payload is invalid
*/
public EntityDocument deserializeEntityDocument(String json) throws JsonProcessingException {
return entityDocumentReader.readValue(json);
}
/**
* Deserializes a JSON string into a {@link EntityRedirectDocument}.
* @throws JsonProcessingException
if the JSON payload is invalid
*/
public EntityRedirectDocument deserializeEntityRedirectDocument(String json) throws JsonProcessingException {
return entityRedirectReader.readValue(json);
}
}
JsonSerializer.java 0000664 0000000 0000000 00000017411 14447725663 0035025 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocumentDumpProcessor;
import org.wikidata.wdtk.datamodel.interfaces.EntityUpdate;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
/**
* This class implements {@link EntityDocumentDumpProcessor} to provide a
* serializer for {@link EntityDocument} objects in JSON.
*
* The implementation does not check if {@link #open()} has been called before
* the first document is serialized. It is the responsibility of the caller to
* do this.
*
* Implementations of the data model are expected to be appropriately serializable
* to JSON with Jackson.
*
* @author Markus Kroetzsch
*
*/
public class JsonSerializer implements EntityDocumentDumpProcessor {
private static final Logger logger = LoggerFactory.getLogger(JsonSerializer.class);
private static final byte[] JSON_START_LIST = "[\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] JSON_SEP = ",\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] JSON_END_LIST = "\n]".getBytes(StandardCharsets.UTF_8);
/**
* The stream that the resulting JSON is written to.
*/
private final OutputStream outputStream;
/**
* Object mapper that is used to serialize JSON.
*/
protected static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
/*
* Support for Optional properties.
*/
mapper.registerModule(new Jdk8Module());
}
/**
* Counter for the number of documents serialized so far.
*/
private int entityDocumentCount;
/**
* Creates a new JSON serializer that writes its output to the given stream.
* The output stream will be managed by the object, i.e., it will be closed
* when {@link #close()} is call ed.
*
* @param outputStream
* the output stream to write to
*/
public JsonSerializer(OutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public void open() {
this.entityDocumentCount = 0;
try {
this.outputStream.write(JSON_START_LIST);
} catch (IOException e) {
reportException(e);
}
}
@Override
public void processItemDocument(ItemDocument itemDocument) {
serializeEntityDocument(itemDocument);
}
@Override
public void processPropertyDocument(PropertyDocument propertyDocument) {
serializeEntityDocument(propertyDocument);
}
@Override
public void processLexemeDocument(LexemeDocument lexemeDocument) {
serializeEntityDocument(lexemeDocument);
}
@Override
public void processMediaInfoDocument(MediaInfoDocument mediaInfoDocument) {
serializeEntityDocument(mediaInfoDocument);
}
@Override
public void close() {
try {
this.outputStream.write(JSON_END_LIST);
this.outputStream.close();
} catch (IOException e) {
reportException(e);
}
}
/**
* Returns the number of entity documents serialized so far.
*
* @return number of serialized entity documents
*/
public int getEntityDocumentCount() {
return this.entityDocumentCount;
}
/**
* Reports a given exception as a RuntimeException, since the interface does
* not allow us to throw checked exceptions directly.
*
* @param e
* the exception to report
* @throws RuntimeException
* in all cases
*/
private void reportException(Exception e) {
logger.error("Failed to write JSON export: " + e.toString());
throw new RuntimeException(e.toString(), e);
}
/**
* Writes the JSON serialization of the given {@link EntityDocument}.
*
* @param entityDocument
* the document to serialize
*/
private void serializeEntityDocument(EntityDocument entityDocument) {
try {
if (this.entityDocumentCount > 0) {
this.outputStream.write(JSON_SEP);
}
mapper.writeValue(this.outputStream, entityDocument);
} catch (IOException e) {
reportException(e);
}
this.entityDocumentCount++;
}
/**
* Serializes the given object in JSON and returns the resulting string.
* Throws if the serialization fails.
*
* @param entityDocument
* object to serialize
* @return JSON serialization
* @throws JsonProcessingException if the object cannot be serialized
*/
public static String getJsonString(EntityDocument entityDocument) throws JsonProcessingException {
return mapper.writeValueAsString(entityDocument);
}
/**
* Serializes the given object in JSON and returns the resulting string.
* Throws if the serialization fails.
*
* @param itemDocument
* object to serialize
* @return JSON serialization
* @throws JsonProcessingException if the object cannot be serialized
*/
public static String getJsonString(ItemDocument itemDocument) throws JsonProcessingException {
return mapper.writeValueAsString(itemDocument);
}
/**
* Serializes the given object in JSON and returns the resulting string.
* Throws if the serialization fails.
*
* @param propertyDocument
* object to serialize
* @return JSON serialization
* @throws JsonProcessingException if the object cannot be serialized
*/
public static String getJsonString(PropertyDocument propertyDocument) throws JsonProcessingException {
return mapper.writeValueAsString(propertyDocument);
}
/**
* Serializes the given object in JSON and returns the resulting string.
* Throws if the serialization fails.
*
* @param mediaInfoDocument
* object to serialize
* @return JSON serialization
* @throws JsonProcessingException if the object cannot be serialized
*/
public static String getJsonString(MediaInfoDocument mediaInfoDocument) throws JsonProcessingException {
return mapper.writeValueAsString(mediaInfoDocument);
}
/**
* Serializes the given object in JSON and returns the resulting string.
* Throws if the serialization fails.
*
* @param statement
* object to serialize
* @return JSON serialization
* @throws JsonProcessingException if the object cannot be serialized
*/
public static String getJsonString(Statement statement) throws JsonProcessingException {
return mapper.writeValueAsString(statement);
}
/**
* Serializes the given object in JSON and returns the resulting string.
* Throws if the serialization fails.
*
* @param update
* object to serialize
* @return JSON serialization
* @throws JsonProcessingException if the object cannot be serialized
*/
public static String getJsonString(EntityUpdate update) throws JsonProcessingException {
return mapper.writeValueAsString(update);
}
}
LabeledDocumentUpdateBuilder.java 0000664 0000000 0000000 00000016273 14447725663 0037570 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Objects;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LabeledStatementDocument;
import org.wikidata.wdtk.datamodel.interfaces.LabeledStatementDocumentUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermedStatementDocument;
/**
* Builder for incremental construction of
* {@link LabeledStatementDocumentUpdate} objects.
*/
public abstract class LabeledDocumentUpdateBuilder extends StatementDocumentUpdateBuilder {
TermUpdate labels = TermUpdate.EMPTY;
/**
* Initializes new builder object for constructing update of entity with given
* ID.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is a placeholder ID
*/
protected LabeledDocumentUpdateBuilder(EntityIdValue entityId, long revisionId) {
super(entityId, revisionId);
}
/**
* Initializes new builder object for constructing update of given base entity
* revision.
*
* @param revision
* base entity revision to be updated
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
protected LabeledDocumentUpdateBuilder(LabeledStatementDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of entity with given
* revision ID.
*
* Supported entity IDs include {@link ItemIdValue}, {@link PropertyIdValue},
* and {@link MediaInfoIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it is a
* placeholder ID
*/
public static LabeledDocumentUpdateBuilder forBaseRevisionId(EntityIdValue entityId, long revisionId) {
Objects.requireNonNull(entityId, "Entity ID cannot be null.");
if (entityId instanceof MediaInfoIdValue) {
return MediaInfoUpdateBuilder.forBaseRevisionId((MediaInfoIdValue) entityId, revisionId);
}
return TermedDocumentUpdateBuilder.forBaseRevisionId(entityId, revisionId);
}
/**
* Creates new builder object for constructing update of entity with given ID.
*
* Supported entity IDs include {@link ItemIdValue}, {@link PropertyIdValue},
* and {@link MediaInfoIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it is a
* placeholder ID
*/
public static LabeledDocumentUpdateBuilder forEntityId(EntityIdValue entityId) {
return forBaseRevisionId(entityId, 0);
}
/**
* Creates new builder object for constructing update of given base entity
* revision. Provided entity document might not represent the latest revision of
* the entity as currently stored in Wikibase. It will be used for validation in
* builder methods. If the document has revision ID, it will be used to detect
* edit conflicts.
*
* Supported entity types include {@link ItemDocument},
* {@link PropertyDocument}, and {@link MediaInfoDocument}.
*
* @param revision
* base entity revision to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} is of unrecognized type or its ID is a
* placeholder ID
*/
public static LabeledDocumentUpdateBuilder forBaseRevision(LabeledStatementDocument revision) {
Objects.requireNonNull(revision, "Base entity revision cannot be null.");
if (revision instanceof MediaInfoDocument) {
return MediaInfoUpdateBuilder.forBaseRevision((MediaInfoDocument) revision);
}
if (revision instanceof TermedStatementDocument) {
return TermedDocumentUpdateBuilder.forBaseRevision((TermedStatementDocument) revision);
}
throw new IllegalArgumentException("Unrecognized entity document type.");
}
@Override
LabeledStatementDocument getBaseRevision() {
return (LabeledStatementDocument) super.getBaseRevision();
}
@Override
public LabeledDocumentUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
/**
* Updates entity labels. If this method is called multiple times, changes are
* accumulated. If base entity revision was provided, redundant changes are
* silently ignored, resulting in empty update.
*
* @param update
* changes in entity labels
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public LabeledDocumentUpdateBuilder updateLabels(TermUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
TermUpdateBuilder combined = getBaseRevision() != null
? TermUpdateBuilder.forTerms(getBaseRevision().getLabels().values())
: TermUpdateBuilder.create();
combined.append(labels);
combined.append(update);
labels = combined.build();
return this;
}
void append(LabeledStatementDocumentUpdate update) {
super.append(update);
updateLabels(update.getLabels());
}
/**
* Creates new {@link LabeledStatementDocumentUpdate} object with contents of
* this builder object.
*
* @return constructed object
*/
@Override
public abstract LabeledStatementDocumentUpdate build();
}
LexemeDeserializer.java 0000664 0000000 0000000 00000012146 14447725663 0035644 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*-
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2022 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.wikidata.wdtk.datamodel.implementation.*;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Custom deserializer, very close to the default serializer generated by Jackson,
* only to also accept empty json objects ({}) in place of empty lists for the list of senses.
* https://github.com/Wikidata/Wikidata-Toolkit/issues/568
*/
public class LexemeDeserializer extends StdDeserializer {
public LexemeDeserializer() {
super(LexemeDocumentImpl.class);
}
@Override
public LexemeDocumentImpl deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
if (! (node instanceof ObjectNode)) {
throw new IOException("Deserializing a lexeme can only be done from a JSON object");
}
ObjectNode object = (ObjectNode) node;
String jsonId = object.get("id").asText();
String lexicalCategory = object.get("lexicalCategory").asText();
String language = object.get("language").asText();
TypeFactory typeFactory = deserializationContext.getTypeFactory();
JsonNode lemmas1 = object.get("lemmas");
Map preLemmas = deserializationContext.readTreeAsValue(
lemmas1,
typeFactory.constructMapType(Map.class, String.class, TermImpl.class));
Map lemmas = null;
if (preLemmas != null) {
lemmas = preLemmas.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue()));
}
Map> claims = deserializationContext.readTreeAsValue(
object.get("claims"),
typeFactory.constructMapType(Map.class, typeFactory.constructType(String.class),
typeFactory.constructCollectionType(List.class, StatementImpl.PreStatement.class)));
List forms;
if (object.get("forms") instanceof ObjectNode && ((ObjectNode)object.get("forms")).isEmpty()) {
forms = Collections.emptyList();
} else {
forms = deserializationContext.readTreeAsValue(
object.get("forms"),
typeFactory.constructCollectionType(List.class, FormDocumentImpl.class));
}
List senses;
if (object.get("senses") instanceof ObjectNode && ((ObjectNode)object.get("senses")).isEmpty()) {
// case for https://github.com/Wikidata/Wikidata-Toolkit/issues/568
senses = Collections.emptyList();
} else {
senses = deserializationContext.readTreeAsValue(
object.get("senses"),
typeFactory.constructCollectionType(List.class, SenseDocumentImpl.class));
}
long lastrevid = 0;
if (object.has("lastrevid")) {
lastrevid = object.get("lastrevid").asLong();
}
String siteIri = (String) deserializationContext.findInjectableValue("siteIri", null , null);
return new LexemeDocumentImpl(
jsonId,
lexicalCategory,
language,
lemmas,
claims,
forms,
senses,
lastrevid,
siteIri
);
}
}
LexemeUpdateBuilder.java 0000664 0000000 0000000 00000037502 14447725663 0035756 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormUpdate;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LexemeUpdate;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SenseUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link LexemeUpdate} objects.
*/
public class LexemeUpdateBuilder extends StatementDocumentUpdateBuilder {
private ItemIdValue language;
private ItemIdValue lexicalCategory;
private TermUpdate lemmas = TermUpdate.EMPTY;
private final List addedSenses = new ArrayList<>();
private final Map updatedSenses = new HashMap<>();
private final Set removedSenses = new HashSet<>();
private final List addedForms = new ArrayList<>();
private final Map updatedForms = new HashMap<>();
private final Set removedForms = new HashSet<>();
private LexemeUpdateBuilder(LexemeIdValue lexemeId, long revisionId) {
super(lexemeId, revisionId);
}
private LexemeUpdateBuilder(LexemeDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of lexeme entity with
* given revision ID.
*
* @param lexemeId
* ID of the lexeme that is to be updated
* @param revisionId
* ID of the base lexeme revision to be updated or zero if not
* available
* @return update builder object
* @throws NullPointerException
* if {@code lexemeId} is {@code null}
* @throws IllegalArgumentException
* if {@code lexemeId} is a placeholder ID
*/
public static LexemeUpdateBuilder forBaseRevisionId(LexemeIdValue lexemeId, long revisionId) {
return new LexemeUpdateBuilder(lexemeId, revisionId);
}
/**
* Creates new builder object for constructing update of lexeme entity with
* given ID.
*
* @param lexemeId
* ID of the lexeme that is to be updated
* @return update builder object
* @throws NullPointerException
* if {@code lexemeId} is {@code null}
* @throws IllegalArgumentException
* if {@code lexemeId} is a placeholder ID
*/
public static LexemeUpdateBuilder forEntityId(LexemeIdValue lexemeId) {
return new LexemeUpdateBuilder(lexemeId, 0);
}
/**
* Creates new builder object for constructing update of given base lexeme
* entity revision. Provided lexeme document might not represent the latest
* revision of the lexeme entity as currently stored in Wikibase. It will be
* used for validation in builder methods. If the document has revision ID, it
* will be used to detect edit conflicts.
*
* @param revision
* base lexeme entity revision to be updated
* @return update builder object
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
public static LexemeUpdateBuilder forBaseRevision(LexemeDocument revision) {
return new LexemeUpdateBuilder(revision);
}
@Override
LexemeIdValue getEntityId() {
return (LexemeIdValue) super.getEntityId();
}
@Override
LexemeDocument getBaseRevision() {
return (LexemeDocument) super.getBaseRevision();
}
@Override
public LexemeUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
/**
* Sets lexeme language. If base entity revision was provided, attempt to
* replace lexeme language with the same value is silently ignored, resulting in
* empty update.
*
* @param language
* new lexeme language
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code language} is {@code null}
* @throws IllegalArgumentException
* if {@code language} is an invalid ID
*/
public LexemeUpdateBuilder setLanguage(ItemIdValue language) {
Objects.requireNonNull(language, "Language cannot be null.");
Validate.isTrue(!language.isPlaceholder(), "Language ID cannot be a placeholder ID.");
if (getBaseRevision() != null && getBaseRevision().getLanguage().equals(language)) {
this.language = null;
return this;
}
this.language = language;
return this;
}
/**
* Sets lexical category of the lexeme. If base entity revision was provided,
* attempt to replace lexical category with the same value is silently ignored,
* resulting in empty update.
*
* @param category
* new lexical category
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code category} is {@code null}
* @throws IllegalArgumentException
* if {@code category} is an invalid ID
*/
public LexemeUpdateBuilder setLexicalCategory(ItemIdValue category) {
Objects.requireNonNull(category, "Lexical category cannot be null.");
Validate.isTrue(!category.isPlaceholder(), "Lexical category ID cannot be a placeholder ID.");
if (getBaseRevision() != null && getBaseRevision().getLexicalCategory().equals(category)) {
lexicalCategory = null;
return this;
}
lexicalCategory = category;
return this;
}
/**
* Updates lemmas. If this method is called multiple times, changes are
* accumulated. If base entity revision was provided, redundant changes are
* silently ignored, resulting in empty update.
*
* @param update
* changes in lemmas
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public LexemeUpdateBuilder updateLemmas(TermUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
TermUpdateBuilder combined = getBaseRevision() != null
? TermUpdateBuilder.forTerms(getBaseRevision().getLemmas().values())
: TermUpdateBuilder.create();
combined.append(lemmas);
combined.append(update);
lemmas = combined.build();
return this;
}
/**
* Adds sense to the lexeme. If {@code sense} has an ID (perhaps because it is a
* modified copy of another sense), its ID is stripped to ensure the sense is
* added and no other sense is modified.
*
* @param sense
* new sense to add
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code sense} is {@code null}
*/
public LexemeUpdateBuilder addSense(SenseDocument sense) {
Objects.requireNonNull(sense, "Sense cannot be null.");
if (!sense.getEntityId().isPlaceholder()) {
sense = sense.withEntityId(SenseIdValue.NULL);
}
if (sense.getRevisionId() != 0) {
sense = sense.withRevisionId(0);
}
addedSenses.add(sense);
return this;
}
/**
* Updates existing sense in the lexeme. If this method is called multiple
* times, changes are accumulated. If base entity revision was provided, the
* update is checked against it and redundant changes are silently ignored,
* resulting in empty update.
*
* @param update
* update of existing sense
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if the sense does not exist in base revision (if available) or
* the update cannot be applied to it
* @throws IllegalStateException
* if the sense was removed by calling
* {@link #removeSense(SenseIdValue)}
*/
public LexemeUpdateBuilder updateSense(SenseUpdate update) {
Objects.requireNonNull(update, "Sense update cannot be null.");
SenseIdValue id = update.getEntityId();
Validate.validState(!removedSenses.contains(id), "Cannot update removed sense.");
SenseUpdateBuilder builder;
if (getBaseRevision() != null) {
SenseDocument original = getBaseRevision().getSenses().stream()
.filter(s -> s.getEntityId().equals(id))
.findFirst().orElse(null);
Validate.isTrue(original != null, "Cannot update sense that is not in the base revision.");
builder = SenseUpdateBuilder.forBaseRevision(original.withRevisionId(getBaseRevisionId()));
} else {
builder = SenseUpdateBuilder.forBaseRevisionId(id, getBaseRevisionId());
}
SenseUpdate prior = updatedSenses.get(id);
if (prior != null) {
builder.append(prior);
}
builder.append(update);
SenseUpdate combined = builder.build();
if (!combined.isEmpty()) {
updatedSenses.put(id, combined);
} else {
updatedSenses.remove(id);
}
return this;
}
/**
* Removes existing sense from the lexeme. Removing the same sense ID twice is
* silently tolerated. Any prior changes made by calling
* {@link #updateSense(SenseUpdate)} are discarded.
*
* @param senseId
* ID of the removed sense
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code senseId} is {@code null}
* @throws IllegalArgumentException
* if {@code senseId} is not valid or if such ID does not exist in
* base revision (if available)
*/
public LexemeUpdateBuilder removeSense(SenseIdValue senseId) {
Objects.requireNonNull(senseId, "Sense ID cannot be null.");
Validate.isTrue(!senseId.isPlaceholder(), "ID of removed sense cannot be a placeholder ID.");
if (getBaseRevision() != null) {
Validate.isTrue(getBaseRevision().getSenses().stream().anyMatch(s -> s.getEntityId().equals(senseId)),
"Cannot remove sense that is not in the base revision.");
}
removedSenses.add(senseId);
updatedSenses.remove(senseId);
return this;
}
/**
* Adds form to the lexeme. If {@code form} has an ID (perhaps because it is a
* modified copy of another form), its ID is stripped to ensure the form is
* added and no other form is modified.
*
* @param form
* new form to add
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code form} is {@code null}
*/
public LexemeUpdateBuilder addForm(FormDocument form) {
Objects.requireNonNull(form, "Form cannot be null.");
if (!form.getEntityId().isPlaceholder()) {
form = form.withEntityId(FormIdValue.NULL);
}
if (form.getRevisionId() != 0) {
form = form.withRevisionId(0);
}
addedForms.add(form);
return this;
}
/**
* Updates existing form in the lexeme. If this method is called multiple times,
* changes are accumulated. If base entity revision was provided, the update is
* checked against it and redundant changes are silently ignored, resulting in
* empty update.
*
* @param update
* update of existing form
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if the form does not exist in base revision (if available) or the
* update cannot be applied to it
* @throws IllegalStateException
* if the form was removed by calling
* {@link #removeForm(FormIdValue)}
*/
public LexemeUpdateBuilder updateForm(FormUpdate update) {
Objects.requireNonNull(update, "Form update cannot be null.");
FormIdValue id = update.getEntityId();
Validate.validState(!removedForms.contains(id), "Cannot update removed form.");
FormUpdateBuilder builder;
if (getBaseRevision() != null) {
FormDocument original = getBaseRevision().getForms().stream()
.filter(s -> s.getEntityId().equals(id))
.findFirst().orElse(null);
Validate.isTrue(original != null, "Cannot update form that is not in the base revision.");
builder = FormUpdateBuilder.forBaseRevision(original.withRevisionId(getBaseRevisionId()));
} else {
builder = FormUpdateBuilder.forBaseRevisionId(id, getBaseRevisionId());
}
FormUpdate prior = updatedForms.get(id);
if (prior != null) {
builder.append(prior);
}
builder.append(update);
FormUpdate combined = builder.build();
if (!combined.isEmpty()) {
updatedForms.put(id, combined);
} else {
updatedForms.remove(id);
}
return this;
}
/**
* Removes existing form from the lexeme. Calling this method overrides any
* previous changes made to the same form ID by {@link #updateForm(FormUpdate)}.
* Removing the same form ID twice is silently tolerated.
*
* @param formId
* ID of the removed form
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code formId} is {@code null}
* @throws IllegalArgumentException
* if {@code formId} is not valid or if such ID does not exist in
* current version of the lexeme document (if available)
*/
public LexemeUpdateBuilder removeForm(FormIdValue formId) {
Objects.requireNonNull(formId, "Form ID cannot be null.");
Validate.isTrue(!formId.isPlaceholder(), "ID of removed form cannot be a placeholder ID.");
if (getBaseRevision() != null) {
Validate.isTrue(getBaseRevision().getForms().stream().anyMatch(s -> s.getEntityId().equals(formId)),
"Cannot remove form that is not in the base revision.");
}
removedForms.add(formId);
updatedForms.remove(formId);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes from
* the update are added on top of changes already present in this builder
* object.
*
* @param update
* lexeme update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if {@code update} cannot be applied to base entity revision (if
* available)
*/
public LexemeUpdateBuilder append(LexemeUpdate update) {
super.append(update);
if (update.getLanguage().isPresent()) {
setLanguage(update.getLanguage().get());
}
if (update.getLexicalCategory().isPresent()) {
setLexicalCategory(update.getLexicalCategory().get());
}
updateLemmas(update.getLemmas());
for (SenseDocument sense : update.getAddedSenses()) {
addSense(sense);
}
for (SenseUpdate sense : update.getUpdatedSenses().values()) {
updateSense(sense);
}
for (SenseIdValue senseId : update.getRemovedSenses()) {
removeSense(senseId);
}
for (FormDocument form : update.getAddedForms()) {
addForm(form);
}
for (FormUpdate form : update.getUpdatedForms().values()) {
updateForm(form);
}
for (FormIdValue formId : update.getRemovedForms()) {
removeForm(formId);
}
return this;
}
@Override
public LexemeUpdate build() {
return Datamodel.makeLexemeUpdate(getEntityId(), getBaseRevisionId(),
language, lexicalCategory, lemmas, statements,
addedSenses, updatedSenses.values(), removedSenses,
addedForms, updatedForms.values(), removedForms);
}
}
MediaInfoUpdateBuilder.java 0000664 0000000 0000000 00000011101 14447725663 0036355 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link MediaInfoUpdate} objects.
*/
public class MediaInfoUpdateBuilder extends LabeledDocumentUpdateBuilder {
private MediaInfoUpdateBuilder(MediaInfoIdValue mediaInfoId, long revisionId) {
super(mediaInfoId, revisionId);
}
private MediaInfoUpdateBuilder(MediaInfoDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of media entity with given
* revision ID.
*
* @param mediaInfoId
* ID of the media entity that is to be updated
* @param revisionId
* ID of the base media entity revision to be updated or zero if not
* available
* @return update builder object
* @throws NullPointerException
* if {@code mediaInfoId} is {@code null}
* @throws IllegalArgumentException
* if {@code mediaInfoId} is a placeholder ID
*/
public static MediaInfoUpdateBuilder forBaseRevisionId(MediaInfoIdValue mediaInfoId, long revisionId) {
return new MediaInfoUpdateBuilder(mediaInfoId, revisionId);
}
/**
* Creates new builder object for constructing update of media entity with given
* ID.
*
* @param mediaInfoId
* ID of the media entity that is to be updated
* @return update builder object
* @throws NullPointerException
* if {@code mediaInfoId} is {@code null}
* @throws IllegalArgumentException
* if {@code mediaInfoId} is a placeholder ID
*/
public static MediaInfoUpdateBuilder forEntityId(MediaInfoIdValue mediaInfoId) {
return new MediaInfoUpdateBuilder(mediaInfoId, 0);
}
/**
* Creates new builder object for constructing update of given base media entity
* revision. Provided media document might not represent the latest revision of
* the media entity as currently stored in Wikibase. It will be used for
* validation in builder methods. If the document has revision ID, it will be
* used to detect edit conflicts.
*
* @param revision
* base media entity revision to be updated
* @return update builder object
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
public static MediaInfoUpdateBuilder forBaseRevision(MediaInfoDocument revision) {
return new MediaInfoUpdateBuilder(revision);
}
@Override
MediaInfoIdValue getEntityId() {
return (MediaInfoIdValue) super.getEntityId();
}
@Override
MediaInfoDocument getBaseRevision() {
return (MediaInfoDocument) super.getBaseRevision();
}
@Override
public MediaInfoUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
@Override
public MediaInfoUpdateBuilder updateLabels(TermUpdate update) {
super.updateLabels(update);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes from
* the update are added on top of changes already present in this builder
* object.
*
* @param update
* media update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if {@code update} cannot be applied to base entity revision (if
* available)
*/
public MediaInfoUpdateBuilder apply(MediaInfoUpdate update) {
super.append(update);
return this;
}
@Override
public MediaInfoUpdate build() {
return Datamodel.makeMediaInfoUpdate(getEntityId(), getBaseRevisionId(), labels, statements);
}
}
PropertyDocumentBuilder.java 0000664 0000000 0000000 00000012433 14447725663 0036713 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
/**
* Builder class to construct {@link PropertyDocument} objects.
*
* @author Markus Kroetzsch
*
*/
public class PropertyDocumentBuilder extends
EntityDocumentBuilder {
private final DatatypeIdValue datatype;
/**
* Constructor when building the property document from scratch.
*
* @param propertyIdValue
* id of the newly constructed property document
* @param datatype
* the datatype of the newly constructed property document
*/
protected PropertyDocumentBuilder(PropertyIdValue propertyIdValue,
DatatypeIdValue datatype) {
super(propertyIdValue);
this.datatype = datatype;
}
/**
* Constructor when building the property document from an existing one.
*
* @param initialDocument
* the initial property document to start the build from
*/
protected PropertyDocumentBuilder(PropertyDocument initialDocument) {
super(initialDocument);
this.datatype = initialDocument.getDatatype();
}
/**
* Starts the construction of an {@link PropertyDocument} with the given id.
*
* @param propertyIdValue
* id of the newly constructed property document
* @param datatype
* the datatype of the newly constructed property document
* @return builder object to continue construction
*/
public static PropertyDocumentBuilder forPropertyIdAndDatatype(
PropertyIdValue propertyIdValue, DatatypeIdValue datatype) {
return new PropertyDocumentBuilder(propertyIdValue, datatype);
}
/**
* Starts the construction of an {@link PropertyDocument} from the existing
* document.
*
* @param initialDocument
* the existing document to start the build from
* @return builder object to continue construction
*/
public static PropertyDocumentBuilder fromPropertyDocument(
PropertyDocument initialDocument) {
return new PropertyDocumentBuilder(initialDocument);
}
/**
* Starts the construction of an {@link PropertyDocument} with the given id.
*
* @param propertyIdValue
* id of the newly constructed property document
* @param datatypeId
* the datatype id of the newly constructed property document,
* e.g., {@link DatatypeIdValue#DT_ITEM}.
* @return builder object to continue construction
* @deprecated use {@link #forPropertyIdAndJsonDatatype(PropertyIdValue, String)}
*/
public static PropertyDocumentBuilder forPropertyIdAndDatatype(
PropertyIdValue propertyIdValue, String datatypeId) {
return forPropertyIdAndDatatype(propertyIdValue,
factory.getDatatypeIdValue(datatypeId));
}
/**
* Starts the construction of an {@link PropertyDocument} with the given id.
*
* @param propertyIdValue
* id of the newly constructed property document
* @param datatypeId
* the datatype id of the newly constructed property document,
* e.g., {@link DatatypeIdValue#DT_ITEM}.
* @return builder object to continue construction
*/
public static PropertyDocumentBuilder forPropertyIdAndJsonDatatype(
PropertyIdValue propertyIdValue, String datatypeId) {
return forPropertyIdAndDatatype(propertyIdValue,
factory.getDatatypeIdValueFromJsonId(datatypeId));
}
/**
* Changes the entity value id for the constructed document.
* See {@link EntityDocument#getEntityId()}.
*
* @param entityId
* the entity id, which must be an ItemIdValue
* @return builder object to continue construction
*/
@Override
public PropertyDocumentBuilder withEntityId(EntityIdValue entityId) {
if (!(entityId instanceof PropertyIdValue)) {
throw new IllegalArgumentException("The entity id of a PropertyDocument must be an PropertyIdValue.");
}
return super.withEntityId(entityId);
}
/**
* Returns the {@link ItemDocument} that has been built.
*
* @return constructed item document
* @throws IllegalStateException
* if the object was built already
*/
@Override
public PropertyDocument build() {
prepareBuild();
return factory.getPropertyDocument(
(PropertyIdValue) this.entityIdValue, this.labels,
this.descriptions, this.aliases, getStatementGroups(),
this.datatype, this.revisionId);
}
@Override
protected PropertyDocumentBuilder getThis() {
return this;
}
}
PropertyUpdateBuilder.java 0000664 0000000 0000000 00000011650 14447725663 0036357 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link PropertyUpdate} objects.
*/
public class PropertyUpdateBuilder extends TermedDocumentUpdateBuilder {
private PropertyUpdateBuilder(PropertyIdValue propertyId, long revisionId) {
super(propertyId, revisionId);
}
private PropertyUpdateBuilder(PropertyDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of property entity with
* given revision ID.
*
* @param propertyId
* ID of the property entity that is to be updated
* @param revisionId
* ID of the base property revision to be updated or zero if not
* available
* @return update builder object
* @throws NullPointerException
* if {@code propertyId} is {@code null}
* @throws IllegalArgumentException
* if {@code propertyId} is a placeholder ID
*/
public static PropertyUpdateBuilder forBaseRevisionId(PropertyIdValue propertyId, long revisionId) {
return new PropertyUpdateBuilder(propertyId, revisionId);
}
/**
* Creates new builder object for constructing update of property entity with
* given ID.
*
* @param propertyId
* ID of the property entity that is to be updated
* @return update builder object
* @throws NullPointerException
* if {@code propertyId} is {@code null}
* @throws IllegalArgumentException
* if {@code propertyId} is a placeholder ID
*/
public static PropertyUpdateBuilder forEntityId(PropertyIdValue propertyId) {
return new PropertyUpdateBuilder(propertyId, 0);
}
/**
* Creates new builder object for constructing update of given base property
* entity revision. Provided property document might not represent the latest
* revision of the property entity as currently stored in Wikibase. It will be
* used for validation in builder methods. If the document has revision ID, it
* will be used to detect edit conflicts.
*
* @param revision
* base property entity revision to be updated
* @return update builder object
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
public static PropertyUpdateBuilder forBaseRevision(PropertyDocument revision) {
return new PropertyUpdateBuilder(revision);
}
@Override
PropertyIdValue getEntityId() {
return (PropertyIdValue) super.getEntityId();
}
@Override
PropertyDocument getBaseRevision() {
return (PropertyDocument) super.getBaseRevision();
}
@Override
public PropertyUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
@Override
public PropertyUpdateBuilder updateLabels(TermUpdate update) {
super.updateLabels(update);
return this;
}
@Override
public PropertyUpdateBuilder updateDescriptions(TermUpdate update) {
super.updateDescriptions(update);
return this;
}
@Override
public PropertyUpdateBuilder updateAliases(String language, AliasUpdate update) {
super.updateAliases(language, update);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes from
* the update are added on top of changes already present in this builder
* object.
*
* @param update
* property update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if {@code update} cannot be applied to base entity revision (if
* available)
*/
public PropertyUpdateBuilder append(PropertyUpdate update) {
super.append(update);
return this;
}
@Override
public PropertyUpdate build() {
return Datamodel.makePropertyUpdate(getEntityId(), getBaseRevisionId(),
labels, descriptions, aliases, statements);
}
}
ReferenceBuilder.java 0000664 0000000 0000000 00000010200 14447725663 0035254 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.Snak;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.Value;
public class ReferenceBuilder extends
AbstractDataObjectBuilder {
final HashMap> snaks = new HashMap<>();
/**
* Constructor.
*/
protected ReferenceBuilder() {
}
/**
* Starts the construction of a {@link Reference}.
*
* @return builder object to continue construction
*/
public static ReferenceBuilder newInstance() {
return new ReferenceBuilder();
}
@Override
public Reference build() {
prepareBuild();
return factory.getReference(getSnakGroups());
}
/**
* Adds the given property and value to the constructed reference.
*
* @param propertyIdValue
* the property to add
* @param value
* the value to add
* @return builder object to continue construction
*/
public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue,
Value value) {
getSnakList(propertyIdValue).add(
factory.getValueSnak(propertyIdValue, value));
return getThis();
}
/**
* Adds a {@link SomeValueSnak} with the given property to the constructed
* reference.
*
* Note that it might not be meaningful to use {@link SomeValueSnak} in a
* reference, depending on the policies of the wiki.
*
* @param propertyIdValue
* the property of the snak
* @return builder object to continue construction
*/
public ReferenceBuilder withSomeValue(PropertyIdValue propertyIdValue) {
getSnakList(propertyIdValue).add(
factory.getSomeValueSnak(propertyIdValue));
return getThis();
}
/**
* Adds a {@link NoValueSnak} with the given property to the constructed
* reference.
*
* Note that it might not be meaningful to use {@link NoValueSnak} in a
* reference. It is usually implicitly assumed that all snaks that are not
* given have no value for a particular reference. Otherwise one would need
* large numbers of {@link NoValueSnak} entries for every reference!
*
* @param propertyIdValue
* the property of the snak
* @return builder object to continue construction
*/
public ReferenceBuilder withNoValue(PropertyIdValue propertyIdValue) {
getSnakList(propertyIdValue).add(
factory.getNoValueSnak(propertyIdValue));
return getThis();
}
@Override
protected ReferenceBuilder getThis() {
return this;
}
/**
* Returns a list of {@link SnakGroup} objects for the currently stored
* snaks.
*
* @return
*/
protected List getSnakGroups() {
ArrayList result = new ArrayList<>(this.snaks.size());
for (ArrayList statementList : this.snaks.values()) {
result.add(factory.getSnakGroup(statementList));
}
return result;
}
/**
* Returns the list of {@link Snak} objects for a given property.
*
* @param propertyIdValue
* @return
*/
protected ArrayList getSnakList(PropertyIdValue propertyIdValue) {
if(!snaks.containsKey(propertyIdValue)) {
snaks.put(propertyIdValue, new ArrayList<>());
}
return this.snaks.get(propertyIdValue);
}
}
SenseUpdateBuilder.java 0000664 0000000 0000000 00000012243 14447725663 0035607 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Objects;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SenseUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link SenseUpdate} objects.
*/
public class SenseUpdateBuilder extends StatementDocumentUpdateBuilder {
private TermUpdate glosses = TermUpdate.EMPTY;
private SenseUpdateBuilder(SenseIdValue senseId, long revisionId) {
super(senseId, revisionId);
}
private SenseUpdateBuilder(SenseDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of sense entity with given
* revision ID.
*
* @param senseId
* ID of the sense that is to be updated
* @param revisionId
* ID of the base sense revision to be updated or zero if not
* available
* @return update builder object
* @throws NullPointerException
* if {@code senseId} is {@code null}
* @throws IllegalArgumentException
* if {@code senseId} is a placeholder ID
*/
public static SenseUpdateBuilder forBaseRevisionId(SenseIdValue senseId, long revisionId) {
return new SenseUpdateBuilder(senseId, revisionId);
}
/**
* Creates new builder object for constructing update of sense entity with given
* ID.
*
* @param senseId
* ID of the sense that is to be updated
* @return update builder object
* @throws NullPointerException
* if {@code senseId} is {@code null}
* @throws IllegalArgumentException
* if {@code senseId} is a placeholder ID
*/
public static SenseUpdateBuilder forEntityId(SenseIdValue senseId) {
return new SenseUpdateBuilder(senseId, 0);
}
/**
* Creates new builder object for constructing update of given base sense entity
* revision. Provided sense document might not represent the latest revision of
* the sense entity as currently stored in Wikibase. It will be used for
* validation in builder methods. If the document has revision ID, it will be
* used to detect edit conflicts.
*
* @param revision
* base sense entity revision to be updated
* @return update builder object
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
public static SenseUpdateBuilder forBaseRevision(SenseDocument revision) {
return new SenseUpdateBuilder(revision);
}
@Override
SenseIdValue getEntityId() {
return (SenseIdValue) super.getEntityId();
}
@Override
SenseDocument getBaseRevision() {
return (SenseDocument) super.getBaseRevision();
}
@Override
public SenseUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
/**
* Updates sense glosses. If this method is called multiple times, changes are
* accumulated. If base entity revision was provided, redundant changes are
* silently ignored, resulting in empty update.
*
* @param update
* changes in sense glosses
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public SenseUpdateBuilder updateGlosses(TermUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
TermUpdateBuilder combined = getBaseRevision() != null
? TermUpdateBuilder.forTerms(getBaseRevision().getGlosses().values())
: TermUpdateBuilder.create();
combined.append(glosses);
combined.append(update);
glosses = combined.build();
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes from
* the update are added on top of changes already present in this builder
* object.
*
* @param update
* sense update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if {@code update} cannot be applied to base entity revision (if
* available)
*/
public SenseUpdateBuilder append(SenseUpdate update) {
super.append(update);
updateGlosses(update.getGlosses());
return this;
}
@Override
public SenseUpdate build() {
return Datamodel.makeSenseUpdate(getEntityId(), getBaseRevisionId(), glosses, statements);
}
}
StatementBuilder.java 0000664 0000000 0000000 00000021223 14447725663 0035331 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.Snak;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementRank;
import org.wikidata.wdtk.datamodel.interfaces.Value;
public class StatementBuilder extends
AbstractDataObjectBuilder {
private final EntityIdValue subject;
private final PropertyIdValue mainProperty;
private Value mainValue = null;
private boolean noMainValue = false;
private final HashMap> qualifiers = new HashMap<>();
private String statementId = "";
private StatementRank rank = StatementRank.NORMAL;
private final ArrayList references = new ArrayList<>();
/**
* Constructor.
*
* @param subject
* id of the entity that the constructed statement refers to
* @param property
* the id of the main property of the constructed statement
*/
protected StatementBuilder(EntityIdValue subject, PropertyIdValue property) {
this.subject = subject;
this.mainProperty = property;
}
/**
* Starts the construction of a {@link Statement} with the given subject.
*
* @param subject
* id of the entity that the constructed statement refers to
* @param property
* the id of the main property of the constructed statement
* @return builder object to continue construction
*/
public static StatementBuilder forSubjectAndProperty(EntityIdValue subject,
PropertyIdValue property) {
return new StatementBuilder(subject, property);
}
@Override
public Statement build() {
prepareBuild();
return factory.getStatement(subject, getMainSnak(), getQualifierGroups(),
references, rank, statementId);
}
/**
* Sets the rank for the constructed statement.
*
* @param rank
* the rank of the statement
* @return builder object to continue construction
*/
public StatementBuilder withRank(StatementRank rank) {
this.rank = rank;
return getThis();
}
/**
* Sets the id for the constructed statement.
*
* @param statementId
* the id of the statement
* @return builder object to continue construction
*/
public StatementBuilder withId(String statementId) {
this.statementId = statementId;
return getThis();
}
/**
* Sets the main value for the constructed statement.
*
* @param value
* the main value of the statement
* @return builder object to continue construction
*/
public StatementBuilder withValue(Value value) {
this.mainValue = value;
return getThis();
}
/**
* Sets the main snak of the statement to be a {{@link SomeValueSnak}.
*
* @return builder object to continue construction
*/
public StatementBuilder withSomeValue() {
this.mainValue = null;
this.noMainValue = false;
return getThis();
}
/**
* Sets the main snak of the statement to be a {{@link NoValueSnak}.
*
* @return builder object to continue construction
*/
public StatementBuilder withNoValue() {
this.mainValue = null;
this.noMainValue = true;
return getThis();
}
/**
* Adds a qualifier with the given property and value to the constructed
* statement.
*
* @param propertyIdValue
* the property of the qualifier
* @param value
* the value of the qualifier
* @return builder object to continue construction
*/
public StatementBuilder withQualifierValue(PropertyIdValue propertyIdValue,
Value value) {
withQualifier(factory.getValueSnak(propertyIdValue, value));
return getThis();
}
/**
* Adds a {@link SomeValueSnak} qualifier with the given property to the
* constructed statement.
*
* @param propertyIdValue
* the property of the qualifier
* @return builder object to continue construction
*/
public StatementBuilder withQualifierSomeValue(
PropertyIdValue propertyIdValue) {
withQualifier(factory.getSomeValueSnak(propertyIdValue));
return getThis();
}
/**
* Adds a {@link NoValueSnak} qualifier with the given property to the
* constructed statement.
*
* Note that it might not be meaningful to use {@link NoValueSnak} in a
* qualifier. It is usually implicitly assumed that all qualifiers that are
* not given have no value for a particular statement. Otherwise one would
* need large numbers of {@link NoValueSnak} qualifiers for every statement!
*
* @param propertyIdValue
* the property of the qualifier
* @return builder object to continue construction
*/
public StatementBuilder withQualifierNoValue(PropertyIdValue propertyIdValue) {
withQualifier(factory.getNoValueSnak(propertyIdValue));
return getThis();
}
/**
* Adds a qualifier {@link Snak} to the constructed statement.
*
* @param qualifier
* the qualifier to add
* @return builder object to continue construction
*/
public StatementBuilder withQualifier(Snak qualifier) {
getQualifierList(qualifier.getPropertyId()).add(qualifier);
return getThis();
}
/**
* Adds all qualifiers from the given {@link SnakGroup} to the constructed
* statement.
*
* @param qualifiers
* the group of qualifiers to add
* @return builder object to continue construction
*/
public StatementBuilder withQualifiers(SnakGroup qualifiers) {
getQualifierList(qualifiers.getProperty()).addAll(qualifiers);
return getThis();
}
/**
* Adds all qualifiers from the given list of {@link SnakGroup} to the
* constructed statement. This is handy to copy all qualifiers from a given
* statement.
*
* @param qualifiers
* the list of groups of qualifiers to add
* @return builder object to continue construction
*/
public StatementBuilder withQualifiers(List qualifiers) {
for (SnakGroup sg : qualifiers) {
withQualifiers(sg);
}
return getThis();
}
/**
* Adds a reference to the constructed statement.
*
* @param reference
* the reference to be added
* @return builder object to continue construction
*/
public StatementBuilder withReference(Reference reference) {
this.references.add(reference);
return getThis();
}
/**
* Adds a list of references to the constructed statement.
*
* @param references
* the references to be added
* @return builder object to continue construction
*/
public StatementBuilder withReferences(List extends Reference> references) {
this.references.addAll(references);
return getThis();
}
@Override
protected StatementBuilder getThis() {
return this;
}
/**
* Returns a list of {@link SnakGroup} objects for the currently stored
* qualifiers.
*
* @return
*/
protected List getQualifierGroups() {
ArrayList result = new ArrayList<>(this.qualifiers.size());
for (ArrayList statementList : this.qualifiers.values()) {
result.add(factory.getSnakGroup(statementList));
}
return result;
}
/**
* Returns the list of {@link Snak} objects for a given qualifier property.
*
* @param propertyIdValue
* @return
*/
protected ArrayList getQualifierList(PropertyIdValue propertyIdValue) {
if(!qualifiers.containsKey(propertyIdValue)) {
qualifiers.put(propertyIdValue, new ArrayList<>());
}
return qualifiers.get(propertyIdValue);
}
/**
* Returns the main {@link Snak} object for the constructed statement.
*
* @return
*/
protected Snak getMainSnak() {
if (this.mainValue != null) {
return factory.getValueSnak(this.mainProperty, this.mainValue);
} else if (this.noMainValue) {
return factory.getNoValueSnak(this.mainProperty);
} else {
return factory.getSomeValueSnak(this.mainProperty);
}
}
}
StatementDocumentUpdateBuilder.java 0000664 0000000 0000000 00000020514 14447725663 0040175 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Objects;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.FormDocument;
import org.wikidata.wdtk.datamodel.interfaces.FormIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.LabeledStatementDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeDocument;
import org.wikidata.wdtk.datamodel.interfaces.LexemeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.SenseDocument;
import org.wikidata.wdtk.datamodel.interfaces.SenseIdValue;
import org.wikidata.wdtk.datamodel.interfaces.StatementDocument;
import org.wikidata.wdtk.datamodel.interfaces.StatementDocumentUpdate;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
/**
* Builder for incremental construction of {@link StatementDocumentUpdate}
* objects.
*
* @see StatementUpdateBuilder
*/
public abstract class StatementDocumentUpdateBuilder extends EntityUpdateBuilder {
StatementUpdate statements = StatementUpdate.EMPTY;
/**
* Initializes new builder object for constructing update of entity with given
* ID.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is a placeholder ID
*/
protected StatementDocumentUpdateBuilder(EntityIdValue entityId, long revisionId) {
super(entityId, revisionId);
}
/**
* Initializes new builder object for constructing update of given base entity
* revision.
*
* @param revision
* base entity revision to be updated
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
protected StatementDocumentUpdateBuilder(StatementDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of entity with given
* revision ID.
*
* Supported entity IDs include {@link ItemIdValue}, {@link PropertyIdValue},
* {@link LexemeIdValue}, {@link FormIdValue}, {@link SenseIdValue}, and
* {@link MediaInfoIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it is a
* placeholder ID
*/
public static StatementDocumentUpdateBuilder forBaseRevisionId(EntityIdValue entityId, long revisionId) {
Objects.requireNonNull(entityId, "Entity ID cannot be null.");
if (entityId instanceof SenseIdValue) {
return SenseUpdateBuilder.forBaseRevisionId((SenseIdValue) entityId, revisionId);
}
if (entityId instanceof FormIdValue) {
return FormUpdateBuilder.forBaseRevisionId((FormIdValue) entityId, revisionId);
}
if (entityId instanceof LexemeIdValue) {
return LexemeUpdateBuilder.forBaseRevisionId((LexemeIdValue) entityId, revisionId);
}
return LabeledDocumentUpdateBuilder.forBaseRevisionId(entityId, revisionId);
}
/**
* Creates new builder object for constructing update of entity with given ID.
*
* Supported entity IDs include {@link ItemIdValue}, {@link PropertyIdValue},
* {@link LexemeIdValue}, {@link FormIdValue}, {@link SenseIdValue}, and
* {@link MediaInfoIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it is a
* placeholder ID
*/
public static StatementDocumentUpdateBuilder forEntityId(EntityIdValue entityId) {
return forBaseRevisionId(entityId, 0);
}
/**
* Creates new builder object for constructing update of given base entity
* revision. Provided entity document might not represent the latest revision of
* the entity as currently stored in Wikibase. It will be used for validation in
* builder methods. If the document has revision ID, it will be used to detect
* edit conflicts.
*
* Supported entity types include {@link ItemDocument},
* {@link PropertyDocument}, {@link LexemeDocument}, {@link FormDocument},
* {@link SenseDocument}, and {@link MediaInfoDocument}.
*
* @param revision
* base entity revision to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} is of unrecognized type or its ID is a
* placeholder ID
*/
public static StatementDocumentUpdateBuilder forBaseRevision(StatementDocument revision) {
Objects.requireNonNull(revision, "Base entity revision cannot be null.");
if (revision instanceof SenseDocument) {
return SenseUpdateBuilder.forBaseRevision((SenseDocument) revision);
}
if (revision instanceof FormDocument) {
return FormUpdateBuilder.forBaseRevision((FormDocument) revision);
}
if (revision instanceof LexemeDocument) {
return LexemeUpdateBuilder.forBaseRevision((LexemeDocument) revision);
}
if (revision instanceof LabeledStatementDocument) {
return LabeledDocumentUpdateBuilder
.forBaseRevision((LabeledStatementDocument) revision);
}
throw new IllegalArgumentException("Unrecognized entity document type.");
}
@Override
StatementDocument getBaseRevision() {
return (StatementDocument) super.getBaseRevision();
}
/**
* Updates entity statements. If this method is called multiple times, changes
* are accumulated. If base entity revision was provided, the update is checked
* against it and redundant changes are silently ignored, resulting in empty
* update.
*
* @param update
* statement update, possibly empty
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if replaced or removed statement is not present in current entity
* revision (if available)
*/
public StatementDocumentUpdateBuilder updateStatements(StatementUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
StatementUpdateBuilder combined = getBaseRevision() != null
? StatementUpdateBuilder.forStatementGroups(getEntityId(), getBaseRevision().getStatementGroups())
: StatementUpdateBuilder.create(getEntityId());
combined.append(statements);
combined.append(update);
statements = combined.build();
return this;
}
void append(StatementDocumentUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
updateStatements(update.getStatements());
}
/**
* Creates new {@link StatementDocumentUpdate} object with contents of this
* builder object.
*
* @return constructed object
*/
@Override
public abstract StatementDocumentUpdate build();
}
StatementUpdateBuilder.java 0000664 0000000 0000000 00000033450 14447725663 0036501 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
/**
* Builder for incremental construction of {@link StatementUpdate} objects.
*
* @see StatementDocumentUpdateBuilder
*/
public class StatementUpdateBuilder {
private final Map base;
private EntityIdValue subject;
private final List added = new ArrayList<>();
private final Map replaced = new HashMap<>();
private final Set removed = new HashSet<>();
private StatementUpdateBuilder(EntityIdValue subject, Collection base) {
if (subject != null) {
Validate.isTrue(!subject.isPlaceholder(), "Subject cannot be a placeholder ID.");
this.subject = subject;
}
if (base != null) {
for (Statement statement : base) {
Objects.requireNonNull(statement, "Base document statements cannot be null.");
Validate.isTrue(
!statement.getSubject().isPlaceholder(),
"Statement subject cannot be a placeholder ID.");
if (this.subject != null) {
Validate.isTrue(this.subject.equals(statement.getSubject()), "Inconsistent statement subject.");
} else {
this.subject = statement.getSubject();
}
Validate.notBlank(statement.getStatementId(), "Base document statement must have valid ID.");
}
Validate.isTrue(
base.stream().map(s -> s.getSubject()).distinct().count() <= 1,
"Base document statements must all refer to the same subject.");
Validate.isTrue(
base.stream().map(s -> s.getStatementId()).distinct().count() == base.size(),
"Base document statements must have unique IDs.");
this.base = base.stream().collect(toMap(s -> s.getStatementId(), s -> s));
} else {
this.base = null;
}
}
/**
* Creates new builder object for constructing statement update.
*
* @return update builder object
*/
public static StatementUpdateBuilder create() {
return new StatementUpdateBuilder(null, null);
}
/**
* Creates new builder object for constructing statement update of given
* subject. All added or replaced statements must have the same subject ID.
*
* @param subject
* statement subject or {@code null} for unspecified ID
* @return update builder object
* @throws IllegalArgumentException
* if subject is a placeholder ID
*/
public static StatementUpdateBuilder create(EntityIdValue subject) {
return new StatementUpdateBuilder(subject, null);
}
/**
* Creates new builder object for constructing update of given base revision
* statements. Provided statements will be used to check correctness of changes.
*
* Since all changes will be checked after the {@link StatementUpdate} is passed
* to {@link EntityDocumentBuilder} anyway, it is usually unnecessary to use
* this method. It is simpler to initialize the builder with {@link #create()}.
*
* @param statements
* statements from base revision of the document
* @return update builder object
* @throws NullPointerException
* if {@code statements} or any of its items is {@code null}
* @throws IllegalArgumentException
* if any statement is missing statement ID or statement subjects
* are inconsistent or placeholders
*/
public static StatementUpdateBuilder forStatements(Collection statements) {
Objects.requireNonNull(statements, "Base document statement collection cannot be null.");
return new StatementUpdateBuilder(null, statements);
}
/**
* Creates new builder object for constructing update of given base revision
* statements with given subject. Provided statements will be used to check
* correctness of changes. All provided statements as well as added or replaced
* statements must have the provided subject ID.
*
* Since all changes will be checked after the {@link StatementUpdate} is passed
* to {@link EntityDocumentBuilder} anyway, it is usually unnecessary to use
* this method. It is simpler to initialize the builder with {@link #create()}.
*
* @param subject
* statement subject or {@code null} for unspecified ID
* @param statements
* statements from base revision of the document
* @return update builder object
* @throws NullPointerException
* if {@code statements} or any of its items is {@code null}
* @throws IllegalArgumentException
* if any statement is missing statement ID or statement subjects
* are inconsistent or placeholders
*/
public static StatementUpdateBuilder forStatements(EntityIdValue subject, Collection statements) {
Objects.requireNonNull(statements, "Base document statement collection cannot be null.");
return new StatementUpdateBuilder(subject, statements);
}
/**
* Creates new builder object for constructing update of given base revision
* statement groups. Provided statements will be used to check correctness of
* changes.
*
* Since all changes will be checked after the {@link StatementUpdate} is passed
* to {@link EntityDocumentBuilder} anyway, it is usually unnecessary to use
* this method. It is simpler to initialize the builder with {@link #create()}.
*
* @param groups
* statement groups from base revision of the document
* @return update builder object
* @throws NullPointerException
* if {@code groups} is {@code null}
* @throws IllegalArgumentException
* if any group is {@code null} or any statement is missing
* statement ID or statement subjects are inconsistent or
* placeholders
*/
public static StatementUpdateBuilder forStatementGroups(Collection groups) {
Objects.requireNonNull(groups, "Base document statement group collection cannot be null.");
Validate.noNullElements(groups, "Base document statement groups cannot be null.");
return new StatementUpdateBuilder(null,
groups.stream().flatMap(g -> g.getStatements().stream()).collect(toList()));
}
/**
* Creates new builder object for constructing update of given base revision
* statement groups with given subject. Provided statements will be used to
* check correctness of changes. All provided statements as well as added or
* replaced statements must have the provided subject ID.
*
* Since all changes will be checked after the {@link StatementUpdate} is passed
* to {@link EntityDocumentBuilder} anyway, it is usually unnecessary to use
* this method. It is simpler to initialize the builder with {@link #create()}.
*
* @param subject
* statement subject or {@code null} for unspecified ID
* @param groups
* statement groups from base revision of the document
* @return update builder object
* @throws NullPointerException
* if {@code groups} is {@code null}
* @throws IllegalArgumentException
* if any group is {@code null} or any statement is missing
* statement ID or statement subjects are inconsistent or
* placeholders
*/
public static StatementUpdateBuilder forStatementGroups(EntityIdValue subject, Collection groups) {
Objects.requireNonNull(groups, "Base document statement group collection cannot be null.");
Validate.noNullElements(groups, "Base document statement groups cannot be null.");
return new StatementUpdateBuilder(subject,
groups.stream().flatMap(g -> g.getStatements().stream()).collect(toList()));
}
/**
* Adds statement to the entity. If {@code statement} has an ID (perhaps because
* it is a modified copy of another statement), its ID is stripped to ensure the
* statement is added and no other statement is modified.
*
* @param statement
* new statement to add
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code statement} is {@code null}
* @throws IllegalArgumentException
* if statement's subject is inconsistent with other statements or
* it is a placeholder ID
*/
public StatementUpdateBuilder add(Statement statement) {
Objects.requireNonNull(statement, "Statement cannot be null.");
Validate.isTrue(
!statement.getSubject().isPlaceholder(),
"Statement subject cannot be a placeholder ID.");
if (subject != null) {
Validate.isTrue(subject.equals(statement.getSubject()), "Inconsistent statement subject.");
}
if (!statement.getStatementId().isEmpty()) {
statement = statement.withStatementId("");
}
added.add(statement);
if (subject == null) {
subject = statement.getSubject();
}
return this;
}
/**
* Replaces existing statement in the entity. Provided {@code statement} must
* have statement ID identifying statement to replace. Calling this method
* overrides any previous changes made to the same statement ID by this method
* or {@link #remove(String)}.
*
* If base revision statements were provided, existence of the statement is
* checked. Any attempt to replace some statement with identical statement is
* silently ignored, resulting in empty update.
*
* @param statement
* replacement for existing statement
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code statement} is {@code null}
* @throws IllegalArgumentException
* if {@code statement} does not have statement ID or it is not
* among base revision statements (if available) or its subject is
* inconsistent with other statements or a placeholder ID
*/
public StatementUpdateBuilder replace(Statement statement) {
Objects.requireNonNull(statement, "Statement cannot be null.");
Validate.isTrue(
!statement.getSubject().isPlaceholder(),
"Statement subject cannot be a placeholder ID.");
Validate.notEmpty(statement.getStatementId(), "Statement must have an ID.");
if (subject != null) {
Validate.isTrue(subject.equals(statement.getSubject()), "Inconsistent statement subject.");
}
if (base != null) {
Statement original = base.get(statement.getStatementId());
Validate.isTrue(original != null, "Replaced statement is not in base revision.");
if (statement.equals(original)) {
replaced.remove(statement.getStatementId());
removed.remove(statement.getStatementId());
return this;
}
}
replaced.put(statement.getStatementId(), statement);
removed.remove(statement.getStatementId());
if (subject == null) {
subject = statement.getSubject();
}
return this;
}
/**
* Removes existing statement from the entity. Calling this method overrides any
* previous changes made to the same statement ID by
* {@link #replace(Statement)}. Removing the same statement ID twice is silently
* tolerated.
*
* If base revision statements were provided, this method checks that statement
* with this ID exists in the base revision.
*
* @param statementId
* ID of the removed statement
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code statementId} is {@code null}
* @throws IllegalArgumentException
* if {@code statementId} is empty or it is not among base revision
* statements (if available)
*/
public StatementUpdateBuilder remove(String statementId) {
Validate.notBlank(statementId, "Statement ID must not be empty.");
if (base != null) {
Statement original = base.get(statementId);
Validate.isTrue(original != null, "Removed statement is not in base revision.");
}
removed.add(statementId);
replaced.remove(statementId);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes are
* performed as if by calling {@link #add(Statement)},
* {@link #replace(Statement)}, and {@link #remove(String)} methods.
*
* @param update
* statement update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
* @throws IllegalArgumentException
* if updated or removed statement is not among base revision
* statements (if available)
*/
public StatementUpdateBuilder append(StatementUpdate update) {
Objects.requireNonNull(update, "Statement update cannot be null.");
for (Statement statement : update.getAdded()) {
add(statement);
}
for (Statement statement : update.getReplaced().values()) {
replace(statement);
}
for (String statementId : update.getRemoved()) {
remove(statementId);
}
return this;
}
/**
* Creates new {@link StatementUpdate} object with contents of this builder
* object.
*
* @return constructed object
*/
public StatementUpdate build() {
return Datamodel.makeStatementUpdate(added, replaced.values(), removed);
}
}
TermUpdateBuilder.java 0000664 0000000 0000000 00000013443 14447725663 0035444 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import static java.util.stream.Collectors.toMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
/**
* Builder for incremental construction of {@link TermUpdate} objects.
*/
public class TermUpdateBuilder {
private final Map base;
private final Map modified = new HashMap<>();
private final Set removed = new HashSet<>();
private TermUpdateBuilder(Collection base) {
if (base != null) {
for (MonolingualTextValue value : base) {
Objects.requireNonNull(value, "Base document terms cannot be null.");
}
Validate.isTrue(
base.stream().map(v -> v.getLanguageCode()).distinct().count() == base.size(),
"Base document terms must have unique language codes.");
this.base = base.stream().collect(toMap(v -> v.getLanguageCode(), v -> v));
} else
this.base = null;
}
/**
* Creates new builder object for constructing term update.
*
* @return update builder object
*/
public static TermUpdateBuilder create() {
return new TermUpdateBuilder(null);
}
/**
* Creates new builder object for constructing update of given base revision
* terms. Provided terms will be used to check correctness of changes.
*
* Since all changes will be checked after the {@link TermUpdate} is passed to
* {@link EntityUpdateBuilder} anyway, it is usually unnecessary to use this
* method. It is simpler to initialize the builder with {@link #create()}.
*
* @param terms
* terms from base revision of the document
* @return update builder object
* @throws NullPointerException
* if {@code terms} or any of its items is {@code null}
* @throws IllegalArgumentException
* if there are duplicate items in {@code terms}
*/
public static TermUpdateBuilder forTerms(Collection terms) {
Objects.requireNonNull(terms, "Base document term collection cannot be null.");
return new TermUpdateBuilder(terms);
}
/**
* Adds or changes term. If a term with this language code already exists, it is
* replaced. Terms with other language codes are not touched. Calling this
* method overrides any previous changes made with the same language code by
* this method or {@link #remove(String)}.
*
* If base revision terms were provided, attempt to overwrite some term with the
* same value will be silently ignored, resulting in empty update.
*
* @param term
* term to add or change
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code term} is {@code null}
*/
public TermUpdateBuilder put(MonolingualTextValue term) {
Objects.requireNonNull(term, "Term cannot be null.");
if (base != null) {
if (term.equals(base.get(term.getLanguageCode()))) {
modified.remove(term.getLanguageCode());
removed.remove(term.getLanguageCode());
return this;
}
}
modified.put(term.getLanguageCode(), term);
removed.remove(term.getLanguageCode());
return this;
}
/**
* Removes term. Terms with other language codes are not touched. Calling this
* method overrides any previous changes made with the same language code by
* this method or {@link #put(MonolingualTextValue)}.
*
* If base revision terms were provided, attempts to remove missing terms will
* be silently ignored, resulting in empty update.
*
* @param languageCode
* language code of the removed term
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code languageCode} is {@code null}
* @throws IllegalArgumentException
* if {@code languageCode} is blank
*/
public TermUpdateBuilder remove(String languageCode) {
Validate.notBlank(languageCode, "Language code must be provided.");
if (base != null && !base.containsKey(languageCode)) {
modified.remove(languageCode);
return this;
}
removed.add(languageCode);
modified.remove(languageCode);
return this;
}
/**
* Replays all changes in provided update into this builder object. Changes are
* performed as if by calling {@link #put(MonolingualTextValue)} and
* {@link #remove(String)} methods.
*
* @param update
* term update to replay
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public TermUpdateBuilder append(TermUpdate update) {
Objects.requireNonNull(update, "Term update cannot be null.");
for (MonolingualTextValue term : update.getModified().values()) {
put(term);
}
for (String language : update.getRemoved()) {
remove(language);
}
return this;
}
/**
* Creates new {@link TermUpdate} object with contents of this builder object.
*
* @return constructed object
*/
public TermUpdate build() {
return Datamodel.makeTermUpdate(modified.values(), removed);
}
}
TermedDocumentUpdateBuilder.java 0000664 0000000 0000000 00000022057 14447725663 0037455 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.helpers;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.StatementUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermUpdate;
import org.wikidata.wdtk.datamodel.interfaces.TermedStatementDocument;
import org.wikidata.wdtk.datamodel.interfaces.TermedStatementDocumentUpdate;
/**
* Builder for incremental construction of {@link TermedStatementDocumentUpdate}
* objects.
*/
public abstract class TermedDocumentUpdateBuilder extends LabeledDocumentUpdateBuilder {
TermUpdate descriptions = TermUpdate.EMPTY;
final Map aliases = new HashMap<>();
/**
* Initializes new builder object for constructing update of entity with given
* ID.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is a placeholder ID
*/
protected TermedDocumentUpdateBuilder(EntityIdValue entityId, long revisionId) {
super(entityId, revisionId);
}
/**
* Initializes new builder object for constructing update of given base entity
* revision.
*
* @param revision
* base entity revision to be updated
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} has placeholder ID
*/
protected TermedDocumentUpdateBuilder(TermedStatementDocument revision) {
super(revision);
}
/**
* Creates new builder object for constructing update of entity with given
* revision ID.
*
* Supported entity IDs include {@link ItemIdValue} and {@link PropertyIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @param revisionId
* ID of the base entity revision to be updated or zero if not
* available
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it is a
* placeholder ID
*/
public static TermedDocumentUpdateBuilder forBaseRevisionId(EntityIdValue entityId, long revisionId) {
Objects.requireNonNull(entityId, "Entity ID cannot be null.");
if (entityId instanceof ItemIdValue) {
return ItemUpdateBuilder.forBaseRevisionId((ItemIdValue) entityId, revisionId);
}
if (entityId instanceof PropertyIdValue) {
return PropertyUpdateBuilder.forBaseRevisionId((PropertyIdValue) entityId, revisionId);
}
throw new IllegalArgumentException("Unrecognized entity ID type.");
}
/**
* Creates new builder object for constructing update of entity with given ID.
*
* Supported entity IDs include {@link ItemIdValue} and {@link PropertyIdValue}.
*
* @param entityId
* ID of the entity that is to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code entityId} is {@code null}
* @throws IllegalArgumentException
* if {@code entityId} is of unrecognized type or it is a
* placeholder ID
*/
public static TermedDocumentUpdateBuilder forEntityId(EntityIdValue entityId) {
return forBaseRevisionId(entityId, 0);
}
/**
* Creates new builder object for constructing update of given base entity
* revision. Provided entity document might not represent the latest revision of
* the entity as currently stored in Wikibase. It will be used for validation in
* builder methods. If the document has revision ID, it will be used to detect
* edit conflicts.
*
* Supported entity types include {@link ItemDocument} and
* {@link PropertyDocument}.
*
* @param revision
* base entity revision to be updated
* @return builder object matching entity type
* @throws NullPointerException
* if {@code revision} is {@code null}
* @throws IllegalArgumentException
* if {@code revision} is of unrecognized type or its ID is a
* placeholder ID
*/
public static TermedDocumentUpdateBuilder forBaseRevision(TermedStatementDocument revision) {
Objects.requireNonNull(revision, "Base entity revision cannot be null.");
if (revision instanceof ItemDocument) {
return ItemUpdateBuilder.forBaseRevision((ItemDocument) revision);
}
if (revision instanceof PropertyDocument) {
return PropertyUpdateBuilder.forBaseRevision((PropertyDocument) revision);
}
throw new IllegalArgumentException("Unrecognized entity document type.");
}
@Override
TermedStatementDocument getBaseRevision() {
return (TermedStatementDocument) super.getBaseRevision();
}
@Override
public TermedDocumentUpdateBuilder updateStatements(StatementUpdate update) {
super.updateStatements(update);
return this;
}
@Override
public TermedDocumentUpdateBuilder updateLabels(TermUpdate update) {
super.updateLabels(update);
return this;
}
/**
* Updates entity descriptions. If this method is called multiple times, changes
* are accumulated. If base entity revision was provided, redundant changes are
* silently ignored, resulting in empty update.
*
* @param update
* changes in entity descriptions
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code update} is {@code null}
*/
public TermedDocumentUpdateBuilder updateDescriptions(TermUpdate update) {
Objects.requireNonNull(update, "Update cannot be null.");
TermUpdateBuilder combined = getBaseRevision() != null
? TermUpdateBuilder.forTerms(getBaseRevision().getDescriptions().values())
: TermUpdateBuilder.create();
combined.append(descriptions);
combined.append(update);
descriptions = combined.build();
return this;
}
/**
* Updates entity aliases. If this method is called multiple times, changes are
* accumulated. If base entity revision was provided, the update is checked
* against it and redundant changes are silently ignored, resulting in empty
* update.
*
* @param language
* language code of the altered aliases
* @param update
* alias changes
* @return {@code this} (fluent method)
* @throws NullPointerException
* if {@code language} or {@code aliases} is {@code null}
* @throws IllegalArgumentException
* if {@code language} is blank or {@code aliases} has inconsistent
* language code
*/
public TermedDocumentUpdateBuilder updateAliases(String language, AliasUpdate update) {
Validate.notBlank(language, "Specify language code.");
Objects.requireNonNull(update, "Alias update cannot be null.");
if (update.getLanguageCode().isPresent()) {
Validate.isTrue(language.equals(update.getLanguageCode().get()),
"Alias update must have matching language code.");
}
AliasUpdateBuilder builder;
if (getBaseRevision() != null) {
builder = AliasUpdateBuilder
.forAliases(getBaseRevision().getAliases().getOrDefault(language, Collections.emptyList()));
} else {
builder = AliasUpdateBuilder.create();
}
builder.append(aliases.getOrDefault(language, AliasUpdate.EMPTY));
builder.append(update);
AliasUpdate combined = builder.build();
if (!combined.isEmpty()) {
aliases.put(language, combined);
} else {
aliases.remove(language);
}
return this;
}
void append(TermedStatementDocumentUpdate update) {
super.append(update);
updateDescriptions(update.getDescriptions());
for (Map.Entry entry : update.getAliases().entrySet()) {
updateAliases(entry.getKey(), entry.getValue());
}
}
/**
* Creates new {@link TermedStatementDocumentUpdate} object with contents of
* this builder object.
*
* @return constructed object
*/
@Override
public abstract TermedStatementDocumentUpdate build();
}
ToString.java 0000664 0000000 0000000 00000051610 14447725663 0033632 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import org.wikidata.wdtk.datamodel.interfaces.*;
import java.text.DecimalFormat;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Static class for computing a toString of arbitrary data objects using only
* their Stringerfaces. This can be used to implement the toString() method of
* arbitrary Stringerface implementations. More efficient solutions might exist
* if the object that implements an Stringerface is of a specific known type,
* but the methods here could always be used as a fallback or default.
*
* The methods here are only meant for human consumption. Generic methods for
* serializing certain data values in well-defined string formats are found in
* {@link DataFormatter} instead.
*
* @author Markus Kroetzsch
*
*/
public class ToString {
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(ItemIdValue o) {
return o.getIri() + " (item)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(PropertyIdValue o) {
return o.getIri() + " (property)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(LexemeIdValue o) {
return o.getIri() + " (lexeme)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(FormIdValue o) {
return o.getIri() + " (form)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(SenseIdValue o) {
return o.getIri() + " (sense)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(MediaInfoIdValue o) {
return o.getIri() + " (media-info)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(DatatypeIdValue o) {
return o.getIri() + " (" + o.getJsonString() + ")";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(TimeValue o) {
DecimalFormat timeForm = new DecimalFormat("00");
return o.getYear()
+ "-"
+ timeForm.format(o.getMonth())
+ "-"
+ timeForm.format(o.getDay())
+ (o.getPrecision() > TimeValue.PREC_DAY
|| o.getHour() + o.getMinute() + o.getSecond() > 0 ? ("T"
+ timeForm.format(o.getHour())
+ ":"
+ timeForm.format(o.getMinute()) + ":" + timeForm
.format(o.getSecond())) : "")
+ " (Prec.: "
+ getTimePrecisionString(o.getPrecision())
+ " [-"
+ o.getBeforeTolerance()
+ " .. +"
+ o.getAfterTolerance()
+ "]"
+ ", PCal: "
+ getCalendarString(o.getPreferredCalendarModel())
+ (o.getTimezoneOffset() != 0 ? (", Timezone: "
+ o.getTimezoneOffset() + "min ") : "") + ")";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(GlobeCoordinatesValue o) {
return (o.getLatitude() / GlobeCoordinatesValue.PREC_DEGREE) + ":"
+ (o.getLongitude() / GlobeCoordinatesValue.PREC_DEGREE) + " ("
+ getGlobeString(o.getGlobe()) + ")";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(StringValue o) {
return "\"" + o.getString().replace("\"", "\\\"") + "\"";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(MonolingualTextValue o) {
return "\"" + o.getText().replace("\"", "\\\"") + "\" ("
+ o.getLanguageCode() + ")";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(QuantityValue o) {
String str = o.getNumericValue().toString();
if(o.getLowerBound() != null && o.getUpperBound() != null) {
str += " [" + o.getLowerBound().toString() + " .. " + o.getUpperBound().toString() + "]";
}
if(!"1".equals(o.getUnit())) {
str += " " + o.getUnit();
}
return str;
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(UnsupportedValue o) {
return "unsupported value of type "+o.getTypeJsonString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(UnsupportedEntityIdValue o) {
return o.getIri() + " (unsupported)";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(ValueSnak o) {
return o.getPropertyId().getIri() + " :: " + o.getValue().toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(SomeValueSnak o) {
return o.getPropertyId().getIri() + " has some value";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(NoValueSnak o) {
return o.getPropertyId().getIri() + " has no value";
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(SnakGroup o) {
final String indent = " ";
StringBuilder result = new StringBuilder();
for (Snak s : o.getSnaks()) {
result.append(indent)
.append(s.toString())
.append("\n");
}
return result.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(Claim o) {
StringBuilder sb = new StringBuilder();
sb.append(o.getSubject()).append(": ");
sb.append(o.getMainSnak().toString()).append("\n");
for (SnakGroup s : o.getQualifiers()) {
sb.append(toString(s));
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(Reference o) {
StringBuilder sb = new StringBuilder();
sb.append(" Reference:\n");
for (SnakGroup s : o.getSnakGroups()) {
sb.append(toString(s));
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(Statement o) {
StringBuilder sb = new StringBuilder();
sb.append("[ID ").append(o.getStatementId()).append("] ");
sb.append(o.getSubject()).append(": ");
sb.append(o.getMainSnak().toString()).append("\n");
for (SnakGroup s : o.getQualifiers()) {
sb.append(toString(s));
}
if (o.getRank() != StatementRank.NORMAL) {
sb.append(" Rank: ").append(o.getRank()).append("\n");
}
for (Reference r : o.getReferences()) {
sb.append(toString(r));
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(StatementGroup o) {
StringBuilder sb = new StringBuilder();
for (Statement s : o) {
sb.append(toString(s));
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(SiteLink o) {
if (o.getBadges().isEmpty()) {
return o.getSiteKey() + "/" + o.getPageTitle();
} else {
return o.getSiteKey() + "/" + o.getPageTitle() + " "
+ o.getBadges();
}
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(PropertyDocument o) {
return "==PropertyDocument " + o.getEntityId().getIri() + " (r"
+ o.getRevisionId() + ") ==\n" + "* Datatype: "
+ o.getDatatype() + toStringForTermedDocument(o)
+ toStringForStatementDocument(o);
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(ItemDocument o) {
StringBuilder sb = new StringBuilder();
sb.append("==ItemDocument ").append(o.getEntityId().getIri());
sb.append(" (r").append(o.getRevisionId()).append(") ");
sb.append("==").append(toStringForTermedDocument(o));
sb.append(toStringForStatementDocument(o));
sb.append("* Site links: ");
boolean first = true;
SortedSet siteKeys = new TreeSet<>(o.getSiteLinks()
.keySet());
for (String key : siteKeys) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(o.getSiteLinks().get(key)));
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(LexemeDocument o) {
StringBuilder sb = new StringBuilder();
sb.append("==LexemeDocument ").append(o.getEntityId().getIri());
sb.append(" (r").append(o.getRevisionId()).append(") ");
sb.append("==");
sb.append("\n* Lexical category: ").append(o.getLexicalCategory().getIri());
sb.append("\n* Language: ").append(o.getLanguage().getIri());
boolean first;
sb.append("\n* Lemmas: ");
first = true;
SortedSet labelKeys = new TreeSet<>(o.getLemmas().keySet());
for (String key : labelKeys) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(o.getLemmas().get(key)));
}
sb.append(toStringForStatementDocument(o));
sb.append("\n* Forms: \n");
for(FormDocument form : o.getForms()) {
sb.append(form.toString()).append('\n');
}
sb.append("\n* Senses: \n");
for(SenseDocument sense : o.getSenses()) {
sb.append(sense.toString()).append('\n');
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(FormDocument o) {
StringBuilder sb = new StringBuilder();
sb.append("==FormDocument ").append(o.getEntityId().getIri());
sb.append(" (r").append(o.getRevisionId()).append(") ");
sb.append("==");
boolean first;
sb.append("\n* Lemmas: ");
first = true;
SortedSet labelKeys = new TreeSet<>(o.getRepresentations().keySet());
for (String key : labelKeys) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(o.getRepresentations().get(key)));
}
sb.append("\n* Grammatical features: ");
for(ItemIdValue feature : o.getGrammaticalFeatures()) {
sb.append(feature.toString()).append(' ');
}
sb.append(toStringForStatementDocument(o));
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(SenseDocument o) {
StringBuilder sb = new StringBuilder();
sb.append("==SenseDocument ").append(o.getEntityId().getIri());
sb.append(" (r").append(o.getRevisionId()).append(") ");
sb.append("==");
boolean first;
sb.append("\n* Lemmas: ");
first = true;
SortedSet labelKeys = new TreeSet<>(o.getGlosses().keySet());
for (String key : labelKeys) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(o.getGlosses().get(key)));
}
sb.append(toStringForStatementDocument(o));
return sb.toString();
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(MediaInfoDocument o) {
StringBuilder sb = new StringBuilder();
sb.append("==MediaInfoDocument ").append(o.getEntityId().getIri());
sb.append(" (r").append(o.getRevisionId()).append(") ");
sb.append("==");
sb.append(toStringForLabeledDocument(o));
sb.append(toStringForStatementDocument(o));
return sb.toString();
}
protected static String toStringForStatementDocument(StatementDocument o) {
StringBuilder sb = new StringBuilder();
sb.append("\n===Statements===\n");
for (StatementGroup sg : o.getStatementGroups()) {
sb.append(toString(sg));
}
sb.append("\n===End of statements===\n");
return sb.toString();
}
/**
* Returns a human-readable string representation of the given
* {@link TermedDocument}.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
protected static String toStringForTermedDocument(TermedDocument o) {
StringBuilder sb = new StringBuilder();
boolean first;
sb.append(toStringForLabeledDocument(o));
sb.append("\n* Descriptions: ");
first = true;
SortedSet descriptionKeys = new TreeSet<>(o
.getDescriptions().keySet());
for (String key : descriptionKeys) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(o.getDescriptions().get(key)));
}
sb.append("\n* Aliases: ");
first = true;
SortedSet aliasKeys = new TreeSet<>(o.getAliases()
.keySet());
for (String key : aliasKeys) {
for (MonolingualTextValue mtv : o.getAliases().get(key)) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(mtv));
}
}
return sb.toString();
}
/**
* Returns a human-readable string representation of the given
* {@link LabeledDocument}.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
private static String toStringForLabeledDocument(LabeledDocument o) {
StringBuilder sb = new StringBuilder();
boolean first;
sb.append("\n* Labels: ");
first = true;
SortedSet labelKeys = new TreeSet<>(o.getLabels()
.keySet());
for (String key : labelKeys) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(toString(o.getLabels().get(key)));
}
return sb.toString();
}
/**
* Returns a human-readable string representation of a reference to a globe
* on which coordinates may be present. Known globes (such as Earth) are
* replaced by their common English names.
*
* @param globeIri
* the globe item's IRI
* @return a string representation of the globe
*/
protected static String getGlobeString(String globeIri) {
switch (globeIri) {
case GlobeCoordinatesValue.GLOBE_EARTH:
return "Earth";
default:
return globeIri;
}
}
/**
* Returns a human-readable string representation of a reference to a
* calendar model that is used for a time value. Known calendars (such as
* proleptic Gregorian calendar) are replaced by short English names. The
* term "proleptic" is omitted.
*
* @param calendarModel
* the calendar model item's IRI
* @return a string representation of the calendar model
*/
protected static String getCalendarString(String calendarModel) {
switch (calendarModel) {
case TimeValue.CM_GREGORIAN_PRO:
return "Gregorian";
case TimeValue.CM_JULIAN_PRO:
return "Julian";
default:
return calendarModel;
}
}
/**
* Returns a human-readable string representation of a reference to a
* precision that is used for a time value.
*
* @param precision
* the numeric precision
* @return a string representation of the precision
*/
protected static String getTimePrecisionString(byte precision) {
switch (precision) {
case TimeValue.PREC_SECOND:
return "sec";
case TimeValue.PREC_MINUTE:
return "min";
case TimeValue.PREC_HOUR:
return "hour";
case TimeValue.PREC_DAY:
return "day";
case TimeValue.PREC_MONTH:
return "month";
case TimeValue.PREC_YEAR:
return "year";
case TimeValue.PREC_DECADE:
return "decade";
case TimeValue.PREC_100Y:
return "100 years";
case TimeValue.PREC_1KY:
return "1000 years";
case TimeValue.PREC_10KY:
return "10K years";
case TimeValue.PREC_100KY:
return "100K years";
case TimeValue.PREC_1MY:
return "1 million years";
case TimeValue.PREC_10MY:
return "10 million years";
case TimeValue.PREC_100MY:
return "100 million years";
case TimeValue.PREC_1GY:
return "1000 million years";
default:
return "Unsupported precision " + precision;
}
}
/**
* Returns a human-readable string representation of the given object.
*
* @see java.lang.Object#toString()
* @param o
* the object to represent as string
* @return a string representation of the object
*/
public static String toString(EntityRedirectDocument o) {
return "==EntityRedirect " + o.getEntityId().getIri() +
" (r" + o.getRevisionId() + ") " +
"==\n" +
"Target: " + o.getTargetId().getIri();
}
}
package-info.java 0000664 0000000 0000000 00000001474 14447725663 0034410 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers /**
* Package for mostly static helper code to work with data objects.
*
* @author Markus Kroetzsch
*
*/
package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/ 0000775 0000000 0000000 00000000000 14447725663 0032655 5 ustar 00root root 0000000 0000000 AliasUpdateImpl.java 0000664 0000000 0000000 00000013323 14447725663 0036461 0 ustar 00root root 0000000 0000000 Wikidata-Toolkit-0.14.6/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation /*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
package org.wikidata.wdtk.datamodel.implementation;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.lang3.Validate;
import org.wikidata.wdtk.datamodel.helpers.Equality;
import org.wikidata.wdtk.datamodel.helpers.Hash;
import org.wikidata.wdtk.datamodel.interfaces.AliasUpdate;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Jackson implementation of {@link AliasUpdate}.
*/
public class AliasUpdateImpl implements AliasUpdate {
@JsonIgnore
private final String languageCode;
@JsonIgnore
private final List recreated;
private final List added;
private final Set removed;
/**
* Initializes new alias update. This update applies to aliases in one language
* only. Callers should specify either {@code recreated} parameter or
* {@code added} and {@code removed} parameters, because combination of the two
* update approaches is not possible. To remove all aliases, pass empty list in
* {@code recreated} parameter.
*
* @param recreated
* new list of aliases that completely replaces the old ones or
* {@code null} to not recreate aliases
* @param added
* aliases added in this update or empty collection for no additions
* @param removed
* aliases removed in this update or empty collection for no removals
* @throws NullPointerException
* if {@code added}, {@code removed}, or any alias is {@code null}
* @throws IllegalArgumentException
* if given invalid combination of parameters
*/
public AliasUpdateImpl(List recreated, List added,
Collection removed) {
Objects.requireNonNull(added, "List of added aliases cannot be null.");
Objects.requireNonNull(removed, "List of removed aliases cannot be null.");
Validate.isTrue(recreated == null || added.isEmpty() && removed.isEmpty(),
"Cannot combine additions/removals with recreating the alias list.");
List all = new ArrayList<>();
if (recreated != null) {
all.addAll(recreated);
}
all.addAll(added);
all.addAll(removed);
for (MonolingualTextValue alias : all) {
Validate.notNull(alias, "Alias object cannot be null.");
}
Validate.isTrue(all.stream().map(v -> v.getLanguageCode()).distinct().count() <= 1,
"Inconsistent language codes.");
if (recreated != null) {
Validate.isTrue(recreated.stream().distinct().count() == recreated.size(),
"Every alias in the new list of aliases must be unique.");
}
Validate.isTrue(added.stream().distinct().count() == added.size(),
"Every new alias must be unique.");
Validate.isTrue(removed.stream().distinct().count() == removed.size(),
"Every removed alias must be unique.");
Validate.isTrue(all.stream().distinct().count() == all.size(),
"Cannot add and remove the same alias.");
languageCode = all.stream().map(v -> v.getLanguageCode()).findFirst().orElse(null);
this.recreated = recreated != null
? Collections.unmodifiableList(recreated.stream().map(TermImpl::new).collect(toList()))
: null;
this.added = Collections.unmodifiableList(added.stream().map(AddedAlias::new).collect(toList()));
this.removed = Collections.unmodifiableSet(removed.stream().map(RemovedAlias::new).collect(toSet()));
}
@JsonIgnore
@Override
public boolean isEmpty() {
return recreated == null && added.isEmpty() && removed.isEmpty();
}
@JsonIgnore
@Override
public Optional getLanguageCode() {
return Optional.ofNullable(languageCode);
}
@JsonIgnore
@Override
public Optional> getRecreated() {
return Optional.ofNullable(recreated);
}
@JsonIgnore
@Override
public List getAdded() {
return added;
}
@JsonIgnore
@Override
public Set getRemoved() {
return removed;
}
static class AddedAlias extends TermImpl {
AddedAlias(MonolingualTextValue alias) {
super(alias);
}
@JsonProperty("add")
String getAddCommand() {
return "";
}
}
static class RemovedAlias extends TermImpl {
RemovedAlias(MonolingualTextValue alias) {
super(alias);
}
@JsonProperty("remove")
String getRemoveCommand() {
return "";
}
}
@JsonValue
List