CloudShellCredential extends GoogleCredential { @Override protected TokenResponse executeRefreshToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); socket.setSoTimeout(READ_TIMEOUT_MS); TokenResponse token = new TokenResponse(); try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(GET_AUTH_TOKEN_REQUEST); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); input.readLine(); Collection<Object> messageArray = jsonFactory.createJsonParser(input) .parseArray(LinkedList.class, Object.class); String accessToken = ((List<Object>) messageArray).get(ACCESS_TOKEN_INDEX).toString(); token.setAccessToken(accessToken); } finally { socket.close(); } return token; } CloudShellCredential(int authPort, JsonFactory jsonFactory);   }
@Test public void refreshAccessToken() throws IOException{ final ServerSocket authSocket = new ServerSocket(0); Runnable serverTask = new Runnable() { @Override public void run() { try { Socket clientSocket = authSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String lines = input.readLine(); lines += '\n' + input.readLine(); assertEquals(CloudShellCredential.GET_AUTH_TOKEN_REQUEST, lines); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); out.println("32\n[\"email\", \"project-id\", \"token\", 1234]"); } catch (Exception reThrown) { throw new RuntimeException(reThrown); } } }; Thread serverThread = new Thread(serverTask); serverThread.start(); GoogleCredential creds = new CloudShellCredential( authSocket.getLocalPort(), GsonFactory.getDefaultInstance()); assertEquals("token", creds.executeRefreshToken().getAccessToken()); }