Skip to content

GDGRzeszow/FirebaseSpringCodelab

Repository files navigation

GDG Christmas Codelabs

#Firebase Admin with Spring codelabs Welcome to Firebase Admin with Spring codelabs! In this codelab, you'll learn how to use the Firebase with server side code in Java language.

Codelab created by @GDGRzeszow for "Firebase Christmas Codelabs" and works with Firebase Android codelab which you can find here

On master branch you can find code with empty spaces to fill. On develop branch you can find code prepared to run.

##Steps

  1. First we need to generate our private key. It will allow us to do all operations at database. To do it login into your Firebase Console and go to your "Project Settings". Next open "Service Accounts" and generate new private key.

Private key generation

You can rename downloaded file to "google-services.json" and replace file in resources folder or copy content and paste into that file.

  1. To have "almost working" project we need to change one more thing. Open application.yml and insert database url. You can find it by clicking "Database" in Firebase Console.

  2. Now we have to initialize our FirebaseService. To do it open Application and add line. This will start service after app start.

  context.getBean(FirebaseService.class).startFirebaseListener();
  1. At this moment we are listening for all changes in messages node. It's time to do something with it! Open class FirebaseServiceImpl. In method onDataChange same as in Android we get DataSnapshots. Our proposition is to do it in this way:
Iterable<DataSnapshot> iterable = dataSnapshot.getChildren();
StreamSupport.stream(iterable.spliterator(), false)
        .forEach(data -> {
            FriendlyMessage friendlyMessage = data.getValue(FriendlyMessage.class);
            final String text = friendlyMessage.getText();
            final String censored = censorService.censorWord(text);
            if (!text.equals(censored)) {
                friendlyMessage.setText(censored);
                data.getRef().setValue(friendlyMessage);
            }
        });

With this code we check every message using CensorService. So let's modify what we are checking.

  1. In CensorServiceImpl you will find two empty spaces. At first TODO you can define which words you want to looking for. Put them as Strings in Arrays.asList().
final List<String> badWords =
        Arrays.asList("veryBadWord","anotherOne");

To have some fun with censoring we have to implement it in censorWord method. For example we can replace all occurrences of defines words with using simple replaceAll method. To do it we have prepared Pattern object.

text = text.replaceAll(pattern.pattern(), "***");

Now run your android app and try to type some censored word. It will be changed to stars!

Result of codelabs