/** * @license Copyright Google Inc. *

* 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. */ public class Execute { // [START apps_script_api_execute] /** * Create a HttpRequestInitializer from the given one, except set * the HTTP read timeout to be longer than the default (to allow * called scripts time to execute). * * @param {HttpRequestInitializer} requestInitializer the initializer * to copy and adjust; typically a Credential object. * @return an initializer with an extended read timeout. */ private static HttpRequestInitializer setHttpTimeout( final HttpRequestInitializer requestInitializer) { return new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { requestInitializer.initialize(httpRequest); // This allows the API to call (and avoid timing out on) // functions that take up to 6 minutes to complete (the maximum // allowed script run time), plus a little overhead. httpRequest.setReadTimeout(380000); } }; } /** * Build and return an authorized Script client service. * * @param {Credential} credential an authorized Credential object * @return an authorized Script client service */ public static Script getScriptService() throws IOException { Credential credential = authorize(); return new Script.Builder( HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(credential)) .setApplicationName(APPLICATION_NAME) .build(); } /** * Interpret an error response returned by the API and return a String * summary. * * @param {Operation} op the Operation returning an error response * @return summary of error response, or null if Operation returned no * error */ public static String getScriptError(Operation op) { if (op.getError() == null) { return null; } // Extract the first (and only) set of error details and cast as a Map. // The values of this map are the script's 'errorMessage' and // 'errorType', and an array of stack trace elements (which also need to // be cast as Maps). Map detail = op.getError().getDetails().get(0); List> stacktrace = (List>) detail.get("scriptStackTraceElements"); java.lang.StringBuilder sb = new StringBuilder("\nScript error message: "); sb.append(detail.get("errorMessage")); sb.append("\nScript error type: "); sb.append(detail.get("errorType")); if (stacktrace != null) { // There may not be a stacktrace if the script didn't start // executing. sb.append("\nScript error stacktrace:"); for (Map elem : stacktrace) { sb.append("\n "); sb.append(elem.get("function")); sb.append(":"); sb.append(elem.get("lineNumber")); } } sb.append("\n"); return sb.toString(); } public static void main(String[] args) throws IOException { // ID of the script to call. Acquire this from the Apps Script editor, // under Publish > Deploy as API executable. String scriptId = "ENTER_YOUR_SCRIPT_ID_HERE"; Script service = getScriptService(); // Create an execution request object. ExecutionRequest request = new ExecutionRequest() .setFunction("getFoldersUnderRoot"); try { // Make the API request. Operation op = service.scripts().run(scriptId, request).execute(); // Print results of request. if (op.getError() != null) { // The API executed, but the script returned an error. System.out.println(getScriptError(op)); } else { // The result provided by the API needs to be cast into // the correct type, based upon what types the Apps // Script function returns. Here, the function returns // an Apps Script Object with String keys and values, // so must be cast into a Java Map (folderSet). Map folderSet = (Map) (op.getResponse().get("result")); if (folderSet.size() == 0) { System.out.println("No folders returned!"); } else { System.out.println("Folders under your root folder:"); for (String id : folderSet.keySet()) { System.out.printf( "\t%s (%s)\n", folderSet.get(id), id); } } } } catch (GoogleJsonResponseException e) { // The API encountered a problem before the script was called. e.printStackTrace(System.out); } } // [END apps_script_api_execute] }