Google API应用程序脚本功能执行始终导致500错误

时间:2018-02-24 22:32:51

标签: java google-api-java-client

我成功获取了访问令牌并初始化了脚本服务。我试过改变他们现在正确的范围。你能看到问题吗?结果如下:

  

GoogleJsonResponseException错误响应:null错误:500内部
  服务器错误{"代码" :500,"错误" :[{
      "结构域" :"全球",
      "消息" :"遇到内部错误。",
      "理由" :" backendError" },
      "消息" :"遇到内部错误。",
      "状态" :" INTERNAL" }

代码:

public static String replaceProjectDetail(String docTitle, String projectTitle, String customerName, String projectNumber) 
    throws GoogleDriveClientException, IOException, Exception {

            initialize_script();
            // ensure the properties were loaded
    if(!isInitialized) {
        throw new GoogleDriveClientException("Cannot process request because client objects are not initialized.");
    }

    final File content = getFileByTitle(docTitle);

            // ID of the script to call. Acquire this from the Apps Script editor,
            // under Publish > Deploy as API executable.
            String scriptId = SUPER SECRET SCRIPT ID;
            Object status = null;
            // Apps Script function to call.
            String functionName = "Function Name";
            String txtUrl = content.getWebViewLink();
            if(LOGGER.isDebugEnabled()) {
               LOGGER.debug("Google file captured: " + content.getName() 
                        + ", url : " + txtUrl);
            }
            //isInitialized = false;
            //initialize_script();

            /** ensure the properties were loaded
    if(!isInitialized) {
        throw new GoogleDriveClientException("Cannot process request because client objects are not initialized.");
    }**/

            byte[] projNum = projectNumber.getBytes("UTF-8");
            byte[] projTitle = projectTitle.getBytes("UTF-8");
            byte[] custName = customerName.getBytes("UTF-8");
            byte[] URL = txtUrl.getBytes("UTF-8");


            // Initialize parameters for that function.
            List<Object> params = new ArrayList<>();
            params.add(projNum);
            params.add(projTitle);
            params.add(custName);
            params.add(URL);

            // Create execution request.
            ExecutionRequest request = new ExecutionRequest()
                .setFunction(functionName)
                .setParameters(params)
                .setDevMode(Boolean.FALSE);


            Credential client_credential = null;


            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug("Google file apps script successfully configured.");
            }

            int high = 1000;
            Random r = new Random();
            int low = 1;

            // Attempt to execute our main action, retrying up to 4 times
            // if an exception is thrown
            for (int n = 0; n <= 4; n++) {
                try {

                    // The main action you want to execute goes here
                    // If this does not come in the form of a return
                    // statement (i.e., code continues below the loop)
                    // then you must insert a break statement after the
                    // action is complete.
                    // Make the API request.
                    client_credential = authorize();
                    //String accessToken = client_credential.getAccessToken();
                    /**if (LOGGER.isDebugEnabled())  {
                        LOGGER.debug("Google access token: " + accessToken);
                    }**/
                    op = service.scripts()
                            .run(scriptId, request)
                            .setAccessToken(client_credential.getAccessToken())
                            .execute();

                    if (LOGGER.isDebugEnabled())  {
                        LOGGER.debug("Successfully executed function: " + op.toPrettyString());
                    }

                    Map<String,Object> response = (ExecutionResponse) op.getResponse();

                    status = response.get("result");

                    if (LOGGER.isDebugEnabled())  {

                        for (Map.Entry<String, Object> entry : response.entrySet()) {
                            if (entry.getValue() instanceof String) {
                                LOGGER.debug("Google file apps script response:  entry.getKey()=" + entry.getKey().toString()
                                        + ", entry.getValue()=" + entry.getValue().toString());
                                return entry.getValue().toString();
                            } else if (entry.getValue() instanceof Class) {
                                LOGGER.debug("Google file apps script response: entry.getValue() = instance of Class.");
                                return "class";
                            } else {
                                throw new IllegalStateException("Expecting either String or Class as entry value");
                            }
                        }
                    }


                    if(LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Google file apps script executed successfully. Return value: " + status.toString());
                    }

                    return "success";
                    } catch (GoogleJsonResponseException e) {

                        String googleErrors = getScriptError(op);

                        if (LOGGER.isDebugEnabled())  {
                            LOGGER.debug("GoogleJsonResponseException error response: " + googleErrors);
                        }

                        LOGGER.error("Failed to execute with error: " + e.getMessage());

                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw e;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000) 
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                    } catch (NullPointerException npe)  {
                        LOGGER.debug("NullPointerException error response: " + npe.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw npe;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000) 
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                    } catch (SocketTimeoutException ste)  {
                        LOGGER.debug("SocketTimeoutException error response: " + ste.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw ste;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000) 
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        } 
                } catch (SocketException se)  {
                        LOGGER.debug("SocketException error response: " + se.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw se;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000) 
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        } 
                    } catch (Exception ex)  {
                        LOGGER.debug("SocketException error response: " + ex.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw ex;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000) 
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        } 
                    }

                }

        return "success";
} 

2 个答案:

答案 0 :(得分:0)

1)用于搜索Google Doc的Apache Tomcat Web服务 2)得到它的网址 3)初始化脚本服务 4)创建一个Google API Apps Script Function Execution          a)使用url搜索文档          b)替换google文档上的文本,该文本是模板的副本 5)记录错误

编程最多重试4次。

答案 1 :(得分:0)

问题不在于此代码。我没有意识到您必须使用相同的凭据来启动脚本服务并获取Google API应用程序脚本功能执行的访问令牌。