Skip to content

Instantly share code, notes, and snippets.

@RR-Helpdesk
Last active June 10, 2023 12:33
Show Gist options
  • Save RR-Helpdesk/72c40a0b02efea22bec7c75a34b9a73d to your computer and use it in GitHub Desktop.
Save RR-Helpdesk/72c40a0b02efea22bec7c75a34b9a73d to your computer and use it in GitHub Desktop.
Application
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START apps_script_api_quickstart]
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.script.Script;
import com.google.api.services.script.model.Content;
import com.google.api.services.script.model.CreateProjectRequest;
import com.google.api.services.script.model.File;
import com.google.api.services.script.model.Project;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AppsScriptQuickstart {
private static final String APPLICATION_NAME = "Apps Script API Java Quickstart";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved credentials folder at /secret.
*/
private static final List<String> SCOPES =
Collections.singletonList("https://www.googleapis.com/auth/script.projects");
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
*
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
throws IOException {
// Load client secrets.
InputStream in = AppsScriptQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Script service =
new Script.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
Script.Projects projects = service.projects();
// Creates a new script project.
Project createOp = projects.create(new CreateProjectRequest().setTitle("My Script")).execute();
// Uploads two files to the project.
File file1 = new File()
.setName("hello")
.setType("SERVER_JS")
.setSource("function helloWorld() {\n console.log(\"Hello, world!\");\n}");
File file2 = new File()
.setName("appsscript")
.setType("JSON")
.setSource("{\"timeZone\":\"America/New_York\",\"exceptionLogging\":\"CLOUD\"}");
Content content = new Content().setFiles(Arrays.asList(file1, file2));
Content updatedContent = projects.updateContent(createOp.getScriptId(), content).execute();
// Logs the project URL.
System.out.printf("https://script.google.com/d/%s/edit\n", updatedContent.getScriptId());
}
}
// [END apps_script_api_quickstart]
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START gmail_update_signature]
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.ListSendAsResponse;
import com.google.api.services.gmail.model.SendAs;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
/* Class to demonstrate the use of Gmail Update Signature API */
public class UpdateSignature {
/**
* Update the gmail signature.
*
* @return the updated signature id , {@code null} otherwise.
* @throws IOException - if service account credentials file not found.
*/
public static String updateGmailSignature() throws IOException {
/* Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity for
guides on implementing OAuth2 for your application. */
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(GmailScopes.GMAIL_SETTINGS_BASIC);
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Create the gmail API client
Gmail service = new Gmail.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("Gmail samples")
.build();
try {
SendAs primaryAlias = null;
ListSendAsResponse aliases = service.users().settings().sendAs().list("me").execute();
for (SendAs alias : aliases.getSendAs()) {
if (alias.getIsPrimary()) {
primaryAlias = alias;
break;
}
}
// Updating a new signature
SendAs aliasSettings = new SendAs().setSignature("Automated Signature");
SendAs result = service.users().settings().sendAs().patch(
"me",
primaryAlias.getSendAsEmail(),
aliasSettings)
.execute();
//Prints the updated signature
System.out.println("Updated signature - " + result.getSignature());
return result.getSignature();
} catch (GoogleJsonResponseException e) {
// TODO(developer) - handle error appropriately
GoogleJsonError error = e.getDetails();
if (error.getCode() == 403) {
System.err.println("Unable to update signature: " + e.getDetails());
} else {
throw e;
}
}
return null;
}
}
// [END gmail_update_signature]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment