Initial commit of Usergrid Java SDK into its own repo
Project: http://git-wip-us.apache.org/repos/asf/usergrid-java/repo Commit: http://git-wip-us.apache.org/repos/asf/usergrid-java/commit/88039bad Tree: http://git-wip-us.apache.org/repos/asf/usergrid-java/tree/88039bad Diff: http://git-wip-us.apache.org/repos/asf/usergrid-java/diff/88039bad Branch: refs/heads/master Commit: 88039badcdfad591d0db850081263a5d24b8ba23 Parents: Author: Michael Russo <[email protected]> Authored: Fri Sep 2 09:37:20 2016 -0700 Committer: Michael Russo <[email protected]> Committed: Fri Sep 2 09:37:20 2016 -0700 ---------------------------------------------------------------------- .gitignore | 3 + LICENSE | 202 ++++++ README.md | 580 ++++++++++++++++ pom.xml | 127 ++++ .../apache/usergrid/java/client/Usergrid.java | 285 ++++++++ .../usergrid/java/client/UsergridClient.java | 429 ++++++++++++ .../java/client/UsergridClientConfig.java | 60 ++ .../usergrid/java/client/UsergridEnums.java | 170 +++++ .../usergrid/java/client/UsergridRequest.java | 205 ++++++ .../java/client/UsergridRequestManager.java | 97 +++ .../java/client/auth/UsergridAppAuth.java | 55 ++ .../usergrid/java/client/auth/UsergridAuth.java | 76 +++ .../java/client/auth/UsergridUserAuth.java | 68 ++ .../client/exception/UsergridException.java | 50 ++ .../java/client/model/UsergridDevice.java | 60 ++ .../java/client/model/UsergridEntity.java | 487 +++++++++++++ .../java/client/model/UsergridUser.java | 198 ++++++ .../java/client/query/UsergridQuery.java | 431 ++++++++++++ .../java/client/response/UsergridResponse.java | 230 +++++++ .../client/response/UsergridResponseError.java | 98 +++ .../usergrid/java/client/utils/JsonUtils.java | 152 +++++ .../usergrid/java/client/utils/MapUtils.java | 36 + .../usergrid/java/client/utils/ObjectUtils.java | 38 ++ .../utils/UsergridEntityDeserializer.java | 41 ++ .../client/ClientAuthFallBackTestCase.java | 72 ++ .../usergrid/client/ClientAuthTestCase.java | 85 +++ .../client/ClientConnectionsTestCase.java | 171 +++++ .../usergrid/client/ClientRestTestCase.java | 90 +++ .../apache/usergrid/client/EntityTestCase.java | 676 +++++++++++++++++++ .../apache/usergrid/client/QueryTestCase.java | 194 ++++++ .../usergrid/client/SDKTestConfiguration.java | 38 ++ .../apache/usergrid/client/SDKTestUtils.java | 108 +++ .../client/UsergridClientAuthTestCase.java | 73 ++ .../usergrid/client/UsergridInitTestCase.java | 48 ++ .../client/UsergridResponseErrorTestCase.java | 62 ++ .../client/UsergridResponseTestCase.java | 85 +++ .../usergrid/client/UsergridTestCase.java | 30 + usergrid-java-client-2.1.0.jar | Bin 0 -> 1992232 bytes 38 files changed, 5910 insertions(+) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/.gitignore ---------------------------------------------------------------------- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40f7468 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +target/ +*.iml \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/LICENSE ---------------------------------------------------------------------- diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ +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. + http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/README.md ---------------------------------------------------------------------- diff --git a/README.md b/README.md new file mode 100644 index 0000000..95e4d04 --- /dev/null +++ b/README.md @@ -0,0 +1,580 @@ +# Usergrid Java SDK + +Usergrid SDK written for Java + +## Initialization + +There are two different ways of initializing the Usergrid Java SDK: + +1. The singleton pattern is both convenient and enables the developer to use a globally available and always-initialized instance of Usergrid. + +```java +Usergrid.initSharedInstance("orgId", "appId"); +``` + +2. The Instance pattern enables the developer to manage instances of the Usergrid client independently and in an isolated fashion. The primary use-case for this is when an application connects to multiple Usergrid targets. + +```java +UsergridClient client = new UsergridClient("orgId","appId"); +``` + +_Note: Examples in this readme assume you are using the `Usergrid` shared instance. If you've implemented the instance pattern instead, simply replace `Usergrid` with your client instance variable._ + +## RESTful operations + +When making any RESTful call, a `type` parameter (or `path`) is always required. Whether you specify this as an argument or in an object as a parameter is up to you. + +### GET + +- To get entities in a collection: + +```java +UsergridResponse response = Usergrid.GET("collection"); +List<UsergridEntity> entities = response.getEntities(); +``` + +- To get a specific entity in a collection by uuid or name: + +```java +UsergridResponse response = Usergrid.GET("collection","<uuid-or-name>"); +UsergridEntity entities = response.entity(); +``` + +- To get specific entities in a collection by passing a `UsergridQuery` object: + +```java +UsergridQuery query = new UsergridQuery("cats").gt("weight", 2.4) + .contains("color", "bl*") + .not() + .eq("color", "blue") + .or() + .eq("color", "orange"); + +// this will build out the following query: +// select * where weight > 2.4 and color contains 'bl*' and not color = 'blue' or color = 'orange' + +UsergridResponse response = Usergrid.GET(query); +List<UsergridEntity> entities = response.getEntities(); +``` + +### POST and PUT + +POST and PUT requests both require a JSON body payload. You can pass either a Java object or a `UsergridEntity` instance. While the former works in principle, best practise is to use a `UsergridEntity` wherever practical. When an entity has a uuid or name property and already exists on the server, use a PUT request to update it. If it does not, use POST to create it. + +- To create a new entity in a collection (**POST**): + +```java +HashMap<String,String> propertyMap = new HashMap<>(); +propertyMap.put("cuisine","pizza"); +UsergridEntity entity = new UsergridEntity("restaurant","Dino's Deep Dish", propertyMap); +Usergrid.POST(entity); // entity should now have a uuid property and be created + +// you can also POST an array of entities: + +HashMap<String,String> propertyMap = new HashMap<>(); +propertyMap.put("cuisine","pizza"); + +ArrayList<UsergridEntity> entities = new ArrayList<>(); +entities.add(new UsergridEntity("restaurant","Dino's Deep Dish", propertyMap)); +entities.add(new UsergridEntity("restaurant","Pizza da Napoli", propertyMap)); +UsergridResponse response = Usergrid.POST(entities); +List<UsergridEntity> responseEntities = response.getEntities(); // responseEntities should now contain now valid posted entities. +``` + +- To update an entity in a collection (**PUT**): + +```java +HashMap<String,String> propertyMap = new HashMap<>(); +propertyMap.put("cuisine","pizza"); +UsergridEntity entity = new UsergridEntity("restaurant","Dino's Deep Dish", propertyMap); +UsergridResponse response = Usergrid.POST(entity); +if( response.ok() ) { + entity.putProperty("owner","Mia Carrara"); + Usergrid.PUT(entity); // entity now has the property 'owner' +} + +// or update a set of entities by passing a UsergridQuery object + +HashMap<String,String> propertiesToUpdate = new HashMap<>(); +propertiesToUpdate.put("cuisine","pizza"); +UsergridQuery query = new UsergridQuery("restaurants").eq("cuisine","italian"); + +UsergridResponse response = Usergrid.PUT(query, propertiesToUpdate); + + /* the first 10 entities matching this query criteria will be updated: + e.g.: + [ + { + "type": "restaurant", + "restaurant": "Il Tarazzo", + "cuisine": "italian", + "keywords": ["pasta"] + }, + { + "type": "restaurant", + "restaurant": "Cono Sur Pizza & Pasta", + "cuisine": "italian", + "keywords": ["pasta"] + } + ] + */ +``` + +### DELETE + +DELETE requests require either a specific entity or a `UsergridQuery` object to be passed as an argument. + +- To delete a specific entity in a collection by uuid or name: + +```java +UsergridResponse response = Usergrid.DELETE("collection", "<uuid-or-name>"); // if successful, entity will now be deleted +``` + +- To specific entities in a collection to delete by passing a `UsergridQuery` object: + +```java +UsergridQuery query = new UsergridQuery("cats").eq("color","black").or().eq("color","white"); + +// this will build out the following query: +// select * where color = 'black' or color = 'white' + +UsergridResponse response = Usergrid.DELETE(query); // the first 10 entities matching this query criteria will be deleted +``` + +## Entity operations and convenience methods + +`UsergridEntity` has a number of helper/convenience methods to make working with entities more convenient. + +### reload() + +Reloads the entity from the server: + +```java +entity.reload(); // entity is now reloaded from the server +``` + +### save() + +Saves (or creates) the entity on the server: + + +```java +entity.putProperty("aNewProperty","A new value"); +entity.save(); // entity is now updated on the server +``` + +### remove() + +Deletes the entity from the server: + +```java +entity.remove(); // entity is now deleted on the server and the local instance should be destroyed +``` + +## Authentication, current user, and auth-fallback + +### appAuth and authenticateApp() + +`Usergrid` can use the app client ID and secret that were passed upon initialization and automatically retrieve an app-level token for these credentials. + +```java +Usergrid.setAppAuth(new UsergridAppAuth("<client-id>", "<client-secret>")); +Usergrid.authenticateApp(); // Usergrid.appAuth is authenticated automatically when this call is successful +``` + +### currentUser, userAuth, and authenticateUser() + +`Usergrid` has a special `currentUser` property. + +By default, when calling `authenticateUser()`, `.currentUser` will be set to this user if the authentication flow is successful. + +```java +UsergridUserAuth userAuth = new UsergridUserAuth("<username>","<password>"); +Usergrid.authenticateUser(userAuth); // Usergrid.currentUser is set to the authenticated user and the token is stored within that context +``` + +If you want to utilize authenticateUser without setting as the current user, simply pass a `false` boolean value as the second parameter: + +```java +UsergridUserAuth userAuth = new UsergridUserAuth("<username>","<password>"); +Usergrid.authenticateUser(userAuth,false); // user is authenticated but Usergrid.currentUser is not set. +``` + +### authMode + +Auth-mode defines what the client should pass in for the authorization header. + +By default, `Usergrid.authMode` is set to `.User`, when a `Usergrid.currentUser` is present and authenticated, an API call will be performed using the token for the user. + +If `Usergrid.authMode` is set to `.None`, all API calls will be performed unauthenticated. + +If instead `Usergrid.authMode` is set to `.App`, the API call will instead be performed using client credentials, _if_ they're available (i.e. `authenticateApp()` was performed at some point). + +### usingAuth() + +At times it is desireable to have complete, granular control over the authentication context of an API call. + +To facilitate this, the passthrough function `.usingAuth()` allows you to pre-define the auth context of the next API call. + +```java +// assume Usergrid.authMode = UsergridAuthMode.NONE. + +Map<String, String> permissionsMap = new HashMap<>(); +permissionsMap.put("permission","get,post,put,delete:/**"); +UsergridResponse response = Usergrid.usingAuth(Usergrid.getAppAuth()).POST("roles/guest/permissions",permissionsMap); + +// here we've temporarily used the client credentials to modify permissions +// subsequent calls will not use this auth context +``` + +## User operations and convenience methods + +`UsergridUser` has a number of helper/convenience methods to make working with user entities more convenient. If you are _not_ utilizing the `Usergrid` shared instance, you must pass an instance of `UsergridClient` as the first argument to any of these helper methods. + +### create() + +Creating a new user: + +```java +UsergridUser user = new UsergridUser("username","password"); +user.create(); // user has now been created and should have a valid uuid +``` + +### login() + +A simpler means of retrieving a user-level token: + +```java +user.login("username","password"); // user is now logged in +``` + +### logout() + +Logs out the selected user. You can also use this convenience method on `Usergrid.currentUser`. + +```java +user.logout(); // user is now logged out +``` + +### resetPassword() + +Resets the password for the selected user. + +```java +// if it was done correctly, the new password will be changed +user.resetPassword("oldPassword", "newPassword"); +``` + +### UsergridUser.CheckAvailable() + +This is a class (static) method that allows you to check whether a username or email address is available or not. + +```java +boolean available = UsergridUser.checkAvailable("email", null); // 'available' == whether an email already exists for a user + +available = UsergridUser.checkAvailable(null, "username"); // 'available' == whether an username already exists for a user + +available = UsergridUser.checkAvailable("email", "username"); // 'available' == whether an email or username already exist for a user +``` + +## Querying and filtering data + +### UsergridQuery initialization + +The `UsergridQuery` class allows you to build out complex query filters using the Usergrid [query syntax](http://docs.apigee.com/app-services/content/querying-your-data). + +The first parameter of the `UsergridQuery` builder pattern should be the collection (or type) you intend to query. You can either pass this as an argument, or as the first builder object: + +```java +UsergridQuery query = new UsergridQuery("cats"); +// or +UsergridQuery query = new UsergridQuery().collection("cats"); +``` + +You then can layer on additional queries: + +```java +UsergridQuery query = new UsergridQuery("cats").gt("weight",2.4).contains("color","bl*") + .not() + .eq("color","white") + .or() + .eq("color","orange"); +``` + +You can also adjust the number of results returned: + +```java +UsergridQuery query = new UsergridQuery("cats").eq("color","black").limit(100); + +// returns a maximum of 100 entities +``` + +And sort the results: + +```java +UsergridQuery query = new UsergridQuery("cats").eq("color","black").limit(100).asc("name") + +// sorts by 'name', ascending +``` + +And you can do geo-location queries: + +```java +UsergridQuery query = new UsergridQuery("devices").locationWithin(<distance>, <lat>, <long>); +``` + +### Using a query in a request + +Queries can be passed as parameters to GET, PUT, and DELETE requests: + +```java +// Gets entities matching the query. +Usergrid.GET(query); + +// Updates the entities matching the query with the new property. +Usergrid.PUT(query, Collections.singletonMap("aNewProperty","A new value")); + +// Deletes entities of a given type matching the query. +Usergrid.DELETE(query); +``` +### List of query builder objects + +`type("string")` + +> The collection name to query + +`collection("string")` + +> An alias for `type` + +`eq("key","value")` or +`equals("key","value")` or +`filter("key","value")` + +> Equal to (e.g. `where color = 'black'`) + +`contains("key","value")` or +`containsString("key","value")` or +`containsWord("key","value")` + +> Contains a string (e.g.` where color contains 'bl*'`) + +`gt("key","value")` or +`greaterThan("key","value")` + +> Greater than (e.g. `where weight > 2.4`) + +`gte("key","value")` or +`greaterThanOrEqual("key","value")` + +> Greater than or equal to (e.g. `where weight >= 2.4`) + +`lt("key","value")` or `lessThan("key","value")` + +> Less than (e.g. `where weight < 2.4`) + +`lte("key","value")` or `lessThanOrEqual("key","value")` + +> Less than or equal to (e.g. `where weight <= 2.4`) + +`not()` + +> Negates the next block in the builder pattern, e.g.: + +```java +UsergridQuery query = new UsergridQuery("cats").not().eq("color","black"); +// select * from cats where not color = 'black' +``` + +`and()` + +> Joins two queries by requiring both of them. `and` is also implied when joining two queries _without_ an operator. E.g.: + +```java +UsergridQuery query = new UsergridQuery("cats").eq("color","black").eq("fur","longHair"); +// is identical to: +UsergridQuery query = new UsergridQuery("cats").eq("color","black").and().eq("fur","longHair"); +``` + +`or()` + +> Joins two queries by requiring only one of them. `or` is never implied. e.g.: + +```java +UsergridQuery query = new UsergridQuery("cats").eq("color","black").or().eq("color", "white"); +``` + +> When using `or()` and `and()` operators, `and()` joins will take precedence over `or()` joins. You can read more about query operators and precedence [here](http://docs.apigee.com/api-baas/content/supported-query-operators-data-types). + +`locationWithin(distanceInMeters, latitude, longitude)` + +> Returns entities which have a location within the specified radius. Arguments can be `float` or `int`. + +`asc("key")` or `ascending("key")` + +> Sorts the results by the specified property, ascending + +`desc("key")` or `descending("key")` + +> Sorts the results by the specified property, descending + +`sort("key",UsergridQuerySortOrder.ASC)` + +> Sorts the results by the specified property, in the specified `UsergridQuerySortOrder` (`.ASC` or `.DESC`). + +`limit(int)` + +> The maximum number of entities to return + +`cursor("string")` + +> A pagination cursor string + +`fromString("query string")` + +> A special builder property that allows you to input a pre-defined query string. All builder properties will be ignored when this property is defined. For example: + +```java +UsergridQuery query = new UsergridQuery().fromString("select * where color = 'black' order by name asc"); +``` + +## UsergridResponse object + +`UsergridResponse` is the core class that handles both successful and unsuccessful HTTP responses from Usergrid. + +If a request is successful, any entities returned in the response will be automatically parsed into `UsergridEntity` objects and pushed to the `entities` property. + +If a request fails, the `error` property will contain information about the problem encountered. + +### ok + +You can check `UsergridResponse.ok`, a `Bool` value, to see if the response was successful. Any status code `< 400` returns true. + +```java +UsergridResponse response = Usergrid.GET("collection"); +if( response.ok() ) { + // woo! +} +``` + +### entity, entities, user, users, first, last + +Depending on the call you make, any entities returned in the response will be automatically parsed into `UsergridEntity` objects and pushed to the `entities` property. If you're querying the `users` collection, these will also be `UsergridUser` objects, a subclass of `UsergridEntity`. + +- `.first()` returns the first entity in an array of entities; `.entity()` is an alias to `.first()`. If there are no entities, both of these will be undefined. + +- `.last()` returns the last entity in an array of entities; if there is only one entity in the array, this will be the same as `.first()` _and_ `.entity()`, and will be undefined if there are no entities in the response. + +- `.getEntities()` will either be an array of entities in the response, or an empty array. + +- `.user()` is a special alias for `.entity()` for when querying the `users()` collection. Instead of being a `UsergridEntity`, it will be its subclass, `UsergridUser`. + +- `.users()` is the same as `.user()`, though behaves as `.getEntities()` does by returning either an array of UsergridUser objects or an empty array. + +Examples: + +```java +UsergridResponse response = Usergrid.GET("collection"); + // you can access: + // response.getEntities() (the returned entities) + // response.first() (the first entity) + // response.entity() (same as response.first) + // response.last() (the last entity returned) + +UsergridResponse response = Usergrid.GET("collection","<uuid-or-name>"); + // you can access: + // response.entity() (the returned entity) + // response.getEntities() (containing only the returned entity) + // response.first() (same as response.entity) + // response.last() (same as response.entity) + +UsergridResponse response = Usergrid.GET("users"); + // you can access: + // response.users() (the returned users) + // response.getEntities() (same as response.users) + // response.user() (the first user) + // response.entity() (same as response.user) + // response.first() (same as response.user) + // response.last() (the last user) + +UsergridResponse response = Usergrid.GET("users","<uuid-or-name>"); + // you can access; + // response.users() (containing only the one user) + // response.getEntities() (same as response.users) + // response.user() (the returned user) + // response.entity() (same as response.user) + // response.first() (same as response.user) + // response.last() (same as response.user) +``` + +## Connections + +Connections can be managed using `Usergrid.connect()`, `Usergrid.disconnect()`, and `Usergrid.getConnections()`, or entity convenience methods of the same name. + +When retrieving connections via `Usergrid.getConnections()`, you can pass in a optional `UsergridQuery` object in order to filter the connectioned entities returned. + +### Connect + +Create a connection between two entities: + +```java +Usergrid.connect(entity1, "relationship", entity2); // entity1 now has an outbound connection to entity2 +``` + +### Retrieve Connections + +Retrieve outbound connections: + +```java +Usergrid.getConnections(UsergridDirection.OUT, entity1, "relationship"); + // entities is an array of entities that entity1 is connected to via 'relationship' + // in this case, we'll see entity2 in the array +``` + +Retrieve inbound connections: + +```java +Usergrid.getConnections(UsergridDirection.IN, entity2, "relationship"); + // entities is an array of entities that connect to entity2 via 'relationship' + // in this case, we'll see entity1 in the array +``` + +### Disconnect + +Delete a connection between two entities: + +```java +Usergrid.disconnect(entity1, "relationship", entity2); + // entity1's outbound connection to entity2 has been destroyed +``` + +## Custom UsergridEntity Subclasses + +Creating custom subclasses of the base `UsergridEntity` class (just like `UsergridUser` and `UsergridDevice`) is possible. + +- To do so, subclass `UsergridEntity` and implement the required methods: + +```java +public class ActivityEntity extends UsergridEntity { + public static final String ACTIVITY_ENTITY_TYPE = "activity"; + + public ActivityEntity(){ + super(ACTIVITY_ENTITY_TYPE); + } +} +``` +- You will also need to register the custom subclass: + +```java +Usergrid.initSharedInstance("orgId","appId"); +UsergridEntity.mapCustomSubclassToType("activity", ActivityEntity.class); +``` + +By registering your custom subclass, the `UsergridEntity` and `UsergridResponse` classes are able to generate instances of these classes based on the an entities `type`. + +In the above example, entities which have a `type` value of `activity` can now be cast as `ActivityEntity` objects. e.g.: + +```java +UsergridResponse response = Usergrid.GET("activity"); +ActivityEntity activityEntity = (ActivityEntity)response.entity(); +``` http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/pom.xml ---------------------------------------------------------------------- diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..a4bb6dc --- /dev/null +++ b/pom.xml @@ -0,0 +1,127 @@ +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <bundle.symbolicName>org.apache.usergrid</bundle.symbolicName> + <bundle.namespace>org.apache.usergrid</bundle.namespace> + <jackson-version>2.7.3</jackson-version> + <junit-version>4.11</junit-version> + <okhttp-version>3.2.0</okhttp-version> + <intellij-annotations-version>9.0.4</intellij-annotations-version> + </properties> + + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.usergrid</groupId> + <artifactId>usergrid-java-client</artifactId> + <version>2.2.0-SNAPSHOT</version> + <packaging>jar</packaging> + <description>A Java client for Usergrid</description> + <url>http://usergrid.apache.org</url> + + <licenses> + <license> + <name>The Apache Software License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> + <distribution>repo</distribution> + </license> + </licenses> + + <developers> + <developer> + <id>eanuff</id> + <name>Ed Anuff</name> + </developer> + <developer> + <id>tnine</id> + <name>Todd Nine</name> + </developer> + <developer> + <id>sganyo</id> + <name>Scott Ganyo</name> + </developer> + <developer> + <id>jwest</id> + <name>Jeffrey West</name> + </developer> + <developer> + <id>adastagiri</id> + <name>Ayesha Dastagiri</name> + </developer> + <developer> + <id>rwalsh</id> + <name>Robert Walsh</name> + </developer> + </developers> + + <build> + <plugins> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.9.1</version> + <configuration> + <doclet>com.sun.tools.doclets.standard.Standard</doclet> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.3</version> + <configuration> + <source>1.7</source> + <target>1.7</target> + </configuration> + </plugin> + </plugins> + </build> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit-version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-core</artifactId> + <version>${jackson-version}</version> + </dependency> + + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-annotations</artifactId> + <version>${jackson-version}</version> + </dependency> + + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + <version>${jackson-version}</version> + </dependency> + + <dependency> + <groupId>com.squareup.okhttp3</groupId> + <artifactId>okhttp</artifactId> + <version>${okhttp-version}</version> + </dependency> + + <dependency> + <groupId>com.intellij</groupId> + <artifactId>annotations</artifactId> + <version>${intellij-annotations-version}</version> + </dependency> + </dependencies> + <name>Apache Usergrid Java SDK</name> + <organization> + <name>The Apache Software Foundation</name> + <url>http://apache.org</url> + </organization> + <issueManagement> + <system>JIRA</system> + <url>https://issues.apache.org/jira/browse/USERGRID</url> + </issueManagement> +</project> \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/src/main/java/org/apache/usergrid/java/client/Usergrid.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/usergrid/java/client/Usergrid.java b/src/main/java/org/apache/usergrid/java/client/Usergrid.java new file mode 100644 index 0000000..f7cd545 --- /dev/null +++ b/src/main/java/org/apache/usergrid/java/client/Usergrid.java @@ -0,0 +1,285 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.apache.usergrid.java.client; + +import org.apache.usergrid.java.client.UsergridEnums.UsergridAuthMode; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.auth.UsergridAuth; +import org.apache.usergrid.java.client.auth.UsergridUserAuth; +import org.apache.usergrid.java.client.model.*; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.apache.usergrid.java.client.UsergridEnums.UsergridDirection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; + +@SuppressWarnings("unused") +public final class Usergrid { + @NotNull public static final String UsergridSDKVersion = "2.1.0"; + + private static UsergridClient sharedClient; + private Usergrid() { /** Private constructor because we only have static methods. **/ } + + public static boolean isInitialized() { + return (Usergrid.sharedClient != null); + } + public static void reset() { Usergrid.sharedClient = null; } + + @NotNull + public static UsergridClient getInstance() throws NullPointerException { + if (!Usergrid.isInitialized()) { + throw new NullPointerException("Shared client has not been initialized!"); + } + return Usergrid.sharedClient; + } + + @NotNull + public static UsergridClient initSharedInstance(@NotNull final UsergridClientConfig config) { + if (Usergrid.isInitialized()) { + System.out.print("The Usergrid shared instance was already initialized. All subsequent initialization attempts (including this) will be ignored."); + } else { + Usergrid.sharedClient = new UsergridClient(config); + } + return Usergrid.sharedClient; + } + + @NotNull + public static UsergridClient initSharedInstance(@NotNull final String orgId, @NotNull final String appId) { + return Usergrid.initSharedInstance(new UsergridClientConfig(orgId, appId)); + } + + @NotNull + public static UsergridClient initSharedInstance(@NotNull final String orgId, @NotNull final String appId, @NotNull final String baseUrl) { + return Usergrid.initSharedInstance(new UsergridClientConfig(orgId, appId, baseUrl)); + } + + @NotNull + public static UsergridClient initSharedInstance(@NotNull final String orgId, @NotNull final String appId, @NotNull final String baseUrl, @NotNull final UsergridAuthMode authMode) { + return Usergrid.initSharedInstance(new UsergridClientConfig(orgId, appId, baseUrl, authMode)); + } + + @NotNull public static UsergridClientConfig getConfig() { return Usergrid.getInstance().getConfig(); } + public static void setConfig(@NotNull UsergridClientConfig config) { Usergrid.getInstance().setConfig(config); } + + @NotNull public static String getAppId() { return Usergrid.getInstance().getAppId(); } + public static void setAppId(@NotNull String appId) { Usergrid.getInstance().setAppId(appId); } + + @NotNull public static String getOrgId() { return Usergrid.getInstance().getOrgId(); } + public static void setOrgId(@NotNull String orgId) { Usergrid.getInstance().setOrgId(orgId); } + + @NotNull public static String getBaseUrl() { return Usergrid.getInstance().getBaseUrl(); } + public static void setBaseUrl(@NotNull String baseUrl) { Usergrid.getInstance().setBaseUrl(baseUrl); } + + @NotNull public static String clientAppUrl() { return Usergrid.getInstance().clientAppUrl(); } + + @NotNull public static UsergridAuthMode getAuthMode() { return Usergrid.getInstance().getAuthMode(); } + public static void setAuthMode(@NotNull final UsergridAuthMode authMode) { Usergrid.getInstance().setAuthMode(authMode); } + + @Nullable public static UsergridAppAuth getAppAuth() { return Usergrid.getInstance().getAppAuth(); } + public static void setAppAuth(@Nullable final UsergridAppAuth appAuth) { Usergrid.getInstance().setAppAuth(appAuth); } + + @Nullable public static UsergridUser getCurrentUser() { return Usergrid.getInstance().getCurrentUser(); } + public static void setCurrentUser(@Nullable final UsergridUser currentUser) { Usergrid.getInstance().setCurrentUser(currentUser); } + + @Nullable + public static UsergridAuth authForRequests() { + return Usergrid.getInstance().authForRequests(); + } + + @NotNull + public static UsergridClient usingAuth(@NotNull final UsergridAuth auth) { + return Usergrid.getInstance().usingAuth(auth); + } + + @NotNull + public static UsergridClient usingToken(@NotNull final String accessToken) { + return Usergrid.getInstance().usingToken(accessToken); + } + + @NotNull + public static UsergridResponse resetPassword(@NotNull final UsergridUser user, @NotNull final String oldPassword, @NotNull final String newPassword) { + return Usergrid.getInstance().resetPassword(user, oldPassword, newPassword); + } + + @NotNull + public static UsergridResponse authenticateApp() { + return Usergrid.getInstance().authenticateApp(); + } + + @NotNull + public static UsergridResponse authenticateApp(@NotNull final UsergridAppAuth appAuth) { + return Usergrid.getInstance().authenticateApp(appAuth); + } + + @NotNull + public static UsergridResponse authenticateUser(@NotNull final UsergridUserAuth userAuth) { + return Usergrid.getInstance().authenticateUser(userAuth); + } + + @NotNull + public static UsergridResponse authenticateUser(@NotNull final UsergridUserAuth userAuth, final boolean setAsCurrentUser) { + return Usergrid.getInstance().authenticateUser(userAuth,setAsCurrentUser); + } + + @NotNull + public static UsergridResponse logoutCurrentUser() { + return Usergrid.getInstance().logoutCurrentUser(); + } + + @NotNull + public static UsergridResponse logoutUserAllTokens(@NotNull final String uuidOrUsername) { + return Usergrid.getInstance().logoutUserAllTokens(uuidOrUsername); + } + + @NotNull + public static UsergridResponse logoutUser(@NotNull final String uuidOrUsername, @Nullable final String token) { + return Usergrid.getInstance().logoutUser(uuidOrUsername,token); + } + + @NotNull + public static UsergridResponse sendRequest(@NotNull final UsergridRequest request) { + return Usergrid.getInstance().sendRequest(request); + } + + @NotNull + public static UsergridResponse GET(@NotNull final String type, @NotNull final String uuidOrName) { + return Usergrid.getInstance().GET(type, uuidOrName); + } + + @NotNull + public static UsergridResponse GET(@NotNull final String type) { + return Usergrid.getInstance().GET(type); + } + + @NotNull + public static UsergridResponse GET(@NotNull final UsergridQuery query) { + return Usergrid.getInstance().GET(query); + } + + @NotNull + public static UsergridResponse PUT(@NotNull final String type, @NotNull final String uuidOrName, @NotNull final Map<String, ?> jsonBody) { + return Usergrid.getInstance().PUT(type, uuidOrName, jsonBody); + } + + @NotNull + public static UsergridResponse PUT(@NotNull final String type, @NotNull final Map<String, ?> jsonBody) { + return Usergrid.getInstance().PUT(type, jsonBody); + } + + @NotNull + public static UsergridResponse PUT(@NotNull final UsergridEntity entity) { + return Usergrid.getInstance().PUT(entity); + } + + @NotNull + public static UsergridResponse PUT(@NotNull final UsergridQuery query, @NotNull final Map<String, ?> jsonBody) { + return Usergrid.getInstance().PUT(query, jsonBody); + } + + @NotNull + public static UsergridResponse POST(@NotNull final String type, @NotNull final String uuidOrName, @NotNull final Map<String, Object> jsonBody) { + return Usergrid.getInstance().POST(type, uuidOrName, jsonBody); + } + + @NotNull + public static UsergridResponse POST(@NotNull final String type, @NotNull final Map<String, ?> jsonBody) { + return Usergrid.getInstance().POST(type, jsonBody); + } + + @NotNull + public static UsergridResponse POST(@NotNull final String type, @NotNull final List<Map<String, ?>> jsonBodies) { + return Usergrid.getInstance().POST(type, jsonBodies); + } + + @NotNull + public static UsergridResponse POST(@NotNull final UsergridEntity entity) throws NullPointerException { + return Usergrid.getInstance().POST(entity); + } + + @NotNull + public static UsergridResponse POST(@NotNull final List<UsergridEntity> entities) { + return Usergrid.getInstance().POST(entities); + } + + @NotNull + public static UsergridResponse DELETE(@NotNull final String type, @NotNull final String uuidOrName) { + return Usergrid.getInstance().DELETE(type, uuidOrName); + } + + @NotNull + public static UsergridResponse DELETE(@NotNull final UsergridEntity entity) { + return Usergrid.getInstance().DELETE(entity); + } + + @NotNull + public static UsergridResponse DELETE(@NotNull final UsergridQuery query) { + return Usergrid.getInstance().DELETE(query); + } + + @NotNull + public static UsergridResponse connect(@NotNull final UsergridEntity entity, @NotNull final String relationship, @NotNull final UsergridEntity to) { + return Usergrid.getInstance().connect(entity, relationship, to); + } + + @NotNull + public static UsergridResponse connect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String fromUuid) { + return Usergrid.getInstance().connect(entityType,entityId,relationship,fromUuid); + } + + @NotNull + public static UsergridResponse connect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String toType, @NotNull final String toName) { + return Usergrid.getInstance().connect(entityType,entityId,relationship,toType,toName); + } + + @NotNull + public static UsergridResponse disconnect(@NotNull final UsergridEntity entity, @NotNull final String relationship, @NotNull final UsergridEntity from) { + return Usergrid.getInstance().disconnect(entity, relationship, from); + } + + @NotNull + public static UsergridResponse disconnect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String fromUuid) { + return Usergrid.getInstance().disconnect(entityType, entityId, relationship, fromUuid); + } + + @NotNull + public static UsergridResponse disconnect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String fromType, @NotNull final String fromName) { + return Usergrid.getInstance().disconnect(entityType, entityId, relationship, fromType, fromName); + } + + @NotNull + public static UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final UsergridEntity entity, @NotNull final String relationship) { + return Usergrid.getInstance().getConnections(direction, entity, relationship); + } + + @NotNull + public static UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final UsergridEntity entity, @NotNull final String relationship, @Nullable final UsergridQuery query) { + return Usergrid.getInstance().getConnections(direction, entity, relationship, query); + } + + @NotNull + public static UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final String type, @NotNull final String uuidOrName, @NotNull final String relationship, @Nullable final UsergridQuery query) { + return Usergrid.getInstance().getConnections(direction,type,uuidOrName,relationship,query); + } + + @NotNull + public static UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final String uuid, @NotNull final String relationship, @Nullable final UsergridQuery query) { + return Usergrid.getInstance().getConnections(direction, uuid, relationship, query); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/src/main/java/org/apache/usergrid/java/client/UsergridClient.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/usergrid/java/client/UsergridClient.java b/src/main/java/org/apache/usergrid/java/client/UsergridClient.java new file mode 100644 index 0000000..a317d07 --- /dev/null +++ b/src/main/java/org/apache/usergrid/java/client/UsergridClient.java @@ -0,0 +1,429 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.apache.usergrid.java.client; + +import org.apache.usergrid.java.client.UsergridEnums.*; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.apache.usergrid.java.client.auth.UsergridAuth; +import org.apache.usergrid.java.client.auth.UsergridUserAuth; +import org.apache.usergrid.java.client.model.*; +import org.apache.usergrid.java.client.query.UsergridQuery; +import org.apache.usergrid.java.client.response.UsergridResponse; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@SuppressWarnings("unused") +public class UsergridClient { + + @NotNull public static String DEFAULT_BASE_URL = "https://api.usergrid.com"; + + @NotNull private UsergridClientConfig config; + @Nullable private UsergridUser currentUser = null; + @Nullable private UsergridAuth tempAuth = null; + + @NotNull private final UsergridRequestManager requestManager; + + public UsergridClient(@NotNull final UsergridClientConfig config) { + this.config = config; + this.requestManager = new UsergridRequestManager(this); + } + + public UsergridClient(@NotNull final String orgId, @NotNull final String appId) { + this(new UsergridClientConfig(orgId, appId)); + } + + public UsergridClient(@NotNull final String orgId, @NotNull final String appId, @NotNull final String baseUrl) { + this(new UsergridClientConfig(orgId, appId, baseUrl)); + } + + public UsergridClient(@NotNull final String orgId, @NotNull final String appId, @NotNull final String baseUrl, @NotNull final UsergridAuthMode authMode) { + this(new UsergridClientConfig(orgId, appId, baseUrl, authMode)); + } + + @NotNull public UsergridClientConfig getConfig() { return this.config; } + public void setConfig(@NotNull final UsergridClientConfig config) { this.config = config; } + + @NotNull public String getAppId() { return this.config.appId; } + public void setAppId(@NotNull final String appId) { this.config.appId = appId; } + + @NotNull public String getOrgId() { return this.config.orgId; } + public void setOrgId(@NotNull final String orgId) { this.config.orgId = orgId; } + + @NotNull public String getBaseUrl() { return this.config.baseUrl; } + public void setBaseUrl(@NotNull final String baseUrl) { this.config.baseUrl = baseUrl; } + + @NotNull public String clientAppUrl() { return getBaseUrl() + "/" + getOrgId() + "/" + getAppId(); } + + @NotNull public String managementUrl() { return getBaseUrl() + "/management"; } + + @NotNull public UsergridAuthMode getAuthMode() { return this.config.authMode; } + public void setAuthMode(@NotNull final UsergridAuthMode authMode) { this.config.authMode = authMode; } + + @Nullable public UsergridUser getCurrentUser() { return this.currentUser; } + public void setCurrentUser(@Nullable final UsergridUser currentUser) { this.currentUser = currentUser; } + + @Nullable public UsergridUserAuth getUserAuth() { return (this.currentUser != null) ? this.currentUser.getUserAuth() : null; } + + @Nullable public UsergridAppAuth getAppAuth() { return this.config.appAuth; } + public void setAppAuth(@Nullable final UsergridAppAuth appAuth) { this.config.appAuth = appAuth; } + + @Nullable + public UsergridAuth authForRequests() { + UsergridAuth authForRequests = null; + if (tempAuth != null) { + if (tempAuth.isValidToken()) { + authForRequests = tempAuth; + } + tempAuth = null; + } else { + switch (config.authMode) { + case USER: { + if (this.currentUser != null && this.currentUser.getUserAuth() != null && this.currentUser.getUserAuth().isValidToken()) { + authForRequests = this.currentUser.getUserAuth(); + } + break; + } + case APP: { + if (this.config.appAuth != null && this.config.appAuth.isValidToken()) { + authForRequests = this.config.appAuth; + } + break; + } + } + } + return authForRequests; + } + + @NotNull + public UsergridClient usingAuth(@Nullable final UsergridAuth auth) { + this.tempAuth = auth; + return this; + } + + @NotNull + public UsergridClient usingToken(@NotNull final String accessToken) { + this.tempAuth = new UsergridAuth(accessToken); + return this; + } + + @NotNull + public UsergridResponse authenticateApp() { + if( this.config.appAuth == null ) { + return UsergridResponse.fromError(this, "Invalid UsergridAppAuth.", "UsergridClient's appAuth is null."); + } + return this.authenticateApp(this.config.appAuth); + } + + @NotNull + public UsergridResponse authenticateApp(@NotNull final UsergridAppAuth auth) { + this.config.appAuth = auth; + return this.requestManager.authenticateApp(auth); + } + + @NotNull + public UsergridResponse authenticateUser(@NotNull final UsergridUserAuth userAuth) { + return this.authenticateUser(userAuth,true); + } + + @NotNull + public UsergridResponse authenticateUser(@NotNull final UsergridUserAuth userAuth, final boolean setAsCurrentUser) { + UsergridResponse response = this.requestManager.authenticateUser(userAuth); + if( response.ok() && setAsCurrentUser ) { + this.setCurrentUser(response.user()); + } + return response; + } + + @NotNull + public UsergridResponse resetPassword(@NotNull final UsergridUser user, @NotNull final String oldPassword, @NotNull final String newPassword) { + String usernameOrEmail = user.usernameOrEmail(); + if( usernameOrEmail == null ) { + return UsergridResponse.fromError(this, "Error resetting password.", "The UsergridUser object must contain a valid username or email to reset the password."); + } + Map<String, Object> data = new HashMap<>(); + data.put("newpassword", newPassword); + data.put("oldpassword", oldPassword); + String[] pathSegments = { "users", usernameOrEmail, "password"}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, data, this.authForRequests() ,pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse logoutCurrentUser() { + UsergridUser currentUser = this.currentUser; + if( currentUser != null ) { + String uuidOrUsername = currentUser.uuidOrUsername(); + UsergridUserAuth userAuth = currentUser.getUserAuth(); + if( uuidOrUsername != null && userAuth != null ) { + String accessToken = userAuth.getAccessToken(); + if( accessToken != null ) { + return logoutUser(uuidOrUsername, accessToken); + } + } + } + return UsergridResponse.fromError(this,"UsergridClient's currentUser is not valid.", "UsergridClient's currentUser is null or has no uuid or username."); + } + + @NotNull + public UsergridResponse logoutUserAllTokens(@NotNull final String uuidOrUsername) { + return logoutUser(uuidOrUsername, null); + } + + @NotNull + public UsergridResponse logoutUser(@NotNull final String uuidOrUsername, @Nullable final String token){ + String[] pathSegments = {"users", uuidOrUsername, ""}; + int len = pathSegments.length; + Map<String, Object> param = new HashMap<>(); + if(token != null){ + pathSegments[len-1] = "revoketoken"; + param.put("token",token); + } + else{ + pathSegments[len-1] = "revoketokens"; + } + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.PUT, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), param, null, this.authForRequests() , pathSegments); + UsergridResponse response = this.sendRequest(request); + UsergridUser currentUser = this.getCurrentUser(); + if( currentUser != null && response.ok() ) { + if( uuidOrUsername.equalsIgnoreCase(currentUser.uuidOrUsername()) ) { + this.setCurrentUser(null); + } + } + return response; + } + + @NotNull + public UsergridResponse sendRequest(@NotNull final UsergridRequest request) { + return this.requestManager.performRequest(request); + } + + @NotNull + public UsergridResponse GET(@NotNull final String type, @NotNull final String uuidOrName) { + String[] pathSegments = {type, uuidOrName}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.GET, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse GET(@NotNull final String type) { + String[] pathSegments = {type}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.GET, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse GET(@NotNull final UsergridQuery query) { + String collectionName = query.getCollection(); + if( collectionName == null ) { + return UsergridResponse.fromError(this, "Query collection name missing.", "Query collection name is missing."); + } + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.GET, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), query, this.authForRequests() , collectionName); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse PUT(@NotNull final String type, @NotNull final String uuidOrName, @NotNull final Map<String, ?> jsonBody) { + String[] pathSegments = { type, uuidOrName }; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.PUT, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, jsonBody, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse PUT(@NotNull final String type, @NotNull final Map<String, ?> jsonBody) { + String uuidOrName = null; + Object uuid = jsonBody.get(UsergridEntityProperties.UUID.toString()); + if( uuid != null ) { + uuidOrName = uuid.toString(); + } else { + Object name = jsonBody.get(UsergridEntityProperties.NAME.toString()); + if( name != null ) { + uuidOrName = name.toString(); + } + } + if( uuidOrName == null ) { + return UsergridResponse.fromError(this, "jsonBody not valid..", "The `jsonBody` must contain a valid value for either `uuid` or `name`."); + } + String[] pathSegments = { type, uuidOrName }; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.PUT, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, jsonBody, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse PUT(@NotNull final UsergridEntity entity) { + String entityUuidOrName = entity.uuidOrName(); + if( entityUuidOrName == null ) { + return UsergridResponse.fromError(this, "No UUID or name found.", "The entity object must have a `uuid` or `name` assigned."); + } + String[] pathSegments = { entity.getType(), entityUuidOrName }; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.PUT, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, entity, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse PUT(@NotNull final UsergridQuery query, @NotNull final Map<String, ?> jsonBody) { + String collectionName = query.getCollection(); + if( collectionName == null ) { + return UsergridResponse.fromError(this, "Query collection name missing.", "Query collection name is missing."); + } + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.PUT, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, jsonBody, null, query, this.authForRequests(),collectionName); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse POST(final @NotNull UsergridEntity entity) { + String[] pathSegments = {entity.getType()}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, entity, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse POST(@NotNull final List<UsergridEntity> entities) { + if( entities.isEmpty() ) { + return UsergridResponse.fromError(this, "Unable to POST entities.", "entities array is empty."); + } + String[] pathSegments = {entities.get(0).getType()}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, entities, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse POST(@NotNull final String type, @NotNull final String uuidOrName, @NotNull final Map<String, ?> jsonBody) { + String[] pathSegments = {type, uuidOrName}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, jsonBody, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse POST(@NotNull final String type, @NotNull final Map<String, ?> jsonBody) { + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, jsonBody, this.authForRequests() , type); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse POST(@NotNull final String type, @NotNull final List<Map<String, ?>> jsonBodies) { + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), null, jsonBodies, this.authForRequests() , type); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse DELETE(@NotNull final UsergridEntity entity) { + String entityUuidOrName = entity.uuidOrName(); + if( entityUuidOrName == null ) { + return UsergridResponse.fromError(this, "No UUID or name found.", "The entity object must have a `uuid` or `name` assigned."); + } + String[] pathSegments = {entity.getType(), entityUuidOrName}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.DELETE, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse DELETE(@NotNull final String type, @NotNull final String uuidOrName) { + String[] pathSegments = {type, uuidOrName}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.DELETE, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse DELETE(@NotNull final UsergridQuery query) { + String collectionName = query.getCollection(); + if( collectionName == null ) { + return UsergridResponse.fromError(this, "Query collection name missing.", "Query collection name is missing."); + } + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.DELETE, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), query, this.authForRequests() , collectionName); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse connect(@NotNull final UsergridEntity entity, @NotNull final String relationship, @NotNull final UsergridEntity to) { + String entityUuidOrName = entity.uuidOrName(); + String toUuidOrName = to.uuidOrName(); + if( entityUuidOrName == null || toUuidOrName == null ) { + return UsergridResponse.fromError(this, "Invalid Entity Connection Attempt.", "One or both entities that are attempting to be connected do not contain a valid UUID or Name property."); + } + return this.connect(entity.getType(), entityUuidOrName, relationship, to.getType(), toUuidOrName); + } + + @NotNull + public UsergridResponse connect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String toType, @NotNull final String toName) { + String[] pathSegments = {entityType, entityId, relationship, toType, toName}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse connect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String toId) { + String[] pathSegments = { entityType, entityId, relationship, toId}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.POST, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse disconnect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String fromUuid) { + String[] pathSegments = {entityType, entityId, relationship, fromUuid}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.DELETE, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse disconnect(@NotNull final String entityType, @NotNull final String entityId, @NotNull final String relationship, @NotNull final String fromType, @NotNull final String fromName) { + String[] pathSegments = {entityType, entityId, relationship, fromType, fromName}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.DELETE, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse disconnect(@NotNull final UsergridEntity entity, @NotNull final String relationship, @NotNull final UsergridEntity from) { + String entityUuidOrName = entity.uuidOrName(); + String fromUuidOrName = from.uuidOrName(); + if( entityUuidOrName == null || fromUuidOrName == null ) { + return UsergridResponse.fromError(this, "Invalid Entity Disconnect Attempt.", "One or both entities that are attempting to be disconnected do not contain a valid UUID or Name property."); + } + return this.disconnect(entity.getType(), entityUuidOrName, relationship, from.getType(), fromUuidOrName); + } + + @NotNull + public UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final UsergridEntity entity, @NotNull final String relationship) { + return this.getConnections(direction,entity,relationship,null); + } + + @NotNull + public UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final UsergridEntity entity, @NotNull final String relationship, @Nullable final UsergridQuery query) { + String entityUuidOrName = entity.uuidOrName(); + if( entityUuidOrName == null ) { + return UsergridResponse.fromError(this, "Invalid Entity Get Connections Attempt.", "The entity must have a `uuid` or `name` assigned."); + } + return this.getConnections(direction,entity.getType(),entityUuidOrName,relationship,query); + } + + @NotNull + public UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final String type, @NotNull final String uuidOrName, @NotNull final String relationship, @Nullable final UsergridQuery query) { + String[] pathSegments = {type, uuidOrName, direction.connectionValue(), relationship}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.GET, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), query, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } + + @NotNull + public UsergridResponse getConnections(@NotNull final UsergridDirection direction, @NotNull final String uuid, @NotNull final String relationship, @Nullable final UsergridQuery query) { + String[] pathSegments = {uuid, direction.connectionValue(), relationship}; + UsergridRequest request = new UsergridRequest(UsergridHttpMethod.GET, UsergridRequest.APPLICATION_JSON_MEDIA_TYPE, this.clientAppUrl(), query, this.authForRequests() , pathSegments); + return this.sendRequest(request); + } +} http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/src/main/java/org/apache/usergrid/java/client/UsergridClientConfig.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/usergrid/java/client/UsergridClientConfig.java b/src/main/java/org/apache/usergrid/java/client/UsergridClientConfig.java new file mode 100644 index 0000000..f12f9ec --- /dev/null +++ b/src/main/java/org/apache/usergrid/java/client/UsergridClientConfig.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.apache.usergrid.java.client; + +import org.apache.usergrid.java.client.UsergridEnums.UsergridAuthMode; +import org.apache.usergrid.java.client.auth.UsergridAppAuth; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class UsergridClientConfig { + + // The organization identifier. + @NotNull public String orgId; + + // The application identifier. + @NotNull public String appId; + + // The base URL that all calls will be made with. + @NotNull public String baseUrl = UsergridClient.DEFAULT_BASE_URL; + + // The `UsergridAuthMode` value used to determine what type of token will be sent, if any. + @NotNull public UsergridAuthMode authMode = UsergridAuthMode.USER; + + @Nullable public UsergridAppAuth appAuth = null; + + @SuppressWarnings("unused") + private UsergridClientConfig() {} + + public UsergridClientConfig(@NotNull final String orgId, @NotNull final String appId) { + this.orgId = orgId; + this.appId = appId; + } + + public UsergridClientConfig(@NotNull final String orgId, @NotNull final String appId, @NotNull final String baseUrl) { + this.orgId = orgId; + this.appId = appId; + this.baseUrl = baseUrl; + } + + public UsergridClientConfig(@NotNull final String orgId, @NotNull final String appId, @NotNull final String baseUrl, @NotNull final UsergridAuthMode authMode) { + this.orgId = orgId; + this.appId = appId; + this.baseUrl = baseUrl; + this.authMode = authMode; + } +} http://git-wip-us.apache.org/repos/asf/usergrid-java/blob/88039bad/src/main/java/org/apache/usergrid/java/client/UsergridEnums.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/usergrid/java/client/UsergridEnums.java b/src/main/java/org/apache/usergrid/java/client/UsergridEnums.java new file mode 100644 index 0000000..4e2a8b0 --- /dev/null +++ b/src/main/java/org/apache/usergrid/java/client/UsergridEnums.java @@ -0,0 +1,170 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.apache.usergrid.java.client; + +import org.apache.usergrid.java.client.model.UsergridEntity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@SuppressWarnings("unused") +public class UsergridEnums { + public enum UsergridAuthMode { + NONE, + USER, + APP + } + + public enum UsergridDirection { + IN("connecting"), + OUT("connections"); + + @NotNull private final String connectionValue; + + UsergridDirection(@NotNull final String connectionValue) { + this.connectionValue = connectionValue; + } + + @NotNull + public String connectionValue() { + return this.connectionValue; + } + } + + public enum UsergridHttpMethod { + GET, + PUT, + POST, + DELETE; + + @Nullable + public static UsergridHttpMethod fromString(@NotNull final String stringValue) { + try { + return UsergridHttpMethod.valueOf(stringValue.toUpperCase()); + } catch(Exception e) { + return null; + } + } + + @Override @NotNull + public String toString() { + return super.toString().toUpperCase(); + } + } + + public enum UsergridQueryOperator { + EQUAL("="), + GREATER_THAN(">"), + GREATER_THAN_EQUAL_TO(">="), + LESS_THAN("<"), + LESS_THAN_EQUAL_TO("<="); + + @NotNull private final String operatorValue; + + UsergridQueryOperator(@NotNull final String operatorValue) { + this.operatorValue = operatorValue; + } + + @NotNull + public String operatorValue() { + return this.operatorValue; + } + } + + public enum UsergridQuerySortOrder { + ASC, + DESC; + + @Nullable + public static UsergridQuerySortOrder fromString(@NotNull final String stringValue) { + try { + return UsergridQuerySortOrder.valueOf(stringValue.toUpperCase()); + } catch(Exception e) { + return null; + } + } + + @Override @NotNull + public String toString() { + return super.toString().toLowerCase(); + } + } + + public enum UsergridEntityProperties { + TYPE, + UUID, + NAME, + CREATED, + MODIFIED, + LOCATION; + + @Nullable + public static UsergridEntityProperties fromString(@NotNull final String stringValue) { + try { + return UsergridEntityProperties.valueOf(stringValue.toUpperCase()); + } catch(Exception e) { + return null; + } + } + + @Override @NotNull + public String toString() { + return super.toString().toLowerCase(); + } + + public boolean isMutableForEntity(@NotNull final UsergridEntity entity) { + switch(this) { + case LOCATION: { + return true; + } + case NAME: { + return entity.isUser(); + } + case TYPE: + case UUID: + case CREATED: + case MODIFIED: + default: { + return false; + } + } + } + } + + public enum UsergridUserProperties { + NAME, + USERNAME, + PASSWORD, + EMAIL, + ACTIVATED, + DISABLED, + PICTURE; + + @Nullable + public static UsergridUserProperties fromString(@NotNull final String stringValue) { + try { + return UsergridUserProperties.valueOf(stringValue.toUpperCase()); + } catch(Exception e) { + return null; + } + } + + @Override @NotNull + public String toString() { + return super.toString().toLowerCase(); + } + } +}
