Invalid grant when authenticating to Google - java

I'm trying to connect to the Google Calendar API. I am have followed the step in Google calendar quick start for Java
{ "error" : "invalid_grant", "error_description" : "Bad Request" }
Can you please advise on how to debug this? The error message is unfortunately not helpful and I already tried everything I could find about this particular error on Stack overflow or elsewhere
Every time I got the same access token for different credentials:
Access token: {user=Class{accessToken=null, refreshToken="" expirationTimeMilliseconds=null}}
code:
public class CalendarServiceImpl implements CalendarService {
public static final String APPLICATION_NAME = "GoogleCalenderApi";
public static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
public static final String TOKENS_DIRECTORY_PATH = "/data.json";
public static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR);
public static final String CREDENTIALS_FILE_PATH = "/data.json";
public Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT, HttpServletRequest request)
throws IOException {
InputStream in = CalendarServiceImpl.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
log.info("Resource not found: " + CREDENTIALS_FILE_PATH);
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
System.out.println("Access token: " + flow.getCredentialDataStore());
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(80)
.build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public void createCalendarEvent(String candidateMailId, String companyEmailId, DateTime fromTime, DateTime toTime,
String summary, String description, HttpServletRequest request)
throws GeneralSecurityException, IOException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Event event = new Event().setSummary(summary).setLocation("Test").setDescription(description);
EventDateTime start = new EventDateTime().setDateTime(fromTime).setTimeZone("Asia/Kolkata");
event.setStart(start);
EventDateTime end = new EventDateTime().setDateTime(toTime).setTimeZone("Asia/Kolkata");
event.setEnd(end);
String[] recurrence = new String[] { "RRULE:FREQ=DAILY" };
event.setRecurrence(Arrays.asList(recurrence));
EventAttendee[] attendees = new EventAttendee[] { new EventAttendee().setEmail(candidateMailId),
new EventAttendee().setEmail(companyEmailId) };
event.setAttendees(Arrays.asList(attendees));
EventReminder[] reminderOverrides = new EventReminder[] { new EventReminder().setMethod("email").setMinutes(10),
new EventReminder().setMethod("popup").setMinutes(10), };
Event.Reminders reminders = new Event.Reminders().setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
// Build service account credential.
Credential credential = getCredentials(HTTP_TRANSPORT, request);
log.info("got credential:" + event);
Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
String calendarId = "primary";
try {
System.out.printf("Event started" + event);
event = service.events().insert(calendarId, event).setSendUpdates("all").execute();
} catch (IOException e) {
log.info("event IOException:" + e);
e.getMessage();
}
log.info("Event created:" + event.getHtmlLink());
}
}

You appear to be using AuthorizationCodeInstalledApp which as it stats is for installed applications. for web applications you need to use AuthorizationCodeFlow.
The official example can be found here
Web server application
public class CalendarServletSample extends AbstractAuthorizationCodeServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// do stuff
}
#Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
GenericUrl url = new GenericUrl(req.getRequestURL().toString());
url.setRawPath("/oauth2callback");
return url.build();
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
"[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
DATA_STORE_FACTORY).setAccessType("offline").build();
}
#Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
// return user ID
}
}
public class CalendarServletCallbackSample extends AbstractAuthorizationCodeCallbackServlet {
#Override
protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential)
throws ServletException, IOException {
resp.sendRedirect("/");
}
#Override
protected void onError(
HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
throws ServletException, IOException {
// handle error
}
#Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
GenericUrl url = new GenericUrl(req.getRequestURL().toString());
url.setRawPath("/oauth2callback");
return url.build();
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(), JacksonFactory.getDefaultInstance()
"[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
DATA_STORE_FACTORY).setAccessType("offline").build();
}
#Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
// return user ID
}
}
AuthorizationCodeFlow opens the consent browser window in the machine that the code is running on. When you are running something as a website it needs to open on the client machine so that the user can see it.

Related

After adding a filter which extends OncePerRequestFilter, getting exception "I/O error while reading input message; nested exception is Stream closed

