├── .github └── workflows │ └── java.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── admin ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── google │ └── firebase │ └── example │ ├── FirebaseAuthSnippets.java │ ├── FirebaseMessagingSnippets.java │ ├── FirebaseRemoteConfigSnippets.java │ └── Main.java ├── build.gradle ├── database ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── google │ └── firebase │ └── example │ └── Main.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.github/workflows/java.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: 4 | - pull_request 5 | - push 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: set up JDK 1.8 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 1.8 16 | - name: Build with Gradle 17 | run: ./gradlew clean build -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .gradle/ 3 | 4 | build/ 5 | 6 | *.class 7 | *.war 8 | *.ear 9 | *.aar 10 | *.iml 11 | 12 | .project 13 | .classpath 14 | .settings -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We'd love for you to contribute to our source code and to make it even better than it is today! Here are the guidelines we'd like you to follow: 4 | 5 | - [Code of Conduct](#coc) 6 | - [Question or Problem?](#question) 7 | - [Issues and Bugs](#issue) 8 | - [Feature Requests](#feature) 9 | - [Submission Guidelines](#submit) 10 | - [Coding Rules](#rules) 11 | - [Signing the CLA](#cla) 12 | 13 | ## Code of Conduct 14 | 15 | As contributors and maintainers of the project, we pledge to respect everyone who contributes by posting issues, updating documentation, submitting pull requests, providing feedback in comments, and any other activities. 16 | 17 | Communication through any of Firebase's channels (GitHub, StackOverflow, Google+, Twitter, etc.) must be constructive and never resort to personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. 18 | 19 | We promise to extend courtesy and respect to everyone involved in this project regardless of gender, gender identity, sexual orientation, disability, age, race, ethnicity, religion, or level of experience. We expect anyone contributing to the project to do the same. 20 | 21 | If any member of the community violates this code of conduct, the maintainers of the project may take action, removing issues, comments, and PRs or blocking accounts as deemed appropriate. 22 | 23 | If you are subject to or witness unacceptable behavior, or have any other concerns, please drop us a line at nivco@google.com. 24 | 25 | ## Got a Question or Problem? 26 | 27 | If you have questions about how to use the project, please direct these to [StackOverflow][stackoverflow] and use the `firebase` tag. We are also available on GitHub issues. 28 | 29 | If you feel that we're missing an important bit of documentation, feel free to 30 | file an issue so we can help. Here's an example to get you started: 31 | 32 | ``` 33 | What are you trying to do or find out more about? 34 | 35 | Where have you looked? 36 | 37 | Where did you expect to find this information? 38 | ``` 39 | 40 | ## Found an Issue? 41 | 42 | If you find a bug in the source code or a mistake in the documentation, you can help us by 43 | submitting an issue on this repository. Even better you can submit a Pull Request 44 | with a fix. 45 | 46 | See [below](#submit) for some guidelines. 47 | 48 | ## Submission Guidelines 49 | 50 | ### Submitting an Issue 51 | 52 | Before you submit your issue search the archive, maybe your question was already answered. 53 | 54 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 55 | Help us to maximize the effort we can spend fixing issues and adding new 56 | features, by not reporting duplicate issues. Providing the following information will increase the 57 | chances of your issue being dealt with quickly: 58 | 59 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 60 | * **Motivation for or Use Case** - explain why this is a bug for you 61 | * **Browsers and Operating System** - is this a problem with all browsers or only IE9? 62 | * **Reproduce the Error** - provide a live example or an unambiguous set of steps. 63 | * **Related Issues** - has a similar issue been reported before? 64 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 65 | causing the problem (line of code or commit) 66 | 67 | **If you get help, help others. Good karma rulez!** 68 | 69 | Here's a template to get you started: 70 | 71 | ``` 72 | System information (OS, Device, etc): 73 | 74 | What steps will reproduce the problem: 75 | 1. 76 | 2. 77 | 3. 78 | 79 | What is the expected result? 80 | 81 | What happens instead of that? 82 | 83 | Code, logs, or screenshot that illustrate the problem: 84 | ``` 85 | 86 | ### Submitting a Pull Request 87 | Before you submit your pull request consider the following guidelines: 88 | 89 | * Search for an open or closed Pull Request 90 | that relates to your submission. You don't want to duplicate effort. 91 | * Please sign our [Contributor License Agreement (CLA)](#cla) before 92 | sending pull requests. We cannot accept code without this. 93 | * Make your changes in a new git branch: 94 | 95 | ```shell 96 | git checkout -b my-fix-branch master 97 | ``` 98 | 99 | * Create your patch, **including appropriate test cases**. 100 | * Follow our [Coding Rules](#rules). 101 | * Commit your changes using a descriptive commit message. 102 | 103 | ```shell 104 | git commit -a 105 | ``` 106 | Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. 107 | 108 | * Build your changes locally to ensure all the tests pass: 109 | 110 | ```shell 111 | gulp 112 | ``` 113 | 114 | * Push your branch to GitHub: 115 | 116 | ```shell 117 | git push origin my-fix-branch 118 | ``` 119 | 120 | * In GitHub, send a pull request to `master`. 121 | * If we suggest changes then: 122 | * Make the required updates. 123 | * Rebase your branch and force push to your GitHub repository (this will update your Pull Request): 124 | 125 | ```shell 126 | git rebase master -i 127 | git push origin my-fix-branch -f 128 | ``` 129 | 130 | That's it! Thank you for your contribution! 131 | 132 | #### After your pull request is merged 133 | 134 | After your pull request is merged, you can safely delete your branch and pull the changes 135 | from the main (upstream) repository: 136 | 137 | * Delete the remote branch on GitHub either through the GitHub UI or your local shell as follows: 138 | 139 | ```shell 140 | git push origin --delete my-fix-branch 141 | ``` 142 | 143 | * Check out the master branch: 144 | 145 | ```shell 146 | git checkout master -f 147 | ``` 148 | 149 | * Delete the local branch: 150 | 151 | ```shell 152 | git branch -D my-fix-branch 153 | ``` 154 | 155 | * Update your master with the latest upstream version: 156 | 157 | ```shell 158 | git pull --ff upstream master 159 | ``` 160 | 161 | ## Coding Rules 162 | 163 | We generally follow [Google's style guides][style-guide]. 164 | 165 | ## Signing the CLA 166 | 167 | Please sign our [Contributor License Agreement][google-cla] (CLA) before sending pull requests. For any code 168 | changes to be accepted, the CLA must be signed. It's a quick process, we promise! 169 | 170 | *This guide was inspired by the [AngularJS contribution guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md).* 171 | 172 | [google-cla]: https://cla.developers.google.com 173 | [style-guide]: http://google.github.io/styleguide/ 174 | [stackoverflow]: http://stackoverflow.com/questions/tagged/firebase -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2017 Google Inc 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | All code in any directories or sub-directories that end with *.html or 205 | *.css is licensed under the Creative Commons Attribution International 206 | 4.0 License, which full text can be found here: 207 | https://creativecommons.org/licenses/by/4.0/legalcode. 208 | 209 | As an exception to this license, all html or css that is generated by 210 | the software at the direction of the user is copyright the user. The 211 | user has full ownership and control over such content, including 212 | whether and how they wish to license it. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Firebase Java Snippets 2 | 3 | This repository holds code snippets used in Java documentation 4 | on [firebase.google.com](https://firebase.google.com/docs/). 5 | 6 | ## Contributing 7 | 8 | We love contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines. 9 | 10 | ## Build Status 11 | [![Actions Status][gh-actions-badge]][gh-actions] 12 | 13 | [gh-actions]: https://github.com/firebase/snippets-java/actions 14 | [gh-actions-badge]: https://github.com/firebase/snippets-java/workflows/Java%20CI/badge.svg -------------------------------------------------------------------------------- /admin/build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.google.firebase.example' 2 | version '1.0' 3 | 4 | apply plugin: 'java' 5 | apply plugin: 'application' 6 | 7 | mainClassName = 'com.google.firebase.example.Main' 8 | 9 | sourceCompatibility = 1.8 10 | 11 | repositories { 12 | mavenCentral() 13 | mavenLocal() 14 | } 15 | 16 | dependencies { 17 | // Firebase Admin Java SDK 18 | compile 'com.google.firebase:firebase-admin:9.1.1' 19 | } 20 | -------------------------------------------------------------------------------- /admin/src/main/java/com/google/firebase/example/FirebaseAuthSnippets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.firebase.example; 17 | 18 | import com.google.auth.oauth2.GoogleCredentials; 19 | import com.google.firebase.auth.*; 20 | import com.google.firebase.auth.UserRecord.CreateRequest; 21 | import com.google.firebase.auth.UserRecord.UpdateRequest; 22 | import com.google.firebase.database.DatabaseReference; 23 | import com.google.firebase.database.FirebaseDatabase; 24 | 25 | import java.io.FileInputStream; 26 | import java.io.IOException; 27 | import java.util.Arrays; 28 | import java.util.HashMap; 29 | import java.util.Map; 30 | import java.util.concurrent.ExecutionException; 31 | 32 | public class FirebaseAuthSnippets { 33 | 34 | public static void bulkGetUsers() throws Exception { 35 | // [START bulk_get_users] 36 | GetUsersResult result = FirebaseAuth.getInstance().getUsersAsync(Arrays.asList( 37 | new UidIdentifier("uid1"), 38 | new EmailIdentifier("user2@example.com"), 39 | new PhoneIdentifier("+15555550003"), 40 | new ProviderIdentifier("google.com", "google_uid4"))).get(); 41 | 42 | System.out.println("Successfully fetched user data:"); 43 | for (UserRecord user : result.getUsers()) { 44 | System.out.println(user.getUid()); 45 | } 46 | 47 | System.out.println("Unable to find users corresponding to these identifiers:"); 48 | for (UserIdentifier uid : result.getNotFound()) { 49 | System.out.println(uid); 50 | } 51 | // [END bulk_get_users] 52 | } 53 | 54 | public static void bulkDeleteUsers() throws Exception { 55 | // [START bulk_delete_users] 56 | DeleteUsersResult result = FirebaseAuth.getInstance().deleteUsersAsync( 57 | Arrays.asList("uid1", "uid2", "uid3")).get(); 58 | 59 | System.out.println("Successfully deleted " + result.getSuccessCount() + " users"); 60 | System.out.println("Failed to delete " + result.getFailureCount() + " users"); 61 | for (ErrorInfo error : result.getErrors()) { 62 | System.out.println("error #" + error.getIndex() + ", reason: " + error.getReason()); 63 | } 64 | // [END bulk_delete_users] 65 | } 66 | 67 | public static void getUserById(String uid) throws InterruptedException, ExecutionException { 68 | // [START get_user_by_id] 69 | UserRecord userRecord = FirebaseAuth.getInstance().getUserAsync(uid).get(); 70 | // See the UserRecord reference doc for the contents of userRecord. 71 | System.out.println("Successfully fetched user data: " + userRecord.getUid()); 72 | // [END get_user_by_id] 73 | } 74 | 75 | public static void getUserByEmail(String email) throws InterruptedException, ExecutionException { 76 | // [START get_user_by_email] 77 | UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmailAsync(email).get(); 78 | // See the UserRecord reference doc for the contents of userRecord. 79 | System.out.println("Successfully fetched user data: " + userRecord.getEmail()); 80 | // [END get_user_by_email] 81 | } 82 | 83 | public static void getUserByPhoneNumber( 84 | String phoneNumber) throws InterruptedException, ExecutionException { 85 | // [START get_user_by_phone] 86 | UserRecord userRecord = FirebaseAuth.getInstance().getUserByPhoneNumberAsync(phoneNumber).get(); 87 | // See the UserRecord reference doc for the contents of userRecord. 88 | System.out.println("Successfully fetched user data: " + userRecord.getPhoneNumber()); 89 | // [END get_user_by_phone] 90 | } 91 | 92 | public static void createUser() throws InterruptedException, ExecutionException { 93 | // [START create_user] 94 | UserRecord.CreateRequest request = new UserRecord.CreateRequest() 95 | .setEmail("user@example.com") 96 | .setEmailVerified(false) 97 | .setPassword("secretPassword") 98 | .setPhoneNumber("+11234567890") 99 | .setDisplayName("John Doe") 100 | .setPhotoUrl("http://www.example.com/12345678/photo.png") 101 | .setDisabled(false); 102 | 103 | UserRecord userRecord = FirebaseAuth.getInstance().createUserAsync(request).get(); 104 | System.out.println("Successfully created new user: " + userRecord.getUid()); 105 | // [END create_user] 106 | } 107 | 108 | public static void createUserWithUid() throws InterruptedException, ExecutionException { 109 | // [START create_user_with_uid] 110 | CreateRequest request = new CreateRequest() 111 | .setUid("some-uid") 112 | .setEmail("user@example.com") 113 | .setPhoneNumber("+11234567890"); 114 | 115 | UserRecord userRecord = FirebaseAuth.getInstance().createUserAsync(request).get(); 116 | System.out.println("Successfully created new user: " + userRecord.getUid()); 117 | // [END create_user_with_uid] 118 | } 119 | 120 | public static void updateUser(String uid) throws InterruptedException, ExecutionException { 121 | // [START update_user] 122 | UpdateRequest request = new UpdateRequest(uid) 123 | .setEmail("user@example.com") 124 | .setPhoneNumber("+11234567890") 125 | .setEmailVerified(true) 126 | .setPassword("newPassword") 127 | .setDisplayName("Jane Doe") 128 | .setPhotoUrl("http://www.example.com/12345678/photo.png") 129 | .setDisabled(true); 130 | 131 | UserRecord userRecord = FirebaseAuth.getInstance().updateUserAsync(request).get(); 132 | System.out.println("Successfully updated user: " + userRecord.getUid()); 133 | // [END update_user] 134 | } 135 | 136 | public static void setCustomUserClaims( 137 | String uid) throws InterruptedException, ExecutionException { 138 | // [START set_custom_user_claims] 139 | // Set admin privilege on the user corresponding to uid. 140 | Map claims = new HashMap<>(); 141 | claims.put("admin", true); 142 | FirebaseAuth.getInstance().setCustomUserClaimsAsync(uid, claims).get(); 143 | // The new custom claims will propagate to the user's ID token the 144 | // next time a new one is issued. 145 | // [END set_custom_user_claims] 146 | 147 | String idToken = "id_token"; 148 | // [START verify_custom_claims] 149 | // Verify the ID token first. 150 | FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get(); 151 | if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) { 152 | // Allow access to requested admin resource. 153 | } 154 | // [END verify_custom_claims] 155 | 156 | // [START read_custom_user_claims] 157 | // Lookup the user associated with the specified uid. 158 | UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get(); 159 | System.out.println(user.getCustomClaims().get("admin")); 160 | // [END read_custom_user_claims] 161 | } 162 | 163 | public static void setCustomUserClaimsScript() throws InterruptedException, ExecutionException { 164 | // [START set_custom_user_claims_script] 165 | UserRecord user = FirebaseAuth.getInstance() 166 | .getUserByEmailAsync("user@admin.example.com").get(); 167 | // Confirm user is verified. 168 | if (user.isEmailVerified()) { 169 | Map claims = new HashMap<>(); 170 | claims.put("admin", true); 171 | FirebaseAuth.getInstance().setCustomUserClaimsAsync(user.getUid(), claims).get(); 172 | } 173 | // [END set_custom_user_claims_script] 174 | } 175 | 176 | public static void setCustomUserClaimsInc() throws InterruptedException, ExecutionException { 177 | // [START set_custom_user_claims_incremental] 178 | UserRecord user = FirebaseAuth.getInstance() 179 | .getUserByEmailAsync("user@admin.example.com").get(); 180 | // Add incremental custom claim without overwriting the existing claims. 181 | Map currentClaims = user.getCustomClaims(); 182 | if (Boolean.TRUE.equals(currentClaims.get("admin"))) { 183 | // Add level. 184 | currentClaims.put("level", 10); 185 | // Add custom claims for additional privileges. 186 | FirebaseAuth.getInstance().setCustomUserClaimsAsync(user.getUid(), currentClaims).get(); 187 | } 188 | // [END set_custom_user_claims_incremental] 189 | } 190 | 191 | public static void listAllUsers() throws InterruptedException, ExecutionException { 192 | // [START list_all_users] 193 | // Start listing users from the beginning, 1000 at a time. 194 | ListUsersPage page = FirebaseAuth.getInstance().listUsersAsync(null).get(); 195 | while (page != null) { 196 | for (ExportedUserRecord user : page.getValues()) { 197 | System.out.println("User: " + user.getUid()); 198 | } 199 | page = page.getNextPage(); 200 | } 201 | 202 | // Iterate through all users. This will still retrieve users in batches, 203 | // buffering no more than 1000 users in memory at a time. 204 | page = FirebaseAuth.getInstance().listUsersAsync(null).get(); 205 | for (ExportedUserRecord user : page.iterateAll()) { 206 | System.out.println("User: " + user.getUid()); 207 | } 208 | // [END list_all_users] 209 | } 210 | 211 | public static void deleteUser(String uid) throws InterruptedException, ExecutionException { 212 | // [START delete_user] 213 | FirebaseAuth.getInstance().deleteUserAsync(uid).get(); 214 | System.out.println("Successfully deleted user."); 215 | // [END delete_user] 216 | } 217 | 218 | public static void createCustomToken() throws InterruptedException, ExecutionException { 219 | // [START custom_token] 220 | String uid = "some-uid"; 221 | 222 | String customToken = FirebaseAuth.getInstance().createCustomTokenAsync(uid).get(); 223 | // Send token back to client 224 | // [END custom_token] 225 | System.out.println("Created custom token: " + customToken); 226 | } 227 | 228 | public static void createCustomTokenWithClaims() throws InterruptedException, ExecutionException { 229 | // [START custom_token_with_claims] 230 | String uid = "some-uid"; 231 | Map additionalClaims = new HashMap(); 232 | additionalClaims.put("premiumAccount", true); 233 | 234 | String customToken = FirebaseAuth.getInstance() 235 | .createCustomTokenAsync(uid, additionalClaims).get(); 236 | // Send token back to client 237 | // [END custom_token_with_claims] 238 | System.out.println("Created custom token: " + customToken); 239 | } 240 | 241 | public static void verifyIdToken(String idToken) throws InterruptedException, ExecutionException { 242 | // [START verify_id_token] 243 | // idToken comes from the client app (shown above) 244 | FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get(); 245 | String uid = decodedToken.getUid(); 246 | // [END verify_id_token] 247 | System.out.println("Decoded ID token from user: " + uid); 248 | } 249 | 250 | public static void verifyIdTokenCheckRevoked(String idToken) throws InterruptedException, ExecutionException { 251 | // [START verify_id_token_check_revoked] 252 | try { 253 | // Verify the ID token while checking if the token is revoked by passing checkRevoked 254 | // as true. 255 | boolean checkRevoked = true; 256 | FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken, checkRevoked).get(); 257 | // Token is valid and not revoked. 258 | String uid = decodedToken.getUid(); 259 | } catch (ExecutionException e) { 260 | if (e.getCause() instanceof FirebaseAuthException) { 261 | FirebaseAuthException authError = (FirebaseAuthException) e.getCause(); 262 | if (authError.getErrorCode().equals("id-token-revoked")) { 263 | // Token has been revoked. Inform the user to reauthenticate or signOut() the user. 264 | } else { 265 | // Token is invalid. 266 | } 267 | } 268 | } 269 | // [END verify_id_token_check_revoked] 270 | } 271 | 272 | public static void revokeIdTokens(String idToken) throws InterruptedException, ExecutionException { 273 | String uid="someUid"; 274 | // [START revoke_tokens] 275 | FirebaseAuth.getInstance().revokeRefreshTokensAsync(uid).get(); 276 | UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get(); 277 | // Convert to seconds as the auth_time in the token claims is in seconds too. 278 | long revocationSecond = user.getTokensValidAfterTimestamp() / 1000; 279 | System.out.println("Tokens revoked at: " + revocationSecond); 280 | // [END revoke_tokens] 281 | 282 | // [START save_revocation_in_db] 283 | DatabaseReference ref = FirebaseDatabase.getInstance().getReference("metadata/" + uid); 284 | Map userData = new HashMap<>(); 285 | userData.put("revokeTime", revocationSecond); 286 | ref.setValueAsync(userData).get(); 287 | // [END save_revocation_in_db] 288 | } 289 | 290 | public static String getServiceAccountAccessToken() throws IOException { 291 | // https://firebase.google.com/docs/reference/dynamic-links/analytics#api_authorization 292 | // [START get_service_account_tokens] 293 | FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json"); 294 | GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount); 295 | credentials.refresh(); 296 | String accessToken = credentials.getAccessToken().getTokenValue(); 297 | // [START_EXCLUDE] 298 | long expirationTime = credentials.getAccessToken().getExpirationTime().getTime(); 299 | // Attach accessToken to HTTPS request in the "Authorization: Bearer" header 300 | // After expirationTime, you must generate a new access token 301 | // [END_EXCLUDE] 302 | return accessToken; 303 | // [END get_service_account_tokens] 304 | } 305 | } 306 | -------------------------------------------------------------------------------- /admin/src/main/java/com/google/firebase/example/FirebaseMessagingSnippets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.firebase.example; 18 | 19 | import com.google.firebase.messaging.AndroidConfig; 20 | import com.google.firebase.messaging.AndroidNotification; 21 | import com.google.firebase.messaging.ApnsConfig; 22 | import com.google.firebase.messaging.Aps; 23 | import com.google.firebase.messaging.ApsAlert; 24 | import com.google.firebase.messaging.FirebaseMessaging; 25 | import com.google.firebase.messaging.Message; 26 | import com.google.firebase.messaging.Notification; 27 | import com.google.firebase.messaging.TopicManagementResponse; 28 | import com.google.firebase.messaging.WebpushConfig; 29 | import com.google.firebase.messaging.WebpushNotification; 30 | 31 | import java.io.IOException; 32 | import java.net.HttpURLConnection; 33 | import java.net.URL; 34 | import java.util.Arrays; 35 | import java.util.List; 36 | 37 | import static com.google.firebase.example.FirebaseAuthSnippets.getServiceAccountAccessToken; 38 | 39 | public class FirebaseMessagingSnippets { 40 | 41 | private static final String PROJECT_ID = ""; 42 | private static final String BASE_URL = "https://fcm.googleapis.com"; 43 | private static final String FCM_SEND_ENDPOINT = "/v1/projects/" + PROJECT_ID + "/messages:send"; 44 | 45 | public void sendToToken() throws Exception { 46 | // [START send_to_token] 47 | // This registration token comes from the client FCM SDKs. 48 | String registrationToken = "YOUR_REGISTRATION_TOKEN"; 49 | 50 | // See documentation on defining a message payload. 51 | Message message = Message.builder() 52 | .putData("score", "850") 53 | .putData("time", "2:45") 54 | .setToken(registrationToken) 55 | .build(); 56 | 57 | // Send a message to the device corresponding to the provided 58 | // registration token. 59 | String response = FirebaseMessaging.getInstance().sendAsync(message).get(); 60 | // Response is a message ID string. 61 | System.out.println("Successfully sent message: " + response); 62 | // [END send_to_token] 63 | } 64 | 65 | public void sendToTopic() throws Exception { 66 | // [START send_to_topic] 67 | // The topic name can be optionally prefixed with "/topics/". 68 | String topic = "highScores"; 69 | 70 | // See documentation on defining a message payload. 71 | Message message = Message.builder() 72 | .putData("score", "850") 73 | .putData("time", "2:45") 74 | .setTopic(topic) 75 | .build(); 76 | 77 | // Send a message to the devices subscribed to the provided topic. 78 | String response = FirebaseMessaging.getInstance().sendAsync(message).get(); 79 | // Response is a message ID string. 80 | System.out.println("Successfully sent message: " + response); 81 | // [END send_to_topic] 82 | } 83 | 84 | public void sendToCondition() throws Exception { 85 | // [START send_to_condition] 86 | // Define a condition which will send to devices which are subscribed 87 | // to either the Google stock or the tech industry topics. 88 | String condition = "'stock-GOOG' in topics || 'industry-tech' in topics"; 89 | 90 | // See documentation on defining a message payload. 91 | Message message = Message.builder() 92 | .setNotification(Notification.builder() 93 | .setTitle("$GOOG up 1.43% on the day") 94 | .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.") 95 | .build()) 96 | .setCondition(condition) 97 | .build(); 98 | 99 | // Send a message to devices subscribed to the combination of topics 100 | // specified by the provided condition. 101 | String response = FirebaseMessaging.getInstance().sendAsync(message).get(); 102 | // Response is a message ID string. 103 | System.out.println("Successfully sent message: " + response); 104 | // [END send_to_condition] 105 | } 106 | 107 | public void sendDryRun() throws Exception { 108 | Message message = Message.builder() 109 | .putData("score", "850") 110 | .putData("time", "2:45") 111 | .setToken("token") 112 | .build(); 113 | 114 | // [START send_dry_run] 115 | // Send a message in the dry run mode. 116 | boolean dryRun = true; 117 | String response = FirebaseMessaging.getInstance().sendAsync(message, dryRun).get(); 118 | // Response is a message ID string. 119 | System.out.println("Dry run successful: " + response); 120 | // [END send_dry_run] 121 | } 122 | 123 | public Message androidMessage() { 124 | // [START android_message] 125 | Message message = Message.builder() 126 | .setAndroidConfig(AndroidConfig.builder() 127 | .setTtl(3600 * 1000) // 1 hour in milliseconds 128 | .setPriority(AndroidConfig.Priority.NORMAL) 129 | .setNotification(AndroidNotification.builder() 130 | .setTitle("$GOOG up 1.43% on the day") 131 | .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.") 132 | .setIcon("stock_ticker_update") 133 | .setColor("#f45342") 134 | .build()) 135 | .build()) 136 | .setTopic("industry-tech") 137 | .build(); 138 | // [END android_message] 139 | return message; 140 | } 141 | 142 | public Message apnsMessage() { 143 | // [START apns_message] 144 | Message message = Message.builder() 145 | .setApnsConfig(ApnsConfig.builder() 146 | .putHeader("apns-priority", "10") 147 | .setAps(Aps.builder() 148 | .setAlert(ApsAlert.builder() 149 | .setTitle("$GOOG up 1.43% on the day") 150 | .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.") 151 | .build()) 152 | .setBadge(42) 153 | .build()) 154 | .build()) 155 | .setTopic("industry-tech") 156 | .build(); 157 | // [END apns_message] 158 | return message; 159 | } 160 | 161 | public Message webpushMessage() { 162 | // [START webpush_message] 163 | Message message = Message.builder() 164 | .setWebpushConfig(WebpushConfig.builder() 165 | .setNotification(new WebpushNotification( 166 | "$GOOG up 1.43% on the day", 167 | "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.", 168 | "https://my-server/icon.png")) 169 | .build()) 170 | .setTopic("industry-tech") 171 | .build(); 172 | // [END webpush_message] 173 | return message; 174 | } 175 | 176 | public Message allPlatformsMessage() { 177 | // [START multi_platforms_message] 178 | Message message = Message.builder() 179 | .setNotification(Notification.builder() 180 | .setTitle("$GOOG up 1.43% on the day") 181 | .setTitle("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.") 182 | .build()) 183 | .setAndroidConfig(AndroidConfig.builder() 184 | .setTtl(3600 * 1000) 185 | .setNotification(AndroidNotification.builder() 186 | .setIcon("stock_ticker_update") 187 | .setColor("#f45342") 188 | .build()) 189 | .build()) 190 | .setApnsConfig(ApnsConfig.builder() 191 | .setAps(Aps.builder() 192 | .setBadge(42) 193 | .build()) 194 | .build()) 195 | .setTopic("industry-tech") 196 | .build(); 197 | // [END multi_platforms_message] 198 | return message; 199 | } 200 | 201 | public void subscribeToTopic() throws Exception { 202 | String topic = "highScores"; 203 | // [START subscribe] 204 | // These registration tokens come from the client FCM SDKs. 205 | List registrationTokens = Arrays.asList( 206 | "YOUR_REGISTRATION_TOKEN_1", 207 | // ... 208 | "YOUR_REGISTRATION_TOKEN_n" 209 | ); 210 | 211 | // Subscribe the devices corresponding to the registration tokens to the 212 | // topic. 213 | TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopicAsync( 214 | registrationTokens, topic).get(); 215 | // See the TopicManagementResponse reference documentation 216 | // for the contents of response. 217 | System.out.println(response.getSuccessCount() + " tokens were subscribed successfully"); 218 | // [END subscribe] 219 | } 220 | 221 | public void unsubscribeFromTopic() throws Exception { 222 | String topic = "highScores"; 223 | // [START unsubscribe] 224 | // These registration tokens come from the client FCM SDKs. 225 | List registrationTokens = Arrays.asList( 226 | "YOUR_REGISTRATION_TOKEN_1", 227 | // ... 228 | "YOUR_REGISTRATION_TOKEN_n" 229 | ); 230 | 231 | // Unsubscribe the devices corresponding to the registration tokens from 232 | // the topic. 233 | TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopicAsync( 234 | registrationTokens, topic).get(); 235 | // See the TopicManagementResponse reference documentation 236 | // for the contents of response. 237 | System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully"); 238 | // [END unsubscribe] 239 | } 240 | 241 | private static HttpURLConnection getConnection() throws IOException { 242 | // [START use_access_token] 243 | URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT); 244 | HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 245 | httpURLConnection.setRequestProperty("Authorization", "Bearer " + getServiceAccountAccessToken()); 246 | httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8"); 247 | return httpURLConnection; 248 | // [END use_access_token] 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /admin/src/main/java/com/google/firebase/example/FirebaseRemoteConfigSnippets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.firebase.example; 17 | 18 | import com.google.auth.oauth2.GoogleCredentials; 19 | import com.google.firebase.FirebaseApp; 20 | import com.google.firebase.FirebaseOptions; 21 | import com.google.firebase.remoteconfig.Condition; 22 | import com.google.firebase.remoteconfig.FirebaseRemoteConfig; 23 | import com.google.firebase.remoteconfig.FirebaseRemoteConfigException; 24 | import com.google.firebase.remoteconfig.ListVersionsPage; 25 | import com.google.firebase.remoteconfig.Parameter; 26 | import com.google.firebase.remoteconfig.ParameterGroup; 27 | import com.google.firebase.remoteconfig.ParameterValue; 28 | import com.google.firebase.remoteconfig.TagColor; 29 | import com.google.firebase.remoteconfig.Template; 30 | import com.google.firebase.remoteconfig.Version; 31 | 32 | import java.io.IOException; 33 | import java.net.HttpURLConnection; 34 | import java.net.URL; 35 | import java.util.Arrays; 36 | import java.util.List; 37 | import java.io.FileInputStream; 38 | import java.io.IOException; 39 | import java.util.concurrent.ExecutionException; 40 | 41 | /** 42 | * Remote Config snippets for documentation. 43 | * 44 | * See: 45 | * https://firebase.google.com/docs/remote-config/automate-rc 46 | */ 47 | public class FirebaseRemoteConfigSnippets { 48 | 49 | private final static String PROJECT_ID = "PROJECT_ID"; 50 | private final static String BASE_URL = "https://firebaseremoteconfig.googleapis.com"; 51 | private final static String REMOTE_CONFIG_ENDPOINT = "/v1/projects/" + PROJECT_ID + "/remoteConfig"; 52 | private final static String[] SCOPES = { "https://www.googleapis.com/auth/firebase.remoteconfig" }; 53 | 54 | //Get the current Remote Config Template 55 | public static Template getRemoteConfig() throws ExecutionException, InterruptedException { 56 | // [START get_rc_template] 57 | Template template = FirebaseRemoteConfig.getInstance().getTemplateAsync().get(); 58 | // See the ETag of the fetched template. 59 | System.out.println("ETag from server: " + template.getETag()); 60 | // [END get_rc_template] 61 | return template; 62 | } 63 | 64 | // Modify Remote Config parameters 65 | public static void addParameterToGroup(Template template) { 66 | // [START add_rc_parameter] 67 | template.getParameterGroups().get("new_menu").getParameters() 68 | .put("spring_season", new Parameter() 69 | .setDefaultValue(ParameterValue.inAppDefault()) 70 | .setDescription("spring season menu visibility.") 71 | ); 72 | // [END add_rc_parameter] 73 | } 74 | 75 | // Modify Remote Config conditions 76 | public static void addNewCondition(Template template) { 77 | // [START add_rc_condition] 78 | template.getConditions().add(new Condition("android_en", 79 | "device.os == 'android' && device.country in ['us', 'uk']", TagColor.BLUE)); 80 | // [END add_rc_condition] 81 | } 82 | 83 | // Validate the Remote Config template 84 | public static void validateTemplate(Template template) throws InterruptedException { 85 | // [START validate_rc_template] 86 | try { 87 | Template validatedTemplate = FirebaseRemoteConfig.getInstance() 88 | .validateTemplateAsync(template).get(); 89 | System.out.println("Template was valid and safe to use"); 90 | } catch (ExecutionException e) { 91 | if (e.getCause() instanceof FirebaseRemoteConfigException) { 92 | FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); 93 | System.out.println("Template is invalid and cannot be published"); 94 | System.out.println(rcError.getMessage()); 95 | } 96 | } 97 | // [END validate_rc_template] 98 | } 99 | 100 | // Publish the Remote Config template 101 | public static void publishTemplate(Template template) throws InterruptedException { 102 | // [START publish_rc_template] 103 | try { 104 | Template publishedTemplate = FirebaseRemoteConfig.getInstance() 105 | .publishTemplateAsync(template).get(); 106 | System.out.println("Template has been published"); 107 | // See the ETag of the published template. 108 | System.out.println("ETag from server: " + publishedTemplate.getETag()); 109 | } catch (ExecutionException e) { 110 | if (e.getCause() instanceof FirebaseRemoteConfigException) { 111 | FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); 112 | System.out.println("Unable to publish template."); 113 | System.out.println(rcError.getMessage()); 114 | } 115 | } 116 | // [END publish_rc_template] 117 | } 118 | 119 | /** 120 | * Remote Config snippets for Manage Remote Config template versions documentation. 121 | * 122 | * See: 123 | * https://firebase.google.com/docs/remote-config/templates 124 | */ 125 | // List all stored versions of the Remote Config template 126 | public static void listAllVersions() throws InterruptedException, ExecutionException { 127 | // [START list_all_versions] 128 | ListVersionsPage page = FirebaseRemoteConfig.getInstance().listVersionsAsync().get(); 129 | while (page != null) { 130 | for (Version version : page.getValues()) { 131 | System.out.println("Version: " + version.getVersionNumber()); 132 | } 133 | page = page.getNextPage(); 134 | } 135 | 136 | // Iterate through all versions. This will still retrieve versions in batches. 137 | page = FirebaseRemoteConfig.getInstance().listVersionsAsync().get(); 138 | for (Version version : page.iterateAll()) { 139 | System.out.println("Version: " + version.getVersionNumber()); 140 | } 141 | // [END list_all_versions] 142 | } 143 | 144 | // Retrieve a specific version of the Remote Config template 145 | public static void getRemoteConfigAtVersion(long versionNumber) throws ExecutionException, InterruptedException { 146 | // [START get_rc_template_at_version] 147 | Template template = FirebaseRemoteConfig.getInstance().getTemplateAtVersionAsync(versionNumber).get(); 148 | // See the ETag of the fetched template. 149 | System.out.println("Successfully fetched the template with ETag: " + template.getETag()); 150 | // [END get_rc_template_at_version] 151 | } 152 | 153 | // Roll back to a specific stored version of the Remote Config template 154 | public static void rollbackToVersion(long versionNumber) throws InterruptedException { 155 | // [START rollback_rc_template] 156 | try { 157 | Template template = FirebaseRemoteConfig.getInstance().rollbackAsync(versionNumber).get(); 158 | System.out.println("Successfully rolled back to template version: " + versionNumber); 159 | System.out.println("New ETag: " + template.getETag()); 160 | } catch (ExecutionException e) { 161 | if (e.getCause() instanceof FirebaseRemoteConfigException) { 162 | FirebaseRemoteConfigException rcError = (FirebaseRemoteConfigException) e.getCause(); 163 | System.out.println("Error trying to rollback template."); 164 | System.out.println(rcError.getMessage()); 165 | } 166 | } 167 | // [END rollback_rc_template] 168 | } 169 | 170 | /** 171 | * Retrieve a valid access token that can be used to authorize requests to the Remote Config REST 172 | * API. 173 | * 174 | * @return Access token. 175 | * @throws IOException 176 | */ 177 | // [START retrieve_access_token] 178 | public static String getAccessToken() throws IOException { 179 | GoogleCredentials googleCredentials = GoogleCredentials 180 | .fromStream(new FileInputStream("service-account.json")) 181 | .createScoped(Arrays.asList(SCOPES)); 182 | googleCredentials.refreshAccessToken(); 183 | return googleCredentials.getAccessToken().getTokenValue(); 184 | } 185 | // [END retrieve_access_token] 186 | 187 | public static void main(String[] args) throws ExecutionException, InterruptedException { 188 | System.out.println("Hello, FirebaseRemoteConfigSnippets!"); 189 | 190 | // Initialize Firebase 191 | try { 192 | // [START initialize] 193 | FileInputStream serviceAccount = new FileInputStream("service-account.json"); 194 | FirebaseOptions options = FirebaseOptions.builder() 195 | .setCredentials(GoogleCredentials.fromStream(serviceAccount)) 196 | .build(); 197 | FirebaseApp.initializeApp(options); 198 | // [END initialize] 199 | } catch (IOException e) { 200 | System.out.println("ERROR: invalid service account credentials. See README."); 201 | System.out.println(e.getMessage()); 202 | 203 | System.exit(1); 204 | } 205 | 206 | // Smoke test 207 | Template template = getRemoteConfig(); 208 | template.getParameterGroups().put("new_menu", new ParameterGroup()); 209 | addParameterToGroup(template); 210 | addNewCondition(template); 211 | validateTemplate(template); 212 | publishTemplate(template); 213 | listAllVersions(); 214 | getRemoteConfigAtVersion(6); 215 | rollbackToVersion(6); 216 | System.out.println("Done!"); 217 | } 218 | 219 | } 220 | -------------------------------------------------------------------------------- /admin/src/main/java/com/google/firebase/example/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.firebase.example; 18 | 19 | import com.google.auth.oauth2.GoogleCredentials; 20 | 21 | import java.io.FileInputStream; 22 | import java.io.IOException; 23 | 24 | public class Main { 25 | public static void main(String[] args) { 26 | // write your code here 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | repositories { 3 | mavenCentral() 4 | mavenLocal() 5 | } 6 | } 7 | 8 | task clean(type: Delete) { 9 | delete rootProject.buildDir 10 | } -------------------------------------------------------------------------------- /database/build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.google.firebase.example' 2 | version '1.0' 3 | 4 | apply plugin: 'java' 5 | apply plugin: 'application' 6 | 7 | mainClassName = 'com.google.firebase.example.Main' 8 | 9 | sourceCompatibility = 1.8 10 | 11 | repositories { 12 | mavenCentral() 13 | mavenLocal() 14 | } 15 | 16 | dependencies { 17 | // Firebase Admin Java SDK 18 | compile 'com.google.firebase:firebase-admin:6.12.2' 19 | } -------------------------------------------------------------------------------- /database/src/main/java/com/google/firebase/example/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.firebase.example; 18 | 19 | import com.google.firebase.database.*; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | import java.util.concurrent.atomic.AtomicInteger; 24 | 25 | public class Main { 26 | 27 | // [START user_class] 28 | public static class User { 29 | 30 | public String date_of_birth; 31 | public String full_name; 32 | public String nickname; 33 | 34 | public User(String date_of_birth, String full_name) { 35 | // [START_EXCLUDE] 36 | this(date_of_birth, full_name, null); 37 | // [END_EXCLUDE] 38 | } 39 | 40 | public User(String date_of_birth, String full_name, String nickname) { 41 | // [START_EXCLUDE] 42 | this.date_of_birth = date_of_birth; 43 | this.full_name = full_name; 44 | this.nickname = nickname; 45 | // [END_EXCLUDE] 46 | } 47 | 48 | } 49 | // [END user_class] 50 | 51 | // [START post_class] 52 | public static class Post { 53 | 54 | public String author; 55 | public String title; 56 | 57 | public Post(String author, String title) { 58 | // [START_EXCLUDE] 59 | this.author = author; 60 | this.title = title; 61 | // [END_EXCLUDE] 62 | } 63 | 64 | } 65 | // [END post_class] 66 | 67 | // [START dinosaur_class] 68 | public static class Dinosaur { 69 | 70 | public int height; 71 | public int weight; 72 | 73 | public Dinosaur(int height, int weight) { 74 | // [START_EXCLUDE] 75 | this.height = height; 76 | this.weight = weight; 77 | // [END_EXCLUDE] 78 | } 79 | 80 | } 81 | // [END dinosaur_class] 82 | 83 | public void savingData() { 84 | // [START get_database_and_reference] 85 | final FirebaseDatabase database = FirebaseDatabase.getInstance(); 86 | DatabaseReference ref = database.getReference("server/saving-data/fireblog"); 87 | // [END get_database_and_reference] 88 | 89 | // TODO(writer): Show user class with this 90 | // [START set_user_data_all] 91 | DatabaseReference usersRef = ref.child("users"); 92 | 93 | Map users = new HashMap<>(); 94 | users.put("alanisawesome", new User("June 23, 1912", "Alan Turing")); 95 | users.put("gracehop", new User("December 9, 1906", "Grace Hopper")); 96 | 97 | usersRef.setValueAsync(users); 98 | // [END set_user_data_all] 99 | 100 | // [START set_user_data_child] 101 | usersRef.child("alanisawesome").setValueAsync(new User("June 23, 1912", "Alan Turing")); 102 | usersRef.child("gracehop").setValueAsync(new User("December 9, 1906", "Grace Hopper")); 103 | // [END set_user_data_child] 104 | 105 | // [START single_user_update_children] 106 | DatabaseReference hopperRef = usersRef.child("gracehop"); 107 | Map hopperUpdates = new HashMap<>(); 108 | hopperUpdates.put("nickname", "Amazing Grace"); 109 | 110 | hopperRef.updateChildrenAsync(hopperUpdates); 111 | // [END single_user_update_children] 112 | 113 | // [START multi_user_update_children] 114 | Map userUpdates = new HashMap<>(); 115 | userUpdates.put("alanisawesome/nickname", "Alan The Machine"); 116 | userUpdates.put("gracehop/nickname", "Amazing Grace"); 117 | 118 | usersRef.updateChildrenAsync(userUpdates); 119 | // [END multi_user_update_children] 120 | 121 | // [START multi_user_object_updates] 122 | Map userNicknameUpdates = new HashMap<>(); 123 | userNicknameUpdates.put("alanisawesome", new User(null, null, "Alan The Machine")); 124 | userNicknameUpdates.put("gracehop", new User(null, null, "Amazing Grace")); 125 | 126 | usersRef.updateChildrenAsync(userNicknameUpdates); 127 | // [END multi_user_object_updates] 128 | 129 | // [START adding_completion_callback] 130 | DatabaseReference dataRef = ref.child("data"); 131 | dataRef.setValueAsync("I'm writing data", new DatabaseReference.CompletionListener() { 132 | @Override 133 | public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { 134 | if (databaseError != null) { 135 | System.out.println("Data could not be saved " + databaseError.getMessage()); 136 | } else { 137 | System.out.println("Data saved successfully."); 138 | } 139 | } 140 | }); 141 | // [END adding_completion_callback] 142 | 143 | // TODO(writer): Show post class with this 144 | // [START push_posts] 145 | DatabaseReference postsRef = ref.child("posts"); 146 | 147 | DatabaseReference newPostRef = postsRef.push(); 148 | newPostRef.setValueAsync(new Post("gracehop", "Announcing COBOL, a New Programming Language")); 149 | 150 | // We can also chain the two calls together 151 | postsRef.push().setValueAsync(new Post("alanisawesome", "The Turing Machine")); 152 | // [END push_posts] 153 | 154 | // [START getting_post_id] 155 | // Generate a reference to a new location and add some data using push() 156 | DatabaseReference pushedPostRef = postsRef.push(); 157 | 158 | // Get the unique ID generated by a push() 159 | String postId = pushedPostRef.getKey(); 160 | // [END getting_post_id] 161 | 162 | // [START save_transaction] 163 | DatabaseReference upvotesRef = ref.child("server/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes"); 164 | upvotesRef.runTransaction(new Transaction.Handler() { 165 | @Override 166 | public Transaction.Result doTransaction(MutableData mutableData) { 167 | Integer currentValue = mutableData.getValue(Integer.class); 168 | if (currentValue == null) { 169 | mutableData.setValue(1); 170 | } else { 171 | mutableData.setValue(currentValue + 1); 172 | } 173 | 174 | return Transaction.success(mutableData); 175 | } 176 | 177 | @Override 178 | public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) { 179 | System.out.println("Transaction completed"); 180 | } 181 | }); 182 | // [END save_transaction] 183 | } 184 | 185 | public void readingData() { 186 | // TODO(writer): Show Post class 187 | // [START get_ref_and_read] 188 | // Get a reference to our posts 189 | final FirebaseDatabase database = FirebaseDatabase.getInstance(); 190 | DatabaseReference ref = database.getReference("server/saving-data/fireblog/posts"); 191 | 192 | // Attach a listener to read the data at our posts reference 193 | ref.addValueEventListener(new ValueEventListener() { 194 | @Override 195 | public void onDataChange(DataSnapshot dataSnapshot) { 196 | Post post = dataSnapshot.getValue(Post.class); 197 | System.out.println(post); 198 | } 199 | 200 | @Override 201 | public void onCancelled(DatabaseError databaseError) { 202 | System.out.println("The read failed: " + databaseError.getCode()); 203 | } 204 | }); 205 | // [END get_ref_and_read] 206 | 207 | // [START child_added] 208 | ref.addChildEventListener(new ChildEventListener() { 209 | @Override 210 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 211 | Post newPost = dataSnapshot.getValue(Post.class); 212 | System.out.println("Author: " + newPost.author); 213 | System.out.println("Title: " + newPost.title); 214 | System.out.println("Previous Post ID: " + prevChildKey); 215 | } 216 | 217 | @Override 218 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 219 | 220 | @Override 221 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 222 | 223 | @Override 224 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 225 | 226 | @Override 227 | public void onCancelled(DatabaseError databaseError) {} 228 | }); 229 | // [END child_added] 230 | 231 | // [START child_changed] 232 | ref.addChildEventListener(new ChildEventListener() { 233 | @Override 234 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {} 235 | 236 | @Override 237 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 238 | Post changedPost = dataSnapshot.getValue(Post.class); 239 | System.out.println("The updated post title is: " + changedPost.title); 240 | } 241 | 242 | @Override 243 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 244 | 245 | @Override 246 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 247 | 248 | @Override 249 | public void onCancelled(DatabaseError databaseError) {} 250 | }); 251 | // [END child_changed] 252 | 253 | // [START child_removed] 254 | ref.addChildEventListener(new ChildEventListener() { 255 | @Override 256 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {} 257 | 258 | @Override 259 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 260 | 261 | @Override 262 | public void onChildRemoved(DataSnapshot dataSnapshot) { 263 | Post removedPost = dataSnapshot.getValue(Post.class); 264 | System.out.println("The blog post titled " + removedPost.title + " has been deleted"); 265 | } 266 | 267 | @Override 268 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 269 | 270 | @Override 271 | public void onCancelled(DatabaseError databaseError) {} 272 | }); 273 | // [END child_removed] 274 | 275 | // [START event_guarantees] 276 | final AtomicInteger count = new AtomicInteger(); 277 | 278 | ref.addChildEventListener(new ChildEventListener() { 279 | @Override 280 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 281 | // New child added, increment count 282 | int newCount = count.incrementAndGet(); 283 | System.out.println("Added " + dataSnapshot.getKey() + ", count is " + newCount); 284 | } 285 | 286 | // [START_EXCLUDE] 287 | @Override 288 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 289 | 290 | @Override 291 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 292 | 293 | @Override 294 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 295 | 296 | @Override 297 | public void onCancelled(DatabaseError databaseError) {} 298 | // [END_EXCLUDE] 299 | }); 300 | 301 | // The number of children will always be equal to 'count' since the value of 302 | // the dataSnapshot here will include every child_added event triggered before this point. 303 | ref.addListenerForSingleValueEvent(new ValueEventListener() { 304 | @Override 305 | public void onDataChange(DataSnapshot dataSnapshot) { 306 | long numChildren = dataSnapshot.getChildrenCount(); 307 | System.out.println(count.get() + " == " + numChildren); 308 | } 309 | 310 | @Override 311 | public void onCancelled(DatabaseError databaseError) {} 312 | }); 313 | // [END event_guarantees] 314 | 315 | // [START remove_listener] 316 | // Create and attach listener 317 | ValueEventListener listener = new ValueEventListener() { 318 | // [START_EXCLUDE] 319 | @Override 320 | public void onDataChange(DataSnapshot dataSnapshot) {} 321 | 322 | @Override 323 | public void onCancelled(DatabaseError databaseError) {} 324 | // [END_EXCLUDE] 325 | }; 326 | ref.addValueEventListener(listener); 327 | 328 | // Remove listener 329 | ref.removeEventListener(listener); 330 | // [END remove_listener] 331 | 332 | // [START single_value_event] 333 | ref.addListenerForSingleValueEvent(new ValueEventListener() { 334 | @Override 335 | public void onDataChange(DataSnapshot dataSnapshot) { 336 | // ... 337 | } 338 | 339 | @Override 340 | public void onCancelled(DatabaseError databaseError) { 341 | // ... 342 | } 343 | }); 344 | // [END single_value_event] 345 | 346 | // TODO(writer): Show dinosaur class 347 | // [START order_by_child] 348 | final DatabaseReference dinosaursRef = database.getReference("dinosaurs"); 349 | dinosaursRef.orderByChild("height").addChildEventListener(new ChildEventListener() { 350 | @Override 351 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 352 | Dinosaur dinosaur = dataSnapshot.getValue(Dinosaur.class); 353 | System.out.println(dataSnapshot.getKey() + " was " + dinosaur.height + " meters tall."); 354 | } 355 | 356 | // [START_EXCLUDE] 357 | @Override 358 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 359 | 360 | @Override 361 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 362 | 363 | @Override 364 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 365 | 366 | @Override 367 | public void onCancelled(DatabaseError databaseError) {} 368 | // [END_EXCLUDE] 369 | }); 370 | // [END order_by_child] 371 | 372 | // [START deeply_nested_query] 373 | dinosaursRef.orderByChild("dimensions/height").addChildEventListener(new ChildEventListener() { 374 | @Override 375 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 376 | // ... 377 | } 378 | 379 | // [START_EXCLUDE] 380 | @Override 381 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 382 | } 383 | 384 | @Override 385 | public void onChildRemoved(DataSnapshot dataSnapshot) { 386 | } 387 | 388 | @Override 389 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) { 390 | } 391 | 392 | @Override 393 | public void onCancelled(DatabaseError databaseError) { 394 | } 395 | // [END_EXCLUDE] 396 | }); 397 | // [END deeply_nested_query] 398 | 399 | // [START order_by_key] 400 | dinosaursRef.orderByKey().addChildEventListener(new ChildEventListener() { 401 | @Override 402 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 403 | System.out.println(dataSnapshot.getKey()); 404 | } 405 | 406 | // [START_EXCLUDE] 407 | @Override 408 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 409 | } 410 | 411 | @Override 412 | public void onChildRemoved(DataSnapshot dataSnapshot) { 413 | } 414 | 415 | @Override 416 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) { 417 | } 418 | 419 | @Override 420 | public void onCancelled(DatabaseError databaseError) { 421 | } 422 | // [END_EXCLUDE] 423 | }); 424 | // [END order_by_key] 425 | 426 | // [START order_by_value] 427 | DatabaseReference scoresRef = database.getReference("scores"); 428 | scoresRef.orderByValue().addChildEventListener(new ChildEventListener() { 429 | @Override 430 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 431 | System.out.println("The " + dataSnapshot.getKey() + " score is " + dataSnapshot.getValue()); 432 | } 433 | 434 | // [START_EXCLUDE] 435 | @Override 436 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 437 | } 438 | 439 | @Override 440 | public void onChildRemoved(DataSnapshot dataSnapshot) { 441 | } 442 | 443 | @Override 444 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) { 445 | } 446 | 447 | @Override 448 | public void onCancelled(DatabaseError databaseError) { 449 | } 450 | // [END_EXCLUDE] 451 | }); 452 | // [END order_by_value] 453 | 454 | // [START limit_to_last] 455 | dinosaursRef.orderByChild("weight").limitToLast(2).addChildEventListener(new ChildEventListener() { 456 | @Override 457 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 458 | System.out.println(dataSnapshot.getKey()); 459 | } 460 | 461 | // [START_EXCLUDE] 462 | @Override 463 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 464 | } 465 | 466 | @Override 467 | public void onChildRemoved(DataSnapshot dataSnapshot) { 468 | } 469 | 470 | @Override 471 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) { 472 | } 473 | 474 | @Override 475 | public void onCancelled(DatabaseError databaseError) { 476 | } 477 | // [END_EXCLUDE] 478 | }); 479 | // [END limit_to_last] 480 | 481 | // [START limit_to_first] 482 | dinosaursRef.orderByChild("weight").limitToFirst(2).addChildEventListener(new ChildEventListener() { 483 | @Override 484 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 485 | System.out.println(dataSnapshot.getKey()); 486 | } 487 | 488 | // [START_EXCLUDE] 489 | @Override 490 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 491 | 492 | @Override 493 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 494 | 495 | @Override 496 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 497 | 498 | @Override 499 | public void onCancelled(DatabaseError databaseError) {} 500 | // [END_EXCLUDE] 501 | }); 502 | // [END limit_to_first] 503 | 504 | // [START limit_order_value] 505 | scoresRef.orderByValue().limitToFirst(3).addChildEventListener(new ChildEventListener() { 506 | @Override 507 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 508 | System.out.println("The " + dataSnapshot.getKey() + " score is " + dataSnapshot.getValue()); 509 | } 510 | 511 | // [START_EXCLUDE] 512 | @Override 513 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 514 | 515 | @Override 516 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 517 | 518 | @Override 519 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 520 | 521 | @Override 522 | public void onCancelled(DatabaseError databaseError) {} 523 | // [END_EXCLUDE] 524 | }); 525 | // [END limit_order_value] 526 | 527 | // [START start_at] 528 | dinosaursRef.orderByChild("height").startAt(3).addChildEventListener(new ChildEventListener() { 529 | @Override 530 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 531 | System.out.println(dataSnapshot.getKey()); 532 | } 533 | 534 | // [START_EXCLUDE] 535 | @Override 536 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 537 | } 538 | 539 | @Override 540 | public void onChildRemoved(DataSnapshot dataSnapshot) { 541 | } 542 | 543 | @Override 544 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) { 545 | } 546 | 547 | @Override 548 | public void onCancelled(DatabaseError databaseError) { 549 | } 550 | // [END_EXCLUDE] 551 | }); 552 | // [END start_at] 553 | 554 | // [START end_at] 555 | dinosaursRef.orderByKey().endAt("pterodactyl").addChildEventListener(new ChildEventListener() { 556 | @Override 557 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 558 | System.out.println(dataSnapshot.getKey()); 559 | } 560 | 561 | // [START_EXCLUDE] 562 | @Override 563 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) { 564 | } 565 | 566 | @Override 567 | public void onChildRemoved(DataSnapshot dataSnapshot) { 568 | } 569 | 570 | @Override 571 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) { 572 | } 573 | 574 | @Override 575 | public void onCancelled(DatabaseError databaseError) { 576 | } 577 | // [END_EXCLUDE] 578 | }); 579 | // [END end_at] 580 | 581 | // [START start_and_end_at] 582 | dinosaursRef.orderByKey().startAt("b").endAt("b\uf8ff").addChildEventListener(new ChildEventListener() { 583 | @Override 584 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 585 | System.out.println(dataSnapshot.getKey()); 586 | } 587 | 588 | // [START_EXCLUDE] 589 | @Override 590 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 591 | 592 | @Override 593 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 594 | 595 | @Override 596 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 597 | 598 | @Override 599 | public void onCancelled(DatabaseError databaseError) {} 600 | // [END_EXCLUDE] 601 | }); 602 | // [END start_and_end_at] 603 | 604 | // [START equal_to] 605 | dinosaursRef.orderByChild("height").equalTo(25).addChildEventListener(new ChildEventListener() { 606 | @Override 607 | public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { 608 | System.out.println(dataSnapshot.getKey()); 609 | } 610 | 611 | // [START_EXCLUDE] 612 | @Override 613 | public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {} 614 | 615 | @Override 616 | public void onChildRemoved(DataSnapshot dataSnapshot) {} 617 | 618 | @Override 619 | public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {} 620 | 621 | @Override 622 | public void onCancelled(DatabaseError databaseError) {} 623 | // [END_EXCLUDE] 624 | }); 625 | // [END equal_to] 626 | 627 | // [START complex_combined] 628 | dinosaursRef.child("stegosaurus").child("height").addValueEventListener(new ValueEventListener() { 629 | @Override 630 | public void onDataChange(DataSnapshot stegoHeightSnapshot) { 631 | Integer favoriteDinoHeight = stegoHeightSnapshot.getValue(Integer.class); 632 | Query query = dinosaursRef.orderByChild("height").endAt(favoriteDinoHeight).limitToLast(2); 633 | query.addValueEventListener(new ValueEventListener() { 634 | @Override 635 | public void onDataChange(DataSnapshot dataSnapshot) { 636 | // Data is ordered by increasing height, so we want the first entry 637 | DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next(); 638 | System.out.println("The dinosaur just shorter than the stegosaurus is: " + firstChild.getKey()); 639 | } 640 | 641 | @Override 642 | public void onCancelled(DatabaseError databaseError) { 643 | // ... 644 | } 645 | }); 646 | } 647 | 648 | @Override 649 | public void onCancelled(DatabaseError databaseError) { 650 | // ... 651 | } 652 | }); 653 | // [END complex_combined] 654 | } 655 | 656 | public static void main(String[] args) { 657 | // write your code here 658 | } 659 | } 660 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/firebase/snippets-java/7051da2745f8f95b176c9c6347e0bb0db3de1112/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':admin' 2 | include ':database' 3 | --------------------------------------------------------------------------------