javaspring-bootgoogle-cloud-platformgoogle-apigoogle-api-java-client

Create a job on jobs google via api returns "The Application Default Credentials are not available"


I started to create an application for posting vacancies in jobs.google. I can not find an open api in order to post these vacancies directly on jobs.google through it. Tell me how to do it.

I found a sample ready-made application, but since I have not yet encountered this, I have difficulties with the implementation

I also can’t figure out what is the difference between jobs.google and career or Cloud Talent Solution

import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

public class BasicJobSample {
    private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");

    private static CloudTalentSolution talentSolutionClient = JobServiceQuickstart.getTalentSolutionClient();
    public static Job generateJobWithRequiredFields(String companyName) {
        String requisitionId = "jobWithRequiredFields:" + String.valueOf(new Random().nextLong());
        ApplicationInfo applicationInfo = new ApplicationInfo().setUris(Arrays.asList("http://careers.google.com"));

        Job job = new Job().setRequisitionId(requisitionId).setTitle("Software Engineer")
                .setCompanyName(companyName).setApplicationInfo(applicationInfo)
                .setDescription("Design, develop, test, deploy, maintain and improve software.");
        System.out.println("Job generated: " + job);
        return job;
    }
    public static Job createJob(Job jobToBeCreated) throws IOException {
        try {
            CreateJobRequest createJobRequest = new CreateJobRequest().setJob(jobToBeCreated);

            Job jobCreated = talentSolutionClient.projects().jobs().create(DEFAULT_PROJECT_ID, createJobRequest)
                    .execute();
            System.out.println("Job created: " + jobCreated);
            return jobCreated;
        } catch (IOException e) {
            System.out.println("Got exception while creating job");
            throw e;
        }
    }
    public static Job getJob(String jobName) throws IOException {
        try {
            Job jobExisted = talentSolutionClient.projects().jobs().get(jobName).execute();
            System.out.println("Job existed: " + jobExisted);
            return jobExisted;
        } catch (IOException e) {
            System.out.println("Got exception while getting job");
            throw e;
        }
    }
    public static Job updateJob(String jobName, Job jobToBeUpdated) throws IOException {
        try {
            UpdateJobRequest updateJobRequest = new UpdateJobRequest().setJob(jobToBeUpdated);
            Job jobUpdated = talentSolutionClient.projects().jobs().patch(jobName, updateJobRequest).execute();
            System.out.println("Job updated: " + jobUpdated);
            return jobUpdated;
        } catch (IOException e) {
            System.out.println("Got exception while updating job");
            throw e;
        }
    }
    public static Job updateJobWithFieldMask(String jobName, String fieldMask, Job jobToBeUpdated)
            throws IOException {
        try {
            UpdateJobRequest updateJobRequest = new UpdateJobRequest().setUpdateMask(fieldMask)
                    .setJob(jobToBeUpdated);
            Job jobUpdated = talentSolutionClient.projects().jobs().patch(jobName, updateJobRequest).execute();
            System.out.println("Job updated: " + jobUpdated);
            return jobUpdated;
        } catch (IOException e) {
            System.out.println("Got exception while updating job");
            throw e;
        }
    }
    public static void deleteJob(String jobName) throws IOException {
        try {
            talentSolutionClient.projects().jobs().delete(jobName).execute();
            System.out.println("Job deleted");
        } catch (IOException e) {
            System.out.println("Got exception while deleting job");
            throw e;
        }
    }
    

