├── .circleci
└── config.yml
├── .editorconfig
├── .gitattributes
├── .github
├── ISSUE_TEMPLATE.md
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .hgtags
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── build.gradle
├── config
└── checkstyle
│ └── checkstyle.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── resources
├── fake-itemset.csv
└── fake-itemset.xml
└── src
├── org
└── opendatakit
│ └── validate
│ ├── ErrorListener.java
│ ├── FormValidator.java
│ ├── StubPropertyManager.java
│ ├── StubReference.java
│ ├── StubReferenceFactory.java
│ ├── StubSetGeopointAction.java
│ └── StubSetGeopointActionHandler.java
└── test
├── java
└── org
│ └── opendatakit
│ └── validate
│ └── ValidateExternalSecondaryInstancesTest.java
└── resources
├── csv_external_instance.xml
├── external_instance_custom_refs.xml
└── xml_external_instance.xml
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | working_directory: ~/work
5 | docker:
6 | - image: circleci/openjdk:latest
7 | steps:
8 | - checkout
9 | - restore_cache:
10 | key: jars-{{ checksum "build.gradle" }}
11 | - run: ./gradlew check jar
12 | - save_cache:
13 | paths:
14 | - ~/.gradle
15 | - ~/work/.gradle
16 | key: jars-{{ checksum "build.gradle" }}
17 | - store_artifacts:
18 | path: build/reports
19 | destination: reports
20 | - store_artifacts:
21 | path: build/libs
22 | destination: libs
23 | - store_test_results:
24 | path: build/test-results
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 4
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=lf
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
14 |
15 | #### Software versions
16 | Validate v1.x.x, Java v1.x.x, operating system, Aggregate v1.x.x, Collect v1.x.x...
17 |
18 | #### Problem description
19 |
20 | #### Steps to reproduce the problem
21 |
22 | #### Expected behavior
23 |
24 | #### Other information
25 | Things you tried, stack traces, related issues, suggestions on how to fix it...
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | Closes #
2 |
3 | #### What has been done to verify that this works as intended?
4 |
5 | #### Why is this the best possible solution? Were any other approaches considered?
6 |
7 | #### Are there any risks to merging this code? If so, what are they?
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | bin
2 | out
3 | *.iml
4 | .gradle
5 | local.properties
6 | .idea
7 | .DS_Store
8 | build
--------------------------------------------------------------------------------
/.hgtags:
--------------------------------------------------------------------------------
1 | aa5ea28cd975201c95c2a152173b0926c6105566 v1.4
2 | 696f3dddfc759384544c3fddc7fe3aed889a1fb9 v1.5
3 | fea4eff3d2395f38810c15d925d0f0e33e9c6124 for ODK Collect v1.2
4 | 535db51b400b8ec14a0ed58a3be4b09883c5cd41 v1.2.1 for ODK Collect v1.2
5 | fb957aaf921dcb8b05a1e1288ae5824a781a0443 v1.2.2 for ODK Collect v1.2
6 | 0ce39057ef8be65ccb8acdbc070dcc4b3fe78977 v1.2.3 for ODK Collect v1.2
7 | 0ce39057ef8be65ccb8acdbc070dcc4b3fe78977 v1.2.3 for ODK Collect v1.2
8 | 952d48eb3f86f6e6d62c051b51767f826a84a1ff v1.2.3 for ODK Collect v1.2
9 | 95d7294212f1a947ed78a949d831388a3d34f306 v1.3 for ODK Collect v1.3 and v1.2
10 | f9bb81dcfe31344c097bdeb0a193402a67f2800b v1.4 for ODK Collect v1.4 thru v1.2
11 | f9bb81dcfe31344c097bdeb0a193402a67f2800b v1.4 for ODK Collect v1.4 thru v1.2
12 | 199069cfb436f9ec768ee3cdbc0e13ce3f43c0ff v1.4 for ODK Collect v1.4 thru v1.2
13 | 199069cfb436f9ec768ee3cdbc0e13ce3f43c0ff v1.4 for ODK Collect v1.4 thru v1.2
14 | f9bb81dcfe31344c097bdeb0a193402a67f2800b v1.4 for ODK Collect v1.4 thru v1.2
15 | a06b4d98045ff3f1b4459cec04ee59d355304279 v1.4 for ODK Collect v1.4 and older
16 | dd14d695c17f754125740c61db25c0dab5e00413 v1.4 for ODK Collect v1.4 rev 1037 and older
17 | 776bb9823fa745d5f15b91844ab706e972738046 v1.4.3 for ODK Collect v1.4.3 and newer
18 | 1ac98ac2fc6be870098e3135f59b33299c255e07 v1.4.4 for ODK Collect v1.4.4 and newer
19 | ba7480bb686e01af87136ec02fa1867ff53f2171 v1.4.5 for ODK Collect v1.4.5 and newer
20 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | Please refer to the project-wide [ODK Code of Conduct](https://github.com/opendatakit/governance/blob/master/CODE-OF-CONDUCT.md).
2 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing code to ODK Validate
2 |
3 | This is a living document. If you see something that could be improved, edit this document and submit a pull request following the instructions below!
4 |
5 | ## Submitting a pull request
6 | To contribute code to ODK Validate, you will need to open a [pull request](https://help.github.com/articles/about-pull-requests/) which will be reviewed by the community and then merged into the core project.
7 |
8 | 1. [Set up your development environment](https://github.com/opendatakit/validate#setting-up-your-development-environment).
9 |
10 | 1. To make sure you have the latest version of the code, set up this repository as [a remote for your fork](https://help.github.com/articles/configuring-a-remote-for-a-fork/) and then [sync your fork](https://help.github.com/articles/syncing-a-fork/).
11 |
12 | 1. Create a branch for the code you will be writing:
13 |
14 | git checkout -b NAME_OF_YOUR_BRANCH
15 |
16 | 1. If there is an [issue](https://github.com/opendatakit/validate/issues) corresponding to what you will work on, put `@opendatakit-bot claim` as a comment on issue to say you are claiming it. If this is your first time contributing to the repo, the bot will send you an invite. Once you accept this invite, the bot will assign you to the issue. If there is no issue yet, create one to provide background on the problem you are solving.
17 |
18 | 1. Once you've made incremental progress towards you goal, commit your changes with a meaningful commit message. Use [keywords for closing issues](https://help.github.com/articles/closing-issues-via-commit-messages/) to refer to issues and have them automatically close when your changes are merged.
19 |
20 | git commit -m "Do a thing. Fix #1."
21 |
22 | 1. Push changes to your fork to make them publicly available:
23 |
24 | git push
25 |
26 | 1. When your changes are ready to be added to the core ODK Validate project, [open a pull request](https://help.github.com/articles/creating-a-pull-request/). Make sure to set the base fork to `opendatakit/validate`. Describe your changes in the comment, refer to any relevant issues using [keywords for closing issues](https://help.github.com/articles/closing-issues-via-commit-messages/) and tag any person you think might need to know about the changes.
27 |
28 | 1. Pull requests will be reviewed when committers have time. If you haven't received a review in 10 days, you may notify committers by putting `@opendatakit/validate` in a comment.
29 |
30 | ## Making sure your pull request is accepted
31 | 1. Confirm that your code compiles.
32 |
33 | 1. Verify the functionality. Ideally, include automated tests with each pull request. If that's not possible, describe in the pull request comment which cases you tried manually to confirm that your code works as expected.
34 |
35 | 1. Make sure that there is an issue that corresponds to the pull request and that it has been discussed by the community as necessary.
36 |
37 | 1. Keep your pull request focused on one narrow goal. This could mean addressing an issue with multiple, smaller pull requests. Small pull requests are easier to review and less likely to introduce bugs. If you would like to make stylistic changes to the code, create a separate pull request.
38 |
39 | 1. Run `./gradlew lint` and `./gradlew check` and fix any errors.
40 |
41 | 1. Write clear code. Use descriptive names and create meaningful abstractions (methods, classes).
42 |
43 | 1. Document your reasoning. Your commit messages should make it clear why each change has been made.
44 |
45 | 1. Follow the guidelines below.
46 |
47 | ## The review process
48 | Bug fixes, pull requests corresponding to issues with a clearly stated goal and pull requests with clear tests and/or process for manual verification are given priority. Pull requests that are unclear or controversial may be tagged as `needs discussion` and/or may take longer to review.
49 |
50 | We try to have at least two people review every pull request and we encourage everyone to participate in the review process to get familiar with the code base and help ensure higher quality. Reviewers should ask themselves some or all of the following questions:
51 | - Was this change adequately discussed prior to implementation?
52 | - Is the intended behavior clear under all conditions?
53 | - What interesting cases should be verified?
54 | - Is the behavior as intended in all cases?
55 | - What other functionality could this PR affect? Does that functionality still work as intended?
56 | - Was the change verified with several different devices and Android versions?
57 | - Is the code easy to understand and to maintain?
58 |
59 | When a pull request is first created, @opendatakit-bot tags it as `needs review` to indicate that code review is needed. Community members review the code and leave their comments, verifying that the changes included are relevant and properly address the issue. A maintainer does a thorough code review and when satisfied with the code, tags the pull request as `needs testing` to indicate the need for a manual [black-box testing](https://en.wikipedia.org/wiki/Black-box_testing) pass. A pull request may go back and forth between `needs testing` and `needs review` until the behavior is thoroughly verified. Once the behavior has been thoroughly verified, the pull request is tagged as `behavior verified`. A maintainer then merges the changes. Pull requests that need more complete reviews including review of approach and/or appropriateness are tagged with `reviews wanted`. Any community member is encouraged to participate in the review process!
60 |
61 | Small fixes that target very particular bugs may occasionally be merged without a second review.
62 |
63 | ## Style guidelines
64 | For now, match the style of the code in the file you are editing.
65 |
66 | ## Code from external sources
67 | ODK Validate is released under the [Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0). Please make sure that any code you include is an OSI-approved [permissive license](https://opensource.org/faq#permissive). **Please note that if no license is specified for a piece of code or if it has an incompatible license such as GPL, using it puts the project at legal risk**.
68 |
69 | Sites with compatible licenses (including [StackOverflow](http://stackoverflow.com/)) will sometimes provide exactly the code snippet needed to solve a problem. You are encouraged to use such snippets in ODK Validate as long as you attribute them by including a direct link to the source. In addition to complying with the content license, this provides useful context for anyone reading the code.
70 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Apache License
2 | ==============
3 |
4 | _Version 2.0, January 2004_
5 | _<>_
6 |
7 | ### Terms and Conditions for use, reproduction, and distribution
8 |
9 | #### 1. Definitions
10 |
11 | “License” shall mean the terms and conditions for use, reproduction, and
12 | distribution as defined by Sections 1 through 9 of this document.
13 |
14 | “Licensor” shall mean the copyright owner or entity authorized by the copyright
15 | owner that is granting the License.
16 |
17 | “Legal Entity” shall mean the union of the acting entity and all other entities
18 | that control, are controlled by, or are under common control with that entity.
19 | For the purposes of this definition, “control” means **(i)** the power, direct or
20 | indirect, to cause the direction or management of such entity, whether by
21 | contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
22 | outstanding shares, or **(iii)** beneficial ownership of such entity.
23 |
24 | “You” (or “Your”) shall mean an individual or Legal Entity exercising
25 | permissions granted by this License.
26 |
27 | “Source” form shall mean the preferred form for making modifications, including
28 | but not limited to software source code, documentation source, and configuration
29 | files.
30 |
31 | “Object” form shall mean any form resulting from mechanical transformation or
32 | translation of a Source form, including but not limited to compiled object code,
33 | generated documentation, and conversions to other media types.
34 |
35 | “Work” shall mean the work of authorship, whether in Source or Object form, made
36 | available under the License, as indicated by a copyright notice that is included
37 | in or attached to the work (an example is provided in the Appendix below).
38 |
39 | “Derivative Works” shall mean any work, whether in Source or Object form, that
40 | is based on (or derived from) the Work and for which the editorial revisions,
41 | annotations, elaborations, or other modifications represent, as a whole, an
42 | original work of authorship. For the purposes of this License, Derivative Works
43 | shall not include works that remain separable from, or merely link (or bind by
44 | name) to the interfaces of, the Work and Derivative Works thereof.
45 |
46 | “Contribution” shall mean any work of authorship, including the original version
47 | of the Work and any modifications or additions to that Work or Derivative Works
48 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
49 | by the copyright owner or by an individual or Legal Entity authorized to submit
50 | on behalf of the copyright owner. For the purposes of this definition,
51 | “submitted” means any form of electronic, verbal, or written communication sent
52 | to the Licensor or its representatives, including but not limited to
53 | communication on electronic mailing lists, source code control systems, and
54 | issue tracking systems that are managed by, or on behalf of, the Licensor for
55 | the purpose of discussing and improving the Work, but excluding communication
56 | that is conspicuously marked or otherwise designated in writing by the copyright
57 | owner as “Not a Contribution.”
58 |
59 | “Contributor” shall mean Licensor and any individual or Legal Entity on behalf
60 | of whom a Contribution has been received by Licensor and subsequently
61 | incorporated within the Work.
62 |
63 | #### 2. Grant of Copyright License
64 |
65 | Subject to the terms and conditions of this License, each Contributor hereby
66 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
67 | irrevocable copyright license to reproduce, prepare Derivative Works of,
68 | publicly display, publicly perform, sublicense, and distribute the Work and such
69 | Derivative Works in Source or Object form.
70 |
71 | #### 3. Grant of Patent License
72 |
73 | Subject to the terms and conditions of this License, each Contributor hereby
74 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
75 | irrevocable (except as stated in this section) patent license to make, have
76 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
77 | such license applies only to those patent claims licensable by such Contributor
78 | that are necessarily infringed by their Contribution(s) alone or by combination
79 | of their Contribution(s) with the Work to which such Contribution(s) was
80 | submitted. If You institute patent litigation against any entity (including a
81 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
82 | Contribution incorporated within the Work constitutes direct or contributory
83 | patent infringement, then any patent licenses granted to You under this License
84 | for that Work shall terminate as of the date such litigation is filed.
85 |
86 | #### 4. Redistribution
87 |
88 | You may reproduce and distribute copies of the Work or Derivative Works thereof
89 | in any medium, with or without modifications, and in Source or Object form,
90 | provided that You meet the following conditions:
91 |
92 | * **(a)** You must give any other recipients of the Work or Derivative Works a copy of
93 | this License; and
94 | * **(b)** You must cause any modified files to carry prominent notices stating that You
95 | changed the files; and
96 | * **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
97 | all copyright, patent, trademark, and attribution notices from the Source form
98 | of the Work, excluding those notices that do not pertain to any part of the
99 | Derivative Works; and
100 | * **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
101 | Derivative Works that You distribute must include a readable copy of the
102 | attribution notices contained within such NOTICE file, excluding those notices
103 | that do not pertain to any part of the Derivative Works, in at least one of the
104 | following places: within a NOTICE text file distributed as part of the
105 | Derivative Works; within the Source form or documentation, if provided along
106 | with the Derivative Works; or, within a display generated by the Derivative
107 | Works, if and wherever such third-party notices normally appear. The contents of
108 | the NOTICE file are for informational purposes only and do not modify the
109 | License. You may add Your own attribution notices within Derivative Works that
110 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
111 | provided that such additional attribution notices cannot be construed as
112 | modifying the License.
113 |
114 | You may add Your own copyright statement to Your modifications and may provide
115 | additional or different license terms and conditions for use, reproduction, or
116 | distribution of Your modifications, or for any such Derivative Works as a whole,
117 | provided Your use, reproduction, and distribution of the Work otherwise complies
118 | with the conditions stated in this License.
119 |
120 | #### 5. Submission of Contributions
121 |
122 | Unless You explicitly state otherwise, any Contribution intentionally submitted
123 | for inclusion in the Work by You to the Licensor shall be under the terms and
124 | conditions of this License, without any additional terms or conditions.
125 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
126 | any separate license agreement you may have executed with Licensor regarding
127 | such Contributions.
128 |
129 | #### 6. Trademarks
130 |
131 | This License does not grant permission to use the trade names, trademarks,
132 | service marks, or product names of the Licensor, except as required for
133 | reasonable and customary use in describing the origin of the Work and
134 | reproducing the content of the NOTICE file.
135 |
136 | #### 7. Disclaimer of Warranty
137 |
138 | Unless required by applicable law or agreed to in writing, Licensor provides the
139 | Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
140 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
141 | including, without limitation, any warranties or conditions of TITLE,
142 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
143 | solely responsible for determining the appropriateness of using or
144 | redistributing the Work and assume any risks associated with Your exercise of
145 | permissions under this License.
146 |
147 | #### 8. Limitation of Liability
148 |
149 | In no event and under no legal theory, whether in tort (including negligence),
150 | contract, or otherwise, unless required by applicable law (such as deliberate
151 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
152 | liable to You for damages, including any direct, indirect, special, incidental,
153 | or consequential damages of any character arising as a result of this License or
154 | out of the use or inability to use the Work (including but not limited to
155 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
156 | any and all other commercial damages or losses), even if such Contributor has
157 | been advised of the possibility of such damages.
158 |
159 | #### 9. Accepting Warranty or Additional Liability
160 |
161 | While redistributing the Work or Derivative Works thereof, You may choose to
162 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
163 | other liability obligations and/or rights consistent with this License. However,
164 | in accepting such obligations, You may act only on Your own behalf and on Your
165 | sole responsibility, not on behalf of any other Contributor, and only if You
166 | agree to indemnify, defend, and hold each Contributor harmless for any liability
167 | incurred by, or claims asserted against, such Contributor by reason of your
168 | accepting any such warranty or additional liability.
169 |
170 | _END OF TERMS AND CONDITIONS_
171 |
172 | ### APPENDIX: How to apply the Apache License to your work
173 |
174 | To apply the Apache License to your work, attach the following boilerplate
175 | notice, with the fields enclosed by brackets `[]` replaced with your own
176 | identifying information. (Don't include the brackets!) The text should be
177 | enclosed in the appropriate comment syntax for the file format. We also
178 | recommend that a file or class name and description of purpose be included on
179 | the same “printed page” as the copyright notice for easier identification within
180 | third-party archives.
181 |
182 | Copyright [yyyy] [name of copyright owner]
183 |
184 | Licensed under the Apache License, Version 2.0 (the "License");
185 | you may not use this file except in compliance with the License.
186 | You may obtain a copy of the License at
187 |
188 | http://www.apache.org/licenses/LICENSE-2.0
189 |
190 | Unless required by applicable law or agreed to in writing, software
191 | distributed under the License is distributed on an "AS IS" BASIS,
192 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193 | See the License for the specific language governing permissions and
194 | limitations under the License.
195 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ODK Validate
2 | 
3 | [](https://opensource.org/licenses/Apache-2.0)
4 | [](https://circleci.com/gh/opendatakit/briefcase)
5 | [](http://slack.opendatakit.org)
6 |
7 | ODK Validate is a desktop Java application for confirming that a form is compliant with the [ODK XForms spec](http://opendatakit.github.io/xforms-spec).
8 |
9 | ODK Validate is part of Open Data Kit (ODK), a free and open-source set of tools which help organizations author, field, and manage mobile data collection solutions. Learn more about the Open Data Kit project and its history [here](https://opendatakit.org/about/) and read about example ODK deployments [here](https://opendatakit.org/about/deployments/).
10 |
11 | * ODK website: [https://opendatakit.org](https://opendatakit.org)
12 | * ODK Validate usage instructions: [https://opendatakit.org/use/validate](https://opendatakit.org/use/validate)
13 | * ODK forum: [https://forum.opendatakit.org](https://forum.opendatakit.org)
14 | * ODK developer Slack chat: [http://slack.opendatakit.org](http://slack.opendatakit.org)
15 | * ODK developer Slack archive: [http://opendatakit.slackarchive.io](http://opendatakit.slackarchive.io)
16 | * ODK developer wiki: [https://github.com/opendatakit/opendatakit/wiki](https://github.com/opendatakit/opendatakit/wiki)
17 |
18 | ## Setting up your development environment
19 |
20 | 1. Fork the validate project ([why and how to fork](https://help.github.com/articles/fork-a-repo/))
21 |
22 | 1. Clone your fork of the project locally. At the command line:
23 |
24 | git clone https://github.com/YOUR-GITHUB-USERNAME/validate
25 |
26 | We recommend using [IntelliJ IDEA](https://www.jetbrains.com/idea/) for development. On the welcome screen, click `Import Project`, navigate to your validate folder, and select the `build.gradle` file. Use the defaults through the wizard. Once the project is imported, IntelliJ may ask you to update your remote maven repositories. Follow the instructions to do so.
27 |
28 | The main class is `org.opendatakit.validate.FormValidator`.
29 |
30 | ## Running the project
31 |
32 | To run the project, go to the `View` menu, then `Tool Windows > Gradle`. `run` will be in `odk-validate > Tasks > application > run`. Double-click `run` to run the application. This Gradle task will now be the default action in your `Run` menu.
33 |
34 | You must use the Gradle task to run the application because there is a generated class (`BuildConfig`) that IntelliJ may not properly import and recognize.
35 |
36 | To package a runnable jar, use the `jar` Gradle task.
37 |
38 | ## How Validate validates
39 |
40 | Validate is a thin wrapper around the [JavaRosa](https://github.com/opendatakit/javarosa/) form parsing library. Validate uses JavaRosa to parse an [ODK XForms](https://opendatakit.github.io/xforms-spec/) form definition into an in-memory representation. Validate then goes through the in-memory representation in the same way a client such as [Collect](https://github.com/opendatakit/collect) would. This simulates displaying questions to the user and exercises the logic in the form. Errors detected by JavaRosa are presented to the user.
41 |
42 | Validate does not simulate entering any data. Expressions that are not reached when first displaying a form are not verified. For example, if an `if` call has an invalid function call in one of its branches such as `if (/data/my_var = 'yes', invalid-function('bad', 'bad'), 0)`, Validate will not identify that unless the default value for `my_var` is `yes`.
43 |
44 | In general, issues with validation or what errors get presented are JavaRosa issues and should be filed [in its repository](https://github.com/opendatakit/javarosa/).
45 |
46 | ## Integrating Validate with your Java app
47 |
48 | 1. Download the [latest ODKValidate jar](https://opendatakit.org/downloads/download-category/validate/) or build your own.
49 |
50 | 1. Add the ODKValidate jar to your classpath.
51 |
52 | 1. Create a custom `ErrorListener` by implementing the `org.opendatakit.validate.ErrorListener` interface.
53 |
54 | 1. Add the custom `ErrorListener` to the form validator and call any of the various `validate(...)` methods.
55 |
56 | See example below:
57 | ```java
58 | ErrorListener listener = new ErrorListener() {
59 | public void error(Object err) {
60 | // ...custom code to handle error message
61 | System.err.println(err);
62 | }
63 |
64 | public void error(Object err, Throwable t) {
65 | // ...custom code to handle error message and exception
66 | System.err.println("" + err + t);
67 | }
68 |
69 | public void info(Object msg) {
70 | // ...custom code
71 | System.out.println(msg);
72 | }
73 | };
74 |
75 | new FormValidator().setErrorListener(listener).validateText("...");
76 |
77 | ```
78 |
79 | ## Calling Validate via the command line interface
80 |
81 | You can use Validate through the command line like this: `java -jar ODKValidate.jar [--fail-fast] path/to/xform.xml [FORM...]`.
82 |
83 | An exit code of 0 means **Valid XForm** and 1 is **Invalid XForm**.
84 |
85 | ## Contributing code
86 | Any and all contributions to the project are welcome. ODK Validate is used across the world primarily by organizations with a social purpose so you can have real impact!
87 |
88 | If you're ready to contribute code, see [the contribution guide](CONTRIBUTING.md).
89 |
90 | ## Downloading builds
91 | Per-commit debug builds can be found on [CircleCI](https://circleci.com/gh/opendatakit/validate). Login with your GitHub account, click the build you'd like, then find the JAR in the Artifacts tab under $CIRCLE_ARTIFACTS/libs.
92 |
93 | Current and previous production builds can be found on the [ODK website](https://opendatakit.org/downloads/download-info/odk-validate/).
94 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'application'
3 | id 'checkstyle'
4 | id 'idea'
5 | id 'de.fuerstenau.buildconfig' version '1.1.8'
6 | }
7 |
8 | repositories {
9 | mavenCentral()
10 | maven { url = 'https://oss.sonatype.org/content/groups/public' }
11 | }
12 |
13 | sourceSets {
14 | main {
15 | java {
16 | srcDirs = ['src']
17 | exclude 'test'
18 | }
19 |
20 | resources {
21 | srcDirs = ['resources']
22 | }
23 | }
24 | }
25 |
26 | targetCompatibility = '1.8'
27 | sourceCompatibility = '1.8'
28 |
29 | dependencies {
30 | compile group: 'net.sf.kxml', name: 'kxml2', version: '2.3.0'
31 | compile (group: 'org.getodk', name: 'javarosa', version: '4.4.1')
32 | compile group: 'org.slf4j', name: 'slf4j-nop', version: '1.7.25'
33 | testCompile 'junit:junit:4.13.2'
34 | testCompile 'org.hamcrest:hamcrest-all:1.3'
35 | }
36 |
37 | // Required to use fileExtensions property in checkstyle file
38 | checkstyle {
39 | toolVersion = '7.6.1'
40 | }
41 |
42 | ant.condition(property: 'os', value: 'windows') {
43 | os(family: 'windows')
44 | }
45 | ant.condition(property: 'os', value: 'unix' ) {
46 | os(family: 'unix')
47 | }
48 |
49 | // Use the result of git describe --tags --dirty as the version name
50 | // From http://stackoverflow.com/questions/17097263#24121734
51 | def getVersionName = { ->
52 | try {
53 | def stdout = new ByteArrayOutputStream()
54 | exec {
55 | switch(ant.properties.os) {
56 | case 'windows':
57 | commandLine 'cmd', '/c', 'git', 'describe', '--tags', '--dirty', '--always'
58 | break
59 | case 'unix':
60 | commandLine 'git', 'describe', '--tags', '--dirty', '--always'
61 | break
62 | }
63 | standardOutput = stdout
64 | }
65 | return stdout.toString().trim()
66 | }
67 | catch (ignored) {
68 | return null;
69 | }
70 | }
71 |
72 | buildConfig {
73 | appName = 'ODK Validate'
74 | version = getVersionName()
75 | clsName = 'BuildConfig'
76 | packageName = 'org.opendatakit.validate.buildconfig'
77 | }
78 |
79 | mainClassName = 'org.opendatakit.validate.FormValidator'
80 |
81 | jar {
82 | baseName = buildConfig.appName
83 | version = buildConfig.version
84 | archiveName = (baseName + ' ' + version + '.jar').replaceAll(" ","-")
85 |
86 | from {
87 | configurations.compile.collect {
88 | if (it.isDirectory()) {
89 | return it
90 | } else {
91 | if (it.path.contains("bouncycastle")) {
92 | return zipTree(it).matching {
93 | include '/**/*/ASN1Encodable.class', '/**/*/ASN1Object.class', '/**/*/X9ECParameters.class',
94 | '/**/*/X9ObjectIdentifiers.class', '/**/*/CipherParameters.class', '/**/*/DefaultServiceProperties.class',
95 | '/**/*/CryptoServiceProperties.class', '/**/*/CryptoServicePurpose.class', '/**/*/CryptoServicesConstraints.class',
96 | '/**/*/CryptoServicesPermission.class', '/**/*/CryptoServicesRegistrar.class', '/**/*/CryptoServicesRegistrar$1.class',
97 | '/**/*/CryptoServicesRegistrar$Property.class', '/**/*/CryptoServicesRegistrar$ThreadLocalSecureRandomProvider.class',
98 | '/**/*/Digest.class', '/**/*/EncodableDigest.class', '/**/*/LongDigest.class', '/**/*/SHA512Digest.class',
99 | '/**/*/Utils.class', '/**/*/Utils$DefaultPropertiesWithPRF.class', '/**/*/ExtendedDigest.class',
100 | '/**/*/AsymmetricKeyParameter.class', '/**/*/DHParameters.class', '/**/*/DHValidationParameters.class',
101 | '/**/*/DSAParameters.class', '/**/*/DSAValidationParameters.class', '/**/*/Ed25519PublicKeyParameters.class',
102 | '/**/*/SecureRandomProvider.class', '/**/*/Signer.class', '/**/*/Ed25519Signer.class', '/**/*/Ed25519Signer$Buffer.class',
103 | '/**/*/Utils.class', '/**/*/X25519Field.class', '/**/*/Codec.class', '/**/*/Ed25519.class', '/**/*/Ed25519$F.class',
104 | '/**/*/Ed25519$PointAccum.class', '/**/*/Ed25519$PointAffine.class', '/**/*/Ed25519$PointExtended.class',
105 | '/**/*/Ed25519$PointPrecomp.class', '/**/*/Ed25519$PointPrecompZ.class', '/**/*/Ed25519$PointTemp.class',
106 | '/**/*/Ed25519$PublicPoint.class', '/**/*/Scalar25519.class', '/**/*/ScalarUtil.class', '/**/*/Wnaf.class',
107 | '/**/*/Mod.class', '/**/*/Nat.class', '/**/*/Nat256.class', '/**/*/Arrays.class', '/**/*/Encodable.class',
108 | '/**/*/DecoderException.class', '/**/*/Encoder.class', '/**/*/EncoderException.class',
109 | '/**/*/Hex.class', '/**/*/HexEncoder.class', '/**/*/Integers.class',
110 | '/**/*/Memoable.class', '/**/*/Pack.class'
111 | }
112 | } else {
113 | return zipTree(it)
114 | }
115 | }
116 | }
117 | }
118 |
119 | manifest {
120 | attributes 'Main-Class': mainClassName
121 | }
122 |
123 | // Some of the dependencies are signed jars. When combined into a big jar, the corresponding signature files
124 | // don't match with big jar, so the runtime refuses to run the jar. The fix is to exclude the signature files.
125 | exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
126 | }
127 |
128 | // Useful for testing
129 | task explodedJar(type: Copy) {
130 | into "$buildDir/libs/$jar.baseName $jar.version"
131 | with jar
132 | }
133 |
--------------------------------------------------------------------------------
/config/checkstyle/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
41 |
46 |
50 |
51 |
52 |
53 |
57 |
58 |
61 |
65 |
70 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
90 |
95 |
100 |
105 |
109 |
114 |
119 |
124 |
130 |
135 |
140 |
145 |
146 |
156 |
164 |
168 |
169 |
170 |
175 |
176 |
177 |
181 |
185 |
190 |
191 |
192 |
195 |
196 |
200 |
209 |
214 |
217 |
220 |
221 |
222 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/getodk/validate/60a6b68cc39cdf61a32c164f9ec273cfdbee85a0/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/resources/fake-itemset.csv:
--------------------------------------------------------------------------------
1 | name,label
2 | a-csv-item, "A CSV Item"
--------------------------------------------------------------------------------
/resources/fake-itemset.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | an-xml-item
4 |
5 |
6 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/ErrorListener.java:
--------------------------------------------------------------------------------
1 | package org.opendatakit.validate;
2 |
3 | public interface ErrorListener {
4 |
5 | void error(Object err);
6 |
7 | void error(Object err, Throwable t);
8 |
9 | void info(Object msg);
10 |
11 | ErrorListener DEFAULT_ERROR_LISTENER = new ErrorListener() {
12 | public void error(Object err) {
13 | System.err.println(err);
14 | }
15 |
16 | public void error(Object err, Throwable t) {
17 | System.err.println(err);
18 | t.printStackTrace();
19 | }
20 |
21 | public void info(Object msg) {
22 | System.out.println(msg);
23 | }
24 |
25 | };
26 | }
27 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/FormValidator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | package org.opendatakit.validate;
16 |
17 | import java.awt.BorderLayout;
18 | import java.awt.Color;
19 | import java.awt.Dimension;
20 | import java.awt.Font;
21 | import java.awt.GridBagConstraints;
22 | import java.awt.GridBagLayout;
23 | import java.awt.Insets;
24 | import java.awt.event.ActionEvent;
25 | import java.awt.event.ActionListener;
26 | import java.io.ByteArrayInputStream;
27 | import java.io.ByteArrayOutputStream;
28 | import java.io.File;
29 | import java.io.FileInputStream;
30 | import java.io.FileNotFoundException;
31 | import java.io.InputStream;
32 | import java.io.IOException;
33 | import java.io.OutputStream;
34 | import java.io.PrintStream;
35 | import java.util.ArrayList;
36 | import java.util.HashSet;
37 | import java.util.List;
38 | import java.util.Set;
39 |
40 | import javax.swing.JButton;
41 | import javax.swing.JFileChooser;
42 | import javax.swing.JFrame;
43 | import javax.swing.JPanel;
44 | import javax.swing.JScrollPane;
45 | import javax.swing.JTextArea;
46 | import javax.swing.JTextField;
47 | import javax.swing.UIManager;
48 | import javax.swing.UnsupportedLookAndFeelException;
49 | import javax.xml.parsers.DocumentBuilderFactory;
50 |
51 | import org.javarosa.core.model.Constants;
52 | import org.javarosa.core.model.FormDef;
53 | import org.javarosa.core.model.FormIndex;
54 | import org.javarosa.core.model.GroupDef;
55 | import org.javarosa.core.model.SelectChoice;
56 | import org.javarosa.core.model.condition.EvaluationContext;
57 | import org.javarosa.core.model.condition.IFunctionHandler;
58 | import org.javarosa.core.model.data.IAnswerData;
59 | import org.javarosa.core.model.instance.InstanceInitializationFactory;
60 | import org.javarosa.core.model.instance.InvalidReferenceException;
61 | import org.javarosa.core.model.instance.TreeElement;
62 | import org.javarosa.core.model.utils.IPreloadHandler;
63 | import org.javarosa.core.reference.ReferenceManager;
64 | import org.javarosa.core.services.PrototypeManager;
65 | import org.javarosa.form.api.FormEntryCaption;
66 | import org.javarosa.form.api.FormEntryController;
67 | import org.javarosa.form.api.FormEntryModel;
68 | import org.javarosa.form.api.FormEntryPrompt;
69 | import org.javarosa.model.xform.XFormsModule;
70 | import org.javarosa.xform.parse.XFormParseException;
71 | import org.javarosa.xform.parse.XFormParser;
72 | import org.javarosa.xform.util.XFormUtils;
73 |
74 | import org.opendatakit.validate.buildconfig.BuildConfig;
75 |
76 | /**
77 | * Uses the javarosa-core library to process a form and show errors, if any.
78 | *
79 | * @author Adam Lerer (adam.lerer@gmail.com)
80 | * @author Yaw Anokwa (yanokwa@gmail.com)
81 | */
82 | public class FormValidator implements ActionListener {
83 | /**
84 | * Classes needed to serialize objects. Need to put anything from JR in here.
85 | */
86 | public final static String[] SERIALIABLE_CLASSES = {
87 | "org.javarosa.core.services.locale.ResourceFileDataSource", // JavaRosaCoreModule
88 | "org.javarosa.core.services.locale.TableLocaleSource", // JavaRosaCoreModule
89 | "org.javarosa.core.model.FormDef",
90 | "org.javarosa.core.model.SubmissionProfile", // CoreModelModule
91 | "org.javarosa.core.model.QuestionDef", // CoreModelModule
92 | "org.javarosa.core.model.GroupDef", // CoreModelModule
93 | "org.javarosa.core.model.instance.FormInstance", // CoreModelModule
94 | "org.javarosa.core.model.data.BooleanData", // CoreModelModule
95 | "org.javarosa.core.model.data.DateData", // CoreModelModule
96 | "org.javarosa.core.model.data.DateTimeData", // CoreModelModule
97 | "org.javarosa.core.model.data.DecimalData", // CoreModelModule
98 | "org.javarosa.core.model.data.GeoPointData", // CoreModelModule
99 | "org.javarosa.core.model.data.GeoShapeData", // CoreModelModule
100 | "org.javarosa.core.model.data.GeoTraceData", // CoreModelModule
101 | "org.javarosa.core.model.data.IntegerData", // CoreModelModule
102 | "org.javarosa.core.model.data.LongData", // CoreModelModule
103 | "org.javarosa.core.model.data.MultiPointerAnswerData", // CoreModelModule
104 | "org.javarosa.core.model.data.PointerAnswerData", // CoreModelModule
105 | "org.javarosa.core.model.data.SelectMultiData", // CoreModelModule
106 | "org.javarosa.core.model.data.SelectOneData", // CoreModelModule
107 | "org.javarosa.core.model.data.StringData", // CoreModelModule
108 | "org.javarosa.core.model.data.TimeData", // CoreModelModule
109 | "org.javarosa.core.model.data.UncastData", // CoreModelModule
110 | "org.javarosa.core.model.data.helper.BasicDataPointer", // CoreModelModule
111 | "org.javarosa.core.model.actions.SetValueAction" //CoreModelModule
112 | };
113 |
114 | private JFrame validatorFrame;
115 | private JTextField formPath;
116 | private JTextArea validatorOutput;
117 | private JButton chooseFileButton;
118 | private JButton validateButton;
119 | private JFileChooser fileChooser;
120 |
121 | private ErrorListener errors = ErrorListener.DEFAULT_ERROR_LISTENER;
122 | private boolean inError = false;
123 |
124 |
125 | public static void main(String[] args) {
126 | try {
127 | UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
128 | if (args.length == 0) {
129 | new FormValidator().show();
130 | } else {
131 | List paths = new ArrayList<>();
132 | boolean failFast = false;
133 | for (String arg : args) {
134 | if (arg.equals("--failFast") || arg.equals("--fail-fast")) {
135 | failFast = true;
136 | } else {
137 | paths.add(arg);
138 | }
139 | }
140 |
141 | new FormValidator().validateAndExitWithErrorCode(
142 | paths, failFast);
143 | }
144 | }
145 | catch (UnsupportedLookAndFeelException e) {
146 | e.printStackTrace();
147 | }
148 | catch (ClassNotFoundException e) {
149 | e.printStackTrace();
150 | }
151 | catch (InstantiationException e) {
152 | e.printStackTrace();
153 | }
154 | catch (IllegalAccessException e) {
155 | e.printStackTrace();
156 | }
157 |
158 | }
159 |
160 |
161 | private void setError(boolean outcome) {
162 | inError = outcome;
163 | }
164 |
165 | public FormValidator() {}
166 |
167 | private FormValidator show() {
168 | validatorFrame = new JFrame(BuildConfig.NAME + " " + BuildConfig.VERSION);
169 | JPanel validatorPanel = new JPanel();
170 | validatorFrame.setResizable(false);
171 |
172 | // Add the widgets.
173 | addWidgets(validatorPanel);
174 |
175 | // redirect out/errors to the GUI
176 | System.setOut(new PrintStream(new JTextAreaOutputStream(validatorOutput)));
177 | System.setErr(new PrintStream(new JTextAreaOutputStream(validatorOutput)));
178 |
179 | // Add the panel to the frame.
180 | validatorFrame.getContentPane().add(validatorPanel, BorderLayout.CENTER);
181 |
182 | // Exit when the window is closed.
183 | validatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
184 |
185 | // Show the converter.
186 | validatorFrame.pack();
187 | validatorFrame.setVisible(true);
188 | return this;
189 | }
190 |
191 | /**
192 | * An OutputStream that writes the output to a text area.
193 | *
194 | * @author alerer@google.com (Adam Lerer)
195 | */
196 | class JTextAreaOutputStream extends OutputStream {
197 | private final JTextArea textArea;
198 |
199 |
200 | public JTextAreaOutputStream(JTextArea textArea) {
201 | this.textArea = textArea;
202 | }
203 |
204 |
205 | @Override
206 | public void write(int b) {
207 | textArea.append(new String(new byte[] {
208 | (byte) (b % 256)
209 | }, 0, 1));
210 | }
211 | }
212 |
213 |
214 | private void addWidgets(JPanel panel) {
215 | panel.setLayout(new GridBagLayout());
216 | GridBagConstraints c = new GridBagConstraints();
217 |
218 | // Create widgets.
219 | formPath = new JTextField(40);
220 |
221 | fileChooser = new JFileChooser();
222 | chooseFileButton = new JButton("Choose File...");
223 | chooseFileButton.addActionListener(this);
224 |
225 | validatorOutput = new JTextArea();
226 | validatorOutput.setEditable(false);
227 | validatorOutput.setLineWrap(true);
228 | validatorOutput.setFont(new Font("Monospaced", Font.PLAIN, 14));
229 | validatorOutput.setForeground(Color.BLACK);
230 |
231 | JScrollPane validatorOutputScrollPane = new JScrollPane(validatorOutput);
232 | validatorOutputScrollPane.setPreferredSize(new Dimension(800, 600));
233 |
234 | validateButton = new JButton("Validate Again");
235 | validateButton.addActionListener(this);
236 |
237 | c.fill = GridBagConstraints.HORIZONTAL;
238 | c.gridx = 0;
239 | c.gridy = 1;
240 | c.insets = new Insets(0, 7, 0, 0);
241 | panel.add(formPath, c);
242 |
243 | c.gridx = 2;
244 | c.gridy = 1;
245 | c.insets = new Insets(10, 0, 10, 7);
246 | panel.add(chooseFileButton, c);
247 |
248 | c.gridx = 0;
249 | c.gridy = 2;
250 | c.gridwidth = 3;
251 | c.insets = new Insets(0, 10, 10, 10);
252 | panel.add(validatorOutputScrollPane, c);
253 |
254 | c.gridx = 0;
255 | c.gridy = 3;
256 | c.gridwidth = 3;
257 | panel.add(validateButton, c);
258 |
259 | }
260 |
261 |
262 | // @Override
263 | public void actionPerformed(ActionEvent e) {
264 |
265 | if (e.getSource() == validateButton) {
266 | setError(false);
267 | validatorOutput.setText("");
268 | validatorOutput.setForeground(Color.BLUE);
269 | validate(formPath.getText());
270 | validatorOutput.setForeground(inError ? Color.red : Color.BLUE);
271 | }
272 |
273 | if (e.getSource() == chooseFileButton) {
274 | int returnVal = fileChooser.showOpenDialog(validatorFrame);
275 |
276 | if (returnVal == JFileChooser.APPROVE_OPTION) {
277 | File file = fileChooser.getSelectedFile();
278 | formPath.setText(file.getPath());
279 | }
280 | setError(false);
281 | validatorOutput.setText("");
282 | validatorOutput.setForeground(Color.BLUE);
283 | validate(formPath.getText());
284 | validatorOutput.setForeground(inError ? Color.red : Color.BLUE);
285 | }
286 | }
287 |
288 | boolean stepThroughEntireForm(FormEntryModel model) throws InvalidReferenceException {
289 | boolean outcome = false;
290 | Set loops = new HashSet();
291 | // step through every value in the form
292 | FormIndex idx = FormIndex.createBeginningOfFormIndex();
293 | int event;
294 | for (;;) {
295 | idx = model.incrementIndex(idx);
296 | event = model.getEvent(idx);
297 | if ( event == FormEntryController.EVENT_END_OF_FORM ) break;
298 |
299 | if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
300 | String elementPath = idx.getReference().toString().replaceAll("\\[\\d+\\]", "");
301 | if ( !loops.contains(elementPath) ) {
302 | loops.add(elementPath);
303 | model.getForm().createNewRepeat(idx);
304 | idx = model.getFormIndex();
305 | }
306 | } else if (event == FormEntryController.EVENT_GROUP) {
307 | GroupDef gd = (GroupDef) model.getForm().getChild(idx);
308 | if ( gd.getChildren() == null || gd.getChildren().size() == 0 ) {
309 | outcome = true;
310 | setError(true);
311 | String elementPath = idx.getReference().toString().replaceAll("\\[\\d+\\]", "");
312 | errors.error("Group has no children! Group: " + elementPath + ". The XML is invalid.\n");
313 | }
314 | } else if (event != FormEntryController.EVENT_QUESTION) {
315 | continue;
316 | } else {
317 | FormEntryPrompt prompt = model.getQuestionPrompt(idx);
318 | if ( prompt.getControlType() == Constants.CONTROL_SELECT_MULTI ||
319 | prompt.getControlType() == Constants.CONTROL_SELECT_ONE ) {
320 | String elementPath = idx.getReference().toString().replaceAll("\\[\\d+\\]", "");
321 | List items;
322 | items = prompt.getSelectChoices();
323 | // check for null values...
324 | for ( int i = 0 ; i < items.size() ; ++i ) {
325 | SelectChoice s = items.get(i);
326 | String text = prompt.getSelectChoiceText(s);
327 | String image = prompt.getSpecialFormSelectChoiceText(s,
328 | FormEntryCaption.TEXT_FORM_IMAGE);
329 | if ((text == null || text.trim().length() == 0 ) &&
330 | (image == null || image.trim().length() == 0)) {
331 | errors.error("Selection choice label text and image uri are both missing for: " + elementPath + " choice: " + (i+1) + ".\n");
332 | }
333 | if ( s.getValue() == null || s.getValue().trim().length() == 0) {
334 | outcome = true;
335 | setError(true);
336 | errors.error("Selection value is missing for: " + elementPath + " choice: " + (i+1) + ". The XML is invalid.\n");
337 | }
338 | }
339 | }
340 | }
341 | }
342 | return outcome;
343 | }
344 |
345 | public void validateAndExitWithErrorCode(List paths, boolean failFast) {
346 | List failed = new ArrayList<>();
347 | for (String path : paths) {
348 | try {
349 | validate(path);
350 | } catch (Exception e) {
351 | errors.error("\nException: ", e);
352 | setError(true);
353 | }
354 |
355 | if (inError) {
356 | if (failFast) {
357 | break;
358 | } else {
359 | failed.add(path);
360 | setError(false);
361 | }
362 | }
363 | }
364 |
365 | if (inError || !failed.isEmpty()) {
366 | if (!failed.isEmpty()) {
367 | errors.error("\nThe following files failed validation:");
368 | for (String path : failed) {
369 | errors.error(path);
370 | }
371 | }
372 |
373 | errors.error("\nResult: Invalid");
374 | System.exit(1);
375 | } else {
376 | System.exit(0);
377 | }
378 | }
379 |
380 | public void validate(String path) {
381 | File src = new File(path);
382 | if (!src.exists()) {
383 | setError(true);
384 | errors.error("File: " + src.getAbsolutePath() + " does not exist.");
385 | return;
386 | }
387 |
388 | FileInputStream fis = null;
389 | try {
390 | fis = new FileInputStream(src);
391 | errors.info("Validating: " + path);
392 | validate(fis);
393 | } catch (FileNotFoundException e) {
394 | setError(true);
395 | errors.error("Please choose a file before attempting to validate.");
396 | return;
397 | } finally {
398 | if (fis != null) {
399 | try {
400 | fis.close();
401 | } catch (IOException e) {
402 | // ignore
403 | e.printStackTrace();
404 | }
405 | }
406 | }
407 |
408 | }
409 |
410 | public void validateText(String xml) {
411 | validate(xml.getBytes());
412 | }
413 |
414 | public void validate(InputStream xmlSource) {
415 | byte[] xformData;
416 | try {
417 | // first read the whole form into memory since this stream is going to be read twice
418 | // first for xml validation
419 | // second for xform validation
420 | validate(copyToByteArray(xmlSource));
421 | } catch (IOException e) {
422 | errors.error("Failed to read XML Input Stream", e);
423 | }
424 | }
425 |
426 | public void validate(byte[] xformData) {
427 | // validate well formed xml
428 | // errors.info("Checking form...");
429 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
430 | factory.setNamespaceAware(true);
431 | try {
432 | factory.newDocumentBuilder().parse(new ByteArrayInputStream(xformData));
433 | } catch (Exception e) {
434 | setError(true);
435 | errors.error("\n\n\n>> XML is invalid.",e);
436 | return;
437 | }
438 |
439 | // need a list of classes that formdef uses
440 | // unfortunately, the JR registerModule() functions do more than this.
441 | // register just the classes that would have been registered by:
442 | // new JavaRosaCoreModule().registerModule();
443 | // new CoreModelModule().registerModule();
444 | // replace with direct call to PrototypeManager
445 | PrototypeManager.registerPrototypes(SERIALIABLE_CLASSES);
446 | // initialize XForms module
447 | new XFormsModule().registerModule();
448 |
449 | // needed to override rms property manager
450 | org.javarosa.core.services.PropertyManager
451 | .setPropertyManager(new StubPropertyManager());
452 |
453 | // For forms with external secondary instances
454 | final ReferenceManager referenceManager = ReferenceManager.instance();
455 | referenceManager.addReferenceFactory(new StubReferenceFactory());
456 |
457 | PrototypeManager.registerPrototype("org.opendatakit.validate.StubSetGeopointAction");
458 | XFormParser.registerActionHandler(StubSetGeopointActionHandler.ELEMENT_NAME, new StubSetGeopointActionHandler());
459 |
460 | // validate if the xform can be parsed.
461 | try {
462 | FormDef fd = XFormUtils.getFormFromInputStream(new ByteArrayInputStream(xformData));
463 | if (fd == null) {
464 | setError(true);
465 | errors.error("\n\n\n>> Something broke the parser. Try again.");
466 | return;
467 | }
468 |
469 | // make sure properties get loaded
470 | fd.getPreloader().addPreloadHandler(new FakePreloadHandler("property"));
471 |
472 | // update evaluation context for function handlers
473 | fd.getEvaluationContext().addFunctionHandler(new IFunctionHandler() {
474 |
475 | public String getName() {
476 | return "pulldata";
477 | }
478 |
479 | public List getPrototypes() {
480 | return new ArrayList();
481 | }
482 |
483 | public boolean rawArgs() {
484 | return true;
485 | }
486 |
487 | public boolean realTime() {
488 | return false;
489 | }
490 |
491 | public Object eval(Object[] args, EvaluationContext ec) {
492 | // no actual implementation here -- just a stub to facilitate validation
493 | return args[0];
494 | }});
495 |
496 | // check for runtime errors
497 | fd.initialize(true, new InstanceInitializationFactory());
498 |
499 | errors.info("\n\n>> Xform parsing completed!\n");
500 |
501 | // create FormEntryController from formdef
502 | FormEntryModel fem = new FormEntryModel(fd);
503 |
504 | // and try to step through the form...
505 | if ( stepThroughEntireForm(fem) ) {
506 | setError(true);
507 | errors.error("\n\n>> Xform is invalid!");
508 | } else {
509 | errors.info("\n\n>> Xform is valid!");
510 | }
511 |
512 | } catch (XFormParseException e) {
513 | setError(true);
514 | errors.error("\n\n>> XForm is invalid.",e);
515 |
516 | } catch (Exception e) {
517 | setError(true);
518 | errors.error("\n\n>> Something broke the parser.",e);
519 |
520 | }
521 |
522 | }
523 |
524 | private byte[] copyToByteArray(InputStream input) throws IOException {
525 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
526 | byte[] buffer = new byte[1024];
527 | int len;
528 | while ((len = input.read(buffer)) > -1) {
529 | baos.write(buffer, 0, len);
530 | }
531 | baos.flush();
532 |
533 | return baos.toByteArray();
534 | }
535 |
536 | public FormValidator setErrorListener(ErrorListener listener){
537 | if(listener == null){
538 | throw new NullPointerException("Cannot set a null error listener");
539 | }
540 | this.errors = listener;
541 | return this;
542 | }
543 |
544 | private class FakePreloadHandler implements IPreloadHandler {
545 |
546 | String preloadHandled;
547 |
548 |
549 | public FakePreloadHandler(String preloadHandled) {
550 | this.preloadHandled = preloadHandled;
551 | }
552 |
553 |
554 | public boolean handlePostProcess(TreeElement arg0, String arg1) {
555 | // TODO Auto-generated method stub
556 | return false;
557 | }
558 |
559 |
560 | public IAnswerData handlePreload(String arg0) {
561 | // TODO Auto-generated method stub
562 | return null;
563 | }
564 |
565 |
566 | public String preloadHandled() {
567 | // TODO Auto-generated method stub
568 | return preloadHandled;
569 | }
570 |
571 | }
572 |
573 | }
574 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/StubPropertyManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 University of Washington
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | package org.opendatakit.validate;
16 |
17 | import java.util.HashSet;
18 | import java.util.List;
19 |
20 | import org.javarosa.core.services.IPropertyManager;
21 | import org.javarosa.core.services.properties.IPropertyRules;
22 |
23 | /**
24 | * Stub for validation purposes.
25 | *
26 | * @author mitchellsundt@gmail.com
27 | */
28 |
29 | public class StubPropertyManager implements IPropertyManager {
30 |
31 |
32 | public final static String DEVICE_ID_PROPERTY = "deviceid"; // imei
33 | private final static String SUBSCRIBER_ID_PROPERTY = "subscriberid"; // imsi
34 | private final static String SIM_SERIAL_PROPERTY = "simserial";
35 | private final static String PHONE_NUMBER_PROPERTY = "phonenumber";
36 | private final static String USERNAME = "username";
37 | private final static String EMAIL = "email";
38 |
39 | public final static String OR_DEVICE_ID_PROPERTY = "uri:deviceid"; // imei
40 | public final static String OR_SUBSCRIBER_ID_PROPERTY = "uri:subscriberid"; // imsi
41 | public final static String OR_SIM_SERIAL_PROPERTY = "uri:simserial";
42 | public final static String OR_PHONE_NUMBER_PROPERTY = "uri:phonenumber";
43 | public final static String OR_USERNAME = "uri:username";
44 | public final static String OR_EMAIL = "uri:email";
45 |
46 | private static HashSet mProperties;
47 |
48 | static {
49 | mProperties = new HashSet();
50 | mProperties.add(DEVICE_ID_PROPERTY);
51 | mProperties.add(SUBSCRIBER_ID_PROPERTY);
52 | mProperties.add(SIM_SERIAL_PROPERTY);
53 | mProperties.add(PHONE_NUMBER_PROPERTY);
54 | mProperties.add(USERNAME);
55 | mProperties.add(EMAIL);
56 | mProperties.add(OR_DEVICE_ID_PROPERTY);
57 | mProperties.add(OR_SUBSCRIBER_ID_PROPERTY);
58 | mProperties.add(OR_SIM_SERIAL_PROPERTY);
59 | mProperties.add(OR_PHONE_NUMBER_PROPERTY);
60 | mProperties.add(OR_USERNAME);
61 | mProperties.add(OR_EMAIL);
62 | }
63 |
64 | public String getName() {
65 | return "Property Manager";
66 | }
67 |
68 |
69 | public StubPropertyManager() {
70 | }
71 |
72 |
73 | public void addRules(IPropertyRules rules) {
74 | }
75 |
76 |
77 | public List getRules() {
78 | return null;
79 | }
80 |
81 | public List getProperty(String arg0) {
82 | return null;
83 | }
84 |
85 | public String getSingularProperty(String propertyName) {
86 | if ( mProperties.contains(propertyName)) {
87 | return "found";
88 | }
89 | if ( propertyName != null && propertyName.length() != 0 ) {
90 | throw new IllegalArgumentException("Unrecognized property name: " + propertyName);
91 | }
92 | return "notfound";
93 | }
94 |
95 |
96 | public void setProperty(String propertyName, String propertyValue) {
97 | }
98 |
99 |
100 | public void setProperty(String propertyName, List propertyValue) {
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/StubReference.java:
--------------------------------------------------------------------------------
1 | package org.opendatakit.validate;
2 |
3 | import org.javarosa.core.reference.Reference;
4 |
5 | import java.io.InputStream;
6 | import java.io.OutputStream;
7 |
8 | public class StubReference implements Reference {
9 |
10 | @Override
11 | public boolean doesBinaryExist() {
12 | return true;
13 | }
14 |
15 | @Override
16 | public InputStream getStream() {
17 | return null;
18 | }
19 |
20 | @Override
21 | public String getURI() {
22 | return null;
23 | }
24 |
25 | @Override
26 | public String getLocalURI() {
27 | return "Can't be found";
28 | }
29 |
30 | @Override
31 | public boolean isReadOnly() {
32 | return false;
33 | }
34 |
35 | @Override
36 | public OutputStream getOutputStream() {
37 | return null;
38 | }
39 |
40 | @Override
41 | public void remove() {
42 | }
43 |
44 | @Override
45 | public Reference[] probeAlternativeReferences() {
46 | return new Reference[0];
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/StubReferenceFactory.java:
--------------------------------------------------------------------------------
1 | package org.opendatakit.validate;
2 |
3 | import org.javarosa.core.reference.Reference;
4 | import org.javarosa.core.reference.ReferenceFactory;
5 |
6 | /**
7 | * Always provides a reference to the same simple XML or CSV document. This allows forms with external secondary instances to
8 | * pass validation.
9 | */
10 | public class StubReferenceFactory implements ReferenceFactory {
11 |
12 | @Override
13 | public boolean derives(String URI) {
14 | return true;
15 | }
16 |
17 | @Override
18 | public Reference derive(String URI) {
19 | return new StubReference();
20 | }
21 |
22 | @Override
23 | public Reference derive(String URI, String context) {
24 | return new StubReference();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/StubSetGeopointAction.java:
--------------------------------------------------------------------------------
1 | package org.opendatakit.validate;
2 |
3 | import org.javarosa.core.model.actions.setgeopoint.SetGeopointAction;
4 | import org.javarosa.core.model.instance.TreeReference;
5 |
6 | /**
7 | * An odk:setgeopoint implementation that does nothing when triggered.
8 | */
9 | public final class StubSetGeopointAction extends SetGeopointAction {
10 | public StubSetGeopointAction() {
11 | // empty body for serialization
12 | }
13 |
14 | StubSetGeopointAction(TreeReference targetReference) {
15 | super(targetReference);
16 | }
17 |
18 | @Override
19 | public void requestLocationUpdates() {
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/org/opendatakit/validate/StubSetGeopointActionHandler.java:
--------------------------------------------------------------------------------
1 | package org.opendatakit.validate;
2 |
3 | import org.javarosa.core.model.actions.setgeopoint.SetGeopointAction;
4 | import org.javarosa.core.model.actions.setgeopoint.SetGeopointActionHandler;
5 |
6 | /**
7 | * Set an implementation that does nothing.
8 | */
9 | public final class StubSetGeopointActionHandler extends SetGeopointActionHandler {
10 | @Override
11 | public SetGeopointAction getSetGeopointAction() {
12 | // We'd like to use the default constructor but then the name field defined in Action wouldn't be set.
13 | // This is because the default constructor has to have an empty body for serialization. Instead, we've
14 | // defined a constructor in StubSetGeopointAction that takes in a TreeReference (and sets the name field).
15 | // We can pass in null since we don't know the target node at this point and SetGeopointActionHandler's
16 | // handle() method will set the target.
17 | return new StubSetGeopointAction(null);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/org/opendatakit/validate/ValidateExternalSecondaryInstancesTest.java:
--------------------------------------------------------------------------------
1 | package org.opendatakit.validate;
2 |
3 | import static org.hamcrest.MatcherAssert.assertThat;
4 | import static org.hamcrest.Matchers.containsString;
5 | import static org.hamcrest.Matchers.isEmptyString;
6 |
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.PrintStream;
9 | import java.net.URISyntaxException;
10 | import java.nio.file.Path;
11 | import java.nio.file.Paths;
12 | import org.junit.Test;
13 |
14 | public class ValidateExternalSecondaryInstancesTest {
15 | @Test
16 | public void supportsXlsformsDefaultValueAndLabelRefs_inItemsets_usingXMLExternalSecondaryInstance() throws URISyntaxException {
17 | final Path path = getPathOf("xml_external_instance.xml");
18 | final FormValidator validator = new FormValidator();
19 |
20 | Output output = Output.runAndGet(() -> validator.validate(path.toString()));
21 | assertThat(output.err, isEmptyString());
22 | assertThat(output.std, containsString("Xform is valid"));
23 | }
24 |
25 | @Test
26 | public void supportsXlsformsDefaultValueAndLabelRefs_inItemsets_usingCsvSecondaryExternalInstance() throws URISyntaxException {
27 | final Path path = getPathOf("csv_external_instance.xml");
28 | final FormValidator validator = new FormValidator();
29 |
30 | Output output = Output.runAndGet(() -> validator.validate(path.toString()));
31 | assertThat(output.err, isEmptyString());
32 | assertThat(output.std, containsString("Xform is valid"));
33 | }
34 |
35 | @Test
36 | public void supportsCustomValueAndLabelRefs_inItemsets_usingExternalSecondaryInstance() throws URISyntaxException {
37 | final Path path = getPathOf("external_instance_custom_refs.xml");
38 | final FormValidator validator = new FormValidator();
39 |
40 | Output output = Output.runAndGet(() -> validator.validate(path.toString()));
41 | assertThat(output.err, isEmptyString());
42 | assertThat(output.std, containsString("Xform is valid"));
43 | }
44 |
45 | private Path getPathOf(String filename) throws URISyntaxException {
46 | return Paths.get(ValidateExternalSecondaryInstancesTest.class.getResource(filename.startsWith("/") ? filename : "/" + filename).toURI());
47 | }
48 |
49 | static class Output {
50 | private final String std;
51 | private final String err;
52 |
53 | Output(String std, String err) {
54 | this.std = std;
55 | this.err = err;
56 | }
57 |
58 | static Output runAndGet(Runnable runnable) {
59 | PrintStream outBackup = System.out;
60 | ByteArrayOutputStream stdBaos = new ByteArrayOutputStream();
61 | PrintStream stdPs = new PrintStream(stdBaos);
62 | System.setOut(stdPs);
63 |
64 | PrintStream errBackup = System.err;
65 | ByteArrayOutputStream errBaos = new ByteArrayOutputStream();
66 | PrintStream errPs = new PrintStream(errBaos);
67 | System.setErr(errPs);
68 |
69 | runnable.run();
70 |
71 | stdPs.flush();
72 | String std = stdBaos.toString();
73 | System.setOut(outBackup);
74 | System.out.print(std);
75 |
76 | errPs.flush();
77 | String err = errBaos.toString();
78 | System.setErr(errBackup);
79 | System.err.print(err);
80 |
81 | return new Output(std, err);
82 | }
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/src/test/resources/csv_external_instance.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | External Secondary Instance with xlsforms generated itemset value/label refs
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/test/resources/external_instance_custom_refs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | External Secondary Instance with xlsforms generated itemset value/label refs
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/test/resources/xml_external_instance.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | External Secondary Instance with xlsforms generated itemset value/label refs
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------