| 9005 |
manish.sha |
1 |
// Copyright 2013 Google Inc. All Rights Reserved.
|
|
|
2 |
//
|
|
|
3 |
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
4 |
// you may not use this file except in compliance with the License.
|
|
|
5 |
// You may obtain a copy of the License at
|
|
|
6 |
//
|
|
|
7 |
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
8 |
//
|
|
|
9 |
// Unless required by applicable law or agreed to in writing, software
|
|
|
10 |
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
12 |
// See the License for the specific language governing permissions and
|
|
|
13 |
// limitations under the License.
|
|
|
14 |
|
|
|
15 |
package adwords.axis.auth;
|
|
|
16 |
|
|
|
17 |
import com.google.api.ads.adwords.axis.factory.AdWordsServices;
|
|
|
18 |
import com.google.api.ads.adwords.axis.v201302.cm.Campaign;
|
|
|
19 |
import com.google.api.ads.adwords.axis.v201302.cm.CampaignPage;
|
|
|
20 |
import com.google.api.ads.adwords.axis.v201302.cm.CampaignServiceInterface;
|
|
|
21 |
import com.google.api.ads.adwords.axis.v201302.cm.Selector;
|
|
|
22 |
import com.google.api.ads.adwords.lib.client.AdWordsSession;
|
|
|
23 |
import com.google.api.ads.adwords.lib.jaxb.v201302.DownloadFormat;
|
|
|
24 |
import com.google.api.ads.adwords.lib.jaxb.v201302.ReportDefinition;
|
|
|
25 |
import com.google.api.ads.adwords.lib.jaxb.v201302.ReportDefinitionDateRangeType;
|
|
|
26 |
import com.google.api.ads.adwords.lib.jaxb.v201302.ReportDefinitionReportType;
|
|
|
27 |
import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;
|
|
|
28 |
import com.google.api.ads.adwords.lib.utils.v201302.ReportDownloader;
|
|
|
29 |
import com.google.api.ads.common.lib.conf.ConfigurationLoadException;
|
|
|
30 |
import com.google.api.ads.common.lib.exception.ValidationException;
|
|
|
31 |
import com.google.api.ads.common.lib.utils.Streams;
|
|
|
32 |
import com.google.api.client.auth.oauth2.Credential;
|
|
|
33 |
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
|
|
|
34 |
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
|
|
|
35 |
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
|
|
|
36 |
import com.google.api.client.http.javanet.NetHttpTransport;
|
|
|
37 |
import com.google.api.client.json.jackson2.JacksonFactory;
|
|
|
38 |
import com.google.api.client.util.store.DataStoreFactory;
|
|
|
39 |
import com.google.api.client.util.store.MemoryDataStoreFactory;
|
|
|
40 |
import com.google.common.collect.Lists;
|
|
|
41 |
|
|
|
42 |
import java.io.BufferedReader;
|
|
|
43 |
import java.io.File;
|
|
|
44 |
import java.io.FileOutputStream;
|
|
|
45 |
import java.io.IOException;
|
|
|
46 |
import java.io.InputStreamReader;
|
|
|
47 |
import java.net.HttpURLConnection;
|
|
|
48 |
|
|
|
49 |
/**
|
|
|
50 |
* This example demonstrates how to create a Credential object from scratch.<br>
|
|
|
51 |
* This example is *not* meant to be used with our other examples, but shows
|
|
|
52 |
* how you might use the general OAuth2 libraries to add OAuth2 to your
|
|
|
53 |
* existing application.<br>
|
|
|
54 |
* <br>
|
|
|
55 |
* For an alternative to service accounts, installed applications, or a web
|
|
|
56 |
* application that will not need to have multiple users log in, using
|
|
|
57 |
* OfflineCredentials to generate a refreshable OAuth2
|
|
|
58 |
* credential instead will be much easier.
|
|
|
59 |
*
|
|
|
60 |
* @author Adam Rogal
|
|
|
61 |
*/
|
|
|
62 |
public class AdvancedCreateCredentialFromScratch {
|
|
|
63 |
|
|
|
64 |
private static final String SCOPE = "https://adwords.google.com/api/adwords";
|
|
|
65 |
|
|
|
66 |
// This callback URL will allow you to copy the token from the success screen.
|
|
|
67 |
// This must match the one associated with your client ID.
|
|
|
68 |
private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
|
|
|
69 |
|
|
|
70 |
// If you do not have a client ID or secret, please create one in the
|
|
|
71 |
// API console: https://code.google.com/apis/console#access
|
|
|
72 |
private static final String CLIENT_ID = "INSERT_CLIENT_ID_HERE";
|
|
|
73 |
private static final String CLIENT_SECRET = "INSERT_CLIENT_SECRET_HERE";
|
|
|
74 |
|
|
|
75 |
// The current user that is authenticating. This is typically a primary key
|
|
|
76 |
// you define yourself that you will reference later in your code when
|
|
|
77 |
// you retrieve the credential for that user.
|
|
|
78 |
private static final String USER_ID = "INSERT_USER_ID_HERE";
|
|
|
79 |
|
|
|
80 |
private static void authorize(DataStoreFactory storeFactory, String userId) throws Exception {
|
|
|
81 |
// Depending on your application, there may be more appropriate ways of
|
|
|
82 |
// performing the authorization flow (such as on a servlet), see
|
|
|
83 |
// https://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow
|
|
|
84 |
// for more information.
|
|
|
85 |
GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
|
|
|
86 |
new NetHttpTransport(),
|
|
|
87 |
new JacksonFactory(),
|
|
|
88 |
CLIENT_ID,
|
|
|
89 |
CLIENT_SECRET,
|
|
|
90 |
Lists.newArrayList(SCOPE))
|
|
|
91 |
.setDataStoreFactory(storeFactory)
|
|
|
92 |
// Set the access type to offline so that the token can be refreshed.
|
|
|
93 |
// By default, the library will automatically refresh tokens when it
|
|
|
94 |
// can, but this can be turned off by setting
|
|
|
95 |
// api.adwords.refreshOAuth2Token=false in your ads.properties file.
|
|
|
96 |
.setAccessType("offline").build();
|
|
|
97 |
|
|
|
98 |
String authorizeUrl =
|
|
|
99 |
authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
|
|
|
100 |
System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');
|
|
|
101 |
|
|
|
102 |
// Wait for the authorization code.
|
|
|
103 |
System.out.println("Type the code you received here: ");
|
|
|
104 |
String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();
|
|
|
105 |
|
|
|
106 |
// Authorize the OAuth2 token.
|
|
|
107 |
GoogleAuthorizationCodeTokenRequest tokenRequest =
|
|
|
108 |
authorizationFlow.newTokenRequest(authorizationCode);
|
|
|
109 |
tokenRequest.setRedirectUri(CALLBACK_URL);
|
|
|
110 |
GoogleTokenResponse tokenResponse = tokenRequest.execute();
|
|
|
111 |
|
|
|
112 |
// Store the credential for the user.
|
|
|
113 |
authorizationFlow.createAndStoreCredential(tokenResponse, userId);
|
|
|
114 |
}
|
|
|
115 |
|
|
|
116 |
private static AdWordsSession createAdWordsSession(
|
|
|
117 |
DataStoreFactory dataStoreFactory, String userId)
|
|
|
118 |
throws IOException, ValidationException, ConfigurationLoadException {
|
|
|
119 |
// Create a GoogleCredential with minimal information.
|
|
|
120 |
GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
|
|
|
121 |
new NetHttpTransport(),
|
|
|
122 |
new JacksonFactory(),
|
|
|
123 |
CLIENT_ID,
|
|
|
124 |
CLIENT_SECRET,
|
|
|
125 |
Lists.newArrayList(SCOPE)).build();
|
|
|
126 |
|
|
|
127 |
// Load the credential.
|
|
|
128 |
Credential credential = authorizationFlow.loadCredential(userId);
|
|
|
129 |
|
|
|
130 |
// Construct a AdWordsSession.
|
|
|
131 |
return new AdWordsSession.Builder()
|
|
|
132 |
.fromFile()
|
|
|
133 |
.withOAuth2Credential(credential)
|
|
|
134 |
.build();
|
|
|
135 |
}
|
|
|
136 |
|
|
|
137 |
public static void runExample(
|
|
|
138 |
AdWordsServices adWordsServices, AdWordsSession session, String reportFile) throws Exception {
|
|
|
139 |
// Get the CampaignService.
|
|
|
140 |
CampaignServiceInterface campaignService =
|
|
|
141 |
adWordsServices.get(session, CampaignServiceInterface.class);
|
|
|
142 |
|
|
|
143 |
// Create selector.
|
|
|
144 |
Selector selector = new Selector();
|
|
|
145 |
selector.setFields(new String[] {"Id", "Name"});
|
|
|
146 |
|
|
|
147 |
// Get all campaigns.
|
|
|
148 |
CampaignPage page = campaignService.get(selector);
|
|
|
149 |
|
|
|
150 |
// Display campaigns.
|
|
|
151 |
if (page.getEntries() != null) {
|
|
|
152 |
for (Campaign campaign : page.getEntries()) {
|
|
|
153 |
System.out.println("Campaign with name \"" + campaign.getName() + "\" and id \""
|
|
|
154 |
+ campaign.getId() + "\" was found.");
|
|
|
155 |
}
|
|
|
156 |
} else {
|
|
|
157 |
System.out.println("No campaigns were found.");
|
|
|
158 |
}
|
|
|
159 |
|
|
|
160 |
// Create selector.
|
|
|
161 |
com.google.api.ads.adwords.lib.jaxb.v201302.Selector reportSelector =
|
|
|
162 |
new com.google.api.ads.adwords.lib.jaxb.v201302.Selector();
|
|
|
163 |
reportSelector.getFields().addAll(Lists.newArrayList(
|
|
|
164 |
"CampaignId",
|
|
|
165 |
"AdGroupId",
|
|
|
166 |
"Id",
|
|
|
167 |
"CriteriaType",
|
|
|
168 |
"Criteria",
|
|
|
169 |
"Impressions",
|
|
|
170 |
"Clicks",
|
|
|
171 |
"Cost"));
|
|
|
172 |
|
|
|
173 |
// Create report definition.
|
|
|
174 |
ReportDefinition reportDefinition = new ReportDefinition();
|
|
|
175 |
reportDefinition.setReportName("Criteria performance report #" + System.currentTimeMillis());
|
|
|
176 |
reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.YESTERDAY);
|
|
|
177 |
reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);
|
|
|
178 |
reportDefinition.setDownloadFormat(DownloadFormat.CSV);
|
|
|
179 |
// Enable to allow rows with zero impressions to show.
|
|
|
180 |
reportDefinition.setIncludeZeroImpressions(true);
|
|
|
181 |
reportDefinition.setSelector(reportSelector);
|
|
|
182 |
|
|
|
183 |
ReportDownloadResponse response =
|
|
|
184 |
new ReportDownloader(session).downloadReport(reportDefinition);
|
|
|
185 |
if (response.getHttpStatus() == HttpURLConnection.HTTP_OK) {
|
|
|
186 |
FileOutputStream fos = new FileOutputStream(new File(reportFile));
|
|
|
187 |
Streams.copy(response.getInputStream(), fos);
|
|
|
188 |
fos.close();
|
|
|
189 |
System.out.println("Report successfully downloaded: " + reportFile);
|
|
|
190 |
} else {
|
|
|
191 |
System.out.println("Report was not downloaded. " + response.getHttpStatus() + ": "
|
|
|
192 |
+ response.getHttpResponseMessage());
|
|
|
193 |
}
|
|
|
194 |
}
|
|
|
195 |
|
|
|
196 |
public static void main(String[] args) throws Exception {
|
|
|
197 |
if (CLIENT_ID.equals("INSERT_CLIENT_ID_HERE")
|
|
|
198 |
|| CLIENT_SECRET.equals("INSERT_CLIENT_SECRET_HERE")) {
|
|
|
199 |
throw new IllegalArgumentException("Please input your client IDs or secret. "
|
|
|
200 |
+ "See https://code.google.com/apis/console#access");
|
|
|
201 |
}
|
|
|
202 |
|
|
|
203 |
// It is highly recommended that you use a credential store in your
|
|
|
204 |
// application to store a per-user Credential.
|
|
|
205 |
// See: https://code.google.com/p/google-oauth-java-client/wiki/OAuth2
|
|
|
206 |
DataStoreFactory storeFactory = new MemoryDataStoreFactory();
|
|
|
207 |
|
|
|
208 |
// Authorize and store your credential.
|
|
|
209 |
authorize(storeFactory, USER_ID);
|
|
|
210 |
|
|
|
211 |
// Create a AdWordsSession from the credential store. You will typically do this
|
|
|
212 |
// in a servlet interceptor for a web application or per separate thread
|
|
|
213 |
// of your offline application.
|
|
|
214 |
AdWordsSession adWordsSession = createAdWordsSession(storeFactory, USER_ID);
|
|
|
215 |
|
|
|
216 |
AdWordsServices adWordsServices = new AdWordsServices();
|
|
|
217 |
|
|
|
218 |
// Location to download report to.
|
|
|
219 |
String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";
|
|
|
220 |
|
|
|
221 |
runExample(adWordsServices, adWordsSession, reportFile);
|
|
|
222 |
}
|
|
|
223 |
}
|