use of com.google.firebase.database.ValueEventListener in project BORED by invent2017.
the class Login method signIn.
private void signIn() {
if (usernameField.getText().toString().trim().isEmpty() || passwordField.getText().toString().trim().isEmpty()) {
Toast.makeText(this, R.string.error_field_required, Toast.LENGTH_SHORT).show();
} else {
final String username = usernameField.getText().toString();
final String password = passwordField.getText().toString();
mDataRef.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(username).exists()) {
if (dataSnapshot.child(username).child("Password").getValue(String.class).equals(password)) {
storeLocalUserData(username, password);
Toast.makeText(Login.this, "Logged in as " + username + ".", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this, MapsActivityCurrentPlace.class);
startActivity(i);
finish();
} else {
Toast.makeText(Login.this, R.string.error_incorrect_password, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Login.this, R.string.error_incorrect_username, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
use of com.google.firebase.database.ValueEventListener in project BORED by invent2017.
the class MapsActivityCurrentPlace method onMapReady.
/**
* Manipulates the map when it's available.
* This callback is triggered when the map is ready to be used.
*/
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(final Marker marker) {
LatLng markerPosition = marker.getPosition();
Location markerLocation = new Location(LocationManager.GPS_PROVIDER);
markerLocation.setLatitude(markerPosition.latitude);
markerLocation.setLongitude(markerPosition.longitude);
if (mLastKnownLocation.distanceTo(markerLocation) <= 500) {
showStoryDetails(marker);
} else {
mDataRef.child("stories").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String storyKey = (String) marker.getTag();
storyKey = storyKey.split("/")[0];
HashtagChecker hashtagChecker = new HashtagChecker(storyKey, dataSnapshot);
String hashtags = hashtagChecker.getHashtags();
if (hashtags != null) {
SingleToast.show(MapsActivityCurrentPlace.this, "This squawk contains \n" + hashtags, Toast.LENGTH_SHORT);
} else {
SingleToast.show(MapsActivityCurrentPlace.this, "This squawk does not have any hashtags.", Toast.LENGTH_SHORT);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
return true;
}
});
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
/*
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(com.projectbored.app.R.layout.custom_info_contents,
(FrameLayout)findViewById(com.projectbored.app.R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(com.projectbored.app.R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(com.projectbored.app.R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
*/
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
if (getIntent().getAction() != null) {
if (getIntent().getAction().equals(Intent.ACTION_VIEW) && getIntent().getData() != null) {
showSelectedStory(getIntent().getData().getLastPathSegment());
} else {
getStories();
}
} else {
Bundle storyDetails = getIntent().getExtras();
if (storyDetails.getString("UserStory") != null) {
showSelectedStory(storyDetails.getString("UserStory"));
} else {
String disappearingStory = storyDetails.getString("key");
getStories();
if (disappearingStory != null) {
LatLng storyPosition = new LatLng(storyDetails.getDouble("Latitude"), storyDetails.getDouble("Longitude"));
mMap.addMarker(new MarkerOptions().position(storyPosition));
}
}
}
}
use of com.google.firebase.database.ValueEventListener in project BORED by invent2017.
the class MapsActivityCurrentPlace method showSelectedStory.
private void showSelectedStory(final String storyKey) {
mMap.clear();
mDataRef.child("stories").child(storyKey).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
String[] locationArray = dataSnapshot.child("Location").getValue(String.class).split(",");
LatLng storyPosition = new LatLng(Double.parseDouble(locationArray[0]), Double.parseDouble(locationArray[1]));
Marker marker = mMap.addMarker(new MarkerOptions().position(storyPosition).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
marker.setTag(storyKey);
mMap.moveCamera(CameraUpdateFactory.newLatLng(storyPosition));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
use of com.google.firebase.database.ValueEventListener in project iosched by google.
the class SessionDetailModel method initReservationListeners.
public void initReservationListeners() {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser != null) {
mQueueReference = getQueueReference(currentUser.getUid());
mSessionReservationStatusReference = getReservationStatusReference(currentUser.getUid(), mSessionId);
mSessionReservationResultReference = getReservationResultsReference(currentUser.getUid(), mSessionId);
mSeatAvailabilityReference = getSeatAvailabilityReference(mSessionId);
mSessionReservationStatusEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String reservationStatus = dataSnapshot.getValue(String.class);
if (reservationStatus != null) {
mReservationStatus = reservationStatus;
mSessionsHelper.setReservationStatus(mSessionUri, ScheduleContract.MyReservations.fromFirebaseString(mReservationStatus), mTitle);
final DataQueryCallback<SessionDetailQueryEnum> reservationStatusCallback = mDataQueryCallbacks.get(RESERVATION_STATUS);
reservationStatusCallback.onModelUpdated(SessionDetailModel.this, RESERVATION_STATUS);
}
} catch (DatabaseException e) {
LOGE(TAG, e.getMessage());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
LOGE(TAG, databaseError.getMessage());
}
};
mSessionReservationResultEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String reservationResult = dataSnapshot.getValue(String.class);
if (reservationResult != null) {
mReservationResult = reservationResult;
DataQueryCallback<SessionDetailQueryEnum> reservationResultCallback = mDataQueryCallbacks.get(RESERVATION_RESULT);
reservationResultCallback.onModelUpdated(SessionDetailModel.this, RESERVATION_RESULT);
mSessionReservationResultReference.removeEventListener(this);
}
} catch (DatabaseException e) {
LOGE(TAG, e.getMessage());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
LOGE(TAG, databaseError.getMessage());
}
};
mQueueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
DataQueryCallback<SessionDetailQueryEnum> reservationPendingCallback = mDataQueryCallbacks.get(RESERVATION_PENDING);
QueueAction queueAction = dataSnapshot.getValue(QueueAction.class);
if (queueAction == null) {
LOGD(TAG, "Exit queue");
mReturnPending = false;
mReservationPending = false;
mQueueReference.removeEventListener(this);
reservationPendingCallback.onModelUpdated(SessionDetailModel.this, RESERVATION_PENDING);
}
} catch (DatabaseException e) {
LOGE(TAG, e.getMessage());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
LOGE(TAG, databaseError.getMessage());
}
};
mSeatAvailabilityEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataQueryCallback<SessionDetailQueryEnum> seatAvailabilityCallback = mDataQueryCallbacks.get(RESERVATION_SEAT_AVAILABILITY);
Boolean seatsAvailable = dataSnapshot.getValue(Boolean.class);
if (seatsAvailable != null) {
mSeatsAvailable = seatsAvailable;
seatAvailabilityCallback.onModelUpdated(SessionDetailModel.this, RESERVATION_SEAT_AVAILABILITY);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
LOGE(TAG, databaseError.getMessage());
}
};
mSessionReservationStatusReference.addValueEventListener(mSessionReservationStatusEventListener);
mSeatAvailabilityReference.addValueEventListener(mSeatAvailabilityEventListener);
} else {
LOGD(TAG, "Not signed in.");
invalidateReservationCache();
DataQueryCallback<SessionDetailQueryEnum> authCallback = mDataQueryCallbacks.get(AUTH_REGISTRATION);
authCallback.onModelUpdated(SessionDetailModel.this, AUTH_REGISTRATION);
}
}
use of com.google.firebase.database.ValueEventListener in project iosched by google.
the class LoadSessionsServlet method doGet.
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
// Check that only admins or other allowed users can make this call.
if (!performBasicChecking(req, resp)) {
return;
}
// Pull existing session and room data from Google Cloud Storage.
JsonParser jsonParser = new JsonParser();
String manifestStr = IOUtils.toString(new URL(Config.CLOUD_STORAGE_BASE_URL + MANIFEST_FILENAME).openStream());
JsonElement jManifest = jsonParser.parse(manifestStr);
JsonArray jDataFiles = jManifest.getAsJsonObject().get("data_files").getAsJsonArray();
String sessionDataFileName = null;
for (int i = 0; i < jDataFiles.size(); i++) {
String filename = jDataFiles.get(i).getAsString();
if (filename.startsWith("session_data")) {
sessionDataFileName = filename;
break;
}
}
if (sessionDataFileName == null) {
// Unable to find session data to load.
resp.setContentType("text/plain");
resp.getWriter().println("Unable to find session data to load.");
return;
}
// Get session and room data from file in GCS.
String sessionDataStr = IOUtils.toString(new URL(Config.CLOUD_STORAGE_BASE_URL + sessionDataFileName).openStream());
JsonElement jSessionData = jsonParser.parse(sessionDataStr);
// Extract rooms and sessions
final JsonArray jRooms = jSessionData.getAsJsonObject().get(ROOMS_KEY).getAsJsonArray();
final JsonArray jSessions = jSessionData.getAsJsonObject().get(SESSIONS_KEY).getAsJsonArray();
// Only sessions that are of type TYPE_SESSIONS can be reserved so remove those that do not
// have this type.
List<JsonElement> sessionsToRemove = new ArrayList<>();
for (JsonElement jSession : jSessions) {
// TODO: keynotes have a better type.
if (jSession.getAsJsonObject().get("id").getAsString().startsWith("__keynote")) {
sessionsToRemove.add(jSession);
continue;
}
JsonArray jTags = jSession.getAsJsonObject().get("tags").getAsJsonArray();
boolean isReservable = false;
for (JsonElement jTag : jTags) {
if (jTag.getAsString().equals("TYPE_SESSIONS")) {
isReservable = true;
break;
}
}
if (!isReservable) {
sessionsToRemove.add(jSession);
}
}
for (JsonElement jsonElement : sessionsToRemove) {
jSessions.remove(jsonElement);
}
log.info("Non-Reservable session count: " + sessionsToRemove.size());
log.info("Reservable session count: " + jSessions.size());
resp.setContentType("text/plain");
resp.getWriter().println("Room and session data retrieved.");
// Initialize Firebase app with service account credentials.
FirebaseOptions options = new FirebaseOptions.Builder().setCredential(FirebaseCredentials.fromCertificate(getServletContext().getResourceAsStream("/WEB-INF/io2017-backend-dev-serv-cred.json"))).setDatabaseUrl("https://io2017-backend-dev.firebaseio.com/").build();
try {
FirebaseApp.initializeApp(options);
log.info("Initialized Firebase");
} catch (Exception e) {
// Firebase Instance already exists.
log.info("Firebase already initialized");
}
// Session retrieval task.
final TaskCompletionSource<Map<String, Session>> sessionsTaskCompletionSource = new TaskCompletionSource<>();
final Task<Map<String, Session>> sessionsTask = sessionsTaskCompletionSource.getTask();
// Get Firebase Database reference to sessions path, add listener for single event.
final FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
defaultDatabase.getReference(PATH_SESSIONS).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Session> sessions = new HashMap<>();
for (DataSnapshot sessionSnapshot : dataSnapshot.getChildren()) {
Session s = sessionSnapshot.getValue(Session.class);
sessions.put(sessionSnapshot.getKey(), s);
}
sessionsTaskCompletionSource.setResult(sessions);
}
@Override
public void onCancelled(DatabaseError databaseError) {
log.warning("RTDB error: " + databaseError.getMessage());
}
});
try {
// Wait for the sessions from RTDB.
Map<String, Session> rtdbSessions = Tasks.await(sessionsTask);
// Update sessions in RTDB with values from GCS.
for (String sessionId : rtdbSessions.keySet()) {
// Update session task.
final TaskCompletionSource<Void> updateSessionTCS = new TaskCompletionSource<>();
final Task<Void> updateSessionTCSTask = updateSessionTCS.getTask();
// Check that GCS has a matching session and room as the one from RTDB.
JsonObject jSession = getSession(sessionId, jSessions);
if (jSession != null) {
JsonObject jRoom = getRoom(jSession, jRooms);
if (jRoom != null) {
final int gcsCap = Long.valueOf(Math.round(jRoom.get(CAPACITY_KEY).getAsInt() * RESERVABLE_CAPACITY_PERCENTAGE)).intValue();
final String gcsRoomName = jRoom.get(NAME_KEY).getAsString();
final long gcsStartTime = getTimeInMillis(jSession, START_TIME_KEY);
final long gcsEndTime = getTimeInMillis(jSession, END_TIME_KEY);
final String gcsTitle = jSession.get(TITLE_KEY).getAsString();
// Update session in a transaction.
defaultDatabase.getReference().child(PATH_SESSIONS).child(sessionId).runTransaction(new Handler() {
@Override
public Result doTransaction(MutableData mutableData) {
Session session = mutableData.getValue(Session.class);
if (session != null) {
// Update start and end times of session in RTDB.
session.time_start = gcsStartTime;
session.time_end = gcsEndTime;
// Update session title.
session.title = gcsTitle;
// Update session room name.
session.room_name = gcsRoomName;
int currResCount = session.seats.reserved;
boolean currHasSeats = session.seats.seats_available;
if (currResCount > gcsCap) {
// If there are to many reservations move extras to waitlist.
int resToMove = currResCount - gcsCap;
moveReservationsToWaitList(resToMove, session);
} else if (currResCount < gcsCap && !currHasSeats) {
// If there is space and a waitlist, promote as many as possible from the
// waitlist.
int numSeatsAvailable = gcsCap - currResCount;
promoteFromWaitList(currResCount, numSeatsAvailable, session);
}
// Update session capacity.
session.seats.capacity = gcsCap;
mutableData.setValue(session);
}
return success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
// Signal that session update is complete.
updateSessionTCS.setResult(null);
}
});
// Wait for session update to complete.
Tasks.await(updateSessionTCSTask);
}
// Remove updated sessions from list of sessions to be added.
jSessions.remove(jSession);
}
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
// Add all sessions that were retrieved from GCS but did not already in RTDB.
for (int i = 0; i < jSessions.size(); i++) {
JsonObject jSession = jSessions.get(i).getAsJsonObject();
String sessionId = jSession.get(ID_KEY).getAsString();
String sessionTitle = jSession.get(TITLE_KEY).getAsString();
String roomId = jSession.get(ROOM_KEY).getAsString();
JsonObject jRoom = getRoom(roomId, jRooms);
int capacity = Long.valueOf(Math.round(jRoom.get(CAPACITY_KEY).getAsInt() * RESERVABLE_CAPACITY_PERCENTAGE)).intValue();
String sessionRoomName = jRoom.get(NAME_KEY).getAsString();
long startTime = getTimeInMillis(jSession, START_TIME_KEY);
long endTime = getTimeInMillis(jSession, END_TIME_KEY);
Session session = new Session();
session.title = sessionTitle;
session.room_name = sessionRoomName;
session.time_end = endTime;
session.time_start = startTime;
Seats seats = new Seats();
seats.capacity = capacity;
seats.reserved = 0;
seats.seats_available = true;
seats.waitlisted = false;
session.seats = seats;
defaultDatabase.getReference(PATH_SESSIONS).child(sessionId).setValue(session);
}
resp.getWriter().println("Sessions added to RTDB.");
}
Aggregations