use of com.google.firebase.database.FirebaseDatabase in project OnlineCanteen by josephgunawan97.
the class AccountUtil method createMappingEmailToUid.
private static Task<Void> createMappingEmailToUid() {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("emailtouid");
return reference.child(firebaseUser.getEmail().replaceAll(Pattern.quote("."), ",")).setValue(firebaseUser.getUid());
}
use of com.google.firebase.database.FirebaseDatabase in project OnlineCanteen by josephgunawan97.
the class AccountUtil method createEmptyWallet.
private static Task<Void> createEmptyWallet() {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("wallet");
return reference.child(firebaseUser.getUid()).setValue(0);
}
use of com.google.firebase.database.FirebaseDatabase 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.");
}
use of com.google.firebase.database.FirebaseDatabase in project NienLuanChuyenNganh-Android by AuNguyenTrungNguyen.
the class AddJobActivity method addJob.
private void addJob() {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(getResources().getString(R.string.dialog));
String title = edtTitle.getText().toString();
String description = edtDescription.getText().toString();
String timeStart = tvStart.getText().toString();
String timeEnd = tvEnd.getText().toString();
if (!title.equals("") && !description.equals("") && !timeStart.equals(getResources().getString(R.string.job_start)) && !timeEnd.equals(getResources().getString(R.string.job_end)) && listEmployees.size() > 0) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String now = dateFormat.format(date);
if (compareDate(now, timeStart) && compareDate(timeStart, timeEnd)) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference().child(Constant.NODE_CONG_VIEC);
String idJob = reference.push().getKey();
SharedPreferences preferences = getSharedPreferences(Constant.PREFERENCE_NAME, MODE_PRIVATE);
String idManage = preferences.getString(Constant.PREFERENCE_KEY_ID, "");
List<String> listIdMember = new ArrayList();
for (EmployeeObject object : listEmployees) {
listIdMember.add(object.getIdEmployee());
}
JobObject jobObject = new JobObject();
jobObject.setIdJob(idJob);
jobObject.setIdManageJob(idManage);
jobObject.setTitleJob(title);
jobObject.setDescriptionJob(description);
jobObject.setStartDateJob(timeStart);
jobObject.setEndDateJob(timeEnd);
jobObject.setStatusJob(Constant.NOT_RECEIVED);
jobObject.setListIdMember(listIdMember);
dialog.show();
reference.child(idJob).setValue(jobObject).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
Toast.makeText(AddJobActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Date is fail!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Data is empty!", Toast.LENGTH_SHORT).show();
}
}
use of com.google.firebase.database.FirebaseDatabase in project Pepper_v0 by SamDaQueen.
the class MenuActivity method onCreate.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Bundle bundle = getIntent().getExtras();
toolbar = getSupportActionBar();
assert toolbar != null;
toolbar.setDisplayHomeAsUpEnabled(true);
ListView listView = findViewById(R.id.menuitemView);
menuItems = new ArrayList<>();
menuAdapter = new MenuAdapter(this, R.layout.item_menu, menuItems);
listView.setAdapter(menuAdapter);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
switch(bundle.getString("category")) {
case "tea":
toolbar.setTitle("Tea & Coffee");
databaseReference = firebaseDatabase.getReference().child("Tea & Coffee");
break;
case "snacks":
toolbar.setTitle("Snacks");
databaseReference = firebaseDatabase.getReference().child("Snacks");
break;
case "chat":
toolbar.setTitle("Bombay Chat");
databaseReference = firebaseDatabase.getReference().child("Bombay Chat");
break;
case "frankie":
toolbar.setTitle("Frankie");
databaseReference = firebaseDatabase.getReference().child("Frankie");
break;
case "south":
toolbar.setTitle("South Indian");
databaseReference = firebaseDatabase.getReference().child("South Indian");
break;
case "lunch":
toolbar.setTitle("Lunch & Dinner");
databaseReference = firebaseDatabase.getReference().child("Lunch & Dinner");
break;
case "sandwich":
toolbar.setTitle("Sandwich");
databaseReference = firebaseDatabase.getReference().child("Sandwich");
break;
case "pavbhaji":
toolbar.setTitle("Pav Bhaji");
databaseReference = firebaseDatabase.getReference().child("Pav Bhaji");
break;
case "chinese":
toolbar.setTitle("Chinese Dishes");
databaseReference = firebaseDatabase.getReference().child("Chinese Dishes");
break;
case "salad":
toolbar.setTitle("Curd, Salad & Fruits");
databaseReference = firebaseDatabase.getReference().child("Curd, Salad and Fruits");
break;
case "spldosa":
toolbar.setTitle("Special Dosa");
databaseReference = firebaseDatabase.getReference().child("Special Dosa");
break;
case "tandoori":
toolbar.setTitle("Tandoori");
databaseReference = firebaseDatabase.getReference().child("Tandoori");
break;
case "splpunjabi":
toolbar.setTitle("Special Punjabi");
databaseReference = firebaseDatabase.getReference().child("Special Punjabi");
break;
case "punjabi":
toolbar.setTitle("Punjabi");
databaseReference = firebaseDatabase.getReference().child("Punjabi");
break;
case "kofta":
toolbar.setTitle("Kofta Dishes");
databaseReference = firebaseDatabase.getReference().child("Kofta Dishes");
break;
case "rice":
toolbar.setTitle("Basmati Rice");
databaseReference = firebaseDatabase.getReference().child("Basmati Rice");
break;
case "starters":
toolbar.setTitle("Starters");
databaseReference = firebaseDatabase.getReference().child("Starters");
break;
case "juice":
toolbar.setTitle("Juices And Shakes");
databaseReference = firebaseDatabase.getReference().child("Juices And Shakes");
break;
}
attachDatabaseReadListener();
checker = true;
// Toast.makeText(this, String.valueOf(checker), Toast.LENGTH_SHORT).show();
}
Aggregations