    public static void main(String... args) throws Exception {
        Company companyToBeCreated = BasicCompanySample.generateCompany();
        Company companyCreated = BasicCompanySample.createCompany(companyToBeCreated);
        String companyName = companyCreated.getName();

        Job jobToBeCreated = generateJobWithRequiredFields(companyName);

        Job jobCreated = createJob(jobToBeCreated);

        String jobName = jobCreated.getName();
        getJob(jobName);

        Job jobToBeUpdated = jobCreated.setDescription("changedDescription");
        updateJob(jobName, jobToBeUpdated);

        updateJobWithFieldMask(jobName, "title", new Job().setTitle("changedJobTitle"));

        deleteJob(jobName);

        BasicCompanySample.deleteCompany(companyName);

        try {
            ListCompaniesResponse listCompaniesResponse = talentSolutionClient.projects().companies()
                    .list(DEFAULT_PROJECT_ID).execute();
            System.out.println("Request Id is " + listCompaniesResponse.getMetadata().getRequestId());
            if (listCompaniesResponse.getCompanies() != null) {
                for (Company company : listCompaniesResponse.getCompanies()) {
                    System.out.println(company.getName());
                }
            }
        } catch (IOException e) {
            System.out.println("Got exception while listing companies");
            throw e;
        }
    }
}


import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.Company;
import com.google.api.services.jobs.v3.model.CreateCompanyRequest;
import com.google.api.services.jobs.v3.model.UpdateCompanyRequest;
import java.io.IOException;
import java.util.Random;

public class BasicCompanySample {
    private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");

    private static CloudTalentSolution talentSolutionClient = JobServiceQuickstart.getTalentSolutionClient();

    public static Company generateCompany() {
       
        String companyName = "company:" + String.valueOf(new Random().nextLong());

        Company company = new Company().setDisplayName("Google")
                .setHeadquartersAddress("1600 Amphitheatre Parkway Mountain View, CA 94043")
                .setExternalId(companyName);
        System.out.println("Company generated: " + company);
        return company;
    }
   
    public static Company createCompany(Company companyToBeCreated) throws IOException {
        try {
            CreateCompanyRequest createCompanyRequest = new CreateCompanyRequest().setCompany(companyToBeCreated);
            Company companyCreated = talentSolutionClient.projects().companies()
                    .create(DEFAULT_PROJECT_ID, createCompanyRequest).execute();
            System.out.println("Company created: " + companyCreated);
            return companyCreated;
        } catch (IOException e) {
            System.out.println("Got exception while creating company");
            throw e;
        }
    }
   
    public static Company getCompany(String companyName) throws IOException {
        try {
            Company companyExisted = talentSolutionClient.projects().companies().get(companyName).execute();
            System.out.println("Company existed: " + companyExisted);
            return companyExisted;
        } catch (IOException e) {
            System.out.println("Got exception while getting company");
            throw e;
        }
    }
    
    public static Company updateCompany(String companyName, Company companyToBeUpdated) throws IOException {
        try {
            UpdateCompanyRequest updateCompanyRequest = new UpdateCompanyRequest().setCompany(companyToBeUpdated);

            Company companyUpdated = talentSolutionClient.projects().companies()
                    .patch(companyName, updateCompanyRequest).execute();

            System.out.println("Company updated: " + companyUpdated);
            return companyUpdated;
        } catch (IOException e) {
            System.out.println("Got exception while updating company");
            throw e;
        }
    }
    
    public static Company updateCompanyWithFieldMask(String companyName, String fieldMask,
                                                     Company companyToBeUpdated) throws IOException {
        try {
            // String foo = String.format("?updateCompanyFields=%s",fieldMask);
            UpdateCompanyRequest updateCompanyRequest = new UpdateCompanyRequest().setUpdateMask(fieldMask)
                    .setCompany(companyToBeUpdated);

            Company companyUpdated = talentSolutionClient.projects().companies()
                    .patch(companyName, updateCompanyRequest).execute();

            System.out.println("Company updated: " + companyUpdated);
            return companyUpdated;
        } catch (IOException e) {
            System.out.println("Got exception while updating company");
            throw e;
        }
    }
   
    public static void deleteCompany(String companyName) throws IOException {
        try {
            talentSolutionClient.projects().companies().delete(companyName).execute();
            System.out.println("Company deleted");
        } catch (IOException e) {
            System.out.println("Got exception while deleting company");
            throw e;
        }
    }
}