I added one Request filter which extends OncePerRequestFilter. This filter I am using in my SpringBoot application which exposes end points for rest api.
After adding this filter it is working in localhost but when we are deploying it to any environment it is throwing this exception:
Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
#Component
public class RequestFilter extends OncePerRequestFilter {
private static Logger LOGGER = LoggerFactory.getLogger(RequestFilter.class);
private static final String X_JWT_PAYLOAD_HEADER = "x-jwt-payload";
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String DATA_KEY = "data";
private static final String MESSAGE_KEY = "message";
private static final String ERROR_KEY = "error";
private static final String ERRORS_KEY = "errors";
private static final String EMPTY_JWT_TOKEN_MSG = "Bad request, mandatory request header " + X_JWT_PAYLOAD_HEADER
+ ", is empty";
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Map<String, String> errorDetails=new HashMap();
try {
LOGGER.debug("Auth Header: {}", request.getHeader(AUTHORIZATION_HEADER));
LOGGER.info("JWT payload header: {}", request.getHeader(X_JWT_PAYLOAD_HEADER));
if (request.getHeader(X_JWT_PAYLOAD_HEADER) == null) {
errorDetails = getErrorMessage("data1", "dat2","data3");
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), errorDetails);
} else {
errorDetails = getErrorMessage("data1","data2","data3");
response.setStatus(HttpStatus.BAD_REQUEST.value());//this can be any status HTTPStatus code
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), errorDetails);
}
if (!isValid) {
errorDetails = getErrorMessage("data1","data2","data3");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), errorDetails);
}
LOGGER.debug("Processing Request Method {} URI {}", request.getMethod(), request.getRequestURI());
} catch (Exception e) {
LOGGER.error("Error validating token :", e);
Map<String, String> errorDetails = getErrorMessage("data1","data2","data3");
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), errorDetails);
filterChain.doFilter(request, response);
}
filterChain.doFilter(request, response);
}
private Map<String, String> getErrorMessage(String dataValue, String messageValue, String errorsValue) {
Map<String, String> errorDetails = new HashMap<>();
errorDetails.put(DATA_KEY, dataValue);
errorDetails.put(MESSAGE_KEY, messageValue);
errorDetails.put(ERROR_KEY, "true");
errorDetails.put(ERRORS_KEY, errorsValue);
return errorDetails;
}
}

Google Docs API V1 access document in Java Servlet

I am trying to access Google Docs API V1 document in Java Servlet using AbstractAuthorizationCodeServlet provide by google api client library but code give error it can't build object of Doc Builder. I have auth 2 creatential and Google doc api is enable from google developer console. below is my code.
#WebServlet("/GetGoogleDoc")
public class GetGoogleDoc extends AbstractAuthorizationCodeServlet {
private static final long serialVersionUID = 1L;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(DocsScopes.DOCUMENTS_READONLY);
private static final String DOCUMENT_ID = "";
private static final String CLIENT_ID="";
private static final String CLIENT_SECRET="";
public GetGoogleDoc() {
super();
// TODO Auto-generated constructor stub
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, initializeFlow())
.build();
}
#Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
GenericUrl url = new GenericUrl(req.getRequestURL().toString());
url.setRawPath("/oauth2callback");
return url.build();
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(), JSON_FACTORY, CLIENT_ID,CLIENT_SECRET,SCOPES).build();
}
#Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
return null;
// return user ID
}
static void replaceNamedRange(Docs service, String documentId, String rangeName, String newText)
throws IOException {
Document document = service.documents().get(documentId).execute();
NamedRanges namedRangeList = document.getNamedRanges().get(rangeName);
if (namedRangeList == null) {
throw new IllegalArgumentException("The named range is no longer present in the document.");
}
List<Range> allRanges = new ArrayList<>();
Set<Integer> insertIndexes = new HashSet<>();
for (NamedRange namedRange : namedRangeList.getNamedRanges()) {
allRanges.addAll(namedRange.getRanges());
insertIndexes.add(namedRange.getRanges().get(0).getStartIndex());
}
// Sort the list of ranges by startIndex, in descending order.
allRanges.sort(Comparator.comparing(Range::getStartIndex).reversed());
// Create a sequence of requests for each range.
List<Request> requests = new ArrayList<>();
for (Range range : allRanges) {
// Delete all the content in the existing range.
requests.add(
new Request().setDeleteContentRange(new DeleteContentRangeRequest().setRange(range)));
if (insertIndexes.contains(range.getStartIndex())) {
// Insert the replacement text.
requests.add(
new Request()
.setInsertText(
new InsertTextRequest()
.setLocation(
new Location()
.setSegmentId(range.getSegmentId())
.setIndex(range.getStartIndex()))
.setText(newText)));
// Re-create the named range on the new text.
requests.add(
new Request()
.setCreateNamedRange(
new CreateNamedRangeRequest()
.setName(rangeName)
.setRange(
new Range()
.setSegmentId(range.getSegmentId())
.setStartIndex(range.getStartIndex())
.setEndIndex(range.getStartIndex() + newText.length()))));
}
}
BatchUpdateDocumentRequest batchUpdateRequest =
new BatchUpdateDocumentRequest()
.setRequests(requests)
.setWriteControl(new WriteControl().setRequiredRevisionId(document.getRevisionId()));
service.documents().batchUpdate(documentId, batchUpdateRequest).execute();
}
}

