|
| 1 | +/* |
| 2 | + * Copyright 2016 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.example.GaeFirebaseEventProxy; |
| 18 | + |
| 19 | +import java.io.FileInputStream; |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.InputStream; |
| 22 | +import java.net.HttpURLConnection; |
| 23 | +import java.net.URL; |
| 24 | +import java.net.URLEncoder; |
| 25 | +import java.util.HashMap; |
| 26 | +import java.util.Map; |
| 27 | +import java.util.Properties; |
| 28 | +import java.util.logging.Logger; |
| 29 | + |
| 30 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 31 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 32 | +import com.firebase.client.AuthData; |
| 33 | +import com.firebase.client.DataSnapshot; |
| 34 | +import com.firebase.client.Firebase; |
| 35 | +import com.firebase.client.FirebaseError; |
| 36 | +import com.firebase.client.ValueEventListener; |
| 37 | +import com.firebase.security.token.TokenGenerator; |
| 38 | +import com.google.appengine.api.utils.SystemProperty; |
| 39 | + |
| 40 | +public class FirebaseEventProxy { |
| 41 | + |
| 42 | + private static final Logger log = Logger.getLogger(FirebaseEventProxy.class.getName()); |
| 43 | + |
| 44 | + private String firebaseAuthToken; |
| 45 | + |
| 46 | + public FirebaseEventProxy() { |
| 47 | + // Store Firebase authentication token as an instance variable. |
| 48 | + this.firebaseAuthToken = this.getFirebaseAuthToken(this.getFirebaseSecret()); |
| 49 | + } |
| 50 | + |
| 51 | + public void start() { |
| 52 | + String FIREBASE_LOCATION = "https://gae-fb-proxy.firebaseio.com/"; |
| 53 | + Firebase firebase = new Firebase(FIREBASE_LOCATION); |
| 54 | + |
| 55 | + // Authenticate with Firebase |
| 56 | + firebase.authWithCustomToken(this.firebaseAuthToken, new Firebase.AuthResultHandler() { |
| 57 | + @Override |
| 58 | + public void onAuthenticationError(FirebaseError error) { |
| 59 | + log.severe("Firebase login error: " + error.getMessage()); |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public void onAuthenticated(AuthData auth) { |
| 64 | + log.info("Firebase login successful"); |
| 65 | + } |
| 66 | + }); |
| 67 | + |
| 68 | + // Subscribe to value events. Depending on use case, you may want to subscribe to child events |
| 69 | + // through childEventListener. |
| 70 | + firebase.addValueEventListener(new ValueEventListener() { |
| 71 | + @Override |
| 72 | + public void onDataChange(DataSnapshot snapshot) { |
| 73 | + if (snapshot.exists()) { |
| 74 | + try { |
| 75 | + // Convert value to JSON using Jackson |
| 76 | + String json = new ObjectMapper().writeValueAsString(snapshot.getValue()); |
| 77 | + |
| 78 | + // Replace the URL with the url of your own listener app. |
| 79 | + URL dest = new URL("http://gae-firebase-listener-python.appspot.com/log"); |
| 80 | + HttpURLConnection connection = (HttpURLConnection) dest.openConnection(); |
| 81 | + connection.setRequestMethod("POST"); |
| 82 | + connection.setDoOutput(true); |
| 83 | + |
| 84 | + // Rely on X-Appengine-Inbound-Appid to authenticate. Turning off redirects is |
| 85 | + // required to enable. |
| 86 | + connection.setInstanceFollowRedirects(false); |
| 87 | + |
| 88 | + // Fill out header if in dev environment |
| 89 | + if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) { |
| 90 | + connection.setRequestProperty("X-Appengine-Inbound-Appid", "dev-instance"); |
| 91 | + } |
| 92 | + |
| 93 | + // Put Firebase data into http request |
| 94 | + StringBuilder stringBuilder = new StringBuilder(); |
| 95 | + stringBuilder.append("&fbSnapshot="); |
| 96 | + stringBuilder.append(URLEncoder.encode(json, "UTF-8")); |
| 97 | + connection.getOutputStream().write(stringBuilder.toString().getBytes()); |
| 98 | + if (connection.getResponseCode() != 200) { |
| 99 | + log.severe("Forwarding failed"); |
| 100 | + } else { |
| 101 | + log.info("Sent: " + json); |
| 102 | + } |
| 103 | + } catch (JsonProcessingException e) { |
| 104 | + log.severe("Unable to convert Firebase response to JSON: " + e.getMessage()); |
| 105 | + } catch (IOException e) { |
| 106 | + log.severe("Error in connecting to app engine: " + e.getMessage()); |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + @Override |
| 112 | + public void onCancelled(FirebaseError error) { |
| 113 | + log.severe("Firebase connection cancelled: " + error.getMessage()); |
| 114 | + } |
| 115 | + }); |
| 116 | + } |
| 117 | + |
| 118 | + private String getFirebaseSecret() { |
| 119 | + Properties props = new Properties(); |
| 120 | + try { |
| 121 | + // Read from src/main/webapp/firebase-secrets.properties |
| 122 | + InputStream inputStream = new FileInputStream("firebase-secret.properties"); |
| 123 | + props.load(inputStream); |
| 124 | + return props.getProperty("firebaseSecret"); |
| 125 | + } catch (java.net.MalformedURLException e) { |
| 126 | + throw new RuntimeException( |
| 127 | + "Error reading firebase secrets from file: src/main/webapp/firebase-sercrets.properties: " |
| 128 | + + e.getMessage()); |
| 129 | + } catch (IOException e) { |
| 130 | + throw new RuntimeException( |
| 131 | + "Error reading firebase secrets from file: src/main/webapp/firebase-sercrets.properties: " |
| 132 | + + e.getMessage()); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + private String getFirebaseAuthToken(String firebaseSecret) { |
| 137 | + Map<String, Object> authPayload = new HashMap<String, Object>(); |
| 138 | + // uid and provider will have to match what you have in your firebase security rules |
| 139 | + authPayload.put("uid", "gae-firebase-event-proxy"); |
| 140 | + authPayload.put("provider", "com.example"); |
| 141 | + TokenGenerator tokenGenerator = new TokenGenerator(firebaseSecret); |
| 142 | + return tokenGenerator.createToken(authPayload); |
| 143 | + } |
| 144 | +} |
0 commit comments