import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.Company;
import com.google.api.services.jobs.v3.model.ListCompaniesResponse;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class JobServiceQuickstart {
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final NetHttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
    private static final String SCOPES = "https://www.googleapis.com/auth/jobs";
    private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");

    private static final CloudTalentSolution talentSolutionClient = createTalentSolutionClient(generateCredential());

    private static CloudTalentSolution createTalentSolutionClient(GoogleCredentials credential) {
        String url = "https://jobs.googleapis.com";
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
        return new CloudTalentSolution.Builder(NET_HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(requestInitializer))
                .setApplicationName("JobServiceClientSamples").setRootUrl(url).build();
    }

    private static GoogleCredentials generateCredential() {
        try {
            // Credentials could be downloaded after creating service account
            // set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable, for example:
            // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
            return GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(SCOPES));
        } catch (Exception e) {
            System.out.print("Error in generating credential");
            throw new RuntimeException(e);
        }
    }

    private static HttpRequestInitializer setHttpTimeout(final HttpRequestInitializer requestInitializer) {
        return request -> {
            requestInitializer.initialize(request);
            request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
            request.setConnectTimeout(1 * 60000); // 1 minute connect timeout
            request.setReadTimeout(1 * 60000); // 1 minute read timeout
        };
    }

    public static CloudTalentSolution getTalentSolutionClient() {
        return talentSolutionClient;
    }

I have added the code to my question. However, it throws an error, most likely this is due to authorization

Error in generating credentialException in thread "main" java.lang.ExceptionInInitializerError
    at io.fortylines.tapintech.jobapi.BasicJobSample.<clinit>(BasicJobSample.java:13)
Caused by: java.lang.RuntimeException: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
    at io.fortylines.tapintech.jobapi.JobServiceQuickstart.generateCredential(JobServiceQuickstart.java:39)
    at io.fortylines.tapintech.jobapi.JobServiceQuickstart.<clinit>(JobServiceQuickstart.java:22)
    ... 1 more
Caused by: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
    at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
    at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:125)
    at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:97)
    at io.fortylines.tapintech.jobapi.JobServiceQuickstart.generateCredential(JobServiceQuickstart.java:36)
    ... 2 more

@Configuration public class Project1Config {

    // Lists all service accounts for the current project.
    public static void listServiceAccounts(String projectId) {
        // String projectId = "my-project-id"

        Iam service = null;
        try {
            service = initService();
        } catch (IOException | GeneralSecurityException e) {
            System.out.println("Unable to initialize service: \n" + e.toString());
            return;
        }

        try {
            ListServiceAccountsResponse response =
                    service.projects().serviceAccounts().list("projects/" + projectId).execute();
            List<ServiceAccount> serviceAccounts = response.getAccounts();

            for (ServiceAccount account : serviceAccounts) {
                System.out.println("Name: " + account.getName());
                System.out.println("Display Name: " + account.getDisplayName());
                System.out.println("Email: " + account.getEmail());
                System.out.println();
            }
        } catch (IOException e) {
            System.out.println("Unable to list service accounts: \n" + e.toString());
        }
    }

    private static Iam initService() throws GeneralSecurityException, IOException {
        // Use the Application Default Credentials strategy for authentication. For more info, see:
        // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
        GoogleCredentials credential =
                GoogleCredentials.getApplicationDefault()
                        .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
        // Initialize the IAM service, which can be used to send requests to the IAM API.
        Iam service =
                new Iam.Builder(
                        GoogleNetHttpTransport.newTrustedTransport(),
                        JacksonFactory.getDefaultInstance(),
                        new HttpCredentialsAdapter(credential))
                        .setApplicationName("service-accounts")
                        .build();
        return service;
    }
}

I also created a configuration class, but I still need to configure it. When registering in the cloud, I registered the name of the project, and also received an email and a 21-digit number. How can I mark them in my project, since the error comes out the same


Solution

  • The Application Default Credentials are not available.

    You have not configured the GOOGLE_APPLICATION_CREDENTIALS environment variable

    This env var must point to the location of your credentials file.

    How Application Default Credentials works