Don't panic if no certificates found

Getting the first certificate will panic if there are no certificates,
which can happen when AllowMissingDependencies is set and the
certificate property is a module reference to a missing module.
Only get the first certificate if the list is not nil.

Use mainCertificate since it handles the logic already.

Test: TestAppMissingCertificateAllowMissingDependencies
Bug: 283102635
Change-Id: I8b27f65aa7d071041171ad45ac52bf47fa31bf2b
diff --git a/java/app.go b/java/app.go
index 3344647..e095092 100755
--- a/java/app.go
+++ b/java/app.go
@@ -585,19 +585,6 @@
 		certificates = append([]Certificate{mainCert}, certificates...)
 	}
 
-	if !m.Platform() {
-		certPath := certificates[0].Pem.String()
-		systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
-		if strings.HasPrefix(certPath, systemCertPath) {
-			enforceSystemCert := ctx.Config().EnforceSystemCertificate()
-			allowed := ctx.Config().EnforceSystemCertificateAllowList()
-
-			if enforceSystemCert && !inList(m.Name(), allowed) {
-				ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
-			}
-		}
-	}
-
 	if len(certificates) > 0 {
 		mainCertificate = certificates[0]
 	} else {
@@ -613,6 +600,20 @@
 		}
 	}
 
+	if !m.Platform() {
+		certPath := mainCertificate.Pem.String()
+		systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
+		if strings.HasPrefix(certPath, systemCertPath) {
+			enforceSystemCert := ctx.Config().EnforceSystemCertificate()
+			allowed := ctx.Config().EnforceSystemCertificateAllowList()
+
+			if enforceSystemCert && !inList(m.Name(), allowed) {
+				ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
+			}
+		}
+	}
+
+
 	return mainCertificate, certificates
 }