diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 31349fc..0000000 --- a/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -*.class - -# Package Files # -*.jar -*.war -*.ear - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# IntelliJ IDEA -.idea -*.iml - -# Maven -target -pom.xml.versionsBackup diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b18f8a4..0000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: java -jdk: - - oraclejdk8 -sudo: false -install: true -addons: - sonarqube: - organization: "microbule" - token: - secure: "D5oe//hLttzWg/jD/kVtPlNffe03iZS8oNgss6viose5cPGU8Q5OPgXUqdXP3sbn4q0j7CQya7p/lUrm1rGlF/n9+5izCz+mn8CmZo8kbWPECZEqF4YYYEKYmve4AhYKqigSQn6ped21YWz7jKtp5ubRSgRu1Vj2Dz6TpNOQr+w40zNq5yb2QyOetCQfA69jFavGEUvD7i1HazZvg2YNDwGwOkIRaXdGV1lkvmMU4cZol5LzbSraWFhfe9amKf9alrz0xQ0JHGIJBUMKxmUjm7Jfn9MVwYMyelinQuWgRqHxsK2tBwrAWtJQCH+UPtI7khNiMmr8xwKO6pnS5gsse/iCRMyhdRdjWAnapHWdHfDLbZZaR48wpXf/bPoAC+KLdPWwC66rCMgC+Se0FseVnoOYcFVur+Jbou5+/VMv1THLDT7X8lRd7ZaT6DVDkBaNxYG440r4u8C0zeMOIekD5CZuog6uOxzfFDwxvU0059nWoLotweCDZ7Y2Y5o891wEE8q+nLqg37t1CQKM8yTRwPydPHPw83jkcys8sQvbNuJ3JQsSOxEHHe0O86R50odWGGPLNnjwaq9G1v/VMPJF/SGnTKjKaPNkdt0Us44EeAxPgnr6FvIxujIstJYNxaL3dgoWCUwFAsWonJwxetgX3ZS3HTjaNRq5tdVGc8j6ZpI=" - apt: - packages: - - oracle-java8-installer -script: - - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -cache: - directories: - - '$HOME/.m2/repository' - - '$HOME/.sonar/cache' -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/bb01c18989c38844789e - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: change # options: [always|never|change] default: always diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 8dada3e..0000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.md b/README.md deleted file mode 100644 index d88699d..0000000 --- a/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Microbule - -[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.microbule/microbule-parent/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.microbule/microbule-parent) -[![Javadocs](https://javadoc.io/badge/org.microbule/microbule-parent.svg)](https://javadoc.io/doc/Microbule/microbule) -[![Build Status](https://travis-ci.org/Microbule/microbule.svg?branch=master)](https://travis-ci.org/Microbule/microbule) -[![Quality Gate](https://sonarqube.com/api/badges/gate?key=org.microbule:microbule-parent)](https://sonarqube.com/dashboard?id=org.microbule%3Amicrobule-parent) -[![Coverage](https://sonarqube.com/api/badges/measure?key=org.microbule:microbule-parent&metric=coverage)](https://sonarqube.com/dashboard?id=org.microbule%3Amicrobule-parent) -[![Tech Debt](https://sonarqube.com/api/badges/measure?key=org.microbule:microbule-parent&metric=sqale_debt_ratio)](https://sonarqube.com/dashboard?id=org.microbule%3Amicrobule-parent) -[![License](http://img.shields.io/:license-apache-brightgreen.svg)](http://www.apache.org/licenses/LICENSE-2.0.html) -[![Gitter chat](https://img.shields.io/gitter/room/nwjs/nw.js.svg)](https://gitter.im/Microbule/Lobby) - -Microbule provides a framework for developing [Microservices](http://www.martinfowler.com/articles/microservices.html) -quickly and easily! Services are written using the standard - [Java API for RESTful Services](https://jax-rs-spec.java.net/) (JAX-RS). - -## Table of Contents - -- [Documentation](#documentation) -- [Building](#building-microbule) -- [Support](#support) -- [Community](#community) -- [Contributing](#contributing) -- [License](#license) -- [What's in a Name?](#whats-in-a-name) - -## Documentation - -Visit our [Documentation](https://microbule.github.io/microbule/)! - -## Building Microbule - -1. Clone the Git repository from GitHub: - -```text -git clone git@github.com:Microbule/microbule.git -``` - -2. Build Microbule Using [Apache Maven](http://maven.apache.org): - -```text -mvn clean install -``` - -## Support - -Please [open an issue](https://github.com/Microbule/microbule/issues/new) for support. - -## Community - -Please join us on [Gitter](https://gitter.im/Microbule/Lobby)! - -## Contributing - -Please contribute using [Github Flow](https://guides.github.com/introduction/flow/). Create a branch, add commits, and [open a pull request](https://github.com/Microbule/microbule/compare). - -## License - -Microbule is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). - -## What's in a Name? - -A "microbule" is a unit of length used in Marvel's -[Guardians of the Galaxy](http://marvel.com/characters/70/guardians_of_the_galaxy) movie (the lineup scene). Microbule strives to be the -microservices framework that the others will try to measure up to! diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..f40c0c3 --- /dev/null +++ b/_config.yml @@ -0,0 +1,8 @@ +title: Microbule +description: Making Microservices Fun and Easy! +google_analytics: +show_downloads: false +theme: jekyll-theme-cayman + +gems: + - jekyll-mentions diff --git a/all/pom.xml b/all/pom.xml deleted file mode 100644 index 260dfca..0000000 --- a/all/pom.xml +++ /dev/null @@ -1,185 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-all - Microbule :: All - - - - - org.microbule - microbule-core - 0.3.0-SNAPSHOT - - - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - - - org.microbule - microbule-errormap-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-mapper - 0.3.0-SNAPSHOT - - - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-time - 0.3.0-SNAPSHOT - - - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - - - - - org.microbule - microbule-metrics-core - 0.3.0-SNAPSHOT - - - - - org.microbule - microbule-cache-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-circuitbreaker-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-cors-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gzip-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-logging-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-requestlog-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-swagger-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-timeout-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-tracer-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-validation-decorator - 0.3.0-SNAPSHOT - - - org.microbule - microbule-version-decorator - 0.3.0-SNAPSHOT - - - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http-hc - ${cxf.version} - - - diff --git a/annotation/pom.xml b/annotation/pom.xml deleted file mode 100644 index c462e5e..0000000 --- a/annotation/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-annotation - Microbule :: Annotation - bundle - - diff --git a/annotation/src/main/java/org/microbule/annotation/JaxrsService.java b/annotation/src/main/java/org/microbule/annotation/JaxrsService.java deleted file mode 100644 index 442d86d..0000000 --- a/annotation/src/main/java/org/microbule/annotation/JaxrsService.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface JaxrsService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String name() default ""; - - String serverAddress() default ""; -} diff --git a/annotation/src/main/java/org/microbule/annotation/Startup.java b/annotation/src/main/java/org/microbule/annotation/Startup.java deleted file mode 100644 index 2912a65..0000000 --- a/annotation/src/main/java/org/microbule/annotation/Startup.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.microbule.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.inject.Qualifier; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Qualifier -public @interface Startup { -} diff --git a/api/pom.xml b/api/pom.xml deleted file mode 100644 index 5238ab6..0000000 --- a/api/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-api - Microbule :: API - bundle - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - diff --git a/api/src/main/java/org/microbule/api/JaxrsConfigService.java b/api/src/main/java/org/microbule/api/JaxrsConfigService.java deleted file mode 100644 index bc18a96..0000000 --- a/api/src/main/java/org/microbule/api/JaxrsConfigService.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.api; - -import org.microbule.config.api.Config; - -public interface JaxrsConfigService { - - Config createConfig(String... path); - - Config createServerConfig(Class serviceInterface, String serviceName); - - Config createProxyConfig(Class serviceInterface, String serviceName); -} diff --git a/api/src/main/java/org/microbule/api/JaxrsProxyFactory.java b/api/src/main/java/org/microbule/api/JaxrsProxyFactory.java deleted file mode 100644 index bb77530..0000000 --- a/api/src/main/java/org/microbule/api/JaxrsProxyFactory.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.api; - -public interface JaxrsProxyFactory { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - - - /** - * Creates a JAX-RS proxy which supports the JAX-RS annotated serviceInterface. - * - * @param serviceInterface the service interface - * @param the proxy type - * @return the - */ - T createProxy(Class serviceInterface); -} diff --git a/api/src/main/java/org/microbule/api/JaxrsProxyReference.java b/api/src/main/java/org/microbule/api/JaxrsProxyReference.java deleted file mode 100644 index c14e047..0000000 --- a/api/src/main/java/org/microbule/api/JaxrsProxyReference.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.api; - -@FunctionalInterface -public interface JaxrsProxyReference { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - T get(); -} diff --git a/api/src/main/java/org/microbule/api/JaxrsServer.java b/api/src/main/java/org/microbule/api/JaxrsServer.java deleted file mode 100644 index 5a1ff7a..0000000 --- a/api/src/main/java/org/microbule/api/JaxrsServer.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.api; - -@FunctionalInterface -public interface JaxrsServer { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Shuts down the JAX-RS server. - */ - void shutdown(); -} diff --git a/api/src/main/java/org/microbule/api/JaxrsServerFactory.java b/api/src/main/java/org/microbule/api/JaxrsServerFactory.java deleted file mode 100644 index 2dafe07..0000000 --- a/api/src/main/java/org/microbule/api/JaxrsServerFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.api; - -public interface JaxrsServerFactory { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Creates a new JAX-RS server - * - * @param serviceInterface the service interface - * @param serviceImplementation the service implementation object - * @return the server - */ - JaxrsServer createJaxrsServer(Class serviceInterface, Object serviceImplementation); -} diff --git a/cache.md b/cache.md new file mode 100644 index 0000000..817e48f --- /dev/null +++ b/cache.md @@ -0,0 +1,46 @@ +# Cache-Control + +Microbule will automatically manage the *Cache-Control* headers for you. Each method annotated with @Cacheable will +yield a *Cache-Control* header. For example, consider the following method: + + ``` + @GET + @Produces(MediaType.TEXT_PLAIN) + @Path("/value") + @Cacheable(maxAge = 600) + String getValue(); + ``` + +When executed, the *Cache-Control* header will contain: + + ``` + Cache-Control=[no-transform,max-age=600] + ``` + +Microbule will also manage the *ETag* and *Last-Modified* headers for you. You can provide these values by using a +JAX-RS Response object: + + ``` + public Response createResponse() { + return Response.ok("payload").lastModified(new Date()).build(); + } + ``` + +or by injecting a *ResourceState* object, using the @Context annotation: + + ``` + public class CacheResourceImpl implements CacheResource { + + @Context + private ResourceState resourceState; + + @Override + public String getValueWithEtag() { + resourceState.setEntityTag("12345"); + return "payload"; + } + } + ``` + +When an *ETag* or *Last-Modified* value is provided, Microbule will check the *If-None-Match* and *If-Modified-Since* +headers correspondingly. If the resource is up-to-date, Microbule will return a "No Content" (204) response. diff --git a/cache/annnotation/pom.xml b/cache/annnotation/pom.xml deleted file mode 100644 index bf47880..0000000 --- a/cache/annnotation/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-cache-parent - 0.3.0-SNAPSHOT - - - microbule-cache-annotation - Microbule :: Cache :: Annotation - bundle - - diff --git a/cache/annnotation/src/main/java/org/microbule/cache/annotation/Cacheable.java b/cache/annnotation/src/main/java/org/microbule/cache/annotation/Cacheable.java deleted file mode 100644 index 469d620..0000000 --- a/cache/annnotation/src/main/java/org/microbule/cache/annotation/Cacheable.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Cacheable { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - int maxAge() default -1; - - boolean mustRevalidate() default false; - - boolean noCache() default false; - - String[] noCacheFields() default {}; - - boolean noStore() default false; - - boolean noTransform() default true; - - String[] privateFields() default {}; - - boolean privateFlag() default false; - - boolean proxyRevalidate() default false; - - int sMaxAge() default -1; -} diff --git a/cache/decorator/pom.xml b/cache/decorator/pom.xml deleted file mode 100644 index 40ad5fe..0000000 --- a/cache/decorator/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-cache-parent - 0.3.0-SNAPSHOT - - - microbule-cache-decorator - Microbule :: Cache :: Decorator - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-cache-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheDynamicFeature.java b/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheDynamicFeature.java deleted file mode 100644 index 0146bb0..0000000 --- a/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheDynamicFeature.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.stream.Collectors; - -import javax.ws.rs.GET; -import javax.ws.rs.container.ResourceInfo; -import javax.ws.rs.core.FeatureContext; -import javax.ws.rs.ext.Provider; - -import org.microbule.cache.annotation.Cacheable; -import org.microbule.util.jaxrs.AnnotationDrivenDynamicFeature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Provider -public class CacheDynamicFeature extends AnnotationDrivenDynamicFeature { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(CacheDynamicFeature.class); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void configure(Cacheable annotation, ResourceInfo resourceInfo, FeatureContext featureContext) { - final Method method = resourceInfo.getResourceMethod(); - getAnnotation(method, GET.class).ifPresent(get -> { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding cache filter to method {}({})...", resourceInfo.getResourceMethod().getName(), Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", "))); - } - featureContext.register(new ContainerCacheFilter(annotation)); - }); - } -} diff --git a/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheInfoProvider.java b/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheInfoProvider.java deleted file mode 100644 index 502062c..0000000 --- a/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheInfoProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator; - -import javax.ws.rs.ext.Provider; - -import org.apache.cxf.jaxrs.ext.ContextProvider; -import org.apache.cxf.message.Message; -import org.microbule.cache.decorator.state.DefaultResourceState; -import org.microbule.cache.decorator.state.ResourceState; - -@Provider -public class CacheInfoProvider implements ContextProvider { -//---------------------------------------------------------------------------------------------------------------------- -// ContextProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public ResourceState createContext(Message message) { - return new DefaultResourceState(message); - } -} diff --git a/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheServerDecorator.java b/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheServerDecorator.java deleted file mode 100644 index d8e9d4d..0000000 --- a/cache/decorator/src/main/java/org/microbule/cache/decorator/CacheServerDecorator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("cacheServerDecorator") -public class CacheServerDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new CacheDynamicFeature()); - descriptor.addProvider(new CacheInfoProvider()); - } - - @Override - public String name() { - return "cache"; - } -} diff --git a/cache/decorator/src/main/java/org/microbule/cache/decorator/ContainerCacheFilter.java b/cache/decorator/src/main/java/org/microbule/cache/decorator/ContainerCacheFilter.java deleted file mode 100644 index 653987f..0000000 --- a/cache/decorator/src/main/java/org/microbule/cache/decorator/ContainerCacheFilter.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Date; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.CacheControl; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import org.apache.commons.lang3.ObjectUtils; -import org.apache.cxf.jaxrs.utils.HttpUtils; -import org.microbule.cache.annotation.Cacheable; -import org.microbule.cache.decorator.state.ResourceState; - -@Provider -public class ContainerCacheFilter implements ContainerResponseFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final CacheControl cacheControl; - - @Context - private ResourceState resourceState; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ContainerCacheFilter(Cacheable cacheable) { - this.cacheControl = createCacheControl(cacheable); - } - - private static CacheControl createCacheControl(Cacheable cacheable) { - CacheControl cacheControl = new CacheControl(); - cacheControl.setMaxAge(cacheable.maxAge()); - cacheControl.setMustRevalidate(cacheable.mustRevalidate()); - cacheControl.setNoCache(cacheable.noCache()); - cacheControl.setNoStore(cacheable.noStore()); - cacheControl.setNoTransform(cacheable.noTransform()); - cacheControl.setPrivate(cacheable.privateFlag()); - cacheControl.setProxyRevalidate(cacheable.proxyRevalidate()); - cacheControl.setSMaxAge(cacheable.sMaxAge()); - cacheControl.getNoCacheFields().addAll(Arrays.asList(cacheable.noCacheFields())); - cacheControl.getPrivateFields().addAll(Arrays.asList(cacheable.privateFields())); - return cacheControl; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerResponseFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - - final EntityTag entityTag = getEntityTag(responseContext); - final Date lastModified = getLastModified(responseContext); - - responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cacheControl); - writeHeader(responseContext, HttpHeaders.ETAG, entityTag); - writeHeader(responseContext, HttpHeaders.LAST_MODIFIED, lastModified == null ? null : HttpUtils.getHttpDateFormat().format(lastModified)); - - final Response.ResponseBuilder builder = evaluatePreconditions(requestContext, entityTag, lastModified); - if (builder != null) { - responseContext.setStatusInfo(Response.Status.NO_CONTENT); - responseContext.setEntity(null); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private Response.ResponseBuilder evaluatePreconditions(ContainerRequestContext request, EntityTag etag, Date lastModified) { - if (etag != null && lastModified != null) { - return request.getRequest().evaluatePreconditions(lastModified, etag); - } else if (etag != null) { - return request.getRequest().evaluatePreconditions(etag); - } else if (lastModified != null) { - return request.getRequest().evaluatePreconditions(lastModified); - } else { - return null; - } - } - - private EntityTag getEntityTag(ContainerResponseContext response) { - return ObjectUtils.defaultIfNull(resourceState.getEntityTag(), response.getEntityTag()); - } - - private Date getLastModified(ContainerResponseContext response) { - return ObjectUtils.defaultIfNull(resourceState.getLastModified(), response.getLastModified()); - } - - private void writeHeader(ContainerResponseContext response, String name, Object value) { - if (value == null) { - response.getHeaders().remove(name); - } else { - response.getHeaders().putSingle(name, value); - } - } -} diff --git a/cache/decorator/src/main/java/org/microbule/cache/decorator/state/DefaultResourceState.java b/cache/decorator/src/main/java/org/microbule/cache/decorator/state/DefaultResourceState.java deleted file mode 100644 index 7a213e4..0000000 --- a/cache/decorator/src/main/java/org/microbule/cache/decorator/state/DefaultResourceState.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator.state; - -import java.util.Date; - -import javax.ws.rs.core.EntityTag; - -import org.apache.cxf.message.Message; - -public class DefaultResourceState implements ResourceState { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String ENTITY_TAG_KEY = "ResourceState.entityTag"; - private static final String LAST_MODIFIED_KEY = "ResourceState.lastModified"; - private final Message message; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DefaultResourceState(Message message) { - this.message = message; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ResourceState Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public EntityTag getEntityTag() { - return (EntityTag) message.get(ENTITY_TAG_KEY); - } - - @Override - public Date getLastModified() { - return (Date) message.get(LAST_MODIFIED_KEY); - } - - @Override - public void setEntityTag(EntityTag entityTag) { - message.put(ENTITY_TAG_KEY, entityTag); - } - - @Override - public void setLastModified(Date lastModified) { - message.put(LAST_MODIFIED_KEY, lastModified); - } -} diff --git a/cache/decorator/src/main/java/org/microbule/cache/decorator/state/ResourceState.java b/cache/decorator/src/main/java/org/microbule/cache/decorator/state/ResourceState.java deleted file mode 100644 index 528b92d..0000000 --- a/cache/decorator/src/main/java/org/microbule/cache/decorator/state/ResourceState.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator.state; - -import java.util.Date; - -import javax.ws.rs.core.EntityTag; - -public interface ResourceState { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - void setLastModified(Date lastUpdated); - - void setEntityTag(EntityTag eTag); - - EntityTag getEntityTag(); - - Date getLastModified(); -} diff --git a/cache/decorator/src/main/resources/META-INF/beans.xml b/cache/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/cache/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/cache/decorator/src/main/resources/OSGI-INF/blueprint/microbule-cache-decorator.xml b/cache/decorator/src/main/resources/OSGI-INF/blueprint/microbule-cache-decorator.xml deleted file mode 100644 index 94bad7e..0000000 --- a/cache/decorator/src/main/resources/OSGI-INF/blueprint/microbule-cache-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/cache/decorator/src/test/java/org/microbule/cache/decorator/CacheServerDecoratorTest.java b/cache/decorator/src/test/java/org/microbule/cache/decorator/CacheServerDecoratorTest.java deleted file mode 100644 index f087253..0000000 --- a/cache/decorator/src/test/java/org/microbule/cache/decorator/CacheServerDecoratorTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator; - -import java.time.temporal.ChronoUnit; -import java.util.Date; - -import javax.ws.rs.core.CacheControl; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.apache.cxf.jaxrs.utils.HttpUtils; -import org.junit.Test; -import org.microbule.cache.decorator.resource.CacheResource; -import org.microbule.cache.decorator.resource.CacheResourceImpl; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.server.JaxrsServerTestCase; - -public class CacheServerDecoratorTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new CacheServerDecorator()); - } - - @Override - protected CacheResource createImplementation() { - return new CacheResourceImpl(); - } - - @Test - public void testEmptyResponseWithMatchingEtag() { - final Response response = createWebTarget().path("name").path("etag") - .request(MediaType.TEXT_PLAIN) - .header(HttpHeaders.IF_NONE_MATCH, CacheResource.ENTITY_TAG) - .get(); - assertEquals(204, response.getStatus()); - } - - @Test - public void testEmptyResponseWithUnmodified() { - final Response response = createWebTarget().path("name").path("lastModified") - .request(MediaType.TEXT_PLAIN) - .header(HttpHeaders.IF_MODIFIED_SINCE, HttpUtils.getHttpDateFormat().format(Date.from(CacheResource.LAST_MODIFIED.toInstant().plus(5, ChronoUnit.MINUTES)))) - .get(); - assertEquals(204, response.getStatus()); - } - - @Test - public void testEntityTagSupport() { - final Response response = createWebTarget().path("name").path("etag").request(MediaType.TEXT_PLAIN).get(); - CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); - assertEquals(600, cacheControl.getMaxAge()); - assertTrue(cacheControl.isNoTransform()); - assertFalse(cacheControl.isMustRevalidate()); - final EntityTag entityTag = response.getEntityTag(); - assertNotNull(entityTag); - assertEquals("12345", entityTag.getValue()); - } - - @Test - public void testLastUpdatedAndEtagSupport() { - final Response response = createWebTarget().path("name").path("lastModifiedAndEtag").request(MediaType.TEXT_PLAIN).get(); - CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); - assertEquals(600, cacheControl.getMaxAge()); - assertTrue(cacheControl.isNoTransform()); - assertFalse(cacheControl.isMustRevalidate()); - - Date lastModified = response.getLastModified(); - assertEquals(CacheResource.LAST_MODIFIED, lastModified); - - final EntityTag entityTag = response.getEntityTag(); - assertNotNull(entityTag); - assertEquals("12345", entityTag.getValue()); - } - - @Test - public void testLastUpdatedSupport() { - final Response response = createWebTarget().path("name").path("lastModified").request(MediaType.TEXT_PLAIN).get(); - CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); - assertEquals(600, cacheControl.getMaxAge()); - assertTrue(cacheControl.isNoTransform()); - assertFalse(cacheControl.isMustRevalidate()); - Date lastModified = response.getLastModified(); - assertEquals(CacheResource.LAST_MODIFIED, lastModified); - } - - @Test - public void testWithNoState() { - final Response response = createWebTarget().path("name").path("noState").request(MediaType.TEXT_PLAIN).get(); - CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); - assertEquals(600, cacheControl.getMaxAge()); - assertTrue(cacheControl.isNoTransform()); - assertFalse(cacheControl.isMustRevalidate()); - - assertNull(response.getLastModified()); - assertNull(response.getEntityTag()); - } - - @Test - public void testWithResponse() { - final Response response = createProxy().createResponse(); - CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); - assertEquals(600, cacheControl.getMaxAge()); - assertTrue(cacheControl.isNoTransform()); - assertFalse(cacheControl.isMustRevalidate()); - - Date lastModified = response.getLastModified(); - assertEquals(CacheResource.LAST_MODIFIED, lastModified); - - final EntityTag entityTag = response.getEntityTag(); - assertNotNull(entityTag); - assertEquals("12345", entityTag.getValue()); - } -} \ No newline at end of file diff --git a/cache/decorator/src/test/java/org/microbule/cache/decorator/resource/CacheResource.java b/cache/decorator/src/test/java/org/microbule/cache/decorator/resource/CacheResource.java deleted file mode 100644 index 16879c9..0000000 --- a/cache/decorator/src/test/java/org/microbule/cache/decorator/resource/CacheResource.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator.resource; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Date; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.microbule.cache.annotation.Cacheable; - -@Path("/") -public interface CacheResource { - - Date LAST_MODIFIED = Date.from(Instant.now().truncatedTo(ChronoUnit.MINUTES)); - EntityTag ENTITY_TAG = new EntityTag("12345"); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("/name/etag") - @Cacheable(maxAge = 600) - String getValueWithEtag(); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("/name/lastModified") - @Cacheable(maxAge = 600) - String getValueWithLastModified(); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("/name/lastModifiedAndEtag") - @Cacheable(maxAge = 600) - String getValueWithLastModifiedAndEtag(); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("/name/noState") - @Cacheable(maxAge = 600) - String getValueWithNoState(); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("/createResponse") - @Cacheable(maxAge = 600) - Response createResponse(); -} diff --git a/cache/decorator/src/test/java/org/microbule/cache/decorator/resource/CacheResourceImpl.java b/cache/decorator/src/test/java/org/microbule/cache/decorator/resource/CacheResourceImpl.java deleted file mode 100644 index 0c83366..0000000 --- a/cache/decorator/src/test/java/org/microbule/cache/decorator/resource/CacheResourceImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cache.decorator.resource; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; - -import org.microbule.cache.decorator.state.ResourceState; - -public class CacheResourceImpl implements CacheResource { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Context - private ResourceState resourceState; - -//---------------------------------------------------------------------------------------------------------------------- -// CacheResource Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String getValueWithEtag() { - resourceState.setEntityTag(ENTITY_TAG); - return "ValueWithEtag"; - } - - @Override - public String getValueWithLastModified() { - resourceState.setLastModified(LAST_MODIFIED); - return "ValueWithLastModified"; - } - - @Override - public String getValueWithNoState() { - return "ValueWithNoState"; - } - - @Override - public String getValueWithLastModifiedAndEtag() { - resourceState.setEntityTag(ENTITY_TAG); - resourceState.setLastModified(LAST_MODIFIED); - return "ValueWithLastModifiedAndEtag"; - } - - @Override - public Response createResponse() { - return Response.ok(System.currentTimeMillis()).lastModified(LAST_MODIFIED).tag(ENTITY_TAG).build(); - } -} diff --git a/cache/pom.xml b/cache/pom.xml deleted file mode 100644 index 2721ba0..0000000 --- a/cache/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-cache-parent - Microbule :: Cache :: Parent - pom - - - annnotation - decorator - - diff --git a/cdi.md b/cdi.md new file mode 100644 index 0000000..0a95a33 --- /dev/null +++ b/cdi.md @@ -0,0 +1,34 @@ +# Contexts and Dependency Injection (CDI) + +Microbule is designed to be automatically detected by your CDI container. All of Microbule's components are assigned JSR-330 (_javax.inject_) annotations. First, you'll need to add Microbule to your classpath. + +# Dependencies + +If you are using Maven, simply add the following dependencies to your pom.xml file: + +```xml + + org.microbule + microbule-all + ${microbule.version} + + + + org.microbule + microbule-cdi-container + ${microbule.version} + +``` + +Let's examine these dependencies: + +- **microbule-all**: the Microbule framework with all of the standard plugins. +- **microbule-cdi-container**: the CDI-based *MicrobuleContainer* implementation, which adapts Microbule to CDI. + +You will also need to choose from the available [ConfigurationProviders](configuration.md). + +Once you have these dependencies defined, Microbule will automatically start up once the CDI "application" scope initializes. + +# JAX-RS Service Discovery + +Once Microbule starts, it will automatically create a CXF server for any `@Path`-annotated bean in the current CDI container. diff --git a/cdi/container/pom.xml b/cdi/container/pom.xml deleted file mode 100644 index 05862cb..0000000 --- a/cdi/container/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-cdi-parent - 0.3.0-SNAPSHOT - - - microbule-cdi-container - Microbule :: CDI :: Container - bundle - - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-cdi - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - test - - - diff --git a/cdi/container/src/main/java/org/microbule/cdi/container/CdiContainer.java b/cdi/container/src/main/java/org/microbule/cdi/container/CdiContainer.java deleted file mode 100644 index 9276512..0000000 --- a/cdi/container/src/main/java/org/microbule/cdi/container/CdiContainer.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cdi.container; - -import java.util.stream.Collectors; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Initialized; -import javax.enterprise.context.spi.CreationalContext; -import javax.enterprise.event.Observes; -import javax.enterprise.inject.Instance; -import javax.enterprise.inject.spi.Bean; -import javax.enterprise.inject.spi.BeanManager; -import javax.enterprise.inject.spi.CDI; -import javax.enterprise.util.AnnotationLiteral; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.Path; - -import com.google.common.collect.Lists; -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.microbule.annotation.Startup; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.core.DefaultServerDefinition; -import org.microbule.container.core.StaticContainer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("cdiContainer") -public class CdiContainer extends StaticContainer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(CdiContainer.class); - - @Inject - private BeanManager beanManager; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public void onInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) { - beanManager.getBeans(Object.class, new AnnotationLiteral() { - }).forEach(bean -> { - final CreationalContext context = beanManager.createCreationalContext(bean); - LOGGER.info("Force initializing {}...", beanManager.getReference(bean, bean.getBeanClass(), context).toString()); - }); - initialize(); - } - - @Override - protected Iterable plugins(Class pluginType) { - final Instance plugins = CDI.current().select(pluginType); - return Lists.newArrayList(plugins.iterator()); - } - - @Override - protected Iterable servers() { - return beanManager.getBeans(Object.class).stream() - .flatMap(bean -> ClassUtils.getAllInterfaces(bean.getBeanClass()).stream().map(serviceInterface -> new ImmutablePair<>(bean, serviceInterface))) - .filter(pair -> pair.getRight().isAnnotationPresent(Path.class)) - .map(pair -> { - final Bean bean = pair.getLeft(); - final Object reference = beanManager.getReference(bean, Object.class, beanManager.createCreationalContext(bean)); - return new DefaultServerDefinition(bean.getName(), pair.getRight(), reference); - }).collect(Collectors.toList()); - } -} diff --git a/cdi/container/src/main/java/org/microbule/cdi/container/JaxrsProxyProducer.java b/cdi/container/src/main/java/org/microbule/cdi/container/JaxrsProxyProducer.java deleted file mode 100644 index ac0c51f..0000000 --- a/cdi/container/src/main/java/org/microbule/cdi/container/JaxrsProxyProducer.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.microbule.cdi.container; - -import javax.enterprise.inject.Produces; -import javax.enterprise.inject.spi.InjectionPoint; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.api.JaxrsProxyFactory; -import org.microbule.api.JaxrsProxyReference; -import org.microbule.util.reflect.Types; - -@Named("jaxrsProxyProducer") -@Singleton -public class JaxrsProxyProducer { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Produces - @SuppressWarnings("unchecked") - public JaxrsProxyReference createProxy(InjectionPoint point, JaxrsProxyFactory proxyFactory) { - final Class serviceInterface = Types.getTypeParameter(point.getType(), JaxrsProxyReference.class, 0); - return () -> proxyFactory.createProxy(serviceInterface); - } -} diff --git a/cdi/container/src/test/java/org/microbule/cdi/container/CdiContainerTest.java b/cdi/container/src/test/java/org/microbule/cdi/container/CdiContainerTest.java deleted file mode 100644 index 6b1b18a..0000000 --- a/cdi/container/src/test/java/org/microbule/cdi/container/CdiContainerTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cdi.container; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.junit.Test; -import org.microbule.api.JaxrsProxyReference; -import org.microbule.test.cdi.CdiTestCase; -import org.microbule.test.core.hello.HelloService; - -@Singleton -public class CdiContainerTest extends CdiTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - private Consumer consumer; - - @Inject - private JaxrsProxyReference helloProxy; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testInjectingProxy() { - assertNotNull(helloProxy); - } - - @Test - public void testPlugins() { - assertEquals(1, consumer.getWidgets().size()); - } - - @Test - public void testServers() { - assertEquals(1, consumer.getServerDefinitions().size()); - } -} \ No newline at end of file diff --git a/cdi/container/src/test/java/org/microbule/cdi/container/Consumer.java b/cdi/container/src/test/java/org/microbule/cdi/container/Consumer.java deleted file mode 100644 index f2b2a46..0000000 --- a/cdi/container/src/test/java/org/microbule/cdi/container/Consumer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cdi.container; - -import java.util.LinkedList; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.api.ServerListener; - -@Named("consumer") -@Singleton -public class Consumer implements ServerListener { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final List widgets; - - private final List serverDefinitions = new LinkedList<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public Consumer(MicrobuleContainer container) { - widgets = container.pluginList(Widget.class); - container.addServerListener(this); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ServerListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void registerServer(ServerDefinition serverDefinition) { - serverDefinitions.add(serverDefinition); - } - - @Override - public void unregisterServer(String id) { - serverDefinitions.removeIf(def -> id.equals(def.id())); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public List getServerDefinitions() { - return serverDefinitions; - } - - public List getWidgets() { - return widgets; - } -} diff --git a/cdi/container/src/test/java/org/microbule/cdi/container/SimpleWidget.java b/cdi/container/src/test/java/org/microbule/cdi/container/SimpleWidget.java deleted file mode 100644 index 8cb8ec3..0000000 --- a/cdi/container/src/test/java/org/microbule/cdi/container/SimpleWidget.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cdi.container; - -import javax.inject.Named; -import javax.inject.Singleton; - -@Named("simpleWidget") -@Singleton -public class SimpleWidget implements Widget { -} diff --git a/cdi/container/src/test/java/org/microbule/cdi/container/Widget.java b/cdi/container/src/test/java/org/microbule/cdi/container/Widget.java deleted file mode 100644 index 6c6afde..0000000 --- a/cdi/container/src/test/java/org/microbule/cdi/container/Widget.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cdi.container; - -public interface Widget { - -} diff --git a/cdi/pom.xml b/cdi/pom.xml deleted file mode 100644 index c8d97a0..0000000 --- a/cdi/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-cdi-parent - Microbule :: CDI :: Parent - pom - - - container - - - - - javax.enterprise - cdi-api - ${cdi.version} - provided - - - - diff --git a/cglib/pom.xml b/cglib/pom.xml deleted file mode 100644 index 27cc44e..0000000 --- a/cglib/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-cglib - Microbule :: CGLIB Dynamic Proxy Support - bundle - - - net.sf.cglib.core,,* - - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.cglib - ${cglib.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/cglib/src/main/java/org/microbule/cglib/CglibDynamicProxyStrategy.java b/cglib/src/main/java/org/microbule/cglib/CglibDynamicProxyStrategy.java deleted file mode 100644 index bd03f2f..0000000 --- a/cglib/src/main/java/org/microbule/cglib/CglibDynamicProxyStrategy.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cglib; - -import java.util.function.Supplier; - -import javax.inject.Named; -import javax.inject.Singleton; - -import net.sf.cglib.proxy.Callback; -import net.sf.cglib.proxy.CallbackFilter; -import net.sf.cglib.proxy.Dispatcher; -import net.sf.cglib.proxy.Enhancer; -import net.sf.cglib.proxy.MethodInterceptor; -import org.microbule.spi.JaxrsDynamicProxyStrategy; -import org.microbule.util.proxy.DynamicProxyUtils; -import org.microbule.util.reflect.DelegatingClassLoader; - -@Named("cglibDynamicProxyStrategy") -@Singleton -public class CglibDynamicProxyStrategy implements JaxrsDynamicProxyStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final CallbackFilter FILTER = method -> { - if (DynamicProxyUtils.isEqualsMethod(method)) { - return 1; - } else if (DynamicProxyUtils.isHashCodeMethod(method)) { - return 2; - } else if (DynamicProxyUtils.isToStringMethod(method)) { - return 3; - } else { - return 0; - } - }; - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsDynamicProxyStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public T createDynamicProxy(Class type, Supplier targetSupplier, String descriptionPattern, Object... descriptionParams) { - final String description = String.format(descriptionPattern, descriptionParams); - final Enhancer enhancer = new Enhancer(); - enhancer.setClassLoader(new DelegatingClassLoader(type.getClassLoader(), Enhancer.class.getClassLoader())); - enhancer.setInterfaces(new Class[]{type}); - enhancer.setSuperclass(Object.class); - enhancer.setCallbackFilter(FILTER); - enhancer.setCallbacks(new Callback[]{ - (Dispatcher) targetSupplier::get, - (MethodInterceptor) (proxy, method, params, methodProxy) -> proxy == params[0], - (MethodInterceptor) (proxy, method, params, methodProxy) -> System.identityHashCode(proxy), - (MethodInterceptor) (proxy, method, params, methodProxy) -> description - }); - return type.cast(enhancer.create()); - } -} diff --git a/cglib/src/main/resources/OSGI-INF/blueprint/microbule-cglib.xml b/cglib/src/main/resources/OSGI-INF/blueprint/microbule-cglib.xml deleted file mode 100644 index 7c596be..0000000 --- a/cglib/src/main/resources/OSGI-INF/blueprint/microbule-cglib.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/cglib/src/test/java/org/microbule/cglib/CglibDynamicProxyStrategyTest.java b/cglib/src/test/java/org/microbule/cglib/CglibDynamicProxyStrategyTest.java deleted file mode 100644 index eac60ec..0000000 --- a/cglib/src/test/java/org/microbule/cglib/CglibDynamicProxyStrategyTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cglib; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; - -public class CglibDynamicProxyStrategyTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testEquals() { - final CglibDynamicProxyStrategy strategy = new CglibDynamicProxyStrategy(); - final HelloService proxy1 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - final HelloService proxy2 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - assertEquals(proxy1, proxy1); - assertNotEquals(proxy1, proxy2); - } - - - @Test - public void testToString() { - final CglibDynamicProxyStrategy strategy = new CglibDynamicProxyStrategy(); - final HelloService proxy1 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - assertEquals("my description", proxy1.toString()); - } - - @Test - public void testClassCaching() { - final CglibDynamicProxyStrategy strategy = new CglibDynamicProxyStrategy(); - final HelloService proxy1 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - final HelloService proxy2 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - assertEquals(proxy1.getClass(), proxy2.getClass()); - } - - @Test - public void testHashCode() { - final CglibDynamicProxyStrategy strategy = new CglibDynamicProxyStrategy(); - final HelloService proxy1 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - assertEquals(System.identityHashCode(proxy1), proxy1.hashCode()); - } - - @Test - public void testRegularMethodCall() { - final CglibDynamicProxyStrategy strategy = new CglibDynamicProxyStrategy(); - final HelloService proxy1 = strategy.createDynamicProxy(HelloService.class, HelloServiceImpl::new, "my description"); - assertEquals("Hello, Microbule!", proxy1.sayHello("Microbule")); - } -} \ No newline at end of file diff --git a/circuitbreaker.md b/circuitbreaker.md new file mode 100644 index 0000000..6dc7a2e --- /dev/null +++ b/circuitbreaker.md @@ -0,0 +1,3 @@ +# Circuit Breaker + +Microbule supports the [Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) pattern for client proxies. diff --git a/circuitbreaker/pom.xml b/circuitbreaker/pom.xml deleted file mode 100644 index 418adc9..0000000 --- a/circuitbreaker/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-circuitbreaker-decorator - Microbule :: Circuit Breaker :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/circuitbreaker/src/main/java/org/microbule/circuitbreaker/decorator/CircuitBreakerDecorator.java b/circuitbreaker/src/main/java/org/microbule/circuitbreaker/decorator/CircuitBreakerDecorator.java deleted file mode 100644 index ab2bc31..0000000 --- a/circuitbreaker/src/main/java/org/microbule/circuitbreaker/decorator/CircuitBreakerDecorator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.circuitbreaker.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("circuitBreakerDecorator") -public class CircuitBreakerDecorator implements JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new CircuitBreakerFilter(descriptor, config)); - } - - @Override - public String name() { - return "circuitbreaker"; - } -} diff --git a/circuitbreaker/src/main/java/org/microbule/circuitbreaker/decorator/CircuitBreakerFilter.java b/circuitbreaker/src/main/java/org/microbule/circuitbreaker/decorator/CircuitBreakerFilter.java deleted file mode 100644 index 9eedac7..0000000 --- a/circuitbreaker/src/main/java/org/microbule/circuitbreaker/decorator/CircuitBreakerFilter.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.circuitbreaker.decorator; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import org.apache.commons.lang3.concurrent.CircuitBreaker; -import org.apache.commons.lang3.concurrent.EventCountCircuitBreaker; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Provider -public class CircuitBreakerFilter implements ClientRequestFilter, ClientResponseFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String OPEN_THRESHOLD_PROP = "openThreshold"; - private static final String OPEN_INTERVAL_PROP = "openInterval"; - private static final String OPEN_INTERVAL_UNIT_PROP = "openIntervalUnit"; - - private static final String CLOSE_THRESHOLD_PROP = "closeThreshold"; - private static final String CLOSE_INTERVAL_PROP = "closeInterval"; - private static final String CLOSE_INTERVAL_UNIT_PROP = "closeIntervalUnit"; - - private static final int DEFAULT_OPEN_THRESHOLD = 10; - private static final int DEFUALT_CLOSE_THRESHOLD = 10; - private static final long DEFAULT_OPEN_INTERVAL = 1L; - private static final long DEFAULT_CLOSE_INTERVAL = 1L; - private static final TimeUnit DEFAULT_UNIT = TimeUnit.SECONDS; - - private final CircuitBreaker circuitBreaker; - private final String serviceInterface; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - CircuitBreakerFilter(JaxrsServiceDescriptor descriptor, Config config) { - this.serviceInterface = descriptor.serviceInterface().getSimpleName(); - - final int openThreshold = config.integerValue(OPEN_THRESHOLD_PROP).orElse(DEFAULT_OPEN_THRESHOLD); - final long openInterval = config.longValue(OPEN_INTERVAL_PROP).orElse(DEFAULT_OPEN_INTERVAL); - final TimeUnit openIntervalUnit = config.enumValue(OPEN_INTERVAL_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_UNIT); - - final int closeThreshold = config.integerValue(CLOSE_THRESHOLD_PROP).orElse(DEFUALT_CLOSE_THRESHOLD); - final long closeInterval = config.longValue(CLOSE_INTERVAL_PROP).orElse(DEFAULT_CLOSE_INTERVAL); - final TimeUnit closeIntervalUnit = config.enumValue(CLOSE_INTERVAL_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_UNIT); - - this.circuitBreaker = new EventCountCircuitBreaker(openThreshold, openInterval, openIntervalUnit, closeThreshold, closeInterval, closeIntervalUnit); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ClientRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - if (!circuitBreaker.checkState()) { - requestContext.abortWith(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(String.format("Service %s is currently unavilable.", serviceInterface)).build()); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// ClientResponseFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - if (Response.Status.Family.SERVER_ERROR == responseContext.getStatusInfo().getFamily()) { - circuitBreaker.incrementAndCheckState(1); - } - } -} diff --git a/circuitbreaker/src/main/resources/META-INF/beans.xml b/circuitbreaker/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/circuitbreaker/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/circuitbreaker/src/main/resources/OSGI-INF/blueprint/microbule-circuitbreaker-decorator.xml b/circuitbreaker/src/main/resources/OSGI-INF/blueprint/microbule-circuitbreaker-decorator.xml deleted file mode 100644 index b989761..0000000 --- a/circuitbreaker/src/main/resources/OSGI-INF/blueprint/microbule-circuitbreaker-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/circuitbreaker/src/test/java/org/microbule/circuitbreaker/decorator/CircuitBreakerFilterTest.java b/circuitbreaker/src/test/java/org/microbule/circuitbreaker/decorator/CircuitBreakerFilterTest.java deleted file mode 100644 index 7390764..0000000 --- a/circuitbreaker/src/test/java/org/microbule/circuitbreaker/decorator/CircuitBreakerFilterTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.circuitbreaker.decorator; - -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.ServiceUnavailableException; - -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; -import org.microbule.test.server.hello.HelloTestCase; - -public class CircuitBreakerFilterTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new CircuitBreakerDecorator()); - } - - @Override - protected HelloService createImplementation() { - return new EvilHelloService(); - } - - @Test(expected = ServiceUnavailableException.class) - public void testOpeningCircuitBreaker() { - final HelloService proxy = createProxy(); - for (int i = 0; i < 20; ++i) { - try { - proxy.sayHello("Dr. Evil"); - } catch (InternalServerErrorException e) { - // Ignore! - } - } - proxy.sayHello("Microbule"); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class EvilHelloService extends HelloServiceImpl implements HelloService { -//---------------------------------------------------------------------------------------------------------------------- -// HelloService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String sayHello(String name) { - if ("Dr. Evil".equals(name)) { - throw new InternalServerErrorException("I don't like you!"); - } - return super.sayHello(name); - } - } -} \ No newline at end of file diff --git a/config/annotation/pom.xml b/config/annotation/pom.xml deleted file mode 100644 index b206c49..0000000 --- a/config/annotation/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-annotation - Microbule :: Config :: Annotation - bundle - - - diff --git a/config/annotation/src/main/java/org/microbule/config/annotation/ServiceName.java b/config/annotation/src/main/java/org/microbule/config/annotation/ServiceName.java deleted file mode 100644 index c2814af..0000000 --- a/config/annotation/src/main/java/org/microbule/config/annotation/ServiceName.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface ServiceName { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String value(); -} diff --git a/config/api/pom.xml b/config/api/pom.xml deleted file mode 100644 index 5e07dba..0000000 --- a/config/api/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-api - Microbule :: Config :: API - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/config/api/src/main/java/org/microbule/config/api/Config.java b/config/api/src/main/java/org/microbule/config/api/Config.java deleted file mode 100644 index 55ad760..0000000 --- a/config/api/src/main/java/org/microbule/config/api/Config.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.api; - -import java.util.Optional; -import java.util.function.Function; - -/** - * A Config provides access to configuration values. They values are arranged in a hierarchy - * organized by "paths". - */ -public interface Config { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Get a Boolean value - * - * @param key the value key - * @return the optional Boolean value - */ - default Optional booleanValue(String key) { - return value(key, Boolean::valueOf); - } - - /** - * Get a Double value - * - * @param key the value key - * @return the optional Double value - */ - default Optional doubleValue(String key) { - return value(key, Double::valueOf); - } - - /** - * Get an enum value - * - * @param key the value key - * @param enumType the enum type - * @param the enum type - * @return the optional enum value - */ - default > Optional enumValue(String key, Class enumType) { - return value(key).map(value -> Enum.valueOf(enumType, value)); - } - - /** - * Filter this {@link Config} object using the specified path - * - * @param paths the path - * @return a new {@link Config} object containing only values at the specifed path or below - */ - Config filtered(String... paths); - - /** - * Get an Integer value - * - * @param key the value key - * @return the optional Integer value - */ - default Optional integerValue(String key) { - return value(key, Integer::valueOf); - } - - /** - * Get a Long value - * - * @param key the value key - * @return the optional Long value - */ - default Optional longValue(String key) { - return value(key, Long::valueOf); - } - - /** - * Get a String value - * - * @param key the value key - * @return the optional String value - */ - Optional value(String key); - - /** - * Get a value by converting it to the target type using the specified converter - * - * @param key the value key - * @param converter the converter - * @param the target type - * @return the optional target type value - */ - default Optional value(String key, Function converter) { - return value(key).map(converter); - } -} diff --git a/config/api/src/main/java/org/microbule/config/api/ConfigService.java b/config/api/src/main/java/org/microbule/config/api/ConfigService.java deleted file mode 100644 index 5c66b9e..0000000 --- a/config/api/src/main/java/org/microbule/config/api/ConfigService.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.api; - -public interface ConfigService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Creates a new configuration for the given path. - * @param path the path - * @return the configuration - */ - Config createConfig(String... path); -} diff --git a/config/api/src/main/java/org/microbule/config/api/ConfigurationException.java b/config/api/src/main/java/org/microbule/config/api/ConfigurationException.java deleted file mode 100644 index 0fa97aa..0000000 --- a/config/api/src/main/java/org/microbule/config/api/ConfigurationException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.api; - -import org.microbule.util.exception.MicrobuleException; - -public class ConfigurationException extends MicrobuleException { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ConfigurationException(String message, Object... params) { - super(message, params); - } - - public ConfigurationException(Throwable cause, String message, Object... params) { - super(cause, message, params); - } -} diff --git a/config/api/src/test/java/org/microbule/config/api/ConfigTest.java b/config/api/src/test/java/org/microbule/config/api/ConfigTest.java deleted file mode 100644 index 3a8ffb7..0000000 --- a/config/api/src/test/java/org/microbule/config/api/ConfigTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.api; - -import java.lang.annotation.ElementType; -import java.util.Optional; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class ConfigTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testBooleanValue() { - assertEquals(Boolean.TRUE, new ConstantConfig("true").booleanValue("whatever").get()); - } - - @Test - public void testDoubleValue() { - assertEquals(new Double(123.456), new ConstantConfig("123.456").doubleValue("whatever").get()); - } - - @Test - public void testEnumValue() { - assertEquals(ElementType.METHOD, new ConstantConfig("METHOD").enumValue("whatever", ElementType.class).get()); - } - - @Test - public void testIntegerValue() { - assertEquals(new Integer(123), new ConstantConfig("123").integerValue("whatever").get()); - } - - @Test - public void testLongValue() { - assertEquals(new Long(123), new ConstantConfig("123").longValue("whatever").get()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class ConstantConfig implements Config { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String value; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ConstantConfig(String value) { - this.value = value; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Config Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config filtered(String... paths) { - return this; - } - - @Override - public Optional value(String key) { - return Optional.ofNullable(value); - } - } -} \ No newline at end of file diff --git a/config/api/src/test/java/org/microbule/config/api/ConfigurationExceptionTest.java b/config/api/src/test/java/org/microbule/config/api/ConfigurationExceptionTest.java deleted file mode 100644 index 7d2ac4f..0000000 --- a/config/api/src/test/java/org/microbule/config/api/ConfigurationExceptionTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.api; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class ConfigurationExceptionTest extends MicrobuleTestCase { - - @Test - public void testConstructor() { - final ConfigurationException exception = new ConfigurationException("Hello, %s!", "Microbule"); - assertEquals("Hello, Microbule!", exception.getMessage()); - } - - @Test - public void testConstructorWithCause() { - final IllegalArgumentException cause = new IllegalArgumentException("oops!"); - final ConfigurationException exception = new ConfigurationException(cause, "Hello, %s!", "Microbule"); - assertEquals("Hello, Microbule!", exception.getMessage()); - assertEquals(cause, exception.getCause()); - } -} \ No newline at end of file diff --git a/config/consul/pom.xml b/config/consul/pom.xml deleted file mode 100644 index c4f921b..0000000 --- a/config/consul/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-consul - Microbule :: Config :: Consul - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-decorator - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - test - - - - - diff --git a/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java b/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java deleted file mode 100644 index 0dbbfdc..0000000 --- a/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.consul; - -import java.util.Base64; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.google.common.base.Charsets; -import com.google.gson.reflect.TypeToken; -import org.apache.commons.lang3.StringUtils; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.config.core.EmptyConfig; -import org.microbule.config.core.MapConfig; -import org.microbule.config.spi.ConfigProvider; -import org.microbule.util.jaxrs.WebTargetUtils; - -import static org.microbule.util.jaxrs.WebTargetUtils.extend; - -@Singleton -@Named("consulConfigProvider") -public class ConsulConfigProvider implements ConfigProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String RECURSE_PARAM = "recurse"; - private static final String SEPARATOR = "/"; - private static final String DEFAULT_BASE_ADDRESS = "http://localhost:8500/v1/kv/microbule"; - private static final String BASE_ADDRESS_PROP = "baseAddress"; - private static final String NAME = "consul"; - private static final TypeToken> TYPE_TOKEN = new TypeToken>() { - }; - - private final WebTarget baseTarget; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ConsulConfigProvider() { - this(ConfigUtils.bootstrapConfig(NAME).value(BASE_ADDRESS_PROP).orElse(DEFAULT_BASE_ADDRESS)); - } - - public ConsulConfigProvider(String baseAddress) { - baseTarget = ClientBuilder.newClient().target(baseAddress); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config getConfig(String... path) { - final Response response = extend(baseTarget, path).queryParam(RECURSE_PARAM, Boolean.TRUE).request(MediaType.APPLICATION_JSON_TYPE).get(); - final String keyPath = Stream.of(path).collect(Collectors.joining(SEPARATOR)) + SEPARATOR; - return WebTargetUtils.parseJsonResponse(response, TYPE_TOKEN) - .map(nodes -> nodes.stream().collect(Collectors.toMap(node -> StringUtils.substringAfter(node.getKey(), keyPath), node -> base64Decode(node.getValue())))) - .map(map -> (Config)new MapConfig(map, SEPARATOR)) - .orElse(EmptyConfig.INSTANCE); - } - - @Override - public String name() { - return NAME; - } - - @Override - public int priority() { - return ConfigUtils.PRIORITY_EXTERNAL; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private String base64Decode(String value) { - return new String(Base64.getDecoder().decode(value), Charsets.UTF_8); - } -} diff --git a/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java b/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java deleted file mode 100644 index 4d2c435..0000000 --- a/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.consul; - -import com.google.gson.annotations.SerializedName; - -public class ConsulNode { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @SerializedName("Key") - private final String key; - - @SerializedName("Value") - private final String value; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ConsulNode(String key, String value) { - this.key = key; - this.value = value; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getKey() { - return key; - } - - public String getValue() { - return value; - } -} diff --git a/config/consul/src/main/resources/META-INF/beans.xml b/config/consul/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/config/consul/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/config/consul/src/main/resources/OSGI-INF/blueprint/microbule-config-consul.xml b/config/consul/src/main/resources/OSGI-INF/blueprint/microbule-config-consul.xml deleted file mode 100644 index 3a9b2ee..0000000 --- a/config/consul/src/main/resources/OSGI-INF/blueprint/microbule-config-consul.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java b/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java deleted file mode 100644 index 9c1e25c..0000000 --- a/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.consul; - -import java.io.InputStreamReader; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import com.google.common.base.Charsets; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import org.junit.Before; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; -import org.microbule.test.server.JaxrsServerTestCase; - -public class ConsulConfigProviderTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference> response = new AtomicReference<>(); - private static final TypeToken> TYPE_TOKEN = new TypeToken>() { - }; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new GsonServerDecorator(new DefaultGsonService(container))); - container.addBean(new GsonProxyDecorator(new DefaultGsonService(container))); - } - - @Override - protected MockConsulService createImplementation() { - return new MockConsulServiceImpl(response); - } - - @Before - public void setBaseAddress() { - System.setProperty("microbule.consul.baseAddress", getBaseAddress()); - } - - @Test - public void testGetConfig() { - final ConsulConfigProvider provider = new ConsulConfigProvider(); - assertEquals("consul", provider.name()); - assertEquals(ConfigUtils.PRIORITY_EXTERNAL, provider.priority()); - - response.set(parseResponse("/response.json", TYPE_TOKEN)); - - final Config config = provider.getConfig("one", "two"); - assertEquals("Microbule", config.value("three").get()); - assertEquals("three, sir", config.value("five").get()); - - } - - private T parseResponse(String resourceName, TypeToken type) { - return new Gson().fromJson(new InputStreamReader(getClass().getResourceAsStream(resourceName), Charsets.UTF_8), type.getType()); - } -} \ No newline at end of file diff --git a/config/consul/src/test/java/org/microbule/config/consul/ConsulNodeTest.java b/config/consul/src/test/java/org/microbule/config/consul/ConsulNodeTest.java deleted file mode 100644 index 64c990c..0000000 --- a/config/consul/src/test/java/org/microbule/config/consul/ConsulNodeTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.consul; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class ConsulNodeTest extends MockObjectTestCase { - - @Test - public void testConstructor() { - final ConsulNode node = new ConsulNode("foo", "bar"); - assertEquals("foo", node.getKey()); - assertEquals("bar", node.getValue()); - } -} \ No newline at end of file diff --git a/config/consul/src/test/java/org/microbule/config/consul/MockConsulService.java b/config/consul/src/test/java/org/microbule/config/consul/MockConsulService.java deleted file mode 100644 index 3bba99c..0000000 --- a/config/consul/src/test/java/org/microbule/config/consul/MockConsulService.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.consul; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -@Path("/") -public interface MockConsulService -{ -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @GET - @Path("/{path:.*}") - @Produces(MediaType.APPLICATION_JSON) - List getKeyValues(@PathParam("path") String path); -} diff --git a/config/consul/src/test/java/org/microbule/config/consul/MockConsulServiceImpl.java b/config/consul/src/test/java/org/microbule/config/consul/MockConsulServiceImpl.java deleted file mode 100644 index 1d5c61c..0000000 --- a/config/consul/src/test/java/org/microbule/config/consul/MockConsulServiceImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.consul; - -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -public class MockConsulServiceImpl implements MockConsulService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference> response; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MockConsulServiceImpl(AtomicReference> response) { - this.response = response; - } - -//---------------------------------------------------------------------------------------------------------------------- -// MockConsulService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public List getKeyValues(String path) { - return response.get(); - } -} diff --git a/config/consul/src/test/resources/response.json b/config/consul/src/test/resources/response.json deleted file mode 100644 index 63ab543..0000000 --- a/config/consul/src/test/resources/response.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "LockIndex": 0, - "Key": "one/two/five", - "Flags": 0, - "Value": "dGhyZWUsIHNpcg==", - "CreateIndex": 14, - "ModifyIndex": 14 - }, - { - "LockIndex": 0, - "Key": "one/two/three", - "Flags": 0, - "Value": "TWljcm9idWxl", - "CreateIndex": 11, - "ModifyIndex": 11 - } -] \ No newline at end of file diff --git a/config/core/pom.xml b/config/core/pom.xml deleted file mode 100644 index fcadccb..0000000 --- a/config/core/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-core - Microbule :: Config :: Core - bundle - - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-spi - 0.3.0-SNAPSHOT - - - com.google.code.gson - gson - ${gson.version} - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - - diff --git a/config/core/src/main/java/org/microbule/config/core/AbstractConfig.java b/config/core/src/main/java/org/microbule/config/core/AbstractConfig.java deleted file mode 100644 index 5eb9353..0000000 --- a/config/core/src/main/java/org/microbule/config/core/AbstractConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.microbule.config.api.Config; - -public abstract class AbstractConfig implements Config { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - protected static final String DEFAULT_SEPARATOR = "."; - - private final String groupPrefix; - private final String separator; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public AbstractConfig(String groupPrefix, String separator) { - this.groupPrefix = groupPrefix; - this.separator = separator; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract Config qualifiedConfig(String qualifiedGroupPrefix, String separator); - - protected abstract Optional qualifiedValue(String qualifiedKey); - -//---------------------------------------------------------------------------------------------------------------------- -// Config Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public Config filtered(String... keys) { - return qualifiedConfig(qualify(keys), separator); - } - - @Override - public Optional value(String key) { - return qualifiedValue(qualify(key)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected String qualify(String... keys) { - final String keyPath = keys.length == 0 ? null : Stream.of(keys).collect(Collectors.joining(separator)); - return Optional.ofNullable(groupPrefix).map(prefix -> prefix + separator + keyPath).orElse(keyPath); - } -} diff --git a/config/core/src/main/java/org/microbule/config/core/CompositeConfig.java b/config/core/src/main/java/org/microbule/config/core/CompositeConfig.java deleted file mode 100644 index 43f9131..0000000 --- a/config/core/src/main/java/org/microbule/config/core/CompositeConfig.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.microbule.config.api.Config; - -public class CompositeConfig implements Config { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final List members; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public CompositeConfig(Config... members) { - this(Arrays.asList(members)); - } - - public CompositeConfig(List members) { - this.members = members; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Config Implementation -//---------------------------------------------------------------------------------------------------------------------- - - public static Config create(List members) { - switch (members.size()) { - case 0: - return EmptyConfig.INSTANCE; - case 1: - return members.get(0); - default: - return new CompositeConfig(members); - } - } - - @Override - public Config filtered(String... paths) { - return new CompositeConfig(members.stream().map(config -> config.filtered(paths)).collect(Collectors.toList())); - } - - @Override - public Optional value(String key) { - return members.stream() - .map(member -> member.value(key)) - .filter(Optional::isPresent) - .map(Optional::get) - .findFirst(); - } -} diff --git a/config/core/src/main/java/org/microbule/config/core/ConfigUtils.java b/config/core/src/main/java/org/microbule/config/core/ConfigUtils.java deleted file mode 100644 index 3f16fbe..0000000 --- a/config/core/src/main/java/org/microbule/config/core/ConfigUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.microbule.config.api.Config; - -public final class ConfigUtils { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final int PRIORITY_SYSPROP = -2000; - public static final int PRIORITY_ENV = -1000; - public static final int DEFAULT_PRIORITY = 0; - public static final int PRIORITY_EXTERNAL = 1000; - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static Config bootstrapConfig(String providerName) { - return new CompositeConfig(fromProperties(System.getProperties()), new MapConfig(System.getenv())) - .filtered("microbule", providerName); - } - - public static Config fromProperties(Properties props) { - Map map = new HashMap<>(); - for (String propertyName : props.stringPropertyNames()) { - map.put(propertyName, props.getProperty(propertyName)); - } - return new MapConfig(map); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private ConfigUtils() { - } -} diff --git a/config/core/src/main/java/org/microbule/config/core/DefaultConfigService.java b/config/core/src/main/java/org/microbule/config/core/DefaultConfigService.java deleted file mode 100644 index 1b2e3db..0000000 --- a/config/core/src/main/java/org/microbule/config/core/DefaultConfigService.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.Comparator; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.config.api.ConfigService; -import org.microbule.config.spi.ConfigProvider; -import org.microbule.container.api.MicrobuleContainer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("configService") -public class DefaultConfigService implements ConfigService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultConfigService.class); - - private final Set providers; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultConfigService(MicrobuleContainer container) { - this.providers = container.pluginSortedSet(ConfigProvider.class, Comparator.comparingInt(ConfigProvider::priority)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config createConfig(String... path) { - return CompositeConfig.create(providers.stream().map(provider -> providerConfig(provider, path)).collect(Collectors.toList())); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private Config providerConfig(ConfigProvider provider, String[] path) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Creating configuration using provider \"{}\" at path \"/{}\".", provider.name(), Stream.of(path).collect(Collectors.joining("/"))); - } - return provider.getConfig(path); - } -} diff --git a/config/core/src/main/java/org/microbule/config/core/EmptyConfig.java b/config/core/src/main/java/org/microbule/config/core/EmptyConfig.java deleted file mode 100644 index 3b5202f..0000000 --- a/config/core/src/main/java/org/microbule/config/core/EmptyConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.Optional; - -import org.microbule.config.api.Config; - -public class EmptyConfig implements Config { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final Config INSTANCE = new EmptyConfig(); - -//---------------------------------------------------------------------------------------------------------------------- -// Config Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config filtered(String... paths) { - return this; - } - - @Override - public Optional value(String key) { - return Optional.empty(); - } -} diff --git a/config/core/src/main/java/org/microbule/config/core/MapConfig.java b/config/core/src/main/java/org/microbule/config/core/MapConfig.java deleted file mode 100644 index b54633f..0000000 --- a/config/core/src/main/java/org/microbule/config/core/MapConfig.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import org.microbule.config.api.Config; - -import static java.util.Optional.ofNullable; - -public class MapConfig extends AbstractConfig { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Map values; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MapConfig() { - this(new HashMap<>(), null, DEFAULT_SEPARATOR); - } - - public MapConfig(Map values) { - this(new HashMap<>(values), null, DEFAULT_SEPARATOR); - } - - public MapConfig(Map values, String separator) { - this(new HashMap<>(values), null, separator); - } - - private MapConfig(Map values, String groupPrefix, String separator) { - super(groupPrefix, separator); - this.values = values; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public MapConfig addValue(String key, String value) { - values.put(qualify(key), value); - return this; - } - - @Override - protected Config qualifiedConfig(String qualifiedGroupPrefix, String separator) { - return new MapConfig(values, qualifiedGroupPrefix, separator); - } - - @Override - protected Optional qualifiedValue(String qualifiedKey) { - return ofNullable(values.get(qualifiedKey)); - } -} diff --git a/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java b/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java deleted file mode 100644 index 287508f..0000000 --- a/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.microbule.config.core; - -import java.util.Optional; - -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import org.microbule.config.api.Config; - -public class RecordingConfig implements Config { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final JsonObject recordedJson; - private final Config delegate; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public RecordingConfig(Config delegate) { - this(delegate, new JsonObject()); - } - - private RecordingConfig(Config delegate, JsonObject recordedJson) { - this.delegate = delegate; - this.recordedJson = recordedJson; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Config Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config filtered(String... paths) { - JsonObject filteredJson = recordedJson; - for (String path : paths) { - JsonObject sub = new JsonObject(); - filteredJson.add(path, sub); - filteredJson = sub; - } - return new RecordingConfig(delegate.filtered(paths), filteredJson); - } - - @Override - public Optional value(String key) { - final Optional value = delegate.value(key); - recordedJson.add(key, value.map(JsonPrimitive::new).orElse(JsonNull.INSTANCE)); - return value; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public JsonObject getRecordedJson() { - return recordedJson; - } -} diff --git a/config/core/src/main/resources/META-INF/beans.xml b/config/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/config/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/config/core/src/main/resources/OSGI-INF/blueprint/microbule-config-core.xml b/config/core/src/main/resources/OSGI-INF/blueprint/microbule-config-core.xml deleted file mode 100644 index 37d1848..0000000 --- a/config/core/src/main/resources/OSGI-INF/blueprint/microbule-config-core.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/config/core/src/test/java/org/microbule/config/core/CompositeConfigTest.java b/config/core/src/test/java/org/microbule/config/core/CompositeConfigTest.java deleted file mode 100644 index 44e95ea..0000000 --- a/config/core/src/test/java/org/microbule/config/core/CompositeConfigTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; -import org.microbule.config.api.Config; - -public class CompositeConfigTest extends Assert { - @Test - public void testValue() { - MapConfig config1 = new MapConfig(); - config1.addValue("foo", "bar"); - MapConfig config2 = new MapConfig(); - config2.addValue("foo", "baz"); - config2.addValue("hello", "world"); - - final CompositeConfig config = new CompositeConfig(config1, config2); - assertEquals("bar", config.value("foo").get()); - assertEquals("world", config.value("hello").get()); - } - - @Test - public void testGroup() { - MapConfig config1 = new MapConfig(); - config1.addValue("a.foo", "bar"); - MapConfig config2 = new MapConfig(); - config2.addValue("a.foo", "baz"); - config2.addValue("a.hello", "world"); - - final Config config = new CompositeConfig(config1, config2).filtered("a"); - assertEquals("bar", config.value("foo").get()); - assertEquals("world", config.value("hello").get()); - } - - @Test - public void testCreate() { - - Config config1 = new MapConfig(); - Config config2 = new MapConfig(); - - assertSame(EmptyConfig.INSTANCE, CompositeConfig.create(Lists.newArrayList())); - - assertEquals(config1, CompositeConfig.create(Lists.newArrayList(config1))); - - - } -} \ No newline at end of file diff --git a/config/core/src/test/java/org/microbule/config/core/ConfigUtilsTest.java b/config/core/src/test/java/org/microbule/config/core/ConfigUtilsTest.java deleted file mode 100644 index 9c7edd7..0000000 --- a/config/core/src/test/java/org/microbule/config/core/ConfigUtilsTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.test.core.MicrobuleTestCase; - -public class ConfigUtilsTest extends MicrobuleTestCase { - - @Test - public void testIsUtilsClass() throws Exception { - assertIsUtilsClass(ConfigUtils.class); - } - - @Test - public void testBootstrapConfig() { - System.setProperty("microbule.foo.bar", "baz"); - final Config config = ConfigUtils.bootstrapConfig("foo"); - assertEquals("baz", config.value("bar").get()); - } - -} \ No newline at end of file diff --git a/config/core/src/test/java/org/microbule/config/core/DefaultConfigServiceTest.java b/config/core/src/test/java/org/microbule/config/core/DefaultConfigServiceTest.java deleted file mode 100644 index 89c1451..0000000 --- a/config/core/src/test/java/org/microbule/config/core/DefaultConfigServiceTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.Comparator; -import java.util.SortedSet; -import java.util.concurrent.ConcurrentSkipListSet; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.spi.ConfigProvider; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.when; - -public class DefaultConfigServiceTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private ConfigProvider provider1; - - @Mock - private ConfigProvider provider2; - - @Mock - private MicrobuleContainer container; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - @SuppressWarnings("unchecked") - public void testWithNoConfigProviders() { - final MapConfig config1 = new MapConfig(); - config1.addValue("a.one", "config1.a1"); - config1.addValue("b.one", "config1.b1"); - config1.addValue("b.two", "config1.b2"); - - when(provider1.getConfig("a")).thenReturn(config1.filtered("a")); - when(provider1.getConfig("b")).thenReturn(config1.filtered("b")); - when(provider1.name()).thenReturn("provider1"); - when(provider1.priority()).thenReturn(ConfigUtils.DEFAULT_PRIORITY); - - final MapConfig config2 = new MapConfig(); - config2.addValue("a.one", "config2.a1"); - config2.addValue("a.three", "config2.a3"); - config2.addValue("b.one", "config2.b1"); - config2.addValue("b.three", "config2.b3"); - - when(provider2.getConfig("a")).thenReturn(config2.filtered("a")); - when(provider2.getConfig("b")).thenReturn(config2.filtered("b")); - when(provider2.name()).thenReturn("provider2"); - when(provider2.priority()).thenReturn(ConfigUtils.PRIORITY_EXTERNAL); - - - when(container.pluginSortedSet(same(ConfigProvider.class), any())).thenAnswer(invocation -> { - SortedSet set = new ConcurrentSkipListSet<>((Comparator) invocation.getArgument(1)); - set.add(provider1); - set.add(provider2); - return set; - }); - - final DefaultConfigService configService = new DefaultConfigService(container); - - Config config = configService.createConfig("a"); - assertEquals("config1.a1", config.value("one").get()); - - assertEquals("config2.b3", createWithoutLogging(() -> configService.createConfig("b")).value("three").get()); - } -} \ No newline at end of file diff --git a/config/core/src/test/java/org/microbule/config/core/EmptyConfigTest.java b/config/core/src/test/java/org/microbule/config/core/EmptyConfigTest.java deleted file mode 100644 index 1039235..0000000 --- a/config/core/src/test/java/org/microbule/config/core/EmptyConfigTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import org.junit.Assert; -import org.junit.Test; - -public class EmptyConfigTest extends Assert { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testValue() { - assertFalse(EmptyConfig.INSTANCE.value("whatever").isPresent()); - } - - @Test - public void testGroup() { - assertSame(EmptyConfig.INSTANCE, EmptyConfig.INSTANCE.filtered("whatever")); - } -} \ No newline at end of file diff --git a/config/core/src/test/java/org/microbule/config/core/MapConfigTest.java b/config/core/src/test/java/org/microbule/config/core/MapConfigTest.java deleted file mode 100644 index 941825e..0000000 --- a/config/core/src/test/java/org/microbule/config/core/MapConfigTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.core; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; -import org.microbule.config.api.Config; - -public class MapConfigTest extends Assert { - @Test - public void testValue() { - Map values = new HashMap<>(); - values.put("foo", "bar"); - final MapConfig config = new MapConfig(values); - assertEquals("bar", config.value("foo").get()); - } - - @Test - public void testWithCustomSeparator() { - Map values = new HashMap<>(); - values.put("foo/bar", "baz"); - final MapConfig config = new MapConfig(values, "/"); - assertEquals("baz", config.filtered("foo").value("bar").get()); - } - - @Test - public void testFilteredWithNoPaths() { - Map values = new HashMap<>(); - values.put("foo/bar", "baz"); - final Config config = new MapConfig(values, "/").filtered(); - assertEquals("baz", config.filtered("foo").value("bar").get()); - } -} \ No newline at end of file diff --git a/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java b/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java deleted file mode 100644 index 74e9d39..0000000 --- a/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.microbule.config.core; - -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.test.core.MicrobuleTestCase; - -public class RecordingConfigTest extends MicrobuleTestCase { - - @Test - public void testWithEmpty() { - final RecordingConfig recording = new RecordingConfig(new MapConfig()); - recording.value("foo"); - recording.value("bar"); - recording.filtered("baz"); - final JsonObject json = recording.getRecordedJson(); - assertEquals(JsonNull.INSTANCE, json.get("foo")); - assertEquals(JsonNull.INSTANCE, json.get("bar")); - assertEquals(new JsonObject(), json.get("baz")); - } - - @Test - public void testRecording() { - final MapConfig mapConfig = new MapConfig(); - mapConfig.addValue("foo", "bar"); - mapConfig.addValue("theint", "12345"); - ((MapConfig) mapConfig.filtered("nested")).addValue("hello", "world"); - ((MapConfig) mapConfig.filtered("nested", "nested2")).addValue("hello", "world"); - final RecordingConfig recording = new RecordingConfig(mapConfig); - - recording.value("foo"); - recording.value("baz"); - recording.integerValue("theint"); - final Config nested = recording.filtered("nested"); - nested.value("hello"); - nested.value("bogus"); - nested.filtered("nested2").value("hello"); - - final JsonObject json = recording.getRecordedJson(); - - assertEquals(new JsonPrimitive("bar"), json.get("foo")); - assertEquals(new JsonPrimitive("12345"), json.get("theint")); - assertEquals(JsonNull.INSTANCE, json.get("baz")); - - JsonObject nestedJson = json.getAsJsonObject("nested"); - assertEquals(new JsonPrimitive("world"), nestedJson.get("hello")); - assertEquals(JsonNull.INSTANCE, nestedJson.get("bogus")); - - JsonObject nestedJson2 = nestedJson.getAsJsonObject("nested2"); - assertEquals(new JsonPrimitive("world"), nestedJson2.get("hello")); - } -} \ No newline at end of file diff --git a/config/env/pom.xml b/config/env/pom.xml deleted file mode 100644 index 97ee63d..0000000 --- a/config/env/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-env - Microbule :: Config :: Environment Variables - bundle - - - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - - diff --git a/config/env/src/main/java/org/microbule/config/env/EnvironmentVariablesConfigProvider.java b/config/env/src/main/java/org/microbule/config/env/EnvironmentVariablesConfigProvider.java deleted file mode 100644 index 0cc4e1b..0000000 --- a/config/env/src/main/java/org/microbule/config/env/EnvironmentVariablesConfigProvider.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.env; - -import java.util.Map; -import java.util.function.Supplier; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.config.core.MapConfig; -import org.microbule.config.spi.ConfigProvider; - -@Singleton -@Named("envConfigProvider") -public class EnvironmentVariablesConfigProvider implements ConfigProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String SEPARATOR = "_"; - private final Supplier> envSupplier; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public EnvironmentVariablesConfigProvider() { - this(System::getenv); - } - - public EnvironmentVariablesConfigProvider(Supplier> envSupplier) { - this.envSupplier = envSupplier; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config getConfig(String... path) { - return new MapConfig(envSupplier.get(), SEPARATOR).filtered(path); - } - - @Override - public String name() { - return "env"; - } - - @Override - public int priority() { - return ConfigUtils.PRIORITY_ENV; - } -} diff --git a/config/env/src/main/resources/META-INF/beans.xml b/config/env/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/config/env/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/config/env/src/main/resources/OSGI-INF/blueprint/microbule-config-env.xml b/config/env/src/main/resources/OSGI-INF/blueprint/microbule-config-env.xml deleted file mode 100644 index a191188..0000000 --- a/config/env/src/main/resources/OSGI-INF/blueprint/microbule-config-env.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/config/env/src/test/java/org/microbule/config/env/EnvironmentVariablesConfigProviderTest.java b/config/env/src/test/java/org/microbule/config/env/EnvironmentVariablesConfigProviderTest.java deleted file mode 100644 index 76c97ba..0000000 --- a/config/env/src/test/java/org/microbule/config/env/EnvironmentVariablesConfigProviderTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.env; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; - -public class EnvironmentVariablesConfigProviderTest extends Assert { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testGetServerConfig() { - Map env = new HashMap<>(); - env.put("one_two_foo", "bar"); - EnvironmentVariablesConfigProvider provider = new EnvironmentVariablesConfigProvider(() -> env); - assertEquals("env", provider.name()); - assertEquals(ConfigUtils.PRIORITY_ENV, provider.priority()); - final Config config = provider.getConfig("one", "two"); - assertEquals("bar", config.value("foo").get()); - } - - @Test - public void testWithDefaultConstructor() { - final EnvironmentVariablesConfigProvider provider = new EnvironmentVariablesConfigProvider(); - final Config config = provider.getConfig(); - final Map env = System.getenv(); - assertEquals(env.get("PATH"), config.value("PATH").get()); - } -} \ No newline at end of file diff --git a/config/etcd/pom.xml b/config/etcd/pom.xml deleted file mode 100644 index f35d13d..0000000 --- a/config/etcd/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-etcd - Microbule :: Config :: Etcd - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-decorator - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - test - - - - - diff --git a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java b/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java deleted file mode 100644 index 3fae587..0000000 --- a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.apache.commons.lang3.StringUtils; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.config.core.EmptyConfig; -import org.microbule.config.core.MapConfig; -import org.microbule.config.spi.ConfigProvider; -import org.microbule.util.jaxrs.WebTargetUtils; - -import static org.microbule.util.jaxrs.WebTargetUtils.extend; - -@Singleton -@Named("etcdConfigProvider") -public class EtcdConfigProvider implements ConfigProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String SEPARATOR = "/"; - private static final String NAME = "etcd"; - private static final String BASE_ADDRESS_PROP = "baseAddress"; - private static final String DEFAULT_BASE_ADDRESS = "http://localhost:2379/v2/keys/microbule"; - - private final WebTarget baseTarget; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public EtcdConfigProvider() { - this(ConfigUtils.bootstrapConfig(NAME).value(BASE_ADDRESS_PROP).orElse(DEFAULT_BASE_ADDRESS)); - } - - public EtcdConfigProvider(String baseAddress) { - baseTarget = ClientBuilder.newClient().target(baseAddress); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String name() { - return NAME; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public Config getConfig(String... path) { - final Response response = extend(baseTarget, path).queryParam("recursive", "true").request(MediaType.APPLICATION_JSON_TYPE).get(); - final String keyPath = Stream.of(path).collect(Collectors.joining(SEPARATOR)) + SEPARATOR; - final Optional etcdResponse = WebTargetUtils.parseJsonResponse(response, EtcdResponse.class); - return etcdResponse.map(r -> { - Map values = new HashMap<>(); - fillMap(values, r.getNode(), keyPath); - return (Config) new MapConfig(values, "/"); - }).orElse(EmptyConfig.INSTANCE); - } - - @Override - public int priority() { - return ConfigUtils.PRIORITY_EXTERNAL; - } - - private void fillMap(Map values, EtcdNode node, String keyPath) { - if (node.isDir()) { - node.getNodes().forEach(child -> fillMap(values, child, keyPath)); - } else { - values.put(StringUtils.substringAfter(node.getKey(), keyPath), node.getValue()); - } - } -} diff --git a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdNode.java b/config/etcd/src/main/java/org/microbule/config/etcd/EtcdNode.java deleted file mode 100644 index a9076e6..0000000 --- a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdNode.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -import java.util.List; - -public class EtcdNode { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String key; - private final boolean dir; - private final List nodes; - private final String value; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public EtcdNode(String key, boolean dir, List nodes, String value) { - this.key = key; - this.dir = dir; - this.nodes = nodes; - this.value = value; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getKey() { - return key; - } - - public List getNodes() { - return nodes; - } - - public String getValue() { - return value; - } - - public boolean isDir() { - return dir; - } -} diff --git a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdResponse.java b/config/etcd/src/main/java/org/microbule/config/etcd/EtcdResponse.java deleted file mode 100644 index 160951c..0000000 --- a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -public class EtcdResponse { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final EtcdNode node; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public EtcdResponse(EtcdNode node) { - this.node = node; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public EtcdNode getNode() { - return node; - } -} diff --git a/config/etcd/src/main/resources/META-INF/beans.xml b/config/etcd/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/config/etcd/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/config/etcd/src/main/resources/OSGI-INF/blueprint/microbule-config-etcd.xml b/config/etcd/src/main/resources/OSGI-INF/blueprint/microbule-config-etcd.xml deleted file mode 100644 index 60a73d2..0000000 --- a/config/etcd/src/main/resources/OSGI-INF/blueprint/microbule-config-etcd.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java b/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java deleted file mode 100644 index ff35b3a..0000000 --- a/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -import java.io.InputStreamReader; -import java.util.concurrent.atomic.AtomicReference; - -import com.google.common.base.Charsets; -import com.google.gson.Gson; -import org.junit.Before; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; -import org.microbule.test.server.JaxrsServerTestCase; - -public class EtcdConfigProviderTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference root = new AtomicReference<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new GsonServerDecorator(new DefaultGsonService(container))); - container.addBean(new GsonProxyDecorator(new DefaultGsonService(container))); - } - - @Override - protected MockEtcdService createImplementation() { - return new MockEtcdServiceImpl(root); - } - - @Before - public void setBaseAddress() { - System.setProperty("microbule.etcd.baseAddress", getBaseAddress()); - } - @Test - public void testConfig() { - final EtcdConfigProvider provider = new EtcdConfigProvider(); - assertEquals("etcd", provider.name()); - assertEquals(ConfigUtils.PRIORITY_EXTERNAL, provider.priority()); - - root.set(parseResponse("/response.json", EtcdResponse.class).getNode()); - - final Config config = provider.getConfig("one", "two"); - assertEquals("Microbule", config.value("three").get()); - assertEquals("three, sir", config.value("five").get()); - } - - private T parseResponse(String resourceName, Class type) { - return new Gson().fromJson(new InputStreamReader(getClass().getResourceAsStream(resourceName), Charsets.UTF_8), type); - } - -} \ No newline at end of file diff --git a/config/etcd/src/test/java/org/microbule/config/etcd/EtcdNodeTest.java b/config/etcd/src/test/java/org/microbule/config/etcd/EtcdNodeTest.java deleted file mode 100644 index 5eebc4b..0000000 --- a/config/etcd/src/test/java/org/microbule/config/etcd/EtcdNodeTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -import java.util.ArrayList; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class EtcdNodeTest extends MockObjectTestCase { - - @Test - public void testConstructor() { - final EtcdNode node = new EtcdNode("one", false, new ArrayList<>(), "val1"); - assertEquals("one", node.getKey()); - assertFalse(node.isDir()); - assertEquals(new ArrayList<>(), node.getNodes()); - assertEquals("val1", node.getValue()); - - } -} \ No newline at end of file diff --git a/config/etcd/src/test/java/org/microbule/config/etcd/MockEtcdService.java b/config/etcd/src/test/java/org/microbule/config/etcd/MockEtcdService.java deleted file mode 100644 index a97c8dc..0000000 --- a/config/etcd/src/test/java/org/microbule/config/etcd/MockEtcdService.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -@Path("/") -public interface MockEtcdService { - - @GET - @Path("/{path:.*}") - @Produces(MediaType.APPLICATION_JSON) - EtcdResponse getKeyValues(@PathParam("path") String path); -} diff --git a/config/etcd/src/test/java/org/microbule/config/etcd/MockEtcdServiceImpl.java b/config/etcd/src/test/java/org/microbule/config/etcd/MockEtcdServiceImpl.java deleted file mode 100644 index 46b2357..0000000 --- a/config/etcd/src/test/java/org/microbule/config/etcd/MockEtcdServiceImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.etcd; - -import java.util.concurrent.atomic.AtomicReference; - -public class MockEtcdServiceImpl implements MockEtcdService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference root; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MockEtcdServiceImpl(AtomicReference root) { - this.root = root; - } - -//---------------------------------------------------------------------------------------------------------------------- -// MockEtcdService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public EtcdResponse getKeyValues(String path) { - return new EtcdResponse(root.get()); - } -} diff --git a/config/etcd/src/test/resources/response.json b/config/etcd/src/test/resources/response.json deleted file mode 100644 index 9490ef6..0000000 --- a/config/etcd/src/test/resources/response.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "action": "get", - "node": { - "key": "/microbule/one/two", - "dir": true, - "nodes": [ - { - "key": "/microbule/one/two/three", - "value": "Microbule", - "modifiedIndex": 5, - "createdIndex": 5 - }, - { - "key": "/microbule/one/two/five", - "value": "three, sir", - "modifiedIndex": 6, - "createdIndex": 6 - } - ], - "modifiedIndex": 5, - "createdIndex": 5 - } -} \ No newline at end of file diff --git a/config/pom.xml b/config/pom.xml deleted file mode 100644 index a9e5a07..0000000 --- a/config/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-config-parent - Microbule :: Config :: Parent - pom - - - api - spi - core - consul - etcd - env - sysprop - annotation - - diff --git a/config/spi/pom.xml b/config/spi/pom.xml deleted file mode 100644 index 3e6894f..0000000 --- a/config/spi/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-spi - Microbule :: Config :: SPI - bundle - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - - - diff --git a/config/spi/src/main/java/org/microbule/config/spi/ConfigProvider.java b/config/spi/src/main/java/org/microbule/config/spi/ConfigProvider.java deleted file mode 100644 index fb1932d..0000000 --- a/config/spi/src/main/java/org/microbule/config/spi/ConfigProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.spi; - -import org.microbule.config.api.Config; - -/** - * A ConfigProvider is responsible for gather configuration data from a configuration source. - */ -public interface ConfigProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Returns a {@link Config} object located at the specified path. - * - * @param path the path - * @return the config object - */ - Config getConfig(String... path); - - /** - * The name of the provider - * - * @return the name - */ - String name(); - - /** - * The priority of the provider (will be sorted in ascending order) - * - * @return the priority - */ - int priority(); -} diff --git a/config/sysprop/pom.xml b/config/sysprop/pom.xml deleted file mode 100644 index c1b1430..0000000 --- a/config/sysprop/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-config-parent - 0.3.0-SNAPSHOT - - - microbule-config-sysprop - Microbule :: Config :: System Properties - bundle - - - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - - diff --git a/config/sysprop/src/main/java/org/microbule/config/sysprop/SystemPropertiesConfigProvider.java b/config/sysprop/src/main/java/org/microbule/config/sysprop/SystemPropertiesConfigProvider.java deleted file mode 100644 index 960a101..0000000 --- a/config/sysprop/src/main/java/org/microbule/config/sysprop/SystemPropertiesConfigProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.sysprop; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.config.spi.ConfigProvider; - -@Singleton -@Named("systemPropertiesConfigProvider") -public class SystemPropertiesConfigProvider implements ConfigProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String NAME = "sysprop"; - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config getConfig(String... path) { - return ConfigUtils.fromProperties(System.getProperties()).filtered(path); - } - - @Override - public String name() { - return NAME; - } - - @Override - public int priority() { - return ConfigUtils.PRIORITY_SYSPROP; - } -} diff --git a/config/sysprop/src/main/resources/META-INF/beans.xml b/config/sysprop/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/config/sysprop/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/config/sysprop/src/main/resources/OSGI-INF/blueprint/microbule-config-sysprop.xml b/config/sysprop/src/main/resources/OSGI-INF/blueprint/microbule-config-sysprop.xml deleted file mode 100644 index a35afbf..0000000 --- a/config/sysprop/src/main/resources/OSGI-INF/blueprint/microbule-config-sysprop.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/config/sysprop/src/test/java/org/microbule/config/sysprop/SystemPropertiesConfigProviderTest.java b/config/sysprop/src/test/java/org/microbule/config/sysprop/SystemPropertiesConfigProviderTest.java deleted file mode 100644 index b84b25c..0000000 --- a/config/sysprop/src/test/java/org/microbule/config/sysprop/SystemPropertiesConfigProviderTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.config.sysprop; - -import org.junit.Assert; -import org.junit.Test; -import org.microbule.config.core.ConfigUtils; - -public class SystemPropertiesConfigProviderTest extends Assert { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testGetConfig() { - System.setProperty("one.two.foo", "bar"); - final SystemPropertiesConfigProvider provider = new SystemPropertiesConfigProvider(); - - assertEquals("sysprop", provider.name()); - assertEquals(ConfigUtils.PRIORITY_SYSPROP, provider.priority()); - - assertEquals("bar", provider.getConfig("one", "two").value("foo").get()); - } - - @Test - public void testDefaultConstructor() { - final SystemPropertiesConfigProvider provider = new SystemPropertiesConfigProvider(); - - assertEquals(System.getProperty("user.dir"), provider.getConfig("user").value("dir").get()); - } -} \ No newline at end of file diff --git a/configuration.md b/configuration.md new file mode 100644 index 0000000..450d382 --- /dev/null +++ b/configuration.md @@ -0,0 +1,23 @@ +# Configuration + +Microbule includes a pluggable configuration framework. Whenever configuration data is requested, each registered *ConfigProvider* is consulted. The following *ConfigProviders* are included: + +#### System Providers +* System Properties - Java system properties +* Environment Variables - environment variables + +#### Container Providers +* Spring - Spring's Environment +* OSGi - a ManagedServiceFactory which receives configuration data from ConfigAdmin + +#### Remote Providers +* Consul - retrieves configuration data from Consul +* Etcd - retrieves configuration data from Etcd + +## Search Order +The *ConfigProviders* are ordered according to their *priority*, which defaults to: + +* System Properties +* Environment Variables +* Container Providers +* Remote Providers diff --git a/container/api/pom.xml b/container/api/pom.xml deleted file mode 100644 index 9e20832..0000000 --- a/container/api/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-container-parent - 0.3.0-SNAPSHOT - - - microbule-container-api - Microbule :: Container :: API - bundle - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - - diff --git a/container/api/src/main/java/org/microbule/container/api/MicrobuleContainer.java b/container/api/src/main/java/org/microbule/container/api/MicrobuleContainer.java deleted file mode 100644 index 673e291..0000000 --- a/container/api/src/main/java/org/microbule/container/api/MicrobuleContainer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.api; - -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; - -public interface MicrobuleContainer { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - void addPluginListener(Class beanType, PluginListener listener); - - void addServerListener(ServerListener listener); - - List pluginList(Class beanType); - - Map pluginMap(Class beanType, Function keyFunction); - - AtomicReference pluginReference(Class beanType, B defaultValue); - - > SortedSet pluginSortedSet(Class pluginType); - - SortedSet pluginSortedSet(Class beanType, Comparator comparator); -} diff --git a/container/api/src/main/java/org/microbule/container/api/PluginListener.java b/container/api/src/main/java/org/microbule/container/api/PluginListener.java deleted file mode 100644 index 5a8812c..0000000 --- a/container/api/src/main/java/org/microbule/container/api/PluginListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.api; - -public interface PluginListener

{ -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - boolean registerPlugin(P plugin); - - void unregisterPlugin(P bean); -} diff --git a/container/api/src/main/java/org/microbule/container/api/ServerDefinition.java b/container/api/src/main/java/org/microbule/container/api/ServerDefinition.java deleted file mode 100644 index adf95f4..0000000 --- a/container/api/src/main/java/org/microbule/container/api/ServerDefinition.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.api; - -public interface ServerDefinition { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String id(); - - Object serviceImplementation(); - - Class serviceInterface(); -} diff --git a/container/api/src/main/java/org/microbule/container/api/ServerListener.java b/container/api/src/main/java/org/microbule/container/api/ServerListener.java deleted file mode 100644 index 191da62..0000000 --- a/container/api/src/main/java/org/microbule/container/api/ServerListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.api; - -public interface ServerListener { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - void registerServer(ServerDefinition serverDefinition); - - void unregisterServer(String id); -} diff --git a/container/core/pom.xml b/container/core/pom.xml deleted file mode 100644 index 40e42d4..0000000 --- a/container/core/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-container-parent - 0.3.0-SNAPSHOT - - - microbule-container-core - Microbule :: Container :: Core - bundle - - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - - diff --git a/container/core/src/main/java/org/microbule/container/core/AbstractContainer.java b/container/core/src/main/java/org/microbule/container/core/AbstractContainer.java deleted file mode 100644 index dbe9b2e..0000000 --- a/container/core/src/main/java/org/microbule/container/core/AbstractContainer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core; - -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; - -import com.google.common.collect.MapMaker; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.container.core.listener.CollectionPluginListener; -import org.microbule.container.core.listener.MapPluginListener; -import org.microbule.container.core.listener.RefPluginListener; - -public abstract class AbstractContainer implements MicrobuleContainer { -//---------------------------------------------------------------------------------------------------------------------- -// MicrobuleContainer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public List pluginList(Class beanType) { - final List list = new CopyOnWriteArrayList<>(); - addPluginListener(beanType, new CollectionPluginListener<>(list)); - return list; - } - - @Override - public Map pluginMap(Class beanType, Function keyFunction) { - final Map map = new MapMaker().makeMap(); - addPluginListener(beanType, new MapPluginListener<>(map, keyFunction)); - return map; - } - - @Override - public AtomicReference pluginReference(Class beanType, B defaultValue) { - final AtomicReference ref = new AtomicReference<>(defaultValue); - addPluginListener(beanType, new RefPluginListener<>(ref, defaultValue)); - return ref; - } - - @Override - public > SortedSet pluginSortedSet(Class pluginType) { - return pluginSortedSet(pluginType, Comparator.naturalOrder()); - } - - @Override - public SortedSet pluginSortedSet(Class beanType, Comparator comparator) { - final SortedSet beans = new ConcurrentSkipListSet<>(comparator); - addPluginListener(beanType, new CollectionPluginListener<>(beans)); - return beans; - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/DefaultServerDefinition.java b/container/core/src/main/java/org/microbule/container/core/DefaultServerDefinition.java deleted file mode 100644 index 322c7c9..0000000 --- a/container/core/src/main/java/org/microbule/container/core/DefaultServerDefinition.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core; - -import org.microbule.container.api.ServerDefinition; - -public class DefaultServerDefinition implements ServerDefinition { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String id; - private final Class serviceInterface; - private final Object serviceImplementation; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DefaultServerDefinition(String id, Class serviceInterface, Object serviceImplementation) { - this.id = id; - this.serviceInterface = serviceInterface; - this.serviceImplementation = serviceImplementation; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ServerDefinition Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String id() { - return id; - } - - @Override - public Object serviceImplementation() { - return serviceImplementation; - } - - @Override - public Class serviceInterface() { - return serviceInterface; - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/PluginListenerRegistration.java b/container/core/src/main/java/org/microbule/container/core/PluginListenerRegistration.java deleted file mode 100644 index 0f815ac..0000000 --- a/container/core/src/main/java/org/microbule/container/core/PluginListenerRegistration.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core; - - -import org.microbule.container.api.PluginListener; - -public class PluginListenerRegistration { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Class pluginType; - private final PluginListener listener; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public PluginListenerRegistration(Class pluginType, PluginListener listener) { - this.pluginType = pluginType; - this.listener = listener; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public Class getPluginType() { - return pluginType; - } - - public PluginListener getListener() { - return listener; - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/SimpleContainer.java b/container/core/src/main/java/org/microbule/container/core/SimpleContainer.java deleted file mode 100644 index b75aea2..0000000 --- a/container/core/src/main/java/org/microbule/container/core/SimpleContainer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core; - -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.stream.Collectors; - -import javax.ws.rs.Path; - -import org.apache.commons.lang3.ClassUtils; -import org.microbule.container.api.ServerDefinition; - -public class SimpleContainer extends StaticContainer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Set beans = new CopyOnWriteArraySet<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public void addBean(Object bean) { - beans.add(bean); - } - - @Override - protected Iterable plugins(Class pluginType) { - return beans.stream() - .filter(pluginType::isInstance) - .map(pluginType::cast) - .collect(Collectors.toList()); - } - - public void removeBean(Object bean) { - beans.remove(bean); - beanRemoved(bean); - } - - @Override - protected Iterable servers() { - return beans.stream() - .flatMap(bean -> ClassUtils.getAllInterfaces(bean.getClass()).stream() - .filter(serviceInterface -> serviceInterface.isAnnotationPresent(Path.class)) - .map(serviceInterface -> new DefaultServerDefinition(idOf(bean), serviceInterface, bean))) - .collect(Collectors.toList()); - } - - public void shutdown() { - servers().forEach(server -> serverRemoved(server.id())); - beans.forEach(bean -> { - serverRemoved(idOf(bean)); - removeBean(bean); - }); - } - - private String idOf(Object bean) { - return String.valueOf(System.identityHashCode(bean)); - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/StaticContainer.java b/container/core/src/main/java/org/microbule/container/core/StaticContainer.java deleted file mode 100644 index c7c1905..0000000 --- a/container/core/src/main/java/org/microbule/container/core/StaticContainer.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.microbule.container.api.PluginListener; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.api.ServerListener; - -public abstract class StaticContainer extends AbstractContainer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final List> pluginListeners = new CopyOnWriteArrayList<>(); - private final List serverListeners = new CopyOnWriteArrayList<>(); - - private final AtomicBoolean initialized = new AtomicBoolean(false); - -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract Iterable plugins(Class beanType); - - protected abstract Iterable servers(); - -//---------------------------------------------------------------------------------------------------------------------- -// MicrobuleContainer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void addPluginListener(Class beanType, PluginListener listener) { - final PluginListenerRegistration registration = new PluginListenerRegistration<>(beanType, listener); - pluginListeners.add(registration); - if (initialized.get()) { - registerPlugin(registration); - } - } - - @Override - public void addServerListener(ServerListener listener) { - serverListeners.add(listener); - if (initialized.get()) { - servers().forEach(listener::registerServer); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public void initialize() { - initialized.set(true); - pluginListeners.forEach(this::registerPlugin); - servers().forEach(def -> serverListeners.forEach(listener -> listener.registerServer(def))); - } - - protected void beanRemoved(Object bean) { - for (PluginListenerRegistration pluginListener : pluginListeners) { - if (pluginListener.getPluginType().isInstance(bean)) { - unregisterPlugin(pluginListener, bean); - } - } - } - - private void registerPlugin(PluginListenerRegistration registration) { - plugins(registration.getPluginType()).forEach(bean -> registration.getListener().registerPlugin(bean)); - } - - private void unregisterPlugin(PluginListenerRegistration registration, Object bean) { - registration.getListener().unregisterPlugin(registration.getPluginType().cast(bean)); - } - - protected void serverRemoved(String id) { - serverListeners.forEach(serverListener -> serverListener.unregisterServer(id)); - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/listener/CollectionPluginListener.java b/container/core/src/main/java/org/microbule/container/core/listener/CollectionPluginListener.java deleted file mode 100644 index 3319b80..0000000 --- a/container/core/src/main/java/org/microbule/container/core/listener/CollectionPluginListener.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core.listener; - -import java.util.Collection; - -import org.microbule.container.api.PluginListener; - - -public class CollectionPluginListener implements PluginListener { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Collection plugins; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public CollectionPluginListener(Collection plugins) { - this.plugins = plugins; - } - -//---------------------------------------------------------------------------------------------------------------------- -// PluginListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean registerPlugin(B plugin) { - return plugins.add(plugin); - } - - @Override - public void unregisterPlugin(B bean) { - plugins.remove(bean); - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/listener/MapPluginListener.java b/container/core/src/main/java/org/microbule/container/core/listener/MapPluginListener.java deleted file mode 100644 index 8720863..0000000 --- a/container/core/src/main/java/org/microbule/container/core/listener/MapPluginListener.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core.listener; - -import java.util.Map; -import java.util.function.Function; - -import org.microbule.container.api.PluginListener; - -public class MapPluginListener implements PluginListener { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Map pluginMap; - private final Function keyFunction; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MapPluginListener(Map pluginMap, Function keyFunction) { - this.pluginMap = pluginMap; - this.keyFunction = keyFunction; - } - -//---------------------------------------------------------------------------------------------------------------------- -// PluginListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean registerPlugin(B plugin) { - return pluginMap.putIfAbsent(keyFunction.apply(plugin), plugin) == null; - } - - @Override - public void unregisterPlugin(B bean) { - pluginMap.remove(keyFunction.apply(bean)); - } -} diff --git a/container/core/src/main/java/org/microbule/container/core/listener/RefPluginListener.java b/container/core/src/main/java/org/microbule/container/core/listener/RefPluginListener.java deleted file mode 100644 index 240c715..0000000 --- a/container/core/src/main/java/org/microbule/container/core/listener/RefPluginListener.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core.listener; - -import java.util.concurrent.atomic.AtomicReference; - -import org.microbule.container.api.PluginListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RefPluginListener implements PluginListener { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(RefPluginListener.class); - - private final AtomicReference pluginRef; - private final B defaultValue; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public RefPluginListener(AtomicReference pluginRef, B defaultValue) { - this.pluginRef = pluginRef; - this.defaultValue = defaultValue; - } - -//---------------------------------------------------------------------------------------------------------------------- -// PluginListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean registerPlugin(B plugin) { - if (pluginRef.compareAndSet(defaultValue, plugin)) { - LOGGER.debug("Overriding default value {} with {}...", defaultValue, plugin); - return true; - } - return false; - } - - @Override - public void unregisterPlugin(B bean) { - if (pluginRef.compareAndSet(bean, defaultValue)) { - LOGGER.debug("Restoring default value {}...", defaultValue); - } - } -} diff --git a/container/core/src/test/java/org/microbule/container/core/SimpleContainerTest.java b/container/core/src/test/java/org/microbule/container/core/SimpleContainerTest.java deleted file mode 100644 index 91b4dd7..0000000 --- a/container/core/src/test/java/org/microbule/container/core/SimpleContainerTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.container.core; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.concurrent.atomic.AtomicReference; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import org.junit.Test; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.api.ServerListener; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; - -public class SimpleContainerTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testMap() { - final SimpleContainer container = new SimpleContainer(); - final Map map = container.pluginMap(String.class, String::length); - - container.addBean("a"); - container.addBean("aa"); - container.addBean("aaa"); - container.initialize(); - - assertEquals("a", map.get(1)); - assertEquals("aa", map.get(2)); - assertEquals("aaa", map.get(3)); - - container.removeBean("aaa"); - - assertNull(map.get(3)); - } - - @Test - public void testMapWitDuplicate() { - final SimpleContainer container = new SimpleContainer(); - final Map map = container.pluginMap(String.class, String::length); - container.addBean("a"); - container.addBean("b"); - container.initialize(); - - assertEquals("a", map.get(1)); - assertEquals(1, map.size()); - } - - @Test - public void testPluginList() { - final SimpleContainer container = new SimpleContainer(); - container.addBean("Hello"); - container.addBean("World"); - - final List strings = container.pluginList(String.class); - assertTrue(strings.isEmpty()); - - container.initialize(); - assertEquals(Arrays.asList("Hello", "World"), strings); - - container.addBean("Microbule"); - - assertEquals(Arrays.asList("Hello", "World", "Microbule"), container.pluginList(String.class)); - - container.removeBean("World"); - - assertEquals(Collections.singletonList("Hello"), strings); - } - - @Test - public void testRef() { - final SimpleContainer container = new SimpleContainer(); - - final AtomicReference ref = container.pluginReference(String.class, "thedefault"); - assertEquals("thedefault", ref.get()); - - container.addBean("hello"); - - container.initialize(); - assertEquals("hello", ref.get()); - - container.removeBean("hello"); - - assertEquals("thedefault", ref.get()); - } - - @Test - public void testRefWithMultiplePlugins() { - final SimpleContainer container = new SimpleContainer(); - - final AtomicReference ref = container.pluginReference(String.class, "thedefault"); - assertEquals("thedefault", ref.get()); - - container.addBean("hello"); - container.addBean("world"); - container.initialize(); - assertEquals("hello", ref.get()); - container.removeBean("hello"); - assertEquals("thedefault", ref.get()); - container.removeBean("world"); - assertEquals("thedefault", ref.get()); - } - - @Test - public void testServers() { - final SimpleContainer container = new SimpleContainer(); - final HelloServiceImpl impl = new HelloServiceImpl(); - container.addBean(impl); - - final CollectingServerListener collector1 = new CollectingServerListener(); - container.addServerListener(collector1); - container.initialize(); - - assertEquals(1, collector1.definitions.size()); - - final ServerDefinition def = collector1.definitions.get(0); - assertNotNull(def.id()); - assertEquals(impl, def.serviceImplementation()); - assertEquals(HelloService.class, def.serviceInterface()); - - final CollectingServerListener collector2 = new CollectingServerListener(); - container.addServerListener(collector2); - assertEquals(1, collector2.definitions.size()); - } - - @Test - public void testShutdown() { - final SimpleContainer container = new SimpleContainer(); - container.addBean("Hello"); - container.addBean("World"); - - List plugins = container.pluginList(String.class); - - final HelloServiceImpl impl = new HelloServiceImpl(); - container.addBean(impl); - - final CollectingServerListener collector = new CollectingServerListener(); - container.addServerListener(collector); - container.initialize(); - - container.shutdown(); - - assertEquals(0, plugins.size()); - assertEquals(0, collector.definitions.size()); - } - - @Test - public void testSortedSet() { - final SimpleContainer container = new SimpleContainer(); - final SortedSet strings = container.pluginSortedSet(String.class); - - container.addBean("a"); - container.addBean("b"); - container.addBean("c"); - container.initialize(); - - assertEquals(Sets.newTreeSet(Lists.newArrayList("a", "b", "c")), strings); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class CollectingServerListener implements ServerListener { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final List definitions = new LinkedList<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// ServerListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void registerServer(ServerDefinition serverDefinition) { - definitions.add(serverDefinition); - } - - @Override - public void unregisterServer(String id) { - definitions.removeIf(def -> def.id().equals(id)); - } - } -} \ No newline at end of file diff --git a/container/pom.xml b/container/pom.xml deleted file mode 100644 index 95c6a95..0000000 --- a/container/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-container-parent - Microbule :: Container :: Parent - pom - - - api - core - - - - - - - - - - diff --git a/core/pom.xml b/core/pom.xml deleted file mode 100644 index 4e2522a..0000000 --- a/core/pom.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-core - Microbule :: Core - bundle - - - - org.microbule - microbule-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-scheduler-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-api - 0.3.0-SNAPSHOT - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - test - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - test - - - org.apache.cxf - cxf-rt-transports-http-hc - ${cxf.version} - test - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - test - - - diff --git a/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java b/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java deleted file mode 100644 index 783ad62..0000000 --- a/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.microbule.core; - -import com.google.gson.JsonObject; - -public class CachedJaxrsProxy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final T proxy; - private final JsonObject config; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public CachedJaxrsProxy(T proxy, JsonObject config) { - this.proxy = proxy; - this.config = config; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public JsonObject getConfig() { - return config; - } - - public T getProxy() { - return proxy; - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsConfigBuilder.java b/core/src/main/java/org/microbule/core/DefaultJaxrsConfigBuilder.java deleted file mode 100644 index fcd765f..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsConfigBuilder.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.LinkedList; -import java.util.List; - -import org.microbule.config.api.Config; -import org.microbule.config.api.ConfigService; -import org.microbule.config.core.CompositeConfig; -import org.microbule.spi.JaxrsConfigBuilder; - -public class DefaultJaxrsConfigBuilder implements JaxrsConfigBuilder { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final ConfigService configService; - private final Class serviceInterface; - private final String serviceName; - private final List members = new LinkedList<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DefaultJaxrsConfigBuilder(ConfigService configService, Class serviceInterface, String serviceName) { - this.configService = configService; - this.serviceInterface = serviceInterface; - this.serviceName = serviceName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsConfigBuilder Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config build() { - return CompositeConfig.create(members); - } - - @Override - public Class serviceInterface() { - return serviceInterface; - } - - @Override - public String serviceName() { - return serviceName; - } - - @Override - public JaxrsConfigBuilder withPath(String... path) { - members.add(configService.createConfig(path)); - return this; - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsConfigBuilderStrategy.java b/core/src/main/java/org/microbule/core/DefaultJaxrsConfigBuilderStrategy.java deleted file mode 100644 index a5e230e..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsConfigBuilderStrategy.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import org.microbule.spi.JaxrsConfigBuilder; -import org.microbule.spi.JaxrsConfigBuilderStrategy; - -public class DefaultJaxrsConfigBuilderStrategy implements JaxrsConfigBuilderStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String DEFAULTS_PATH_SEGMENT = "default"; - private static final String SERVER_PATH_SEGMENT = "server"; - private static final String PROXY_PATH_SEGMENT = "proxy"; - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsConfigBuilderStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public JaxrsConfigBuilder buildProxyConfig(JaxrsConfigBuilder builder) { - final String serviceName = builder.serviceName(); - return builder.withPath(serviceName, PROXY_PATH_SEGMENT) - .withPath(serviceName) - .withPath(DEFAULTS_PATH_SEGMENT, PROXY_PATH_SEGMENT); - } - - @Override - public JaxrsConfigBuilder buildServerConfig(JaxrsConfigBuilder builder) { - final String serviceName = builder.serviceName(); - return builder.withPath(serviceName, SERVER_PATH_SEGMENT) - .withPath(serviceName) - .withPath(DEFAULTS_PATH_SEGMENT, SERVER_PATH_SEGMENT); - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsConfigService.java b/core/src/main/java/org/microbule/core/DefaultJaxrsConfigService.java deleted file mode 100644 index 75f0ac3..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsConfigService.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.concurrent.atomic.AtomicReference; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.api.JaxrsConfigService; -import org.microbule.config.api.Config; -import org.microbule.config.api.ConfigService; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.spi.JaxrsConfigBuilderStrategy; - -@Singleton -@Named("jaxrsConfigService") -public class DefaultJaxrsConfigService implements JaxrsConfigService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference serviceConfigBuilder; - private final ConfigService configService; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultJaxrsConfigService(MicrobuleContainer container, ConfigService configService) { - this.configService = configService; - serviceConfigBuilder = container.pluginReference(JaxrsConfigBuilderStrategy.class, new DefaultJaxrsConfigBuilderStrategy()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsConfigService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config createConfig(String... path) { - return configService.createConfig(path); - } - - @Override - public Config createProxyConfig(Class serviceInterface, String serviceName) { - final DefaultJaxrsConfigBuilder builder = new DefaultJaxrsConfigBuilder<>(configService, serviceInterface, serviceName); - return serviceConfigBuilder.get().buildProxyConfig(builder).build(); - } - - @Override - public Config createServerConfig(Class serviceInterface, String serviceName) { - final DefaultJaxrsConfigBuilder builder = new DefaultJaxrsConfigBuilder<>(configService, serviceInterface, serviceName); - return serviceConfigBuilder.get().buildServerConfig(builder).build(); - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsProxyFactory.java b/core/src/main/java/org/microbule/core/DefaultJaxrsProxyFactory.java deleted file mode 100644 index dcc5099..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsProxyFactory.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.PreDestroy; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; -import org.apache.cxf.jaxrs.client.JAXRSClientFactory; -import org.microbule.api.JaxrsConfigService; -import org.microbule.api.JaxrsProxyFactory; -import org.microbule.config.api.Config; -import org.microbule.config.core.RecordingConfig; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.scheduler.api.SchedulerService; -import org.microbule.spi.JaxrsAddressChooser; -import org.microbule.spi.JaxrsDynamicProxyStrategy; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDiscovery; -import org.microbule.spi.JaxrsServiceNamingStrategy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("jaxrsProxyFactory") -public class DefaultJaxrsProxyFactory extends JaxrsServiceDecoratorRegistry implements JaxrsProxyFactory, RemovalListener, JaxrsProxyDispatcher> { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultJaxrsProxyFactory.class); - private final JaxrsConfigService configService; - private final AtomicReference serviceDiscovery; - private final AtomicReference dynamicProxyStrategy; - private final AtomicReference namingStrategy; - private final SchedulerService schedulerService; - private final Supplier, JaxrsProxyDispatcher>> proxyCacheSupplier; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultJaxrsProxyFactory(MicrobuleContainer container, JaxrsConfigService configService, SchedulerService schedulerService) { - super(JaxrsProxyDecorator.class, container); - this.configService = configService; - this.schedulerService = schedulerService; - this.serviceDiscovery = container.pluginReference(JaxrsServiceDiscovery.class, new DefaultJaxrsServiceDiscovery(configService)); - this.dynamicProxyStrategy = container.pluginReference(JaxrsDynamicProxyStrategy.class, new JdkDynamicProxyStrategy()); - this.namingStrategy = container.pluginReference(JaxrsServiceNamingStrategy.class, new DefaultJaxrsServiceNamingStrategy()); - this.proxyCacheSupplier = Suppliers.memoize(this::createProxyCache); - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsProxyFactory Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public T createProxy(Class serviceInterface) { - return dynamicProxyStrategy.get().createDynamicProxy(serviceInterface, () -> serviceInterface.cast(proxyCacheSupplier.get().getUnchecked(serviceInterface).getTarget()), "Microbule \"%s\" proxy", serviceInterface.getSimpleName()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// RemovalListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void onRemoval(RemovalNotification, JaxrsProxyDispatcher> notification) { - notification.getValue().close(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private LoadingCache, JaxrsProxyDispatcher> createProxyCache() { - final Config config = configService.createConfig(JaxrsProxyFactory.class.getSimpleName(), "cache"); - final Long expiration = config.longValue("expiration").orElse(5L); - final TimeUnit expirationUnit = config.enumValue("expirationUnit", TimeUnit.class).orElse(TimeUnit.MINUTES); - return CacheBuilder.newBuilder() - .removalListener(this) - .expireAfterAccess(expiration, expirationUnit).build(new CacheLoader, JaxrsProxyDispatcher>() { - @Override - public JaxrsProxyDispatcher load(Class serviceInterface) throws Exception { - return createDispatcher(serviceInterface); - } - }); - } - - private JaxrsProxyDispatcher createDispatcher(Class serviceInterface) { - final String serviceName = namingStrategy.get().serviceName(serviceInterface); - LOGGER.info("Creating \"{}\" proxy dispatcher ({})...", serviceName, serviceInterface.getSimpleName()); - final JaxrsProxyCache proxyCache = createProxyCache(serviceInterface, serviceName); - final JaxrsAddressChooser addressChooser = createEndpointChooser(serviceInterface, serviceName); - return new JaxrsProxyDispatcher<>(proxyCache, addressChooser); - } - - private JaxrsProxyCache createProxyCache(Class serviceInterface, String serviceName) { - final Config cacheConfig = configService.createConfig(JaxrsProxyFactory.class.getSimpleName(), "cache"); - LOGGER.debug("Creating JaxrsProxyCache<{}> for \"{}\" service.", serviceInterface.getSimpleName(), serviceName); - return new JaxrsProxyCache<>(baseAddress -> { - final RecordingConfig recordingConfig = new RecordingConfig(configService.createProxyConfig(serviceInterface, serviceName)); - final DefaultJaxrsServiceDescriptor descriptor = new DefaultJaxrsServiceDescriptor(serviceInterface, serviceName); - decorate(descriptor, recordingConfig); - final T proxy = JAXRSClientFactory.create(baseAddress, serviceInterface, descriptor.getProviders(), descriptor.getFeatures(), null); - return new CachedJaxrsProxy<>(proxy, recordingConfig.getRecordedJson()); - }, schedulerService, serviceName, cacheConfig); - } - - private JaxrsAddressChooser createEndpointChooser(Class serviceInterface, String serviceName) { - LOGGER.debug("Creating \"{}\" service JaxrsAddressChooser ({})...", serviceName, serviceInterface.getSimpleName()); - return serviceDiscovery.get().createAddressChooser(serviceInterface, serviceName); - } - - @PreDestroy - public void destroy() { - proxyCacheSupplier.get().invalidateAll(); - } - - @Override - protected Logger getLogger() { - return LOGGER; - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsServerFactory.java b/core/src/main/java/org/microbule/core/DefaultJaxrsServerFactory.java deleted file mode 100644 index 61f4c98..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsServerFactory.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.concurrent.atomic.AtomicReference; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.apache.commons.lang3.StringUtils; -import org.apache.cxf.BusFactory; -import org.apache.cxf.endpoint.Server; -import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; -import org.microbule.api.JaxrsConfigService; -import org.microbule.api.JaxrsServer; -import org.microbule.api.JaxrsServerFactory; -import org.microbule.config.api.Config; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceNamingStrategy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("jaxrsServerFactory") -public class DefaultJaxrsServerFactory extends JaxrsServiceDecoratorRegistry implements JaxrsServerFactory { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final String SERVER_ADDRESS_PROP = "serverAddress"; - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultJaxrsServerFactory.class); - public static final String BASE_ADDRESS_PROP = "baseAddress"; - - private final JaxrsConfigService configService; - private final AtomicReference namingStrategy; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultJaxrsServerFactory(MicrobuleContainer container, JaxrsConfigService configService) { - super(JaxrsServerDecorator.class, container); - this.configService = configService; - this.namingStrategy = container.pluginReference(JaxrsServiceNamingStrategy.class, new DefaultJaxrsServiceNamingStrategy()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServerFactory Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public JaxrsServer createJaxrsServer(Class serviceInterface, Object serviceImplementation) { - final String serviceName = namingStrategy.get().serviceName(serviceInterface); - final Config serverConfig = configService.createServerConfig(serviceInterface, serviceName); - final String baseAddress = serverConfig.value(BASE_ADDRESS_PROP).orElse(StringUtils.EMPTY); - final String serverAddress = serverConfig.value(SERVER_ADDRESS_PROP).orElse(namingStrategy.get().serverAddress(serviceInterface)); - final String fullAddress = baseAddress + serverAddress; - LOGGER.info("Starting {} JAX-RS server ({})...", serviceInterface.getSimpleName(), fullAddress); - - final DefaultJaxrsServiceDescriptor descriptor = new DefaultJaxrsServiceDescriptor(serviceInterface, serviceName); - decorate(descriptor, serverConfig); - final JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); - sf.setBus(BusFactory.getDefaultBus(true)); - sf.setServiceBean(serviceImplementation); - - sf.setAddress(fullAddress); - sf.setFeatures(descriptor.getFeatures()); - sf.setProviders(descriptor.getProviders()); - final Server server = sf.create(); - LOGGER.info("Successfully started {} JAX-RS server ({}).", serviceInterface.getSimpleName(), serverAddress); - return server::destroy; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected Logger getLogger() { - return LOGGER; - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsServiceDescriptor.java b/core/src/main/java/org/microbule/core/DefaultJaxrsServiceDescriptor.java deleted file mode 100644 index aa4b7a1..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsServiceDescriptor.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.LinkedList; -import java.util.List; - -import org.apache.cxf.feature.Feature; -import org.microbule.spi.JaxrsServiceDescriptor; - -public class DefaultJaxrsServiceDescriptor implements JaxrsServiceDescriptor { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Class serviceInterface; - private final String serviceName; - private final List providers = new LinkedList<>(); - private final List features = new LinkedList<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - DefaultJaxrsServiceDescriptor(Class serviceInterface, String serviceName) { - this.serviceInterface = serviceInterface; - this.serviceName = serviceName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDescriptor Implementation -//---------------------------------------------------------------------------------------------------------------------- - - public JaxrsServiceDescriptor addFeature(Feature feature) { - features.add(feature); - return this; - } - - public JaxrsServiceDescriptor addProvider(Object provider) { - providers.add(provider); - return this; - } - - public Class serviceInterface() { - return serviceInterface; - } - - @Override - public String serviceName() { - return serviceName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - List getFeatures() { - return features; - } - - List getProviders() { - return providers; - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsServiceDiscovery.java b/core/src/main/java/org/microbule/core/DefaultJaxrsServiceDiscovery.java deleted file mode 100644 index e29a519..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsServiceDiscovery.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import org.microbule.api.JaxrsConfigService; -import org.microbule.config.api.Config; -import org.microbule.config.api.ConfigurationException; -import org.microbule.spi.JaxrsAddressChooser; -import org.microbule.spi.JaxrsServiceDiscovery; - -public class DefaultJaxrsServiceDiscovery implements JaxrsServiceDiscovery { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final String PROXY_ADDRESS_PROP = "proxyAddress"; - - private final JaxrsConfigService configService; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DefaultJaxrsServiceDiscovery(JaxrsConfigService configService) { - this.configService = configService; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDiscovery Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public JaxrsAddressChooser createAddressChooser(Class serviceInterface, String serviceName) { - final Config config = configService.createProxyConfig(serviceInterface, serviceName); - final String baseAddress = config.value(PROXY_ADDRESS_PROP).orElseThrow(() -> new ConfigurationException("Missing '%s' property.", PROXY_ADDRESS_PROP)); - return () -> baseAddress; - } -} diff --git a/core/src/main/java/org/microbule/core/DefaultJaxrsServiceNamingStrategy.java b/core/src/main/java/org/microbule/core/DefaultJaxrsServiceNamingStrategy.java deleted file mode 100644 index 5f9585b..0000000 --- a/core/src/main/java/org/microbule/core/DefaultJaxrsServiceNamingStrategy.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.Optional; -import java.util.function.Function; - -import org.apache.commons.lang3.StringUtils; -import org.microbule.annotation.JaxrsService; -import org.microbule.spi.JaxrsServiceNamingStrategy; - -public class DefaultJaxrsServiceNamingStrategy implements JaxrsServiceNamingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceNamingStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String serverAddress(Class serviceInterface) { - final String fallback = "/" + serviceName(serviceInterface); - return annotationProperty(serviceInterface, fallback, annotation -> StringUtils.defaultIfBlank(annotation.serverAddress(), fallback)); - } - - @Override - public String serviceName(Class serviceInterface) { - final String fallback = serviceInterface.getSimpleName(); - return annotationProperty(serviceInterface, fallback, annotation -> StringUtils.defaultIfBlank(annotation.name(), fallback)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private T annotationProperty(Class serviceInterface, T fallback, Function fn) { - return Optional.ofNullable(serviceInterface.getAnnotation(JaxrsService.class)) - .map(fn) - .orElse(fallback); - } -} diff --git a/core/src/main/java/org/microbule/core/JaxrsProxyCache.java b/core/src/main/java/org/microbule/core/JaxrsProxyCache.java deleted file mode 100644 index 48f4718..0000000 --- a/core/src/main/java/org/microbule/core/JaxrsProxyCache.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.concurrent.TimeUnit; -import java.util.function.Function; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.microbule.config.api.Config; -import org.microbule.scheduler.api.RefreshableReference; -import org.microbule.scheduler.api.SchedulerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -class JaxrsProxyCache implements RemovalListener>>, AutoCloseable { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); - private static final String TIMEOUT_PROP = "timeout"; - private static final String TIMEOUT_UNIT_PROP = "timeoutUnit"; - private static final String REFRESH_DELAY_PROP = "refreshDelay"; - private static final String REFRESH_DELAY_UNIT_PROP = "refreshDelayUnit"; - private static final long DEFAULT_TIMEOUT = 5; - private static final TimeUnit DEFAULT_UNIT = TimeUnit.MINUTES; - private static final long DEFAULT_REFRESH_DELAY = 1; - private static final Logger LOGGER = LoggerFactory.getLogger(JaxrsProxyCache.class); - private final LoadingCache>> cache; - private final String serviceName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - JaxrsProxyCache(Function> factory, SchedulerService schedulerService, String serviceName, Config cacheConfig) { - this.serviceName = serviceName; - final long timeout = cacheConfig.longValue(TIMEOUT_PROP).orElse(DEFAULT_TIMEOUT); - final TimeUnit timeoutUnit = cacheConfig.enumValue(TIMEOUT_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_UNIT); - final long refreshDelay = cacheConfig.longValue(REFRESH_DELAY_PROP).orElse(DEFAULT_REFRESH_DELAY); - final TimeUnit refreshDelayUnit = cacheConfig.enumValue(REFRESH_DELAY_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_UNIT); - this.cache = CacheBuilder.newBuilder() - .removalListener(this) - .expireAfterAccess(timeout, timeoutUnit) - .build(new CacheLoader>>() { - @Override - public RefreshableReference> load(String address) throws Exception { - return schedulerService.createRefreshableReference(currentValue -> { - final CachedJaxrsProxy newValue = factory.apply(address); - if (currentValue == null) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Created dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, GSON.toJson(newValue.getConfig())); - } - return newValue; - } else if (currentValue.getConfig().equals(newValue.getConfig())) { - LOGGER.debug("Retained current dynamic proxy for \"{}\" service at address: {}", serviceName, address); - return currentValue; - } else { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Refreshed dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, GSON.toJson(newValue.getConfig())); - } - return newValue; - } - }, refreshDelay, refreshDelayUnit); - } - }); - } - -//---------------------------------------------------------------------------------------------------------------------- -// AutoCloseable Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void close() { - cache.invalidateAll(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// RemovalListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void onRemoval(RemovalNotification>> notification) { - LOGGER.debug("Canceling dynamic proxy refresh for \"{}\" service.", serviceName); - notification.getValue().cancel(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - T getTarget(String address) { - return cache.getUnchecked(address).get().getProxy(); - } -} diff --git a/core/src/main/java/org/microbule/core/JaxrsProxyDispatcher.java b/core/src/main/java/org/microbule/core/JaxrsProxyDispatcher.java deleted file mode 100644 index ce09d4c..0000000 --- a/core/src/main/java/org/microbule/core/JaxrsProxyDispatcher.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.microbule.core; - -import org.microbule.spi.JaxrsAddressChooser; - -public class JaxrsProxyDispatcher implements AutoCloseable { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final JaxrsProxyCache targetCache; - private final JaxrsAddressChooser addressChooser; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public JaxrsProxyDispatcher(JaxrsProxyCache targetCache, JaxrsAddressChooser addressChooser) { - this.targetCache = targetCache; - this.addressChooser = addressChooser; - } - -//---------------------------------------------------------------------------------------------------------------------- -// AutoCloseable Implementation -//---------------------------------------------------------------------------------------------------------------------- - - public void close() { - addressChooser.close(); - targetCache.close(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public T getTarget() { - return targetCache.getTarget(addressChooser.chooseAddress()); - } -} diff --git a/core/src/main/java/org/microbule/core/JaxrsServerBootstrap.java b/core/src/main/java/org/microbule/core/JaxrsServerBootstrap.java deleted file mode 100644 index 68424e0..0000000 --- a/core/src/main/java/org/microbule/core/JaxrsServerBootstrap.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.common.collect.MapMaker; -import org.microbule.annotation.Startup; -import org.microbule.api.JaxrsServer; -import org.microbule.api.JaxrsServerFactory; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.api.ServerListener; - -@Named("jaxrsServerBootstrap") -@Singleton -@Startup -public class JaxrsServerBootstrap implements ServerListener { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final JaxrsServerFactory factory; - private final Map servers = new MapMaker().makeMap(); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public JaxrsServerBootstrap(MicrobuleContainer container, JaxrsServerFactory factory) { - this.factory = factory; - container.addServerListener(this); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ServerListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void registerServer(ServerDefinition serverDefinition) { - final JaxrsServer server = factory.createJaxrsServer(serverDefinition.serviceInterface(), serverDefinition.serviceImplementation()); - servers.put(serverDefinition.id(), server); - } - - @Override - public void unregisterServer(String id) { - JaxrsServer server = servers.remove(id); - if (server != null) { - server.shutdown(); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// Canonical Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String toString() { - return "JAX-RS Server Bootstrap"; - } -} diff --git a/core/src/main/java/org/microbule/core/JaxrsServiceDecoratorRegistry.java b/core/src/main/java/org/microbule/core/JaxrsServiceDecoratorRegistry.java deleted file mode 100644 index 6693111..0000000 --- a/core/src/main/java/org/microbule/core/JaxrsServiceDecoratorRegistry.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.Map; - -import org.microbule.config.api.Config; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.spi.JaxrsServiceDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.slf4j.Logger; - -public abstract class JaxrsServiceDecoratorRegistry { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String ENABLED_PROPERTY = "enabled"; - private final Map decoratorsMap; - private final Class decoratorType; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public JaxrsServiceDecoratorRegistry(Class decoratorType, MicrobuleContainer container) { - this.decoratorType = decoratorType; - this.decoratorsMap = container.pluginMap(decoratorType, JaxrsServiceDecorator::name); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract Logger getLogger(); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - decoratorsMap.forEach((name, decorator) -> { - final Config decoratorConfig = config.filtered(name); - if (decoratorConfig.booleanValue(ENABLED_PROPERTY).orElse(Boolean.TRUE)) { - getLogger().debug("Decorating {} service using {} \"{}\".", descriptor.serviceInterface().getSimpleName(), decoratorType.getSimpleName(), name); - decorator.decorate(descriptor, decoratorConfig); - } else { - getLogger().debug("Skipping decorator {} \"{}\" for service {}.", name, decoratorType.getSimpleName(), descriptor.serviceInterface().getSimpleName()); - } - }); - } -} diff --git a/core/src/main/java/org/microbule/core/JdkDynamicProxyStrategy.java b/core/src/main/java/org/microbule/core/JdkDynamicProxyStrategy.java deleted file mode 100644 index a3869f5..0000000 --- a/core/src/main/java/org/microbule/core/JdkDynamicProxyStrategy.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import java.util.function.Supplier; - -import org.microbule.spi.JaxrsDynamicProxyStrategy; -import org.microbule.util.proxy.DynamicProxyUtils; - -public class JdkDynamicProxyStrategy implements JaxrsDynamicProxyStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsDynamicProxyStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public T createDynamicProxy(Class type, Supplier targetSupplier, String descriptionPattern, Object... descriptionParams) { - return DynamicProxyUtils.createProxy(type, targetSupplier, descriptionPattern, descriptionParams); - } -} diff --git a/core/src/main/resources/META-INF/beans.xml b/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/core/src/main/resources/OSGI-INF/blueprint/microbule-core.xml b/core/src/main/resources/OSGI-INF/blueprint/microbule-core.xml deleted file mode 100644 index 57835cc..0000000 --- a/core/src/main/resources/OSGI-INF/blueprint/microbule-core.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/DefaultJaxrsConfigBuilderStrategyTest.java b/core/src/test/java/org/microbule/core/DefaultJaxrsConfigBuilderStrategyTest.java deleted file mode 100644 index c45de7d..0000000 --- a/core/src/test/java/org/microbule/core/DefaultJaxrsConfigBuilderStrategyTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import org.junit.Before; -import org.junit.Test; -import org.microbule.spi.JaxrsConfigBuilder; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.mockito.InOrder; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -public class DefaultJaxrsConfigBuilderStrategyTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private JaxrsConfigBuilder configBuilder; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testBuildProxyConfig() { - final DefaultJaxrsConfigBuilderStrategy strategy = new DefaultJaxrsConfigBuilderStrategy(); - strategy.buildProxyConfig(configBuilder); - - final InOrder order = inOrder(configBuilder); - order.verify(configBuilder).serviceName(); - order.verify(configBuilder).withPath("hello", "proxy"); - order.verify(configBuilder).withPath("hello"); - order.verify(configBuilder).withPath("default", "proxy"); - - verifyNoMoreInteractions(configBuilder); - } - - @Test - public void testBuildServerConfig() { - final DefaultJaxrsConfigBuilderStrategy strategy = new DefaultJaxrsConfigBuilderStrategy(); - strategy.buildServerConfig(configBuilder); - - final InOrder order = inOrder(configBuilder); - order.verify(configBuilder).serviceName(); - order.verify(configBuilder).withPath("hello", "server"); - order.verify(configBuilder).withPath("hello"); - order.verify(configBuilder).withPath("default", "server"); - - verifyNoMoreInteractions(configBuilder); - } - - @Before - public void trainMock() { - when(configBuilder.withPath(any())).thenReturn(configBuilder); - when(configBuilder.serviceInterface()).thenReturn(HelloService.class); - when(configBuilder.serviceName()).thenReturn("hello"); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/DefaultJaxrsConfigBuilderTest.java b/core/src/test/java/org/microbule/core/DefaultJaxrsConfigBuilderTest.java deleted file mode 100644 index 0d2635b..0000000 --- a/core/src/test/java/org/microbule/core/DefaultJaxrsConfigBuilderTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.microbule.core; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.api.ConfigService; -import org.microbule.config.core.MapConfig; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.mockito.Mock; - -import static org.mockito.Mockito.when; - -public class DefaultJaxrsConfigBuilderTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private ConfigService configService; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testBuild() { - final DefaultJaxrsConfigBuilder builder = new DefaultJaxrsConfigBuilder<>(configService, HelloService.class, "hello"); - MapConfig c = new MapConfig(); - c.addValue("key", "value1"); - when(configService.createConfig("a", "b", "c")).thenReturn(c); - MapConfig d = new MapConfig(); - d.addValue("key", "value2"); - when(configService.createConfig("a", "b", "d")).thenReturn(d); - final Config config = builder.withPath("a", "b", "c") - .withPath("a", "b", "d") - .build(); - assertEquals("value1", config.value("key").get()); - } - - @Test - public void testConstructor() { - final DefaultJaxrsConfigBuilder builder = new DefaultJaxrsConfigBuilder<>(configService, HelloService.class, "hello"); - assertEquals(HelloService.class, builder.serviceInterface()); - assertEquals("hello", builder.serviceName()); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/DefaultJaxrsConfigServiceTest.java b/core/src/test/java/org/microbule/core/DefaultJaxrsConfigServiceTest.java deleted file mode 100644 index 5ec24dc..0000000 --- a/core/src/test/java/org/microbule/core/DefaultJaxrsConfigServiceTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import org.junit.Before; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.api.ConfigService; -import org.microbule.config.core.CompositeConfig; -import org.microbule.config.core.EmptyConfig; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.mockito.InOrder; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DefaultJaxrsConfigServiceTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private ConfigService configService; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateProxyConfig() { - SimpleContainer container = new SimpleContainer(); - final DefaultJaxrsConfigService service = new DefaultJaxrsConfigService(container, configService); - - final Config config = service.createProxyConfig(HelloService.class, "hello"); - assertTrue(config instanceof CompositeConfig); - final InOrder inOrder = inOrder(configService); - inOrder.verify(configService).createConfig("hello", "proxy"); - inOrder.verify(configService).createConfig("hello"); - inOrder.verify(configService).createConfig("default", "proxy"); - } - - @Test - public void testCreateServerConfig() { - SimpleContainer container = new SimpleContainer(); - final DefaultJaxrsConfigService service = new DefaultJaxrsConfigService(container, configService); - - final Config config = service.createServerConfig(HelloService.class, "hello"); - final InOrder inOrder = inOrder(configService); - inOrder.verify(configService).createConfig("hello", "server"); - inOrder.verify(configService).createConfig("hello"); - inOrder.verify(configService).createConfig("default", "server"); - - } - - @Test - public void testCreateConfig() { - SimpleContainer container = new SimpleContainer(); - final DefaultJaxrsConfigService service = new DefaultJaxrsConfigService(container, configService); - final Config config = service.createConfig("one", "two", "three"); - verify(configService).createConfig("one", "two", "three"); - } - - @Before - public void trainMock() { - when(configService.createConfig(any())).thenReturn(EmptyConfig.INSTANCE); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/DefaultJaxrsServerFactoryTest.java b/core/src/test/java/org/microbule/core/DefaultJaxrsServerFactoryTest.java deleted file mode 100644 index 4d18d32..0000000 --- a/core/src/test/java/org/microbule/core/DefaultJaxrsServerFactoryTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.microbule.api.JaxrsConfigService; -import org.microbule.config.api.Config; -import org.microbule.config.core.EmptyConfig; -import org.microbule.config.core.MapConfig; -import org.microbule.container.core.SimpleContainer; -import org.microbule.scheduler.api.SchedulerService; -import org.microbule.scheduler.core.DefaultSchedulerService; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - -public class DefaultJaxrsServerFactoryTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final String ADDRESS = "http://localhost:8383/hello"; - - @Mock - private JaxrsProxyDecorator proxyDecorator; - - @Mock - private JaxrsServerDecorator serverDecorator; - - @Mock - private JaxrsServerDecorator ignoredServerDecorator; - - @Mock - private JaxrsProxyDecorator ignoredProxyDecorator; - - @Mock - private JaxrsConfigService configService; - - private SchedulerService schedulerService = new DefaultSchedulerService(1); - - - private DefaultJaxrsProxyFactory proxyFactory; - private SimpleContainer container; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void startServer() { - container = new SimpleContainer(); - - MapConfig serverConfig = new MapConfig(); - serverConfig.addValue("serverAddress", ADDRESS); - serverConfig.addValue("ignored.enabled", "false"); - when(configService.createServerConfig(HelloService.class, "HelloService")).thenReturn(serverConfig); - - MapConfig proxyConfig1 = new MapConfig(); - proxyConfig1.addValue("proxyAddress", ADDRESS); - proxyConfig1.addValue("ignored.enabled", "false"); - - MapConfig proxyConfig2 = new MapConfig(); - proxyConfig2.addValue("proxyAddress", ADDRESS); - proxyConfig2.addValue("ignored.enabled", "true"); - when(configService.createProxyConfig(HelloService.class, "HelloService")).thenReturn(proxyConfig1, proxyConfig1, proxyConfig2); - - - when(configService.createConfig(any())).thenReturn(EmptyConfig.INSTANCE); - - MapConfig cacheConfig = new MapConfig(); - cacheConfig.addValue("refreshDelay", "20"); - cacheConfig.addValue("refreshDelayUnit", "MILLISECONDS"); - - when(configService.createConfig("JaxrsProxyFactory", "cache")).thenReturn(cacheConfig); - - when(serverDecorator.name()).thenReturn("mock"); - container.addBean(serverDecorator); - when(ignoredServerDecorator.name()).thenReturn("ignored"); - container.addBean(ignoredServerDecorator); - - when(proxyDecorator.name()).thenReturn("mock"); - container.addBean(proxyDecorator); - when(ignoredProxyDecorator.name()).thenReturn("ignored"); - container.addBean(ignoredProxyDecorator); - - proxyFactory = new DefaultJaxrsProxyFactory(container, configService, schedulerService); - - container.addBean(new HelloServiceImpl()); - - new JaxrsServerBootstrap(container, new DefaultJaxrsServerFactory(container, configService)); - container.initialize(); - verify(serverDecorator).decorate(any(JaxrsServiceDescriptor.class), any(Config.class)); - } - - @After - public void stopServer() { - container.shutdown(); - proxyFactory.destroy(); - } - - @Test - public void testCallingService() { - final HelloService hello = proxyFactory.createProxy(HelloService.class); - - - assertEquals("Hello, Microbule!", hello.sayHello("Microbule")); - - verify(proxyDecorator, atLeastOnce()).decorate(any(JaxrsServiceDescriptor.class), any(Config.class)); - } - - @Test - public void testCallingServiceWithoutLogging() { - final String greeting = createWithoutLogging(() -> proxyFactory.createProxy(HelloService.class).sayHello("Microbule")); - - assertEquals("Hello, Microbule!", greeting); - - verify(proxyDecorator, atLeastOnce()).decorate(any(JaxrsServiceDescriptor.class), any(Config.class)); - } - - @Test - public void testCallingServiceAfterRefresh() { - final HelloService hello = proxyFactory.createProxy(HelloService.class); - - assertEquals("Hello, Microbule!", hello.sayHello("Microbule")); - await(100); - assertEquals("Hello, Microbule!", hello.sayHello("Microbule")); - } - - @Test - public void testCallingServiceAfterRefreshWithoutLogging() { - final String greeting = createWithoutLogging(() -> { - final HelloService hello = proxyFactory.createProxy(HelloService.class); - hello.sayHello("Microbule"); - await(100); - return hello.sayHello("Microbule"); - }); - - assertEquals("Hello, Microbule!", greeting); - } -} diff --git a/core/src/test/java/org/microbule/core/DefaultJaxrsServiceDescriptorTest.java b/core/src/test/java/org/microbule/core/DefaultJaxrsServiceDescriptorTest.java deleted file mode 100644 index b042776..0000000 --- a/core/src/test/java/org/microbule/core/DefaultJaxrsServiceDescriptorTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import org.apache.cxf.feature.LoggingFeature; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.microbule.test.core.hello.HelloService; - -public class DefaultJaxrsServiceDescriptorTest extends Assert { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private DefaultJaxrsServiceDescriptor descriptor; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initConfig() { - descriptor = new DefaultJaxrsServiceDescriptor(HelloService.class, "hello"); - } - - @Test - public void testAddFeature() { - descriptor.addFeature(new LoggingFeature()); - assertEquals(1, descriptor.getFeatures().size()); - } - - @Test - public void testAddProvider() { - descriptor.addProvider(new Object()); - assertEquals(1, descriptor.getProviders().size()); - } - - @Test - public void testServiceInterface() { - assertEquals(HelloService.class, descriptor.serviceInterface()); - } - - @Test - public void testServiceName() { - assertEquals("hello", descriptor.serviceName()); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/DefaultJaxrsServiceNamingStrategyTest.java b/core/src/test/java/org/microbule/core/DefaultJaxrsServiceNamingStrategyTest.java deleted file mode 100644 index e314c97..0000000 --- a/core/src/test/java/org/microbule/core/DefaultJaxrsServiceNamingStrategyTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core; - -import javax.ws.rs.Path; - -import org.junit.Test; -import org.microbule.annotation.JaxrsService; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; - -public class DefaultJaxrsServiceNamingStrategyTest extends MockObjectTestCase { - - @Test - public void testFallbackNaming() { - final DefaultJaxrsServiceNamingStrategy namingStrategy = new DefaultJaxrsServiceNamingStrategy(); - assertEquals("HelloService", namingStrategy.serviceName(HelloService.class)); - assertEquals("UnnamedService", namingStrategy.serviceName(UnnamedService.class)); - } - - @Test - public void testWithSpecifiedName() { - final DefaultJaxrsServiceNamingStrategy namingStrategy = new DefaultJaxrsServiceNamingStrategy(); - assertEquals("coolService", namingStrategy.serviceName(MyCoolService.class)); - } - - @Test - public void testWithSpecifiedServerAddress() { - final DefaultJaxrsServiceNamingStrategy namingStrategy = new DefaultJaxrsServiceNamingStrategy(); - assertEquals("/cool", namingStrategy.serverAddress(MyCoolService.class)); - } - - @Test - public void testWithFallbackServerAddress() { - final DefaultJaxrsServiceNamingStrategy namingStrategy = new DefaultJaxrsServiceNamingStrategy(); - assertEquals("/UnnamedService", namingStrategy.serverAddress(UnnamedService.class)); - } - - @Path("/") - @JaxrsService(name = "coolService", serverAddress = "/cool") - public interface MyCoolService { - - } - - @Path("/") - @JaxrsService - public interface UnnamedService { - - } -} \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/JaxrsServerBootstrapTest.java b/core/src/test/java/org/microbule/core/JaxrsServerBootstrapTest.java deleted file mode 100644 index 2ee7931..0000000 --- a/core/src/test/java/org/microbule/core/JaxrsServerBootstrapTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.microbule.core; - -import org.junit.Test; -import org.microbule.api.JaxrsServerFactory; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -public class JaxrsServerBootstrapTest extends MockObjectTestCase { - - @Mock - private MicrobuleContainer container; - - @Mock - private JaxrsServerFactory factory; - - @Test - public void testToString() { - final JaxrsServerBootstrap bootstrap = new JaxrsServerBootstrap(container, factory); - assertEquals("JAX-RS Server Bootstrap", bootstrap.toString()); - } -} \ No newline at end of file diff --git a/core/src/test/java/org/microbule/core/providers/RequestCountClientFilter.java b/core/src/test/java/org/microbule/core/providers/RequestCountClientFilter.java deleted file mode 100644 index 8fcacf0..0000000 --- a/core/src/test/java/org/microbule/core/providers/RequestCountClientFilter.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core.providers; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicLong; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.ext.Provider; - -@Provider -public class RequestCountClientFilter implements ClientRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicLong requestCount = new AtomicLong(); - -//---------------------------------------------------------------------------------------------------------------------- -// ClientRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - requestCount.incrementAndGet(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public AtomicLong getRequestCount() { - return requestCount; - } -} diff --git a/core/src/test/java/org/microbule/core/providers/RequestCountContainerFilter.java b/core/src/test/java/org/microbule/core/providers/RequestCountContainerFilter.java deleted file mode 100644 index f924c59..0000000 --- a/core/src/test/java/org/microbule/core/providers/RequestCountContainerFilter.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.core.providers; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicLong; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.ext.Provider; - -@Provider -public class RequestCountContainerFilter implements ContainerRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicLong requestCount = new AtomicLong(); - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - requestCount.incrementAndGet(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public AtomicLong getRequestCount() { - return requestCount; - } -} diff --git a/cors.md b/cors.md new file mode 100644 index 0000000..dd54766 --- /dev/null +++ b/cors.md @@ -0,0 +1,3 @@ +# Cross-Origin Resource Scripting (CORS) + +Microbule supports CORS requests. diff --git a/cors/pom.xml b/cors/pom.xml deleted file mode 100644 index 1869c08..0000000 --- a/cors/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-cors-decorator - Microbule :: CORS :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/cors/src/main/java/org/microbule/cors/decorator/CorsDecorator.java b/cors/src/main/java/org/microbule/cors/decorator/CorsDecorator.java deleted file mode 100644 index 5e33c1e..0000000 --- a/cors/src/main/java/org/microbule/cors/decorator/CorsDecorator.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cors.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("corsDecorator") -public class CorsDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new CorsFilter(config)); - } - - @Override - public String name() { - return "cors"; - } -} diff --git a/cors/src/main/java/org/microbule/cors/decorator/CorsFilter.java b/cors/src/main/java/org/microbule/cors/decorator/CorsFilter.java deleted file mode 100644 index c9d7e92..0000000 --- a/cors/src/main/java/org/microbule/cors/decorator/CorsFilter.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cors.decorator; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.container.PreMatching; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import org.microbule.config.api.Config; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Provider -@PreMatching -public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String DEFAULT_ALLOWED_METHODS = "HEAD, GET, PUT, POST, DELETE"; - private static final String COMMA_SEPARATED = ","; - static final String ALLOWED_ORIGINS_PROP = "allowedOrigins"; - private static final String ALLOW_CREDENTIALS_PROP = "allowCredentials"; - static final String ALLOWED_METHODS_PROP = "allowedMethods"; - static final String ALLOWED_HEADERS_PROP = "allowedHeaders"; - private static final String MAX_AGE_PROP = "maxAge"; - private static final String EXPOSED_HEADERS_PROP = "exposedHeaders"; - private static final String EMPTY_STRING = ""; - private static final Logger LOGGER = LoggerFactory.getLogger(CorsFilter.class); - private static final String PREFLIGHT_FLAG_PROP = "CorsFilter.preflightFlag"; - private static final Set SIMPLE_RESPONSE_HEADERS = new HashSet<>(Arrays.asList( - "CACHE-CONTROL", - "CONTENT-LANGUAGE", - "CONTENT-TYPE", - "EXPIRES", - "LAST-MODIFIED", - "PRAGMA" - )); - - private static final String HEADER_ORIGIN = "Origin"; - private static final String HEADER_AC_REQUEST_METHOD = "Access-Control-Request-Method"; - private static final String HEADER_AC_REQUEST_HEADERS = "Access-Control-Request-Headers"; - private static final String HEADER_AC_ALLOW_METHODS = "Access-Control-Allow-Methods"; - private static final String HEADER_AC_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; - private static final String HEADER_AC_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; - private static final String HEADER_AC_MAX_AGE = "Access-Control-Max-Age"; - - private static final String HEADER_AC_ALLOW_HEADERS = "Access-Control-Allow-Headers"; - private static final String HEADER_VARY = "Vary"; - private static final String HEADER_AC_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; - - private static final String HTTP_METHOD_OPTIONS = "OPTIONS"; - - private static final String ALLOW_ALL = "*"; - private static final long DEFAULT_MAX_AGE = TimeUnit.DAYS.toSeconds(1); - - private final Set allowedOrigins; - private final Set allowedMethods; - private final Set allowedHeaders; - private final Set exposedHeaders; - private final boolean allowCredentials; - private final long maxAge; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - CorsFilter(Config config) { - this.allowedOrigins = parseWhitelist(config.value(ALLOWED_ORIGINS_PROP).orElse(ALLOW_ALL)); - this.allowedMethods = parseWhitelist(config.value(ALLOWED_METHODS_PROP).orElse(DEFAULT_ALLOWED_METHODS)); - this.allowedHeaders = parseWhitelist(config.value(ALLOWED_HEADERS_PROP).orElse(ALLOW_ALL).toUpperCase()); - this.exposedHeaders = parseCommaSeparatedSet(config.value(EXPOSED_HEADERS_PROP).orElse(EMPTY_STRING)); - this.maxAge = config.longValue(MAX_AGE_PROP).orElse(DEFAULT_MAX_AGE); - this.allowCredentials = config.booleanValue(ALLOW_CREDENTIALS_PROP).orElse(Boolean.FALSE); - } - - private static Set parseWhitelist(String whitelist) { - if (ALLOW_ALL.equals(whitelist)) { - return new HashSet<>(); - } else { - return parseCommaSeparatedSet(whitelist); - } - } - - private static Set parseCommaSeparatedSet(String value) { - if (EMPTY_STRING.equals(value)) { - return new HashSet<>(); - } - return Arrays.stream(value.split(COMMA_SEPARATED)).map(String::trim).collect(Collectors.toSet()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext request) throws IOException { - if (isPreflight(request)) { - LOGGER.debug("Handling pre-flight CORS request: {} {}", request.getMethod(), request.getUriInfo().getPath()); - request.abortWith(handlePreflight(request)); - request.setProperty(PREFLIGHT_FLAG_PROP, Boolean.TRUE); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerResponseFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { - if (!Boolean.TRUE.equals(request.getProperty(PREFLIGHT_FLAG_PROP))) { - final MultivaluedMap headers = response.getHeaders(); - final String origin = request.getHeaderString(HEADER_ORIGIN); - if (origin != null && isAllowedOrigin(origin)) { - LOGGER.debug("Handling simple CORS request: {} {}", request.getMethod(), request.getUriInfo().getPath()); - exposedHeaders.forEach(header -> headers.add(HEADER_AC_EXPOSE_HEADERS, header)); - headers.add(HEADER_AC_ALLOW_ORIGIN, origin); - headers.add(HEADER_AC_ALLOW_CREDENTIALS, String.valueOf(allowCredentials)); - } - headers.add(HEADER_VARY, HEADER_ORIGIN); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private Response handlePreflight(ContainerRequestContext request) { - final String origin = request.getHeaderString(HEADER_ORIGIN); - if (!isAllowedOrigin(origin)) { - LOGGER.warn("CORS pre-flight failed: origin \"{}\".", origin); - return failedPreflight(); - } - final String method = request.getHeaderString(HEADER_AC_REQUEST_METHOD); - if (!isWhitelisted(allowedMethods, method)) { - LOGGER.warn("CORS pre-flight failed: method \"{}\".", method); - return failedPreflight(); - } - final List requestHeaders = request.getHeaders().getOrDefault(HEADER_AC_REQUEST_HEADERS, new LinkedList<>()).stream().filter(header -> !SIMPLE_RESPONSE_HEADERS.contains(header)).collect(Collectors.toList()); - final Optional invalidHeader = requestHeaders.stream().filter(requestHeader -> !isWhitelisted(allowedHeaders, requestHeader.toUpperCase())).findFirst(); - if (invalidHeader.isPresent()) { - LOGGER.warn("CORS pre-flight failed: header \"{}\".", invalidHeader.get()); - return failedPreflight(); - } - final Response.ResponseBuilder builder = Response.noContent(); - builder.header(HEADER_VARY, HEADER_ORIGIN); - builder.header(HEADER_AC_ALLOW_ORIGIN, origin); - builder.header(HEADER_AC_ALLOW_CREDENTIALS, String.valueOf(allowCredentials)); - builder.header(HEADER_AC_MAX_AGE, String.valueOf(maxAge)); - allowedMethods.forEach(allowedMethod -> builder.header(HEADER_AC_ALLOW_METHODS, allowedMethod)); - requestHeaders.forEach(requestHeader -> builder.header(HEADER_AC_ALLOW_HEADERS, requestHeader)); - return builder.build(); - } - - private boolean isAllowedOrigin(String origin) { - return isWhitelisted(allowedOrigins, origin); - } - - private static boolean isWhitelisted(Set acceptedValues, String value) { - return acceptedValues.isEmpty() || acceptedValues.contains(value); - } - - private Response failedPreflight() { - return Response.noContent().header(HEADER_VARY, HEADER_ORIGIN).build(); - } - - private boolean isPreflight(ContainerRequestContext request) { - return HTTP_METHOD_OPTIONS.equals(request.getMethod()) && - request.getHeaderString(HEADER_ORIGIN) != null && - request.getHeaderString(HEADER_AC_REQUEST_METHOD) != null; - } -} diff --git a/cors/src/main/resources/META-INF/beans.xml b/cors/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/cors/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/cors/src/main/resources/OSGI-INF/blueprint/microbule-cors-decorator.xml b/cors/src/main/resources/OSGI-INF/blueprint/microbule-cors-decorator.xml deleted file mode 100644 index 3176c78..0000000 --- a/cors/src/main/resources/OSGI-INF/blueprint/microbule-cors-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/cors/src/test/java/org/microbule/cors/decorator/CorsDecoratorTest.java b/cors/src/test/java/org/microbule/cors/decorator/CorsDecoratorTest.java deleted file mode 100644 index 36f1e2a..0000000 --- a/cors/src/test/java/org/microbule/cors/decorator/CorsDecoratorTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.cors.decorator; - -import javax.ws.rs.HttpMethod; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.junit.Assert; -import org.junit.Test; -import org.microbule.config.core.MapConfig; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.server.hello.HelloTestCase; - -public class CorsDecoratorTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String ALLOWED_ORIGIN = "http://localhost/"; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new CorsDecorator()); - } - - @Override - protected void configureServer(MapConfig serverConfig) { - serverConfig.addValue("cors." + CorsFilter.ALLOWED_ORIGINS_PROP, ALLOWED_ORIGIN); - serverConfig.addValue("cors." + CorsFilter.ALLOWED_METHODS_PROP, "GET,PUT,POST"); - serverConfig.addValue("cors." + CorsFilter.ALLOWED_HEADERS_PROP, "Microbule-Foo"); - } - - @Test - public void testPreflightCorsRequest() { - final WebTarget target = createWebTarget(); - final Response response = target.path("hello").path("Microbule") - .request(MediaType.TEXT_PLAIN) - .header("Origin", ALLOWED_ORIGIN) - .header("Access-Control-Request-Method", HttpMethod.GET) - .options(); - Assert.assertEquals(ALLOWED_ORIGIN, response.getHeaderString("Access-Control-Allow-Origin")); - Assert.assertEquals("Origin", response.getHeaderString("Vary")); - } - - @Test - public void testPreflightCorsRequestWithInvalidHeader() { - final WebTarget target = createWebTarget(); - final Response response = target.path("hello").path("Microbule") - .request(MediaType.TEXT_PLAIN) - .header("Origin", ALLOWED_ORIGIN) - .header("Access-Control-Request-Method", HttpMethod.GET) - .header("Access-Control-Request-Headers", "Microbule-Bar") - .options(); - - Assert.assertNull(response.getHeaderString("Access-Control-Allow-Origin")); - Assert.assertEquals("Origin", response.getHeaderString("Vary")); - } - - @Test - public void testPreflightCorsRequestWithInvalidMethod() { - final WebTarget target = createWebTarget(); - final Response response = target.path("hello").path("Microbule") - .request(MediaType.TEXT_PLAIN) - .header("Origin", ALLOWED_ORIGIN) - .header("Access-Control-Request-Method", HttpMethod.HEAD) - .options(); - Assert.assertNull(response.getHeaderString("Access-Control-Allow-Origin")); - Assert.assertEquals("Origin", response.getHeaderString("Vary")); - } - - @Test - public void testPreflightCorsRequestWithInvalidOrigin() { - final WebTarget target = createWebTarget(); - final Response response = target.path("hello").path("Microbule") - .request(MediaType.TEXT_PLAIN) - .header("Origin", "http://somebogusorigin/") - .header("Access-Control-Request-Method", HttpMethod.GET) - .options(); - Assert.assertNull(response.getHeaderString("Access-Control-Allow-Origin")); - Assert.assertEquals("Origin", response.getHeaderString("Vary")); - } - - @Test - public void testSimpleCorsRequest() { - final WebTarget target = createWebTarget(); - final Response response = target.path("hello").path("Microbule") - .request(MediaType.TEXT_PLAIN) - .header("Origin", ALLOWED_ORIGIN) - .get(); - Assert.assertEquals(ALLOWED_ORIGIN, response.getHeaderString("Access-Control-Allow-Origin")); - Assert.assertEquals("Origin", response.getHeaderString("Vary")); - } -} \ No newline at end of file diff --git a/errormap.md b/errormap.md new file mode 100644 index 0000000..b06e40f --- /dev/null +++ b/errormap.md @@ -0,0 +1,6 @@ +# Error Mapping + +Microbule will inject its own JAX-RS ExceptionMappers into the services by default. These ExceptionMappers will use +the ErrorMapperService to create responses when an exception happens. The default format of the error response will be +a plain text response with newline-separated error messages. You can override the default format by providing an +ErrorResponseStrategy. diff --git a/errormap/api/pom.xml b/errormap/api/pom.xml deleted file mode 100644 index 094079f..0000000 --- a/errormap/api/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-errormap-parent - 0.3.0-SNAPSHOT - - - microbule-errormap-api - Microbule :: Error Mapping :: API - bundle - - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/errormap/api/src/main/java/org/microbule/errormap/api/ErrorMapperService.java b/errormap/api/src/main/java/org/microbule/errormap/api/ErrorMapperService.java deleted file mode 100644 index 368fd0a..0000000 --- a/errormap/api/src/main/java/org/microbule/errormap/api/ErrorMapperService.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.api; - - -import javax.ws.rs.core.Response; - -public interface ErrorMapperService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - Exception createException(String strategy, Response response); - - Response createResponse(String strategy, Exception e); -} diff --git a/errormap/api/src/main/java/org/microbule/errormap/api/ErrorMapperUtils.java b/errormap/api/src/main/java/org/microbule/errormap/api/ErrorMapperUtils.java deleted file mode 100644 index 6da6f87..0000000 --- a/errormap/api/src/main/java/org/microbule/errormap/api/ErrorMapperUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.api; - -public final class ErrorMapperUtils { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final String DEFAULT_STRATEGY = "text"; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private ErrorMapperUtils() { - - } -} diff --git a/errormap/api/src/test/java/org/microbule/errormap/api/ErrorMapperUtilsTest.java b/errormap/api/src/test/java/org/microbule/errormap/api/ErrorMapperUtilsTest.java deleted file mode 100644 index 05af7be..0000000 --- a/errormap/api/src/test/java/org/microbule/errormap/api/ErrorMapperUtilsTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.api; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class ErrorMapperUtilsTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testIsUtilsClass() throws Exception { - assertIsUtilsClass(ErrorMapperUtils.class); - } -} \ No newline at end of file diff --git a/errormap/core/pom.xml b/errormap/core/pom.xml deleted file mode 100644 index 49cf7a2..0000000 --- a/errormap/core/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-errormap-parent - 0.3.0-SNAPSHOT - - - microbule-errormap-core - Microbule :: Error Mapping :: Core - bundle - - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/AbstractErrorResponseStrategy.java b/errormap/core/src/main/java/org/microbule/errormap/core/AbstractErrorResponseStrategy.java deleted file mode 100644 index 465b1f5..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/AbstractErrorResponseStrategy.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import java.lang.reflect.Constructor; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -import org.microbule.errormap.spi.ErrorResponseStrategy; - -public abstract class AbstractErrorResponseStrategy implements ErrorResponseStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - protected static final String NEWLINE = "\n"; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected RuntimeException createException(Response response, String errorMessage) { - Class exceptionClass = WebApplicationExceptions.getWebApplicationExceptionClass(response); - try { - final Constructor ctor = exceptionClass.getConstructor(String.class, Response.class); - return ctor.newInstance(errorMessage, response); - } catch (ReflectiveOperationException e) { - return new WebApplicationException(errorMessage, response); - } - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/DefaultErrorMapper.java b/errormap/core/src/main/java/org/microbule/errormap/core/DefaultErrorMapper.java deleted file mode 100644 index 35f782a..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/DefaultErrorMapper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import java.util.Collections; -import java.util.List; - -import javax.ws.rs.core.Response; - -import org.microbule.errormap.spi.ErrorMapper; - - -public class DefaultErrorMapper implements ErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final ErrorMapper INSTANCE = new DefaultErrorMapper(); - -//---------------------------------------------------------------------------------------------------------------------- -// ErrorMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public List getErrorMessages(Exception exception) { - return Collections.singletonList(exception.getMessage()); - } - - @Override - public Class getExceptionType() { - return Exception.class; - } - - @Override - public Response.Status getStatus(Exception exception) { - return Response.Status.INTERNAL_SERVER_ERROR; - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/DefaultErrorMapperService.java b/errormap/core/src/main/java/org/microbule/errormap/core/DefaultErrorMapperService.java deleted file mode 100644 index 83264e6..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/DefaultErrorMapperService.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import java.util.Map; -import java.util.Optional; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.core.Response; - -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.errormap.api.ErrorMapperService; -import org.microbule.errormap.core.text.PlainTextErrorResponseStrategy; -import org.microbule.errormap.spi.ErrorMapper; -import org.microbule.errormap.spi.ErrorResponseStrategy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("errorMapperService") -public class DefaultErrorMapperService implements ErrorMapperService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultErrorMapperService.class); - - private final Map, ErrorMapper> errorMappers; - private final Map responseStrategies; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultErrorMapperService(MicrobuleContainer container) { - this.errorMappers = container.pluginMap(ErrorMapper.class, ErrorMapper::getExceptionType); - this.responseStrategies = container.pluginMap(ErrorResponseStrategy.class, ErrorResponseStrategy::name); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ErrorMapperService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Exception createException(String strategyName, Response response) { - return getStrategy(strategyName).createException(response); - } - - @Override - public Response createResponse(String strategyName, Exception e) { - ErrorMapper handler = getExceptionHandler(e); - return getStrategy(strategyName).createResponse(handler.getStatus(e), handler.getErrorMessages(e)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private ErrorMapper getExceptionHandler(Exception exception) { - return findExceptionHandler(exception.getClass()); - } - - private ErrorMapper findExceptionHandler(Class targetType) { - if (Exception.class.equals(targetType)) { - return DefaultErrorMapper.INSTANCE; - } - final ErrorMapper mapper = errorMappers.get(targetType); - if (mapper == null) { - return findExceptionHandler(targetType.getSuperclass()); - } - return mapper; - } - - private ErrorResponseStrategy getStrategy(String strategyName) { - return Optional.ofNullable(responseStrategies.get(strategyName)) - .orElseGet(() -> { - LOGGER.warn("Error response strategy \"{}\" not available, using \"{}\" instead.", strategyName, PlainTextErrorResponseStrategy.INSTANCE.name()); - return PlainTextErrorResponseStrategy.INSTANCE; - }); - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/Responses.java b/errormap/core/src/main/java/org/microbule/errormap/core/Responses.java deleted file mode 100644 index edb652a..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/Responses.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import javax.ws.rs.core.Response; - -import org.apache.commons.lang3.StringUtils; - -public final class Responses { -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static String getErrorMessage(Response response) { - if (response.hasEntity()) { - return StringUtils.defaultString(response.readEntity(String.class), response.getStatusInfo().getReasonPhrase()); - } - return response.getStatusInfo().getReasonPhrase(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private Responses() { - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/WebApplicationExceptions.java b/errormap/core/src/main/java/org/microbule/errormap/core/WebApplicationExceptions.java deleted file mode 100644 index cc596ed..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/WebApplicationExceptions.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAcceptableException; -import javax.ws.rs.NotAllowedException; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.NotSupportedException; -import javax.ws.rs.RedirectionException; -import javax.ws.rs.ServerErrorException; -import javax.ws.rs.ServiceUnavailableException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -public final class WebApplicationExceptions { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Map> EXCEPTIONS_MAP = new HashMap<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - static { - EXCEPTIONS_MAP.put(400, BadRequestException.class); - EXCEPTIONS_MAP.put(401, NotAuthorizedException.class); - EXCEPTIONS_MAP.put(403, ForbiddenException.class); - EXCEPTIONS_MAP.put(404, NotFoundException.class); - EXCEPTIONS_MAP.put(405, NotAllowedException.class); - EXCEPTIONS_MAP.put(406, NotAcceptableException.class); - EXCEPTIONS_MAP.put(415, NotSupportedException.class); - EXCEPTIONS_MAP.put(500, InternalServerErrorException.class); - EXCEPTIONS_MAP.put(503, ServiceUnavailableException.class); - } - - public static Class getWebApplicationExceptionClass(Response response) { - int status = response.getStatus(); - final Class exceptionType = EXCEPTIONS_MAP.get(status); - if (exceptionType == null) { - final int family = status / 100; - switch (family) { - case 3: - return RedirectionException.class; - case 4: - return ClientErrorException.class; - case 5: - return ServerErrorException.class; - default: - return WebApplicationException.class; - } - } - return exceptionType; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private WebApplicationExceptions() { - - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/json/JsonErrorResponse.java b/errormap/core/src/main/java/org/microbule/errormap/core/json/JsonErrorResponse.java deleted file mode 100644 index 4b54077..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/json/JsonErrorResponse.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core.json; - -import java.util.List; - -public class JsonErrorResponse { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final int status; - - private final List messages; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public JsonErrorResponse(int status, List messages) { - this.status = status; - this.messages = messages; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public List getMessages() { - return messages; - } - - public int getStatus() { - return status; - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/json/JsonErrorResponseStrategy.java b/errormap/core/src/main/java/org/microbule/errormap/core/json/JsonErrorResponseStrategy.java deleted file mode 100644 index cf063b9..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/json/JsonErrorResponseStrategy.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core.json; - -import java.util.List; -import java.util.stream.Collectors; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.microbule.errormap.core.AbstractErrorResponseStrategy; -import org.microbule.errormap.spi.ErrorResponseStrategy; - -@Named("jsonErrorResponseStrategy") -@Singleton -public class JsonErrorResponseStrategy extends AbstractErrorResponseStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final ErrorResponseStrategy INSTANCE = new JsonErrorResponseStrategy(); - - private static final String NAME = "json"; - -//---------------------------------------------------------------------------------------------------------------------- -// ErrorResponseStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public RuntimeException createException(Response response) { - final JsonErrorResponse errorResponse = response.readEntity(JsonErrorResponse.class); - final String errorMessage = errorResponse.getMessages().stream().collect(Collectors.joining(NEWLINE)); - return createException(response, errorMessage); - } - - @Override - public Response createResponse(Response.StatusType status, List errorMessages) { - return Response - .status(status) - .type(MediaType.APPLICATION_JSON_TYPE) - .entity(new JsonErrorResponse(status.getStatusCode(), errorMessages)) - .build(); - } - - @Override - public String name() { - return NAME; - } -} diff --git a/errormap/core/src/main/java/org/microbule/errormap/core/text/PlainTextErrorResponseStrategy.java b/errormap/core/src/main/java/org/microbule/errormap/core/text/PlainTextErrorResponseStrategy.java deleted file mode 100644 index 5180181..0000000 --- a/errormap/core/src/main/java/org/microbule/errormap/core/text/PlainTextErrorResponseStrategy.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core.text; - -import java.util.List; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.apache.commons.lang3.StringUtils; -import org.microbule.errormap.core.AbstractErrorResponseStrategy; -import org.microbule.errormap.core.Responses; -import org.microbule.errormap.spi.ErrorResponseStrategy; - -@Named("plainTextErrorResponseStrategy") -@Singleton -public class PlainTextErrorResponseStrategy extends AbstractErrorResponseStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final ErrorResponseStrategy INSTANCE = new PlainTextErrorResponseStrategy(); - private static final String NAME = "text"; - -//---------------------------------------------------------------------------------------------------------------------- -// ErrorResponseStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public RuntimeException createException(Response response) { - return createException(response, Responses.getErrorMessage(response)); - } - - @Override - public Response createResponse(Response.StatusType status, List errorMessages) { - return Response.status(status) - .type(MediaType.TEXT_PLAIN_TYPE) - .entity(StringUtils.join(errorMessages, NEWLINE)) - .build(); - } - - @Override - public String name() { - return NAME; - } -} diff --git a/errormap/core/src/main/resources/META-INF/beans.xml b/errormap/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/errormap/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/errormap/core/src/main/resources/OSGI-INF/blueprint/microbule-errormap-impl.xml b/errormap/core/src/main/resources/OSGI-INF/blueprint/microbule-errormap-impl.xml deleted file mode 100644 index b517a63..0000000 --- a/errormap/core/src/main/resources/OSGI-INF/blueprint/microbule-errormap-impl.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/AbstractErrorResponseStrategyTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/AbstractErrorResponseStrategyTest.java deleted file mode 100644 index d9430c5..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/AbstractErrorResponseStrategyTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAcceptableException; -import javax.ws.rs.NotAllowedException; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.NotSupportedException; -import javax.ws.rs.RedirectionException; -import javax.ws.rs.ServerErrorException; -import javax.ws.rs.ServiceUnavailableException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public abstract class AbstractErrorResponseStrategyTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract RuntimeException createException(Response.Status status, String message); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateException() { - assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class); - assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class); - assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class); - assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class); - assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class); - assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class); - assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class); - assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class); - assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class); - assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class); - assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class); - assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class); - assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class); - } - - private void assertExceptionType(Response.Status status, Class exceptionType) { - final RuntimeException exception = createException(status, "The error message."); - assertEquals(exceptionType, exception.getClass()); - assertEquals("The error message.", exception.getMessage()); - } -} diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/DefaultErrorMapperServiceTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/DefaultErrorMapperServiceTest.java deleted file mode 100644 index ec3e67c..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/DefaultErrorMapperServiceTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import javax.ws.rs.NotFoundException; -import javax.ws.rs.core.Response; - -import org.junit.Before; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.errormap.core.json.JsonErrorResponseStrategy; -import org.microbule.errormap.core.text.PlainTextErrorResponseStrategy; -import org.microbule.errormap.spi.ConstantErrorMapper; -import org.microbule.test.core.MockObjectTestCase; - -public class DefaultErrorMapperServiceTest extends MockObjectTestCase { - - private DefaultErrorMapperService service; - - @Before - public void initService() { - SimpleContainer container = new SimpleContainer(); - container.addBean(new PlainTextErrorResponseStrategy()); - container.addBean(new JsonErrorResponseStrategy()); - container.addBean(new ConstantErrorMapper(IllegalArgumentException.class, Response.Status.BAD_REQUEST)); - service = new DefaultErrorMapperService(container); - container.initialize(); - } - - @Test - public void testCreateResponse() { - final Response response = service.createResponse("text", new IllegalArgumentException("Didn't find it!")); - assertEquals(400, response.getStatus()); - assertEquals("Didn't find it!", response.readEntity(String.class)); - } - - @Test - public void testCreateResponseWithNoMapper() { - final Response response = service.createResponse("text", new RuntimeException("Didn't find it!")); - assertEquals(500, response.getStatus()); - assertEquals("Didn't find it!", response.readEntity(String.class)); - } - - @Test - public void testCreateException() { - final Exception exception = service.createException("text", Response.status(Response.Status.NOT_FOUND).build()); - assertEquals(NotFoundException.class, exception.getClass()); - } - - @Test - public void testCreateExceptionWhenStrategyNotFound() { - final Exception exception = service.createException("bogus", Response.status(Response.Status.NOT_FOUND).entity("It was not found!").build()); - assertEquals(NotFoundException.class, exception.getClass()); - } - - -} \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/DefaultErrorMapperTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/DefaultErrorMapperTest.java deleted file mode 100644 index f7846ab..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/DefaultErrorMapperTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import java.util.Collections; - -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class DefaultErrorMapperTest extends MockObjectTestCase { - @Test - public void testGetErrorMessages() { - assertEquals(Collections.singletonList("Oops!"), DefaultErrorMapper.INSTANCE.getErrorMessages(new RuntimeException("Oops!"))); - } - - @Test - public void testGetExceptionType() { - assertEquals(Exception.class, DefaultErrorMapper.INSTANCE.getExceptionType()); - } - - @Test - public void testGetStatus() { - assertEquals(Response.Status.INTERNAL_SERVER_ERROR, DefaultErrorMapper.INSTANCE.getStatus(new RuntimeException("Oops!"))); - } -} \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/ResponsesTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/ResponsesTest.java deleted file mode 100644 index b470c3b..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/ResponsesTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class ResponsesTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testGetErrorMessage() { - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), Responses.getErrorMessage(Response.serverError().build())); - } - - @Test - public void testIsUtilsClass() throws Exception { - assertIsUtilsClass(Responses.class); - } -} \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/WebApplicationExceptionsTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/WebApplicationExceptionsTest.java deleted file mode 100644 index d62fd46..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/WebApplicationExceptionsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class WebApplicationExceptionsTest extends MicrobuleTestCase{ - @Test - public void testIsUtilsClass() throws Exception { - assertIsUtilsClass(WebApplicationExceptions.class); - } -} \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/json/JsonErrorResponseStrategyTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/json/JsonErrorResponseStrategyTest.java deleted file mode 100644 index 5bc5104..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/json/JsonErrorResponseStrategyTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core.json; - -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.errormap.core.AbstractErrorResponseStrategyTest; - -public class JsonErrorResponseStrategyTest extends AbstractErrorResponseStrategyTest { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected RuntimeException createException(Response.Status status, String message) { - final JsonErrorResponse response = new JsonErrorResponse(status.getStatusCode(), Lists.newArrayList(message)); - return new JsonErrorResponseStrategy().createException(Response.status(status).entity(response).build()); - } - - @Test - public void testCreateResponse() { - final JsonErrorResponseStrategy strategy = new JsonErrorResponseStrategy(); - final Response response = strategy.createResponse(Response.Status.FORBIDDEN, Lists.newArrayList("You are forbidden!", "Not gonna happen!")); - final JsonErrorResponse errorResponse = response.readEntity(JsonErrorResponse.class); - assertEquals(Response.Status.FORBIDDEN.getStatusCode(), errorResponse.getStatus()); - assertEquals(Lists.newArrayList("You are forbidden!", "Not gonna happen!"), errorResponse.getMessages()); - } - - @Test - public void testName() { - final JsonErrorResponseStrategy strategy = new JsonErrorResponseStrategy(); - assertEquals("json", strategy.name()); - } -} \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/json/JsonErrorResponseTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/json/JsonErrorResponseTest.java deleted file mode 100644 index 6e71b13..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/json/JsonErrorResponseTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core.json; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class JsonErrorResponseTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testConstructor() { - final JsonErrorResponse response = new JsonErrorResponse(404, Lists.newArrayList("one", "two", "three")); - assertEquals(404, response.getStatus()); - assertEquals(Lists.newArrayList("one", "two", "three"), response.getMessages()); - } -} \ No newline at end of file diff --git a/errormap/core/src/test/java/org/microbule/errormap/core/text/PlainTextErrorResponseStrategyTest.java b/errormap/core/src/test/java/org/microbule/errormap/core/text/PlainTextErrorResponseStrategyTest.java deleted file mode 100644 index c573b68..0000000 --- a/errormap/core/src/test/java/org/microbule/errormap/core/text/PlainTextErrorResponseStrategyTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.core.text; - -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.errormap.core.AbstractErrorResponseStrategyTest; -import org.microbule.errormap.spi.ErrorResponseStrategy; - -public class PlainTextErrorResponseStrategyTest extends AbstractErrorResponseStrategyTest { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected RuntimeException createException(Response.Status status, String message) { - return PlainTextErrorResponseStrategy.INSTANCE.createException(Response.status(status).entity(message).build()); - } - - @Test - public void testCreateResponse() { - final ErrorResponseStrategy strategy = PlainTextErrorResponseStrategy.INSTANCE; - final Response response = strategy.createResponse(Response.Status.FORBIDDEN, Lists.newArrayList("You are forbidden!", "Not gonna happen!")); - assertEquals("You are forbidden!\nNot gonna happen!", response.readEntity(String.class)); - assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); - } -} \ No newline at end of file diff --git a/errormap/decorator/pom.xml b/errormap/decorator/pom.xml deleted file mode 100644 index 83cf0c0..0000000 --- a/errormap/decorator/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-errormap-parent - 0.3.0-SNAPSHOT - - - microbule-errormap-decorator - Microbule :: Error Mapping :: Decorator - bundle - - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-spi - 0.3.0-SNAPSHOT - - - com.google.guava - guava - ${guava.version} - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperExceptionMapper.java b/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperExceptionMapper.java deleted file mode 100644 index 73f127b..0000000 --- a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperExceptionMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -import org.microbule.errormap.api.ErrorMapperService; - - -public abstract class ErrorMapperExceptionMapper implements ExceptionMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final ErrorMapperService errorMapperService; - private final String strategy; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ErrorMapperExceptionMapper(ErrorMapperService errorMapperService, String strategy) { - this.errorMapperService = errorMapperService; - this.strategy = strategy; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ExceptionMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response toResponse(E exception) { - return errorMapperService.createResponse(strategy, exception); - } -} diff --git a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperProxyDecorator.java b/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperProxyDecorator.java deleted file mode 100644 index e76cc17..0000000 --- a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperProxyDecorator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.errormap.api.ErrorMapperService; -import org.microbule.errormap.api.ErrorMapperUtils; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("errorMapperProxyDecorator") -public class ErrorMapperProxyDecorator implements JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(ErrorMapperProxyDecorator.class); - private static final String STRATEGY = "strategy"; - private final ErrorMapperService errorMapperService; - private final String defaultStrategy; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public ErrorMapperProxyDecorator(ErrorMapperService errorMapperService) { - this(errorMapperService, ErrorMapperUtils.DEFAULT_STRATEGY); - } - - public ErrorMapperProxyDecorator(ErrorMapperService errorMapperService, String defaultStrategy) { - this.errorMapperService = errorMapperService; - this.defaultStrategy = defaultStrategy; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - final String strategy = config.value(STRATEGY).orElse(defaultStrategy); - LOGGER.debug("Using \"{}\" error response strategy for {} JAX-RS proxy.", strategy, descriptor.serviceInterface().getSimpleName()); - descriptor.addProvider(new ErrorMapperResponseExceptionMapper(errorMapperService, strategy)); - } - - @Override - public String name() { - return "errormap"; - } -} diff --git a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperResponseExceptionMapper.java b/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperResponseExceptionMapper.java deleted file mode 100644 index 71abe08..0000000 --- a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperResponseExceptionMapper.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import org.apache.cxf.jaxrs.client.ResponseExceptionMapper; -import org.microbule.errormap.api.ErrorMapperService; - -@Provider -public class ErrorMapperResponseExceptionMapper implements ResponseExceptionMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final ErrorMapperService errorMapperService; - private final String strategy; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ErrorMapperResponseExceptionMapper(ErrorMapperService errorMapperService, String strategy) { - this.errorMapperService = errorMapperService; - this.strategy = strategy; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ResponseExceptionMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Exception fromResponse(Response response) { - return errorMapperService.createException(strategy, response); - } -} diff --git a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperServerDecorator.java b/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperServerDecorator.java deleted file mode 100644 index edeedd4..0000000 --- a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/ErrorMapperServerDecorator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.errormap.api.ErrorMapperService; -import org.microbule.errormap.api.ErrorMapperUtils; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("errorMapperServerDecorator") -public class ErrorMapperServerDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(ErrorMapperServerDecorator.class); - private static final String STRATEGY = "strategy"; - - private final ErrorMapperService errorMapperService; - private final String defaultStrategy; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public ErrorMapperServerDecorator(ErrorMapperService errorMapperService) { - this(errorMapperService, ErrorMapperUtils.DEFAULT_STRATEGY); - } - - public ErrorMapperServerDecorator(ErrorMapperService errorMapperService, String defaultStrategy) { - this.errorMapperService = errorMapperService; - this.defaultStrategy = defaultStrategy; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - final String strategy = config.value(STRATEGY).orElse(defaultStrategy); - LOGGER.debug("Using \"{}\" error response strategy for {} JAX-RS server.", strategy, descriptor.serviceInterface().getSimpleName()); - descriptor.addProvider(new WebApplicationExceptionMapper(errorMapperService, strategy)); - descriptor.addProvider(new RootExceptionMapper(errorMapperService, strategy)); - } - - @Override - public String name() { - return "errormap"; - } -} diff --git a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/RootExceptionMapper.java b/errormap/decorator/src/main/java/org/microbule/errormap/decorator/RootExceptionMapper.java deleted file mode 100644 index 23adec6..0000000 --- a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/RootExceptionMapper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.ws.rs.ext.Provider; - -import org.microbule.errormap.api.ErrorMapperService; - -@Provider -public class RootExceptionMapper extends ErrorMapperExceptionMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public RootExceptionMapper(ErrorMapperService errorMapperService, String strategy) { - super(errorMapperService, strategy); - } -} diff --git a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/WebApplicationExceptionMapper.java b/errormap/decorator/src/main/java/org/microbule/errormap/decorator/WebApplicationExceptionMapper.java deleted file mode 100644 index 02210bc..0000000 --- a/errormap/decorator/src/main/java/org/microbule/errormap/decorator/WebApplicationExceptionMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.ext.Provider; - -import org.microbule.errormap.api.ErrorMapperService; - -@Provider -public class WebApplicationExceptionMapper extends ErrorMapperExceptionMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public WebApplicationExceptionMapper(ErrorMapperService errorMapperService, String strategy) { - super(errorMapperService, strategy); - } -} diff --git a/errormap/decorator/src/main/resources/META-INF/beans.xml b/errormap/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/errormap/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/errormap/decorator/src/main/resources/OSGI-INF/blueprint/microbule-errormap-decorator.xml b/errormap/decorator/src/main/resources/OSGI-INF/blueprint/microbule-errormap-decorator.xml deleted file mode 100644 index ab80003..0000000 --- a/errormap/decorator/src/main/resources/OSGI-INF/blueprint/microbule-errormap-decorator.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/errormap/decorator/src/test/java/org/microbule/errormap/decorator/ErrorMapperDecoratorsTest.java b/errormap/decorator/src/test/java/org/microbule/errormap/decorator/ErrorMapperDecoratorsTest.java deleted file mode 100644 index 50a9af7..0000000 --- a/errormap/decorator/src/test/java/org/microbule/errormap/decorator/ErrorMapperDecoratorsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.decorator; - -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.errormap.api.ErrorMapperService; -import org.microbule.errormap.api.ErrorMapperUtils; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; -import org.microbule.test.server.hello.HelloTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -public class ErrorMapperDecoratorsTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private ErrorMapperService errorMapperService; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - when(errorMapperService.createResponse(eq(ErrorMapperUtils.DEFAULT_STRATEGY), any(Exception.class))).thenReturn(Response.serverError().build()); - when(errorMapperService.createException(eq(ErrorMapperUtils.DEFAULT_STRATEGY), any(Response.class))).thenReturn(new IllegalArgumentException("I'm not saying hello to you!")); - container.addBean(new ErrorMapperServerDecorator(errorMapperService)); - container.addBean(new ErrorMapperProxyDecorator(errorMapperService)); - } - - @Override - protected HelloService createImplementation() { - return new EvilHelloServiceImpl(); - } - - @Test - public void testWithException() { - expectException(IllegalArgumentException.class, "I'm not saying hello to you!"); - createProxy().sayHello("Dr. Evil"); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class EvilHelloServiceImpl extends HelloServiceImpl { -//---------------------------------------------------------------------------------------------------------------------- -// HelloService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String sayHello(String name) { - if ("Dr. Evil".equals(name)) { - throw new IllegalArgumentException("I'm not saying hello to you!"); - } - return super.sayHello(name); - } - } -} \ No newline at end of file diff --git a/errormap/mapper/pom.xml b/errormap/mapper/pom.xml deleted file mode 100644 index ab0efde..0000000 --- a/errormap/mapper/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-errormap-parent - 0.3.0-SNAPSHOT - - - microbule-errormap-mapper - Microbule :: Error Mapping :: Mappers - bundle - - - - org.microbule - microbule-errormap-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-core - 0.3.0-SNAPSHOT - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - test - - - diff --git a/errormap/mapper/src/main/java/org/microbule/errormap/mapper/IllegalArgumentExceptionErrorMapper.java b/errormap/mapper/src/main/java/org/microbule/errormap/mapper/IllegalArgumentExceptionErrorMapper.java deleted file mode 100644 index 173809e..0000000 --- a/errormap/mapper/src/main/java/org/microbule/errormap/mapper/IllegalArgumentExceptionErrorMapper.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.microbule.errormap.mapper; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.core.Response; - -import org.microbule.errormap.spi.ConstantErrorMapper; - -@Named("illegalArgumentExceptionMapper") -@Singleton -public class IllegalArgumentExceptionErrorMapper extends ConstantErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public IllegalArgumentExceptionErrorMapper() { - super(IllegalArgumentException.class, Response.Status.BAD_REQUEST); - } -} diff --git a/errormap/mapper/src/main/java/org/microbule/errormap/mapper/VerifyExceptionErrorMapper.java b/errormap/mapper/src/main/java/org/microbule/errormap/mapper/VerifyExceptionErrorMapper.java deleted file mode 100644 index bb0e77f..0000000 --- a/errormap/mapper/src/main/java/org/microbule/errormap/mapper/VerifyExceptionErrorMapper.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.microbule.errormap.mapper; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.core.Response; - -import com.google.common.base.VerifyException; -import org.microbule.errormap.spi.ConstantErrorMapper; - -@Named("verifyExceptionMapper") -@Singleton -public class VerifyExceptionErrorMapper extends ConstantErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public VerifyExceptionErrorMapper() { - super(VerifyException.class, Response.Status.BAD_REQUEST); - } -} diff --git a/errormap/mapper/src/main/java/org/microbule/errormap/mapper/WebApplicationExceptionErrorMapper.java b/errormap/mapper/src/main/java/org/microbule/errormap/mapper/WebApplicationExceptionErrorMapper.java deleted file mode 100644 index 659516c..0000000 --- a/errormap/mapper/src/main/java/org/microbule/errormap/mapper/WebApplicationExceptionErrorMapper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.mapper; - -import java.util.Collections; -import java.util.List; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -import org.apache.commons.lang3.StringUtils; -import org.microbule.errormap.core.Responses; -import org.microbule.errormap.spi.TypedErrorMapper; - -@Named("webApplicationExceptionMapper") -@Singleton -public class WebApplicationExceptionErrorMapper extends TypedErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected List doGetErrorMessages(WebApplicationException exception) { - Response response = exception.getResponse(); - if (StringUtils.isBlank(exception.getMessage())) { - return Collections.singletonList(Responses.getErrorMessage(response)); - } else { - return Collections.singletonList(exception.getMessage()); - } - } - - @Override - protected Response.StatusType doGetStatus(WebApplicationException exception) { - return exception.getResponse().getStatusInfo(); - } -} diff --git a/errormap/mapper/src/main/resources/META-INF/beans.xml b/errormap/mapper/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/errormap/mapper/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/errormap/mapper/src/main/resources/OSGI-INF/blueprint/microbule-errormap-mapper.xml b/errormap/mapper/src/main/resources/OSGI-INF/blueprint/microbule-errormap-mapper.xml deleted file mode 100644 index 5e9ccd9..0000000 --- a/errormap/mapper/src/main/resources/OSGI-INF/blueprint/microbule-errormap-mapper.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/errormap/mapper/src/test/java/org/microbule/errormap/mapper/IllegalArgumentExceptionErrorMapperTest.java b/errormap/mapper/src/test/java/org/microbule/errormap/mapper/IllegalArgumentExceptionErrorMapperTest.java deleted file mode 100644 index a9fd0cf..0000000 --- a/errormap/mapper/src/test/java/org/microbule/errormap/mapper/IllegalArgumentExceptionErrorMapperTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.microbule.errormap.mapper; - -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class IllegalArgumentExceptionErrorMapperTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testConstructor() { - final IllegalArgumentExceptionErrorMapper mapper = new IllegalArgumentExceptionErrorMapper(); - assertEquals(IllegalArgumentException.class, mapper.getExceptionType()); - assertEquals(Response.Status.BAD_REQUEST, mapper.getStatus()); - } -} \ No newline at end of file diff --git a/errormap/mapper/src/test/java/org/microbule/errormap/mapper/VerifyExceptionErrorMapperTest.java b/errormap/mapper/src/test/java/org/microbule/errormap/mapper/VerifyExceptionErrorMapperTest.java deleted file mode 100644 index 41bb4ff..0000000 --- a/errormap/mapper/src/test/java/org/microbule/errormap/mapper/VerifyExceptionErrorMapperTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.microbule.errormap.mapper; - -import javax.ws.rs.core.Response; - -import com.google.common.base.VerifyException; -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class VerifyExceptionErrorMapperTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testConstructor() { - final VerifyExceptionErrorMapper mapper = new VerifyExceptionErrorMapper(); - assertEquals(VerifyException.class, mapper.getExceptionType()); - assertEquals(Response.Status.BAD_REQUEST, mapper.getStatus()); - } -} \ No newline at end of file diff --git a/errormap/mapper/src/test/java/org/microbule/errormap/mapper/WebApplicationExceptionErrorMapperTest.java b/errormap/mapper/src/test/java/org/microbule/errormap/mapper/WebApplicationExceptionErrorMapperTest.java deleted file mode 100644 index d7c13ca..0000000 --- a/errormap/mapper/src/test/java/org/microbule/errormap/mapper/WebApplicationExceptionErrorMapperTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.microbule.errormap.mapper; - -import java.util.Collections; - -import javax.ws.rs.NotFoundException; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class WebApplicationExceptionErrorMapperTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testGetErrorMessages() { - final WebApplicationExceptionErrorMapper errorMapper = new WebApplicationExceptionErrorMapper(); - assertEquals(Collections.singletonList("Not found!"), errorMapper.doGetErrorMessages(new NotFoundException("Not found!"))); - assertEquals(Collections.singletonList("Not Found"), errorMapper.doGetErrorMessages(new NotFoundException(""))); - } - - @Test - public void testGetStatus() { - final WebApplicationExceptionErrorMapper errorMapper = new WebApplicationExceptionErrorMapper(); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), errorMapper.getStatus(new NotFoundException()).getStatusCode()); - } -} \ No newline at end of file diff --git a/errormap/pom.xml b/errormap/pom.xml deleted file mode 100644 index cbc3e29..0000000 --- a/errormap/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-errormap-parent - Microbule :: Error Mapping :: Parent - pom - - - api - spi - core - decorator - mapper - - diff --git a/errormap/spi/pom.xml b/errormap/spi/pom.xml deleted file mode 100644 index f8f53af..0000000 --- a/errormap/spi/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-errormap-parent - 0.3.0-SNAPSHOT - - - microbule-errormap-spi - Microbule :: Error Mapping :: SPI - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/errormap/spi/src/main/java/org/microbule/errormap/spi/AbstractErrorMapper.java b/errormap/spi/src/main/java/org/microbule/errormap/spi/AbstractErrorMapper.java deleted file mode 100644 index 8cf8c8f..0000000 --- a/errormap/spi/src/main/java/org/microbule/errormap/spi/AbstractErrorMapper.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import java.util.Collections; -import java.util.List; - -public abstract class AbstractErrorMapper implements ErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// ErrorMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public List getErrorMessages(Exception exception) { - return Collections.singletonList(exception.getMessage()); - } -} diff --git a/errormap/spi/src/main/java/org/microbule/errormap/spi/ConstantErrorMapper.java b/errormap/spi/src/main/java/org/microbule/errormap/spi/ConstantErrorMapper.java deleted file mode 100644 index 76dbdf3..0000000 --- a/errormap/spi/src/main/java/org/microbule/errormap/spi/ConstantErrorMapper.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import javax.ws.rs.core.Response; - -public class ConstantErrorMapper extends AbstractErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Class exceptionType; - private final Response.Status status; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ConstantErrorMapper(Class exceptionType, Response.Status status) { - this.exceptionType = exceptionType; - this.status = status; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ErrorMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Class getExceptionType() { - return exceptionType; - } - - @Override - public Response.Status getStatus(Exception exception) { - return status; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public Response.Status getStatus() { - return status; - } -} diff --git a/errormap/spi/src/main/java/org/microbule/errormap/spi/ErrorMapper.java b/errormap/spi/src/main/java/org/microbule/errormap/spi/ErrorMapper.java deleted file mode 100644 index 8daf907..0000000 --- a/errormap/spi/src/main/java/org/microbule/errormap/spi/ErrorMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import java.util.List; - -import javax.ws.rs.core.Response; - -public interface ErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Returns a list of error messages for this exception. - * - * @param exception the exception - * @return a list of error messages - */ - List getErrorMessages(Exception exception); - - /** - * Returns the exception type - * - * @return the exception type - */ - Class getExceptionType(); - - /** - * Returns the status code. - * - * @param exception the exception - * @return the status - */ - Response.StatusType getStatus(Exception exception); -} diff --git a/errormap/spi/src/main/java/org/microbule/errormap/spi/ErrorResponseStrategy.java b/errormap/spi/src/main/java/org/microbule/errormap/spi/ErrorResponseStrategy.java deleted file mode 100644 index 329e749..0000000 --- a/errormap/spi/src/main/java/org/microbule/errormap/spi/ErrorResponseStrategy.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import java.util.List; - -import javax.ws.rs.core.Response; - - -public interface ErrorResponseStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String name(); - - Response createResponse(Response.StatusType status, List errorMessages); - - RuntimeException createException(Response response); -} diff --git a/errormap/spi/src/main/java/org/microbule/errormap/spi/TypedErrorMapper.java b/errormap/spi/src/main/java/org/microbule/errormap/spi/TypedErrorMapper.java deleted file mode 100644 index be77986..0000000 --- a/errormap/spi/src/main/java/org/microbule/errormap/spi/TypedErrorMapper.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import java.util.List; - -import javax.ws.rs.core.Response; - -import org.microbule.util.reflect.Types; - -public abstract class TypedErrorMapper implements ErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Class exceptionType; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - protected TypedErrorMapper() { - this.exceptionType = Types.getTypeParameter(getClass(), TypedErrorMapper.class, 0); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract List doGetErrorMessages(E exception); - - protected abstract Response.StatusType doGetStatus(E exception); - -//---------------------------------------------------------------------------------------------------------------------- -// ErrorMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - @SuppressWarnings("unchecked") - public List getErrorMessages(Exception exception) { - return doGetErrorMessages((E) exception); - } - - @Override - public Class getExceptionType() { - return exceptionType; - } - - @Override - @SuppressWarnings("unchecked") - public Response.StatusType getStatus(Exception exception) { - return doGetStatus((E) exception); - } -} diff --git a/errormap/spi/src/test/java/org/microbule/errormap/spi/ConstantErrorMapperTest.java b/errormap/spi/src/test/java/org/microbule/errormap/spi/ConstantErrorMapperTest.java deleted file mode 100644 index d9dac37..0000000 --- a/errormap/spi/src/test/java/org/microbule/errormap/spi/ConstantErrorMapperTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import java.sql.SQLException; - -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class ConstantErrorMapperTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testMapping() { - final ConstantErrorMapper mapper = new ConstantErrorMapper(SQLException.class, Response.Status.INTERNAL_SERVER_ERROR); - assertEquals(SQLException.class, mapper.getExceptionType()); - final SQLException exception = new SQLException("Oops!"); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR, mapper.getStatus()); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR, mapper.getStatus(exception)); - assertEquals(Lists.newArrayList("Oops!"), mapper.getErrorMessages(exception)); - } -} \ No newline at end of file diff --git a/errormap/spi/src/test/java/org/microbule/errormap/spi/TypedErrorMapperTest.java b/errormap/spi/src/test/java/org/microbule/errormap/spi/TypedErrorMapperTest.java deleted file mode 100644 index 0c731b3..0000000 --- a/errormap/spi/src/test/java/org/microbule/errormap/spi/TypedErrorMapperTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.errormap.spi; - -import java.sql.SQLException; -import java.util.List; - -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class TypedErrorMapperTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testMapping() { - final ErrorMapper mapper = new SqlExceptionMapper(); - assertEquals(SQLException.class, mapper.getExceptionType()); - final SQLException exception = new SQLException("Oops!"); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR, mapper.getStatus(exception)); - assertEquals(Lists.newArrayList("Oops!"), mapper.getErrorMessages(exception)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class SqlExceptionMapper extends TypedErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected List doGetErrorMessages(SQLException exception) { - return Lists.newArrayList(exception.getMessage()); - } - - @Override - protected Response.StatusType doGetStatus(SQLException exception) { - return Response.Status.INTERNAL_SERVER_ERROR; - } - } -} \ No newline at end of file diff --git a/example/activator/pom.xml b/example/activator/pom.xml deleted file mode 100644 index 6054780..0000000 --- a/example/activator/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-example-parent - 0.3.0-SNAPSHOT - - - microbule-example-activator - Microbule :: Example :: OSGi Activator - bundle - - - org.microbule.example.activator.HelloActivator - - - - - org.osgi - org.osgi.core - ${osgi.version} - provided - - - org.osgi - org.osgi.compendium - ${osgi.version} - provided - - - org.microbule - microbule-example-common - 0.3.0-SNAPSHOT - - - diff --git a/example/activator/src/main/java/org/microbule/example/activator/HelloActivator.java b/example/activator/src/main/java/org/microbule/example/activator/HelloActivator.java deleted file mode 100644 index 79c52cc..0000000 --- a/example/activator/src/main/java/org/microbule/example/activator/HelloActivator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.activator; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.microbule.example.common.DefaultHelloResource; -import org.microbule.example.common.HelloResource; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -public class HelloActivator implements BundleActivator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private ServiceRegistration registration; - -//---------------------------------------------------------------------------------------------------------------------- -// BundleActivator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void start(BundleContext context) throws Exception { - Dictionary props = new Hashtable<>(); - props.put("microbule.server", "true"); - registration = context.registerService(HelloResource.class, new DefaultHelloResource(), props); - } - - @Override - public void stop(BundleContext context) throws Exception { - registration.unregister(); - } -} diff --git a/example/blueprint/pom.xml b/example/blueprint/pom.xml deleted file mode 100644 index 3fe0720..0000000 --- a/example/blueprint/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-example-parent - 0.3.0-SNAPSHOT - - - microbule-example-blueprint - Microbule :: Example :: Blueprint - bundle - - - - org.microbule - microbule-example-common - 0.3.0-SNAPSHOT - - - org.microbule - microbule-tracer-spi - 0.3.0-SNAPSHOT - - - diff --git a/example/blueprint/src/main/resources/OSGI-INF/blueprint/microbule-example-blueprint.xml b/example/blueprint/src/main/resources/OSGI-INF/blueprint/microbule-example-blueprint.xml deleted file mode 100644 index 4769dfe..0000000 --- a/example/blueprint/src/main/resources/OSGI-INF/blueprint/microbule-example-blueprint.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/example/cdi/pom.xml b/example/cdi/pom.xml deleted file mode 100644 index c8b91ce..0000000 --- a/example/cdi/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-example-parent - 0.3.0-SNAPSHOT - - - microbule-example-cdi - Microbule :: Example :: CDI - bundle - - - - org.microbule - microbule-example-common - 0.3.0-SNAPSHOT - - - javax.enterprise - cdi-api - ${cdi.version} - - - org.ops4j.pax.cdi - pax-cdi-api - ${pax.cdi.version} - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - osgi.extender; filter:="(osgi.extender=pax.cdi)",org.ops4j.pax.cdi.extension; filter:="(extension=pax-cdi-extension)" - - - - - - diff --git a/example/cdi/src/main/java/org/microbule/example/cdi/HelloCdi.java b/example/cdi/src/main/java/org/microbule/example/cdi/HelloCdi.java deleted file mode 100644 index 81305fb..0000000 --- a/example/cdi/src/main/java/org/microbule/example/cdi/HelloCdi.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.cdi; - -import org.microbule.example.common.DefaultHelloResource; -import org.microbule.example.common.HelloResource; -import org.ops4j.pax.cdi.api.OsgiServiceProvider; -import org.ops4j.pax.cdi.api.Properties; -import org.ops4j.pax.cdi.api.Property; - -@OsgiServiceProvider(classes = HelloResource.class) -@Properties({ - @Property(name = "microbule.server", value = "true") -}) -public class HelloCdi extends DefaultHelloResource implements HelloResource { -} diff --git a/example/cdi/src/main/resources/META-INF/beans.xml b/example/cdi/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 49b89b3..0000000 --- a/example/cdi/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - \ No newline at end of file diff --git a/example/cloudfoundry/README.md b/example/cloudfoundry/README.md deleted file mode 100644 index c569ac7..0000000 --- a/example/cloudfoundry/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Microbule Cloud Foundry Example - -## Building - -```text -mvn clean package -``` - -## Running Locally - -```text -mvn spring-boot:run -``` - -## Running in Cloud Foundry - -- Login to Cloud Foundry - -``` -cf login -a {API-ENDPOINT} -``` - -- Push Application - -``` -cf push {APP-NAME} -p target/microbule-example-cloudfoundry-${version}.jar -``` \ No newline at end of file diff --git a/example/cloudfoundry/manifest.yml b/example/cloudfoundry/manifest.yml deleted file mode 100644 index 2fc5aa9..0000000 --- a/example/cloudfoundry/manifest.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -applications: -- name: microbule-example-cloudfoundry - memory: 512M diff --git a/example/cloudfoundry/pom.xml b/example/cloudfoundry/pom.xml deleted file mode 100644 index e9fb2a2..0000000 --- a/example/cloudfoundry/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-example-parent - 0.3.0-SNAPSHOT - - - - microbule-example-cloudfoundry - Microbule :: Example :: Cloud Foundry - - - - org.microbule - microbule-all - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spring-bootstrap - 0.3.0-SNAPSHOT - - - org.springframework.boot - spring-boot - ${spring.boot.version} - - - org.microbule - microbule-example-common - 0.3.0-SNAPSHOT - - - org.microbule - microbule-cglib - 0.3.0-SNAPSHOT - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - - - repackage - - - - - - - diff --git a/example/cloudfoundry/src/main/java/org/microbule/example/pcf/Startup.java b/example/cloudfoundry/src/main/java/org/microbule/example/pcf/Startup.java deleted file mode 100644 index 7295771..0000000 --- a/example/cloudfoundry/src/main/java/org/microbule/example/pcf/Startup.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.pcf; - -import java.util.concurrent.TimeUnit; - -import org.microbule.api.JaxrsProxyReference; -import org.microbule.example.common.HelloResource; -import org.microbule.scheduler.api.SchedulerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.core.annotation.Order; - -@Configuration -@ComponentScan(basePackages = "org.microbule") -@PropertySource("classpath:application.properties") -public class Startup { - - private static final Logger LOGGER = LoggerFactory.getLogger(Startup.class); - - @Autowired - private JaxrsProxyReference helloResource; - - @Autowired - private SchedulerService schedulerService; - - public static void main(String[] args) { - SpringApplication.run(Startup.class, args); - } - - - @EventListener - @Order() - public void applicationStarted(ContextRefreshedEvent event) { - LOGGER.info("The application has started!"); - - schedulerService.schedule(() -> LOGGER.info(helloResource.get().sayHello("Microbule").getGreeting()), 10, TimeUnit.SECONDS); - } -} diff --git a/example/cloudfoundry/src/main/resources/application.properties b/example/cloudfoundry/src/main/resources/application.properties deleted file mode 100644 index 66c910c..0000000 --- a/example/cloudfoundry/src/main/resources/application.properties +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2017 The Microbule Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -default.server.baseAddress=http://0.0.0.0:${PORT:8080} -hello.proxy.proxyAddress=http://0.0.0.0:${PORT:8080}/hello \ No newline at end of file diff --git a/example/cloudfoundry/src/main/resources/log4j.properties b/example/cloudfoundry/src/main/resources/log4j.properties deleted file mode 100644 index 1d8689b..0000000 --- a/example/cloudfoundry/src/main/resources/log4j.properties +++ /dev/null @@ -1,29 +0,0 @@ -# -# Copyright (c) 2017 The Microbule Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# - -# Root logger option -log4j.rootLogger=INFO, stdout - -# Direct log messages to stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p %c{1} (%X{microbule_trace_id}) - %m%n - -log4j.logger.org.apache.cxf.interceptor=WARN - -log4j.logger.org.microbule=DEBUG diff --git a/example/common/pom.xml b/example/common/pom.xml deleted file mode 100644 index 92a160f..0000000 --- a/example/common/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-example-parent - 0.3.0-SNAPSHOT - - - microbule-example-common - Microbule :: Example :: Common - bundle - - - - javax.validation - validation-api - ${validation.api.version} - - - org.microbule - microbule-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-cache-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-annotation - 0.3.0-SNAPSHOT - - - io.swagger - swagger-jaxrs - ${swagger.version} - - - javax.ws.rs - jsr311-api - - - - - diff --git a/example/common/src/main/java/org/microbule/example/common/DefaultHelloResource.java b/example/common/src/main/java/org/microbule/example/common/DefaultHelloResource.java deleted file mode 100644 index 2feebc7..0000000 --- a/example/common/src/main/java/org/microbule/example/common/DefaultHelloResource.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.common; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("helloResource") -public class DefaultHelloResource implements HelloResource { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Logger logger = LoggerFactory.getLogger(getClass()); - -//---------------------------------------------------------------------------------------------------------------------- -// HelloResource Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public HelloResponse sayHello(String name) { - logger.info("Saying hello to \"{}\"...", name); - return new HelloResponse("Hello, " + name + "!"); - } -} diff --git a/example/common/src/main/java/org/microbule/example/common/HelloResource.java b/example/common/src/main/java/org/microbule/example/common/HelloResource.java deleted file mode 100644 index cadaca0..0000000 --- a/example/common/src/main/java/org/microbule/example/common/HelloResource.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.common; - -import javax.validation.constraints.Size; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import org.microbule.annotation.JaxrsService; -import org.microbule.cache.annotation.Cacheable; -import org.microbule.metrics.annotation.Timed; - -@Path("/") -@Api(value = "/", produces = "application/json") -@JaxrsService(name = "hello") -public interface HelloResource { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Path("/{name}") - @Produces(MediaType.APPLICATION_JSON) - @GET - @Timed(strategy = "timeWindow") - @Cacheable - @ApiOperation(value = "Say Hello", notes = "Returns a greeting", response = HelloResponse.class) - HelloResponse sayHello(@ApiParam(value = "name", required = true) @PathParam("name") @Size(min = 5, message = "Name must be at least 5 characters long.") String name); -} diff --git a/example/common/src/main/java/org/microbule/example/common/HelloResponse.java b/example/common/src/main/java/org/microbule/example/common/HelloResponse.java deleted file mode 100644 index 6dbc4ac..0000000 --- a/example/common/src/main/java/org/microbule/example/common/HelloResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.common; - -public class HelloResponse { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String greeting; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public HelloResponse(String greeting) { - this.greeting = greeting; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getGreeting() { - return greeting; - } -} diff --git a/example/pom.xml b/example/pom.xml deleted file mode 100644 index d3e8007..0000000 --- a/example/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-example-parent - Microbule :: Example :: Parent - pom - - - common - cdi - scr - blueprint - activator - cloudfoundry - - diff --git a/example/scr/pom.xml b/example/scr/pom.xml deleted file mode 100644 index d30ebf6..0000000 --- a/example/scr/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-example-parent - 0.3.0-SNAPSHOT - - - microbule-example-scr - Microbule :: Example :: SCR - bundle - - - - org.osgi - org.osgi.core - ${osgi.version} - provided - - - org.osgi - org.osgi.compendium - ${osgi.version} - provided - - - org.microbule - microbule-example-common - 0.3.0-SNAPSHOT - - - diff --git a/example/scr/src/main/java/org/microbule/example/scr/HelloScr.java b/example/scr/src/main/java/org/microbule/example/scr/HelloScr.java deleted file mode 100644 index 9c8e33c..0000000 --- a/example/scr/src/main/java/org/microbule/example/scr/HelloScr.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.example.scr; - -import org.microbule.example.common.DefaultHelloResource; -import org.microbule.example.common.HelloResource; -import org.osgi.service.component.annotations.Component; - -@Component(property = {"microbule.server=true"}, service = HelloResource.class) -public class HelloScr extends DefaultHelloResource { -} diff --git a/features/pom.xml b/features/pom.xml deleted file mode 100644 index 3c0f9d3..0000000 --- a/features/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-features - Microbule :: Apache Karaf Features Repository - - - - org.microbule - microbule-osgi-container - 0.3.0-SNAPSHOT - - - org.microbule - microbule-osgi-config - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-sysprop - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-env - 0.3.0-SNAPSHOT - - - - - - src/main/resources - true - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - package - - attach-artifact - - - - - ${project.build.outputDirectory}/features.xml - xml - features - - - - - - - - - diff --git a/features/src/main/resources/features.xml b/features/src/main/resources/features.xml deleted file mode 100644 index 7775ee3..0000000 --- a/features/src/main/resources/features.xml +++ /dev/null @@ -1,206 +0,0 @@ - - - - - - mvn:org.apache.cxf.karaf/apache-cxf/${cxf.version}/xml/features - - - - microbule-core - microbule-errormap - microbule-gzip - microbule-logging - microbule-swagger - microbule-cors - microbule-cache - microbule-validation - microbule-requestlog - microbule-timeout - microbule-tracer - microbule-circuitbreaker - microbule-gson - microbule-metrics - microbule-version - - - - - cxf-jaxrs - cxf-rs-description-swagger2 - - - mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.cglib/${cglib.version} - - mvn:org.apache.geronimo.specs/geronimo-atinject_1.0_spec/1.0 - mvn:com.google.code.gson/gson/${gson.version} - mvn:com.google.guava/guava/${guava.version} - mvn:org.apache.commons/commons-lang3/${commons.lang3.version} - mvn:com.savoirtech.eos/eos-core/${eos.version} - - mvn:org.microbule/microbule-util/${project.version} - - mvn:org.microbule/microbule-container-api/${project.version} - mvn:org.microbule/microbule-container-core/${project.version} - - mvn:org.microbule/microbule-config-api/${project.version} - mvn:org.microbule/microbule-config-spi/${project.version} - mvn:org.microbule/microbule-config-core/${project.version} - mvn:org.microbule/microbule-config-env/${project.version} - mvn:org.microbule/microbule-config-sysprop/${project.version} - - mvn:org.microbule/microbule-scheduler-api/${project.version} - mvn:org.microbule/microbule-scheduler-core/${project.version} - - mvn:org.microbule/microbule-annotation/${project.version} - mvn:org.microbule/microbule-api/${project.version} - mvn:org.microbule/microbule-spi/${project.version} - mvn:org.microbule/microbule-cglib/${project.version} - mvn:org.microbule/microbule-core/${project.version} - mvn:org.microbule/microbule-osgi-container/${project.version} - mvn:org.microbule/microbule-osgi-blueprint/${project.version} - mvn:org.microbule/microbule-osgi-config/${project.version} - - - - - mvn:org.microbule/microbule-errormap-api/${project.version} - mvn:org.microbule/microbule-errormap-spi/${project.version} - mvn:org.microbule/microbule-errormap-core/${project.version} - mvn:org.microbule/microbule-errormap-decorator/${project.version} - mvn:org.microbule/microbule-errormap-mapper/${project.version} - - - - mvn:org.microbule/microbule-gson-api/${project.version} - mvn:org.microbule/microbule-gson-spi/${project.version} - mvn:org.microbule/microbule-gson-provider/${project.version} - mvn:org.microbule/microbule-gson-util/${project.version} - mvn:org.microbule/microbule-gson-time/${project.version} - mvn:org.microbule/microbule-gson-core/${project.version} - mvn:org.microbule/microbule-gson-decorator/${project.version} - - - - mvn:io.dropwizard.metrics/metrics-core/${dropwizard.metrics.version} - mvn:org.microbule/microbule-metrics-annotation/${project.version} - mvn:org.microbule/microbule-metrics-api/${project.version} - mvn:org.microbule/microbule-metrics-spi/${project.version} - mvn:org.microbule/microbule-metrics-core/${project.version} - mvn:org.microbule/microbule-metrics-decorator/${project.version} - - - - mvn:org.microbule/microbule-gzip-decorator/${project.version} - - - - mvn:org.microbule/microbule-tracer-spi/${project.version} - mvn:org.microbule/microbule-tracer-decorator/${project.version} - - - - mvn:org.microbule/microbule-logging-decorator/${project.version} - - - - mvn:org.microbule/microbule-swagger-decorator/${project.version} - - - - mvn:org.microbule/microbule-cors-decorator/${project.version} - - - - mvn:org.microbule/microbule-requestlog-decorator/${project.version} - - - - mvn:org.microbule/microbule-circuitbreaker-decorator/${project.version} - - - - - mvn:org.microbule/microbule-cache-annotation/${project.version} - mvn:org.microbule/microbule-cache-decorator/${project.version} - - - - mvn:javax.validation/validation-api/${validation.api.version} - mvn:org.jboss.logging/jboss-logging/${jboss.logging.version} - mvn:com.fasterxml/classmate/${classmate.version} - mvn:javax.el/javax.el-api/${javax.el.api.version} - mvn:org.glassfish.web/javax.el/${glassfish.el.version} - mvn:org.hibernate/hibernate-validator/${hibernate.validator.version} - mvn:org.microbule/microbule-validation-annotation/${project.version} - mvn:org.microbule/microbule-validation-decorator/${project.version} - - - - mvn:org.microbule/microbule-timeout-decorator/${project.version} - - - - mvn:org.microbule/microbule-version-decorator/${project.version} - - - - - - microbule - mvn:org.microbule/microbule-example-common/${project.version} - mvn:org.microbule/microbule-example-blueprint/${project.version} - - - - microbule - mvn:org.microbule/microbule-example-common/${project.version} - mvn:org.microbule/microbule-example-activator/${project.version} - - - - microbule - scr - mvn:org.microbule/microbule-example-common/${project.version} - mvn:org.microbule/microbule-example-scr/${project.version} - - - - microbule - pax-cdi-1.2-weld - mvn:org.microbule/microbule-example-common/${project.version} - mvn:org.microbule/microbule-example-cdi/${project.version} - - - diff --git a/gson/api/pom.xml b/gson/api/pom.xml deleted file mode 100644 index ff64cb9..0000000 --- a/gson/api/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-api - Microbule :: GSON :: API - bundle - - diff --git a/gson/api/src/main/java/org/microbule/gson/api/GsonService.java b/gson/api/src/main/java/org/microbule/gson/api/GsonService.java deleted file mode 100644 index d8f330f..0000000 --- a/gson/api/src/main/java/org/microbule/gson/api/GsonService.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.api; - -import java.io.Reader; -import java.lang.reflect.Type; -import java.util.function.Consumer; -import java.util.function.Function; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; - -public interface GsonService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Appends an object's JSON value to the supplied {@link Appendable} object. - * - * @param src the object - * @param writer the appendable - * @param the appendable type - * @return the appendable - */ - A append(Object src, A writer); - - /** - * Appends an {@link JsonElement}'s JSON value to the supplied {@link Appendable} object. - * - * @param json the element - * @param writer the appendable - * @param the appendable type - * @return the appendable - */ - A append(JsonElement json, A writer); - - /** - * Appends an object's JSON value to the supplied {@link Appendable} object. - * - * @param src the object - * @param type the object's type (to be used in the case of generics) - * @param writer the appendable - * @param the appendable type - * @return the appendable - */ - A append(Object src, Type type, A writer); - /** - * Allows access to the {@link Gson} instance in order to create some object. Do NOT maintain a reference to the - * {@link Gson} object! - * - * @param function a function - * @param the type to return - * @return the value created by the function - */ - T createWithGson(Function function); - - /** - * Allows access to the {@link Gson} instance. Do NOT maintain a reference to the supplied {@link Gson} object! - * - * @param consumer a consumer - */ - void doWithGson(Consumer consumer); - - /** - * Parses an object from the supplied {@link Reader}. - * - * @param json the reader containing the JSON - * @param type the generic type - * @param the object type to return (uses type inference) - * @return the parsed object - */ - T parse(Reader json, Type type); - - /** - * Parses an object from the supplied {@link JsonElement}. - * - * @param json the JSON element - * @param type the type - * @param the object type - * @return the parsed object - */ - T parse(JsonElement json, Class type); - - /** - * Parses an object from the supplied {@link JsonElement}. - * - * @param json the JSON element - * @param type the generic type - * @param the object type (uses type inference) - * @return the parsed object - */ - T parse(JsonElement json, Type type); - - /** - * Parses an object from the supplied JSON string. - * - * @param json the JSON string - * @param type the type - * @param the object type - * @return the parsed object - */ - T parse(String json, Class type); - - /** - * Parses an object from the supplied JSON string. - * - * @param json the JSON string - * @param type the generic type - * @param the object type - * @return the parsed object - */ - T parse(String json, Type type); - - /** - * Parses an object from the supplied {@link Reader}. - * - * @param json the reader containing the JSON - * @param type the type - * @param the object type to return - * @return the parsed object - */ - T parse(Reader json, Class type); - - /** - * Transforms an input object into a {@link JsonElement}. - * @param src the source object - * @param the JSON element type (uses type inference) - * @return the parsed JSON element - */ - T toJson(Object src); - - /** - * Transforms an input object into a {@link JsonElement}. - * @param src the source object - * @param type the source object's generic type - * @param the JSON element type (uses type inference) - * @return the parsed JSON element - */ - T toJson(Object src, Type type); - - /** - * Transforms an object into its JSON string representation. - * @param src the source object - * @return the JSON string - */ - String toJsonString(Object src); - - /** - * Transforms a {@link JsonElement} into its JSON string representation. - * @param json the JSON element - * @return the JSON string - */ - String toJsonString(JsonElement json); - - /** - * Transforms an object into its JSON string representation. - * @param src the source object - * @param type the source object's generic type - * @return the JSON string - */ - String toJsonString(Object src, Type type); -} diff --git a/gson/core/pom.xml b/gson/core/pom.xml deleted file mode 100644 index 1c7606a..0000000 --- a/gson/core/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-core - Microbule :: GSON :: Core - bundle - - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/core/src/main/java/org/microbule/gson/core/DefaultGsonService.java b/gson/core/src/main/java/org/microbule/gson/core/DefaultGsonService.java deleted file mode 100644 index 89c9d73..0000000 --- a/gson/core/src/main/java/org/microbule/gson/core/DefaultGsonService.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.core; - -import java.io.Reader; -import java.lang.reflect.Type; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.function.Function; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.container.api.PluginListener; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("gsonService") -public class DefaultGsonService implements GsonService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultGsonService.class); - private final List customizers = new CopyOnWriteArrayList<>(); - private final AtomicReference gson = new AtomicReference<>(new GsonBuilder().create()); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultGsonService(MicrobuleContainer container) { - container.addPluginListener(GsonBuilderCustomizer.class, new GsonCustomizerListener()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// GsonService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public A append(Object src, A writer) { - getGson().toJson(src, writer); - return writer; - } - - @Override - public A append(JsonElement json, A writer) { - getGson().toJson(json, writer); - return writer; - } - - @Override - public A append(Object src, Type type, A writer) { - getGson().toJson(src, type, writer); - return writer; - } - - @Override - public T createWithGson(Function function) { - return function.apply(getGson()); - } - - @Override - public void doWithGson(Consumer consumer) { - consumer.accept(getGson()); - } - - @Override - public T parse(Reader json, Type type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(JsonElement json, Class type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(JsonElement json, Type type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(String json, Class type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(String json, Type type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(Reader json, Class type) { - return getGson().fromJson(json, type); - } - - @Override - @SuppressWarnings("unchecked") - public T toJson(Object src) { - return (T) getGson().toJsonTree(src); - } - - @Override - @SuppressWarnings("unchecked") - public T toJson(Object src, Type type) { - return (T) getGson().toJsonTree(src, type); - } - - @Override - public String toJsonString(Object src) { - return getGson().toJson(src); - } - - @Override - public String toJsonString(JsonElement json) { - return getGson().toJson(json); - } - - @Override - public String toJsonString(Object src, Type type) { - return getGson().toJson(src, type); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - Gson getGson() { - return gson.get(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private class GsonCustomizerListener implements PluginListener { -//---------------------------------------------------------------------------------------------------------------------- -// PluginListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean registerPlugin(GsonBuilderCustomizer plugin) { - customizers.add(plugin); - LOGGER.debug("Rebuilding GSON instance to include plugin {}.", plugin); - rebuild(); - return true; - } - - @Override - public void unregisterPlugin(GsonBuilderCustomizer plugin) { - customizers.remove(plugin); - LOGGER.debug("Rebuilding GSON instance without plugin {}.", plugin); - rebuild(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private void rebuild() { - GsonBuilder builder = new GsonBuilder(); - builder.setPrettyPrinting(); - customizers.forEach(customizer -> customizer.customize(builder)); - gson.set(builder.create()); - } - } -} diff --git a/gson/core/src/main/resources/META-INF/beans.xml b/gson/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gson/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gson/core/src/main/resources/OSGI-INF/blueprint/microbule-gson-core.xml b/gson/core/src/main/resources/OSGI-INF/blueprint/microbule-gson-core.xml deleted file mode 100644 index 9903fc6..0000000 --- a/gson/core/src/main/resources/OSGI-INF/blueprint/microbule-gson-core.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/gson/core/src/test/java/org/microbule/gson/core/DefaultGsonServiceTest.java b/gson/core/src/test/java/org/microbule/gson/core/DefaultGsonServiceTest.java deleted file mode 100644 index 5fd7847..0000000 --- a/gson/core/src/test/java/org/microbule/gson/core/DefaultGsonServiceTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.core; - -import java.io.StringReader; -import java.io.StringWriter; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import org.junit.Before; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class DefaultGsonServiceTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private GsonBuilderCustomizer customizer; - private DefaultGsonService service; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initGsonService() { - final SimpleContainer container = new SimpleContainer(); - service = new DefaultGsonService(container); - container.initialize(); - } - - @Test - public void testDoWithGson() { - service.doWithGson(gson -> { - assertTrue(gson.htmlSafe()); - }); - } - - @Test - public void testAddCustomizer() { - doAnswer(invocation -> { - GsonBuilder builder = invocation.getArgument(0); - builder.disableHtmlEscaping(); - return null; - }).when(customizer).customize(any(GsonBuilder.class)); - final SimpleContainer container = new SimpleContainer(); - final DefaultGsonService service = new DefaultGsonService(container); - container.addBean(customizer); - container.initialize(); - verify(customizer).customize(any(GsonBuilder.class)); - assertFalse(service.getGson().htmlSafe()); - container.shutdown(); - verifyNoMoreInteractions(customizer); - } - - @Test - public void testAppending() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = service.toJson(person); - - assertEquals(json.toString(), service.append(person, new StringWriter()).toString()); - assertEquals(json.toString(), service.append(person, Person.class.getGenericSuperclass(), new StringWriter()).toString()); - assertEquals(json.toString(), service.append(json, new StringWriter()).toString()); - } - - @Test - public void testCreateWithGson() { - final Person person = new Person("Hello", "Microbule"); - final String json = service.createWithGson(gson -> gson.toJson(person)); - assertEquals(json, service.toJsonString(person)); - } - - @Test - public void testParsing() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = service.toJson(person); - - assertJsonEquals(person, service.parse(new StringReader(json.toString()), Person.class)); - assertJsonEquals(person, service.parse(new StringReader(json.toString()), Person.class.getGenericSuperclass())); - - assertJsonEquals(person, service.parse(json.toString(), Person.class)); - assertJsonEquals(person, service.parse(json.toString(), Person.class.getGenericSuperclass())); - - assertJsonEquals(person, service.parse(json, Person.class)); - assertJsonEquals(person, service.parse(json, Person.class.getGenericSuperclass())); - } - - private void assertJsonEquals(T expected, T actual) { - assertEquals(service.toJsonString(expected), service.toJsonString(actual)); - } - - @Test - public void testToJson() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = new JsonObject(); - json.addProperty("firstName", "Hello"); - json.addProperty("lastName", "Microbule"); - - assertEquals(json, service.toJson(person)); - assertEquals(json, service.toJson(person, Person.class.getGenericSuperclass())); - } - - @Test - public void testToJsonString() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = new JsonObject(); - json.addProperty("firstName", "Hello"); - json.addProperty("lastName", "Microbule"); - - assertEquals(json.toString(), service.toJsonString(person)); - assertEquals(json.toString(), service.toJsonString(person, Person.class.getGenericSuperclass())); - assertEquals(json.toString(), service.toJsonString(json)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class Person { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String firstName; - private final String lastName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - } -} \ No newline at end of file diff --git a/gson/decorator/pom.xml b/gson/decorator/pom.xml deleted file mode 100644 index abefa52..0000000 --- a/gson/decorator/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-decorator - Microbule :: GSON :: Decorator - bundle - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-gson-provider - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonProxyDecorator.java b/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonProxyDecorator.java deleted file mode 100644 index a552a09..0000000 --- a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonProxyDecorator.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.microbule.gson.decorator; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.gson.provider.JsonResponseParsingException; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Named("gsonProxyDecorator") -@Singleton -public class GsonProxyDecorator implements JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final GsonService gsonService; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public GsonProxyDecorator(GsonService gsonService) { - this.gsonService = gsonService; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, JsonResponseParsingException::new)); - } - - @Override - public String name() { - return "gson"; - } -} diff --git a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonServerDecorator.java b/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonServerDecorator.java deleted file mode 100644 index 6a3c66d..0000000 --- a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonServerDecorator.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.microbule.gson.decorator; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.ws.rs.core.Response; - -import org.microbule.config.api.Config; -import org.microbule.errormap.spi.ConstantErrorMapper; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.gson.provider.JsonRequestParsingException; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Named("gsonServerDecorator") -@Singleton -public class GsonServerDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final GsonService gsonService; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public GsonServerDecorator(GsonService gsonService) { - this.gsonService = gsonService; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, JsonRequestParsingException::new)); - descriptor.addProvider(new ConstantErrorMapper(JsonRequestParsingException.class, Response.Status.BAD_REQUEST)); - } - - @Override - public String name() { - return "gson"; - } -} diff --git a/gson/decorator/src/main/resources/META-INF/beans.xml b/gson/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gson/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gson/decorator/src/main/resources/OSGI-INF/blueprint/microbule-gson-decorator.xml b/gson/decorator/src/main/resources/OSGI-INF/blueprint/microbule-gson-decorator.xml deleted file mode 100644 index a55afcd..0000000 --- a/gson/decorator/src/main/resources/OSGI-INF/blueprint/microbule-gson-decorator.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonProxyDecoratorTest.java b/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonProxyDecoratorTest.java deleted file mode 100644 index 34ad8a0..0000000 --- a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonProxyDecoratorTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.decorator; - -import org.junit.Test; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; - -public class GsonProxyDecoratorTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private GsonService gsonService; - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Test - public void testDecorate() { - final GsonProxyDecorator decorator = new GsonProxyDecorator(gsonService); - assertEquals("gson", decorator.name()); - decorator.decorate(descriptor, null); - verify(descriptor).addProvider(any(GsonProvider.class)); - } -} \ No newline at end of file diff --git a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonServerDecoratorTest.java b/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonServerDecoratorTest.java deleted file mode 100644 index b499edc..0000000 --- a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonServerDecoratorTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.decorator; - -import org.junit.Test; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; - -public class GsonServerDecoratorTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private GsonService gsonService; - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Test - public void testDecorate() { - final GsonServerDecorator decorator = new GsonServerDecorator(gsonService); - assertEquals("gson", decorator.name()); - decorator.decorate(descriptor, null); - verify(descriptor).addProvider(any(GsonProvider.class)); - } -} \ No newline at end of file diff --git a/gson/pom.xml b/gson/pom.xml deleted file mode 100644 index fe7fd60..0000000 --- a/gson/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-gson-parent - Microbule :: GSON :: Parent - pom - - - api - spi - core - provider - decorator - util - time - - - - - com.google.code.gson - gson - ${gson.version} - - - diff --git a/gson/provider/pom.xml b/gson/provider/pom.xml deleted file mode 100644 index 82a9730..0000000 --- a/gson/provider/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-provider - Microbule :: GSON :: Provider - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-gson-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/provider/src/main/java/org/microbule/gson/provider/GsonProvider.java b/gson/provider/src/main/java/org/microbule/gson/provider/GsonProvider.java deleted file mode 100644 index 35a23ee..0000000 --- a/gson/provider/src/main/java/org/microbule/gson/provider/GsonProvider.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.microbule.gson.provider; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.function.Function; - -import javax.ws.rs.Consumes; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.ext.MessageBodyReader; -import javax.ws.rs.ext.MessageBodyWriter; -import javax.ws.rs.ext.Provider; - -import com.google.common.base.Charsets; -import com.google.gson.JsonSyntaxException; -import org.apache.commons.lang3.ObjectUtils; -import org.microbule.gson.api.GsonService; - -@Provider -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class GsonProvider implements MessageBodyReader,MessageBodyWriter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final GsonService gsonService; - private final Function exceptionProvider; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public GsonProvider(GsonService gsonService, Function exceptionProvider) { - this.gsonService = gsonService; - this.exceptionProvider = exceptionProvider; - } - -//---------------------------------------------------------------------------------------------------------------------- -// MessageBodyReader Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return true; - } - - @Override - public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { - try (InputStreamReader streamReader = new InputStreamReader(entityStream, Charsets.UTF_8)) { - try { - return gsonService.parse(streamReader, resolveType(type, genericType)); - } catch (JsonSyntaxException e) { - throw exceptionProvider.apply(e); - } - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// MessageBodyWriter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return -1; - } - - @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return true; - } - - @Override - public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { - try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8)) { - gsonService.append(o, resolveType(type, genericType), writer); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private Type resolveType(Class type, Type genericType) { - if (ObjectUtils.notEqual(type, genericType)) { - return genericType; - } else { - return type; - } - } -} diff --git a/gson/provider/src/main/java/org/microbule/gson/provider/JsonRequestParsingException.java b/gson/provider/src/main/java/org/microbule/gson/provider/JsonRequestParsingException.java deleted file mode 100644 index cbf824a..0000000 --- a/gson/provider/src/main/java/org/microbule/gson/provider/JsonRequestParsingException.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.microbule.gson.provider; - -import com.google.gson.JsonSyntaxException; -import org.microbule.util.exception.MicrobuleException; - -public class JsonRequestParsingException extends MicrobuleException { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public JsonRequestParsingException(JsonSyntaxException e) { - super(e, e.getMessage()); - } -} diff --git a/gson/provider/src/main/java/org/microbule/gson/provider/JsonResponseParsingException.java b/gson/provider/src/main/java/org/microbule/gson/provider/JsonResponseParsingException.java deleted file mode 100644 index 097e0af..0000000 --- a/gson/provider/src/main/java/org/microbule/gson/provider/JsonResponseParsingException.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.microbule.gson.provider; - -import com.google.gson.JsonSyntaxException; -import org.microbule.util.exception.MicrobuleException; - -public class JsonResponseParsingException extends MicrobuleException { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public JsonResponseParsingException(JsonSyntaxException e) { - super(e, e.getMessage()); - } -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/BadJsonService.java b/gson/provider/src/test/java/org/microbule/gson/provider/BadJsonService.java deleted file mode 100644 index 35df9db..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/BadJsonService.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.microbule.gson.provider; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@Path("/") -public interface BadJsonService { - - @Produces(MediaType.APPLICATION_JSON) - @GET - @Path("bad") - Response createBadJson(); -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/GsonClientProviderTest.java b/gson/provider/src/test/java/org/microbule/gson/provider/GsonClientProviderTest.java deleted file mode 100644 index 44688de..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/GsonClientProviderTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.microbule.gson.provider; - -import javax.ws.rs.client.ResponseProcessingException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.server.JaxrsServerTestCase; - -public class GsonClientProviderTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - GsonService gsonService = new DefaultGsonService(container); - container.addBean(new JaxrsProxyDecorator() { - @Override - public String name() { - return "gsonTest"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, e -> new JsonResponseParsingException(e))); - } - }); - } - - @Override - protected BadJsonService createImplementation() { - return new BadJsonServiceImpl(); - } - - @Test(expected = ResponseProcessingException.class) - public void testParsingBadResponse() { - final Response response = createProxy().createBadJson(); - response.readEntity(Person.class); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class BadJsonServiceImpl implements BadJsonService { -//---------------------------------------------------------------------------------------------------------------------- -// BadJsonService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response createBadJson() { - return Response.ok("{{{}}", MediaType.APPLICATION_JSON_TYPE).build(); - } - } -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/GsonServerProviderTest.java b/gson/provider/src/test/java/org/microbule/gson/provider/GsonServerProviderTest.java deleted file mode 100644 index 5ef5794..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/GsonServerProviderTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.provider; - -import java.util.List; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.server.JaxrsServerTestCase; -import org.mockito.Mock; - -import static org.mockito.Mockito.when; - -public class GsonServerProviderTest extends JaxrsServerTestCase { - - @Mock - private PersonService serviceImpl; - - @Override - protected PersonService createImplementation() { - return serviceImpl; - } - - @Override - protected void addBeans(SimpleContainer container) { - GsonService gsonService = new DefaultGsonService(container); - container.addBean(new JaxrsServerDecorator() { - @Override - public String name() { - return "gsonServer"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, e -> new JsonRequestParsingException(e))); - } - }); - - container.addBean(new JaxrsProxyDecorator() { - @Override - public String name() { - return "gsonProxy"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, e -> new JsonResponseParsingException(e))); - } - }); - } - - @Test - public void testGetSize() { - assertEquals(-1, new GsonProvider(null, null).getSize(null, null, null, null, null)); - } - - @Test - public void testWithJsonSyntaxException() { - final Response response = createWebTarget().path("people").request().post(Entity.entity("{{{}", MediaType.APPLICATION_JSON_TYPE)); - assertEquals(500, response.getStatus()); - } - - @Test - public void testBeanSerialization() { - when(serviceImpl.findPerson("Slappy", "White")).thenReturn(new Person("Slappy", "White")); - final Person person = createProxy().findPerson("Slappy", "White"); - assertEquals("Slappy", person.getFirstName()); - assertEquals("White", person.getLastName()); - } - - @Test - public void testGenericTypeSerialization() { - when(serviceImpl.all()).thenReturn(Lists.newArrayList(new Person("Slappy", "White"))); - final List persons = createProxy().all(); - assertEquals(1, persons.size()); - } -} \ No newline at end of file diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/Person.java b/gson/provider/src/test/java/org/microbule/gson/provider/Person.java deleted file mode 100644 index 7a30070..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/Person.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.provider; - -public class Person { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String firstName; - private final String lastName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/PersonService.java b/gson/provider/src/test/java/org/microbule/gson/provider/PersonService.java deleted file mode 100644 index b5981f4..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/PersonService.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.provider; - -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -@Path("/") -public interface PersonService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @GET - @Path("/people/{firstName}/{lastName}") - @Produces(MediaType.APPLICATION_JSON) - Person findPerson(@PathParam("firstName") String firstName, @PathParam("lastName") String lastName); - - @POST - @Path("/people") - @Consumes(MediaType.APPLICATION_JSON) - void addPerson(Person person); - - @GET - @Path("/people") - @Produces(MediaType.APPLICATION_JSON) - List all(); -} diff --git a/gson/spi/pom.xml b/gson/spi/pom.xml deleted file mode 100644 index 3e844a3..0000000 --- a/gson/spi/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-spi - Microbule :: GSON :: SPI - bundle - - diff --git a/gson/spi/src/main/java/org/microbule/gson/spi/GsonBuilderCustomizer.java b/gson/spi/src/main/java/org/microbule/gson/spi/GsonBuilderCustomizer.java deleted file mode 100644 index 76cc8f6..0000000 --- a/gson/spi/src/main/java/org/microbule/gson/spi/GsonBuilderCustomizer.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.spi; - -import com.google.gson.GsonBuilder; - -public interface GsonBuilderCustomizer { - void customize(GsonBuilder builder); -} diff --git a/gson/time/pom.xml b/gson/time/pom.xml deleted file mode 100644 index 31b6180..0000000 --- a/gson/time/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-time - Microbule :: GSON :: JavaSE 8 Date/Time - bundle - - - - org.microbule - microbule-gson-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/time/src/main/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizer.java b/gson/time/src/main/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizer.java deleted file mode 100644 index cb65b11..0000000 --- a/gson/time/src/main/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizer.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.microbule.gson.time; - -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.MonthDay; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.Period; -import java.time.Year; -import java.time.YearMonth; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.gson.GsonBuilder; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.microbule.gson.util.StringValueAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Named("javaTimeGsonBuilderCustomizer") -@Singleton -public class JavaTimeGsonBuilderCustomizer implements GsonBuilderCustomizer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(JavaTimeGsonBuilderCustomizer.class); - -//---------------------------------------------------------------------------------------------------------------------- -// GsonBuilderCustomizer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void customize(GsonBuilder builder) { - LOGGER.info("Adding GSON type adapters for JavaSE 8 Date/Time classes..."); - builder.registerTypeAdapter(Duration.class, StringValueAdapter.toStringAdapter(Duration::parse)); - builder.registerTypeAdapter(Instant.class, StringValueAdapter.toStringAdapter(Instant::parse)); - builder.registerTypeAdapter(LocalDate.class, StringValueAdapter.toStringAdapter(LocalDate::parse)); - builder.registerTypeAdapter(LocalDateTime.class, StringValueAdapter.toStringAdapter(LocalDateTime::parse)); - builder.registerTypeAdapter(LocalTime.class, StringValueAdapter.toStringAdapter(LocalTime::parse)); - builder.registerTypeAdapter(MonthDay.class, StringValueAdapter.toStringAdapter(MonthDay::parse)); - builder.registerTypeAdapter(OffsetDateTime.class, StringValueAdapter.toStringAdapter(OffsetDateTime::parse)); - builder.registerTypeAdapter(OffsetTime.class, StringValueAdapter.toStringAdapter(OffsetTime::parse)); - builder.registerTypeAdapter(Period.class, StringValueAdapter.toStringAdapter(Period::parse)); - builder.registerTypeAdapter(Year.class, StringValueAdapter.toStringAdapter(Year::parse)); - builder.registerTypeAdapter(YearMonth.class, StringValueAdapter.toStringAdapter(YearMonth::parse)); - } -} diff --git a/gson/time/src/main/resources/META-INF/beans.xml b/gson/time/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gson/time/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gson/time/src/main/resources/OSGI-INF/blueprint/microbule-gson-time.xml b/gson/time/src/main/resources/OSGI-INF/blueprint/microbule-gson-time.xml deleted file mode 100644 index 1acda0e..0000000 --- a/gson/time/src/main/resources/OSGI-INF/blueprint/microbule-gson-time.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/gson/time/src/test/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizerTest.java b/gson/time/src/test/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizerTest.java deleted file mode 100644 index 2ed854c..0000000 --- a/gson/time/src/test/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.microbule.gson.time; - -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.MonthDay; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.Period; -import java.time.Year; -import java.time.YearMonth; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonPrimitive; -import org.junit.Before; -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class JavaTimeGsonBuilderCustomizerTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private Gson gson; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initGson() { - GsonBuilder builder = new GsonBuilder(); - new JavaTimeGsonBuilderCustomizer().customize(builder); - gson = builder.serializeNulls().create(); - } - - @Test - public void testJavaTypesSupported() { - assertTypeSupported(Duration.ofMinutes(5)); - assertTypeSupported(Instant.now()); - assertTypeSupported(LocalDate.now()); - assertTypeSupported(LocalDateTime.now()); - assertTypeSupported(LocalTime.now()); - assertTypeSupported(MonthDay.now()); - assertTypeSupported(OffsetDateTime.now()); - assertTypeSupported(OffsetTime.now()); - assertTypeSupported(Period.ofWeeks(3)); - assertTypeSupported(Year.now()); - assertTypeSupported(YearMonth.now()); - } - - @SuppressWarnings("unchecked") - private void assertTypeSupported(T value) { - final JsonPrimitive jsonValue = (JsonPrimitive)gson.toJsonTree(value); - assertEquals(value.toString(), jsonValue.getAsString()); - T parsed = (T)gson.fromJson(jsonValue, value.getClass()); - assertEquals(value, parsed); - } -} \ No newline at end of file diff --git a/gson/util/pom.xml b/gson/util/pom.xml deleted file mode 100644 index f4641ff..0000000 --- a/gson/util/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-util - Microbule :: GSON :: Utilities - bundle - - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/util/src/main/java/org/microbule/gson/util/NullSafeTypeAdapter.java b/gson/util/src/main/java/org/microbule/gson/util/NullSafeTypeAdapter.java deleted file mode 100644 index f936dbe..0000000 --- a/gson/util/src/main/java/org/microbule/gson/util/NullSafeTypeAdapter.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.microbule.gson.util; - -import java.io.IOException; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; - -public abstract class NullSafeTypeAdapter extends TypeAdapter { -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract T readNonNull(JsonReader var1) throws IOException; - - protected abstract void writeNonNull(JsonWriter var1, T var2) throws IOException; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public final T read(JsonReader in) throws IOException { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } else { - return this.readNonNull(in); - } - } - - public final void write(JsonWriter out, T value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - this.writeNonNull(out, value); - } - } -} diff --git a/gson/util/src/main/java/org/microbule/gson/util/StringValueAdapter.java b/gson/util/src/main/java/org/microbule/gson/util/StringValueAdapter.java deleted file mode 100644 index 5bb36ee..0000000 --- a/gson/util/src/main/java/org/microbule/gson/util/StringValueAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.microbule.gson.util; - -import java.io.IOException; -import java.util.function.Function; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -public class StringValueAdapter extends NullSafeTypeAdapter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Function formatter; - private final Function parser; - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static TypeAdapter toStringAdapter(Function parser) { - return new StringValueAdapter<>(Object::toString, parser); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public StringValueAdapter(Function formatter, Function parser) { - this.formatter = formatter; - this.parser = parser; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected final T readNonNull(JsonReader in) throws IOException { - return this.parser.apply(in.nextString()); - } - - protected final void writeNonNull(JsonWriter out, T value) throws IOException { - out.value(formatter.apply(value)); - } -} diff --git a/gson/util/src/test/java/org/microbule/gson/util/StringValueAdapterTest.java b/gson/util/src/test/java/org/microbule/gson/util/StringValueAdapterTest.java deleted file mode 100644 index a778b16..0000000 --- a/gson/util/src/test/java/org/microbule/gson/util/StringValueAdapterTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.microbule.gson.util; - -import java.time.LocalDateTime; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.junit.Before; -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class StringValueAdapterTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private Gson gson; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initGson() { - final GsonBuilder builder = new GsonBuilder(); - builder.registerTypeAdapter(LocalDateTime.class, StringValueAdapter.toStringAdapter(LocalDateTime::parse)); - gson = builder.serializeNulls().create(); - } - - @Test - public void testReadingNulls() { - final Holder holder = gson.fromJson("{\"now\":null}", Holder.class); - assertNull(holder.now); - } - - @Test - public void testReadingValues() { - final LocalDateTime now = LocalDateTime.now(); - final Holder holder = gson.fromJson(String.format("{\"now\":\"%s\"}", now.toString()), Holder.class); - assertEquals(now, holder.now); - } - - @Test - public void testWritingNulls() { - assertEquals("{\"now\":null}", gson.toJson(new Holder())); - } - - @Test - public void testWritingValues() { - final LocalDateTime now = LocalDateTime.now(); - assertEquals(String.format("{\"now\":\"%s\"}", now.toString()), gson.toJson(new Holder(now))); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class Holder { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private LocalDateTime now; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Holder() { - } - - public Holder(LocalDateTime now) { - this.now = now; - } - } -} \ No newline at end of file diff --git a/gzip.md b/gzip.md new file mode 100644 index 0000000..d264710 --- /dev/null +++ b/gzip.md @@ -0,0 +1,3 @@ +# GZIP + +Microbule will automatically use GZIP to encode/decode payloads. diff --git a/gzip/pom.xml b/gzip/pom.xml deleted file mode 100644 index d865892..0000000 --- a/gzip/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-gzip-decorator - Microbule :: GZIP :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gzip/src/main/java/org/microbule/gzip/decorator/GzipDecorator.java b/gzip/src/main/java/org/microbule/gzip/decorator/GzipDecorator.java deleted file mode 100644 index 7786c6c..0000000 --- a/gzip/src/main/java/org/microbule/gzip/decorator/GzipDecorator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gzip.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.apache.cxf.transport.common.gzip.GZIPFeature; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("gzipDecorator") -public class GzipDecorator implements JaxrsServerDecorator, JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final String THRESHOLD_PROP = "threshold"; - public static final String FORCE_PROP = "force"; - public static final int DEFAULT_TRESHOLD = 1024; - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - final GZIPFeature feature = new GZIPFeature(); - feature.setForce(config.booleanValue(FORCE_PROP).orElse(Boolean.FALSE)); - feature.setThreshold(config.integerValue(THRESHOLD_PROP).orElse(DEFAULT_TRESHOLD)); - descriptor.addFeature(feature); - } - - @Override - public String name() { - return "gzip"; - } -} diff --git a/gzip/src/main/resources/META-INF/beans.xml b/gzip/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gzip/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gzip/src/main/resources/OSGI-INF/blueprint/microbule-gzip-decorator.xml b/gzip/src/main/resources/OSGI-INF/blueprint/microbule-gzip-decorator.xml deleted file mode 100644 index d766e20..0000000 --- a/gzip/src/main/resources/OSGI-INF/blueprint/microbule-gzip-decorator.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/gzip/src/test/java/org/microbule/gzip/decorator/GzipDecoratorTest.java b/gzip/src/test/java/org/microbule/gzip/decorator/GzipDecoratorTest.java deleted file mode 100644 index 77c698c..0000000 --- a/gzip/src/test/java/org/microbule/gzip/decorator/GzipDecoratorTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gzip.decorator; - -import org.apache.cxf.transport.common.gzip.GZIPFeature; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class GzipDecoratorTest extends MockObjectTestCase { - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Mock - private Config config; - - @Test - public void testDecorate() { - final GzipDecorator decorator = new GzipDecorator(); - assertEquals("gzip", decorator.name()); - decorator.decorate(descriptor, config); - verify(config).booleanValue("force"); - verify(config).integerValue("threshold"); - verify(descriptor).addFeature(any(GZIPFeature.class)); - verifyNoMoreInteractions(descriptor, config); - } - -} \ No newline at end of file diff --git a/index.md b/index.md new file mode 100644 index 0000000..cf3569b --- /dev/null +++ b/index.md @@ -0,0 +1,97 @@ +# Microbule + + +Microbule provides a framework for developing [Microservices](http://www.martinfowler.com/articles/microservices.html) +quickly and easily! Services are written using the standard + [Java API for RESTful Services](https://jax-rs-spec.java.net/) (JAX-RS). + +## Table of Contents + + +- [Getting Started](#getting-started) +- [Features](#microbule-features) +- [What's in the Box](#whats-in-the-box) + +## Getting Started + +Microbule supports many of the popular deployment containers/frameworks available. Simply choose from: + +- [Spring Framework](spring.md) +- [Contexts and Dependency Injection (CDI)](cdi.md) +- [Apache Karaf](karaf.md) + +## What's in the Box? + +Okay, so maybe Microbule doesn't really come in a box, but it does include some very helpful features "out-of-the-box": + +- [JSON Binding](json.md) +- [Circuit Breaker](circuitbreaker.md) +- [Request Logging](requestlog.md) +- [Bean Validation](validation.md) +- [Cross-Origin Resource Scripting (CORS)](cors.md) +- [Tracer](tracer.md) +- [Cache-Control](cache.md) +- [Connect/Receive Timeouts](timeout.md) +- [Error Mapping](errormap.md) +- [GZIP](gzip.md) +- [Swagger](swagger.md) +- [Metrics](metrics.md) + +## Creating Client Proxies + +One of the beautiful features of Apache CXF is its ability to generate dynamic client proxies that implement the JAX-RS +service interface. Microbule uses this feature to provide type-safe client proxies: + +``` +JaxrsProxyFactory proxyFactory = ...; +Map props = new HashMap<>(); +props.put("microbule.circuitbreaker.enabled", "false"); +HelloService helloService = proxyFactory.createProxy(HelloService.class, "http://localhost:8383/HelloService", props); +``` + +Microbule exposes a JaxrsProxyFactory OSGi service for you to use. Simply inject it wherever you need to create client +proxies. + +## Extending Microbule + +Extending Microbule couldn't be simpler. JAX-RS relies upon the notion of "providers" in order to customize the +"containers" and "clients." Microbule provides two extension points JaxrsServerDecorator and JaxrsProxyDecorator which +allow you to add container and client providers, respectively: + + ``` + public class MyServerDecorator implements JaxrsServerDecorator { + @Override + public void decorate(JaxrsServerConfig server) { + MyServerProvider provider = new MyServerProvider(); + server.addProvider(provider); + } + } + } + ``` + +The JaxrsServerConfig object will provide access to the service interface, the base address, and the service properties +associated with the OSGi service used for the server. To register your provider, you must expose it as an OSGi service +with the "name" service property indicating its name. Similarly, for customizing client proxies, you simply implement +JaxrsProxyDecorator: + + ``` + public class MyProxyDecorator implements JaxrsProxyDecorator { + @Override + public void decorate(JaxrsProxyConfig proxy) { + MyProxyProvider provider = new MyProxyProvider(); + proxy.addProvider(provider); + } + } + ``` + +Again, the JaxrsProxyDecorator must be expopsed as an OSGi service with the "name" property. + +## Opting Out + +By default, Microbule will apply all registered decorators to your services/proxies. However, you can opt out of them +individually using a service property. For example, if you want to provide your own JSON processing provider, you can +disable the GSON-based provider by setting the following service property: + + ``` + microbule.gson.enabled=false + ``` diff --git a/itest/cdi/pom.xml b/itest/cdi/pom.xml deleted file mode 100644 index 20e98de..0000000 --- a/itest/cdi/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-itest-parent - 0.3.0-SNAPSHOT - - - microbule-itest-cdi - Microbule :: Integration Tests :: CDI - - - ${project.basedir}/reports/jacoco.exec - - - - - org.microbule - microbule-all - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-test-cdi-server - 0.3.0-SNAPSHOT - test - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - true - - - - diff --git a/itest/cdi/src/test/java/org/microbule/itest/cdi/MicrobuleCdiIT.java b/itest/cdi/src/test/java/org/microbule/itest/cdi/MicrobuleCdiIT.java deleted file mode 100644 index 6b5f746..0000000 --- a/itest/cdi/src/test/java/org/microbule/itest/cdi/MicrobuleCdiIT.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.microbule.itest.cdi; - -import javax.inject.Singleton; - -import org.microbule.test.cdi.server.CdiServerTestCase; - -@Singleton -public class MicrobuleCdiIT extends CdiServerTestCase { -} diff --git a/itest/karaf/pom.xml b/itest/karaf/pom.xml deleted file mode 100644 index 89ede94..0000000 --- a/itest/karaf/pom.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-itest-parent - 0.3.0-SNAPSHOT - - - microbule-itest-karaf - Microbule :: Integration Tests :: Apache Karaf - - - ${project.basedir}/reports/jacoco.exec - - - - - org.microbule - microbule-api - 0.3.0-SNAPSHOT - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.microbule - microbule-features - 0.3.0-SNAPSHOT - - - - org.ops4j.pax.exam - pax-exam-junit4 - ${pax.exam.version} - test - - - - org.ops4j.pax.exam - pax-exam-container-karaf - ${pax.exam.version} - test - - - - org.ops4j.pax.exam - pax-exam-link-mvn - ${pax.exam.version} - test - - - - org.apache.geronimo.specs - geronimo-atinject_1.0_spec - 1.0 - test - - - - org.eclipse.osgi - org.eclipse.osgi - 3.7.1 - test - - - - org.apache.karaf.features - org.apache.karaf.features.core - ${karaf.version} - test - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - true - - once - - ${argLine} - ${project.version} - ${karaf.version} - - - - - - diff --git a/itest/karaf/src/test/java/org/microbule/itest/karaf/KarafFeaturesIT.java b/itest/karaf/src/test/java/org/microbule/itest/karaf/KarafFeaturesIT.java deleted file mode 100644 index e8e4780..0000000 --- a/itest/karaf/src/test/java/org/microbule/itest/karaf/KarafFeaturesIT.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.itest.karaf; - -import java.io.File; - -import javax.inject.Inject; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.microbule.api.JaxrsProxyFactory; -import org.microbule.api.JaxrsServerFactory; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.karaf.options.LogLevelOption; -import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; -import org.ops4j.pax.exam.spi.reactors.PerClass; - -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.maven; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.vmOption; -import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole; -import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features; -import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration; -import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder; -import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel; - -@RunWith(PaxExam.class) -@ExamReactorStrategy(PerClass.class) -public class KarafFeaturesIT extends Assert { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String DEFAULT_KARAF_VERSION = "4.1.1"; - - @Inject - private JaxrsProxyFactory proxyFactory; - - @Inject - private JaxrsServerFactory serverFactory; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Configuration - public Option[] configure() { - final String jvmOptions = StringUtils.defaultIfBlank(System.getProperty("jvm.options"), "-Dnoop"); - final String karafVersion = System.getProperty("karaf.version", DEFAULT_KARAF_VERSION); - final String projectVersion = System.getProperty("project.version"); - return options( - karafDistributionConfiguration() - .frameworkUrl(maven("org.apache.karaf", "apache-karaf", karafVersion).type("tar.gz")) - .unpackDirectory(new File("target/karaf")), - vmOption(jvmOptions), - configureConsole() - .startRemoteShell() - .ignoreLocalConsole(), - - features(maven("org.microbule", "microbule-features", projectVersion).type("xml").classifier("features"), "microbule"), - junitBundles(), - keepRuntimeFolder(), - logLevel(LogLevelOption.LogLevel.WARN)); - } - - @Test - public void testFeatureInstalls() throws Exception { - assertNotNull(proxyFactory); - assertNotNull(serverFactory); - } -} diff --git a/itest/pom.xml b/itest/pom.xml deleted file mode 100644 index 62dd390..0000000 --- a/itest/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-itest-parent - Microbule :: Integration Tests :: Parent - pom - - - karaf - cdi - spring - - diff --git a/itest/spring/pom.xml b/itest/spring/pom.xml deleted file mode 100644 index 073605c..0000000 --- a/itest/spring/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-itest-parent - 0.3.0-SNAPSHOT - - - microbule-itest-spring - Microbule :: Integration Tests :: Spring - - - ${project.basedir}/reports/jacoco.exec - - - - - org.microbule - microbule-test-spring-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-all - 0.3.0-SNAPSHOT - test - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - true - - - - diff --git a/itest/spring/src/test/java/org/microbule/itest/spring/MicrobuleSpringIT.java b/itest/spring/src/test/java/org/microbule/itest/spring/MicrobuleSpringIT.java deleted file mode 100644 index c39c296..0000000 --- a/itest/spring/src/test/java/org/microbule/itest/spring/MicrobuleSpringIT.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.microbule.itest.spring; - -import org.microbule.test.spring.server.SpringServerTestCase; - -public class MicrobuleSpringIT extends SpringServerTestCase { -} diff --git a/json.md b/json.md new file mode 100644 index 0000000..f8ba4cb --- /dev/null +++ b/json.md @@ -0,0 +1,82 @@ +# JSON Binding + +Microbule includes JSON binding support using the [Google GSON](https://github.com/google/gson) library. For example, consider the following JAX-RS service: + +```java +@Path("/") +public interface PersonService { + + @GET + @Path("/people/{id}") + @Produces(MediaType.APPLICATION_JSON) + Person getPerson(@PathParam("id") String id); + + @POST + @Path("/people") + @Consumes(MediaType.APPLICATION_JSON) + void addPerson(Person person); +} +``` + +which uses the *Person* class: + +```java +public class Person { + + private final String id; + private String firstName; + private String lastName; + + public Person(String id) { + this.id = id; + } + + // Getters/Setters... +} +``` + +Microbule allows you to implement your service using this simle Java-based API: + +```java +public class PersonServiceImpl implements PersonService { + + private final PersonDao dao; + + public PersonServiceImpl(PersonDao dao) { + this.dao = dao; + } + + public Person getPerson(String id) { + return dao.findById(id); + } + + public void addPerson(Person person) { + dao.save(person); + } +} +``` + +Furthermore, clients using your service can use Microbule-generated type-safe proxies and simply code to your service interface. Microbule will take care of all of the JSON serialization/deserialization automatically. When calling the *addPerson()* method, for instance, Microbule will generate the following JSON request body: + +```json +{ + "id": "12345", + "firstName": "Mr.", + "lastName": "Microbule" +} +``` + +Likewise, when calling *getPerson()*, Microbule will generate the the JSON response body using the same format. + + +## Customizing GSON + +By default, GSON can do a pretty good job transforming your objects to/from JSON. There are some times, however, when you will want to customize how GSON handles certain types of fields. In order to do that, you must implement a *GsonBuilderCustomizer*: + +```java +public interfac GsonBuilderCustomizer { + void customize(GsonBuilder builder); +} +``` + +When a GsonBuilderCustomizer is detected by the MicrobuleContainer, it will be used to customize the *Gson* object used by Microbule. Feel free to check out the GSON [User Guide](https://github.com/google/gson/blob/master/UserGuide.md) for more information on how you can customize GSON. diff --git a/karaf.md b/karaf.md new file mode 100644 index 0000000..12a1067 --- /dev/null +++ b/karaf.md @@ -0,0 +1,31 @@ +# Apache Karaf + +Microbule comes with a Karaf features repository file. To install Microbule, simply execute the following commands in the Karaf console: + +``` +feature:repo-add mvn:org.microbule/microbule-features/[VERSION]/xml/features +feature:install microbule +``` + +# JAX-RS Service Discovery + +Microbule uses the OSGi [Whiteboard Pattern](http://enroute.osgi.org/doc/218-patterns.html) to discover JAX-RS services at runtime. In order to register a JAX-RS service with Microbule, you simply have to expose them as OSGi service with the "microbule.server" property (any value will do). If you use a simple OSGi bundle activator: + +```java +public class HelloActivator implements BundleActivator { + + private ServiceRegistration registration; + + @Override + public void start(BundleContext context) throws Exception { + Dictionary props = new Hashtable<>(); + props.put("microbule.server", "true"); + registration = context.registerService(HelloResource.class, new DefaultHelloResource(), props); + } + + @Override + public void stop(BundleContext context) throws Exception { + registration.unregister(); + } +} +``` diff --git a/logging/pom.xml b/logging/pom.xml deleted file mode 100644 index cb89158..0000000 --- a/logging/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-logging-decorator - Microbule :: Logging :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/logging/src/main/java/org/microbule/logging/decorator/LoggingDecorator.java b/logging/src/main/java/org/microbule/logging/decorator/LoggingDecorator.java deleted file mode 100644 index 413a120..0000000 --- a/logging/src/main/java/org/microbule/logging/decorator/LoggingDecorator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.logging.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.apache.cxf.feature.LoggingFeature; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("loggingDecorator") -public class LoggingDecorator implements JaxrsServerDecorator, JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addFeature(new LoggingFeature()); - } - - @Override - public String name() { - return "logging"; - } -} diff --git a/logging/src/main/resources/META-INF/beans.xml b/logging/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/logging/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/logging/src/main/resources/OSGI-INF/blueprint/microbule-logging-decorator.xml b/logging/src/main/resources/OSGI-INF/blueprint/microbule-logging-decorator.xml deleted file mode 100644 index 39e1995..0000000 --- a/logging/src/main/resources/OSGI-INF/blueprint/microbule-logging-decorator.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/logging/src/test/java/org/microbule/logging/decorator/LoggingDecoratorTest.java b/logging/src/test/java/org/microbule/logging/decorator/LoggingDecoratorTest.java deleted file mode 100644 index 51580f3..0000000 --- a/logging/src/test/java/org/microbule/logging/decorator/LoggingDecoratorTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.logging.decorator; - -import org.apache.cxf.feature.LoggingFeature; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class LoggingDecoratorTest extends MockObjectTestCase { - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Mock - private Config config; - - @Test - public void testDecorate() { - final LoggingDecorator decorator = new LoggingDecorator(); - assertEquals("logging", decorator.name()); - decorator.decorate(descriptor, config); - verify(descriptor).addFeature(any(LoggingFeature.class)); - verifyNoMoreInteractions(descriptor, config); - } - -} \ No newline at end of file diff --git a/metrics.md b/metrics.md new file mode 100644 index 0000000..10e91b1 --- /dev/null +++ b/metrics.md @@ -0,0 +1,3 @@ +# Metrics + +Microbule can collect metrics for your service methods using the [DropWizard Metrics](http://metrics.dropwizard.io/) library. diff --git a/metrics/annotation/pom.xml b/metrics/annotation/pom.xml deleted file mode 100644 index 3a7709b..0000000 --- a/metrics/annotation/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-metrics-parent - 0.3.0-SNAPSHOT - - - microbule-metrics-annotation - Microbule :: Metrics :: Annotation - bundle - - - diff --git a/metrics/annotation/src/main/java/org/microbule/metrics/annotation/Timed.java b/metrics/annotation/src/main/java/org/microbule/metrics/annotation/Timed.java deleted file mode 100644 index 0a9769b..0000000 --- a/metrics/annotation/src/main/java/org/microbule/metrics/annotation/Timed.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.microbule.metrics.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import static org.apache.commons.lang3.StringUtils.EMPTY; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface Timed { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String name() default EMPTY; - - String strategy() default EMPTY; -} diff --git a/metrics/api/pom.xml b/metrics/api/pom.xml deleted file mode 100644 index 7b8b35f..0000000 --- a/metrics/api/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-metrics-parent - 0.3.0-SNAPSHOT - - - microbule-metrics-api - Microbule :: Metrics :: API - bundle - - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - diff --git a/metrics/api/src/main/java/org/microbule/metrics/api/MetricsService.java b/metrics/api/src/main/java/org/microbule/metrics/api/MetricsService.java deleted file mode 100644 index e0b52c6..0000000 --- a/metrics/api/src/main/java/org/microbule/metrics/api/MetricsService.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.microbule.metrics.api; - -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; - -public interface MetricsService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - Timer createTimer(String name, String timingStrategyName, Config config); - - MetricRegistry getRegistry(); - -} diff --git a/metrics/core/pom.xml b/metrics/core/pom.xml deleted file mode 100644 index 4a7f628..0000000 --- a/metrics/core/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-metrics-parent - 0.3.0-SNAPSHOT - - - microbule-metrics-core - Microbule :: Metrics :: Core - bundle - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - test - - - - diff --git a/metrics/core/src/main/java/org/microbule/metrics/core/DefaultMetricsService.java b/metrics/core/src/main/java/org/microbule/metrics/core/DefaultMetricsService.java deleted file mode 100644 index 193f2ef..0000000 --- a/metrics/core/src/main/java/org/microbule/metrics/core/DefaultMetricsService.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.microbule.metrics.core; - -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.metrics.api.MetricsService; -import org.microbule.metrics.core.strategy.DefaultTimingStrategy; -import org.microbule.metrics.spi.TimingStrategy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Named("metricsService") -@Singleton -public class DefaultMetricsService implements MetricsService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMetricsService.class); - private final MetricRegistry registry = new MetricRegistry(); - private final Map timingStrategies; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultMetricsService(MicrobuleContainer container) { - this.timingStrategies = container.pluginMap(TimingStrategy.class, TimingStrategy::name); - } - -//---------------------------------------------------------------------------------------------------------------------- -// MetricsService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Timer createTimer(String name, String timingStrategyName, Config config) { - return registry.timer(name, () -> { - TimingStrategy strategy = timingStrategies.get(timingStrategyName); - if (strategy == null) { - LOGGER.warn("Timing strategy \"{}\" not found, using default instead.", timingStrategyName); - strategy = DefaultTimingStrategy.INSTANCE; - } - return strategy.createTimer(config.filtered(strategy.name())); - }); - } - - @Override - public MetricRegistry getRegistry() { - return registry; - } -} diff --git a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/DefaultTimingStrategy.java b/metrics/core/src/main/java/org/microbule/metrics/core/strategy/DefaultTimingStrategy.java deleted file mode 100644 index ccf3b45..0000000 --- a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/DefaultTimingStrategy.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; -import org.microbule.metrics.spi.TimingStrategy; - -public class DefaultTimingStrategy implements TimingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final TimingStrategy INSTANCE = new DefaultTimingStrategy(); - -//---------------------------------------------------------------------------------------------------------------------- -// Named Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String name() { - return "default"; - } - -//---------------------------------------------------------------------------------------------------------------------- -// TimingStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Timer createTimer(Config config) { - return new Timer(); - } -} diff --git a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/ExponentiallyDecayingTimingStrategy.java b/metrics/core/src/main/java/org/microbule/metrics/core/strategy/ExponentiallyDecayingTimingStrategy.java deleted file mode 100644 index c17f040..0000000 --- a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/ExponentiallyDecayingTimingStrategy.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.ExponentiallyDecayingReservoir; -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; -import org.microbule.metrics.spi.TimingStrategy; - -@Named("exponentiallyDecayingTimingStrategy") -@Singleton -public class ExponentiallyDecayingTimingStrategy implements TimingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String SIZE_PROP = "size"; - private static final String ALPHA_PROP = "alpha"; - private static final int DEFAULT_SIZE = 1028; - private static final double DEFAULT_ALPHA = 0.015; - -//---------------------------------------------------------------------------------------------------------------------- -// TimingStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Timer createTimer(Config config) { - return new Timer(new ExponentiallyDecayingReservoir( - config.integerValue(SIZE_PROP).orElse(DEFAULT_SIZE), - config.doubleValue(ALPHA_PROP).orElse(DEFAULT_ALPHA))); - } - - @Override - public String name() { - return "decay"; - } -} diff --git a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/SlidingTimeWindowTimingStrategy.java b/metrics/core/src/main/java/org/microbule/metrics/core/strategy/SlidingTimeWindowTimingStrategy.java deleted file mode 100644 index 4d4b833..0000000 --- a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/SlidingTimeWindowTimingStrategy.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import java.util.concurrent.TimeUnit; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.SlidingTimeWindowReservoir; -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; -import org.microbule.metrics.spi.TimingStrategy; - -@Named("slidingTimeWindowTimingStrategy") -@Singleton -public class SlidingTimeWindowTimingStrategy implements TimingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final TimeUnit DEFAULT_WINDOW_UNIT = TimeUnit.MINUTES; - private static final long DEFAULT_WINDOW = 15; - private static final String WINDOW_PROP = "window"; - private static final String WINDOW_UNIT_PROP = "windowUnit"; - -//---------------------------------------------------------------------------------------------------------------------- -// TimingStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Timer createTimer(Config config) { - return new Timer(new SlidingTimeWindowReservoir( - config.longValue(WINDOW_PROP).orElse(DEFAULT_WINDOW), - config.enumValue(WINDOW_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_WINDOW_UNIT))); - } - - @Override - public String name() { - return "timeWindow"; - } -} diff --git a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/SlidingWindowTimingStrategy.java b/metrics/core/src/main/java/org/microbule/metrics/core/strategy/SlidingWindowTimingStrategy.java deleted file mode 100644 index 442a4e3..0000000 --- a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/SlidingWindowTimingStrategy.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.SlidingWindowReservoir; -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; -import org.microbule.metrics.spi.TimingStrategy; - -@Named("slidingWindowTimingStrategy") -@Singleton -public class SlidingWindowTimingStrategy implements TimingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final int DEFAULT_SIZE = 1024; - private static final String SIZE_PROP = "size"; - -//---------------------------------------------------------------------------------------------------------------------- -// Named Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String name() { - return "window"; - } - -//---------------------------------------------------------------------------------------------------------------------- -// TimingStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Timer createTimer(Config config) { - return new Timer(new SlidingWindowReservoir(config.integerValue(SIZE_PROP).orElse(DEFAULT_SIZE))); - } -} diff --git a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/UniformTimingStrategy.java b/metrics/core/src/main/java/org/microbule/metrics/core/strategy/UniformTimingStrategy.java deleted file mode 100644 index 37998c1..0000000 --- a/metrics/core/src/main/java/org/microbule/metrics/core/strategy/UniformTimingStrategy.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.Timer; -import com.codahale.metrics.UniformReservoir; -import org.microbule.config.api.Config; -import org.microbule.metrics.spi.TimingStrategy; - -@Named("uniformTimingStrategy") -@Singleton -public class UniformTimingStrategy implements TimingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final int DEFAULT_SIZE = 1024; - private static final String SIZE_PROP = "size"; - -//---------------------------------------------------------------------------------------------------------------------- -// TimingStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Timer createTimer(Config config) { - return new Timer(new UniformReservoir(config.integerValue(SIZE_PROP).orElse(DEFAULT_SIZE))); - } - - @Override - public String name() { - return "uniform"; - } -} diff --git a/metrics/core/src/main/resources/META-INF/beans.xml b/metrics/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/metrics/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/metrics/core/src/main/resources/OSGI-INF/blueprint/microbule-metrics-core.xml b/metrics/core/src/main/resources/OSGI-INF/blueprint/microbule-metrics-core.xml deleted file mode 100644 index d583c59..0000000 --- a/metrics/core/src/main/resources/OSGI-INF/blueprint/microbule-metrics-core.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/metrics/core/src/test/java/org/microbule/metrics/core/DefaultMetricsServiceTest.java b/metrics/core/src/test/java/org/microbule/metrics/core/DefaultMetricsServiceTest.java deleted file mode 100644 index 909dd0e..0000000 --- a/metrics/core/src/test/java/org/microbule/metrics/core/DefaultMetricsServiceTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.microbule.metrics.core; - -import com.codahale.metrics.Timer; -import org.junit.Before; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.core.MapConfig; -import org.microbule.container.core.SimpleContainer; -import org.microbule.metrics.spi.TimingStrategy; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; -import org.mockito.Mockito; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DefaultMetricsServiceTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private TimingStrategy strategy; - - @Mock - private Config config; - - @Mock - private Config strategyConfig; - - private DefaultMetricsService service; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initContainer() { - when(strategy.name()).thenReturn("mockStrategy"); - when(strategy.createTimer(any(Config.class))).thenReturn(new Timer()); - - SimpleContainer container = new SimpleContainer(); - - container.addBean(strategy); - - service = new DefaultMetricsService(container); - - container.initialize(); - } - - @Test - public void testCreateTimerWithUnknown() { - final Timer timer = service.createTimer("foo", "bogus", new MapConfig()); - assertNotNull(timer); - - assertNotNull(service.getRegistry()); - verify(strategy).name(); - Mockito.verifyNoMoreInteractions(strategy); - } - - @Test - public void testCreateTimer() { - when(config.filtered("mockStrategy")).thenReturn(strategyConfig); - - final Timer timer = service.createTimer("foo", "mockStrategy", config); - assertNotNull(timer); - - assertNotNull(service.getRegistry()); - verify(strategy, times(2)).name(); - verify(strategy).createTimer(strategyConfig); - Mockito.verifyNoMoreInteractions(strategy); - } -} \ No newline at end of file diff --git a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/AbstractTimingStrategyTest.java b/metrics/core/src/test/java/org/microbule/metrics/core/strategy/AbstractTimingStrategyTest.java deleted file mode 100644 index 62ad357..0000000 --- a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/AbstractTimingStrategyTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import java.lang.reflect.Field; - -import com.codahale.metrics.Histogram; -import com.codahale.metrics.Reservoir; -import com.codahale.metrics.Timer; -import org.microbule.test.core.MockObjectTestCase; - -public abstract class AbstractTimingStrategyTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @SuppressWarnings("unchecked") - protected T fieldValue(Object target, String fieldName) throws ReflectiveOperationException { - final Field field = target.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - return (T)field.get(target); - } - - protected T reservoir(Timer timer) throws ReflectiveOperationException{ - Histogram histogram = fieldValue(timer, "histogram"); - return fieldValue(histogram, "reservoir"); - } -} diff --git a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/ExponentiallyDecayingTimingStrategyTest.java b/metrics/core/src/test/java/org/microbule/metrics/core/strategy/ExponentiallyDecayingTimingStrategyTest.java deleted file mode 100644 index 54df23d..0000000 --- a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/ExponentiallyDecayingTimingStrategyTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import com.codahale.metrics.ExponentiallyDecayingReservoir; -import com.codahale.metrics.Timer; -import org.junit.Test; -import org.microbule.config.core.MapConfig; - -public class ExponentiallyDecayingTimingStrategyTest extends AbstractTimingStrategyTest { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateTimer() throws Exception { - final ExponentiallyDecayingTimingStrategy strategy = new ExponentiallyDecayingTimingStrategy(); - final Timer timer = strategy.createTimer(new MapConfig()); - - ExponentiallyDecayingReservoir reservoir = reservoir(timer); - assertNotNull(reservoir); - assertEquals("decay", strategy.name()); - } -} \ No newline at end of file diff --git a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/SlidingTimeWindowTimingStrategyTest.java b/metrics/core/src/test/java/org/microbule/metrics/core/strategy/SlidingTimeWindowTimingStrategyTest.java deleted file mode 100644 index edaecb6..0000000 --- a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/SlidingTimeWindowTimingStrategyTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import com.codahale.metrics.SlidingTimeWindowReservoir; -import com.codahale.metrics.Timer; -import org.junit.Test; -import org.microbule.config.core.MapConfig; - -public class SlidingTimeWindowTimingStrategyTest extends AbstractTimingStrategyTest { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateTimer() throws ReflectiveOperationException { - final SlidingTimeWindowTimingStrategy strategy = new SlidingTimeWindowTimingStrategy(); - final Timer timer = strategy.createTimer(new MapConfig()); - SlidingTimeWindowReservoir reservoir = reservoir(timer); - assertNotNull(reservoir); - assertEquals("timeWindow", strategy.name()); - } -} \ No newline at end of file diff --git a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/SlidingWindowTimingStrategyTest.java b/metrics/core/src/test/java/org/microbule/metrics/core/strategy/SlidingWindowTimingStrategyTest.java deleted file mode 100644 index 2439f1b..0000000 --- a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/SlidingWindowTimingStrategyTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import com.codahale.metrics.SlidingWindowReservoir; -import com.codahale.metrics.Timer; -import org.junit.Test; -import org.microbule.config.core.MapConfig; - -public class SlidingWindowTimingStrategyTest extends AbstractTimingStrategyTest { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateTimer() throws ReflectiveOperationException { - final SlidingWindowTimingStrategy strategy = new SlidingWindowTimingStrategy(); - final Timer timer = strategy.createTimer(new MapConfig()); - SlidingWindowReservoir reservoir = reservoir(timer); - assertNotNull(reservoir); - assertEquals("window", strategy.name()); - } -} \ No newline at end of file diff --git a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/UniformTimingStrategyTest.java b/metrics/core/src/test/java/org/microbule/metrics/core/strategy/UniformTimingStrategyTest.java deleted file mode 100644 index 6f59676..0000000 --- a/metrics/core/src/test/java/org/microbule/metrics/core/strategy/UniformTimingStrategyTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.microbule.metrics.core.strategy; - -import com.codahale.metrics.Timer; -import com.codahale.metrics.UniformReservoir; -import org.junit.Test; -import org.microbule.config.core.MapConfig; - -public class UniformTimingStrategyTest extends AbstractTimingStrategyTest { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateTimer() throws ReflectiveOperationException { - final UniformTimingStrategy strategy = new UniformTimingStrategy(); - final Timer timer = strategy.createTimer(new MapConfig()); - UniformReservoir reservoir = reservoir(timer); - assertNotNull(reservoir); - assertEquals("uniform", strategy.name()); - } -} \ No newline at end of file diff --git a/metrics/decorator/pom.xml b/metrics/decorator/pom.xml deleted file mode 100644 index 0adb0c8..0000000 --- a/metrics/decorator/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-metrics-parent - 0.3.0-SNAPSHOT - - - microbule-metrics-decorator - Microbule :: Metrics :: Decorator - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-metrics-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-metrics-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-decorator - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - test - - - - diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsDecorator.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsDecorator.java deleted file mode 100644 index 2945225..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsDecorator.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.microbule.metrics.decorator; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.metrics.api.MetricsService; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Named("metricsDecorator") -@Singleton -public class MetricsDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final MetricsService metricsService; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public MetricsDecorator(MetricsService metricsService) { - this.metricsService = metricsService; - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new MetricsFeature(metricsService, descriptor, config)); - descriptor.addProvider(new MetricsRequestFilter(metricsService.getRegistry(), descriptor.serviceInterface().getSimpleName())); - } - - @Override - public String name() { - return "metrics"; - } -} diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsFeature.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsFeature.java deleted file mode 100644 index 5142350..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsFeature.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.stream.Collectors; - -import javax.ws.rs.container.ResourceInfo; -import javax.ws.rs.core.FeatureContext; -import javax.ws.rs.ext.Provider; - -import com.codahale.metrics.MetricRegistry; -import com.codahale.metrics.Timer; -import org.apache.commons.lang3.StringUtils; -import org.microbule.config.api.Config; -import org.microbule.metrics.annotation.Timed; -import org.microbule.metrics.api.MetricsService; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.util.jaxrs.AnnotationDrivenDynamicFeature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Provider -public class MetricsFeature extends AnnotationDrivenDynamicFeature { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(MetricsFeature.class); - - private final MetricsService metricsService; - private final Config config; - private final JaxrsServiceDescriptor descriptor; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - MetricsFeature(MetricsService metricsService, JaxrsServiceDescriptor descriptor, Config config) { - this.metricsService = metricsService; - this.descriptor = descriptor; - this.config = config; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void configure(Timed annotation, ResourceInfo resourceInfo, FeatureContext featureContext) { - final Method method = resourceInfo.getResourceMethod(); - final String name = MetricRegistry.name(descriptor.serviceInterface().getSimpleName(), StringUtils.defaultIfBlank(annotation.name(), method.getName())); - final Timer timer = metricsService.createTimer(name, annotation.strategy(), config); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding \"{}\" timer using strategy \"{}\" filter to method {}.{}({})...", name, annotation.strategy(), descriptor.serviceInterface().getSimpleName(), method.getName(), Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", "))); - } - featureContext.register(new MetricsFilter(timer)); - } -} diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsFilter.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsFilter.java deleted file mode 100644 index 12af238..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsFilter.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.io.IOException; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import com.codahale.metrics.Timer; - -@Provider -@Priority(Priorities.USER - 200) -public class MetricsFilter implements ContainerRequestFilter, ContainerResponseFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String CONTEXT_PROP = MetricsFilter.class.getSimpleName() + "." + Timer.Context.class.getSimpleName(); - private final Timer timer; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - MetricsFilter(Timer timer) { - this.timer = timer; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - requestContext.setProperty(CONTEXT_PROP, timer.time()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerResponseFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - final Timer.Context context = (Timer.Context) requestContext.getProperty(CONTEXT_PROP); - if (context != null && Response.Status.Family.SUCCESSFUL.equals(responseContext.getStatusInfo().getFamily())) { - context.stop(); - } - } -} \ No newline at end of file diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsGsonBuilderCustomizer.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsGsonBuilderCustomizer.java deleted file mode 100644 index 10b9563..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsGsonBuilderCustomizer.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.lang.reflect.Type; -import java.util.concurrent.TimeUnit; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.Snapshot; -import com.codahale.metrics.Timer; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Named("metricsGsonBuilderCustomizer") -@Singleton -public class MetricsGsonBuilderCustomizer implements GsonBuilderCustomizer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final double DURATION_FACTOR = 1.0 / TimeUnit.SECONDS.toNanos(1); - private static final Logger LOGGER = LoggerFactory.getLogger(MetricsGsonBuilderCustomizer.class); - -//---------------------------------------------------------------------------------------------------------------------- -// GsonBuilderCustomizer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void customize(GsonBuilder builder) { - LOGGER.info("Adding GSON type adapter for DropWizard Metrics' Timer class..."); - builder.registerTypeAdapter(Timer.class, new TimerSerializer()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class TimerSerializer implements JsonSerializer { -//---------------------------------------------------------------------------------------------------------------------- -// JsonSerializer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public JsonElement serialize(Timer timer, Type typeOfSrc, JsonSerializationContext context) { - JsonObject json = new JsonObject(); - final Snapshot snapshot = timer.getSnapshot(); - json.addProperty("count", timer.getCount()); - json.addProperty("max", snapshot.getMax() * DURATION_FACTOR); - json.addProperty("mean", snapshot.getMean() * DURATION_FACTOR); - json.addProperty("min", snapshot.getMin() * DURATION_FACTOR); - - json.addProperty("p50", snapshot.getMedian() * DURATION_FACTOR); - json.addProperty("p75", snapshot.get75thPercentile() * DURATION_FACTOR); - json.addProperty("p95", snapshot.get95thPercentile() * DURATION_FACTOR); - json.addProperty("p98", snapshot.get98thPercentile() * DURATION_FACTOR); - json.addProperty("p99", snapshot.get99thPercentile() * DURATION_FACTOR); - json.addProperty("p999", snapshot.get999thPercentile() * DURATION_FACTOR); - - json.addProperty("stddev", snapshot.getStdDev() * DURATION_FACTOR); - json.addProperty("m15_rate", timer.getFifteenMinuteRate()); - json.addProperty("m1_rate", timer.getOneMinuteRate()); - json.addProperty("m5_rate", timer.getFiveMinuteRate()); - json.addProperty("mean_rate", timer.getMeanRate()); - json.addProperty("duration_units", "seconds"); - json.addProperty("rate_units", "calls/second"); - return json; - } - } -} diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsRequestFilter.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsRequestFilter.java deleted file mode 100644 index 5406e0e..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsRequestFilter.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.microbule.metrics.decorator; - -import javax.ws.rs.container.ContainerRequestContext; - -import com.codahale.metrics.MetricRegistry; -import org.microbule.util.jaxrs.ExtensionRequestFilter; - -public class MetricsRequestFilter extends ExtensionRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final MetricRegistry metricRegistry; - private final String namePrefix; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MetricsRequestFilter(MetricRegistry metricRegistry, String namePrefix) { - this.metricRegistry = metricRegistry; - this.namePrefix = namePrefix; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected MetricsResponse createResponse(ContainerRequestContext requestContext) { - return new MetricsResponse(metricRegistry.getTimers((name, metric) -> name.startsWith(namePrefix))); - } - - @Override - protected String markerParam() { - return "_metrics"; - } -} diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsResponse.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsResponse.java deleted file mode 100644 index fe45f5c..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsResponse.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.util.Map; - -import com.codahale.metrics.Timer; - -public class MetricsResponse { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Map timers; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MetricsResponse(Map timers) { - this.timers = timers; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public Map getTimers() { - return timers; - } -} diff --git a/metrics/decorator/src/main/resources/META-INF/beans.xml b/metrics/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/metrics/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml b/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml deleted file mode 100644 index 5fc2c2a..0000000 --- a/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java b/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java deleted file mode 100644 index 20f0f63..0000000 --- a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.io.StringReader; - -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.codahale.metrics.Timer; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; -import org.microbule.metrics.core.DefaultMetricsService; -import org.microbule.metrics.core.strategy.ExponentiallyDecayingTimingStrategy; -import org.microbule.metrics.core.strategy.SlidingTimeWindowTimingStrategy; -import org.microbule.metrics.core.strategy.SlidingWindowTimingStrategy; -import org.microbule.metrics.core.strategy.UniformTimingStrategy; -import org.microbule.test.server.JaxrsServerTestCase; - -public class MetricsDecoratorTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private DefaultMetricsService metricsService; - private DefaultGsonService gsonService; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - metricsService = new DefaultMetricsService(container); - container.addBean(metricsService); - container.addBean(new ExponentiallyDecayingTimingStrategy()); - container.addBean(new SlidingTimeWindowTimingStrategy()); - container.addBean(new SlidingWindowTimingStrategy()); - container.addBean(new UniformTimingStrategy()); - container.addBean(new MetricsDecorator(metricsService)); - gsonService = new DefaultGsonService(container); - container.addBean(gsonService); - container.addBean(new MetricsGsonBuilderCustomizer()); - container.addBean(new GsonServerDecorator(gsonService)); - container.addBean(new GsonProxyDecorator(gsonService)); - } - - @Override - protected TimedResource createImplementation() { - return new TimedResourceImpl(); - } - - @Test - public void testDecayTiming() { - assertNotNull(createProxy().decayTimer()); - - final Timer timer = metricsService.getRegistry().timer("TimedResource.decayTimer"); - assertEquals(1, timer.getCount()); - } - - @Test - public void testDefaultTiming() { - assertNotNull(createProxy().defaultTimer()); - - final Timer timer = metricsService.getRegistry().timer("TimedResource.defaultTimer"); - assertEquals(1, timer.getCount()); - } - - @Test - public void testMetricsFilter() { - Response response = createWebTarget().queryParam("_metrics", "").request(MediaType.APPLICATION_JSON_TYPE).get(); - assertEquals(200, response.getStatus()); - MetricsResponse metricsResponse = gsonService.parse(new StringReader(response.readEntity(String.class)), MetricsResponse.class); - - metricsResponse.getTimers().forEach((k,v) -> { - assertTrue(k.startsWith("TimedResource")); - }); - } - - @Test - public void testNoMetricsWhenErrorOccurs() { - try { - createProxy().errorTimer(); - fail("Should encounter an error!"); - } - catch(InternalServerErrorException e) { - // Do nothing! - } - - final Timer timer = metricsService.getRegistry().timer("TimedResource.errorTimer"); - assertEquals(0, timer.getCount()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class TimedResourceImpl implements TimedResource { -//---------------------------------------------------------------------------------------------------------------------- -// TimedResource Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String decayTimer() { - return now(); - } - - @Override - public String defaultTimer() { - return now(); - } - - @Override - public String errorTimer() { - throw new InternalServerErrorException("Oops!"); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private String now() { - return String.valueOf(System.currentTimeMillis()); - } - } -} \ No newline at end of file diff --git a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsResponseTest.java b/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsResponseTest.java deleted file mode 100644 index c563947..0000000 --- a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsResponseTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.util.HashMap; - -import com.codahale.metrics.Timer; -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class MetricsResponseTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testConstructor() { - final HashMap timers = new HashMap<>(); - final MetricsResponse response = new MetricsResponse(timers); - assertSame(timers, response.getTimers()); - } -} \ No newline at end of file diff --git a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/TimedResource.java b/metrics/decorator/src/test/java/org/microbule/metrics/decorator/TimedResource.java deleted file mode 100644 index f42ce76..0000000 --- a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/TimedResource.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.microbule.metrics.decorator; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import org.microbule.metrics.annotation.Timed; - -@Path("/") -public interface TimedResource { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Timed - @Path("/defaultTimer") - String defaultTimer(); - - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Timed(strategy = "decay") - @Path("/decayTimer") - String decayTimer(); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Timed - @Path("/errorTimer") - String errorTimer(); -} diff --git a/metrics/pom.xml b/metrics/pom.xml deleted file mode 100644 index cfb8192..0000000 --- a/metrics/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-metrics-parent - Microbule :: Metrics :: Parent - pom - - - annotation - api - spi - core - decorator - - - - - io.dropwizard.metrics - metrics-core - ${dropwizard.metrics.version} - - - diff --git a/metrics/spi/pom.xml b/metrics/spi/pom.xml deleted file mode 100644 index b029cf0..0000000 --- a/metrics/spi/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-metrics-parent - 0.3.0-SNAPSHOT - - - microbule-metrics-spi - Microbule :: Metrics :: SPI - bundle - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - - diff --git a/metrics/spi/src/main/java/org/microbule/metrics/spi/TimingStrategy.java b/metrics/spi/src/main/java/org/microbule/metrics/spi/TimingStrategy.java deleted file mode 100644 index 35a5c9f..0000000 --- a/metrics/spi/src/main/java/org/microbule/metrics/spi/TimingStrategy.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.microbule.metrics.spi; - -import com.codahale.metrics.Timer; -import org.microbule.config.api.Config; - -public interface TimingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - Timer createTimer(Config config); - - String name(); -} diff --git a/osgi/blueprint/pom.xml b/osgi/blueprint/pom.xml deleted file mode 100644 index 5c33467..0000000 --- a/osgi/blueprint/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-osgi-parent - 0.3.0-SNAPSHOT - - - microbule-osgi-blueprint - Microbule :: OSGi :: Blueprint - bundle - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - com.savoirtech.eos - eos-core - ${eos.version} - - - org.microbule - microbule-osgi-container - 0.3.0-SNAPSHOT - - - org.apache.aries.blueprint - org.apache.aries.blueprint.core - ${aries.blueprint.version} - - - org.microbule - microbule-test-osgi - 0.3.0-SNAPSHOT - test - - - diff --git a/osgi/blueprint/src/main/java/org/microbule/osgi/blueprint/MicrobuleNamespaceHandler.java b/osgi/blueprint/src/main/java/org/microbule/osgi/blueprint/MicrobuleNamespaceHandler.java deleted file mode 100644 index 2f3412f..0000000 --- a/osgi/blueprint/src/main/java/org/microbule/osgi/blueprint/MicrobuleNamespaceHandler.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.osgi.blueprint; - -import java.net.URL; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; - -import org.apache.aries.blueprint.NamespaceHandler; -import org.apache.aries.blueprint.ParserContext; -import org.apache.aries.blueprint.mutable.MutableBeanMetadata; -import org.apache.aries.blueprint.mutable.MutableRefMetadata; -import org.apache.aries.blueprint.mutable.MutableReferenceMetadata; -import org.apache.aries.blueprint.mutable.MutableServiceMetadata; -import org.apache.aries.blueprint.mutable.MutableValueMetadata; -import org.apache.commons.lang3.StringUtils; -import org.microbule.api.JaxrsProxyFactory; -import org.microbule.osgi.container.OsgiContainer; -import org.osgi.framework.BundleContext; -import org.osgi.service.blueprint.reflect.ComponentMetadata; -import org.osgi.service.blueprint.reflect.Metadata; -import org.osgi.service.blueprint.reflect.RefMetadata; -import org.osgi.service.blueprint.reflect.ValueMetadata; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -public class MicrobuleNamespaceHandler implements NamespaceHandler { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String CONTAINER_ELEMENT = "container"; - private static final String QUIET_PERIOD_IN_MS_ATTR = "quietPeriodInMs"; - public static final String JAXRS_PROXY_FACTORY_ID = "_jaxrsProxyFactory"; - private static final String SERVICE_INTERFACE_ATTR = "serviceInterface"; - private static final String REF_ATTR = "ref"; - public static final String NAMESPACE_URI = "http://www.microbule.org/blueprint"; - private static final String CREATE_PROXY_METHOD = "createProxy"; - private static final Logger LOGGER = LoggerFactory.getLogger(MicrobuleNamespaceHandler.class); - private static final String SCHEMA_LOCATION = "schemas/blueprint/microbule.xsd"; - private static final String ID_ATTR = "id"; - public static final String BUNDLE_CONTEXT_ID = "blueprintBundleContext"; - - private final long defaultQuietPeriodInMs; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MicrobuleNamespaceHandler(long defaultQuietPeriodInMs) { - this.defaultQuietPeriodInMs = defaultQuietPeriodInMs; - } - -//---------------------------------------------------------------------------------------------------------------------- -// NamespaceHandler Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public ComponentMetadata decorate(Node node, ComponentMetadata componentMetadata, ParserContext parserContext) { - return componentMetadata; - } - - @Override - public Set getManagedClasses() { - return null; - } - - @Override - public URL getSchemaLocation(String namespaceUri) { - if (NAMESPACE_URI.equals(namespaceUri)) { - return getClass().getClassLoader().getResource(SCHEMA_LOCATION); - } - return null; - } - - @Override - public Metadata parse(Element element, ParserContext parserContext) { - if (CONTAINER_ELEMENT.equals(element.getLocalName())) { - return parseContainerElement(element, parserContext); - } else if ("server".equals(element.getLocalName())) { - return parseServerElement(element, parserContext); - } else if ("proxy".equals(element.getLocalName())) { - return parseProxyElement(element, parserContext); - } - return null; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private void createJaxrsProxyFactoryReference(ParserContext parserContext) { - MutableReferenceMetadata jaxrsProxyFactory = serviceRef(parserContext, JAXRS_PROXY_FACTORY_ID, JaxrsProxyFactory.class); - parserContext.getComponentDefinitionRegistry().registerComponentDefinition(jaxrsProxyFactory); - } - - private MutableReferenceMetadata serviceRef(ParserContext parserContext, String id, Class serviceInterface) { - MutableReferenceMetadata ref = parserContext.createMetadata(MutableReferenceMetadata.class); - ref.setId(id); - ref.setRuntimeInterface(serviceInterface); - return ref; - } - - private Metadata parseContainerElement(Element element, ParserContext parserContext) { - final MutableBeanMetadata bean = parserContext.createMetadata(MutableBeanMetadata.class); - final String quietPeriodInMs = Optional.ofNullable(StringUtils.trimToNull(element.getAttribute(QUIET_PERIOD_IN_MS_ATTR))).orElse(String.valueOf(defaultQuietPeriodInMs)); - - bean.setClassName(OsgiContainer.class.getName()); - bean.setRuntimeClass(OsgiContainer.class); - bean.setId(element.getAttribute(ID_ATTR)); - bean.addDependsOn(BUNDLE_CONTEXT_ID); - bean.addArgument(bundleContextRef(parserContext), BundleContext.class.getName(), 0); - bean.addArgument(value(parserContext, quietPeriodInMs, Long.TYPE), Long.TYPE.getName(), 1); - return bean; - } - - private RefMetadata bundleContextRef(ParserContext parserContext) { - return ref(parserContext, BUNDLE_CONTEXT_ID); - } - - private static RefMetadata ref(ParserContext context, String value) { - MutableRefMetadata r = context.createMetadata(MutableRefMetadata.class); - r.setComponentId(value); - return r; - } - - private ValueMetadata value(ParserContext context, String value, Class type) { - final MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class); - metadata.setType(type.getName()); - metadata.setStringValue(value); - return metadata; - } - - protected Metadata parseProxyElement(Element element, ParserContext parserContext) { - whenNotExists(parserContext, JAXRS_PROXY_FACTORY_ID, this::createJaxrsProxyFactoryReference); - - MutableBeanMetadata bean = parserContext.createMetadata(MutableBeanMetadata.class); - bean.setId(element.getAttribute(ID_ATTR)); - bean.addDependsOn(JAXRS_PROXY_FACTORY_ID); - bean.setRuntimeClass(JaxrsProxyFactory.class); - bean.setFactoryComponent(ref(parserContext, JAXRS_PROXY_FACTORY_ID)); - bean.setFactoryMethod(CREATE_PROXY_METHOD); - bean.addArgument(value(parserContext, serviceInterfaceOf(element), Class.class), Class.class.getName(), 0); - LOGGER.debug("Created proxy bean: {}", bean); - return bean; - } - - protected String serviceInterfaceOf(Element element) { - return element.getAttribute(SERVICE_INTERFACE_ATTR); - } - - private void whenNotExists(ParserContext parserContext, String componentId, Consumer fn) { - if (!parserContext.getComponentDefinitionRegistry().containsComponentDefinition(componentId)) { - fn.accept(parserContext); - } - } - - protected Metadata parseServerElement(Element element, ParserContext parserContext) { - final MutableServiceMetadata metadata = parserContext.createMetadata(MutableServiceMetadata.class); - metadata.setId(parserContext.generateId()); - metadata.setServiceComponent(ref(parserContext, element.getAttribute(REF_ATTR))); - metadata.addInterface(serviceInterfaceOf(element)); - metadata.addServiceProperty(value(parserContext, "microbule.server", String.class), value(parserContext, "true", String.class)); - LOGGER.debug("Created server service:{}", metadata); - return metadata; - } -} diff --git a/osgi/blueprint/src/main/resources/OSGI-INF/blueprint/microbule-osgi-blueprint.xml b/osgi/blueprint/src/main/resources/OSGI-INF/blueprint/microbule-osgi-blueprint.xml deleted file mode 100644 index 0bdfc37..0000000 --- a/osgi/blueprint/src/main/resources/OSGI-INF/blueprint/microbule-osgi-blueprint.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/osgi/blueprint/src/main/resources/schemas/blueprint/microbule.xsd b/osgi/blueprint/src/main/resources/schemas/blueprint/microbule.xsd deleted file mode 100644 index b869515..0000000 --- a/osgi/blueprint/src/main/resources/schemas/blueprint/microbule.xsd +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/osgi/blueprint/src/test/java/org/microbule/osgi/blueprint/MicrobuleNamespaceHandlerTest.java b/osgi/blueprint/src/test/java/org/microbule/osgi/blueprint/MicrobuleNamespaceHandlerTest.java deleted file mode 100644 index 5993560..0000000 --- a/osgi/blueprint/src/test/java/org/microbule/osgi/blueprint/MicrobuleNamespaceHandlerTest.java +++ /dev/null @@ -1,216 +0,0 @@ -package org.microbule.osgi.blueprint; - -import java.io.IOException; -import java.util.Collections; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import com.google.common.collect.Lists; -import org.apache.aries.blueprint.ComponentDefinitionRegistry; -import org.apache.aries.blueprint.ParserContext; -import org.apache.aries.blueprint.mutable.MutableBeanMetadata; -import org.apache.aries.blueprint.mutable.MutableRefMetadata; -import org.apache.aries.blueprint.mutable.MutableReferenceMetadata; -import org.apache.aries.blueprint.mutable.MutableServiceMetadata; -import org.apache.aries.blueprint.mutable.MutableValueMetadata; -import org.apache.aries.blueprint.reflect.BeanMetadataImpl; -import org.apache.aries.blueprint.reflect.RefMetadataImpl; -import org.apache.aries.blueprint.reflect.ReferenceMetadataImpl; -import org.apache.aries.blueprint.reflect.ServiceMetadataImpl; -import org.apache.aries.blueprint.reflect.ValueMetadataImpl; -import org.junit.Before; -import org.junit.Test; -import org.microbule.osgi.container.OsgiContainer; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.osgi.framework.BundleContext; -import org.osgi.service.blueprint.reflect.BeanArgument; -import org.osgi.service.blueprint.reflect.BeanMetadata; -import org.osgi.service.blueprint.reflect.ComponentMetadata; -import org.osgi.service.blueprint.reflect.MapEntry; -import org.osgi.service.blueprint.reflect.Metadata; -import org.osgi.service.blueprint.reflect.RefMetadata; -import org.osgi.service.blueprint.reflect.ReferenceMetadata; -import org.osgi.service.blueprint.reflect.ServiceMetadata; -import org.osgi.service.blueprint.reflect.Target; -import org.osgi.service.blueprint.reflect.ValueMetadata; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import static org.microbule.osgi.blueprint.MicrobuleNamespaceHandler.NAMESPACE_URI; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -public class MicrobuleNamespaceHandlerTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final int QUIET_PERIOD_IN_MS = 3000; - @Mock - private ParserContext parserContext; - - @Mock - private ComponentDefinitionRegistry componentDefinitionRegistry; - - @Captor - private ArgumentCaptor jaxrsProxyFactoryCaptor; - - @Mock - private ComponentMetadata metadata; - private MicrobuleNamespaceHandler handler; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initHandler() { - handler = new MicrobuleNamespaceHandler(QUIET_PERIOD_IN_MS); - } - - protected Element parseRootElement() throws SAXException, IOException, ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - Document doc = factory.newDocumentBuilder().parse(getClass().getResourceAsStream("/blueprint/example-blueprint.xml")); - return doc.getDocumentElement(); - } - - @Test - public void testDecorate() { - assertEquals(metadata, handler.decorate(null, metadata, parserContext)); - } - - @Test - public void testGetManagedClasses() { - assertNull(handler.getManagedClasses()); - } - - @Test - public void testGetSchemaLocation() { - assertEquals(getClass().getClassLoader().getResource("schemas/blueprint/microbule.xsd"), handler.getSchemaLocation(MicrobuleNamespaceHandler.NAMESPACE_URI)); - assertNull(handler.getSchemaLocation("foo")); - } - - @Test - public void testParseContainer() throws Exception { - Element root = parseRootElement(); - NodeList nodes = root.getElementsByTagNameNS(NAMESPACE_URI, "container"); - Element element = (Element) nodes.item(0); - - Metadata parsed = handler.parse(element, parserContext); - assertTrue(parsed instanceof BeanMetadata); - BeanMetadata beanMetadata = (BeanMetadata) parsed; - - assertEquals(OsgiContainer.class.getName(), beanMetadata.getClassName()); - assertEquals(2, beanMetadata.getArguments().size()); - final BeanArgument argument1 = beanMetadata.getArguments().get(0); - assertTrue(argument1.getValue() instanceof RefMetadata); - RefMetadata bundleContextRef = (RefMetadata) argument1.getValue(); - assertEquals("blueprintBundleContext", bundleContextRef.getComponentId()); - assertEquals(BundleContext.class.getName(), argument1.getValueType()); - - final BeanArgument argument2 = beanMetadata.getArguments().get(1); - assertTrue(argument2.getValue() instanceof ValueMetadata); - ValueMetadata quietPeriodInMs = (ValueMetadata) argument2.getValue(); - assertEquals("1000", quietPeriodInMs.getStringValue()); - assertEquals(Long.TYPE.getName(), quietPeriodInMs.getType()); - assertEquals(Long.TYPE.getName(), argument2.getValueType()); - } - - @Test - public void testParseProxy() throws Exception { - Element root = parseRootElement(); - NodeList nodes = root.getElementsByTagNameNS(NAMESPACE_URI, "proxy"); - Element element = (Element) nodes.item(0); - - Metadata parsed = handler.parse(element, parserContext); - - assertTrue(parsed instanceof BeanMetadata); - BeanMetadata beanMetadata = (BeanMetadata) parsed; - assertEquals("createProxy", beanMetadata.getFactoryMethod()); - assertTrue(beanMetadata.getFactoryComponent() instanceof RefMetadata); - - RefMetadata omnibusFactoryRef = (RefMetadata) beanMetadata.getFactoryComponent(); - assertEquals(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID, omnibusFactoryRef.getComponentId()); - assertEquals(Collections.singletonList(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID), beanMetadata.getDependsOn()); - verify(parserContext, atLeastOnce()).getComponentDefinitionRegistry(); - verify(componentDefinitionRegistry).containsComponentDefinition(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID); - verify(componentDefinitionRegistry).registerComponentDefinition(jaxrsProxyFactoryCaptor.capture()); - } - - @Test - public void testParseProxyWhenJaxrsProxyAlreadyDefined() throws Exception { - Element root = parseRootElement(); - NodeList nodes = root.getElementsByTagNameNS(NAMESPACE_URI, "proxy"); - Element element = (Element) nodes.item(0); - when(componentDefinitionRegistry.containsComponentDefinition(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID)).thenReturn(true); - Metadata parsed = handler.parse(element, parserContext); - - assertTrue(parsed instanceof BeanMetadata); - BeanMetadata beanMetadata = (BeanMetadata) parsed; - assertEquals("createProxy", beanMetadata.getFactoryMethod()); - assertTrue(beanMetadata.getFactoryComponent() instanceof RefMetadata); - - RefMetadata omnibusFactoryRef = (RefMetadata) beanMetadata.getFactoryComponent(); - assertEquals(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID, omnibusFactoryRef.getComponentId()); - assertEquals(Collections.singletonList(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID), beanMetadata.getDependsOn()); - verify(parserContext, atLeastOnce()).getComponentDefinitionRegistry(); - verify(componentDefinitionRegistry).containsComponentDefinition(MicrobuleNamespaceHandler.JAXRS_PROXY_FACTORY_ID); - verifyNoMoreInteractions(componentDefinitionRegistry); - } - - @Test - public void testParseServer() throws Exception { - Element root = parseRootElement(); - NodeList nodes = root.getElementsByTagNameNS(NAMESPACE_URI, "server"); - Element element = (Element) nodes.item(0); - - Metadata parsed = handler.parse(element, parserContext); - - assertTrue(parsed instanceof ServiceMetadata); - ServiceMetadata serviceMetadata = (ServiceMetadata) parsed; - assertEquals(1, serviceMetadata.getServiceProperties().size()); - - final MapEntry entry = serviceMetadata.getServiceProperties().get(0); - final ValueMetadata key = (ValueMetadata) entry.getKey(); - assertEquals("microbule.server", key.getStringValue()); - assertEquals(String.class.getName(), key.getType()); - - final ValueMetadata value = (ValueMetadata) entry.getValue(); - assertEquals("true", value.getStringValue()); - assertEquals(String.class.getName(), value.getType()); - - assertEquals(Lists.newArrayList(HelloService.class.getName()), serviceMetadata.getInterfaces()); - final Target target = serviceMetadata.getServiceComponent(); - assertTrue(target instanceof RefMetadata); - RefMetadata targetRef = (RefMetadata) target; - assertEquals("helloService", targetRef.getComponentId()); - } - - @Test - public void testParseUnknown() throws Exception { - Element root = parseRootElement(); - NodeList nodes = root.getElementsByTagNameNS("http://www.osgi.org/xmlns/blueprint/v1.0.0", "bean"); - Element element = (Element) nodes.item(0); - assertNull(handler.parse(element, parserContext)); - } - - @Before - public void trainParserContext() { - when(parserContext.getComponentDefinitionRegistry()).thenReturn(componentDefinitionRegistry); - when(parserContext.createMetadata(MutableReferenceMetadata.class)).thenAnswer(invocation -> new ReferenceMetadataImpl()); - when(parserContext.createMetadata(MutableBeanMetadata.class)).thenAnswer(invocation -> new BeanMetadataImpl()); - when(parserContext.createMetadata(MutableRefMetadata.class)).thenAnswer(invocation -> new RefMetadataImpl()); - when(parserContext.createMetadata(MutableValueMetadata.class)).thenAnswer(invocation -> new ValueMetadataImpl()); - when(parserContext.createMetadata(MutableServiceMetadata.class)).thenAnswer(invocation -> new ServiceMetadataImpl()); - } -} \ No newline at end of file diff --git a/osgi/blueprint/src/test/resources/blueprint/example-blueprint.xml b/osgi/blueprint/src/test/resources/blueprint/example-blueprint.xml deleted file mode 100644 index 5fea89f..0000000 --- a/osgi/blueprint/src/test/resources/blueprint/example-blueprint.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/osgi/config/pom.xml b/osgi/config/pom.xml deleted file mode 100644 index c78574b..0000000 --- a/osgi/config/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-osgi-parent - 0.3.0-SNAPSHOT - - - microbule-osgi-config - Microbule :: OSGi :: Config - bundle - - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-osgi - 0.3.0-SNAPSHOT - test - - - diff --git a/osgi/config/src/main/java/org/microbule/osgi/config/OsgiConfigProvider.java b/osgi/config/src/main/java/org/microbule/osgi/config/OsgiConfigProvider.java deleted file mode 100644 index 0eeb406..0000000 --- a/osgi/config/src/main/java/org/microbule/osgi/config/OsgiConfigProvider.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.osgi.config; - -import java.util.Collections; -import java.util.Dictionary; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; - -import com.google.common.collect.Maps; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.config.core.EmptyConfig; -import org.microbule.config.core.MapConfig; -import org.microbule.config.spi.ConfigProvider; -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; - -public class OsgiConfigProvider implements ConfigProvider, ManagedService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference configRef = new AtomicReference<>(EmptyConfig.INSTANCE); - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config getConfig(String... path) { - return configRef.get().filtered(path); - } - - @Override - public String name() { - return "osgi"; - } - - @Override - public int priority() { - return ConfigUtils.DEFAULT_PRIORITY; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ManagedService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void updated(Dictionary properties) throws ConfigurationException { - if (properties != null) { - Map values = Maps.toMap(Collections.list(properties.keys()), key -> Optional.ofNullable(properties.get(key)).map(String::valueOf).orElse(null)); - configRef.set(new MapConfig(values)); - } else { - configRef.set(EmptyConfig.INSTANCE); - } - } -} diff --git a/osgi/config/src/main/resources/OSGI-INF/blueprint/microbule-osgi-config.xml b/osgi/config/src/main/resources/OSGI-INF/blueprint/microbule-osgi-config.xml deleted file mode 100644 index 7c7120d..0000000 --- a/osgi/config/src/main/resources/OSGI-INF/blueprint/microbule-osgi-config.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/osgi/config/src/test/java/org/microbule/osgi/config/OsgiConfigProviderTest.java b/osgi/config/src/test/java/org/microbule/osgi/config/OsgiConfigProviderTest.java deleted file mode 100644 index 1750985..0000000 --- a/osgi/config/src/test/java/org/microbule/osgi/config/OsgiConfigProviderTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.osgi.config; - -import java.util.Hashtable; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.test.core.MockObjectTestCase; - -public class OsgiConfigProviderTest extends MockObjectTestCase { - - @Test - public void testGetConfig() throws Exception { - final OsgiConfigProvider provider = new OsgiConfigProvider(); - assertEquals("osgi", provider.name()); - assertEquals(ConfigUtils.DEFAULT_PRIORITY, provider.priority()); - - Config config = provider.getConfig("foo", "bar"); - - assertFalse(config.value("baz").isPresent()); - - Hashtable props = new Hashtable<>(); - props.put("foo.bar.baz", "hello"); - provider.updated(props); - - config = provider.getConfig("foo", "bar"); - assertEquals("hello", config.value("baz").get()); - - provider.updated(null); - - config = provider.getConfig("foo", "bar"); - assertFalse(config.value("baz").isPresent()); - } -} \ No newline at end of file diff --git a/osgi/container/pom.xml b/osgi/container/pom.xml deleted file mode 100644 index 8bfaadd..0000000 --- a/osgi/container/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-osgi-parent - 0.3.0-SNAPSHOT - - - microbule-osgi-container - Microbule :: OSGi :: Container - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - com.savoirtech.eos - eos-core - ${eos.version} - - - org.microbule - microbule-test-osgi - 0.3.0-SNAPSHOT - test - - - diff --git a/osgi/container/src/main/java/org/microbule/osgi/container/OsgiContainer.java b/osgi/container/src/main/java/org/microbule/osgi/container/OsgiContainer.java deleted file mode 100644 index 72a55c3..0000000 --- a/osgi/container/src/main/java/org/microbule/osgi/container/OsgiContainer.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.osgi.container; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import javax.ws.rs.Path; - -import org.microbule.container.api.PluginListener; -import org.microbule.container.api.ServerListener; -import org.microbule.container.core.AbstractContainer; -import org.microbule.container.core.DefaultServerDefinition; -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceEvent; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class OsgiContainer extends AbstractContainer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String MICROBULE_SERVER_FILTER = "(microbule.server=*)"; - - private static final Logger LOGGER = LoggerFactory.getLogger(OsgiContainer.class); - - private final BundleContext bundleContext; - - private final List serverListeners = new CopyOnWriteArrayList<>(); - private final AtomicLong lastUpdated; - private final ScheduledExecutorService scheduler; - private final long quietPeriod; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public OsgiContainer(BundleContext bundleContext, long quietPeriodInMs) { - this.bundleContext = bundleContext; - this.quietPeriod = TimeUnit.MILLISECONDS.toNanos(quietPeriodInMs); - this.scheduler = Executors.newSingleThreadScheduledExecutor(); - this.lastUpdated = new AtomicLong(System.nanoTime()); - scheduler.schedule(this::checkLastUpdate, quietPeriodInMs, TimeUnit.NANOSECONDS); - } - -//---------------------------------------------------------------------------------------------------------------------- -// MicrobuleContainer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void addPluginListener(Class beanType, PluginListener listener) { - new PluginListenerWhiteboard<>(bundleContext, beanType, listener, lastUpdated).start(); - } - - @Override - public void addServerListener(ServerListener listener) { - serverListeners.add(listener); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private void checkLastUpdate() { - final long elapsed = System.nanoTime() - lastUpdated.get(); - if (elapsed >= quietPeriod) { - LOGGER.info("Quiet period ({} ms) expired, searching for servers.", TimeUnit.NANOSECONDS.toMillis(quietPeriod)); - registerServiceListener(); - findExistingServices(); - scheduler.shutdownNow(); - } else { - final long newDelay = quietPeriod - elapsed; - LOGGER.debug("Only {} ms have elapsed since last update time, checking again in {} ms...", TimeUnit.NANOSECONDS.toMillis(elapsed), TimeUnit.NANOSECONDS.toMillis(newDelay)); - scheduler.schedule(this::checkLastUpdate, newDelay, TimeUnit.NANOSECONDS); - } - } - - private void registerServiceListener() { - try { - bundleContext.addServiceListener(event -> { - if (event.getType() == ServiceEvent.REGISTERED) { - registerService(event.getServiceReference()); - } else if (event.getType() == ServiceEvent.UNREGISTERING) { - final Long serviceId = serviceId(event.getServiceReference()); - serverListeners.forEach(listener -> listener.unregisterServer(serviceId.toString())); - bundleContext.ungetService(event.getServiceReference()); - } - }, MICROBULE_SERVER_FILTER); - } catch (InvalidSyntaxException e) { - LOGGER.error("Unable to add service listener JAX-RS services using filter \"{}\".", MICROBULE_SERVER_FILTER, e); - } - } - - private void registerService(ServiceReference ref) { - final String[] serviceInterfaceNames = (String[]) ref.getProperty(Constants.OBJECTCLASS); - Arrays.stream(serviceInterfaceNames).forEach(serviceInterfaceName -> { - try { - final Class serviceInterface = ref.getBundle().loadClass(serviceInterfaceName); - if (serviceInterface.isAnnotationPresent(Path.class)) { - final Long serviceId = serviceId(ref); - final Object serviceImplementation = bundleContext.getService(ref); - final DefaultServerDefinition definition = new DefaultServerDefinition(serviceId.toString(), serviceInterface, serviceImplementation); - serverListeners.forEach(listener -> listener.registerServer(definition)); - } - } catch (ClassNotFoundException e) { - LOGGER.error("Unable to load service interface from target bundle!", e); - } - }); - } - - private Long serviceId(ServiceReference ref) { - return (Long) ref.getProperty(Constants.SERVICE_ID); - } - - private void findExistingServices() { - try { - final ServiceReference[] serviceReferences = bundleContext.getAllServiceReferences(null, MICROBULE_SERVER_FILTER); - if (serviceReferences != null) { - Arrays.stream(serviceReferences).forEach(this::registerService); - } - } catch (InvalidSyntaxException e) { - LOGGER.error("Unable to search for JAX-RS services using filter \"{}\".", MICROBULE_SERVER_FILTER, e); - } - } -} diff --git a/osgi/container/src/main/java/org/microbule/osgi/container/PluginListenerWhiteboard.java b/osgi/container/src/main/java/org/microbule/osgi/container/PluginListenerWhiteboard.java deleted file mode 100644 index ff1b7d4..0000000 --- a/osgi/container/src/main/java/org/microbule/osgi/container/PluginListenerWhiteboard.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.osgi.container; - -import java.util.concurrent.atomic.AtomicLong; - -import com.savoirtech.eos.pattern.whiteboard.AbstractWhiteboard; -import com.savoirtech.eos.util.ServiceProperties; -import org.microbule.container.api.PluginListener; -import org.osgi.framework.BundleContext; - -public class PluginListenerWhiteboard

extends AbstractWhiteboard { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final PluginListener

pluginListener; - private final AtomicLong lastUpdated; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public PluginListenerWhiteboard(BundleContext bundleContext, Class

pluginType, PluginListener

pluginListener, AtomicLong lastUpdated) { - super(bundleContext, pluginType); - this.pluginListener = pluginListener; - this.lastUpdated = lastUpdated; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected P addService(P service, ServiceProperties props) { - if (pluginListener.registerPlugin(service)) { - lastUpdated.set(System.nanoTime()); - return service; - } - return null; - } - - @Override - protected void removeService(P service, P tracked) { - pluginListener.unregisterPlugin(service); - } -} diff --git a/osgi/container/src/test/java/org/microbule/osgi/container/OsgiContainerTest.java b/osgi/container/src/test/java/org/microbule/osgi/container/OsgiContainerTest.java deleted file mode 100644 index 02b29e8..0000000 --- a/osgi/container/src/test/java/org/microbule/osgi/container/OsgiContainerTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.osgi.container; - -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import org.junit.Rule; -import org.junit.Test; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.api.ServerListener; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; -import org.microbule.test.osgi.OsgiRule; -import org.osgi.framework.ServiceRegistration; - -import static org.microbule.test.osgi.ServicePropsBuilder.props; - -public class OsgiContainerTest extends MockObjectTestCase { - - @Rule - public final OsgiRule osgiRule = new OsgiRule(); - - @Test - public void testPlugins() throws Exception { - osgiRule.registerService(HelloService.class, new HelloServiceImpl(), props().with("microbule.server", "true")); - - final OsgiContainer container = new OsgiContainer(osgiRule.getBundleContext(), 100); - final List serverDefinitions = new LinkedList<>(); - container.addServerListener(new ServerListener() { - @Override - public void registerServer(ServerDefinition serverDefinition) { - serverDefinitions.add(serverDefinition); - } - - @Override - public void unregisterServer(String id) { - serverDefinitions.removeIf(def -> def.id().equals(id)); - } - }); - final List plugins = container.pluginList(HelloService.class); - await(150); - final ServiceRegistration registration = osgiRule.registerService(HelloService.class, new HelloServiceImpl(), props().with("microbule.server", "true")); - - assertEquals(2, plugins.size()); - assertEquals(2, serverDefinitions.size()); - - registration.unregister(); - - assertEquals(1, plugins.size()); - assertEquals(1, serverDefinitions.size()); - } - - - @Test - public void testPluginsWhenRejected() throws Exception { - final HelloServiceImpl service1 = new HelloServiceImpl(); - final ServiceRegistration registration1 = osgiRule.registerService(HelloService.class, service1, props().with("microbule.server", "true")); - - final OsgiContainer container = new OsgiContainer(osgiRule.getBundleContext(), 100); - final HelloServiceImpl defaultVal = new HelloServiceImpl(); - final AtomicReference ref = container.pluginReference(HelloService.class, defaultVal); - assertEquals(service1, ref.get()); - final HelloServiceImpl service2 = new HelloServiceImpl(); - final ServiceRegistration registration2 = osgiRule.registerService(HelloService.class, service2, props().with("microbule.server", "true")); - assertEquals(service1, ref.get()); - registration2.unregister(); - assertEquals(service1, ref.get()); - registration1.unregister(); - assertEquals(defaultVal, ref.get()); - } - -} \ No newline at end of file diff --git a/osgi/pom.xml b/osgi/pom.xml deleted file mode 100644 index 46735a0..0000000 --- a/osgi/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-osgi-parent - Microbule :: OSGi :: Parent - pom - - - blueprint - config - container - - - - org.osgi - org.osgi.core - ${osgi.version} - provided - - - org.osgi - org.osgi.compendium - ${osgi.version} - provided - - - org.microbule - microbule-test-osgi - 0.3.0-SNAPSHOT - test - - - diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 42e1918..0000000 --- a/pom.xml +++ /dev/null @@ -1,352 +0,0 @@ - - - - - - - 4.0.0 - - - org.sonatype.oss - oss-parent - 7 - - - org.microbule - microbule-parent - Microbule :: Parent - pom - 0.3.0-SNAPSHOT - - - all - api - spi - core - osgi - test - errormap - gzip - logging - swagger - cors - cache - validation - requestlog - timeout - circuitbreaker - tracer - gson - example - features - itest - config - spring - cdi - container - util - cglib - annotation - scheduler - metrics - version - - - - UTF-8 - UTF-8 - 1.8 - 1.8 - - 1.4.3 - 3.0.0 - 1.2 - 3.2.5_1 - 1.3.1 - 3.5 - 3.1.11 - - 3.2.2 - 1.1.0 - 2.2.6 - 2.7 - 21.0 - 5.2.4.Final - 2.2.5 - 3.3.0.Final - 4.12 - 4.1.1 - 2.7.22 - 5.0.0 - 0.11.0 - 4.9.2 - 1.7.25 - 4.3.8.RELEASE - 1.5.3.RELEASE - 1.5.12 - 1.1.0.Final - 1.7.3 - - - 1.9.1 - 3.3.0 - 2.8.2 - 2.18.1 - 0.7.7.201606060606 - 2.6 - 2.7 - 3.2 - 2.4 - 2.18.1 - 2.6 - - - {local-packages};-split-package:=error - * - {local-packages} - - lib - - - - org/microbule/test/**,org/microbule/example/** - - - - - https://github.com/jwcarman/microbule - scm:git:git@github.com:jwcarman/microbule.git - scm:git:git@github.com:jwcarman/microbule.git - - - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - A business-friendly OSS license - - - - - - javax.inject - javax.inject - 1 - - - javax.annotation - javax.annotation-api - 1.2 - - - javax.ws.rs - javax.ws.rs-api - 2.0.1 - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - - - - - org.codehaus.mojo - sonar-maven-plugin - ${sonar.plugin.version} - - - - org.codehaus.mojo - build-helper-maven-plugin - ${build.helper.plugin.version} - - - - org.apache.maven.plugins - maven-resources-plugin - ${resources.plugin.version} - - - - org.apache.maven.plugins - maven-deploy-plugin - ${deploy.plugin.version} - - 3 - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.plugin.version} - - random - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${failsafe.plugin.version} - - - verify - - integration-test - verify - - - - - - - org.apache.maven.plugins - maven-source-plugin - ${source.plugin.version} - - - attach-sources - - jar - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${jar.plugin.version} - - - - true - true - - - ${maven.build.timestamp} - - - - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.plugin.version} - - true - - - - default-prepare-agent - - prepare-agent - - - - default-prepare-agent-integration - - prepare-agent-integration - - - - default-report - - report - - - - default-report-integration - - report-integration - - - - - - - maven-release-plugin - true - - clean install verify - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - true - - bundle - - - ${osgi.import} - ${osgi.export} - ${osgi.private} - ${osgi.embed} - ${osgi.embed.dir} - ${osgi.dynamic} - ${osgi.activator} - ${maven.build.timestamp} - ${project.name} - ${project.version} - ${project.organization.name} - ${project.name} - ${project.version} - ${project.groupId} - ${project.organization.name} - - - - - bundle-manifest - process-classes - - manifest - - - - - - - - - diff --git a/requestlog.md b/requestlog.md new file mode 100644 index 0000000..f536a4c --- /dev/null +++ b/requestlog.md @@ -0,0 +1,8 @@ +# Request Logging + +Microbule will automatically log (at INFO level) all request BEGIN/END events along with timings. For example: + +``` + 2016-11-21 10:57:01,568 INFO RequestLogFilter - BEGIN GET /hello/Microbule + 2016-11-21 10:57:01,583 INFO RequestLogFilter - END GET /hello/Microbule - 200 OK (0.001 sec) + ``` diff --git a/requestlog/pom.xml b/requestlog/pom.xml deleted file mode 100644 index a769771..0000000 --- a/requestlog/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-requestlog-decorator - Microbule :: Request Log :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/requestlog/src/main/java/org/microbule/requestlog/decorator/RequestLogDecorator.java b/requestlog/src/main/java/org/microbule/requestlog/decorator/RequestLogDecorator.java deleted file mode 100644 index 9e2c0bb..0000000 --- a/requestlog/src/main/java/org/microbule/requestlog/decorator/RequestLogDecorator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.requestlog.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("requestLogDecorator") -public class RequestLogDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void decorate(JaxrsServiceDescriptor server, Config config) { - server.addProvider(new RequestLogFilter()); - } - - @Override - public String name() { - return "requestlog"; - } -} diff --git a/requestlog/src/main/java/org/microbule/requestlog/decorator/RequestLogFilter.java b/requestlog/src/main/java/org/microbule/requestlog/decorator/RequestLogFilter.java deleted file mode 100644 index 401179a..0000000 --- a/requestlog/src/main/java/org/microbule/requestlog/decorator/RequestLogFilter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.requestlog.decorator; - -import java.io.IOException; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import org.apache.commons.lang3.time.DurationFormatUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static java.util.concurrent.TimeUnit.NANOSECONDS; - -@Provider -@Priority(Priorities.USER - 100) -public class RequestLogFilter implements ContainerRequestFilter, ContainerResponseFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(RequestLogFilter.class); - - private static final String BEGIN_TS_PROP = RequestLogFilter.class.getCanonicalName() + ".beginTs"; - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - requestContext.setProperty(BEGIN_TS_PROP, System.nanoTime()); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("BEGIN {} {}", requestContext.getMethod(), requestContext.getUriInfo().getAbsolutePath().getPath()); - } - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerResponseFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - final Long beginTs = (Long)requestContext.getProperty(BEGIN_TS_PROP); - if(beginTs != null && LOGGER.isInfoEnabled()) { - final long elapsedNanos = System.nanoTime() - beginTs; - final Response.StatusType statusInfo = responseContext.getStatusInfo(); - LOGGER.info("END {} {} - {} {} ({} sec)", requestContext.getMethod(), requestContext.getUriInfo().getAbsolutePath().getPath(), statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), DurationFormatUtils.formatDuration(NANOSECONDS.toMillis(elapsedNanos), "s.SSS")); - } - } -} diff --git a/requestlog/src/main/resources/META-INF/beans.xml b/requestlog/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/requestlog/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/requestlog/src/main/resources/OSGI-INF/blueprint/microbule-requestlog-decorator.xml b/requestlog/src/main/resources/OSGI-INF/blueprint/microbule-requestlog-decorator.xml deleted file mode 100644 index 4e0d4dc..0000000 --- a/requestlog/src/main/resources/OSGI-INF/blueprint/microbule-requestlog-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/requestlog/src/test/java/org/microbule/requestlog/decorator/RequestLogDecoratorTest.java b/requestlog/src/test/java/org/microbule/requestlog/decorator/RequestLogDecoratorTest.java deleted file mode 100644 index d71027f..0000000 --- a/requestlog/src/test/java/org/microbule/requestlog/decorator/RequestLogDecoratorTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.requestlog.decorator; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.server.hello.HelloTestCase; - -public class RequestLogDecoratorTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new RequestLogDecorator()); - } - - @Test - public void testSayHelloWithoutLogging() { - Logger.getLogger(RequestLogFilter.class).setLevel(Level.ERROR); - assertEquals("Hello, Microbule!", createProxy().sayHello("Microbule")); - Logger.getLogger(RequestLogFilter.class).setLevel(Level.INFO); - } -} \ No newline at end of file diff --git a/scheduler/api/pom.xml b/scheduler/api/pom.xml deleted file mode 100644 index 929e71d..0000000 --- a/scheduler/api/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-scheduler-parent - 0.3.0-SNAPSHOT - - - microbule-scheduler-api - Microbule :: Scheduler :: API - bundle - - diff --git a/scheduler/api/src/main/java/org/microbule/scheduler/api/RefreshableReference.java b/scheduler/api/src/main/java/org/microbule/scheduler/api/RefreshableReference.java deleted file mode 100644 index 9e409ab..0000000 --- a/scheduler/api/src/main/java/org/microbule/scheduler/api/RefreshableReference.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler.api; - -/** - * A RefreshableReference will be updated periodically using a background thread. - * - * @param the value type - */ -public interface RefreshableReference extends Scheduled { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Gets the current value. - * - * @return the current value - */ - T get(); -} diff --git a/scheduler/api/src/main/java/org/microbule/scheduler/api/Refresher.java b/scheduler/api/src/main/java/org/microbule/scheduler/api/Refresher.java deleted file mode 100644 index 0dd414f..0000000 --- a/scheduler/api/src/main/java/org/microbule/scheduler/api/Refresher.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler.api; - -@FunctionalInterface -public interface Refresher { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Refreshes the value. - * - * @param currentValue the current value (may be null) - * @return the new value - */ - T refresh(T currentValue); -} diff --git a/scheduler/api/src/main/java/org/microbule/scheduler/api/Scheduled.java b/scheduler/api/src/main/java/org/microbule/scheduler/api/Scheduled.java deleted file mode 100644 index f2864f6..0000000 --- a/scheduler/api/src/main/java/org/microbule/scheduler/api/Scheduled.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler.api; - -@FunctionalInterface -public interface Scheduled { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Cancels this scheduled event. - */ - void cancel(); -} diff --git a/scheduler/api/src/main/java/org/microbule/scheduler/api/SchedulerService.java b/scheduler/api/src/main/java/org/microbule/scheduler/api/SchedulerService.java deleted file mode 100644 index 85127a8..0000000 --- a/scheduler/api/src/main/java/org/microbule/scheduler/api/SchedulerService.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler.api; - -import java.util.concurrent.TimeUnit; - -public interface SchedulerService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - RefreshableReference createRefreshableReference(Refresher refresher, long delay, TimeUnit unit); - - Scheduled schedule(Runnable task, long delay, TimeUnit unit); - -} diff --git a/scheduler/core/pom.xml b/scheduler/core/pom.xml deleted file mode 100644 index c89c307..0000000 --- a/scheduler/core/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-scheduler-parent - 0.3.0-SNAPSHOT - - - microbule-scheduler-core - Microbule :: Scheduler :: Core - bundle - - - - org.microbule - microbule-scheduler-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/scheduler/core/src/main/java/org/microbule/scheduler/core/DefaultRefreshableReference.java b/scheduler/core/src/main/java/org/microbule/scheduler/core/DefaultRefreshableReference.java deleted file mode 100644 index 5c85eb0..0000000 --- a/scheduler/core/src/main/java/org/microbule/scheduler/core/DefaultRefreshableReference.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler.core; - -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.atomic.AtomicReference; - -import org.microbule.scheduler.api.RefreshableReference; - -public class DefaultRefreshableReference implements RefreshableReference { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final AtomicReference reference; - private final ScheduledFuture future; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DefaultRefreshableReference(AtomicReference reference, ScheduledFuture future) { - this.reference = reference; - this.future = future; - } - -//---------------------------------------------------------------------------------------------------------------------- -// RefreshableReference Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void cancel() { - future.cancel(true); - } - - @Override - public T get() { - return reference.get(); - } -} diff --git a/scheduler/core/src/main/java/org/microbule/scheduler/core/DefaultSchedulerService.java b/scheduler/core/src/main/java/org/microbule/scheduler/core/DefaultSchedulerService.java deleted file mode 100644 index ff16b46..0000000 --- a/scheduler/core/src/main/java/org/microbule/scheduler/core/DefaultSchedulerService.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler.core; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.PreDestroy; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.scheduler.api.RefreshableReference; -import org.microbule.scheduler.api.Refresher; -import org.microbule.scheduler.api.Scheduled; -import org.microbule.scheduler.api.SchedulerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Named("refreshService") -@Singleton -public class DefaultSchedulerService implements SchedulerService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final int DEFAULT_SCHEDULER_THREADS = 10; - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSchedulerService.class); - - private final ScheduledExecutorService scheduler; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DefaultSchedulerService() { - this(DEFAULT_SCHEDULER_THREADS); - } - - public DefaultSchedulerService(int schedulerThreads) { - final AtomicInteger count = new AtomicInteger(); - scheduler = Executors.newScheduledThreadPool(schedulerThreads, r -> new Thread(r, "Microbule Scheduler Thread " + count.incrementAndGet())); - } - -//---------------------------------------------------------------------------------------------------------------------- -// SchedulerService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public RefreshableReference createRefreshableReference(Refresher refresher, long delay, TimeUnit unit) { - final AtomicReference ref = new AtomicReference<>(refresher.refresh(null)); - LOGGER.debug("Scheduling {} every {} {}...", refresher, delay, unit); - final ScheduledFuture future = scheduler.scheduleWithFixedDelay(() -> { - try { - LOGGER.debug("Refreshing using refresher {}...", refresher); - ref.set(refresher.refresh(ref.get())); - } catch (RuntimeException e) { - LOGGER.error("Error occurred while refreshing using refresher {}.", refresher, e); - } - }, delay, delay, unit); - return new DefaultRefreshableReference<>(ref, future); - } - - @Override - public Scheduled schedule(Runnable task, long delay, TimeUnit unit) { - final ScheduledFuture future = scheduler.scheduleWithFixedDelay(task, delay, delay, unit); - return () -> future.cancel(true); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @PreDestroy - public void shutdownScheduler() { - scheduler.shutdownNow(); - } -} diff --git a/scheduler/core/src/main/resources/META-INF/beans.xml b/scheduler/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/scheduler/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/scheduler/core/src/main/resources/OSGI-INF/blueprint/microbule-refresh-core.xml b/scheduler/core/src/main/resources/OSGI-INF/blueprint/microbule-refresh-core.xml deleted file mode 100644 index 86f3b68..0000000 --- a/scheduler/core/src/main/resources/OSGI-INF/blueprint/microbule-refresh-core.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/scheduler/core/src/test/java/org/microbule/scheduler/DefaultSchedulerServiceTest.java b/scheduler/core/src/test/java/org/microbule/scheduler/DefaultSchedulerServiceTest.java deleted file mode 100644 index 98ef3ca..0000000 --- a/scheduler/core/src/test/java/org/microbule/scheduler/DefaultSchedulerServiceTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.scheduler; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.junit.Test; -import org.microbule.scheduler.api.RefreshableReference; -import org.microbule.scheduler.api.Refresher; -import org.microbule.scheduler.api.Scheduled; -import org.microbule.scheduler.core.DefaultSchedulerService; -import org.microbule.test.core.MockObjectTestCase; - -public class DefaultSchedulerServiceTest extends MockObjectTestCase { - - @Test - public void testInitialValue() { - final DefaultSchedulerService service = new DefaultSchedulerService(1); - - final RefreshableReference reference = service.createRefreshableReference(currentValue -> currentValue == null ? 0 : currentValue + 1, 1, TimeUnit.MINUTES); - reference.cancel(); - assertEquals(Long.valueOf(0), reference.get()); - - } - - @Test - public void testRefreshedValue() { - final DefaultSchedulerService service = new DefaultSchedulerService(); - final RefreshableReference reference = service.createRefreshableReference(currentValue -> currentValue == null ? 0 : currentValue + 1, 100, TimeUnit.MILLISECONDS); - await(150); - reference.cancel(); - assertEquals(Long.valueOf(1), reference.get()); - } - - @Test - public void testCancelRefresh() { - final DefaultSchedulerService service = new DefaultSchedulerService(1); - - final RefreshableReference reference = service.createRefreshableReference(currentValue -> currentValue == null ? 0 : currentValue + 1, 25, TimeUnit.MILLISECONDS); - reference.cancel(); - await(40); - assertEquals(Long.valueOf(0), reference.get()); - } - - @Test - public void testRefreshException() { - final DefaultSchedulerService service = new DefaultSchedulerService(1); - - final RefreshableReference reference = service.createRefreshableReference(new Refresher() { - private final AtomicBoolean errored = new AtomicBoolean(false); - - @Override - public Long refresh(Long currentValue) { - if (currentValue != null && currentValue == 1 && !errored.get()) { - errored.set(true); - throw new RuntimeException("Not going to update!"); - } - return currentValue == null ? 0 : currentValue + 1; - } - }, 20, TimeUnit.MILLISECONDS); - await(100); - reference.cancel(); - assertTrue(reference.get() > 1); - } - - @Test - public void testSchedule() throws Exception { - final DefaultSchedulerService service = new DefaultSchedulerService(1); - CountDownLatch latch = new CountDownLatch(1); - final Scheduled schedule = service.schedule(latch::countDown, 25, TimeUnit.MILLISECONDS); - assertTrue(latch.await(50, TimeUnit.MILLISECONDS)); - } - - @Test(expected = RejectedExecutionException.class) - public void testShutdown() throws Exception { - final DefaultSchedulerService service = new DefaultSchedulerService(1); - service.shutdownScheduler(); - CountDownLatch latch = new CountDownLatch(1); - service.schedule(latch::countDown, 25, TimeUnit.MILLISECONDS); - } - -} \ No newline at end of file diff --git a/scheduler/pom.xml b/scheduler/pom.xml deleted file mode 100644 index 7c8dbe8..0000000 --- a/scheduler/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-scheduler-parent - Microbule :: Scheduler :: Parent - pom - - - api - core - - - diff --git a/spi/pom.xml b/spi/pom.xml deleted file mode 100644 index 9d02d10..0000000 --- a/spi/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-spi - Microbule :: Service Provider Interface - bundle - - - - org.microbule - microbule-config-api - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-core - ${cxf.version} - - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/spi/src/main/java/org/microbule/spi/JaxrsAddressChooser.java b/spi/src/main/java/org/microbule/spi/JaxrsAddressChooser.java deleted file mode 100644 index eec3371..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsAddressChooser.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -@FunctionalInterface -public interface JaxrsAddressChooser extends AutoCloseable { -//---------------------------------------------------------------------------------------------------------------------- -// AutoCloseable Implementation -//---------------------------------------------------------------------------------------------------------------------- - - default void close() { - - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String chooseAddress(); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsConfigBuilder.java b/spi/src/main/java/org/microbule/spi/JaxrsConfigBuilder.java deleted file mode 100644 index 6af7a5c..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsConfigBuilder.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -import org.microbule.config.api.Config; - -public interface JaxrsConfigBuilder { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Builds the {@link Config} object - * - * @return the config object - */ - Config build(); - - /** - * Returns the service interface of the JAX-RS service. - * - * @return the service interface of the JAX-RS service - */ - Class serviceInterface(); - - /** - * Returns the service name of the JAX-RS service. - * - * @return the service name of the JAX-RS service - */ - String serviceName(); - - /** - * Adds a new path to this config builder - * - * @param path the path - * @return this config builder - */ - JaxrsConfigBuilder withPath(String... path); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsConfigBuilderStrategy.java b/spi/src/main/java/org/microbule/spi/JaxrsConfigBuilderStrategy.java deleted file mode 100644 index fcf625e..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsConfigBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -public interface JaxrsConfigBuilderStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - JaxrsConfigBuilder buildProxyConfig(JaxrsConfigBuilder builder); - - JaxrsConfigBuilder buildServerConfig(JaxrsConfigBuilder builder); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsDynamicProxyStrategy.java b/spi/src/main/java/org/microbule/spi/JaxrsDynamicProxyStrategy.java deleted file mode 100644 index b74ad49..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsDynamicProxyStrategy.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -import java.util.function.Supplier; - -@FunctionalInterface -public interface JaxrsDynamicProxyStrategy { - T createDynamicProxy(Class type, Supplier targetSupplier, String description, Object... descriptionParams); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsProxyDecorator.java b/spi/src/main/java/org/microbule/spi/JaxrsProxyDecorator.java deleted file mode 100644 index d4794a8..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsProxyDecorator.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -public interface JaxrsProxyDecorator extends JaxrsServiceDecorator { -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsServerDecorator.java b/spi/src/main/java/org/microbule/spi/JaxrsServerDecorator.java deleted file mode 100644 index 49095ee..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsServerDecorator.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -public interface JaxrsServerDecorator extends JaxrsServiceDecorator { - -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsServiceDecorator.java b/spi/src/main/java/org/microbule/spi/JaxrsServiceDecorator.java deleted file mode 100644 index 8709763..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsServiceDecorator.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -import org.microbule.config.api.Config; - -public interface JaxrsServiceDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String name(); - - void decorate(JaxrsServiceDescriptor descriptor, Config config); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsServiceDescriptor.java b/spi/src/main/java/org/microbule/spi/JaxrsServiceDescriptor.java deleted file mode 100644 index 7c03463..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsServiceDescriptor.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - - -import org.apache.cxf.feature.Feature; - -public interface JaxrsServiceDescriptor { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - JaxrsServiceDescriptor addFeature(Feature feature); - - JaxrsServiceDescriptor addProvider(Object provider); - - Class serviceInterface(); - - String serviceName(); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsServiceDiscovery.java b/spi/src/main/java/org/microbule/spi/JaxrsServiceDiscovery.java deleted file mode 100644 index 104c338..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsServiceDiscovery.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -@FunctionalInterface -public interface JaxrsServiceDiscovery { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - JaxrsAddressChooser createAddressChooser(Class serviceInterface, String serviceName); -} diff --git a/spi/src/main/java/org/microbule/spi/JaxrsServiceNamingStrategy.java b/spi/src/main/java/org/microbule/spi/JaxrsServiceNamingStrategy.java deleted file mode 100644 index 32bd8d4..0000000 --- a/spi/src/main/java/org/microbule/spi/JaxrsServiceNamingStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spi; - -public interface JaxrsServiceNamingStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - String serverAddress(Class serviceInterface); - - String serviceName(Class serviceInterface); -} diff --git a/spi/src/test/java/org/microbule/spi/JaxrsAddressChooserTest.java b/spi/src/test/java/org/microbule/spi/JaxrsAddressChooserTest.java deleted file mode 100644 index 3c6a6ca..0000000 --- a/spi/src/test/java/org/microbule/spi/JaxrsAddressChooserTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.microbule.spi; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class JaxrsAddressChooserTest extends MicrobuleTestCase { - @Test - public void testClose() { - final JaxrsAddressChooser chooser = () -> "foo"; - chooser.close(); - } - - - -} \ No newline at end of file diff --git a/spring.md b/spring.md new file mode 100644 index 0000000..0622e3e --- /dev/null +++ b/spring.md @@ -0,0 +1,52 @@ +# Spring Framework + +Microbule is designed to be automatically loaded into your Spring ApplicationContext. All of Microbule's components are assigned JSR-330 (_javax.inject_) annotations. First, you'll need to add Microbule to the classpath. + +# Dependencies + +If you are using Maven, simply add the following dependencies to your pom.xml file: + +```xml + + org.microbule + microbule-all + ${microbule.version} + + + + org.microbule + microbule-spring-container + ${microbule.version} + + + + org.microbule + microbule-spring-config + ${microbule.version} + +``` + +Let's examine these dependencies: + +- **microbule-all**: the Microbule framework with all of the standard plugins. +- **microbule-spring-container**: the Spring-based MicrobuleContainer implementation, which adapts Microbule to Spring. +- **microbule-spring-config**: the Spring-based ConfigurationProvider, which allows Microbule to be configured using Spring's PropertySource abstraction. + +Once you have these dependencies defined, you can easily load Microbule into your ApplicationContext. + +# Loading Microbule + +Since Microbule uses JSR-330, it can be automatically detected using Spring's component scan feature. For example, if you are using Spring's Java-based configuration: + +```java +@Configuration +@ComponentScan(basePackages = {"org.microbule","com.myco.myproj"}) +@PropertySource("classpath:application.properties") +public class MyApplicationConfiguration { + +} +``` + +# JAX-RS Service Discovery + +Once Microbule starts, it will automatically create a CXF server for any `@Path`-annotated bean in the current ApplicationContext. diff --git a/spring/bootstrap/pom.xml b/spring/bootstrap/pom.xml deleted file mode 100644 index b011a04..0000000 --- a/spring/bootstrap/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - 4.0.0 - - - org.microbule - microbule-spring-parent - 0.3.0-SNAPSHOT - - - microbule-spring-bootstrap - Microbule :: Spring :: Bootstrap - - - - org.microbule - microbule-all - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spring-container - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spring-config - 0.3.0-SNAPSHOT - - - - - diff --git a/spring/config/pom.xml b/spring/config/pom.xml deleted file mode 100644 index fcf3feb..0000000 --- a/spring/config/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - 4.0.0 - - - org.microbule - microbule-spring-parent - 0.3.0-SNAPSHOT - - - microbule-spring-config - Microbule :: Spring :: Config - bundle - - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.springframework - spring-test - ${spring.version} - test - - - org.microbule - microbule-spring-container - 0.3.0-SNAPSHOT - test - - - diff --git a/spring/config/src/main/java/org/microbule/spring/config/SpringEnvironmentConfig.java b/spring/config/src/main/java/org/microbule/spring/config/SpringEnvironmentConfig.java deleted file mode 100644 index 332abc9..0000000 --- a/spring/config/src/main/java/org/microbule/spring/config/SpringEnvironmentConfig.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.config; - -import java.util.Optional; - -import org.microbule.config.api.Config; -import org.microbule.config.core.AbstractConfig; -import org.springframework.core.env.Environment; - -public class SpringEnvironmentConfig extends AbstractConfig { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Environment environment; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public SpringEnvironmentConfig(Environment environment) { - this(environment, null, DEFAULT_SEPARATOR); - } - - private SpringEnvironmentConfig(Environment environment, String groupPrefix, String separator) { - super(groupPrefix, separator); - this.environment = environment; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected Config qualifiedConfig(String qualifiedGroupPrefix, String separator) { - return new SpringEnvironmentConfig(environment, qualifiedGroupPrefix, separator); - } - - @Override - protected Optional qualifiedValue(String qualifiedKey) { - return Optional.ofNullable(environment.getProperty(qualifiedKey)); - } -} diff --git a/spring/config/src/main/java/org/microbule/spring/config/SpringEnvironmentConfigProvider.java b/spring/config/src/main/java/org/microbule/spring/config/SpringEnvironmentConfigProvider.java deleted file mode 100644 index 6466f3e..0000000 --- a/spring/config/src/main/java/org/microbule/spring/config/SpringEnvironmentConfigProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.config; - -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.config.spi.ConfigProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -public class SpringEnvironmentConfigProvider implements ConfigProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String NAME = "spring"; - - @Autowired - private Environment environment; - -//---------------------------------------------------------------------------------------------------------------------- -// ConfigProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config getConfig(String... path) { - return new SpringEnvironmentConfig(environment).filtered(path); - } - - @Override - public String name() { - return NAME; - } - - @Override - public int priority() { - return ConfigUtils.DEFAULT_PRIORITY; - } -} diff --git a/spring/config/src/test/java/org/microbule/spring/config/MicrobuleConfig.java b/spring/config/src/test/java/org/microbule/spring/config/MicrobuleConfig.java deleted file mode 100644 index d130f48..0000000 --- a/spring/config/src/test/java/org/microbule/spring/config/MicrobuleConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "org.microbule") -public class MicrobuleConfig { -} diff --git a/spring/config/src/test/java/org/microbule/spring/config/SpringEnvironmentConfigProviderTest.java b/spring/config/src/test/java/org/microbule/spring/config/SpringEnvironmentConfigProviderTest.java deleted file mode 100644 index 8db9ce4..0000000 --- a/spring/config/src/test/java/org/microbule/spring/config/SpringEnvironmentConfigProviderTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.config; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.microbule.config.api.Config; -import org.microbule.config.core.ConfigUtils; -import org.microbule.test.core.MockObjectTestCase; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MicrobuleConfig.class) -@TestPropertySource("classpath:application.properties") -public class SpringEnvironmentConfigProviderTest extends MockObjectTestCase { - - @Autowired - private SpringEnvironmentConfigProvider provider; - - @Test - public void testConfig() { - assertEquals("spring", provider.name()); - assertEquals(ConfigUtils.DEFAULT_PRIORITY, provider.priority()); - - final Config config = provider.getConfig("one", "two"); - assertEquals("hello", config.value("three").get()); - assertEquals("three, sir", config.value("five").get()); - } - -} \ No newline at end of file diff --git a/spring/config/src/test/resources/application.properties b/spring/config/src/test/resources/application.properties deleted file mode 100644 index b2a0479..0000000 --- a/spring/config/src/test/resources/application.properties +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2017 The Microbule Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -one.two.three=hello -one.two.five=three, sir \ No newline at end of file diff --git a/spring/container/pom.xml b/spring/container/pom.xml deleted file mode 100644 index 548bd9b..0000000 --- a/spring/container/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - 4.0.0 - - - org.microbule - microbule-spring-parent - 0.3.0-SNAPSHOT - - - microbule-spring-container - Microbule :: Spring :: Container - bundle - - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.springframework - spring-test - ${spring.version} - test - - - org.microbule - microbule-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - test - - - diff --git a/spring/container/src/main/java/org/microbule/spring/container/SpringContainer.java b/spring/container/src/main/java/org/microbule/spring/container/SpringContainer.java deleted file mode 100644 index 1f56a05..0000000 --- a/spring/container/src/main/java/org/microbule/spring/container/SpringContainer.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.container; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.stream.Stream; - -import javax.ws.rs.Path; - -import org.microbule.api.JaxrsProxyFactory; -import org.microbule.api.JaxrsProxyReference; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.core.DefaultServerDefinition; -import org.microbule.container.core.StaticContainer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.beans.factory.config.DependencyDescriptor; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Lazy; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; - -@Component -public class SpringContainer extends StaticContainer implements BeanPostProcessor { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(SpringContainer.class); - private final List serverDefinitions = new CopyOnWriteArrayList<>(); - - - @Autowired - private ApplicationContext applicationContext; - -//---------------------------------------------------------------------------------------------------------------------- -// BeanPostProcessor Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) { - return bean; - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) { - Stream.of(bean.getClass().getInterfaces()).forEach(serviceInterface -> { - if (serviceInterface.isAnnotationPresent(Path.class)) { - LOGGER.debug("Discovered {} service implementation bean named \"{}\".", serviceInterface.getSimpleName(), beanName); - serverDefinitions.add(new DefaultServerDefinition(beanName, serviceInterface, bean)); - } - }); - return bean; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Bean - @Lazy - @SuppressWarnings("unchecked") - public JaxrsProxyReference createProxyReference(DependencyDescriptor point, @Autowired JaxrsProxyFactory factory) { - final Class serviceInterface = point.getResolvableType().getGeneric(0).getRawClass(); - final T proxy = (T) factory.createProxy(serviceInterface); - return () -> proxy; - } - - @EventListener - @Order(0) - public void onContextRefreshed(ContextRefreshedEvent event) { - initialize(); - } - - @Override - protected Iterable plugins(Class beanType) { - return applicationContext.getBeansOfType(beanType).values(); - } - - @Override - protected Iterable servers() { - return serverDefinitions; - } -} diff --git a/spring/container/src/test/java/org/microbule/spring/container/Collector.java b/spring/container/src/test/java/org/microbule/spring/container/Collector.java deleted file mode 100644 index dde73cb..0000000 --- a/spring/container/src/test/java/org/microbule/spring/container/Collector.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.container; - -import java.util.LinkedList; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.container.api.ServerDefinition; -import org.microbule.container.api.ServerListener; - -@Named("collector") -@Singleton -public class Collector { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final List plugins; - private final List serverDefinitions = new LinkedList<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public Collector(MicrobuleContainer container) { - this.plugins = container.pluginList(MyPlugin.class); - container.addServerListener(new ServerListener() { - @Override - public void registerServer(ServerDefinition serverDefinition) { - serverDefinitions.add(serverDefinition); - } - - @Override - public void unregisterServer(String id) { - serverDefinitions.removeIf(def -> id.equals(def.id())); - } - }); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public List getPlugins() { - return plugins; - } - - public List getServerDefinitions() { - return serverDefinitions; - } -} diff --git a/spring/container/src/test/java/org/microbule/spring/container/MicrobuleConfig.java b/spring/container/src/test/java/org/microbule/spring/container/MicrobuleConfig.java deleted file mode 100644 index 6a1aa96..0000000 --- a/spring/container/src/test/java/org/microbule/spring/container/MicrobuleConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.container; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "org.microbule") -public class MicrobuleConfig { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Bean - public MyPlugin plugin1(){ - return new MyPlugin() { - }; - } - - @Bean - public MyPlugin plugin2(){ - return new MyPlugin() { - }; - } -} diff --git a/spring/container/src/test/java/org/microbule/spring/container/MyPlugin.java b/spring/container/src/test/java/org/microbule/spring/container/MyPlugin.java deleted file mode 100644 index 84bebbf..0000000 --- a/spring/container/src/test/java/org/microbule/spring/container/MyPlugin.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.container; - -public interface MyPlugin { -} diff --git a/spring/container/src/test/java/org/microbule/spring/container/SpringContainerTest.java b/spring/container/src/test/java/org/microbule/spring/container/SpringContainerTest.java deleted file mode 100644 index bb95c39..0000000 --- a/spring/container/src/test/java/org/microbule/spring/container/SpringContainerTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.spring.container; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.microbule.api.JaxrsProxyReference; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MicrobuleConfig.class) -public class SpringContainerTest extends MockObjectTestCase { - - @Autowired - private Collector collector; - - @Autowired - private JaxrsProxyReference helloService; - - @Test - public void testPlugins() { - assertEquals(2, collector.getPlugins().size()); - } - - @Test - public void testServers() { - assertEquals(1, collector.getServerDefinitions().size()); - } - - @Test - public void testRef() { - assertNotNull(helloService); - } -} \ No newline at end of file diff --git a/spring/pom.xml b/spring/pom.xml deleted file mode 100644 index 592e2f4..0000000 --- a/spring/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-spring-parent - Microbule :: Spring :: Parent - pom - - - container - config - bootstrap - - - - - org.springframework - spring-context - ${spring.version} - - - diff --git a/swagger.md b/swagger.md new file mode 100644 index 0000000..f906874 --- /dev/null +++ b/swagger.md @@ -0,0 +1,3 @@ +# Swagger + +Microbule adds [Swagger](http://swagger.io/) support to your services. diff --git a/swagger/pom.xml b/swagger/pom.xml deleted file mode 100644 index 94b0c77..0000000 --- a/swagger/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-swagger-decorator - Microbule :: Swagger :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-rt-rs-service-description-swagger - ${cxf.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/swagger/src/main/java/org/microbule/swagger/decorator/SwaggerDecorator.java b/swagger/src/main/java/org/microbule/swagger/decorator/SwaggerDecorator.java deleted file mode 100644 index 5cff71a..0000000 --- a/swagger/src/main/java/org/microbule/swagger/decorator/SwaggerDecorator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.swagger.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.apache.cxf.jaxrs.swagger.Swagger2Feature; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("swaggerDecorator") -public class SwaggerDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - final Swagger2Feature feature = new Swagger2Feature(); - feature.setPrettyPrint(true); - feature.setScan(false); - descriptor.addFeature(feature); - } - - @Override - public String name() { - return "swagger"; - } -} diff --git a/swagger/src/main/resources/META-INF/beans.xml b/swagger/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/swagger/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/swagger/src/main/resources/OSGI-INF/blueprint/microbule-swagger-decorator.xml b/swagger/src/main/resources/OSGI-INF/blueprint/microbule-swagger-decorator.xml deleted file mode 100644 index a79ec59..0000000 --- a/swagger/src/main/resources/OSGI-INF/blueprint/microbule-swagger-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/swagger/src/test/java/org/microbule/swagger/decorator/SwaggerDecoratorTest.java b/swagger/src/test/java/org/microbule/swagger/decorator/SwaggerDecoratorTest.java deleted file mode 100644 index 6a8d1ea..0000000 --- a/swagger/src/test/java/org/microbule/swagger/decorator/SwaggerDecoratorTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.swagger.decorator; - -import org.apache.cxf.jaxrs.swagger.Swagger2Feature; -import org.junit.Test; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; - -import static org.mockito.Mockito.verify; - -public class SwaggerDecoratorTest extends MockObjectTestCase { - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Captor - private ArgumentCaptor captor; - - @Test - public void testDecorate() { - final SwaggerDecorator decorator = new SwaggerDecorator(); - decorator.decorate(descriptor, null); - verify(descriptor).addFeature(captor.capture()); - final Swagger2Feature feature = captor.getValue(); - assertTrue(feature.isPrettyPrint()); - } - - @Test - public void testName() { - assertEquals("swagger", new SwaggerDecorator().name()); - } - -} \ No newline at end of file diff --git a/test/cdi-server/pom.xml b/test/cdi-server/pom.xml deleted file mode 100644 index 41a513b..0000000 --- a/test/cdi-server/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-test-parent - 0.3.0-SNAPSHOT - - - microbule-test-cdi-server - Microbule :: Test :: CDI Server - - - - javax.validation - validation-api - ${validation.api.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-cdi-container - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http-hc - ${cxf.version} - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-cdi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-sysprop - 0.3.0-SNAPSHOT - - - diff --git a/test/cdi-server/src/main/java/org/microbule/test/cdi/server/CdiServerTestCase.java b/test/cdi-server/src/main/java/org/microbule/test/cdi/server/CdiServerTestCase.java deleted file mode 100644 index fdddf77..0000000 --- a/test/cdi-server/src/main/java/org/microbule/test/cdi/server/CdiServerTestCase.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.microbule.test.cdi.server; - -import javax.inject.Inject; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.microbule.api.JaxrsProxyReference; -import org.microbule.test.cdi.CdiTestCase; -import org.microbule.test.core.hello.HelloService; - -public abstract class CdiServerTestCase extends CdiTestCase { - - @Inject - private JaxrsProxyReference helloRef; - - @BeforeClass - public static void configure() { - System.setProperty("HelloService.proxy.proxyAddress", "http://localhost:8484/HelloService"); - System.setProperty("default.server.baseAddress", "http://localhost:8484"); - } - - @Test - public void testSayHello() { - assertEquals("Hello, Microbule!", helloRef.get().sayHello("Microbule")); - } -} diff --git a/test/cdi-server/src/test/java/org/microbule/test/cdi/server/CdiServerTestCaseTest.java b/test/cdi-server/src/test/java/org/microbule/test/cdi/server/CdiServerTestCaseTest.java deleted file mode 100644 index a74b26f..0000000 --- a/test/cdi-server/src/test/java/org/microbule/test/cdi/server/CdiServerTestCaseTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.microbule.test.cdi.server; - -import javax.inject.Singleton; - -@Singleton -public class CdiServerTestCaseTest extends CdiServerTestCase { - - -} diff --git a/test/cdi/pom.xml b/test/cdi/pom.xml deleted file mode 100644 index 7044914..0000000 --- a/test/cdi/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-test-parent - 0.3.0-SNAPSHOT - - - microbule-test-cdi - Microbule :: Test :: CDI - - - - javax.enterprise - cdi-api - ${cdi.version} - - - org.apache.openwebbeans - openwebbeans-impl - ${openwebbeans.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - - - org.slf4j - jul-to-slf4j - ${slf4j.version} - - - diff --git a/test/cdi/src/main/java/org/microbule/test/cdi/CdiTestCase.java b/test/cdi/src/main/java/org/microbule/test/cdi/CdiTestCase.java deleted file mode 100644 index 0224af1..0000000 --- a/test/cdi/src/main/java/org/microbule/test/cdi/CdiTestCase.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.cdi; - -import org.junit.runner.RunWith; -import org.microbule.test.core.MockObjectTestCase; - -@RunWith(CdiTestRunner.class) -public abstract class CdiTestCase extends MockObjectTestCase { -} diff --git a/test/cdi/src/main/java/org/microbule/test/cdi/CdiTestRunner.java b/test/cdi/src/main/java/org/microbule/test/cdi/CdiTestRunner.java deleted file mode 100644 index a9c90d4..0000000 --- a/test/cdi/src/main/java/org/microbule/test/cdi/CdiTestRunner.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.cdi; - -import javax.enterprise.inject.spi.CDI; - -import org.apache.webbeans.config.WebBeansContext; -import org.apache.webbeans.spi.ContainerLifecycle; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; -import org.slf4j.bridge.SLF4JBridgeHandler; - -public class CdiTestRunner extends BlockJUnit4ClassRunner { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public CdiTestRunner(Class c) throws InitializationError { - super(c); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected Object createTest() throws Exception { - SLF4JBridgeHandler.install(); - final WebBeansContext context = WebBeansContext.currentInstance(); - final ContainerLifecycle lifecycle = context.getService(ContainerLifecycle.class); - lifecycle.startApplication(null); - return CDI.current().select(getTestClass().getJavaClass()).get(); - } -} diff --git a/test/core/pom.xml b/test/core/pom.xml deleted file mode 100644 index 50565ae..0000000 --- a/test/core/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-test-parent - 0.3.0-SNAPSHOT - - - microbule-test-core - Microbule :: Test :: Core - - - - javax.validation - validation-api - ${validation.api.version} - - - junit - junit - ${junit.version} - - - org.mockito - mockito-core - ${mockito.version} - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - org.awaitility - awaitility - ${awaitility.version} - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http-hc - ${cxf.version} - - - diff --git a/test/core/src/main/java/org/microbule/test/core/MicrobuleTestCase.java b/test/core/src/main/java/org/microbule/test/core/MicrobuleTestCase.java deleted file mode 100644 index c4f3b22..0000000 --- a/test/core/src/main/java/org/microbule/test/core/MicrobuleTestCase.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.core; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.awaitility.Awaitility; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.rules.ExpectedException; - -public class MicrobuleTestCase extends Assert { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Rule - public final ExpectedException exception = ExpectedException.none(); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected void assertIsUtilsClass(Class clazz) throws ReflectiveOperationException { - assertTrue(Modifier.isFinal(clazz.getModifiers())); - assertEquals(1, clazz.getDeclaredConstructors().length); - final Constructor ctor = clazz.getDeclaredConstructor(); - assertTrue(Modifier.isPrivate(ctor.getModifiers())); - ctor.setAccessible(true); - ctor.newInstance(); - } - - protected void expectException(Class type, String msg, Object... params) { - exception.expect(type); - exception.expectMessage(String.format(msg, params)); - } - - protected void await(long duration) { - await(5, duration); - } - - private void await(long pollInterval, long duration) { - final long expiration = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(duration); - Awaitility.await().pollInterval(pollInterval, TimeUnit.MILLISECONDS).pollDelay(pollInterval, TimeUnit.MILLISECONDS).until(() -> System.nanoTime() >= expiration); - } - - protected T createWithoutLogging(Supplier supplier) { - final Logger logger = Logger.getLogger("org.microbule"); - final Level previousLevel = logger.getLevel(); - try { - logger.setLevel(Level.WARN); - return supplier.get(); - } finally { - logger.setLevel(previousLevel); - } - } -} diff --git a/test/core/src/main/java/org/microbule/test/core/MockObjectTestCase.java b/test/core/src/main/java/org/microbule/test/core/MockObjectTestCase.java deleted file mode 100644 index 0660a94..0000000 --- a/test/core/src/main/java/org/microbule/test/core/MockObjectTestCase.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.core; - -import org.junit.Before; -import org.mockito.MockitoAnnotations; - -public abstract class MockObjectTestCase extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } -} diff --git a/test/core/src/main/java/org/microbule/test/core/hello/HelloService.java b/test/core/src/main/java/org/microbule/test/core/hello/HelloService.java deleted file mode 100644 index b7a378a..0000000 --- a/test/core/src/main/java/org/microbule/test/core/hello/HelloService.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.core.hello; - -import javax.validation.constraints.Size; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -@Path("/") -public interface HelloService { - - @GET - @Path("/hello/{name}") - @Produces(MediaType.TEXT_PLAIN) - String sayHello(@PathParam("name") @Size(min = 5, message="Name must be at least 5 characters long.") String name); - - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("/version") - String version(); -} diff --git a/test/core/src/main/java/org/microbule/test/core/hello/HelloServiceImpl.java b/test/core/src/main/java/org/microbule/test/core/hello/HelloServiceImpl.java deleted file mode 100644 index f30b46a..0000000 --- a/test/core/src/main/java/org/microbule/test/core/hello/HelloServiceImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.core.hello; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("helloService") -public class HelloServiceImpl implements HelloService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(HelloServiceImpl.class); - -//---------------------------------------------------------------------------------------------------------------------- -// HelloService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public String sayHello(String name) { - LOGGER.info("Saying hello to \"{}\".", name); - return String.format("Hello, %s!", name); - } - - @Override - public String version() { - return "1.0"; - } -} - diff --git a/test/core/src/main/resources/log4j.properties b/test/core/src/main/resources/log4j.properties deleted file mode 100644 index 7d89742..0000000 --- a/test/core/src/main/resources/log4j.properties +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright (c) 2017 The Microbule Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# - -# Root logger option -log4j.rootLogger=INFO, stdout - -# Direct log messages to stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p %c{1} (%X{microbule_trace_id}) - %m%n - -log4j.logger.org.microbule=DEBUG \ No newline at end of file diff --git a/test/osgi/pom.xml b/test/osgi/pom.xml deleted file mode 100644 index b384228..0000000 --- a/test/osgi/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-test-parent - 0.3.0-SNAPSHOT - - - microbule-test-osgi - Microbule :: Test :: OSGi - - - - org.apache.felix - org.apache.felix.connect - 0.1.0 - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - - - diff --git a/test/osgi/src/main/java/org/microbule/test/osgi/OsgiRule.java b/test/osgi/src/main/java/org/microbule/test/osgi/OsgiRule.java deleted file mode 100644 index e328064..0000000 --- a/test/osgi/src/main/java/org/microbule/test/osgi/OsgiRule.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.osgi; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.felix.connect.PojoServiceRegistryFactoryImpl; -import org.apache.felix.connect.launch.BundleDescriptor; -import org.apache.felix.connect.launch.ClasspathScanner; -import org.apache.felix.connect.launch.PojoServiceRegistry; -import org.apache.felix.connect.launch.PojoServiceRegistryFactory; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -public class OsgiRule implements TestRule { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private String bundleFilter = "(Bundle-SymbolicName=org.microbule.*)"; - private PojoServiceRegistry registry; - -//---------------------------------------------------------------------------------------------------------------------- -// TestRule Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Statement apply(Statement statement, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - Map config = new HashMap<>(); - ClasspathScanner scanner = new ClasspathScanner(); - List bundles = scanner.scanForBundles(bundleFilter); - config.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, bundles); - registry = new PojoServiceRegistryFactoryImpl().newPojoServiceRegistry(config); - statement.evaluate(); - } - }; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public BundleContext getBundleContext() { - return registry.getBundleContext(); - } - - @SuppressWarnings("unchecked") - public ServiceRegistration registerService(Class serviceInterface, T serviceObject, ServicePropsBuilder builder) { - return (ServiceRegistration) registry.registerService(serviceInterface.getName(), serviceObject, builder.build()); - } - - public OsgiRule withBundleFilter(String bundleFilter) { - this.bundleFilter = bundleFilter; - return this; - } -} diff --git a/test/osgi/src/main/java/org/microbule/test/osgi/ServicePropsBuilder.java b/test/osgi/src/main/java/org/microbule/test/osgi/ServicePropsBuilder.java deleted file mode 100644 index 94ebf42..0000000 --- a/test/osgi/src/main/java/org/microbule/test/osgi/ServicePropsBuilder.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.osgi; - -import java.util.Dictionary; -import java.util.Hashtable; - -public class ServicePropsBuilder { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Dictionary props = new Hashtable<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static ServicePropsBuilder props() { - return new ServicePropsBuilder(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public Dictionary build() { - return props; - } - - public ServicePropsBuilder with(String name, Object value) { - if (value == null) { - props.remove(name); - } else { - props.put(name, value); - } - return this; - } -} diff --git a/test/pom.xml b/test/pom.xml deleted file mode 100644 index f1d4f53..0000000 --- a/test/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-test-parent - Microbule :: Test :: Parent - pom - - - core - osgi - server - cdi - spring-server - cdi-server - - - diff --git a/test/server/pom.xml b/test/server/pom.xml deleted file mode 100644 index 5548378..0000000 --- a/test/server/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-test-parent - 0.3.0-SNAPSHOT - - - microbule-test-server - Microbule :: Test :: Server - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - javax.validation - validation-api - ${validation.api.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http-hc - ${cxf.version} - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-cdi - 0.3.0-SNAPSHOT - - - diff --git a/test/server/src/main/java/org/microbule/test/server/JaxrsServerTestCase.java b/test/server/src/main/java/org/microbule/test/server/JaxrsServerTestCase.java deleted file mode 100644 index 98f50d6..0000000 --- a/test/server/src/main/java/org/microbule/test/server/JaxrsServerTestCase.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.server; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; - -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -import org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit; -import org.junit.After; -import org.junit.Before; -import org.microbule.api.JaxrsConfigService; -import org.microbule.api.JaxrsServer; -import org.microbule.config.api.Config; -import org.microbule.config.core.MapConfig; -import org.microbule.container.core.SimpleContainer; -import org.microbule.core.DefaultJaxrsProxyFactory; -import org.microbule.core.DefaultJaxrsServerFactory; -import org.microbule.core.DefaultJaxrsServiceDiscovery; -import org.microbule.scheduler.core.DefaultSchedulerService; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.util.reflect.Types; - -public abstract class JaxrsServerTestCase extends MockObjectTestCase implements JaxrsConfigService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String BASE_ADDRESS_PATTERN = "http://localhost:%d/%s"; - - private JaxrsServer server; - private String baseAddress; - private final SimpleContainer container = new SimpleContainer(); - private DefaultJaxrsProxyFactory proxyFactory; - -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract T createImplementation(); - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsConfigService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Config createConfig(String... path) { - MapConfig config = new MapConfig(); - configureGlobalConfig(config); - return config; - } - - @Override - public final Config createProxyConfig(Class serviceInterface, String serviceName) { - MapConfig config = new MapConfig(); - configureProxy(config); - config.addValue(DefaultJaxrsServiceDiscovery.PROXY_ADDRESS_PROP, baseAddress); - return config; - } - - @Override - public final Config createServerConfig(Class serviceInterface, String serviceName) { - MapConfig config = new MapConfig(); - configureServer(config); - config.addValue(DefaultJaxrsServerFactory.SERVER_ADDRESS_PROP, baseAddress); - return config; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getBaseAddress() { - return baseAddress; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected void addBeans(SimpleContainer container) { - // Do nothing! - } - - protected int calculatePort() { - try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLocalHost())) { - return socket.getLocalPort(); - } catch (IOException e) { - throw new IllegalStateException("Unable to allocate port for test case.", e); - } - } - - protected void configureGlobalConfig(MapConfig globalConfig) { - // Do nothing! - } - - protected void configureProxy(MapConfig proxyConfig) { - // Do nothing! - } - - protected void configureServer(MapConfig serverConfig) { - // Do nothing! - } - - protected String createBaseAddress() { - return String.format(BASE_ADDRESS_PATTERN, calculatePort(), getClass().getSimpleName()); - } - - protected T createProxy() { - return proxyFactory.createProxy(getServiceInterface()); - } - - private Class getServiceInterface() { - return Types.getTypeParameter(getClass(), JaxrsServerTestCase.class, 0); - } - - protected WebTarget createWebTarget() { - return ClientBuilder.newClient().target(getBaseAddress()).property(AsyncHTTPConduit.USE_ASYNC, Boolean.TRUE); - } - - @After - public void shutdownServer() { - if (server != null) { - server.shutdown(); - } - } - - @Before - public void startServer() { - addBeans(container); - final DefaultJaxrsServerFactory factory = new DefaultJaxrsServerFactory(container, this); - proxyFactory = new DefaultJaxrsProxyFactory(container, this, new DefaultSchedulerService(1)); - container.initialize(); - - baseAddress = createBaseAddress(); - server = factory.createJaxrsServer(getServiceInterface(), createImplementation()); - } -} diff --git a/test/server/src/main/java/org/microbule/test/server/hello/HelloTestCase.java b/test/server/src/main/java/org/microbule/test/server/hello/HelloTestCase.java deleted file mode 100644 index 9895b3a..0000000 --- a/test/server/src/main/java/org/microbule/test/server/hello/HelloTestCase.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.test.server.hello; - -import org.junit.Test; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; -import org.microbule.test.server.JaxrsServerTestCase; - -public abstract class HelloTestCase extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected HelloService createImplementation() { - return new HelloServiceImpl(); - } - - @Test - public void testSayHello() { - assertEquals("Hello, Microbule!", createProxy().sayHello("Microbule")); - } -} diff --git a/test/spring-server/pom.xml b/test/spring-server/pom.xml deleted file mode 100644 index 8036e0c..0000000 --- a/test/spring-server/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-test-parent - 0.3.0-SNAPSHOT - - - microbule-test-spring-server - Microbule :: Test :: Spring Server - - - - javax.validation - validation-api - ${validation.api.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-config-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spring-bootstrap - 0.3.0-SNAPSHOT - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http-hc - ${cxf.version} - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-scheduler-core - 0.3.0-SNAPSHOT - - - org.springframework - spring-test - ${spring.version} - - - diff --git a/test/spring-server/src/main/java/org/microbule/test/spring/server/MicrobuleConfiguration.java b/test/spring-server/src/main/java/org/microbule/test/spring/server/MicrobuleConfiguration.java deleted file mode 100644 index bfb23ae..0000000 --- a/test/spring-server/src/main/java/org/microbule/test/spring/server/MicrobuleConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.microbule.test.spring.server; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "org.microbule") -public class MicrobuleConfiguration { -} diff --git a/test/spring-server/src/main/java/org/microbule/test/spring/server/SpringServerTestCase.java b/test/spring-server/src/main/java/org/microbule/test/spring/server/SpringServerTestCase.java deleted file mode 100644 index b40b81f..0000000 --- a/test/spring-server/src/main/java/org/microbule/test/spring/server/SpringServerTestCase.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.microbule.test.spring.server; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.microbule.api.JaxrsProxyReference; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MicrobuleConfiguration.class) -@TestPropertySource("classpath:application.properties") -public abstract class SpringServerTestCase extends MockObjectTestCase { - - - @Autowired - private JaxrsProxyReference helloRef; - - @Test - public void testSayHello() { - assertEquals("Hello, Microbule!", helloRef.get().sayHello("Microbule")); - } -} diff --git a/test/spring-server/src/main/resources/application.properties b/test/spring-server/src/main/resources/application.properties deleted file mode 100644 index 8c0e5cd..0000000 --- a/test/spring-server/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -default.server.baseAddress=http://localhost:8484 -HelloService.proxy.proxyAddress=http://localhost:8484/HelloService \ No newline at end of file diff --git a/test/spring-server/src/test/java/org/microbule/test/spring/server/SpringServerTestCaseTest.java b/test/spring-server/src/test/java/org/microbule/test/spring/server/SpringServerTestCaseTest.java deleted file mode 100644 index 970bc5b..0000000 --- a/test/spring-server/src/test/java/org/microbule/test/spring/server/SpringServerTestCaseTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.microbule.test.spring.server; - -public class SpringServerTestCaseTest extends SpringServerTestCase { - -} diff --git a/timeout.md b/timeout.md new file mode 100644 index 0000000..e8d9c93 --- /dev/null +++ b/timeout.md @@ -0,0 +1,8 @@ +# Connection/Receive Timeouts + +Microbule will automatically set connection and receive timeouts (10 sec and 30 sec by default) on all generated client +proxies. You can customize the timeout values using configuration properties when you create the proxy. For example, +you can set the "receiveTimeout" property to a value (in milliseconds) to be used by all calls for the proxy. +Alternatively, you can customize per-method (we use the method name as the key) timeouts by setting the +"foo.connectionTimeout" value, which would override the connection timeout value for the "foo" method +only. diff --git a/timeout/pom.xml b/timeout/pom.xml deleted file mode 100644 index 9c8fda3..0000000 --- a/timeout/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-timeout-decorator - Microbule :: Timeout :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/timeout/src/main/java/org/microbule/timeout/decorator/TimeoutFilter.java b/timeout/src/main/java/org/microbule/timeout/decorator/TimeoutFilter.java deleted file mode 100644 index 3e4b16f..0000000 --- a/timeout/src/main/java/org/microbule/timeout/decorator/TimeoutFilter.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.timeout.decorator; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Stream; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.ext.Provider; - -import org.apache.cxf.jaxrs.utils.JAXRSUtils; -import org.apache.cxf.message.Exchange; -import org.apache.cxf.message.Message; -import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Provider -public class TimeoutFilter implements ClientRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String CONNECTION_TIMEOUT_PROP_PATTERN = "%s.connectionTimeout"; - private static final String RECEIVE_TIMEOUT_PROP_PATTERN = "%s.receiveTimeout"; - private static final String DEFAULT_CONNECTION_TIMEOUT_PROP = "connectionTimeout"; - private static final String DEFAULT_RECEIVE_TIMEOUT_PROP = "receiveTimeout"; - private static final String OPERATION_NAME_PROP = "org.apache.cxf.resource.operation.name"; - private static final long DEFAULT_CONNECTION_TIMEOUT = 30000; - private static final long DEFAULT_RECEIVE_TIMEOUT = 60000; - - private final Map policyMap = new HashMap<>(); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public TimeoutFilter(JaxrsServiceDescriptor descriptor, Config config) { - final long defaultConnectionTimeout = getTimeout(config, DEFAULT_CONNECTION_TIMEOUT_PROP, DEFAULT_CONNECTION_TIMEOUT); - final long defaultReceiveTimeout = getTimeout(config, DEFAULT_RECEIVE_TIMEOUT_PROP, DEFAULT_RECEIVE_TIMEOUT); - Stream.of(descriptor.serviceInterface().getMethods()) - .forEach(method -> { - final String methodName = method.getName(); - HTTPClientPolicy policy = new HTTPClientPolicy(); - policy.setConnectionTimeout(getTimeout(config, String.format(CONNECTION_TIMEOUT_PROP_PATTERN, methodName), defaultConnectionTimeout)); - policy.setReceiveTimeout(getTimeout(config, String.format(RECEIVE_TIMEOUT_PROP_PATTERN, methodName), defaultReceiveTimeout)); - policyMap.put(methodName, policy); - }); - } - - private static long getTimeout(Config config, String name, long defaultValue) { - return config.longValue(name).orElse(defaultValue); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ClientRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - final Message message = JAXRSUtils.getCurrentMessage(); - final Exchange exchange = message.getExchange(); - final String methodName = String.valueOf(exchange.get(OPERATION_NAME_PROP)); - message.put(HTTPClientPolicy.class, policyMap.get(methodName)); - } -} diff --git a/timeout/src/main/java/org/microbule/timeout/decorator/TimeoutProxyDecorator.java b/timeout/src/main/java/org/microbule/timeout/decorator/TimeoutProxyDecorator.java deleted file mode 100644 index bc87c74..0000000 --- a/timeout/src/main/java/org/microbule/timeout/decorator/TimeoutProxyDecorator.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.timeout.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("timeoutProxyDecorator") -public class TimeoutProxyDecorator implements JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new TimeoutFilter(descriptor, config)); - } - - @Override - public String name() { - return "timeout"; - } -} diff --git a/timeout/src/main/resources/META-INF/beans.xml b/timeout/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/timeout/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/timeout/src/main/resources/OSGI-INF/blueprint/microbule-timeout-decorator.xml b/timeout/src/main/resources/OSGI-INF/blueprint/microbule-timeout-decorator.xml deleted file mode 100644 index 0a990be..0000000 --- a/timeout/src/main/resources/OSGI-INF/blueprint/microbule-timeout-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/timeout/src/test/java/org/microbule/timeout/decorator/DelayResource.java b/timeout/src/test/java/org/microbule/timeout/decorator/DelayResource.java deleted file mode 100644 index bc849c8..0000000 --- a/timeout/src/test/java/org/microbule/timeout/decorator/DelayResource.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.timeout.decorator; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -public interface DelayResource { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Path("/delay/{value}") - @GET - @Produces(MediaType.TEXT_PLAIN) - String delay(@PathParam("value") long value); -} diff --git a/timeout/src/test/java/org/microbule/timeout/decorator/DelayResourceImpl.java b/timeout/src/test/java/org/microbule/timeout/decorator/DelayResourceImpl.java deleted file mode 100644 index 5d112da..0000000 --- a/timeout/src/test/java/org/microbule/timeout/decorator/DelayResourceImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.timeout.decorator; - -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.awaitility.Awaitility.await; - -public class DelayResourceImpl implements DelayResource { -//---------------------------------------------------------------------------------------------------------------------- -// DelayResource Implementation -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DelayResourceImpl.class); - - @Override - public String delay(long value) { - LOGGER.info("Delaying {} ms...", value); - final long expiration = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(value); - await().until(() -> System.nanoTime() >= expiration); - return String.valueOf(value); - } -} diff --git a/timeout/src/test/java/org/microbule/timeout/decorator/TimeoutProxyDecoratorTest.java b/timeout/src/test/java/org/microbule/timeout/decorator/TimeoutProxyDecoratorTest.java deleted file mode 100644 index 69dd0fc..0000000 --- a/timeout/src/test/java/org/microbule/timeout/decorator/TimeoutProxyDecoratorTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.timeout.decorator; - -import javax.ws.rs.ProcessingException; - -import org.junit.Assert; -import org.junit.Test; -import org.microbule.config.core.MapConfig; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.server.JaxrsServerTestCase; - -public class TimeoutProxyDecoratorTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new TimeoutProxyDecorator()); - } - - @Override - protected void configureProxy(MapConfig proxyConfig) { - proxyConfig.addValue("timeout.connectionTimeout", "100"); - proxyConfig.addValue("timeout.receiveTimeout", "500"); - } - - @Override - protected DelayResource createImplementation() { - return new DelayResourceImpl(); - } - - @Test(expected = ProcessingException.class) - public void testConnectionTimeoutExpired() { - final DelayResource proxy = createProxy(); - proxy.delay(3000); - } - - @Test - public void testConnectionTimeout() { - final DelayResource proxy = createProxy(); - Assert.assertEquals("150", proxy.delay(150)); - } -} \ No newline at end of file diff --git a/tracer.md b/tracer.md new file mode 100644 index 0000000..44e61f4 --- /dev/null +++ b/tracer.md @@ -0,0 +1,15 @@ +# Tracer + +Microbule will generate a the following random UUID header values automatically: + +- **Microbule-Trace-ID**: a unique value corresponding to a "transaction." If the header is found on the request, the +existing value will be used. +- **Microbule-Request-ID**: a unique value corresponding to the request itself. This is generated for each and every +request. + +A typical response will contain the following headers: + + ``` + Microbule-Request-ID=[3a5bf571-99fd-4c6b-b79e-7ff0a28e9350] + Microbule-Trace-ID=[da3e59f4-8aff-4a89-bc30-7ad310fecf63] + ``` diff --git a/tracer/decorator/pom.xml b/tracer/decorator/pom.xml deleted file mode 100644 index 7b6838e..0000000 --- a/tracer/decorator/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-tracer-parent - 0.3.0-SNAPSHOT - - - microbule-tracer-decorator - Microbule :: Tracer :: Decorator - bundle - - - org.microbule - microbule-container-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-tracer-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-test-osgi - 0.3.0-SNAPSHOT - test - - - diff --git a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/AbstractTracerDecorator.java b/tracer/decorator/src/main/java/org/microbule/tracer/decorator/AbstractTracerDecorator.java deleted file mode 100644 index d457886..0000000 --- a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/AbstractTracerDecorator.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import org.microbule.spi.JaxrsServiceDecorator; - -public abstract class AbstractTracerDecorator implements JaxrsServiceDecorator{ - - public static final String DEFAULT_REQUEST_ID_HEADER = "Microbule-Request-ID"; - public static final String DEFAULT_TRACE_ID_HEADER = "Microbule-Trace-ID"; - public static final String TRACE_ID_KEY = "microbule_trace_id"; - public static final String REQUEST_ID_KEY = "microbule_request_id"; - public static final String TRACE_ID_HEADER_PROP = "traceIdHeader"; - public static final String REQUEST_ID_HEADER_PROP = "requestIdHeader"; - - public static final String DECORATOR_NAME = "tracer"; - - @Override - public String name() { - return DECORATOR_NAME; - } -} diff --git a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerClientFilter.java b/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerClientFilter.java deleted file mode 100644 index 91df872..0000000 --- a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerClientFilter.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import java.io.IOException; - -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.MDC; - -public class TracerClientFilter implements ClientRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String traceIdHeader; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public TracerClientFilter(String traceIdHeader) { - this.traceIdHeader = traceIdHeader; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ClientRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - final String traceId = MDC.get(AbstractTracerDecorator.TRACE_ID_KEY); - if (StringUtils.isNotBlank(traceId)) { - requestContext.getHeaders().putSingle(traceIdHeader, traceId); - } - } -} diff --git a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerContainerFilter.java b/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerContainerFilter.java deleted file mode 100644 index 6bdc267..0000000 --- a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerContainerFilter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Priority; -import javax.ws.rs.Priorities; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.ext.Provider; - -import org.microbule.tracer.spi.TracerIdStrategy; -import org.slf4j.MDC; - -@Provider -@Priority(Priorities.HEADER_DECORATOR) -public class TracerContainerFilter implements ContainerRequestFilter, ContainerResponseFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String traceIdHeader; - private final String requestIdHeader; - private final AtomicReference idGeneratorRef; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public TracerContainerFilter(AtomicReference idGeneratorRef, String traceIdHeader, String requestIdHeader) { - this.idGeneratorRef = idGeneratorRef; - this.traceIdHeader = traceIdHeader; - this.requestIdHeader = requestIdHeader; - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext request) throws IOException { - String traceId = request.getHeaderString(traceIdHeader); - if(traceId == null) { - traceId = idGeneratorRef.get().generateTraceId(request); - } - final String requestId = idGeneratorRef.get().generateRequestId(request); - request.setProperty(AbstractTracerDecorator.TRACE_ID_KEY, traceId); - request.setProperty(AbstractTracerDecorator.REQUEST_ID_KEY, requestId); - MDC.put(AbstractTracerDecorator.TRACE_ID_KEY, traceId); - MDC.put(AbstractTracerDecorator.REQUEST_ID_KEY, requestId); - } - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerResponseFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { - MDC.remove(AbstractTracerDecorator.TRACE_ID_KEY); - MDC.remove(AbstractTracerDecorator.REQUEST_ID_KEY); - response.getHeaders().putSingle(traceIdHeader, request.getProperty(AbstractTracerDecorator.TRACE_ID_KEY)); - response.getHeaders().putSingle(requestIdHeader, request.getProperty(AbstractTracerDecorator.REQUEST_ID_KEY)); - } -} diff --git a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerProxyDecorator.java b/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerProxyDecorator.java deleted file mode 100644 index 05b4e82..0000000 --- a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerProxyDecorator.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Singleton -@Named("tracerProxyDecorator") -public class TracerProxyDecorator extends AbstractTracerDecorator implements JaxrsProxyDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - final String traceIdHeader = config.value(TRACE_ID_HEADER_PROP).orElse(DEFAULT_TRACE_ID_HEADER); - descriptor.addProvider(new TracerClientFilter(traceIdHeader)); - } -} diff --git a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerServerDecorator.java b/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerServerDecorator.java deleted file mode 100644 index e938e47..0000000 --- a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/TracerServerDecorator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import java.util.concurrent.atomic.AtomicReference; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.tracer.spi.TracerIdStrategy; - -@Singleton -@Named("tracerServerDecorator") -public class TracerServerDecorator extends AbstractTracerDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - - private final AtomicReference idGeneratorRef; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public TracerServerDecorator(MicrobuleContainer container) { - this.idGeneratorRef = container.pluginReference(TracerIdStrategy.class, UuidStrategy.INSTANCE); - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - final String traceIdHeader = config.value(TRACE_ID_HEADER_PROP).orElse(DEFAULT_TRACE_ID_HEADER); - final String requestIdHeader = config.value(REQUEST_ID_HEADER_PROP).orElse(DEFAULT_REQUEST_ID_HEADER); - descriptor.addProvider(new TracerContainerFilter(idGeneratorRef, traceIdHeader, requestIdHeader)); - } -} diff --git a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/UuidStrategy.java b/tracer/decorator/src/main/java/org/microbule/tracer/decorator/UuidStrategy.java deleted file mode 100644 index ad23f50..0000000 --- a/tracer/decorator/src/main/java/org/microbule/tracer/decorator/UuidStrategy.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import java.util.UUID; - -import javax.ws.rs.container.ContainerRequestContext; - -import org.microbule.tracer.spi.TracerIdStrategy; - -public class UuidStrategy implements TracerIdStrategy { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - public static final TracerIdStrategy INSTANCE = new UuidStrategy(); - -//---------------------------------------------------------------------------------------------------------------------- -// TracerIdStrategy Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public String generateRequestId(ContainerRequestContext request) { - return uuid(); - } - - @Override - public String generateTraceId(ContainerRequestContext request) { - return uuid(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private String uuid() { - return UUID.randomUUID().toString(); - } -} diff --git a/tracer/decorator/src/main/resources/META-INF/beans.xml b/tracer/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/tracer/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/tracer/decorator/src/main/resources/OSGI-INF/blueprint/microbule-tracer-decorator.xml b/tracer/decorator/src/main/resources/OSGI-INF/blueprint/microbule-tracer-decorator.xml deleted file mode 100644 index 2a63e38..0000000 --- a/tracer/decorator/src/main/resources/OSGI-INF/blueprint/microbule-tracer-decorator.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tracer/decorator/src/test/java/org/microbule/tracer/decorator/TracerProxyDecoratorTest.java b/tracer/decorator/src/test/java/org/microbule/tracer/decorator/TracerProxyDecoratorTest.java deleted file mode 100644 index 748299b..0000000 --- a/tracer/decorator/src/test/java/org/microbule/tracer/decorator/TracerProxyDecoratorTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import org.junit.Assert; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.server.hello.HelloTestCase; -import org.slf4j.MDC; - -public class TracerProxyDecoratorTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new TracerProxyDecorator()); - } - - @Test - public void testWithCustomTraceId() { - final HelloService proxy = createProxy(); - MDC.put(AbstractTracerDecorator.TRACE_ID_KEY, "foobarbaz"); - Assert.assertEquals("Hello, Microbule!", proxy.sayHello("Microbule")); - MDC.remove(AbstractTracerDecorator.TRACE_ID_KEY); - } -} \ No newline at end of file diff --git a/tracer/decorator/src/test/java/org/microbule/tracer/decorator/TracerServerDecoratorTest.java b/tracer/decorator/src/test/java/org/microbule/tracer/decorator/TracerServerDecoratorTest.java deleted file mode 100644 index 7f53908..0000000 --- a/tracer/decorator/src/test/java/org/microbule/tracer/decorator/TracerServerDecoratorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.decorator; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.test.osgi.OsgiRule; -import org.microbule.test.server.hello.HelloTestCase; - -public class TracerServerDecoratorTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Rule - public final OsgiRule osgiRule = new OsgiRule(); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new TracerServerDecorator(container)); - } - - @Test - public void testWithCustomTraceId() { - final WebTarget target = createWebTarget(); - final Response response = target.path("hello").path("Microbule") - .request(MediaType.TEXT_PLAIN) - .header(AbstractTracerDecorator.DEFAULT_TRACE_ID_HEADER, "foobarbaz") - .get(); - assertEquals(200, response.getStatus()); - Assert.assertEquals("foobarbaz", response.getHeaderString(AbstractTracerDecorator.DEFAULT_TRACE_ID_HEADER)); - Assert.assertNotNull(response.getHeaderString(AbstractTracerDecorator.DEFAULT_REQUEST_ID_HEADER)); - } -} \ No newline at end of file diff --git a/tracer/pom.xml b/tracer/pom.xml deleted file mode 100644 index d02532f..0000000 --- a/tracer/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-tracer-parent - Microbule :: Tracer :: Parent - pom - - - spi - decorator - - diff --git a/tracer/spi/pom.xml b/tracer/spi/pom.xml deleted file mode 100644 index e640589..0000000 --- a/tracer/spi/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-tracer-parent - 0.3.0-SNAPSHOT - - - microbule-tracer-spi - Microbule :: Tracer :: SPI - bundle - - diff --git a/tracer/spi/src/main/java/org/microbule/tracer/spi/TracerIdStrategy.java b/tracer/spi/src/main/java/org/microbule/tracer/spi/TracerIdStrategy.java deleted file mode 100644 index 9ecabf8..0000000 --- a/tracer/spi/src/main/java/org/microbule/tracer/spi/TracerIdStrategy.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.tracer.spi; - -import javax.ws.rs.container.ContainerRequestContext; - -public interface TracerIdStrategy { - String generateTraceId(ContainerRequestContext request); - - String generateRequestId(ContainerRequestContext request); -} diff --git a/util/pom.xml b/util/pom.xml deleted file mode 100644 index 4dcd2a7..0000000 --- a/util/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-util - Microbule :: Util - bundle - - - - com.google.code.gson - gson - ${gson.version} - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - test - - - diff --git a/util/src/main/java/org/microbule/util/collection/RoundRobin.java b/util/src/main/java/org/microbule/util/collection/RoundRobin.java deleted file mode 100644 index 9811a9b..0000000 --- a/util/src/main/java/org/microbule/util/collection/RoundRobin.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.microbule.util.collection; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import com.google.common.collect.Lists; - -public class RoundRobin { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final List items; - private final AtomicInteger index = new AtomicInteger(); - private final int n; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public RoundRobin(List items) { - this.items = items == null ? Collections.emptyList() : Lists.newArrayList(items); - this.n = this.items.size(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public T nextItem() { - return n == 0 ? null : items.get(index.getAndUpdate(val -> (val + 1) % n)); - } -} diff --git a/util/src/main/java/org/microbule/util/exception/MicrobuleException.java b/util/src/main/java/org/microbule/util/exception/MicrobuleException.java deleted file mode 100644 index 4751950..0000000 --- a/util/src/main/java/org/microbule/util/exception/MicrobuleException.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.microbule.util.exception; - -import static java.lang.String.format; - -public class MicrobuleException extends RuntimeException { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public MicrobuleException(String message, Object... params) { - super(format(message, params)); - } - - public MicrobuleException(Throwable cause, String message, Object... params) { - super(format(message, params), cause); - } -} diff --git a/util/src/main/java/org/microbule/util/jaxrs/AnnotationDrivenDynamicFeature.java b/util/src/main/java/org/microbule/util/jaxrs/AnnotationDrivenDynamicFeature.java deleted file mode 100644 index 082e511..0000000 --- a/util/src/main/java/org/microbule/util/jaxrs/AnnotationDrivenDynamicFeature.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.microbule.util.jaxrs; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.Objects; -import java.util.Optional; - -import javax.ws.rs.container.DynamicFeature; -import javax.ws.rs.container.ResourceInfo; -import javax.ws.rs.core.FeatureContext; - -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.lang3.reflect.MethodUtils; -import org.microbule.util.reflect.Types; - -public abstract class AnnotationDrivenDynamicFeature implements DynamicFeature { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Class annotationType = Types.getTypeParameter(getClass().getGenericSuperclass(), AnnotationDrivenDynamicFeature.class, 0); - -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract void configure(A annotation, ResourceInfo resourceInfo, FeatureContext featureContext); - -//---------------------------------------------------------------------------------------------------------------------- -// DynamicFeature Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void configure(ResourceInfo resourceInfo, FeatureContext context) { - getAnnotation(resourceInfo.getResourceMethod(), annotationType) - .ifPresent(annot -> configure(annot, resourceInfo, context)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected Optional getAnnotation(Method method, Class type) { - return MethodUtils.getOverrideHierarchy(method, ClassUtils.Interfaces.INCLUDE).stream() - .map(m -> m.getAnnotation(type)) - .filter(Objects::nonNull) - .findFirst(); - } -} diff --git a/util/src/main/java/org/microbule/util/jaxrs/ExtensionRequestFilter.java b/util/src/main/java/org/microbule/util/jaxrs/ExtensionRequestFilter.java deleted file mode 100644 index bfe3c59..0000000 --- a/util/src/main/java/org/microbule/util/jaxrs/ExtensionRequestFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.microbule.util.jaxrs; - -import java.io.IOException; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.PreMatching; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -@Provider -@PreMatching -public abstract class ExtensionRequestFilter implements ContainerRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract T createResponse(ContainerRequestContext requestContext); - - protected abstract String markerParam(); - -//---------------------------------------------------------------------------------------------------------------------- -// ContainerRequestFilter Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - if ("GET".equals(requestContext.getMethod()) && requestContext.getUriInfo().getQueryParameters().containsKey(markerParam())) { - requestContext.abortWith( - Response.ok(createResponse(requestContext)) - .type(MediaType.APPLICATION_JSON_TYPE) - .build()); - } - } -} diff --git a/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java b/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java deleted file mode 100644 index 4d0e00d..0000000 --- a/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.util.jaxrs; - -import java.util.Optional; - -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -public final class WebTargetUtils { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Gson GSON = new Gson(); - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static WebTarget extend(WebTarget baseTarget, String... paths) { - WebTarget answer = baseTarget; - for (String path : paths) { - answer = answer.path(path); - } - return answer; - } - - public static Optional parseJsonResponse(Response response, Class type) { - return parseJsonResponse(response, TypeToken.get(type)); - } - - public static Optional parseJsonResponse(Response response, TypeToken token) { - if (Response.Status.OK.getStatusCode() == response.getStatus()) { - return Optional.of(GSON.fromJson(response.readEntity(String.class), token.getType())); - } - return Optional.empty(); - } - - private WebTargetUtils() { - - } -} diff --git a/util/src/main/java/org/microbule/util/proxy/DynamicProxyUtils.java b/util/src/main/java/org/microbule/util/proxy/DynamicProxyUtils.java deleted file mode 100644 index dfd1a17..0000000 --- a/util/src/main/java/org/microbule/util/proxy/DynamicProxyUtils.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.util.proxy; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.function.Supplier; - -public final class DynamicProxyUtils { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final String TO_STRING_METHOD_NAME = "toString"; - private static final String EQUALS_METHOD_NAME = "equals"; - private static final String HASH_CODE_METHOD_NAME = "hashCode"; - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static T createProxy(final Class proxyInterface, InvocationHandler handler) { - return proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(), new Class[]{proxyInterface}, handler)); - } - - public static T createProxy(final Class proxyInterface, final Supplier targetSupplier, String descriptionPattern, Object... descriptionParams) { - final String description = String.format(descriptionPattern, descriptionParams); - final InvocationHandler handler = (proxy, method, args) -> { - if (isEqualsMethod(method)) { - return proxy == args[0]; - } - if (isHashCodeMethod(method)) { - return System.identityHashCode(proxy); - } - if (isToStringMethod(method)) { - return description; - } - try { - return method.invoke(targetSupplier.get(), args); - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } - }; - return createProxy(proxyInterface, handler); - } - - public static boolean isEqualsMethod(Method method) { - return EQUALS_METHOD_NAME.equals(method.getName()) && - method.getParameterTypes().length == 1 - && Object.class.equals(method.getParameterTypes()[0]); - } - - public static boolean isHashCodeMethod(Method method) { - return HASH_CODE_METHOD_NAME.equals(method.getName()) && method.getParameterTypes().length == 0; - } - - public static boolean isToStringMethod(Method method) { - return TO_STRING_METHOD_NAME.equals(method.getName()) && method.getParameterCount() == 0; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private DynamicProxyUtils() { - - } -} diff --git a/util/src/main/java/org/microbule/util/reflect/DelegatingClassLoader.java b/util/src/main/java/org/microbule/util/reflect/DelegatingClassLoader.java deleted file mode 100644 index 3765bf2..0000000 --- a/util/src/main/java/org/microbule/util/reflect/DelegatingClassLoader.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.microbule.util.reflect; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -public class DelegatingClassLoader extends ClassLoader { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final ClassLoader delegate; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public DelegatingClassLoader(ClassLoader parent, ClassLoader delegate) { - super(parent); - this.delegate = delegate; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public ClassLoader getDelegate() { - return delegate; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Canonical Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - DelegatingClassLoader that = (DelegatingClassLoader) o; - - return new EqualsBuilder() - .append(getParent(), that.getParent()) - .append(delegate, that.delegate) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(getParent()) - .append(delegate) - .toHashCode(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - return delegate.loadClass(name); - } -} diff --git a/util/src/main/java/org/microbule/util/reflect/Types.java b/util/src/main/java/org/microbule/util/reflect/Types.java deleted file mode 100644 index 84b1762..0000000 --- a/util/src/main/java/org/microbule/util/reflect/Types.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.microbule.util.reflect; - -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.Map; - -import org.apache.commons.lang3.reflect.TypeUtils; - -public final class Types { -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - @SuppressWarnings("unchecked") - public static Class getTypeParameter(Type subType, Class superType, int index) { - final Map, Type> arguments = TypeUtils.getTypeArguments(subType, superType); - final TypeVariable> variable = superType.getTypeParameters()[index]; - return (Class) arguments.get(variable); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private Types() { - - } -} diff --git a/util/src/test/java/org/microbule/util/collection/RoundRobinTest.java b/util/src/test/java/org/microbule/util/collection/RoundRobinTest.java deleted file mode 100644 index 81d790f..0000000 --- a/util/src/test/java/org/microbule/util/collection/RoundRobinTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.microbule.util.collection; - -import java.util.LinkedList; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class RoundRobinTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testWithEmptyList() { - RoundRobin balancer = new RoundRobin<>(new LinkedList<>()); - assertNull(balancer.nextItem()); - } - - @Test - public void testWithNullList() { - RoundRobin balancer = new RoundRobin<>(null); - assertNull(balancer.nextItem()); - } - - @Test - public void testWithOneItem() { - RoundRobin balancer = new RoundRobin<>(Lists.newArrayList("one")); - assertEquals("one", balancer.nextItem()); - assertEquals("one", balancer.nextItem()); - assertEquals("one", balancer.nextItem()); - assertEquals("one", balancer.nextItem()); - } - - @Test - public void testRoundRobin() { - RoundRobin balancer = new RoundRobin<>(Lists.newArrayList("one", "two", "three")); - assertEquals("one", balancer.nextItem()); - assertEquals("two", balancer.nextItem()); - assertEquals("three", balancer.nextItem()); - assertEquals("one", balancer.nextItem()); - } - - @Test - public void testRoundRobinWithDups() { - RoundRobin balancer = new RoundRobin<>(Lists.newArrayList("one", "one", "two", "three")); - assertEquals("one", balancer.nextItem()); - assertEquals("one", balancer.nextItem()); - assertEquals("two", balancer.nextItem()); - assertEquals("three", balancer.nextItem()); - assertEquals("one", balancer.nextItem()); - } -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/exception/MicrobuleExceptionTest.java b/util/src/test/java/org/microbule/util/exception/MicrobuleExceptionTest.java deleted file mode 100644 index b2f1343..0000000 --- a/util/src/test/java/org/microbule/util/exception/MicrobuleExceptionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.microbule.util.exception; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class MicrobuleExceptionTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testConstructor() { - final MicrobuleException e = new MicrobuleException("One %s %s", "two", "three"); - assertEquals("One two three", e.getMessage()); - } - - @Test - public void testConstructorWithCause() { - final Throwable cause = new IllegalArgumentException("Not gonna do it!"); - final MicrobuleException e = new MicrobuleException(cause, "One %s %s", "two", "three"); - assertEquals("One two three", e.getMessage()); - assertEquals(cause, e.getCause()); - } -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/jaxrs/AnnotationDrivenDynamicFeatureTest.java b/util/src/test/java/org/microbule/util/jaxrs/AnnotationDrivenDynamicFeatureTest.java deleted file mode 100644 index c10b33d..0000000 --- a/util/src/test/java/org/microbule/util/jaxrs/AnnotationDrivenDynamicFeatureTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.microbule.util.jaxrs; - -import javax.inject.Inject; -import javax.ws.rs.container.ResourceInfo; -import javax.ws.rs.core.FeatureContext; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.Mockito.when; - -public class AnnotationDrivenDynamicFeatureTest extends MockObjectTestCase { - - @Mock - private ResourceInfo resourceInfo; - - @Mock - private FeatureContext featureContext; - - @Test - public void testConfigure() throws Exception { - when(resourceInfo.getResourceMethod()).thenReturn(TestResource.class.getMethod("resourceMethod")); - - final TestFeature feature = new TestFeature(); - feature.configure(resourceInfo, featureContext); - assertTrue(feature.called); - } - - - public static class TestFeature extends AnnotationDrivenDynamicFeature { - private boolean called = false; - @Override - protected void configure(Inject annotation, ResourceInfo resourceInfo, FeatureContext featureContext) { - called = true; - } - } - - public static class TestResource { - - @Inject - public void resourceMethod() { - - } - } -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/jaxrs/ExtensionRequestFilterTest.java b/util/src/test/java/org/microbule/util/jaxrs/ExtensionRequestFilterTest.java deleted file mode 100644 index 42f2ced..0000000 --- a/util/src/test/java/org/microbule/util/jaxrs/ExtensionRequestFilterTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.microbule.util.jaxrs; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -public class ExtensionRequestFilterTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private ContainerRequestContext requestContext; - - @Mock - private UriInfo uriInfo; - - @Captor - private ArgumentCaptor responseCaptor; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testGetWithParam() throws Exception { - when(requestContext.getMethod()).thenReturn("GET"); - when(requestContext.getUriInfo()).thenReturn(uriInfo); - final MultivaluedHashMap queryParams = new MultivaluedHashMap<>(); - queryParams.add("_status", "bogus"); - when(uriInfo.getQueryParameters()).thenReturn(queryParams); - - final StatusFilter filter = new StatusFilter(); - filter.filter(requestContext); - verify(requestContext).getMethod(); - verify(requestContext).getUriInfo(); - verify(uriInfo).getQueryParameters(); - verify(requestContext).abortWith(responseCaptor.capture()); - verifyNoMoreInteractions(requestContext, uriInfo); - - final Response response = responseCaptor.getValue(); - assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType()); - assertEquals("ok", response.getEntity()); - } - - @Test - public void testPostWithParam() throws Exception { - when(requestContext.getMethod()).thenReturn("POST"); - when(requestContext.getUriInfo()).thenReturn(uriInfo); - final MultivaluedHashMap queryParams = new MultivaluedHashMap<>(); - queryParams.add("_status", "bogus"); - when(uriInfo.getQueryParameters()).thenReturn(queryParams); - - final StatusFilter filter = new StatusFilter(); - filter.filter(requestContext); - verify(requestContext).getMethod(); - verifyNoMoreInteractions(requestContext, uriInfo); - } - - @Test - public void testGetWithoutParam() throws Exception { - when(requestContext.getMethod()).thenReturn("GET"); - when(requestContext.getUriInfo()).thenReturn(uriInfo); - final MultivaluedHashMap queryParams = new MultivaluedHashMap<>(); - when(uriInfo.getQueryParameters()).thenReturn(queryParams); - - final StatusFilter filter = new StatusFilter(); - filter.filter(requestContext); - verify(requestContext).getMethod(); - verify(requestContext).getUriInfo(); - verify(uriInfo).getQueryParameters(); - verifyNoMoreInteractions(requestContext, uriInfo); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class StatusFilter extends ExtensionRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected String createResponse(ContainerRequestContext requestContext) { - return "ok"; - } - - @Override - protected String markerParam() { - return "_status"; - } - } -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java b/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java deleted file mode 100644 index a1631d2..0000000 --- a/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.util.jaxrs; - -import java.util.Optional; - -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.google.gson.Gson; -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class WebTargetUtilsTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testExtend() { - final WebTarget target = ClientBuilder.newClient().target("http://localhost:8080/foo"); - final WebTarget extended = WebTargetUtils.extend(target, "bar", "baz"); - assertTrue(extended.getUri().toString().endsWith("/bar/baz")); - } - - @Test - public void testIsUtilClass() throws Exception { - assertIsUtilsClass(WebTargetUtils.class); - } - - @Test - public void testParseSuccessfulResponse() { - Gson gson = new Gson(); - - final Response response = Response.ok(gson.toJson(new Person("Slappy", "White"))).type(MediaType.APPLICATION_JSON_TYPE).build(); - final Optional personOptional = WebTargetUtils.parseJsonResponse(response, Person.class); - assertTrue(personOptional.isPresent()); - Person person = personOptional.get(); - assertEquals("Slappy", person.getFirstName()); - assertEquals("White", person.getLastName()); - } - - @Test - public void testParseUnsuccessfulResponse() { - final Response response = Response.serverError().build(); - final Optional personOptional = WebTargetUtils.parseJsonResponse(response, Person.class); - assertFalse(personOptional.isPresent()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class Person { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String firstName; - private final String lastName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - } -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/proxy/DynamicProxyUtilsTest.java b/util/src/test/java/org/microbule/util/proxy/DynamicProxyUtilsTest.java deleted file mode 100644 index feab954..0000000 --- a/util/src/test/java/org/microbule/util/proxy/DynamicProxyUtilsTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.util.proxy; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.core.hello.HelloServiceImpl; - -public class DynamicProxyUtilsTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testCreateProxy() { - final HelloService proxy = DynamicProxyUtils.createProxy(HelloService.class, HelloServiceImpl::new, "foo"); - assertEquals("Hello, Microbule!", proxy.sayHello("Microbule")); - } - - @Test - public void testEquals() { - final HelloService proxy1 = DynamicProxyUtils.createProxy(HelloService.class, HelloServiceImpl::new, "foo"); - final HelloService proxy2 = DynamicProxyUtils.createProxy(HelloService.class, HelloServiceImpl::new, "foo"); - assertEquals(proxy1, proxy1); - assertNotEquals(proxy1, proxy2); - } - - @Test - public void testHashCode() { - final HelloService proxy = DynamicProxyUtils.createProxy(HelloService.class, HelloServiceImpl::new, "foo"); - assertEquals(System.identityHashCode(proxy), proxy.hashCode()); - } - - @Test - public void testIsHashCode() throws Exception { - assertFalse(DynamicProxyUtils.isHashCodeMethod(BadMethods.class.getMethod("equals"))); - assertFalse(DynamicProxyUtils.isHashCodeMethod(BadMethods.class.getMethod("hashCode", String.class))); - } - - @Test - public void testIsToString() throws Exception { - assertFalse(DynamicProxyUtils.isToStringMethod(BadMethods.class.getMethod("equals"))); - assertFalse(DynamicProxyUtils.isToStringMethod(BadMethods.class.getMethod("toString", String.class))); - } - - @Test - public void testIsEquals() throws Exception { - assertFalse(DynamicProxyUtils.isEqualsMethod(BadMethods.class.getMethod("toString", String.class))); - assertFalse(DynamicProxyUtils.isEqualsMethod(BadMethods.class.getMethod("equals"))); - assertFalse(DynamicProxyUtils.isEqualsMethod(BadMethods.class.getMethod("equals",String.class))); - } - - @Test - public void testToString() { - final HelloService proxy = DynamicProxyUtils.createProxy(HelloService.class, HelloServiceImpl::new, "foo"); - assertEquals("foo", proxy.toString()); - } - - @Test - public void testIsUtilsClass() throws Exception { - assertIsUtilsClass(DynamicProxyUtils.class); - } - - - @Test(expected = IllegalArgumentException.class) - public void testWithException() { - final HelloService proxy = DynamicProxyUtils.createProxy(HelloService.class, () -> new HelloService() { - @Override - public String sayHello(String name) { - throw new IllegalArgumentException(name); - } - - @Override - public String version() { - return "1.0"; - } - }, "foo"); - proxy.sayHello("Microbule"); - } - - interface BadMethods { - boolean equals(String str); - - boolean equals(); - - int hashCode(String str); - - String toString(String str); - } - -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/reflect/DelegatingClassLoaderTest.java b/util/src/test/java/org/microbule/util/reflect/DelegatingClassLoaderTest.java deleted file mode 100644 index d5c32b9..0000000 --- a/util/src/test/java/org/microbule/util/reflect/DelegatingClassLoaderTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.microbule.util.reflect; - -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class DelegatingClassLoaderTest extends MockObjectTestCase { - @Test - public void testConstructor() { - final URLClassLoader delegate = new URLClassLoader(new URL[]{DelegatingClassLoader.class.getProtectionDomain().getCodeSource().getLocation()}); - final DelegatingClassLoader loader = new DelegatingClassLoader(ClassLoader.getSystemClassLoader(), delegate); - assertEquals(delegate, loader.getDelegate()); - assertEquals(ClassLoader.getSystemClassLoader(), loader.getParent()); - } - - @Test - public void testEquals() { - final URLClassLoader delegate = new URLClassLoader(new URL[]{DelegatingClassLoader.class.getProtectionDomain().getCodeSource().getLocation()}); - final DelegatingClassLoader loader1 = new DelegatingClassLoader(ClassLoader.getSystemClassLoader(), delegate); - final DelegatingClassLoader loader2 = new DelegatingClassLoader(ClassLoader.getSystemClassLoader(), delegate); - assertNotEquals(loader1, null); - assertNotEquals(loader1, "FOO"); - assertEquals(loader1, loader1); - assertEquals(loader1, loader2); - } - - @Test - public void testHashCode() { - final URLClassLoader delegate = new URLClassLoader(new URL[]{DelegatingClassLoader.class.getProtectionDomain().getCodeSource().getLocation()}); - final DelegatingClassLoader loader1 = new DelegatingClassLoader(ClassLoader.getSystemClassLoader(), delegate); - final DelegatingClassLoader loader2 = new DelegatingClassLoader(ClassLoader.getSystemClassLoader(), delegate); - assertEquals(loader1.hashCode(), loader2.hashCode()); - } - - @Test - public void testLoadClass() throws Exception { - final URLClassLoader delegate = new URLClassLoader(new URL[]{DelegatingClassLoader.class.getProtectionDomain().getCodeSource().getLocation()}); - final DelegatingClassLoader loader = new DelegatingClassLoader(new BlacklistedClassLoader("org.microbule"), delegate); - assertEquals(delegate.loadClass(DelegatingClassLoader.class.getName()), loader.findClass(DelegatingClassLoader.class.getName())); - } - - private static class BlacklistedClassLoader extends ClassLoader { - private final String blacklist; - - public BlacklistedClassLoader(String blacklist) { - this.blacklist = blacklist; - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if(name.startsWith(blacklist)) { - throw new ClassNotFoundException("Not found!"); - } - return super.loadClass(name); - } - } -} \ No newline at end of file diff --git a/util/src/test/java/org/microbule/util/reflect/TypesTest.java b/util/src/test/java/org/microbule/util/reflect/TypesTest.java deleted file mode 100644 index 9b738c0..0000000 --- a/util/src/test/java/org/microbule/util/reflect/TypesTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.microbule.util.reflect; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class TypesTest extends MicrobuleTestCase { - @Test - public void testIsUtilsClass() throws Exception { - assertIsUtilsClass(Types.class); - } - - @Test - public void testGetTypeParameter() throws Exception { - final Type type = MyType.class.getDeclaredField("map").getGenericType(); - assertEquals(String.class, Types.getTypeParameter(type, Map.class, 0)); - assertEquals(Integer.class, Types.getTypeParameter(type, Map.class, 1)); - } - - public static class MyType { - private final Map map = new HashMap<>(); - } -} \ No newline at end of file diff --git a/validation.md b/validation.md new file mode 100644 index 0000000..7100861 --- /dev/null +++ b/validation.md @@ -0,0 +1,15 @@ +# Bean Validation + +Microbule can automatically validate method parameters using Bean Validation: + + ``` + @Path("/") + public interface HelloResource { + + @Path("/hello/{name}") + @Produces(MediaType.APPLICATION_JSON) + @GET + @Cacheable + HelloResponse sayHello(@PathParam("name") @Size(min = 5, message="Name must be at least 5 characters long.") String name); + } + ``` diff --git a/validation/annotation/pom.xml b/validation/annotation/pom.xml deleted file mode 100644 index f77f17e..0000000 --- a/validation/annotation/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-validation-parent - 0.3.0-SNAPSHOT - - - microbule-validation-annotation - Microbule :: Validation :: Annotation - bundle - - - - javax.validation - validation-api - ${validation.api.version} - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/validation/annotation/src/main/java/org/microbule/validation/annotation/Groups.java b/validation/annotation/src/main/java/org/microbule/validation/annotation/Groups.java deleted file mode 100644 index 7b6a2c8..0000000 --- a/validation/annotation/src/main/java/org/microbule/validation/annotation/Groups.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Used to specify custom validation groups for service methods. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface Groups { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Returns the list of custom validation groups. - * - * @return the list of custom validation groups - */ - Class[] value(); -} diff --git a/validation/annotation/src/main/java/org/microbule/validation/annotation/payload/StatusProvider.java b/validation/annotation/src/main/java/org/microbule/validation/annotation/payload/StatusProvider.java deleted file mode 100644 index 645a236..0000000 --- a/validation/annotation/src/main/java/org/microbule/validation/annotation/payload/StatusProvider.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.annotation.payload; - -import javax.validation.Payload; -import javax.ws.rs.core.Response; - -@FunctionalInterface -public interface StatusProvider extends Payload { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - Response.Status status(); - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - class BadRequest implements StatusProvider { -//---------------------------------------------------------------------------------------------------------------------- -// StatusProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response.Status status() { - return Response.Status.BAD_REQUEST; - } - } - - class Conflict implements StatusProvider { -//---------------------------------------------------------------------------------------------------------------------- -// StatusProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response.Status status() { - return Response.Status.CONFLICT; - } - } - - class Forbidden implements StatusProvider { -//---------------------------------------------------------------------------------------------------------------------- -// StatusProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response.Status status() { - return Response.Status.FORBIDDEN; - } - } - - class NotAuthorized implements StatusProvider { -//---------------------------------------------------------------------------------------------------------------------- -// StatusProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response.Status status() { - return Response.Status.UNAUTHORIZED; - } - } - - class NotFound implements StatusProvider { -//---------------------------------------------------------------------------------------------------------------------- -// StatusProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response.Status status() { - return Response.Status.NOT_FOUND; - } - } -} diff --git a/validation/annotation/src/test/java/org/microbule/validation/annotation/payload/StatusProviderTest.java b/validation/annotation/src/test/java/org/microbule/validation/annotation/payload/StatusProviderTest.java deleted file mode 100644 index 2f7115c..0000000 --- a/validation/annotation/src/test/java/org/microbule/validation/annotation/payload/StatusProviderTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.annotation.payload; - -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; - -public class StatusProviderTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Test - public void testBadRequest() { - assertEquals(Response.Status.BAD_REQUEST, new StatusProvider.BadRequest().status()); - } - - @Test - public void testConfict() { - assertEquals(Response.Status.CONFLICT, new StatusProvider.Conflict().status()); - } - - @Test - public void testForbidden() { - assertEquals(Response.Status.FORBIDDEN, new StatusProvider.Forbidden().status()); - } - - @Test - public void testNotFound() { - assertEquals(Response.Status.NOT_FOUND, new StatusProvider.NotFound().status()); - } - - @Test - public void testUnauthorized() { - assertEquals(Response.Status.UNAUTHORIZED, new StatusProvider.NotAuthorized().status()); - } -} \ No newline at end of file diff --git a/validation/decorator/pom.xml b/validation/decorator/pom.xml deleted file mode 100644 index b7de418..0000000 --- a/validation/decorator/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-validation-parent - 0.3.0-SNAPSHOT - - - microbule-validation-decorator - Microbule :: Validation :: Decorator - bundle - - - org.microbule - microbule-validation-annotation - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - javax.el - javax.el-api - 3.0.0 - - - javax.validation - validation-api - ${validation.api.version} - - - org.hibernate - hibernate-validator - ${hibernate.validator.version} - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.microbule - microbule-errormap-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - diff --git a/validation/decorator/src/main/java/org/microbule/validation/decorator/JaxrsServerValidationException.java b/validation/decorator/src/main/java/org/microbule/validation/decorator/JaxrsServerValidationException.java deleted file mode 100644 index 23bbfdf..0000000 --- a/validation/decorator/src/main/java/org/microbule/validation/decorator/JaxrsServerValidationException.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.microbule.validation.decorator; - -import java.util.Set; -import java.util.stream.Stream; - -import javax.validation.ConstraintViolation; - -public class JaxrsServerValidationException extends RuntimeException { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final transient Set> violations; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public JaxrsServerValidationException(Set> violations) { - this.violations = violations; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public Stream> violations() { - return violations.stream(); - } -} diff --git a/validation/decorator/src/main/java/org/microbule/validation/decorator/JaxrsServerValidationExceptionErrorMapper.java b/validation/decorator/src/main/java/org/microbule/validation/decorator/JaxrsServerValidationExceptionErrorMapper.java deleted file mode 100644 index b0590f4..0000000 --- a/validation/decorator/src/main/java/org/microbule/validation/decorator/JaxrsServerValidationExceptionErrorMapper.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.decorator; - -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.validation.ConstraintViolation; -import javax.ws.rs.core.Response; - -import org.microbule.errormap.spi.TypedErrorMapper; -import org.microbule.validation.annotation.payload.StatusProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static javax.ws.rs.core.Response.Status.BAD_REQUEST; - - -@Named("jaxrsServerValidationExceptionMapper") -@Singleton -public class JaxrsServerValidationExceptionErrorMapper extends TypedErrorMapper { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(JaxrsServerValidationExceptionErrorMapper.class); - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected List doGetErrorMessages(JaxrsServerValidationException exception) { - return exception.violations().map(ConstraintViolation::getMessage).sorted().collect(Collectors.toList()); - } - - @Override - protected Response.StatusType doGetStatus(JaxrsServerValidationException exception) { - return exception.violations() - .flatMap(cve -> cve.getConstraintDescriptor().getPayload().stream()) - .filter(StatusProvider.class::isAssignableFrom) - .map(payloadClass -> { - try { - return (StatusProvider) payloadClass.newInstance(); - } catch (ReflectiveOperationException e) { - LOGGER.error("Unable to instantiate custom ResponseCodePayload object of type {}.", payloadClass.getCanonicalName(), e); - return new StatusProvider.BadRequest(); - } - }) - .map(StatusProvider::status) - .min(Comparator.comparingInt(Response.Status::getStatusCode)).orElse(BAD_REQUEST); - } -} diff --git a/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationDecorator.java b/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationDecorator.java deleted file mode 100644 index ae02b2e..0000000 --- a/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationDecorator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.decorator; - -import java.util.Collections; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.validation.Validation; -import javax.validation.Validator; - -import org.hibernate.validator.HibernateValidator; -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Named("validationDecorator") -@Singleton -public class ValidationDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final ValidationFeature feature; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public ValidationDecorator() { - this.feature = new ValidationFeature(newValidator()); - } - - private static Validator newValidator() { - return Validation.byDefaultProvider().providerResolver(() -> Collections.singletonList(new HibernateValidator())).configure().buildValidatorFactory().getValidator(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addFeature(feature); - } - - @Override - public String name() { - return "validation"; - } -} diff --git a/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationFeature.java b/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationFeature.java deleted file mode 100644 index f7559a3..0000000 --- a/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationFeature.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.decorator; - - -import javax.validation.Validator; - -import org.apache.cxf.Bus; -import org.apache.cxf.feature.AbstractFeature; -import org.apache.cxf.interceptor.InterceptorProvider; - -public class ValidationFeature extends AbstractFeature { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final ValidationInterceptor interceptor; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - ValidationFeature(Validator validator) { - this.interceptor = new ValidationInterceptor(validator); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void initializeProvider(InterceptorProvider provider, Bus bus) { - provider.getInInterceptors().add(interceptor); - } -} diff --git a/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationInterceptor.java b/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationInterceptor.java deleted file mode 100644 index d93a155..0000000 --- a/validation/decorator/src/main/java/org/microbule/validation/decorator/ValidationInterceptor.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.decorator; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validator; -import javax.validation.executable.ExecutableValidator; -import javax.validation.groups.Default; - -import org.apache.cxf.logging.FaultListener; -import org.apache.cxf.logging.NoOpFaultListener; -import org.apache.cxf.message.Message; -import org.apache.cxf.message.MessageContentsList; -import org.apache.cxf.phase.AbstractPhaseInterceptor; -import org.apache.cxf.phase.Phase; -import org.microbule.validation.annotation.Groups; - -public class ValidationInterceptor extends AbstractPhaseInterceptor { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Class[] DEFAULT_GROUPS = {Default.class}; - private static final String METHOD_KEY = "org.apache.cxf.resource.method"; - private final Validator validator; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - ValidationInterceptor(Validator validator) { - super(Phase.PRE_INVOKE); - this.validator = validator; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Interceptor Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void handleMessage(Message message) { - final List arguments = MessageContentsList.getContentsList(message); - if (!arguments.isEmpty()) { - final Object instance = message.getExchange().get(Message.SERVICE_OBJECT); - final Method method = (Method) message.get(METHOD_KEY); - final ExecutableValidator methodValidator = validator.forExecutables(); - final Class[] groups = Optional.ofNullable(method.getAnnotation(Groups.class)).map(Groups::value).orElse(DEFAULT_GROUPS); - final Set> violations = methodValidator.validateParameters(instance, method, arguments.toArray(), groups); - if (!violations.isEmpty()) { - message.put(FaultListener.class.getName(), new NoOpFaultListener()); - throw new JaxrsServerValidationException(violations); - } - } - } -} diff --git a/validation/decorator/src/main/resources/META-INF/beans.xml b/validation/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/validation/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/validation/decorator/src/main/resources/OSGI-INF/blueprint/microbule-validation-decorator.xml b/validation/decorator/src/main/resources/OSGI-INF/blueprint/microbule-validation-decorator.xml deleted file mode 100644 index 014ac54..0000000 --- a/validation/decorator/src/main/resources/OSGI-INF/blueprint/microbule-validation-decorator.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/validation/decorator/src/test/java/org/microbule/validation/decorator/JaxrsServerValidationExceptionErrorMapperTest.java b/validation/decorator/src/test/java/org/microbule/validation/decorator/JaxrsServerValidationExceptionErrorMapperTest.java deleted file mode 100644 index 4666eb8..0000000 --- a/validation/decorator/src/test/java/org/microbule/validation/decorator/JaxrsServerValidationExceptionErrorMapperTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.decorator; - -import java.util.List; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Payload; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.constraints.NotNull; -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Before; -import org.junit.Test; -import org.microbule.test.core.MockObjectTestCase; -import org.microbule.validation.annotation.payload.StatusProvider; - -public class JaxrsServerValidationExceptionErrorMapperTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private JaxrsServerValidationExceptionErrorMapper mapper; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void setUp() { - mapper = new JaxrsServerValidationExceptionErrorMapper(); - } - - @Test - public void testErrorCode() { - Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - Set> violations = validator.validate(new ValidatedBean()); - JaxrsServerValidationException exception = new JaxrsServerValidationException(violations); - int code = mapper.getStatus(exception).getStatusCode(); - assertEquals(400, code); - } - - @Test - public void testErrorMessage() { - Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - Set> violations = validator.validate(new ValidatedBean()); - JaxrsServerValidationException exception = new JaxrsServerValidationException(violations); - final List errorMessages = mapper.getErrorMessages(exception); - assertEquals(Lists.newArrayList("A cannot be null.", "B cannot be null."), errorMessages); - } - - @Test - public void testMapping() { - final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - final Set> violations = validator.validate(new MyBean()); - final JaxrsServerValidationExceptionErrorMapper mapper = new JaxrsServerValidationExceptionErrorMapper(); - final JaxrsServerValidationException exception = new JaxrsServerValidationException(violations); - final List messages = mapper.getErrorMessages(exception); - assertEquals(Lists.newArrayList("Field \"bar\" cannot be empty!", "Field \"foo\" cannot be empty!"), messages); - assertEquals(Response.Status.BAD_REQUEST, mapper.getStatus(exception)); - } - - @Test - public void testWithCustomStatusProviderWithMultiplePayloads() { - Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - Set> violations = validator.validate(new CustomErrorCodeBean()); - JaxrsServerValidationException exception = new JaxrsServerValidationException(violations); - - assertEquals(Lists.newArrayList("A cannot be null.", "B cannot be null."), mapper.getErrorMessages(exception)); - assertEquals(401, mapper.getStatus(exception).getStatusCode()); - } - - @Test - public void testWithCustomStatusProviderWithSinglePayload() { - Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - final CustomErrorCodeBean bean = new CustomErrorCodeBean(); - bean.a = "Hello, World!"; - Set> violations = validator.validate(bean); - JaxrsServerValidationException exception = new JaxrsServerValidationException(violations); - - assertEquals(Lists.newArrayList("B cannot be null."), mapper.getErrorMessages(exception)); - assertEquals(403, mapper.getStatus(exception).getStatusCode()); - } - - @Test - public void testWithInvalidStatusProviderPayload() { - Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - final InvalidErrorCodeBean bean = new InvalidErrorCodeBean(); - Set> violations = validator.validate(bean); - JaxrsServerValidationException exception = new JaxrsServerValidationException(violations); - assertEquals(Lists.newArrayList("A cannot be null."), mapper.getErrorMessages(exception)); - assertEquals(400, mapper.getStatus(exception).getStatusCode()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public interface AnotherPayload extends Payload { - } - - public static class CustomErrorCodeBean { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @NotNull(message = "A cannot be null.", payload = {StatusProvider.NotAuthorized.class, AnotherPayload.class}) - private String a; - - @NotNull(message = "B cannot be null.", payload = StatusProvider.Forbidden.class) - private String b; - } - - public static class InvalidErrorCodeBean { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @NotNull(message = "A cannot be null.", payload = {InvalidStatusProvider.class}) - private String a; - } - - public static class InvalidStatusProvider implements StatusProvider { -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - private InvalidStatusProvider() { - - } - -//---------------------------------------------------------------------------------------------------------------------- -// StatusProvider Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response.Status status() { - return null; - } - } - - private static class MyBean { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @NotNull(message = "Field \"foo\" cannot be empty!") - private String foo; - - @NotNull(message = "Field \"bar\" cannot be empty!") - private String bar; - } - - public static class ValidatedBean { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @NotNull(message = "A cannot be null.") - private String a; - - @NotNull(message = "B cannot be null.") - private String b; - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getA() { - return a; - } - - public void setA(String a) { - this.a = a; - } - - public String getB() { - return b; - } - - public void setB(String b) { - this.b = b; - } - } -} \ No newline at end of file diff --git a/validation/decorator/src/test/java/org/microbule/validation/decorator/ValidationDecoratorTest.java b/validation/decorator/src/test/java/org/microbule/validation/decorator/ValidationDecoratorTest.java deleted file mode 100644 index a787d8f..0000000 --- a/validation/decorator/src/test/java/org/microbule/validation/decorator/ValidationDecoratorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.validation.decorator; - -import java.util.stream.Collectors; - -import javax.validation.ConstraintViolation; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.container.core.SimpleContainer; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.server.hello.HelloTestCase; - -public class ValidationDecoratorTest extends HelloTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - container.addBean(new ValidationDecorator()); - container.addBean(new JaxrsServerDecorator() { - @Override - public String name() { - return "errorhandler"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new CveMapper()); - } - }); - } - - @Test - public void validateWithNoParameters() { - assertEquals("1.0", createProxy().version()); - } - - @Test - public void testSayHelloWithShortName() { - expectException(BadRequestException.class, "HTTP 400 Bad Request"); - createProxy().sayHello("foo"); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class CveMapper implements ExceptionMapper { -//---------------------------------------------------------------------------------------------------------------------- -// ExceptionMapper Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response toResponse(JaxrsServerValidationException exception) { - final String message = exception.violations().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(MediaType.TEXT_PLAIN_TYPE).build(); - } - } -} \ No newline at end of file diff --git a/validation/pom.xml b/validation/pom.xml deleted file mode 100644 index 59565c7..0000000 --- a/validation/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-validation-parent - Microbule :: Validation :: Parent - pom - - - decorator - annotation - - - diff --git a/version/pom.xml b/version/pom.xml deleted file mode 100644 index 023046e..0000000 --- a/version/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-parent - 0.3.0-SNAPSHOT - - - microbule-version-decorator - Microbule :: Version :: Decorator - bundle - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-decorator - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - test - - - diff --git a/version/src/main/java/org/microbule/version/decorator/VersionDecorator.java b/version/src/main/java/org/microbule/version/decorator/VersionDecorator.java deleted file mode 100644 index 63af422..0000000 --- a/version/src/main/java/org/microbule/version/decorator/VersionDecorator.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.microbule.version.decorator; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.microbule.config.api.Config; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; - -@Named("versionDecorator") -@Singleton -public class VersionDecorator implements JaxrsServerDecorator { -//---------------------------------------------------------------------------------------------------------------------- -// JaxrsServiceDecorator Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new VersionRequestFilter(new VersionResponse(descriptor.serviceInterface()))); - } - - @Override - public String name() { - return "version"; - } -} diff --git a/version/src/main/java/org/microbule/version/decorator/VersionRequestFilter.java b/version/src/main/java/org/microbule/version/decorator/VersionRequestFilter.java deleted file mode 100644 index 9223fb6..0000000 --- a/version/src/main/java/org/microbule/version/decorator/VersionRequestFilter.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.microbule.version.decorator; - -import javax.ws.rs.container.ContainerRequestContext; - -import org.microbule.util.jaxrs.ExtensionRequestFilter; - -public class VersionRequestFilter extends ExtensionRequestFilter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final VersionResponse response; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public VersionRequestFilter(VersionResponse response) { - this.response = response; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected VersionResponse createResponse(ContainerRequestContext requestContext) { - return response; - } - - @Override - protected String markerParam() { - return "_version"; - } -} diff --git a/version/src/main/java/org/microbule/version/decorator/VersionResponse.java b/version/src/main/java/org/microbule/version/decorator/VersionResponse.java deleted file mode 100644 index aeba68a..0000000 --- a/version/src/main/java/org/microbule/version/decorator/VersionResponse.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.microbule.version.decorator; - -public class VersionResponse { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String version; - private final String title; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public VersionResponse(Class serviceInterface) { - final Package pkg = serviceInterface.getPackage(); - this.version = pkg.getImplementationVersion(); - this.title = pkg.getImplementationTitle(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getTitle() { - return title; - } - - public String getVersion() { - return version; - } -} diff --git a/version/src/main/resources/META-INF/beans.xml b/version/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/version/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/version/src/main/resources/OSGI-INF/blueprint/microbule-version-decorator.xml b/version/src/main/resources/OSGI-INF/blueprint/microbule-version-decorator.xml deleted file mode 100644 index 9fb97fb..0000000 --- a/version/src/main/resources/OSGI-INF/blueprint/microbule-version-decorator.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java b/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java deleted file mode 100644 index 9e93ea8..0000000 --- a/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.microbule.version.decorator; - -import java.io.StringReader; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; -import org.microbule.test.core.hello.HelloService; -import org.microbule.test.server.hello.HelloTestCase; - -public class VersionDecoratorTest extends HelloTestCase { - - private GsonService gsonService; - - @Override - protected void addBeans(SimpleContainer container) { - gsonService = new DefaultGsonService(container); - container.addBean(gsonService); - container.addBean(new GsonServerDecorator(gsonService)); - container.addBean(new GsonProxyDecorator(gsonService)); - container.addBean(new VersionDecorator()); - } - - @Test - public void testGetVersion() { - final Response response = createWebTarget().queryParam("_version", "bogus").request(MediaType.APPLICATION_JSON_TYPE).get(); - assertEquals(200, response.getStatus()); - final VersionResponse versionResponse = gsonService.parse(new StringReader(response.readEntity(String.class)), VersionResponse.class); - final Package pkg = HelloService.class.getPackage(); - assertEquals(pkg.getImplementationVersion(), versionResponse.getVersion()); - assertEquals(pkg.getImplementationTitle(), versionResponse.getTitle()); - } -} \ No newline at end of file