|
4 | 4 | import com.google.firebase.FirebaseApp; |
5 | 5 | import com.google.firebase.FirebaseOptions; |
6 | 6 | import lombok.extern.slf4j.Slf4j; |
| 7 | +import org.springframework.beans.factory.annotation.Value; |
7 | 8 | import org.springframework.stereotype.Service; |
8 | 9 |
|
9 | 10 | import javax.annotation.PostConstruct; |
|
13 | 14 | import java.io.InputStream; |
14 | 15 |
|
15 | 16 | @Service |
| 17 | +@Slf4j |
16 | 18 | public class FirebaseInitialization { |
17 | 19 |
|
| 20 | + private static final String DEFAULT_FIREBASE_RESOURCE = "ontime-c63f1-firebase-adminsdk-fbsvc-a043cdc829.json"; |
| 21 | + |
| 22 | + @Value("${firebase.service-account.path:}") |
| 23 | + private String serviceAccountPath; |
| 24 | + |
18 | 25 | @PostConstruct |
19 | 26 | public void initialize() { |
20 | | - try { |
21 | | - InputStream serviceAccount = getClass().getClassLoader().getResourceAsStream("ontime-c63f1-firebase-adminsdk-fbsvc-a043cdc829.json"); |
22 | | - if (serviceAccount == null) { |
23 | | - throw new FileNotFoundException("Resource not found: ontime-c63f1-firebase-adminsdk-fbsvc-a043cdc829.json"); |
24 | | - } |
25 | | - |
| 27 | + try (InputStream serviceAccount = openServiceAccount()) { |
26 | 28 | FirebaseOptions options = new FirebaseOptions.Builder() |
27 | 29 | .setCredentials(GoogleCredentials.fromStream(serviceAccount)) |
28 | 30 | .build(); |
29 | 31 |
|
30 | | - FirebaseApp.initializeApp(options); |
| 32 | + if (FirebaseApp.getApps().isEmpty()) { |
| 33 | + FirebaseApp.initializeApp(options); |
| 34 | + } |
31 | 35 | } catch (IOException e) { |
32 | | - e.printStackTrace(); |
| 36 | + log.error("Failed to initialize Firebase", e); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private InputStream openServiceAccount() throws IOException { |
| 41 | + if (serviceAccountPath != null && !serviceAccountPath.isBlank()) { |
| 42 | + return new FileInputStream(serviceAccountPath); |
| 43 | + } |
| 44 | + |
| 45 | + InputStream serviceAccount = getClass().getClassLoader().getResourceAsStream(DEFAULT_FIREBASE_RESOURCE); |
| 46 | + if (serviceAccount == null) { |
| 47 | + throw new FileNotFoundException("Resource not found: " + DEFAULT_FIREBASE_RESOURCE); |
33 | 48 | } |
| 49 | + return serviceAccount; |
34 | 50 | } |
35 | 51 | } |
0 commit comments