List all events from Google calendar

I want to list all events all events from Google calendar using this code:
public class GoogleCalendarImpl
{
private static final String APPLICATION_NAME = "";
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/calendar_sample");
private static FileDataStoreFactory dataStoreFactory;
private static HttpTransport httpTransport;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static com.google.api.services.calendar.Calendar client;
static final java.util.List<Calendar> addedCalendarsUsingBatch = Lists.newArrayList();
private static final String calId = "edrhrtherherh#development-1384.iam.gserviceaccount.com";
private static Credential authorize() throws Exception
{
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(GoogleCalendarImpl.class.getResourceAsStream("/development-241a19899242.json")));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory).build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args)
{
try
{
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
Credential credential = authorize();
client = new com.google.api.services.calendar.Calendar.Builder(
httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
getAllEvents();
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
catch (Throwable t)
{
t.printStackTrace();
}
System.exit(1);
}
private static List<Event> getAllEvents() throws IOException
{
List<Event> events = new ArrayList<>();
String nextPageToken = null;
do
{
System.out.println("Loading page " + nextPageToken);
Events feed = client.events().list(calId).setPageToken(nextPageToken).execute();
events.addAll(feed.getItems());
nextPageToken = feed.getNextPageToken();
}
while (nextPageToken != null);
return events;
}
}
But when I run the code Firefox(default web browser) is started and I'm redirected to page:
Error: redirect_uri_mismatch
The redirect URI in the request, http://localhost:56345/Callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/1024206104045435454813?project=762076316631 to update the authorized redirect URIs.
I would like to get all entried from Google calendar configured into my account.
How I can fix this issue?
How to fix Error: redirect_uri_mismatch
Go to your GDC and check what you specified as URI redirect. It should be
http://localhost:portnumber/oauth2callback.
Don't forget the 'oauth2' part.

Calling Apache http client library underload in webservice

I have an issue with my Apache Http Client code. It's a simple hello world method, and another method which calls hello world using the Apache http client code.
I deploy it to webservice and for the first 100 or so in a loop it responds with 20ms fast times. After that is slowly starts going up in response time, if I run it for 3000 requests the response time becomes 150ms, 10000 450ms, etc.. Also the response time never goes back down after long period of in-activity, it only increases.
I have linked this to the method createHttpClient, the b.build method takes longer and longer to build the client for some reason. Is there any way to fix this, or is there a better http API for high long conditions.
My code (not finalized just more of a proof of concept phase right now):
public final class HttpClientTools
{
private static Logger LOG = LoggerFactory.getLogger(HttpClientTools.class);
private HttpClientTools() {}
private static SSLContextBuilder ___builder = null;
private static SSLContext sslContext = null;
private static SSLConnectionSocketFactory __sslsf = null;
private static Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
private static SSLConnectionSocketFactory sslsf = null;
private static final AllowAllHostnameVerifier allowAllHostnameVerifier = new org.apache.http.conn.ssl.AllowAllHostnameVerifier();
private static void init() throws Exception
{
___builder = SSLContexts.custom();
___builder.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }
#Override
public boolean isTrusted(java.security.cert.X509Certificate[] chain,String authType) throws CertificateException { return true; }
});
sslContext = ___builder.build();
__sslsf = new SSLConnectionSocketFactory( sslContext, new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"},null,new X509HostnameVerifier()
{
#Override public void verify(String host, SSLSocket ssl) throws IOException { }
public void verify(String host, X509Certificate cert) throws SSLException { }
#Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { }
#Override public boolean verify(String s, SSLSession sslSession) { return true; }
#Override public void verify(String arg0,java.security.cert.X509Certificate arg1) throws SSLException { }
});
socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", __sslsf).build();
sslsf = new SSLConnectionSocketFactory(___builder.build());
}
private static HttpClient createHttpClient(HttpClientToolsJsonInput input) throws Exception
{
HttpClientToolsInput temp = new HttpClientToolsInput();
temp.setConnectionRequestTimeout(input.getConnectionRequestTimeout());
temp.setConnectionTimeout(input.getConnectionTimeout());
temp.setSocketTimeout(input.getSocketTimeout());
temp.setUsername(input.getUsername());
temp.setPassword(input.getPassword());
temp.setUseDetailedResponseHandler(input.isUseDetailedResponseHandler());
return HttpClientTools.createHttpClient(temp);
}
private static HttpClient createHttpClient(HttpClientToolsInput input) throws Exception
{
HttpClient rtn = null;
long startms = System.currentTimeMillis();
if (___builder == null)
{
init();
}
HttpClientBuilder b = HttpClientBuilder.create();
b.setSslcontext( sslContext);
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(cm);
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(
input.getSocketTimeout()).setConnectTimeout(
input.getConnectionTimeout()).setConnectionRequestTimeout(
input.getConnectionRequestTimeout()).build();
b.setDefaultRequestConfig(defaultRequestConfig);
if (StringTools.doesStringHaveData(input.getUsername()) && StringTools.doesStringHaveData(input.getPassword()) )
{
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(input.getUsername(), input.getPassword()));
b.setDefaultCredentialsProvider(credsProvider);
}
long ms1=System.currentTimeMillis();
rtn = b.build(); // takes increasing time when deployed on tomee
System.out.println("HttpClientTools m12 took "+(System.currentTimeMillis()-ms1)+" ms");
long endms = System.currentTimeMillis();
System.out.println("HttpClientTools getCloseableHttpClient() took "+(endms-startms)+" ms");
return rtn;
}
public static String sendHttpPostRequest(HttpClientToolsInput input) throws Exception
{
HttpClient httpclient = null;
HttpPost _http = null;
InputStream entityIS = null;
String responseBody = null;
HttpResponse clhttpr = null;
try
{
for (String url : input.getUrls())
{
httpclient = HttpClientTools.createHttpClient(input);
_http = new HttpPost(url);
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(input.getSocketTimeout()).setConnectTimeout(input.getConnectionTimeout()).setConnectionRequestTimeout(input.getConnectionRequestTimeout()).build();
_http.setConfig(defaultRequestConfig);
StringEntity strent = new StringEntity(input.getMessage());
strent.setContentType("text/xml; charset=utf-8");
_http.setEntity(strent);
ResponseHandler<String> response = null;
if (input.isUseDetailedResponseHandler())
{
response = new DetailedExceptionReasonResponseHandler();
}
else
{
response = new BasicResponseHandler();
}
boolean https = false;
if (url.toLowerCase(Locale.US).startsWith("https"))
{
https = true;
}
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
HttpHost host = new HttpHost(url);
if (StringTools.doesStringHaveData(input.getUsername()) && StringTools.doesStringHaveData(input.getPassword()))
{
authCache.put(host, basicAuth);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(input.getUsername(), input.getPassword()));
HttpClientContext _context = HttpClientContext.create();
_context.setAuthCache(authCache);
_context.setCredentialsProvider(credentialsProvider);
clhttpr = httpclient.execute(_http, _context);
}
else
{
clhttpr = httpclient.execute(_http);
}
entityIS = clhttpr.getEntity().getContent();
responseBody = Convert.inputStreamToString(entityIS);
try { EntityUtils.consume(_http.getEntity()); } catch(Exception e) {}
try { clhttpr.getEntity().getContent().close(); } catch(Exception e) {}
try { entityIS.close(); } catch(Exception e) {}
}
return responseBody;
}
catch (Exception e)
{
try { EntityUtils.consume(_http.getEntity()); } catch(Exception e1) {}
try { clhttpr.getEntity().getContent().close(); } catch(Exception e2) {}
try { entityIS.close(); } catch(Exception e3) {}
e.printStackTrace();
throw e;
}
}
public static void main(String[] args) throws Exception
{
HttpClientToolsInput input = new HttpClientToolsInput();
input.setConnectionRequestTimeout(9000);
input.setConnectionTimeout(9000);
input.setSocketTimeout(9000);
String msg2="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsdl=\"http://myservice.org/wsdl\"><soapenv:Header/><soapenv:Body><wsdl:callHello/></soapenv:Body></soapenv:Envelope>";
input.setMessage(msg2);
input.setUseDetailedResponseHandler(false);
input.addUrl("http://127.0.0.1:8282/simple-webservice/MyService?wsdl");
String response = "";
long ms=0;
for (int i=0; i<999;i++)
{
ms = System.currentTimeMillis();
response = HttpClientTools.sendHttpPostRequest(input);
System.out.println("response["+i+"][ms="+(System.currentTimeMillis()-ms)+"]="+response);
}
}
}

