I am trying to learn the usage of Google Analytics API. I am following the tutorial provided by "https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-java" and have copy pasted their code.
I have used the following dependency:
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analytics</artifactId>
<version>v3-rev20190807-1.32.1</version>
But I am facing three problems:
Cannot resolve method 'initializeAnalytics' in 'HelloAnalytics'
Cannot resolve symbol 'AnalyticsReporting'
Incompatible types. Found: 'com.google.api.services.analytics.Analytics', required: 'AnalyticsReporting'
The problems are bring faced in following areas:
private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential
.fromStream(new FileInputStream(KEY_FILE_LOCATION))
.createScoped(AnalyticsScopes.all());
// Construct the Analytics service object.
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
and
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
String profile = getFirstProfileId(analytics);
System.out.println("First Profile Id: "+ profile);
printResults(getResults(analytics, profile));
} catch (Exception e) {
e.printStackTrace();
}
}
Kindly let me know if I am making any mistake or if there is any solution available.
Related
I'm working on some improvement on our google drive integration.
Current state:
There is already implementation of saving files into Google Drive folders using hard-coded folderId. This works with no problems.
Now: I want to extend this logic and I need for this list of all folders.
So I followed this guide:
https://developers.google.com/drive/api/guides/search-files
And the problem is that I receive only **one** folder but in google drive there is 10.
Can anyone has any idea what I missed or overlooked? Why result doesn't contain nextPageToken? Spent whole day on it and this drives me crazy.
This is my method (i'm using service account for connection):
#Override
public List<File> getAllFolders() throws IOException {
Drive service = googleDriveProvider.getService();
List<File> files = new ArrayList<>();
String pageToken = null;
do {
FileList result = service.files().list()
.setQ("mimeType='application/vnd.google-apps.folder'")
.setSpaces("drive")
.setSupportsAllDrives(true)
.setIncludeItemsFromAllDrives(true)
.setFields("nextPageToken, files(id, name, parents)")
.setPageToken(pageToken)
.execute();
for (File file : result.getFiles()) {
System.out.printf("Found file: %s (%s)\n",
file.getName(), file.getId());
}
files.addAll(result.getFiles());
pageToken = result.getNextPageToken();
} while (pageToken != null);
return files;
}
And this is GoogleDriveProvider:
#Service
public class GoogleDriveProvider {
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final Set<String> SCOPES = DriveScopes.all();
private static final String GET_DRIVE_SERVICE_ERROR_MESSAGE = "Getting instance of Google drive has failed, error: [%s]";
#Value("${google.drive.service.account.auth.json}")
private String authJson;
#Value("${info.app.name}")
private String appName;
public Drive getService() throws GoogleDriveException {
try {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials credentials = GoogleCredentials.fromStream(
new ByteArrayInputStream(authJson.getBytes())).createScoped(SCOPES);
credentials.refreshIfExpired();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
return new Drive.Builder(httpTransport, JSON_FACTORY, requestInitializer)
.setApplicationName(appName)
.build();
} catch (IOException | GeneralSecurityException e) {
throw new GoogleDriveException(
format(GET_DRIVE_SERVICE_ERROR_MESSAGE, e.getMessage()), e);
}
}
}
Problem solved. Folders must be created by the service account or must be shared with service account first.
I making an app using google drive to store files for user to their google drive
I followed google developer guide in https://developers.google.com/drive/api/guides/about-sdk
and when i press the button to upload my files i got the err in title
this is
my code :
try {
// Load pre-authorized user credentials from the environment.
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
credentials);
Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName(getString(R.string.app_name))
.build();
File fileMetaDate = new File();
fileMetaDate.setName(getString(R.string.db_name_lists));
File file1 = service.files().create(fileMetaDate, fileContent)
.setFields("id")
.execute();
Toast.makeText(this, file1.getId() + " has been created", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
error
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise - java android
To use
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
You must have the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
Other wise you can do it like shown in the Google drive java quickstart
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
InputStream in = DriveQuickstart.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));
I'm trying to use the org.kohsuke API to connect to a github repo and get the list of PRS this is my code:
public static void main(String... args) {
try {
GitHub github = GitHub.connect();
GHRepository r = github.getOrganization("rasilvap").getRepository("lift-tool-test");
List<GHPullRequest> i = r.getPullRequests(GHPullRequest.State.OPEN);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I'm getting the next error in the line GitHub github = GitHub.connect();
java.io.FileNotFoundException: /Users/{myuser}/.github (No such file or directory)
I'm not pretty sure why is looking in my local pc, I have to create a .github folder y my user path?
Any ideas?
I am trying to implement Watson API for visual recognition. I encounter the following error message:
Here is the code:
public class VisualRecognizer {
private VisualRecognition service;
public VisualRecognizer() {
this.service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
this.service.setApiKey("ourkey");
this.service.setEndPoint("https://gateway-a.watsonplatform.net/visual-recognition/api");
}
public String classifyImage(String filePath) throws FileNotFoundException {
InputStream imageStream = new FileInputStream(filePath);
ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
.imagesFile(imageStream)
.build();
ClassifiedImages result = service.classify(classifyOptions).execute();
Any suggestions on how to solve this would be greatly appreciated.
Please mention a file name.
ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
.imagesFile(imageStream).imagesFilename("xyz.jpg")
.build();
For me it worked
Hello I've downloaded and installed the latest version of Drive REST API for java and want to get the metadata of a public file from Google Drive by the fileID - I have the following code:
private static final String APPLICATION_NAME = "test";
private static final String FILE_ID = "theFileId";
public static void main(String[] args) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null).setApplicationName(APPLICATION_NAME).build();
printFile(service, FILE_ID);
}
private static void printFile(Drive service, String fileId) {
try {
File file = service.files().get(fileId).execute();
System.out.println("Title: " + file.getTitle());
} catch (IOException e) {
System.out.println("An error occured: " + e);
}
}
But I get the error message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
I've tried it on https://developers.google.com/drive/v2/reference/files/get which worked out just fine.
Do I have to authenticate with an API key when the file is public and how would I do that if so.
Thanks for your time.
Yes, you need to authenticate with an API key. See the documentation here: https://developers.google.com/drive/web/about-auth