Google app java example

Java quickstart

Quickstarts explain how to set up and run an app that calls a Google Workspace API.

Google Workspace quickstarts use the API client libraries to handle some details of the authentication and authorization flow. We recommend that you use the client libraries for your own apps. This quickstart uses a simplified authentication approach that is appropriate for a testing environment. For a production environment, we recommend learning about authentication and authorization before choosing the access credentials that are appropriate for your app.

Create a Java command-line application that makes requests to the Google Sheets API.

Objectives

Prerequisites

Set up your environment

To complete this quickstart, set up your environment.

Enable the API

If you’re using a new Google Cloud project to complete this quickstart, configure the OAuth consent screen and add yourself as a test user. If you’ve already completed this step for your Cloud project, skip to the next section.

  1. In the Google Cloud console, go to Menu menu >APIs & Services >OAuth consent screen. Go to OAuth consent screen
  2. Select the user type for your app, then click Create.
  3. Complete the app registration form, then click Save and Continue.
  4. For now, you can skip adding scopes and click Save and Continue. In the future, when you create an app for use outside of your Google Workspace organization, you must add and verify the authorization scopes that your app requires.
  5. If you selected External for user type, add test users:
    1. Under Test users, click Add users.
    2. Enter your email address and any other authorized test users, then click Save and Continue.

    Authorize credentials for a desktop application

    1. In the Google Cloud console, go to Menu menu >APIs & Services >Credentials. Go to Credentials
    2. Click Create Credentials >OAuth client ID.
    3. Click Application type >Desktop app.
    4. In the Name field, type a name for the credential. This name is only shown in the Google Cloud console.
    5. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
    6. Click OK. The newly created credential appears under OAuth 2.0 Client IDs.
    7. Save the downloaded JSON file as credentials.json , and move the file to your working directory.

    Prepare the workspace

    gradle init --type basic mkdir -p src/main/java src/main/resources 

    apply plugin: ‘java’ apply plugin: ‘application’ mainClassName = ‘SheetsQuickstart’ sourceCompatibility = 11 targetCompatibility = 11 version = ‘1.0’ repositories < mavenCentral() >dependencies

    Set up the sample

    1. In the src/main/java/ directory, create a new Java file with a name that matches the mainClassName value in your build.gradle file.
    2. Include the following code in your new Java file:
    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.sheets.v4.Sheets; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.api.services.sheets.v4.model.ValueRange; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; public class SheetsQuickstart < private static final String APPLICATION_NAME = "Google Sheets 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 tokens/ folder. */ private static final ListSCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY); 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 = SheetsQuickstart.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"); > /** * Prints the names and majors of students in a sample spreadsheet: * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit */ public static void main(String. args) throws IOException, GeneralSecurityException < // Build a new authorized API client service. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"; final String range = "Class Data!A2:E"; Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); ValueRange response = service.spreadsheets().values() .get(spreadsheetId, range) .execute(); List> values = response.getValues(); if (values == null || values.isEmpty()) < System.out.println("No data found."); >else < System.out.println("Name, Major"); for (List row : values) < // Print columns A and E, which correspond to indices 0 and 4. System.out.printf("%s, %s\n", row.get(0), row.get(4)); >> > >

    Run the sample

    1. If you’re not already signed in to your Google Account, you’re prompted to sign in. If you’re signed in to multiple accounts, select one account to use for authorization.
    2. Click Accept.

    Authorization information is stored in the file system, so the next time you run the sample code, you aren’t prompted for authorization.

    You have successfully created your first Java application that makes requests to the Google Sheets API.

    Next steps

    Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

    Last updated 2023-07-24 UTC.

    Источник

    Пример приложения

    Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.

    На этой странице представлен пример приложения, демонстрирующий, как подготовить корпоративное одноразовое (COSU) устройство и отправить ему команду перезагрузки. Приложение использует клиентскую библиотеку Java Android Management API.

    Прежде чем вы начнете

    1. Загрузите клиентскую библиотеку Java Android Management API и добавьте все jar-файлы в путь к классам.
    2. Создайте или выберите проект Google Cloud Platform, которому будет принадлежать созданное предприятие.
    3. Включите Android Management API в проекте.
    4. Создайте или выберите учетную запись службы с ролью владельца или редактора в проекте.
    5. Выберите учетную запись Google, чтобы зарегистрироваться для нового предприятия. Учетная запись не может быть администратором какого-либо ранее существовавшего предприятия.
    6. Установите константы PROJECT_ID и SERVICE_ACCOUNT_CREDENTIAL_FILE ниже.
    7. При желании измените константу COSU_APP_PACKAGE_NAME ниже, чтобы установить приложение по вашему выбору.

    Код

    package sample; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.androidmanagement.v1.AndroidManagement; import com.google.api.services.androidmanagement.v1.model.ApplicationPolicy; import com.google.api.services.androidmanagement.v1.model.Command; import com.google.api.services.androidmanagement.v1.model.Device; import com.google.api.services.androidmanagement.v1.model.EnrollmentToken; import com.google.api.services.androidmanagement.v1.model.Enterprise; import com.google.api.services.androidmanagement.v1.model.ListDevicesResponse; import com.google.api.services.androidmanagement.v1.model.PersistentPreferredActivity; import com.google.api.services.androidmanagement.v1.model.Policy; import com.google.api.services.androidmanagement.v1.model.SignupUrl; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SampleApp < /** The id of the Google Cloud Platform project. */ private static final String PROJECT_ID = "YOUR_PROJECT_ID"; /** The JSON credential file for the service account. */ private static final String SERVICE_ACCOUNT_CREDENTIAL_FILE = "/PATH/TO/YOUR_FILE"; /** The id of the policy for the COSU device. */ private static final String POLICY_ID = "samplePolicy"; /** The package name of the COSU app. */ private static final String COSU_APP_PACKAGE_NAME = "com.google.android.apps.youtube.gaming"; /** The OAuth scope for the Android Management API. */ private static final String OAUTH_SCOPE = "https://www.googleapis.com/auth/androidmanagement"; /** The name of this app. */ private static final String APP_NAME = "Android Management API sample app"; /** The Android Management API client. */ private final AndroidManagement androidManagementClient; public static void main(String[] args) throws IOException, GeneralSecurityException < new SampleApp(getAndroidManagementClient()).run(); >public SampleApp(AndroidManagement androidManagementClient) < this.androidManagementClient = androidManagementClient; >/** Runs the app. */ public void run() throws IOException < // Create an enterprise. If you've already created an enterprise, the // createEnterprise call can be commented out and replaced with your // enterprise name. String enterpriseName = createEnterprise(); System.out.println("Enterprise created with name: " + enterpriseName); // Set the policy to be used by the device. setPolicy(enterpriseName, POLICY_ID, getCosuPolicy()); // Create an enrollment token to enroll the device. String token = createEnrollmentToken(enterpriseName, POLICY_ID); System.out.println("Enrollment token (to be typed on device): " + token); // List some of the devices for the enterprise. There will be no devices for // a newly created enterprise, but you can run the app again with an // existing enterprise after enrolling a device. Listdevices = listDevices(enterpriseName); for (Device device : devices) < System.out.println("Found device with name: " + device.getName()); >// If there are any devices, reboot one. if (devices.isEmpty()) < System.out.println("No devices found."); >else < rebootDevice(devices.get(0)); >> /** Builds an Android Management API client. */ private static AndroidManagement getAndroidManagementClient() throws IOException, GeneralSecurityException < try (FileInputStream input = new FileInputStream(SERVICE_ACCOUNT_CREDENTIAL_FILE)) < GoogleCredential credential = GoogleCredential.fromStream(input) .createScoped(Collections.singleton(OAUTH_SCOPE)); return new AndroidManagement.Builder( GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential) .setApplicationName(APP_NAME) .build(); >> /** Creates a new enterprise. Returns the enterprise name. */ private String createEnterprise() throws IOException < // Initiate signup process. System.out.println("Creating signup URL. "); SignupUrl signupUrl = androidManagementClient .signupUrls() .create() .setProjectId(PROJECT_ID) .setCallbackUrl("https://localhost:9999") .execute(); System.out.print( "To sign up for a new enterprise, open this URL in your browser: "); System.out.println(signupUrl.getUrl()); System.out.println( "After signup, you will see an error page in the browser."); System.out.print( "Paste the enterpriseToken value from the error page URL here: "); String enterpriseToken = new BufferedReader(new InputStreamReader(System.in)).readLine(); // Create the enterprise. System.out.println("Creating enterprise. "); return androidManagementClient .enterprises() .create(new Enterprise()) .setProjectId(PROJECT_ID) .setSignupUrlName(signupUrl.getName()) .setEnterpriseToken(enterpriseToken) .execute() .getName(); >/** Gets a Policy for a COSU device. */ private Policy getCosuPolicy() < Listcategories = new ArrayList<>(); categories.add("android.intent.category.HOME"); categories.add("android.intent.category.DEFAULT"); return new Policy() .setApplications( Collections.singletonList( new ApplicationPolicy() .setPackageName(COSU_APP_PACKAGE_NAME) .setInstallType("FORCE_INSTALLED") .setDefaultPermissionPolicy("GRANT") .setLockTaskAllowed(true))) .setPersistentPreferredActivities( Collections.singletonList( new PersistentPreferredActivity() .setReceiverActivity(COSU_APP_PACKAGE_NAME) .setActions( Collections.singletonList("android.intent.action.MAIN")) .setCategories(categories))) .setKeyguardDisabled(true) .setStatusBarDisabled(true); > /** Sets the policy of the given id to the given value. */ private void setPolicy(String enterpriseName, String policyId, Policy policy) throws IOException < System.out.println("Setting policy. "); String name = enterpriseName + "/policies/" + policyId; androidManagementClient .enterprises() .policies() .patch(name, policy) .execute(); >/** Creates an enrollment token. */ private String createEnrollmentToken(String enterpriseName, String policyId) throws IOException < System.out.println("Creating enrollment token. "); EnrollmentToken token = new EnrollmentToken().setPolicyName(policyId).setDuration("86400s"); return androidManagementClient .enterprises() .enrollmentTokens() .create(enterpriseName, token) .execute() .getValue(); >/** Lists the first page of devices for an enterprise. */ private List listDevices(String enterpriseName) throws IOException < System.out.println("Listing devices. "); ListDevicesResponse response = androidManagementClient .enterprises() .devices() .list(enterpriseName) .execute(); return response.getDevices() == null ? new ArrayList<>() : response.getDevices(); > /** Reboots a device. Note that reboot only works on Android N+. */ private void rebootDevice(Device device) throws IOException < System.out.println( "Sending reboot command to " + device.getName() + ". "); Command command = new Command().setType("REBOOT"); androidManagementClient .enterprises() .devices() .issueCommand(device.getName(), command) .execute(); >>

    Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons «С указанием авторства 4.0», а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.

    Последнее обновление: 2023-02-03 UTC.

    Источник

    Create a Java Hello World Example with Google App Engine in Eclipse

    In the following tutorial we will create a Java Google App Engine example. The application will display the typical “Hello World” greeting when it is invoked. We’ll develop all the source code in Eclipse with the help of the GAE plugin for Eclipse, test the application through Google App Engine Runtime (included within the plug in) and finally we will deploy it to the GAE account.

    1.- Prerequisites

    2.- Create the GAE Project

    Once you have installed the GAE Plugin for Eclipse, a new icon (a blue “g”) will be shown in the tool bar. Click it and a menu will be displayed.

    Select New Web Application Project.

    A new wizard appears and you have to put the information about your project.

    Make sure that the Use Google Web Toolkit is unchecked, then click Finish.

    3.-Code your Project

    The created project will have this structure:

    The structure of the project is like a typical Web project with some extra libraries and a appengine-web.xml , which we will look into later.

    As you can see, a Servlet is created. In this Servlet you will put all the logic for the incoming requests that your application will have.

    In this example we will return Hello world from GAE , so let’s take a look into the code.

    Источник

    Читайте также:  Alert в java script
Оцените статью