how variables accessible in anonymous class?

I have following code :
class A extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletRespons
response) throws ServletException, IOExceptio
{
String str= "String In doGet()";
JsonBatchCallback<Users> callback = new
JsonBatchCallback<Users>(){
String inThisClass = str; // Showing me error
}
}
}
str is not accessible. How i can access "str".
My Actual Code is as follows :
public class SyncTask extends HttpServlet {
private static final long serialVersionUID = 1L;
final Logger logger = Logger.getLogger(this.getClass().getName());
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String domain = request.getParameter("DomainName");
String reqAdminEmail = request.getParameter("AdminEmail");
String searchRegex = request.getParameter("searchRegex");
Boolean manualSync = false;
if(reqAdminEmail != null){
manualSync = true;
}
String adminEmail = "";
try{
Date startTime = new Date();
Manager mangerObj = new Manager("MASTER");
final String SERVICE_ACCOUNT_EMAIL = Constant.getServiceAccountEmail();
final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = Constant.getServiceAccountPkcs12FilePath();
Collection<String> SCOPES = new ArrayList<String>();
SCOPES.add("https://www.googleapis.com/auth/admin.directory.user");
SCOPES.add("https://www.googleapis.com/auth/admin.directory.orgunit");
String nextToken = null;
int noOfUsers = 0;
mangerObj = new Manager(domain);
Configuration config = mangerObj.getConfiguration();
if(config==null)
return;
else
adminEmail = config.getAdminEmail();
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setServiceAccountUser(adminEmail)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Directory directoryService = new Directory.Builder(httpTransport, jsonFactory, credential).setApplicationName("Directory ").build();
BatchRequest batch = directoryService.batch();
do{
List list = directoryService.users().list();
list.setCustomer("my_customer");
list.setMaxResults(500);
list.setPageToken(nextToken);
list.setFields("nextPageToken,users(relations,orgUnitPath,primaryEmail,name)");
if(searchRegex != null ){
if(searchRegex.isEmpty() == false){
list.setQuery("email:"+searchRegex+"*");
}
}
JsonBatchCallback<Users> callback = new JsonBatchCallback<Users>() {
#Override
public void onSuccess(Users users, HttpHeaders responseHeaders) {
nextToken = users.getNextPageToken(); // i'm not able to access nextToken
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
list.queue(batch, callback);
}while(nextToken != null);
try {
batch.execute();
} catch(Exception ex){
ErrorHandler.errorHandler(this.getClass().getName(), ex);
}
}catch(Exception ex){
ErrorHandler.errorHandler(this.getClass().getName(), ex);
}
}
I have updated my code where actually i am getting error. I want to access nextToken into anonymous class,but i not able to accesss.
Error as follows :
nextToken cannot be resolved to a variable
You need to make the str variable final.
As a matter of fact the inThisClass variable is redundant, at least in what you posted so far.
But your actual code shows a different error message from your sample code. Your actual code cannot be written, because you don't have write-access to local variables in enclosing scopes from anonymous classes. You will have to think of something else, such as a final StringBuilder.
Declare str in doGet as final:
final String str = "String In doGet()";
Anonymous classes can access only final local variables of an outer method. In Java 8 it was changed.
Also your IDE should assist you with fixes of such errors.

Categories