├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── benchmark ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── twitter-atom.xml │ ├── java │ └── me │ │ └── tatarka │ │ └── parsnip │ │ └── benchmark │ │ ├── Api.java │ │ ├── MainActivity.java │ │ ├── PerformanceTestRunner.java │ │ ├── ReadingThread.java │ │ ├── Statistics.java │ │ ├── StatisticsTask.java │ │ ├── TestService.java │ │ ├── TweetsReader.java │ │ ├── model │ │ ├── Author.java │ │ ├── Content.java │ │ ├── Tweet.java │ │ └── Tweets.java │ │ └── parsers │ │ ├── DOMTweetsReader.java │ │ ├── ParsnipTweetsReader.java │ │ ├── PullParserTweetsReader.java │ │ ├── SAXTweetsReader.java │ │ └── SimpleXmlReader.java │ └── res │ ├── layout │ └── activity_main.xml │ └── values │ └── themes.xml ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── parsnip-retrofit-converter ├── .gitignore ├── build.gradle ├── publish.gradle └── src │ └── main │ └── java │ └── me │ └── tatarka │ └── parsnip │ ├── ParsnipConverterFactory.java │ ├── ParsnipRequestBodyConverter.java │ └── ParsnipResponseBodyConverter.java ├── parsnip ├── build.gradle ├── publish.gradle └── src │ ├── main │ └── java │ │ └── me │ │ └── tatarka │ │ └── parsnip │ │ ├── AdapterMethodsFactory.java │ │ ├── ClassFactory.java │ │ ├── ClassXmlAdapter.java │ │ ├── StandardTypeConverters.java │ │ ├── TagInfo.java │ │ ├── TagXmlAdapter.java │ │ ├── TypeConverter.java │ │ ├── Types.java │ │ ├── Util.java │ │ ├── Xml.java │ │ ├── XmlAdapter.java │ │ ├── XmlAdapters.java │ │ ├── XmlDataException.java │ │ └── annotations │ │ ├── FromXml.java │ │ ├── Namespace.java │ │ ├── SerializedName.java │ │ ├── Tag.java │ │ ├── Text.java │ │ ├── ToXml.java │ │ └── XmlQualifier.java │ └── test │ ├── kotlin │ └── me │ │ └── tatarka │ │ └── parsnip │ │ ├── ObjectDeserializerSpecs.kt │ │ ├── ObjectSerializerSpecs.kt │ │ ├── classes │ │ ├── CollectionObject.kt │ │ ├── EmptyObject.kt │ │ ├── EnumObject.kt │ │ ├── NamedEnumObject.kt │ │ ├── NamespaceObject.kt │ │ ├── NestedObject.kt │ │ ├── PrimitiveObject.kt │ │ ├── SameNameObject.kt │ │ ├── StringObject.kt │ │ ├── TagObject.kt │ │ └── TextObject.kt │ │ └── samples │ │ └── Rss.kt │ └── resources │ └── samples │ └── rss │ └── wehaveconcerns.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | build/ 3 | local.properties 4 | .gradle/ 5 | .idea/ 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | ### 0.1 3 | - Initial Release -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/me.tatarka.parsnip/parsnip/badge.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/me.tatarka.parsnip/parsnip) 2 | 3 | # parsnip 4 | A modern XML library for Android and Java 5 | 6 | ## Why parsnip? 7 | - Simple modern api similar to [gson](https://github.com/google/gson) and [moshi](https://github.com/square/moshi). 8 | - Based on kxml which is fast and memory efficient on Android. 9 | - More performant than SimpleXML while requiring less annotations in the common case. 10 | 11 | ## Usage 12 | 13 | ### Download 14 | 15 | ```groovy 16 | compile 'me.tatarka.parsnip:parsnip:0.3' 17 | ``` 18 | 19 | ```xml 20 | 21 | me.tatarka.parsnip 22 | parsnip 23 | 0.2 24 | 25 | ``` 26 | 27 | There is also a retrofit converter 28 | ```groovy 29 | compile 'me.tatarka.parsnip:parsnip-retrofit-converter:0.3' 30 | ``` 31 | 32 | ```xml 33 | 34 | me.tatarka.parsnip 35 | parsnip-retrofit-converter 36 | 0.2 37 | 38 | ``` 39 | 40 | ### Parsing into objects 41 | ```java 42 | String xml = ...; 43 | 44 | Xml xml = new Xml.Builder().build(); 45 | XmlAdapter xmlAdapter = xml.adapter(BlackjackHand.class); 46 | 47 | BlackjackHand blackjackHand = xmlAdapter.fromXml(xml); 48 | ``` 49 | 50 | ### Serialize objects into xml 51 | ```java 52 | BlackjackHand blackjackHand = new BlackjackHand( 53 | new Card('6', SPADES), 54 | Arrays.asList(new Card('4', CLUBS), new Card('A', HEARTS))); 55 | 56 | Xml xml = new Xml.Builder().build(); 57 | XmlAdapter xmlAdapter = xml.adapter(BlackjackHand.class); 58 | 59 | String xml = xmlAdapter.toXml(blackjackHand); 60 | ``` 61 | 62 | ### Built in xml adapters 63 | Parsnip has built-in support for reading and writing 64 | - primitive types 65 | - arrays, collections and lists 66 | - Strings 67 | - enums 68 | 69 | It supports classes by writing them out field-by-field. Primitives will be written out as attributes by default, classes will be written out as tags. 70 | 71 | If you have these classes: 72 | ```java 73 | class BlackjackHand { 74 | public final Card hiddenCard; 75 | public final List visibleCard; 76 | ... 77 | } 78 | 79 | class Card { 80 | public final char rank; 81 | public final Suit suit; 82 | ... 83 | } 84 | 85 | enum Suit { 86 | CLUBS, DIAMONDS, HEARTS, SPADES; 87 | } 88 | ``` 89 | 90 | Parsnip will read and write this xml: 91 | ```xml 92 | 93 | 94 | 95 | 96 | 97 | ``` 98 | 99 | ### Custom naming 100 | You can customize the names of tags and attributes with `@SerializedName()`. The above example will look a little better as such: 101 | ```java 102 | class BlackjackHand { 103 | @SerializedName("HiddenCard") 104 | public final Card hiddenCard; 105 | @SerializedName("VisibleCard") 106 | public final List visibleCards; 107 | ... 108 | } 109 | 110 | class Card { 111 | public final char rank; 112 | public final Suit suit; 113 | ... 114 | } 115 | 116 | enum Suit { 117 | CLUBS, DIAMONDS, HEARTS, SPADES; 118 | } 119 | ``` 120 | 121 | ```xml 122 | 123 | 124 | 125 | 126 | 127 | ``` 128 | 129 | ### Text 130 | You can use the `@Text` annotation to read/write the text of a tag. 131 | ```java 132 | class Card { 133 | @Text 134 | public final char rank; 135 | public final Suit suit; 136 | } 137 | ``` 138 | ```xml 139 | 6 140 | ``` 141 | 142 | ### Tag 143 | Often times you only care about the contents of a tag, not any of it's attributes. You can save some nesting in your hiarchy with the `@Tag` annotation. 144 | ```java 145 | class Card { 146 | @Tag 147 | public final char rank; 148 | @Tag 149 | public final Suit suit; 150 | } 151 | ``` 152 | ```xml 153 | 154 | 6 155 | SPADES 156 | 157 | ``` 158 | 159 | ### Namespace 160 | By default, any namespace on an element will be ignored. If you want to enforce a namespace, you can use the `@Namespace` annotation. 161 | 162 | ```java 163 | class Card { 164 | @Namespace("http://example.com", alias="ns") 165 | public final char rank; 166 | } 167 | ``` 168 | will read 169 | ```xml 170 | 171 | ``` 172 | as `6`. 173 | 174 | When writing xml, the given alias will be used. 175 | 176 | ## License 177 | 178 | Copyright 2015 Evan Tatarka 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /benchmark/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | dependencies { 22 | classpath 'com.android.tools.build:gradle:2.3.3' 23 | } 24 | } 25 | 26 | apply plugin: 'com.android.application' 27 | 28 | sourceCompatibility = 1.7 29 | 30 | android { 31 | compileSdkVersion 25 32 | buildToolsVersion "25.0.3" 33 | 34 | defaultConfig { 35 | minSdkVersion 15 36 | targetSdkVersion 25 37 | } 38 | } 39 | 40 | repositories { 41 | mavenCentral() 42 | } 43 | configurations { 44 | // These are packaged in android 45 | all*.exclude module: 'stax' 46 | all*.exclude module: 'stax-api' 47 | all*.exclude module: 'xpp3' 48 | } 49 | 50 | dependencies { 51 | compile project(':parsnip') 52 | compile project(':parsnip-retrofit-converter') 53 | compile 'com.android.support:appcompat-v7:25.3.1' 54 | compile 'org.quanqi:android-holo-graph:0.1.0' 55 | compile 'org.simpleframework:simple-xml:2.7.1' 56 | compile 'com.squareup.retrofit2:retrofit:2.3.0' 57 | } 58 | -------------------------------------------------------------------------------- /benchmark/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/Api.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import me.tatarka.parsnip.ParsnipConverterFactory; 20 | import me.tatarka.parsnip.Xml; 21 | import retrofit2.Retrofit; 22 | 23 | public class Api { 24 | 25 | public Api() { 26 | final Xml xml = new Xml.Builder().build(); 27 | final Retrofit retrofit = new Retrofit.Builder() 28 | .addConverterFactory(ParsnipConverterFactory.create()) 29 | .build(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import android.app.Activity; 20 | import android.os.Bundle; 21 | import android.view.View; 22 | import android.widget.Button; 23 | import android.widget.ProgressBar; 24 | 25 | import com.echo.holographlibrary.Bar; 26 | import com.echo.holographlibrary.BarGraph; 27 | 28 | import java.util.ArrayList; 29 | 30 | public class MainActivity extends Activity implements StatisticsTask.StateListener { 31 | private static final String TAG = "Parsnip"; 32 | private StatisticsTask task; 33 | 34 | private BarGraph graph; 35 | private Button startBenchmarks; 36 | private ProgressBar progressBar; 37 | 38 | @Override 39 | protected void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | setContentView(R.layout.activity_main); 42 | 43 | graph = (BarGraph) findViewById(R.id.graph); 44 | startBenchmarks = (Button) findViewById(R.id.startBenchmarks); 45 | progressBar = (ProgressBar) findViewById(R.id.progress); 46 | 47 | task = (StatisticsTask) getLastNonConfigurationInstance(); 48 | if (task != null) { 49 | task.setListener(this); 50 | } 51 | startBenchmarks.setOnClickListener(new View.OnClickListener() { 52 | @Override 53 | public void onClick(View v) { 54 | task = new StatisticsTask(getAssets()); 55 | task.setListener(MainActivity.this); 56 | task.execute(); 57 | } 58 | }); 59 | } 60 | 61 | @Override 62 | public Object onRetainNonConfigurationInstance() { 63 | return task; 64 | } 65 | 66 | @Override 67 | public void onTaskStart() { 68 | progressBar.setProgress(0); 69 | startBenchmarks.setEnabled(false); 70 | } 71 | 72 | @Override 73 | public void onTaskProgress(int progress, int total) { 74 | progressBar.setMax(total); 75 | progressBar.setProgress(progress); 76 | } 77 | 78 | @Override 79 | public void onTaskResult(ArrayList bars) { 80 | progressBar.setProgress(0); 81 | startBenchmarks.setEnabled(true); 82 | graph.setBars(bars); 83 | } 84 | 85 | @Override 86 | protected void onDestroy() { 87 | super.onDestroy(); 88 | task.setListener(null); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/PerformanceTestRunner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import android.content.res.AssetManager; 20 | import android.util.Log; 21 | 22 | import java.util.ArrayList; 23 | import java.util.Collections; 24 | import java.util.List; 25 | import java.util.concurrent.CyclicBarrier; 26 | 27 | public class PerformanceTestRunner { 28 | private static final String TAG = "TestRunner"; 29 | 30 | public static List of(TweetsReaderFactory...factories) { 31 | List runners = new ArrayList<>(factories.length); 32 | for (TweetsReaderFactory factory : factories) { 33 | runners.add(new PerformanceTestRunner(factory)); 34 | } 35 | return Collections.unmodifiableList(runners); 36 | } 37 | 38 | public interface TweetsReaderFactory { 39 | String getParserType(); 40 | 41 | TweetsReader newReader() throws Exception; 42 | } 43 | 44 | private TweetsReaderFactory factory; 45 | 46 | public PerformanceTestRunner(TweetsReaderFactory aFactory) { 47 | factory = aFactory; 48 | } 49 | 50 | public Statistics collectStatistics(AssetManager assetManager, int maxConcurrency, int iterations) throws Exception { 51 | Log.d(TAG, factory.getParserType()); 52 | Statistics stats = new Statistics(factory.getParserType()); 53 | for (int i = 1; i <= maxConcurrency; i++) { 54 | long time = testPerformanceWithConcurrency(assetManager, i, iterations); 55 | stats.add(i, time, i * iterations); 56 | } 57 | return stats; 58 | } 59 | 60 | private long testPerformanceWithConcurrency(AssetManager assetManager, int concurrency, int iterations) throws Exception { 61 | CyclicBarrier gate = new CyclicBarrier(concurrency + 1); 62 | List threads = new ArrayList(); 63 | 64 | // prepare everything in advance, we only want to time 65 | // the actual parsing 66 | for (int i = 0; i < concurrency; i++) { 67 | threads.add(new Thread(new ReadingThread(assetManager, factory.newReader(), iterations, gate))); 68 | } 69 | 70 | // get the threads lined up and waiting to go 71 | for (Thread t : threads) { 72 | t.start(); 73 | } 74 | 75 | // start timing _just_ before we allow the threads to go at it 76 | long start = System.nanoTime(); 77 | gate.await(); 78 | 79 | // wait for all parsing threads to finish 80 | for (Thread t : threads) { 81 | t.join(); 82 | } 83 | long stop = System.nanoTime(); 84 | 85 | return stop - start; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/ReadingThread.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import android.content.res.AssetManager; 20 | import android.util.Log; 21 | import me.tatarka.parsnip.benchmark.model.Tweets; 22 | 23 | import java.io.InputStream; 24 | import java.util.concurrent.CyclicBarrier; 25 | 26 | public class ReadingThread implements Runnable { 27 | private static final String TAG = "ReadingThread"; 28 | 29 | private AssetManager assetManager; 30 | private CyclicBarrier gate; 31 | private TweetsReader reader; 32 | private int iterations; 33 | 34 | public ReadingThread(AssetManager assetManager, TweetsReader reader, int iterations, CyclicBarrier gate) { 35 | this.assetManager = assetManager; 36 | this.reader = reader; 37 | this.iterations = iterations; 38 | this.gate = gate; 39 | } 40 | 41 | @Override 42 | public void run() { 43 | try { 44 | gate.await(); 45 | for (int i = 0; i < iterations; i++) { 46 | InputStream in = assetManager.open("twitter-atom.xml"); 47 | Tweets tweets = reader.read(in); 48 | if (tweets == null) { 49 | throw new RuntimeException("Expected Tweets"); 50 | } 51 | } 52 | } catch (Exception e) { 53 | Log.e(TAG, e.getMessage(), e); 54 | Log.e(TAG, "Thread did not complete its batch"); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/Statistics.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import android.support.v4.util.ArrayMap; 20 | 21 | import java.util.ArrayList; 22 | import java.util.Iterator; 23 | import java.util.List; 24 | 25 | public class Statistics implements Iterable { 26 | public static Statistics[] combine(Statistics[] stats) { 27 | ArrayMap statsByParser = new ArrayMap<>(); 28 | for (Statistics s : stats) { 29 | Statistics statistics = statsByParser.get(s.getName()); 30 | if (statistics == null) { 31 | statsByParser.put(s.getName(), s); 32 | } else { 33 | statsByParser.put(s.getName(), statistics.combine(s)); 34 | } 35 | } 36 | Statistics[] resultStats = new Statistics[statsByParser.size()]; 37 | int i = 0; 38 | for (Statistics s : statsByParser.values()) { 39 | s.setIndex(i); 40 | resultStats[i++] = s; 41 | } 42 | return resultStats; 43 | } 44 | 45 | public float getAverageThroughputPerSecond() { 46 | float average = 0; 47 | for (Entry entry : this) { 48 | average += entry.getThroughputPerSecond(); 49 | } 50 | return average / size(); 51 | } 52 | 53 | public class Entry { 54 | private int threads; 55 | private double time; 56 | private double docs; 57 | 58 | public Entry(int threads, double time, double docs) { 59 | this.threads = threads; 60 | this.time = time; 61 | this.docs = docs; 62 | } 63 | 64 | public int getThreads() { 65 | return threads; 66 | } 67 | 68 | public double getElapsedNanos() { 69 | return time; 70 | } 71 | 72 | public double getDocs() { 73 | return docs; 74 | } 75 | 76 | public double getThroughputPerSecond() { 77 | return (1000000000d / time) * docs; 78 | } 79 | 80 | public String toString() { 81 | return getThroughputPerSecond() + " docs/sec with " + threads + " threads"; 82 | } 83 | } 84 | 85 | private int index; 86 | private String name; 87 | private List entries; 88 | 89 | public Statistics(String name) { 90 | this.name = name; 91 | entries = new ArrayList<>(); 92 | } 93 | 94 | public void setIndex(int index) { 95 | this.index = index; 96 | } 97 | 98 | public String getName() { 99 | return name; 100 | } 101 | 102 | public void add(int aThreadCount, double aNanos, double aDocs) { 103 | entries.add(new Entry(aThreadCount, aNanos, aDocs)); 104 | } 105 | 106 | public Entry getEntry(int anIndex) { 107 | return entries.get(anIndex); 108 | } 109 | 110 | public int size() { 111 | return entries.size(); 112 | } 113 | 114 | @Override 115 | public Iterator iterator() { 116 | return entries.iterator(); 117 | } 118 | 119 | public Statistics combine(Statistics statistics) { 120 | if (!name.equals(statistics.name)) 121 | throw new IllegalArgumentException("can't add " + statistics.name + " to " + name); 122 | if (entries.size() != statistics.size()) 123 | throw new IllegalArgumentException("mismatched stats - I have " + size() + " but other has " + statistics.size()); 124 | 125 | Statistics result = new Statistics(name); 126 | for (int i = 0; i < size(); i++) { 127 | Entry _mine = entries.get(i); 128 | Entry _other = statistics.entries.get(i); 129 | 130 | result.add(_mine.threads, _mine.time + _other.time, _mine.docs + _other.docs); 131 | } 132 | return result; 133 | } 134 | 135 | public String toString() { 136 | StringBuilder _sb = new StringBuilder(); 137 | _sb.append("statistics for ").append(name).append("\r\n"); 138 | for (Entry _e : entries) { 139 | _sb.append(_e).append("\r\n"); 140 | } 141 | return _sb.toString(); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/StatisticsTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import android.content.res.AssetManager; 20 | import android.os.AsyncTask; 21 | import android.util.Log; 22 | 23 | import com.echo.holographlibrary.Bar; 24 | 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | 28 | import me.tatarka.parsnip.benchmark.parsers.DOMTweetsReader; 29 | import me.tatarka.parsnip.benchmark.parsers.ParsnipTweetsReader; 30 | import me.tatarka.parsnip.benchmark.parsers.PullParserTweetsReader; 31 | import me.tatarka.parsnip.benchmark.parsers.SAXTweetsReader; 32 | import me.tatarka.parsnip.benchmark.parsers.SimpleXmlReader; 33 | 34 | public class StatisticsTask extends AsyncTask { 35 | private static final String TAG = "Parsnip"; 36 | 37 | static final int CONCURRENCY = 1; 38 | static final int ITERATIONS = 20; 39 | static final int WARM_UP_RUNS = 3; 40 | static final int ITERATION_RUNS = 5; 41 | 42 | private AssetManager assetManager; 43 | private ArrayList bars; 44 | private StateListener listener; 45 | private int progress; 46 | private int total; 47 | private boolean isStarted; 48 | 49 | public StatisticsTask(AssetManager assetManager) { 50 | this.assetManager = assetManager; 51 | } 52 | 53 | @Override 54 | protected void onPreExecute() { 55 | isStarted = true; 56 | if (listener != null) { 57 | listener.onTaskStart(); 58 | } 59 | } 60 | 61 | public void setListener(StateListener listener) { 62 | this.listener = listener; 63 | if (listener != null) { 64 | if (isStarted) { 65 | listener.onTaskStart(); 66 | if (progress > 0 && total > 0) { 67 | listener.onTaskProgress(progress, total); 68 | } 69 | } 70 | if (bars != null) { 71 | listener.onTaskResult(bars); 72 | } 73 | } 74 | } 75 | 76 | @Override 77 | protected Statistics[] doInBackground(Void... params) { 78 | try { 79 | return comparePerformance(CONCURRENCY, ITERATIONS); 80 | } catch (Exception e) { 81 | Log.e(TAG, e.getMessage(), e); 82 | return null; 83 | } 84 | } 85 | 86 | @Override 87 | protected void onProgressUpdate(Integer... values) { 88 | this.progress = values[0]; 89 | this.total = values[1]; 90 | if (listener != null) { 91 | listener.onTaskProgress(values[0], values[1]); 92 | } 93 | } 94 | 95 | @Override 96 | protected void onPostExecute(Statistics[] stats) { 97 | if (stats != null) { 98 | ArrayList bars = new ArrayList<>(stats.length); 99 | for (Statistics stat : stats) { 100 | Bar b = new Bar(); 101 | b.setName(stat.getName()); 102 | b.setValue(stat.getAverageThroughputPerSecond()); 103 | bars.add(b); 104 | } 105 | this.bars = bars; 106 | if (listener != null) { 107 | listener.onTaskResult(bars); 108 | } 109 | } 110 | isStarted = false; 111 | } 112 | 113 | public Statistics[] comparePerformance(int concurrency, int iterations) throws Exception { 114 | List runners = PerformanceTestRunner.of( 115 | ParsnipTweetsReader.FACTORY, 116 | SAXTweetsReader.FACTORY, 117 | PullParserTweetsReader.FACTORY, 118 | DOMTweetsReader.FACTORY, 119 | ParsnipTweetsReader.FACTORY, 120 | SimpleXmlReader.FACTORY 121 | ); 122 | 123 | int size = runners.size(); 124 | int totalCount = (WARM_UP_RUNS + ITERATION_RUNS) * size; 125 | int startCount = 0; 126 | // warm up and discard the first results 127 | performNRunsWithEachTestRunner(concurrency, iterations, runners, WARM_UP_RUNS, startCount, totalCount); 128 | startCount = WARM_UP_RUNS * size; 129 | return Statistics.combine(performNRunsWithEachTestRunner(concurrency, iterations, runners, ITERATION_RUNS, startCount, totalCount)); 130 | } 131 | 132 | private Statistics[] performNRunsWithEachTestRunner(int concurrency, int iterations, List testRunners, int numberOfRuns, int startCount, int totalCount) throws Exception { 133 | Statistics[] stats = new Statistics[numberOfRuns * testRunners.size()]; 134 | int testRunnerSize = testRunners.size(); 135 | for (int i = 0; i < numberOfRuns; i++) { 136 | Log.d(TAG, "Beginning test run " + (i + 1)); 137 | for (int j = 0; j < testRunnerSize; j++) { 138 | PerformanceTestRunner r = testRunners.get(j); 139 | stats[i * testRunnerSize + j] = r.collectStatistics(assetManager, concurrency, iterations); 140 | publishProgress(startCount + i * testRunnerSize + j, totalCount); 141 | } 142 | } 143 | return stats; 144 | } 145 | 146 | 147 | public interface StateListener { 148 | void onTaskStart(); 149 | 150 | void onTaskProgress(int progress, int total); 151 | 152 | void onTaskResult(ArrayList bars); 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/TestService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import me.tatarka.parsnip.benchmark.model.Tweets; 20 | import retrofit2.Call; 21 | import retrofit2.http.GET; 22 | 23 | public interface TestService { 24 | @GET("/tweets") 25 | Call getTweets(); 26 | } 27 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/TweetsReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark; 18 | 19 | import java.io.InputStream; 20 | 21 | import me.tatarka.parsnip.benchmark.model.Tweets; 22 | 23 | public interface TweetsReader { 24 | Tweets read(InputStream stream) throws Exception; 25 | } 26 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/model/Author.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.model; 18 | 19 | import org.simpleframework.xml.Element; 20 | import org.simpleframework.xml.Root; 21 | 22 | import me.tatarka.parsnip.annotations.Tag; 23 | 24 | @Root(strict = false) 25 | public class Author { 26 | @Tag 27 | @Element 28 | public String name; 29 | @Tag 30 | @Element 31 | public String uri; 32 | } 33 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/model/Content.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.model; 18 | 19 | import org.simpleframework.xml.Attribute; 20 | import org.simpleframework.xml.Root; 21 | 22 | import me.tatarka.parsnip.annotations.Text; 23 | 24 | @Root(strict = false) 25 | public class Content { 26 | @Attribute 27 | public String type; 28 | @Text 29 | @org.simpleframework.xml.Text 30 | public String value; 31 | } -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/model/Tweet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.model; 18 | 19 | import org.simpleframework.xml.Element; 20 | import org.simpleframework.xml.Root; 21 | 22 | import java.util.Date; 23 | 24 | import me.tatarka.parsnip.annotations.SerializedName; 25 | import me.tatarka.parsnip.annotations.Tag; 26 | 27 | @Root(strict = false) 28 | @SerializedName("entry") 29 | public class Tweet { 30 | @Tag 31 | @Element 32 | public String title; 33 | @Tag 34 | @Element 35 | public Date published; 36 | @Element 37 | public Content content; 38 | @Tag 39 | @Element 40 | public String lang; 41 | @Element 42 | public Author author; 43 | } 44 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/model/Tweets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.model; 18 | 19 | import org.simpleframework.xml.ElementList; 20 | import org.simpleframework.xml.Root; 21 | 22 | import java.util.List; 23 | 24 | import me.tatarka.parsnip.annotations.SerializedName; 25 | 26 | @Root(strict = false, name = "feed") 27 | @SerializedName("feed") 28 | public class Tweets { 29 | @ElementList(inline = true, entry = "entry") 30 | public List tweets; 31 | } -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/parsers/DOMTweetsReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.parsers; 18 | 19 | import me.tatarka.parsnip.benchmark.PerformanceTestRunner; 20 | import me.tatarka.parsnip.benchmark.TweetsReader; 21 | import me.tatarka.parsnip.benchmark.model.Author; 22 | import me.tatarka.parsnip.benchmark.model.Content; 23 | import me.tatarka.parsnip.benchmark.model.Tweet; 24 | import me.tatarka.parsnip.benchmark.model.Tweets; 25 | import org.w3c.dom.Document; 26 | import org.w3c.dom.Element; 27 | import org.w3c.dom.Node; 28 | import org.w3c.dom.NodeList; 29 | 30 | import javax.xml.parsers.DocumentBuilder; 31 | import javax.xml.parsers.DocumentBuilderFactory; 32 | import java.io.InputStream; 33 | import java.text.DateFormat; 34 | import java.text.SimpleDateFormat; 35 | import java.util.ArrayList; 36 | import java.util.Locale; 37 | 38 | public class DOMTweetsReader implements TweetsReader { 39 | 40 | public static final PerformanceTestRunner.TweetsReaderFactory FACTORY = new PerformanceTestRunner.TweetsReaderFactory() { 41 | @Override 42 | public String getParserType() { 43 | return "W3C DOM"; 44 | } 45 | 46 | @Override 47 | public TweetsReader newReader() throws Exception { 48 | return new DOMTweetsReader(); 49 | } 50 | }; 51 | 52 | private DocumentBuilder builder; 53 | private DateFormat dateFormat; 54 | 55 | public DOMTweetsReader() throws Exception { 56 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 57 | builder = factory.newDocumentBuilder(); 58 | dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); 59 | } 60 | 61 | public Tweets read(InputStream stream) throws Exception { 62 | Document document = builder.parse(stream, "utf-8"); 63 | Tweets result = new Tweets(); 64 | result.tweets = new ArrayList<>(); 65 | unmarshall(document, result); 66 | return result; 67 | } 68 | 69 | public void unmarshall(Document doc, Tweets tweets) 70 | throws Exception { 71 | NodeList nodes = doc.getChildNodes().item(0).getChildNodes(); 72 | for (int i = 0; i < nodes.getLength(); i++) { 73 | Node n = nodes.item(i); 74 | if ((n.getNodeType() == Node.ELEMENT_NODE) && ("entry".equals(n.getNodeName()))) { 75 | Tweet tweet = new Tweet(); 76 | tweets.tweets.add(tweet); 77 | unmarshallEntry((Element) n, tweet); 78 | } 79 | } 80 | } 81 | 82 | private void unmarshallEntry(Element tweetElem, Tweet tweet) 83 | throws Exception { 84 | NodeList _nodes = tweetElem.getChildNodes(); 85 | for (int i = 0; i < _nodes.getLength(); i++) { 86 | Node node = _nodes.item(i); 87 | if (node.getNodeType() == Node.ELEMENT_NODE) { 88 | if ("published".equals(node.getNodeName())) { 89 | tweet.published = dateFormat.parse(getPCData(node)); 90 | } else if ("title".equals(node.getNodeName())) { 91 | tweet.title = getPCData(node); 92 | } else if ("content".equals(node.getNodeName())) { 93 | Content content = new Content(); 94 | tweet.content = content; 95 | unmarshallContent((Element) node, content); 96 | } else if ("twitter:lang".equals(node.getNodeName())) { 97 | tweet.lang = getPCData(node); 98 | } else if ("author".equals(node.getNodeName())) { 99 | Author author = new Author(); 100 | tweet.author = author; 101 | unmarshallAuthor((Element) node, author); 102 | } 103 | } 104 | } 105 | } 106 | 107 | private void unmarshallContent(Element contentElem, Content content) { 108 | content.type = contentElem.getAttribute("type"); 109 | content.value = getPCData(contentElem); 110 | } 111 | 112 | private void unmarshallAuthor(Element authorElem, Author author) { 113 | NodeList nodes = authorElem.getChildNodes(); 114 | for (int i = 0; i < nodes.getLength(); i++) { 115 | Node node = nodes.item(i); 116 | if ("name".equals(node.getNodeName())) { 117 | author.name = getPCData(node); 118 | } else if ("uri".equals(node.getNodeName())) { 119 | author.uri = getPCData(node); 120 | } 121 | } 122 | } 123 | 124 | private String getPCData(Node aNode) { 125 | StringBuilder builder = new StringBuilder(); 126 | if (Node.ELEMENT_NODE == aNode.getNodeType()) { 127 | NodeList nodes = aNode.getChildNodes(); 128 | for (int i = 0; i < nodes.getLength(); i++) { 129 | Node node = nodes.item(i); 130 | if (Node.ELEMENT_NODE == node.getNodeType()) { 131 | builder.append(getPCData(node)); 132 | } else if (Node.TEXT_NODE == node.getNodeType()) { 133 | builder.append(node.getNodeValue()); 134 | } 135 | } 136 | } 137 | return builder.toString(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/parsers/ParsnipTweetsReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.parsers; 18 | 19 | import java.io.InputStream; 20 | import java.text.ParseException; 21 | import java.text.SimpleDateFormat; 22 | import java.util.Date; 23 | import java.util.Locale; 24 | 25 | import me.tatarka.parsnip.TypeConverter; 26 | import me.tatarka.parsnip.Xml; 27 | import me.tatarka.parsnip.XmlAdapter; 28 | import me.tatarka.parsnip.XmlDataException; 29 | import me.tatarka.parsnip.benchmark.PerformanceTestRunner; 30 | import me.tatarka.parsnip.benchmark.TweetsReader; 31 | import me.tatarka.parsnip.benchmark.model.Tweets; 32 | 33 | public class ParsnipTweetsReader implements TweetsReader { 34 | public static final PerformanceTestRunner.TweetsReaderFactory FACTORY = new PerformanceTestRunner.TweetsReaderFactory() { 35 | @Override 36 | public String getParserType() { 37 | return "Parsnip"; 38 | } 39 | 40 | @Override 41 | public TweetsReader newReader() throws Exception { 42 | return new ParsnipTweetsReader(); 43 | } 44 | }; 45 | 46 | private Xml xml = new Xml.Builder().add(Date.class, new DateTypeConverter()).build(); 47 | 48 | @Override 49 | public Tweets read(InputStream stream) throws Exception { 50 | XmlAdapter adapter = xml.adapter(Tweets.class); 51 | Tweets tweets = adapter.fromXml(stream); 52 | return tweets; 53 | } 54 | 55 | static class DateTypeConverter implements TypeConverter { 56 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); 57 | 58 | @Override 59 | public Date from(String value) { 60 | try { 61 | return dateFormat.parse(value); 62 | } catch (ParseException e) { 63 | throw new XmlDataException(e); 64 | } 65 | } 66 | 67 | @Override 68 | public String to(Date value) { 69 | return dateFormat.format(value); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/parsers/PullParserTweetsReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.parsers; 18 | 19 | import org.xmlpull.v1.XmlPullParser; 20 | import org.xmlpull.v1.XmlPullParserFactory; 21 | 22 | import java.io.InputStream; 23 | import java.text.DateFormat; 24 | import java.text.SimpleDateFormat; 25 | import java.util.ArrayList; 26 | import java.util.Locale; 27 | 28 | import me.tatarka.parsnip.benchmark.PerformanceTestRunner; 29 | import me.tatarka.parsnip.benchmark.TweetsReader; 30 | import me.tatarka.parsnip.benchmark.model.Author; 31 | import me.tatarka.parsnip.benchmark.model.Content; 32 | import me.tatarka.parsnip.benchmark.model.Tweet; 33 | import me.tatarka.parsnip.benchmark.model.Tweets; 34 | 35 | public class PullParserTweetsReader implements TweetsReader { 36 | public static final PerformanceTestRunner.TweetsReaderFactory FACTORY = new PerformanceTestRunner.TweetsReaderFactory() { 37 | @Override 38 | public String getParserType() { 39 | return "Pull"; 40 | } 41 | 42 | @Override 43 | public TweetsReader newReader() throws Exception { 44 | return new PullParserTweetsReader(); 45 | } 46 | }; 47 | 48 | private DateFormat dateFormat; 49 | private XmlPullParserFactory f; 50 | 51 | public PullParserTweetsReader() throws Exception { 52 | dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); 53 | f = XmlPullParserFactory.newInstance(); 54 | f.setNamespaceAware(true); 55 | } 56 | 57 | @Override 58 | public Tweets read(InputStream stream) throws Exception { 59 | XmlPullParser parser = f.newPullParser(); 60 | parser.setInput(stream, "utf-8"); 61 | parser.nextTag(); 62 | return parse(parser); 63 | } 64 | 65 | private Tweets parse(XmlPullParser parser) throws Exception { 66 | Tweets tweets = new Tweets(); 67 | tweets.tweets = new ArrayList<>(); 68 | while (parser.next() != XmlPullParser.END_DOCUMENT) { 69 | if (parser.getEventType() != XmlPullParser.START_TAG) { 70 | continue; 71 | } 72 | String name = parser.getName(); 73 | switch (name) { 74 | case "entry": 75 | tweets.tweets.add(readTweet(parser)); 76 | break; 77 | default: 78 | skip(parser); 79 | } 80 | } 81 | 82 | return tweets; 83 | } 84 | 85 | private Tweet readTweet(XmlPullParser parser) throws Exception { 86 | Tweet tweet = new Tweet(); 87 | while (parser.next() != XmlPullParser.END_TAG) { 88 | if (parser.getEventType() != XmlPullParser.START_TAG) { 89 | continue; 90 | } 91 | String name = parser.getName(); 92 | switch (name) { 93 | case "published": 94 | tweet.published = dateFormat.parse(readText(parser)); 95 | break; 96 | case "title": 97 | tweet.title = readText(parser); 98 | break; 99 | case "content": 100 | tweet.content = readContent(parser); 101 | break; 102 | case "lang": 103 | tweet.lang = readText(parser); 104 | break; 105 | case "author": 106 | tweet.author = readAuthor(parser); 107 | break; 108 | default: 109 | skip(parser); 110 | } 111 | } 112 | return tweet; 113 | } 114 | 115 | private Content readContent(XmlPullParser parser) throws Exception { 116 | Content content = new Content(); 117 | content.type = parser.getAttributeValue(null, "type"); 118 | content.value = readText(parser); 119 | return content; 120 | } 121 | 122 | private Author readAuthor(XmlPullParser parser) throws Exception { 123 | Author author = new Author(); 124 | while (parser.next() != XmlPullParser.END_TAG) { 125 | if (parser.getEventType() != XmlPullParser.START_TAG) { 126 | continue; 127 | } 128 | String name = parser.getName(); 129 | switch (name) { 130 | case "name": 131 | author.name = readText(parser); 132 | break; 133 | case "uri": 134 | author.uri = readText(parser); 135 | break; 136 | default: 137 | skip(parser); 138 | } 139 | } 140 | return author; 141 | } 142 | 143 | 144 | private String readText(XmlPullParser parser) throws Exception { 145 | String result = ""; 146 | if (parser.next() == XmlPullParser.TEXT) { 147 | result = parser.getText(); 148 | parser.nextTag(); 149 | } 150 | return result; 151 | } 152 | 153 | 154 | private void skip(XmlPullParser parser) throws Exception { 155 | if (parser.getEventType() != XmlPullParser.START_TAG) { 156 | throw new IllegalStateException(); 157 | } 158 | int depth = 1; 159 | while (depth != 0) { 160 | switch (parser.next()) { 161 | case XmlPullParser.END_TAG: 162 | depth--; 163 | break; 164 | case XmlPullParser.START_TAG: 165 | depth++; 166 | break; 167 | } 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/parsers/SAXTweetsReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.parsers; 18 | 19 | import me.tatarka.parsnip.benchmark.PerformanceTestRunner; 20 | import me.tatarka.parsnip.benchmark.TweetsReader; 21 | import me.tatarka.parsnip.benchmark.model.Author; 22 | import me.tatarka.parsnip.benchmark.model.Content; 23 | import me.tatarka.parsnip.benchmark.model.Tweet; 24 | import me.tatarka.parsnip.benchmark.model.Tweets; 25 | import org.xml.sax.Attributes; 26 | import org.xml.sax.InputSource; 27 | import org.xml.sax.SAXException; 28 | import org.xml.sax.XMLReader; 29 | import org.xml.sax.ext.LexicalHandler; 30 | import org.xml.sax.helpers.DefaultHandler; 31 | 32 | import javax.xml.parsers.SAXParser; 33 | import javax.xml.parsers.SAXParserFactory; 34 | import java.io.InputStream; 35 | import java.text.DateFormat; 36 | import java.text.ParseException; 37 | import java.text.SimpleDateFormat; 38 | import java.util.ArrayList; 39 | import java.util.Locale; 40 | 41 | public class SAXTweetsReader implements TweetsReader { 42 | public static final PerformanceTestRunner.TweetsReaderFactory FACTORY = new PerformanceTestRunner.TweetsReaderFactory() { 43 | @Override 44 | public String getParserType() { 45 | return "SAX"; 46 | } 47 | 48 | @Override 49 | public TweetsReader newReader() throws Exception { 50 | return new SAXTweetsReader(); 51 | } 52 | }; 53 | 54 | private XMLReader reader; 55 | private TweetsHandler handler; 56 | 57 | public SAXTweetsReader() throws Exception { 58 | SAXParserFactory factory = SAXParserFactory.newInstance(); 59 | SAXParser parser = factory.newSAXParser(); 60 | reader = parser.getXMLReader(); 61 | handler = new TweetsHandler(); 62 | reader.setContentHandler(handler); 63 | reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); 64 | } 65 | 66 | @Override 67 | public Tweets read(InputStream stream) throws Exception { 68 | reader.parse(new InputSource(stream)); 69 | return handler.getResult(); 70 | } 71 | 72 | private static class TweetsHandler extends DefaultLexicalHandler { 73 | private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); 74 | private Tweets tweets; 75 | private Tweet tweet; 76 | private Content content; 77 | private Author author; 78 | private String currentElement; 79 | private StringBuilder chars; 80 | 81 | public Tweets getResult() { 82 | return tweets; 83 | } 84 | 85 | @Override 86 | public void startDocument() throws SAXException { 87 | chars = new StringBuilder(); 88 | tweets = new Tweets(); 89 | tweets.tweets = new ArrayList<>(); 90 | } 91 | 92 | @Override 93 | public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 94 | currentElement = qName; 95 | chars.setLength(0); 96 | 97 | if ("entry".equals(qName)) { 98 | tweets.tweets.add(tweet = new Tweet()); 99 | } else if ("content".equals(qName)) { 100 | tweet.content = (content = new Content()); 101 | content.type = attributes.getValue("type"); 102 | } else if ("author".equals(qName)) { 103 | tweet.author = (author = new Author()); 104 | } 105 | } 106 | 107 | @Override 108 | public void endElement(String uri, String localName, String qName) throws SAXException { 109 | if (chars.length() > 0) { 110 | setCharacterValue(chars); 111 | } 112 | currentElement = null; 113 | } 114 | 115 | @Override 116 | public void startEntity(String name) throws SAXException { 117 | } 118 | 119 | @Override 120 | public void endEntity(String name) throws SAXException { 121 | } 122 | 123 | @Override 124 | public void characters(char[] ch, int start, int length) 125 | throws SAXException { 126 | chars.append(ch, start, length); 127 | } 128 | 129 | private void setCharacterValue(StringBuilder characters) throws SAXException { 130 | if ("published".equals(currentElement)) { 131 | try { 132 | tweet.published = dateFormat.parse(characters.toString()); 133 | } catch (ParseException anExc) { 134 | throw new SAXException(anExc); 135 | } 136 | } else if (("title".equals(currentElement)) && (tweet != null)) { 137 | tweet.title = characters.toString(); 138 | } else if ("content".equals(currentElement)) { 139 | content.value = characters.toString(); 140 | } else if ("twitter:lang".equals(currentElement)) { 141 | tweet.lang = characters.toString(); 142 | } else if ("name".equals(currentElement)) { 143 | author.name = characters.toString(); 144 | } else if ("uri".equals(currentElement)) { 145 | author.uri = characters.toString(); 146 | } 147 | } 148 | } 149 | 150 | static class DefaultLexicalHandler extends DefaultHandler implements LexicalHandler { 151 | @Override 152 | public void comment(char[] aArg0, int aArg1, int aArg2) throws SAXException { 153 | } 154 | 155 | @Override 156 | public void endCDATA() throws SAXException { 157 | } 158 | 159 | @Override 160 | public void endDTD() throws SAXException { 161 | } 162 | 163 | @Override 164 | public void endEntity(String aName) throws SAXException { 165 | } 166 | 167 | @Override 168 | public void startCDATA() throws SAXException { 169 | } 170 | 171 | @Override 172 | public void startDTD(String aArg0, String aArg1, String aArg2) throws SAXException { 173 | } 174 | 175 | @Override 176 | public void startEntity(String aName) throws SAXException { 177 | } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /benchmark/src/main/java/me/tatarka/parsnip/benchmark/parsers/SimpleXmlReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Evan Tatarka. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.tatarka.parsnip.benchmark.parsers; 18 | 19 | import org.simpleframework.xml.Serializer; 20 | import org.simpleframework.xml.core.Persister; 21 | import org.simpleframework.xml.transform.RegistryMatcher; 22 | import org.simpleframework.xml.transform.Transform; 23 | 24 | import java.io.InputStream; 25 | import java.text.SimpleDateFormat; 26 | import java.util.Date; 27 | import java.util.Locale; 28 | 29 | import me.tatarka.parsnip.benchmark.PerformanceTestRunner; 30 | import me.tatarka.parsnip.benchmark.TweetsReader; 31 | import me.tatarka.parsnip.benchmark.model.Tweets; 32 | 33 | public class SimpleXmlReader implements TweetsReader { 34 | public static final PerformanceTestRunner.TweetsReaderFactory FACTORY = new PerformanceTestRunner.TweetsReaderFactory() { 35 | @Override 36 | public String getParserType() { 37 | return "Simple"; 38 | } 39 | 40 | @Override 41 | public TweetsReader newReader() throws Exception { 42 | return new SimpleXmlReader(); 43 | } 44 | }; 45 | 46 | private Serializer serializer; 47 | 48 | public SimpleXmlReader() { 49 | RegistryMatcher m = new RegistryMatcher(); 50 | m.bind(Date.class, new DateFormatTransformer()); 51 | serializer = new Persister(m); 52 | } 53 | 54 | @Override 55 | public Tweets read(InputStream stream) throws Exception { 56 | return serializer.read(Tweets.class, stream); 57 | } 58 | 59 | static class DateFormatTransformer implements Transform { 60 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); 61 | 62 | @Override 63 | public Date read(String value) throws Exception { 64 | return dateFormat.parse(value); 65 | } 66 | 67 | @Override 68 | public String write(Date value) throws Exception { 69 | return dateFormat.format(value); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /benchmark/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 22 | 23 | 33 | 34 | 39 | 40 | 45 | 46 |