1+ // Copyright 2022 Google LLC
2+ //
3+ // Licensed under the Apache License, Version 2.0 (the "License");
4+ // you may not use this file except in compliance with the License.
5+ // You may obtain a copy of the License at
6+ //
7+ // https://www.apache.org/licenses/LICENSE-2.0
8+ //
9+ // Unless required by applicable law or agreed to in writing, software
10+ // distributed under the License is distributed on an "AS IS" BASIS,
11+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+ // See the License for the specific language governing permissions and
13+ // limitations under the License.
14+
15+
16+ // [START gmail_update_smime_certs]
17+ import com .google .api .client .http .HttpRequestInitializer ;
18+ import com .google .api .client .http .javanet .NetHttpTransport ;
19+ import com .google .api .client .json .gson .GsonFactory ;
20+ import com .google .api .services .gmail .Gmail ;
21+ import com .google .api .services .gmail .GmailScopes ;
22+ import com .google .api .services .gmail .model .ListSmimeInfoResponse ;
23+ import com .google .api .services .gmail .model .SmimeInfo ;
24+ import com .google .auth .http .HttpCredentialsAdapter ;
25+ import com .google .auth .oauth2 .GoogleCredentials ;
26+
27+ import java .io .IOException ;
28+ import java .time .Instant ;
29+ import java .time .LocalDateTime ;
30+ import java .time .ZoneId ;
31+ import java .util .Collections ;
32+
33+ /* Class to demonstrate the use of Gmail Update Smime Certificate API*/
34+ public class UpdateSmimeCerts {
35+ /**
36+ * Update S/MIME certificates for the user.
37+ *
38+ * <p>First performs a lookup of all certificates for a user. If there are no certificates, or
39+ * they all expire before the specified date/time, uploads the certificate in the specified file.
40+ * If the default certificate is expired or there was no default set, chooses the certificate with
41+ * the expiration furthest into the future and sets it as default.
42+ *
43+ * @param userId User's email address.
44+ * @param sendAsEmail The "send as" email address, or None if it should be the same as user_id.
45+ * @param certFilename Name of the file containing the S/MIME certificate.
46+ * @param certPassword Password for the certificate file, or None if the file is not
47+ * password-protected.
48+ * @param expireTime DateTime object against which the certificate expiration is compared. If
49+ * None, uses the current time. @ returns: The ID of the default certificate.
50+ * @return The ID of the default certifcate.
51+ */
52+ public static String updateSmimeCerts (String userId ,
53+ String sendAsEmail ,
54+ String certFilename ,
55+ String certPassword ,
56+ LocalDateTime expireTime )
57+ throws IOException {
58+ /* Load pre-authorized user credentials from the environment.
59+ TODO(developer) - See https://developers.google.com/identity for
60+ guides on implementing OAuth2 for your application. */
61+ GoogleCredentials credentials = GoogleCredentials .getApplicationDefault ()
62+ .createScoped (Collections .singletonList (GmailScopes .GMAIL_SETTINGS_SHARING ));
63+ HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter (
64+ credentials );
65+
66+ // Create the gmail API client
67+ Gmail service = new Gmail .Builder (new NetHttpTransport (),
68+ GsonFactory .getDefaultInstance (),
69+ requestInitializer )
70+ .setApplicationName ("Gmail samples" )
71+ .build ();
72+
73+ if (sendAsEmail == null ) {
74+ sendAsEmail = userId ;
75+ }
76+
77+ ListSmimeInfoResponse listResults ;
78+ try {
79+ listResults = service .users ().settings ().sendAs ().smimeInfo ().list (userId , sendAsEmail ).execute ();
80+ } catch (IOException e ) {
81+ System .err .printf ("An error occurred during list: %s\n " , e );
82+ return null ;
83+ }
84+
85+ String defaultCertId = null ;
86+ String bestCertId = null ;
87+ LocalDateTime bestCertExpire = LocalDateTime .MIN ;
88+
89+ if (expireTime == null ) {
90+ expireTime = LocalDateTime .now ();
91+ }
92+ if (listResults != null && listResults .getSmimeInfo () != null ) {
93+ for (SmimeInfo smimeInfo : listResults .getSmimeInfo ()) {
94+ String certId = smimeInfo .getId ();
95+ boolean isDefaultCert = smimeInfo .getIsDefault ();
96+ if (isDefaultCert ) {
97+ defaultCertId = certId ;
98+ }
99+ LocalDateTime exp =
100+ LocalDateTime .ofInstant (
101+ Instant .ofEpochMilli (smimeInfo .getExpiration ()), ZoneId .systemDefault ());
102+ if (exp .isAfter (expireTime )) {
103+ if (exp .isAfter (bestCertExpire )) {
104+ bestCertId = certId ;
105+ bestCertExpire = exp ;
106+ }
107+ } else {
108+ if (isDefaultCert ) {
109+ defaultCertId = null ;
110+ }
111+ }
112+ }
113+ }
114+ if (defaultCertId == null ) {
115+ String defaultId = bestCertId ;
116+ if (defaultId == null && certFilename != null ) {
117+ SmimeInfo insertResults = InsertSmimeInfo .insertSmimeInfo (certFilename ,
118+ certPassword ,
119+ userId ,
120+ sendAsEmail );
121+ if (insertResults != null ) {
122+ defaultId = insertResults .getId ();
123+ }
124+ }
125+
126+ if (defaultId != null ) {
127+ try {
128+ service .users ().settings ().sendAs ().smimeInfo ().setDefault (userId , sendAsEmail , defaultId ).execute ();
129+ return defaultId ;
130+ } catch (IOException e ) {
131+ System .err .printf ("An error occured during setDefault: %s" , e );
132+ }
133+ }
134+ } else {
135+ return defaultCertId ;
136+ }
137+
138+ return null ;
139+ }
140+ }
141+ // [END gmail_update_smime_certs]
0 commit comments