├── .github
└── workflows
│ └── sbt-devops.yml
├── .gitignore
├── .scalafmt.conf
├── CHANGES.md
├── LICENSE.txt
├── NOTICE.txt
├── README.md
├── build.sbt
├── play-soap
└── src
│ ├── main
│ └── scala
│ │ └── com
│ │ └── sandinh
│ │ └── soap
│ │ └── WS.scala
│ └── test
│ ├── resources
│ └── logback-test.xml
│ └── scala
│ └── com
│ └── sandinh
│ └── soap
│ ├── Calculator.scala
│ └── WSSpec.scala
├── project
├── build.properties
└── plugins.sbt
└── scala-soap
└── src
├── main
├── scala-2.13+
│ └── com
│ │ └── sandinh
│ │ └── xml
│ │ └── IterableReader.scala
├── scala-2.13-
│ └── com
│ │ └── sandinh
│ │ └── xml
│ │ └── IterableReader.scala
└── scala
│ └── com
│ └── sandinh
│ ├── soap
│ ├── SOAP.scala
│ └── SOAPDate.scala
│ └── xml
│ └── Xml.scala
└── test
├── resources
└── logback-test.xml
└── scala
├── SOAPDateSpec.scala
├── SOAPSpec.scala
└── XmlSpec.scala
/.github/workflows/sbt-devops.yml:
--------------------------------------------------------------------------------
1 | # @see https://github.com/ohze/sbt-devops/blob/main/files/sbt-devops.yml
2 | name: sbt-devops
3 | on: [push, pull_request]
4 | jobs:
5 | build:
6 | runs-on: ubuntu-20.04
7 | outputs:
8 | commitMsg: ${{ steps.commitMsg.outputs.msg }}
9 | strategy:
10 | matrix:
11 | java: [ '8', '11', '17' ]
12 | prj:
13 | - scala-soap
14 | - scala-soap2_12
15 | - play-soap_2_62_12
16 | - play-soap_2_8
17 | - play-soap_2_82_12
18 | steps:
19 | - uses: actions/checkout@v2
20 | - id: commitMsg
21 | run: echo "::set-output name=msg::$(git show -s --format=%s $GITHUB_SHA)"
22 | - uses: actions/setup-java@v2
23 | with:
24 | java-version: ${{ matrix.java }}
25 | distribution: 'temurin'
26 | - uses: coursier/cache-action@v6
27 | - run: sbt devopsQA ${{ matrix.prj }}/test
28 | if: matrix.prj == 'scala-soap'
29 | - run: sbt ${{ matrix.prj }}/test
30 | if: matrix.prj != 'scala-soap'
31 | # https://www.scala-sbt.org/1.x/docs/GitHub-Actions-with-sbt.html#Caching
32 | - run: |
33 | rm -rf "$HOME/.ivy2/local" || true
34 | find $HOME/Library/Caches/Coursier/v1 -name "ivydata-*.properties" -delete || true
35 | find $HOME/.ivy2/cache -name "ivydata-*.properties" -delete || true
36 | find $HOME/.cache/coursier/v1 -name "ivydata-*.properties" -delete || true
37 | find $HOME/.sbt -name "*.lock" -delete || true
38 | shell: bash
39 |
40 | publish:
41 | needs: build
42 | if: |
43 | success() &&
44 | github.event_name == 'push' &&
45 | (github.ref == 'refs/heads/main' ||
46 | github.ref == 'refs/heads/master' ||
47 | startsWith(github.ref, 'refs/tags/'))
48 | runs-on: ubuntu-20.04
49 | outputs:
50 | info: ${{ steps.info.outputs.info }}
51 | steps:
52 | - uses: actions/checkout@v2
53 | with:
54 | fetch-depth: 0
55 | - uses: actions/setup-java@v2
56 | with:
57 | distribution: 'temurin'
58 | java-version: '8'
59 | - run: sbt versionCheck ci-release
60 | env:
61 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }}
62 | PGP_SECRET: ${{ secrets.PGP_SECRET }}
63 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }}
64 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }}
65 | # optional
66 | #CI_CLEAN: '; clean ; sonatypeBundleClean'
67 | CI_RELEASE: 'publishSigned'
68 | #CI_SONATYPE_RELEASE: 'sonatypeBundleRelease'
69 | CI_SNAPSHOT_RELEASE: 'publish'
70 | - id: info
71 | run: echo "::set-output name=info::$(cat "$GITHUB_WORKSPACE/target/publish.info")"
72 |
73 | notify:
74 | needs: [build, publish]
75 | if: always()
76 | runs-on: ubuntu-latest
77 | steps:
78 | - uses: docker://ohze/devops-notify
79 | env:
80 | # You can use `DEVOPS_` | `SLACK_` prefix for `MATTERMOST_*` envs below
81 | # ex SLACK_WEBHOOK_URL instead of MATTERMOST_WEBHOOK_URL
82 | MATTERMOST_WEBHOOK_URL: ${{ secrets.MATTERMOST_WEBHOOK_URL }}
83 | # optional. See https://developers.mattermost.com/integrate/incoming-webhooks/#parameters
84 | #MATTERMOST_ICON: icon_url or icon_emoji
85 | #MATTERMOST_CHANNEL: use default of the webhook if not set
86 | #MATTERMOST_USERNAME: use default of the webhook if not set
87 | #MATTERMOST_PRETEXT: Message shown above the CI status attachment, ex to mention some user. Default empty.
88 | _DEVOPS_NEEDS: ${{ toJSON(needs) }}
89 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .classpath
2 | .project
3 | .idea
4 | .idea_modules
5 | .cache
6 | *.class
7 | *.log
8 |
9 | # sbt specific
10 | dist/*
11 | target/
12 | lib_managed/
13 | src_managed/
14 | project/boot/
15 | project/plugins/project/
16 |
17 | # Scala-IDE specific
18 | .scala_dependencies
19 | .DS_Store
20 |
--------------------------------------------------------------------------------
/.scalafmt.conf:
--------------------------------------------------------------------------------
1 | version = 3.0.4
2 | project.git = yes
3 | trailingCommas = keep
4 | docstrings.wrap = no
5 | runner.dialect = scala213source3
6 | fileOverride {
7 | "glob:**/*.sbt" {
8 | runner.dialect = sbt1
9 | }
10 | "glob:**/project/*.scala" {
11 | runner.dialect = scala212source3
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/CHANGES.md:
--------------------------------------------------------------------------------
1 | ### Changelogs
2 | ##### v1.9.0
3 | + support scala 2.13 & drop support for scala 2.11
4 | + update slf4j-api 1.7.29, scala-xml 1.2.0
5 | + update play-ahs-ws 2.8.0 (a dependency of play-ws)
6 | + also update sbt 1.3.5, & sbt plugins
7 | + update .travis.yml for testing on (openjdk8, 11) x (scala 2.13.1, 2.12.10)
8 |
9 | ##### v1.8.0
10 | + update scala 2.12.4, 2.11.12
11 | + update play 2.6.7 & remove dependencies joda-time, joda-convert
12 | + update sbt 1.0.3, sbt-coursier 1.0.0-RC13
13 |
14 | break changes caused by migrate from joda-time to java.time:
15 | + `SOAPDate(date: org.joda.time.DateTime, dateFormatter: org.joda.time.format.DateTimeFormatter)`
16 | =>
17 | `SOAPDate(date: java.time.LocalDateTime, dateFormatter: java.time.format.DateTimeFormatter)`
18 | + `SOAPDate("some invalid date")` is previously `throwA[IllegalArgumentException]`
19 | => now `throwA[DateTimeParseException]`
20 |
21 | ##### v1.7.0
22 | + cross compile for scala 2.12.3 & 2.11.11
23 | + update play 2.6.3
24 | + update scala-xml 1.0.6, slf4j-api 1.7.25, joda-time 2.9.9, joda-convert 1.8.3
25 | // TODO remove joda-time depencency
26 | + update sbt 1.0.1, sbt-sonatype 2.0, sbt-pgp 1.1.0
27 | + use sbt-coursier
28 | + use sbt-scalafmt-coursier instead fo sbt-scalariform
29 | + move source code to github.com/ohze/scala-soap
30 | + remove deprecated classes SoapWS11 & SoapWS12
31 |
32 | ##### v1.6.1
33 | + update play 2.5.3
34 |
35 | ##### v1.6.0
36 | + update sbt 0.13.11, scala 2.11.8, slf4j-api 1.7.21, joda-time 2.9.3
37 | + split into `scala-soap` & `play-soap`. Only `play-soap` depend on `play-ws`.
38 | + update play-ws from 2.4.6 to 2.5.2
39 | + SoapWS11 & SoapWS12 is now deprecated. Use WS11 and inject wsClient instead.
40 | Ex, see the test class [CurrencyByCountryWS12](play-soap/src/test/scala/com/sandinh/soap/GetCurrencyByCountry.scala#L45):
41 | ```scala
42 | @Singleton
43 | class CurrencyByCountryWS12 @Inject() (protected val wsClient: WSClient) extends WS12[Param, Result] {
44 | protected def url = "http://www.webservicex.net/country.asmx"
45 | }
46 | ```
47 |
48 | ##### v1.5.0
49 | + break binary compatibility. You must re-compile your code when update scala-soap to this version.
50 | + SOAPDate - moved from using java.util.Date (not thread safe) to org.joda.time.DateTime
51 | + depend on joda-time is now mandatory, not optional transitively from play-ws
52 |
53 | ##### v1.4.1
54 | + update play 2.4.6 (optional dependency), scala-xml 1.0.5, slf4j-api 1.7.13
55 |
56 | ##### v1.4.0
57 | + update play 2.4.2 (optional dependency). Note play 2.4.x require java 8
58 |
59 | ##### v1.3.1
60 | + only update play 2.3.9, scala 2.11.6, scala-xml 1.0.4
61 | + remove crossBuild for scala 2.10
62 |
63 | ##### v1.3.0
64 | + update scala 2.11.5, sbt 0.13.7, slf4j-api 1.7.10, play-ws (optional dependency) 2.3.7
65 | + add scala-xml 1.0.3 as a dependency for scala-soap _2.11
66 | + make explicit result type of implicit defs & add `import scala.language.implicitConversions`
67 | + remove object BasicReaders, SpecialReaders, BasicWriters, SpecialWriters & remove trait DefaultImplicits
68 |
69 | ##### v1.2.1
70 | + update scala 2.11.1, play-ws (optional dependency) 2.3.0-RC2
71 |
72 | ##### v1.2.0
73 | + cross compile to scala 2.10 & 2.11
74 | + update optional dependency `play 2.2.2` to `play-ws 2.3.0-RC1`
75 |
76 | ##### v1.1.2
77 | + reformat code using scalariform
78 | + add traits WS11 & WS12
79 | + update scala 2.10.4
80 |
81 | ##### v1.1.1
82 | + Only update play 2.2.1 to 2.2.2
83 |
84 | ##### v1.0.0
85 | + Change package to com.sandinh
86 | + Add com.sandinh.soap.WS. Usage: see [WSSpec](https://github.com/ohze/scala-soap/blob/master/src/test/scala/com/sandinh/soap/WSSpec.scala)
87 | + Optional depends on "play" (require if you use WS)
88 |
89 | ##### v0.9.0
90 | First version.
91 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | 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
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | XML and SOAP Play library - for Scala and Play Framework.
2 |
3 | Scala tool to serialize/deserialize XML (and SOAP) without code generation or other magic.
4 |
5 | Copyright 2012 Pascal Voitot (@mandubian pascal.voitot.dev@gmail.com)
6 | Copyright 2013 Paweł Prażak
7 |
8 | Licensed under the Apache License, Version 2.0 (the "License");
9 | you may not use this file except in compliance with the License.
10 | You may obtain a copy of the License at
11 |
12 | http://www.apache.org/licenses/LICENSE-2.0
13 |
14 | Unless required by applicable law or agreed to in writing, software
15 | distributed under the License is distributed on an "AS IS" BASIS,
16 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | See the License for the specific language governing permissions and
18 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | XML and SOAP Play library
2 | =========================
3 | [](https://github.com/ohze/scala-soap/actions/workflows/sbt-devops.yml)
4 |
5 | XML and SOAP Play library, for Scala to serialize/deserialize XML (and SOAP) without code generation or other magic.
6 |
7 | You may use this api if like me:
8 | - You don't like SOAP because it's not human-friendly at all, it's too verbose and the surrounding standards are just non-sense
9 | - You hate WSDL because it's not humanly readable and requires tools to manipulate them
10 | - You must pollute your code with esoteric annotations just to do RPC in the great majority of cases
11 | - You hate all those bloated frameworks to manage SOAP and the crazy standards around it
12 | - You don't understand why we still use SOAP but you still have to communicate in SOAP in many cases so you still must bear it
13 | - You just want to extract the data you need from SOAP frames you receive and to generate SOAP frames that look like what your client expect but you don't care about the standards behind that.
14 |
15 | **This API is just a set of tools, almost only syntactic sugar to help you**:
16 | - It DOES NOT pretend to provide pure standard SOAP.
17 | - It DOES NOT generate WSDL so you must provide it yourself.
18 | - It just helps you mimic SOAP by providing a few tools and helpers to deserialize/serialize.
19 | - It just aims at being practical without needing deep knowledge of SOAP standards.
20 | - It can serialize/deserialize SOAP so it can also do it for XML...
21 | - It uses pure Scala XML library even if it's a bit incoherent sometimes. AntiXML could be cool too...
22 |
23 | More information on https://github.com/ohze/scala-soap
24 |
25 | ### Install
26 | scala-soap is [published](http://search.maven.org/#search|ga|1|g%3A%22com.sandinh%22%20scala-soap) to maven center.
27 |
28 | add to build.sbt:
29 | ```
30 | libraryDependencies += "com.sandinh" %% "scala-soap" % scalaSoapVersion
31 | ```
32 | Or:
33 | ```
34 | libraryDependencies += "com.sandinh" %% "play-soap" % playSoapVersion
35 | ```
36 |
37 | ### Changelogs
38 | see [CHANGES.md](CHANGES.md)
39 |
40 | ### Licence
41 | This software is licensed under the Apache 2 license:
42 | http://www.apache.org/licenses/LICENSE-2.0
43 |
44 | Copyright 2014-2017 Sân Đình (http://sandinh.com)
45 |
46 | Credits to Pascal Voitot and Paweł Prażak for previous version of this codebase
47 |
48 | Credits to Étienne Vallette d'Osia for inspiring/tackling draft version of this code ;)
49 |
--------------------------------------------------------------------------------
/build.sbt:
--------------------------------------------------------------------------------
1 | import com.typesafe.tools.mima.core.NewMixinForwarderProblem
2 | import com.typesafe.tools.mima.core.ProblemFilters.exclude
3 |
4 | lazy val `scala-soap` = projectMatrix
5 | .jvmPlatform(Seq(scala212, scala213))
6 | .settings(
7 | libraryDependencies ++= Seq(
8 | "org.scala-lang.modules" %% "scala-xml" % "1.3.0",
9 | "org.slf4j" % "slf4j-api" % "1.7.32",
10 | "ch.qos.logback" % "logback-classic" % "1.2.6" % Test
11 | ) ++ specs2("-core").value,
12 | // Adds a `src/main/scala-2.13+` source directory for Scala 2.13 and newer
13 | // and a `src/main/scala-2.13-` source directory for Scala version older than 2.13
14 | Compile / unmanagedSourceDirectories += {
15 | val sourceDir = (Compile / sourceDirectory).value
16 | CrossVersion.partialVersion(scalaVersion.value) match {
17 | case Some((2, n)) if n >= 13 => sourceDir / "scala-2.13+"
18 | case _ => sourceDir / "scala-2.13-"
19 | }
20 | },
21 | versionPolicyPreviousVersions := (scalaBinaryVersion.value match {
22 | case "2.12" => Seq("1.8.0")
23 | case _ => Seq("1.9.0")
24 | }),
25 | mimaBinaryIssueFilters ++= Seq( // format: off
26 | // we make SpecialReaders extends IterableReader
27 | exclude[NewMixinForwarderProblem]("com.sandinh.xml.SpecialReaders.traversableReader"),
28 | ), // format: on
29 | libraryDependencySchemes ++= Seq(
30 | "org.scala-lang.modules" %% "scala-xml" % "semver-spec",
31 | ),
32 | )
33 |
34 | lazy val `play-soap` = projectMatrix
35 | .playAxis(play26, Seq(scala212))
36 | .playAxis(play28, Seq(scala212, scala213))
37 | .dependsOn(`scala-soap`)
38 | .settings(
39 | libraryDependencies ++= play("ahc-ws", "specs2" -> Test).value,
40 | addOpensForTest(),
41 | mimaPreviousArtifacts := (playAxis.value match {
42 | case `play26` => Set("com.sandinh" %% "play-soap" % "1.8.0")
43 | case _ => Set.empty // TODO mimaPreviousArtifacts.value
44 | }),
45 | libraryDependencySchemes ++= Seq(
46 | "com.google.guava" % "guava" % "always", // change from 22.0 to 23.6.1-jre
47 | "com.typesafe" %% "ssl-config-core" % "always", // change from 0.2.2 to 0.3.8
48 | "org.scala-lang.modules" %% "scala-xml" % "semver-spec",
49 | "org.scala-lang.modules" %% "scala-parser-combinators" % "semver-spec",
50 | ),
51 | )
52 |
53 | lazy val `scala-soap-root` = (project in file("."))
54 | .aggregate(`scala-soap`.projectRefs ++ `play-soap`.projectRefs: _*)
55 | .settings(skipPublish)
56 |
57 | inThisBuild(
58 | Seq(
59 | versionScheme := Some("semver-spec"),
60 | developers := List(
61 | Developer(
62 | "thanhbv",
63 | "Bui Viet Thanh",
64 | "thanhbv@sandinh.net",
65 | url("https://sandinh.com")
66 | ),
67 | Developer(
68 | "pawelprazak",
69 | "Paweł Prażak",
70 | "pawelprazak@gmail.com",
71 | url("https://github.com/pawelprazak")
72 | ),
73 | Developer(
74 | "mandubian",
75 | "Pascal Voitot",
76 | "pascal.voitot.dev@gmail.com",
77 | url("http://www.mandubian.com")
78 | ),
79 | ),
80 | )
81 | )
82 |
--------------------------------------------------------------------------------
/play-soap/src/main/scala/com/sandinh/soap/WS.scala:
--------------------------------------------------------------------------------
1 | /** @author giabao
2 | * created: 2013-10-30 10:13
3 | * (c) 2011-2013 sandinh.com
4 | */
5 | package com.sandinh.soap
6 |
7 | import com.sandinh.xml.{XmlReader, XmlWriter}
8 | import scala.concurrent.Future
9 | import scala.concurrent.ExecutionContext.Implicits.global
10 | import play.api.libs.ws.WSClient
11 | import play.api.http.HeaderNames._
12 | import scala.xml.NamespaceBinding
13 | import org.slf4j.LoggerFactory
14 |
15 | trait WS[P, R] {
16 | lazy val logger = LoggerFactory.getLogger("com.sandinh.soap.WS")
17 |
18 | protected def url: String
19 |
20 | protected def wsClient: WSClient
21 |
22 | def call(param: P)(implicit w: XmlWriter[P], r: XmlReader[R]): Future[R]
23 |
24 | protected final def call(
25 | param: P,
26 | ns: NamespaceBinding,
27 | hdrs: (String, String)*
28 | )(implicit w: XmlWriter[P], r: XmlReader[R]): Future[R] = {
29 | val s = SOAP.toSoap(param, ns).buildString(stripComments = true)
30 | val data = ("" + s).getBytes("UTF-8")
31 | val headers = hdrs :+ (CONTENT_LENGTH -> data.length.toString)
32 | logger.debug("-->{}\n{}\n{}", url, headers, s)
33 | wsClient
34 | .url(url)
35 | .addHttpHeaders(headers: _*)
36 | .post(data)
37 | .map { res =>
38 | logger.debug("<--\n{}", res.body)
39 | //if we use `val x = res.xml` then `testOnly com.sandinh.soap.WSSpec` sometimes throw
40 | //ClassCastException: : org.apache.xerces.parsers.XIncludeAwareParserConfiguration cannot be cast to org.apache.xerces.xni.parser.XMLParserConfiguration (null:-1)
41 | //@see http://www.ibm.com/developerworks/websphere/library/techarticles/0310_searle/searle.html
42 | //@see http://xerces.apache.org/xerces2-j/faq-general.html#faq-5
43 | val x = xml.XML.loadString(res.body)
44 | SOAP.fromSOAP[R](x).get
45 | }
46 | }
47 | }
48 |
49 | trait WS11[P, R] extends WS[P, R] {
50 | protected def action: String
51 |
52 | @inline private def ct = CONTENT_TYPE -> "text/xml; charset=utf-8"
53 | @inline private def actionHeader = ("SOAPAction", "\"" + action + "\"")
54 |
55 | def call(param: P)(implicit w: XmlWriter[P], r: XmlReader[R]): Future[R] =
56 | call(param, SOAP.SoapNS, ct, actionHeader)
57 | }
58 |
59 | trait WS12[P, R] extends WS[P, R] {
60 | @inline private def ct = CONTENT_TYPE -> "application/soap+xml; charset=utf-8"
61 |
62 | def call(param: P)(implicit w: XmlWriter[P], r: XmlReader[R]): Future[R] =
63 | call(param, SOAP.SoapNS12, ct)
64 | }
65 |
--------------------------------------------------------------------------------
/play-soap/src/test/resources/logback-test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/play-soap/src/test/scala/com/sandinh/soap/Calculator.scala:
--------------------------------------------------------------------------------
1 | package com.sandinh.soap
2 |
3 | import javax.inject.{Inject, Singleton}
4 | import com.sandinh.xml.{Xml, XmlReader, XmlWriter}
5 | import play.api.libs.ws.WSClient
6 | import scala.xml.NodeSeq
7 | import com.sandinh.soap.DefaultImplicits._
8 |
9 | /** @see [[http://www.dneonline.com/calculator.asmx?op=Add]] */
10 | object Calculator {
11 | case class Param(x: Int, y: Int)
12 | case class Result(r: Int)
13 |
14 | implicit object ParamXmlW extends XmlWriter[Param] {
15 | def write(t: Param, base: NodeSeq): NodeSeq =
16 |
17 | {t.x}
18 | {t.y}
19 |
20 | }
21 |
22 | implicit object ResultXmlR extends XmlReader[Result] {
23 | def read(x: NodeSeq): Option[Result] =
24 | for {
25 | res <- (x \ "AddResponse").headOption
26 | r <- Xml.fromXml[Int](res \ "AddResult")
27 | } yield Result(r)
28 | }
29 |
30 | val url = "http://www.dneonline.com/calculator.asmx"
31 | }
32 |
33 | import Calculator._
34 |
35 | @Singleton
36 | class CalculatorWS11 @Inject() (protected val wsClient: WSClient)
37 | extends WS11[Param, Result] {
38 | protected def url = Calculator.url
39 | protected def action = "http://tempuri.org/Add"
40 | }
41 |
42 | @Singleton
43 | class CalculatorWS12 @Inject() (protected val wsClient: WSClient)
44 | extends WS12[Param, Result] {
45 | protected def url = Calculator.url
46 | }
47 |
--------------------------------------------------------------------------------
/play-soap/src/test/scala/com/sandinh/soap/WSSpec.scala:
--------------------------------------------------------------------------------
1 | /** @author giabao
2 | * created: 2013-10-30 11:13
3 | * (c) 2011-2013 sandinh.com
4 | */
5 | package com.sandinh.soap
6 |
7 | import org.specs2.concurrent.ExecutionEnv
8 | import play.api.test.{PlaySpecification, WithApplication}
9 | import scala.concurrent.duration._
10 |
11 | class WSSpec(implicit ee: ExecutionEnv) extends PlaySpecification {
12 | "WS" should {
13 | val timeOut = 20.seconds
14 | import Calculator._
15 | val p = Param(5, 6)
16 | def test(ws: WS[Param, Result]) =
17 | ws.call(p).map(_.r) must beEqualTo(p.x + p.y)
18 | .awaitFor(timeOut)
19 | .eventually(5, 1.second)
20 |
21 | "able to call Calculator soap service using soap 1.1" >> new WithApplication {
22 | test(app.injector.instanceOf[CalculatorWS11])
23 | }
24 | "able to call Calculator soap service using soap 1.2" >> new WithApplication {
25 | test(app.injector.instanceOf[CalculatorWS12])
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/project/build.properties:
--------------------------------------------------------------------------------
1 | sbt.version=1.6.0-M1
2 |
--------------------------------------------------------------------------------
/project/plugins.sbt:
--------------------------------------------------------------------------------
1 | addSbtPlugin("com.sandinh" % "sd-devops-oss" % "6.2.0")
2 | addSbtPlugin("com.sandinh" % "sd-matrix" % "6.2.0")
3 |
--------------------------------------------------------------------------------
/scala-soap/src/main/scala-2.13+/com/sandinh/xml/IterableReader.scala:
--------------------------------------------------------------------------------
1 | package com.sandinh.xml
2 |
3 | import scala.collection.Factory
4 |
5 | trait IterableReader {
6 | implicit def traversableReader[F[_], A](implicit
7 | bf: Factory[A, F[A]],
8 | r: XmlReader[A]
9 | ): XmlReader[F[A]] = new XmlReader[F[A]] {
10 | def read(x: xml.NodeSeq): Option[F[A]] = {
11 | val ret = bf.fromSpecific(x.flatMap(n => r.read(n)))
12 | Some(ret)
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/scala-soap/src/main/scala-2.13-/com/sandinh/xml/IterableReader.scala:
--------------------------------------------------------------------------------
1 | package com.sandinh.xml
2 |
3 | import scala.collection.generic.CanBuildFrom
4 | import scala.language.higherKinds
5 |
6 | trait IterableReader {
7 | implicit def traversableReader[F[_], A](implicit
8 | bf: CanBuildFrom[F[_], A, F[A]],
9 | r: XmlReader[A]
10 | ): XmlReader[F[A]] = new XmlReader[F[A]] {
11 | def read(x: xml.NodeSeq): Option[F[A]] = {
12 | val builder = bf()
13 | x.foreach { n =>
14 | r.read(n) foreach builder.+=
15 | }
16 | Some(builder.result())
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/scala-soap/src/main/scala/com/sandinh/soap/SOAP.scala:
--------------------------------------------------------------------------------
1 | package com.sandinh.soap
2 |
3 | import scala.language.implicitConversions
4 | import scala.xml.{Elem, NamespaceBinding}
5 | import com.sandinh.xml._
6 | import org.slf4j.LoggerFactory
7 |
8 | object SOAP extends SOAP
9 |
10 | trait SOAP {
11 | def toSoap[T](t: T, ns: NamespaceBinding = SoapNS)(implicit
12 | w: XmlWriter[T]
13 | ): xml.Elem =
14 | DefaultImplicits
15 | .SoapEnvelopeWriter[T](w)
16 | .write(SoapEnvelope(t)(ns), xml.NodeSeq.Empty)
17 | .asInstanceOf[Elem]
18 |
19 | def fromSOAP[T](x: xml.NodeSeq)(implicit r: XmlReader[T]): Option[T] =
20 | DefaultImplicits.SoapEnvelopeReader[T](r).read(x) match {
21 | case Some(SoapEnvelope(t)) => Some(t)
22 | case None => None
23 | }
24 |
25 | val SoapNS = NamespaceBinding(
26 | "soapenv",
27 | "http://schemas.xmlsoap.org/soap/envelope/",
28 | xml.TopScope
29 | )
30 | val SoapNS12 = NamespaceBinding(
31 | "soapenv",
32 | "http://www.w3.org/2003/05/soap-envelope",
33 | xml.TopScope
34 | )
35 | }
36 |
37 | case class SoapEnvelope[T](t: T)(implicit
38 | _namespace: NamespaceBinding = SOAP.SoapNS
39 | ) {
40 | def namespace = _namespace
41 | }
42 |
43 | case class SoapFault[T](
44 | faultcode: String,
45 | faultstring: String,
46 | faultactor: String,
47 | detail: T
48 | )
49 |
50 | object SoapFault {
51 | object FaultCode {
52 |
53 | /** Found an invalid namespace for the SOAP Envelope element */
54 | val VersionMismatch = "SOAP-ENV:VersionMismatch"
55 |
56 | /** An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood */
57 | val MustUnderstand = "SOAP-ENV:MustUnderstand"
58 |
59 | /** The message was incorrectly formed or contained incorrect information */
60 | val Client = "SOAP-ENV:Client"
61 |
62 | /** There was a problem with the server so the message could not proceed */
63 | val Server = "SOAP-ENV:Server"
64 | }
65 | }
66 |
67 | object DefaultImplicits
68 | extends DefaultSOAPFormatters
69 | with BasicReaders
70 | with SpecialReaders
71 | with BasicWriters
72 | with SpecialWriters
73 |
74 | trait DefaultSOAPFormatters {
75 | private lazy val logger = LoggerFactory getLogger getClass.getName
76 |
77 | implicit def SoapEnvelopeReader[T](implicit
78 | reader: XmlReader[T]
79 | ): XmlReader[SoapEnvelope[T]] = new XmlReader[SoapEnvelope[T]] {
80 | def read(x: xml.NodeSeq): Option[SoapEnvelope[T]] = {
81 | x.collectFirst { case x: xml.Elem if x.label == "Envelope" => x }
82 | .flatMap { env =>
83 | (env \ "Body").headOption.flatMap { body =>
84 | reader.read(body).map { t =>
85 | SoapEnvelope(t)(env.scope)
86 | }
87 | }
88 | }
89 | }
90 | }
91 |
92 | implicit def SoapEnvelopeWriter[T](implicit
93 | fmt: XmlWriter[T]
94 | ): XmlWriter[SoapEnvelope[T]] = new XmlWriter[SoapEnvelope[T]] {
95 |
96 | /** @param base not used */
97 | def write(st: SoapEnvelope[T], base: xml.NodeSeq) = {
98 | val env =
99 |
100 |
101 | {Xml.toXml(st.t)}
102 |
103 | env.copy(scope = st.namespace)
104 | }
105 | }
106 |
107 | implicit def SoapFaultReader[T](implicit
108 | fmt: XmlReader[T],
109 | strR: XmlReader[String]
110 | ): XmlReader[SoapFault[T]] = new XmlReader[SoapFault[T]] {
111 | def read(x: xml.NodeSeq): Option[SoapFault[T]] = {
112 | val envelope = x \\ "Fault"
113 | envelope.headOption.flatMap[SoapFault[T]]({ elt =>
114 | (
115 | strR.read(elt \ "faultcode"),
116 | strR.read(elt \ "faultstring"),
117 | strR.read(elt \ "faultactor"),
118 | fmt.read(elt \ "detail")
119 | ) match {
120 | case (None, _, _, _) =>
121 | logger.debug("Code part missing in SOAP Fault"); None
122 | case (_, None, _, _) =>
123 | logger.debug("Message part missing in SOAP Fault"); None
124 | case (_, _, None, _) =>
125 | logger.debug("Actor part missing in SOAP Fault"); None
126 | case (_, _, _, None) =>
127 | logger.debug("Detail part missing in SOAP Fault"); None
128 | case (Some(code), Some(msg), Some(actor), Some(detail)) =>
129 | Some(SoapFault(code, msg, actor, detail))
130 | case _ => None
131 | }
132 | })
133 | }
134 | }
135 |
136 | implicit def SoapFaultWriter[T](implicit
137 | fmt: XmlWriter[T]
138 | ): XmlWriter[SoapFault[T]] = new XmlWriter[SoapFault[T]] {
139 | def write(fault: SoapFault[T], base: xml.NodeSeq) =
140 |
141 | {fault.faultcode}
142 | {fault.faultstring}
143 | {fault.faultactor}
144 | {Xml.toXml(fault.detail)}
145 |
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/scala-soap/src/main/scala/com/sandinh/soap/SOAPDate.scala:
--------------------------------------------------------------------------------
1 | package com.sandinh.soap
2 |
3 | import java.time.{LocalDate, LocalDateTime}
4 | import java.time.format.DateTimeFormatter
5 | import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME
6 |
7 | class SOAPDate(date: LocalDateTime, dateFormatter: DateTimeFormatter) {
8 | override def toString: String = dateFormatter.format(date)
9 | def toDate: LocalDateTime = date
10 | }
11 |
12 | object SOAPDate {
13 | def apply(date: LocalDateTime) = new SOAPDate(date, ISO_LOCAL_DATE_TIME)
14 | def apply(dateText: String) =
15 | new SOAPDate(textToDate(dateText), ISO_LOCAL_DATE_TIME)
16 |
17 | def textToDate(dateText: String): LocalDateTime = {
18 | if (dateText.length == 10) //"yyyy-MM-dd".length
19 | LocalDate.parse(dateText).atStartOfDay()
20 | else
21 | LocalDateTime.parse(dateText)
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/scala-soap/src/main/scala/com/sandinh/xml/Xml.scala:
--------------------------------------------------------------------------------
1 | package com.sandinh.xml
2 |
3 | import scala.util.Try
4 | import scala.xml.Attribute
5 | import com.sandinh.soap.{DefaultImplicits, SOAPDate}
6 | import scala.language.{implicitConversions, higherKinds}
7 |
8 | trait XmlReader[T] {
9 | def read(x: xml.NodeSeq): Option[T]
10 | }
11 |
12 | trait XmlWriter[-T] {
13 | def write(t: T, base: xml.NodeSeq): xml.NodeSeq
14 | }
15 |
16 | trait XmlConverter[T] extends XmlReader[T] with XmlWriter[T]
17 |
18 | object Xml extends Xml
19 |
20 | trait Xml {
21 | def toXml[T](t: T, base: xml.NodeSeq = xml.NodeSeq.Empty)(implicit
22 | w: XmlWriter[T]
23 | ): xml.NodeSeq = w.write(t, base)
24 |
25 | def fromXml[T](x: xml.NodeSeq)(implicit r: XmlReader[T]): Option[T] =
26 | r.read(x)
27 | }
28 |
29 | trait BasicReaders {
30 | import scala.util.control.Exception._
31 |
32 | implicit object StringReader extends XmlReader[String] {
33 | def read(x: xml.NodeSeq): Option[String] =
34 | if (x.isEmpty) None else Some(x.text)
35 | }
36 |
37 | implicit object IntReader extends XmlReader[Int] {
38 | def read(x: xml.NodeSeq): Option[Int] = if (x.isEmpty) None
39 | else catching(classOf[NumberFormatException]) opt x.text.toInt
40 | }
41 |
42 | implicit object LongReader extends XmlReader[Long] {
43 | def read(x: xml.NodeSeq): Option[Long] = if (x.isEmpty) None
44 | else catching(classOf[NumberFormatException]) opt x.text.toLong
45 | }
46 |
47 | implicit object ShortReader extends XmlReader[Short] {
48 | def read(x: xml.NodeSeq): Option[Short] = if (x.isEmpty) None
49 | else catching(classOf[NumberFormatException]) opt x.text.toShort
50 | }
51 |
52 | implicit object FloatReader extends XmlReader[Float] {
53 | def read(x: xml.NodeSeq): Option[Float] = if (x.isEmpty) None
54 | else catching(classOf[NumberFormatException]) opt x.text.toFloat
55 | }
56 |
57 | implicit object DoubleReader extends XmlReader[Double] {
58 | def read(x: xml.NodeSeq): Option[Double] = if (x.isEmpty) None
59 | else catching(classOf[NumberFormatException]) opt x.text.toDouble
60 | }
61 |
62 | implicit object BooleanReader extends XmlReader[Boolean] {
63 | def read(x: xml.NodeSeq): Option[Boolean] =
64 | if (x.isEmpty) None else Try(x.text.toBoolean).toOption
65 | }
66 | }
67 |
68 | trait SpecialReaders extends IterableReader {
69 | implicit def OptionReader[T](implicit r: XmlReader[T]): XmlReader[Option[T]] =
70 | new XmlReader[Option[T]] {
71 | def read(x: xml.NodeSeq): Option[Option[T]] = {
72 | x.collectFirst { case e: xml.Elem =>
73 | if (
74 | e.attributes.exists { a =>
75 | a.key == "nil" && a.value.text == "true"
76 | }
77 | ) None
78 | else r.read(e)
79 | } orElse Some(None)
80 | }
81 | }
82 |
83 | implicit def mapReader[K, V](implicit
84 | rk: XmlReader[K],
85 | rv: XmlReader[V]
86 | ): XmlReader[Map[K, V]] = new XmlReader[Map[K, V]] {
87 | def read(x: xml.NodeSeq): Option[Map[K, V]] = {
88 | Some(
89 | x.collect { case e: xml.Elem =>
90 | for (
91 | k <- Xml.fromXml[K](e \ "key");
92 | v <- Xml.fromXml[V](e \ "value")
93 | ) yield k -> v
94 | }.filter(_.isDefined)
95 | .map(_.get)
96 | .toMap[K, V]
97 | )
98 | }
99 | }
100 |
101 | implicit object SOAPDateReader extends XmlReader[SOAPDate] {
102 | def read(x: xml.NodeSeq): Option[SOAPDate] =
103 | if (x.isEmpty) None else Some(SOAPDate(x.text))
104 | }
105 | }
106 |
107 | trait BasicWriters {
108 | implicit object StringWriter extends XmlWriter[String] {
109 | def write(s: String, base: xml.NodeSeq): xml.NodeSeq = base
110 | .collectFirst { case e: xml.Elem =>
111 | e.copy(child = xml.Text(s))
112 | }
113 | .getOrElse(xml.Text(s))
114 | }
115 |
116 | implicit object IntWriter extends XmlWriter[Int] {
117 | def write(s: Int, base: xml.NodeSeq): xml.NodeSeq =
118 | StringWriter.write(s.toString, base)
119 | }
120 |
121 | implicit object LongWriter extends XmlWriter[Long] {
122 | def write(s: Long, base: xml.NodeSeq): xml.NodeSeq =
123 | StringWriter.write(s.toString, base)
124 | }
125 |
126 | implicit object FloatWriter extends XmlWriter[Float] {
127 | def write(s: Float, base: xml.NodeSeq): xml.NodeSeq =
128 | StringWriter.write(s.toString, base)
129 | }
130 |
131 | implicit object ShortWriter extends XmlWriter[Short] {
132 | def write(s: Short, base: xml.NodeSeq): xml.NodeSeq =
133 | StringWriter.write(s.toString, base)
134 | }
135 |
136 | implicit object DoubleWriter extends XmlWriter[Double] {
137 | def write(s: Double, base: xml.NodeSeq): xml.NodeSeq =
138 | StringWriter.write(s.toString, base)
139 | }
140 |
141 | implicit object BooleanWriter extends XmlWriter[Boolean] {
142 | def write(s: Boolean, base: xml.NodeSeq): xml.NodeSeq =
143 | StringWriter.write(s.toString, base)
144 | }
145 |
146 | }
147 |
148 | trait SpecialWriters {
149 | val xsiNS = xml.NamespaceBinding(
150 | "xsi",
151 | "http://www.w3.org/2001/XMLSchema-instance",
152 | xml.TopScope
153 | )
154 |
155 | implicit def optionWriter[T](implicit
156 | writer: XmlWriter[T]
157 | ): XmlWriter[Option[T]] = new XmlWriter[Option[T]] {
158 | def write(option: Option[T], base: xml.NodeSeq) = {
159 | option match {
160 | case None =>
161 | base
162 | .collectFirst { case e: xml.Elem =>
163 | e.copy(scope = xsiNS) % Attribute("xsi", "nil", "true", xml.Null)
164 | }
165 | .getOrElse(xml.NodeSeq.Empty)
166 | case Some(x) => writer.write(x, base)
167 | }
168 | }
169 | }
170 |
171 | implicit def traversableWriter[T](implicit
172 | w: XmlWriter[T]
173 | ): XmlWriter[Iterable[T]] = new XmlWriter[Iterable[T]] {
174 | def write(t: Iterable[T], base: xml.NodeSeq) = {
175 | t.foldLeft(xml.NodeSeq.Empty)((acc, n) => acc ++ w.write(n, base))
176 | }
177 | }
178 |
179 | implicit def mapWriter[K, V](implicit
180 | kw: XmlWriter[K],
181 | vw: XmlWriter[V]
182 | ): XmlWriter[Map[K, V]] = new XmlWriter[Map[K, V]] {
183 | def write(m: Map[K, V], base: xml.NodeSeq) = {
184 | m.foldLeft(xml.NodeSeq.Empty) { (acc, n) =>
185 | base
186 | .collectFirst { case e: xml.Elem =>
187 | e.copy(child = kw.write(n._1, ) ++ vw.write(n._2, ))
188 | }
189 | .map(acc ++ _)
190 | .getOrElse(acc)
191 | }
192 | }
193 | }
194 |
195 | implicit object SOAPDateWriter extends XmlWriter[SOAPDate] {
196 | def write(d: SOAPDate, base: xml.NodeSeq): xml.NodeSeq =
197 | DefaultImplicits.StringWriter.write(d.toString, base)
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/scala-soap/src/test/resources/logback-test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/scala-soap/src/test/scala/SOAPDateSpec.scala:
--------------------------------------------------------------------------------
1 | import java.time.format.DateTimeParseException
2 |
3 | import org.specs2.mutable._
4 | import com.sandinh.soap.SOAPDate
5 | import java.time.LocalDateTime
6 | import java.time.Instant.EPOCH
7 | import java.time.ZoneOffset.UTC
8 |
9 | class SOAPDateSpec extends Specification {
10 |
11 | "SOAPDate" should {
12 |
13 | "parse SOAP format datetime yyyy-MM-dd'T'HH:mm:ss" in {
14 | SOAPDate("1970-01-01T00:00:01").toString === "1970-01-01T00:00:01"
15 | SOAPDate("1970-02-01T00:00:00").toString === "1970-02-01T00:00:00"
16 | SOAPDate("1970-01-01T00:00:00").toString === "1970-01-01T00:00:00"
17 | }
18 |
19 | "parse SOAP format date yyyy-MM-dd only" in {
20 | SOAPDate("1970-01-01").toString === "1970-01-01T00:00:00"
21 | }
22 |
23 | "parse SOAP format LocalDateTime from UNIX 0" in {
24 | SOAPDate(
25 | LocalDateTime.ofInstant(EPOCH, UTC)
26 | ).toString === "1970-01-01T00:00:00"
27 | }
28 |
29 | "throw DateTimeParseException on invalid format" in {
30 | SOAPDate("bzdura") must throwA[DateTimeParseException]
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/scala-soap/src/test/scala/SOAPSpec.scala:
--------------------------------------------------------------------------------
1 | import com.sandinh.soap.{SoapFault, SOAP}
2 | import com.sandinh.xml.{XmlConverter, XmlReader, Xml}
3 | import org.specs2.mutable._
4 | import com.sandinh.soap.DefaultImplicits._
5 | import scala.xml.NamespaceBinding
6 |
7 | class SOAPSpec extends Specification {
8 |
9 | case class Foo(
10 | id: Long,
11 | name: String,
12 | age: Int,
13 | amount: Float,
14 | isX: Boolean,
15 | opt: Option[Double],
16 | abs: Option[String],
17 | numbers: List[Int],
18 | map: Map[String, Short]
19 | )
20 |
21 | implicit object FooXmlF extends XmlConverter[Foo] {
22 | def read(x: xml.NodeSeq): Option[Foo] = {
23 | for (
24 | foo <- (x \ "foo").headOption;
25 | id <- Xml.fromXml[Long](foo \ "id");
26 | name <- Xml.fromXml[String](foo \ "name");
27 | age <- Xml.fromXml[Int](foo \ "age");
28 | amount <- Xml.fromXml[Float](foo \ "amount");
29 | isX <- Xml.fromXml[Boolean](foo \ "isX");
30 | opt <- Xml.fromXml[Option[Double]](foo \ "opt");
31 | abs <- Xml.fromXml[Option[String]](foo \ "abs");
32 | numbers <- Xml.fromXml[List[Int]](foo \ "numbers" \ "nb");
33 | map <- Xml.fromXml[Map[String, Short]](foo \ "map" \ "item")
34 | ) yield Foo(id, name, age, amount, isX, opt, abs, numbers, map)
35 | }
36 |
37 | def write(f: Foo, base: xml.NodeSeq): xml.NodeSeq = {
38 |
39 | {f.id}
40 | {f.name}
41 | {f.age}
42 | {f.amount}
43 | {f.isX}
44 | {Xml.toXml(f.opt, )}
45 | {Xml.toXml(f.abs, )}
46 | {Xml.toXml(f.numbers, )}
47 |
48 |
49 | }
50 | }
51 |
52 | val testObject = Foo(
53 | 1234L,
54 | "albert",
55 | 23,
56 | 123.456f,
57 | isX = true,
58 | Some(987.654),
59 | None,
60 | List(123, 57),
61 | Map("alpha" -> 23.toShort, "beta" -> 87.toShort)
62 | )
63 |
64 | val testNs = NamespaceBinding(
65 | prefix = "test",
66 | uri = "http://test.com/",
67 | parent = SOAP.SoapNS
68 | )
69 |
70 | val testSoapMessage =
71 |
72 |
73 |
74 |
75 | 1234
76 | albert
77 | 23
78 | 123.456
79 | true
80 | 987.654
81 |
82 |
83 | 123
84 | 57
85 |
86 |
90 |
91 |
92 |
93 |
94 | "SOAP" should {
95 | "serialize SOAP" in {
96 | SOAP.toSoap(
97 | testObject,
98 | testNs
99 | ) must beEqualTo(
100 | testSoapMessage
101 | ).ignoreSpace
102 | }
103 |
104 | "deserialize SOAP" in {
105 | SOAP.fromSOAP[Foo](
106 | testSoapMessage
107 | ) must equalTo(Some(testObject)).ignoreSpace
108 | }
109 |
110 | "deserialize SOAP to None if error" in {
111 | SOAP.fromSOAP[Foo](
112 |
113 | 1234
114 | 123
115 | fd
116 | float
117 | true
118 |
119 | ) must equalTo(None)
120 | }
121 |
122 | "deserialize SOAP fault that it previously generated" in {
123 | val message = SOAP.toSoap(
124 | SoapFault(
125 | faultcode = SoapFault.FaultCode.Server,
126 | faultstring = "Super error",
127 | faultactor = "http://uriToError.com",
128 | detail = "erreur"
129 | )
130 | )
131 | val fault = SOAP.fromSOAP[SoapFault[String]](message)
132 | fault must beSome
133 | fault.get.faultcode must equalTo(SoapFault.FaultCode.Server)
134 | fault.get.faultstring must equalTo("Super error")
135 | }
136 |
137 | "return None if faultcode parameter is missing" in {
138 | val soapMessage =
139 |
140 |
141 |
142 | 2
143 | 3
144 | Message
145 |
146 |
147 |
148 | val res = SOAP.fromSOAP[SoapFault[String]](soapMessage)
149 | res must beNone
150 | }
151 | "return None if faultstring parameter is missing" in {
152 | val soapMessage =
153 |
154 |
155 |
156 | 1
157 | 3
158 | Message
159 |
160 |
161 |
162 | val res = SOAP.fromSOAP[SoapFault[String]](soapMessage)
163 | res must beNone
164 | }
165 | "return None if faultactor parameter is missing" in {
166 | val soapMessage =
167 |
168 |
169 |
170 | 1
171 | 2
172 |
173 | Message
174 |
175 |
176 |
177 |
178 | val res = SOAP.fromSOAP[SoapFault[String]](soapMessage)
179 | res must beNone
180 | }
181 | "return None if detail parameter is missing" in {
182 | val soapMessage =
183 |
184 |
185 |
186 | 1
187 | 2
188 | 3
189 |
190 |
191 |
192 | val res = SOAP.fromSOAP[SoapFault[String]](soapMessage)
193 | res must beNone
194 | }
195 |
196 | "deserialize SOAP fault generated by third party" in {
197 | case class ComplexObject(param1: String, param2: String)
198 | implicit object ComplexObjectReader extends XmlReader[ComplexObject] {
199 | def read(x: xml.NodeSeq): Option[ComplexObject] = {
200 | for (
201 | msg <- (x \ "message").headOption;
202 | param1 <- Xml.fromXml[String](msg \ "param1");
203 | param2 <- Xml.fromXml[String](msg \ "param2")
204 | ) yield ComplexObject(param1, param2)
205 | }
206 | }
207 |
208 | val soapMessage =
209 |
210 |
211 |
212 | 1
213 | 2
214 | 3
215 |
216 |
217 | Textual information
218 | More information
219 |
220 |
221 |
222 |
223 |
224 |
225 | val fault = SOAP.fromSOAP[SoapFault[ComplexObject]](soapMessage)
226 | fault must beSome
227 | fault.get.faultcode must equalTo("1")
228 | fault.get.detail.param1 must equalTo("Textual information")
229 | fault.get.detail.param2 must equalTo("More information")
230 | }
231 | }
232 | }
233 |
--------------------------------------------------------------------------------
/scala-soap/src/test/scala/XmlSpec.scala:
--------------------------------------------------------------------------------
1 | import org.specs2.mutable._
2 | import com.sandinh.xml.{XmlConverter, Xml}
3 | import com.sandinh.soap.DefaultImplicits._
4 |
5 | class XmlSpec extends Specification {
6 | case class Foo(
7 | id: Long,
8 | name: String,
9 | age: Int,
10 | amount: Float,
11 | isX: Boolean,
12 | opt: Option[Double],
13 | numbers: List[Int],
14 | map: Map[String, Short]
15 | )
16 |
17 | implicit object FooXmlF extends XmlConverter[Foo] {
18 | def read(x: xml.NodeSeq): Option[Foo] = {
19 | for (
20 | id <- Xml.fromXml[Long](x \ "id");
21 | name <- Xml.fromXml[String](x \ "name");
22 | age <- Xml.fromXml[Int](x \ "age");
23 | amount <- Xml.fromXml[Float](x \ "amount");
24 | isX <- Xml.fromXml[Boolean](x \ "isX");
25 | opt <- Xml.fromXml[Option[Double]](x \ "opt");
26 | numbers <- Xml.fromXml[List[Int]](x \ "numbers" \ "nb");
27 | map <- Xml.fromXml[Map[String, Short]](x \ "map" \ "item")
28 | ) yield Foo(id, name, age, amount, isX, opt, numbers, map)
29 | }
30 |
31 | def write(f: Foo, base: xml.NodeSeq): xml.NodeSeq = {
32 |
33 | {f.id}
34 | {f.name}
35 | {f.age}
36 | {f.amount}
37 | {f.isX}
38 | {Xml.toXml(f.opt, )}
39 | {Xml.toXml(f.numbers, )}
40 |
41 |
42 | }
43 | }
44 |
45 | "Xml" should {
46 | "serialize XML" in {
47 | Xml.toXml(
48 | Foo(
49 | 1234L,
50 | "albert",
51 | 23,
52 | 123.456f,
53 | isX = true,
54 | None,
55 | List(123, 57),
56 | Map("alpha" -> 23.toShort, "beta" -> 87.toShort)
57 | )
58 | ) must beEqualTo(
59 |
60 | 1234
61 | albert
62 | 23
63 | 123.456
64 | true
65 |
66 |
67 | 123
68 | 57
69 |
70 |
74 |
75 | ).ignoreSpace
76 | }
77 |
78 | "deserialize XML with option nil=true" in {
79 | Xml.fromXml[Foo](
80 |
81 | 1234
82 | albert
83 | 23
84 | 123.456
85 | true
86 |
87 |
88 | 123
89 | 57
90 |
91 |
95 |
96 | ) must beSome(
97 | Foo(
98 | 1234L,
99 | "albert",
100 | 23,
101 | 123.456f,
102 | isX = true,
103 | None,
104 | List(123, 57),
105 | Map("alpha" -> 23.toShort, "beta" -> 87.toShort)
106 | )
107 | )
108 | }
109 |
110 | "deserialize XML" in {
111 | Xml.fromXml[Foo](
112 |
113 | 1234
114 | albert
115 | 23
116 | 123.456
117 | true
118 |
119 | 123
120 | 57
121 |
122 |
126 |
127 | ) must beSome(
128 | Foo(
129 | 1234L,
130 | "albert",
131 | 23,
132 | 123.456f,
133 | isX = true,
134 | None,
135 | List(123, 57),
136 | Map("alpha" -> 23.toShort, "beta" -> 87.toShort)
137 | )
138 | )
139 | }
140 |
141 | "deserialize XML to None if error" in {
142 | Xml.fromXml[Foo](
143 |
144 | 1234
145 | 123
146 | fd
147 | float
148 | true
149 |
150 | ) must beNone
151 | }
152 |
153 | "deserialize Int accordingly to Some or None" in {
154 | Xml.fromXml[Int](123 ) must beSome(123)
155 | Xml.fromXml[Int](abc ) must beNone
156 | Xml.fromXml[Int](12 \\ "tag") must beNone
157 | Xml.fromXml[Int]( ) must beNone
158 | Xml.fromXml[Int]( ) must beNone
159 | Xml.fromXml[Int]( ) must beNone
160 | }
161 |
162 | "deserialize Short accordingly to Some or None" in {
163 | Xml.fromXml[Short](123 ) must beSome(123)
164 | Xml.fromXml[Short](abc ) must beNone
165 | Xml.fromXml[Short](12 \\ "tag") must beNone
166 | }
167 |
168 | "deserialize Long accordingly to Some or None" in {
169 | Xml.fromXml[Long](123 ) must beSome(123)
170 | Xml.fromXml[Long](abc ) must beNone
171 | Xml.fromXml[Long](12 \\ "tag") must beNone
172 | }
173 |
174 | "deserialize Float accordingly to Some or None" in {
175 | Xml.fromXml[Float](123 ) must beSome(123)
176 | Xml.fromXml[Float](abc ) must beNone
177 | Xml.fromXml[Float](12 \\ "tag") must beNone
178 | }
179 | "deserialize Double accordingly to Some or None" in {
180 | Xml.fromXml[Double](123 ) must beSome(123)
181 | Xml.fromXml[Double](abc ) must beNone
182 | Xml.fromXml[Double](12 \\ "tag") must beNone
183 | Xml.fromXml[Double]( ) must beNone
184 | Xml.fromXml[Double]( ) must beNone
185 | Xml.fromXml[Double]( ) must beNone
186 | }
187 | "deserialize Boolean accordingly to Some or None" in {
188 | Xml.fromXml[Boolean](true ) must beSome(true)
189 | Xml.fromXml[Boolean](abc ) must beNone
190 | Xml.fromXml[Boolean](12 \\ "tag") must beNone
191 | Xml.fromXml[Boolean]( ) must beNone
192 | Xml.fromXml[Boolean]( ) must beNone
193 | }
194 |
195 | "deserialize String accordingly to Some or None" in {
196 | Xml.fromXml[String](text ) must beSome("text")
197 | Xml.fromXml[String](<text> ) must beSome("")
198 | Xml.fromXml[String]( ) must beSome(" ")
199 | Xml.fromXml[String]( ) must beSome("")
200 | Xml.fromXml[String]( ) must beSome("")
201 | Xml.fromXml[String]( \ "nb") must beNone
202 | }
203 |
204 | "deserialize List accordingly to Some empty or nonEmpty List, but not None" in {
205 | Xml.fromXml[List[Int]](12357 \ "nb") must beSome(
206 | List(123, 57)
207 | )
208 | Xml.fromXml[List[String]](
209 | 12357 \ "nb"
210 | ) must beSome(List("123", "57"))
211 | Xml.fromXml[List[String]]( \ "nb") must beSome(List.empty[String])
212 | Xml.fromXml[List[String]]( ) must beSome(List(" "))
213 | Xml.fromXml[List[String]]() must beSome(List(""))
214 | }
215 |
216 | "deserialize Map accordingly to Some empty or nonEmpty Map, but not None" in {
217 | Xml.fromXml[Map[String, Int]](
218 | - alpha23
\ "item"
219 | ) must beSome(Map("alpha" -> 23))
220 | Xml.fromXml[Map[String, Int]](
221 | alpha23
222 | ) must beSome(Map("alpha" -> 23))
223 | Xml.fromXml[Map[String, Int]]( \ "item") must beSome(
224 | Map.empty[String, Int]
225 | )
226 | Xml.fromXml[Map[String, Int]]() must beSome(Map.empty[String, Int])
227 | Xml.fromXml[Map[String, Int]]( ) must beSome(
228 | Map.empty[String, Int]
229 | )
230 | }
231 | }
232 | }
233 |
--------------------------------------------------------------------------------