इस दस्तावेज़ में, सैंपल वेब ऐप्लिकेशन के ज़रिए, Java सर्वलेट का इस्तेमाल करके OAuth 2.0 अनुमति कॉलबैक हैंडलर को लागू करने का तरीका बताया गया है. यह ऐप्लिकेशन, Google Tasks API का इस्तेमाल करके उपयोगकर्ता के टास्क दिखाएगा. सैंपल ऐप्लिकेशन, सबसे पहले उपयोगकर्ता के Google Tasks को ऐक्सेस करने की अनुमति का अनुरोध करेगा. इसके बाद, वह उपयोगकर्ता के टास्क को टास्क की डिफ़ॉल्ट सूची में दिखाएगा.
ऑडियंस
यह दस्तावेज़ उन लोगों के लिए है जिन्हें Java और J2EE वेब ऐप्लिकेशन आर्किटेक्चर के बारे में जानकारी है. हमारा सुझाव है कि आप OAuth 2.0 के ऑथराइज़ेशन फ़्लो के बारे में थोड़ा जान लें.
सामग्री
पूरी तरह से काम करने वाला सैंपल बनाने के लिए, आपको कई चरणों को पूरा करना होगा. इसके लिए, आपको:
- web.xml फ़ाइल में सर्वलेट मैपिंग की जानकारी देना
- अपने सिस्टम पर उपयोगकर्ताओं की पुष्टि करना और Tasks को ऐक्सेस करने के लिए अनुमति का अनुरोध करना
- Google के ऑथराइज़ेशन एंडपॉइंट से ऑथराइज़ेशन कोड सुनना
- ऑथराइज़ेशन कोड को रीफ़्रेश और ऐक्सेस टोकन से बदलना
- उपयोगकर्ता के टास्क पढ़ना और उन्हें दिखाना
web.xml फ़ाइल में सर्वलेट मैपिंग की जानकारी देना
हम अपने ऐप्लिकेशन में दो सर्वलेट का इस्तेमाल करेंगे:
- PrintTasksTitlesServlet (/ पर मैप किया गया): ऐप्लिकेशन का एंट्री पॉइंट, जो उपयोगकर्ता की पुष्टि करेगा और उपयोगकर्ता के टास्क दिखाएगा
- OAuthCodeCallbackHandlerServlet (/oauth2callback पर मैप किया गया): OAuth 2.0 का कॉलबैक, जो OAuth ऑथराइज़ेशन एंडपॉइंट से मिले रिस्पॉन्स को मैनेज करता है
यहां web.xml फ़ाइल दी गई है, जो इन दो सर्वलेट को हमारे ऐप्लिकेशन के यूआरएल से मैप करती है:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>PrintTasksTitles</servlet-name> <servlet-class>com.google.oauthsample.PrintTasksTitlesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PrintTasksTitles</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet> <servlet-name>OAuthCodeCallbackHandlerServlet</servlet-name> <servlet-class>com.google.oauthsample.OAuthCodeCallbackHandlerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OAuthCodeCallbackHandlerServlet</servlet-name> <url-pattern>/oauth2callback</url-pattern> </servlet-mapping> </web-app>
अपने सिस्टम पर उपयोगकर्ताओं की पुष्टि करना और उसके टास्क ऐक्सेस करने के लिए अनुमति का अनुरोध करना
उपयोगकर्ता, रूट '/' यूआरएल के ज़रिए ऐप्लिकेशन में प्रवेश करता है. यह यूआरएल, PrintTaskListsTitlesServlet सर्वलेट से मैप किया गया है. उस सर्वलेट में ये काम किए जाते हैं:
- यह जांच करता है कि उपयोगकर्ता की पुष्टि सिस्टम पर की गई है या नहीं
- अगर उपयोगकर्ता की पहचान की पुष्टि नहीं की जाती है, तो उसे पुष्टि करने वाले पेज पर रीडायरेक्ट कर दिया जाता है
- अगर उपयोगकर्ता की पुष्टि हो जाती है, तो हम यह जांच करते हैं कि हमारे डेटा स्टोरेज में पहले से कोई रीफ़्रेश टोकन है या नहीं. इसे नीचे दिए गए OAuthTokenDao से मैनेज किया जाता है. अगर उपयोगकर्ता के लिए स्टोर में कोई रीफ़्रेश टोकन नहीं है, तो इसका मतलब है कि उपयोगकर्ता ने अब तक ऐप्लिकेशन को अपने टास्क ऐक्सेस करने की अनुमति नहीं दी है. ऐसे में, उपयोगकर्ता को Google के OAuth 2.0 ऑथराइज़ेशन एंडपॉइंट पर रीडायरेक्ट कर दिया जाता है.
package com.google.oauthsample; import ... /** * Simple sample Servlet which will display the tasks in the default task list of the user. */ @SuppressWarnings("serial") public class PrintTasksTitlesServlet extends HttpServlet { /** * The OAuth Token DAO implementation, used to persist the OAuth refresh token. * Consider injecting it instead of using a static initialization. Also we are * using a simple memory implementation as a mock. Change the implementation to * using your database system. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl(); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the current user // This is using App Engine's User Service but you should replace this to // your own user/login implementation UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); // If the user is not logged-in it is redirected to the login service, then back to this page if (user == null) { resp.sendRedirect(userService.createLoginURL(getFullRequestUrl(req))); return; } // Checking if we already have tokens for this user in store AccessTokenResponse accessTokenResponse = oauthTokenDao.getKeys(user.getEmail()); // If we don't have tokens for this user if (accessTokenResponse == null) { OAuthProperties oauthProperties = new OAuthProperties(); // Redirect to the Google OAuth 2.0 authorization endpoint resp.sendRedirect(new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()); return; } } /** * Construct the request's URL without the parameter part. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getFullRequestUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = req.getServletPath(); String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); String queryString = (req.getQueryString() == null) ? "" : "?" + req.getQueryString(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo + queryString; } }
ध्यान दें: ऊपर दिए गए तरीके में, कुछ App Engine लाइब्रेरी का इस्तेमाल किया गया है. इनका इस्तेमाल, प्रोसेस को आसान बनाने के लिए किया जाता है. अगर किसी दूसरे प्लैटफ़ॉर्म के लिए डेवलप किया जा रहा है, तो UserService इंटरफ़ेस को फिर से लागू करें. यह इंटरफ़ेस, उपयोगकर्ता की पुष्टि करता है.
उपयोगकर्ता के ऑथराइज़ेशन टोकन को सेव और ऐक्सेस करने के लिए, ऐप्लिकेशन डीएओ का इस्तेमाल करता है. यहां इंटरफ़ेस - OAuthTokenDao - और मॉक (इन-मेमोरी) इंप्लिमेंटेशन - OAuthTokenDaoMemoryImpl - दिया गया है. इनका इस्तेमाल इस सैंपल में किया गया है:
package com.google.oauthsample; import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; /** * Allows easy storage and access of authorization tokens. */ public interface OAuthTokenDao { /** * Stores the given AccessTokenResponse using the {@code username}, the OAuth * {@code clientID} and the tokens scopes as keys. * * @param tokens The AccessTokenResponse to store * @param userName The userName associated wit the token */ public void saveKeys(AccessTokenResponse tokens, String userName); /** * Returns the AccessTokenResponse stored for the given username, clientId and * scopes. Returns {@code null} if there is no AccessTokenResponse for this * user and scopes. * * @param userName The username of which to get the stored AccessTokenResponse * @return The AccessTokenResponse of the given username */ public AccessTokenResponse getKeys(String userName); }
package com.google.oauthsample; import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; ... /** * Quick and Dirty memory implementation of {@link OAuthTokenDao} based on * HashMaps. */ public class OAuthTokenDaoMemoryImpl implements OAuthTokenDao { /** Object where all the Tokens will be stored */ private static Map<String, AccessTokenResponse> tokenPersistance = new HashMap<String, AccessTokenResponse>(); public void saveKeys(AccessTokenResponse tokens, String userName) { tokenPersistance.put(userName, tokens); } public AccessTokenResponse getKeys(String userName) { return tokenPersistance.get(userName); } }
साथ ही, ऐप्लिकेशन के लिए OAuth 2.0 क्रेडेंशियल, प्रॉपर्टी फ़ाइल में सेव किए जाते हैं. इसके अलावा, उन्हें अपनी किसी Java क्लास में कहीं भी कॉन्स्टेंट के तौर पर सेट किया जा सकता है. हालांकि, यहां OAuthProperties क्लास और oauth.properties फ़ाइल दी गई है, जिसका इस्तेमाल सैंपल में किया जा रहा है:
package com.google.oauthsample; import ... /** * Object representation of an OAuth properties file. */ public class OAuthProperties { public static final String DEFAULT_OAUTH_PROPERTIES_FILE_NAME = "oauth.properties"; /** The OAuth 2.0 Client ID */ private String clientId; /** The OAuth 2.0 Client Secret */ private String clientSecret; /** The Google APIs scopes to access */ private String scopes; /** * Instantiates a new OauthProperties object reading its values from the * {@code OAUTH_PROPERTIES_FILE_NAME} properties file. * * @throws IOException IF there is an issue reading the {@code propertiesFile} * @throws OauthPropertiesFormatException If the given {@code propertiesFile} * is not of the right format (does not contains the keys {@code * clientId}, {@code clientSecret} and {@code scopes}) */ public OAuthProperties() throws IOException { this(OAuthProperties.class.getResourceAsStream(DEFAULT_OAUTH_PROPERTIES_FILE_NAME)); } /** * Instantiates a new OauthProperties object reading its values from the given * properties file. * * @param propertiesFile the InputStream to read an OAuth Properties file. The * file should contain the keys {@code clientId}, {@code * clientSecret} and {@code scopes} * @throws IOException IF there is an issue reading the {@code propertiesFile} * @throws OAuthPropertiesFormatException If the given {@code propertiesFile} * is not of the right format (does not contains the keys {@code * clientId}, {@code clientSecret} and {@code scopes}) */ public OAuthProperties(InputStream propertiesFile) throws IOException { Properties oauthProperties = new Properties(); oauthProperties.load(propertiesFile); clientId = oauthProperties.getProperty("clientId"); clientSecret = oauthProperties.getProperty("clientSecret"); scopes = oauthProperties.getProperty("scopes"); if ((clientId == null) || (clientSecret == null) || (scopes == null)) { throw new OAuthPropertiesFormatException(); } } /** * @return the clientId */ public String getClientId() { return clientId; } /** * @return the clientSecret */ public String getClientSecret() { return clientSecret; } /** * @return the scopes */ public String getScopesAsString() { return scopes; } /** * Thrown when the OAuth properties file was not at the right format, i.e not * having the right properties names. */ @SuppressWarnings("serial") public class OAuthPropertiesFormatException extends RuntimeException { } }
यहां oauth.properties फ़ाइल दी गई है. इसमें आपके ऐप्लिकेशन के OAuth 2.0 क्रेडेंशियल शामिल हैं. आपको यहां दी गई वैल्यू को खुद बदलना होगा.
# Client ID and secret. They can be found in the APIs console. clientId=1234567890.apps.googleusercontent.com clientSecret=aBcDeFgHiJkLmNoPqRsTuVwXyZ # API scopes. Space separated. scopes=https://www.googleapis.com/auth/tasks
OAuth 2.0 क्लाइंट आईडी और क्लाइंट पासकोड की मदद से, आपके ऐप्लिकेशन की पहचान की जाती है. साथ ही, Tasks API को आपके ऐप्लिकेशन के लिए तय किए गए फ़िल्टर और कोटा के नियम लागू करने की अनुमति मिलती है. क्लाइंट आईडी और सीक्रेट, Google API कंसोल में मिल सकते हैं. Console पर जाने के बाद, आपको:
- कोई प्रोजेक्ट बनाएं या चुनें.
- सेवाओं की सूची में, Tasks API की स्थिति को चालू पर टॉगल करके, Tasks API को चालू करें.
- अगर अब तक कोई OAuth 2.0 क्लाइंट आईडी नहीं बनाया गया है, तो एपीआई ऐक्सेस में जाकर एक बनाएं.
- पक्का करें कि प्रोजेक्ट के OAuth 2.0 कोड कॉलबैक हैंडलर यूआरएल को रीडायरेक्ट यूआरआई में रजिस्टर/व्हाइटलिस्ट किया गया हो. उदाहरण के लिए, अगर आपका वेब ऐप्लिकेशन https://www.example.com डोमेन से दिखाया जाता है, तो आपको इस सैंपल प्रोजेक्ट में https://www.example.com/oauth2callback रजिस्टर करना होगा.

Google के ऑथराइज़ेशन एंडपॉइंट से ऑथराइज़ेशन कोड सुनना
अगर उपयोगकर्ता ने अब तक ऐप्लिकेशन को टास्क ऐक्सेस करने की अनुमति नहीं दी है और इसलिए, उसे Google के OAuth 2.0 ऑथराइज़ेशन एंडपॉइंट पर रीडायरेक्ट किया गया है, तो उपयोगकर्ता को Google से अनुमति देने वाला डायलॉग दिखेगा. इसमें उपयोगकर्ता से आपके ऐप्लिकेशन को टास्क ऐक्सेस करने की अनुमति देने के लिए कहा जाएगा:

ऐक्सेस देने या अस्वीकार करने के बाद, उपयोगकर्ता को OAuth 2.0 कोड कॉलबैक हैंडलर पर रीडायरेक्ट कर दिया जाएगा. इसे Google के ऑथराइज़ेशन यूआरएल को बनाते समय, रीडायरेक्ट/कॉलबैक के तौर पर तय किया गया है:
new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()
OAuth 2.0 कोड कॉलबैक हैंडलर - OAuthCodeCallbackHandlerServlet - Google OAuth 2.0 एंडपॉइंट से रीडायरेक्ट को मैनेज करता है. दो तरह के मामले हैं:
- उपयोगकर्ता ने ऐक्सेस दिया है: यूआरएल पैरामीटर से OAuth 2.0 कोड पाने के लिए, अनुरोध को पार्स करता है
- उपयोगकर्ता ने ऐक्सेस देने से इनकार किया है: उपयोगकर्ता को एक मैसेज दिखाता है
package com.google.oauthsample; import ... /** * Servlet handling the OAuth callback from the authentication service. We are * retrieving the OAuth code, then exchanging it for a refresh and an access * token and saving it. */ @SuppressWarnings("serial") public class OAuthCodeCallbackHandlerServlet extends HttpServlet { /** The name of the Oauth code URL parameter */ public static final String CODE_URL_PARAM_NAME = "code"; /** The name of the OAuth error URL parameter */ public static final String ERROR_URL_PARAM_NAME = "error"; /** The URL suffix of the servlet */ public static final String URL_MAPPING = "/oauth2callback"; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the "error" URL parameter String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME); // Checking if there was an error such as the user denied access if (error != null && error.length > 0) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\"."); return; } // Getting the "code" URL parameter String[] code = req.getParameterValues(CODE_URL_PARAM_NAME); // Checking conditions on the "code" URL parameter if (code == null || code.length == 0) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing"); return; } } /** * Construct the OAuth code callback handler URL. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getOAuthCodeCallbackHandlerUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = URL_MAPPING; String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo; } }
ऑथराइज़ेशन कोड को रीफ़्रेश और ऐक्सेस टोकन से बदलना
इसके बाद, OAuthCodeCallbackHandlerServlet, रीफ़्रेश और ऐक्सेस टोकन के लिए Auth 2.0 कोड को एक्सचेंज करता है. साथ ही, उसे डेटास्टोर में सेव करता है और उपयोगकर्ता को PrintTaskListsTitlesServlet यूआरएल पर वापस रीडायरेक्ट करता है:
नीचे दी गई फ़ाइल में जोड़ा गया कोड सिंटैक्स हाइलाइट किया गया है. पहले से मौजूद कोड को धूसर रंग में दिखाया गया है.
package com.google.oauthsample; import ... /** * Servlet handling the OAuth callback from the authentication service. We are * retrieving the OAuth code, then exchanging it for a refresh and an access * token and saving it. */ @SuppressWarnings("serial") public class OAuthCodeCallbackHandlerServlet extends HttpServlet { /** The name of the Oauth code URL parameter */ public static final String CODE_URL_PARAM_NAME = "code"; /** The name of the OAuth error URL parameter */ public static final String ERROR_URL_PARAM_NAME = "error"; /** The URL suffix of the servlet */ public static final String URL_MAPPING = "/oauth2callback";/** कॉलबैक को मैनेज करने के बाद, उपयोगकर्ता को रीडायरेक्ट करने के लिए यूआरएल. अगर आपके पास लोगों को रीडायरेक्ट करने के लिए एक से ज़्यादा यूआरएल हैं, तो उपयोगकर्ताओं को Google के अनुमति वाले यूआरएल पर रीडायरेक्ट करने से पहले, * इसे कुकी में सेव करें. */ public static final String REDIRECT_URL = "/"; /** The OAuth Token DAO implementation. इसके बजाय, इसे इंजेक्ट करें * स्टैटिक शुरू करने की सुविधा का इस्तेमाल करने के बजाय. साथ ही, हम मॉक के तौर पर, मेमोरी लागू करने के एक आसान तरीके का इस्तेमाल कर रहे हैं. लागू करने के तरीके को बदलकर, अपने डेटाबेस सिस्टम का इस्तेमाल करें. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl();// इनकमिंग अनुरोध का यूआरएल बनाएं String requestUrl = getOAuthCodeCallbackHandlerUrl(req); // कोड को OAuth टोकन के लिए एक्सचेंज करें AccessTokenResponse accessTokenResponse = exchangeCodeForAccessAndRefreshTokens(code[0], requestUrl); // मौजूदा उपयोगकर्ता को पाना // यह App Engine की User Service का इस्तेमाल कर रहा है, लेकिन आपको इसे अपने उपयोगकर्ता/लॉगिन लागू करने के लिए बदलना चाहिए UserService userService = UserServiceFactory.getUserService(); String email = userService.getCurrentUser().getEmail(); // टोकन सेव करें oauthTokenDao.saveKeys(accessTokenResponse, email); resp.sendRedirect(REDIRECT_URL); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the "error" URL parameter String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME); // Checking if there was an error such as the user denied access if (error != null && error.length > 0) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\"."); return; } // Getting the "code" URL parameter String[] code = req.getParameterValues(CODE_URL_PARAM_NAME); // Checking conditions on the "code" URL parameter if (code == null || code.length == 0) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing"); return; }/** * दिए गए कोड को एक्सचेंज और रीफ़्रेश टोकन के लिए एक्सचेंज करता है. * * @param code The code gotten back from the authorization service * @param currentUrl The URL of the callback * @param oauthProperties The object containing the OAuth configuration * @return The object containing an access and refresh token both * @throws IOException */ public AccessTokenResponse exchangeCodeForAccessAndRefreshTokens(String code, String currentUrl) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); // Loading the oauth config file OAuthProperties oauthProperties = new OAuthProperties(); return new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory, oauthProperties .getClientId(), oauthProperties.getClientSecret(), code, currentUrl).execute(); } } /** * Construct the OAuth code callback handler URL. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getOAuthCodeCallbackHandlerUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = URL_MAPPING; String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo; }OAuthCodeCallbackHandlerServlet.java फ़ाइलध्यान दें: ऊपर दिए गए तरीके में, कुछ App Engine लाइब्रेरी का इस्तेमाल किया गया है. इनका इस्तेमाल, प्रोसेस को आसान बनाने के लिए किया जाता है. अगर किसी दूसरे प्लैटफ़ॉर्म के लिए डेवलप किया जा रहा है, तो UserService इंटरफ़ेस को फिर से लागू करें. यह इंटरफ़ेस, उपयोगकर्ता की पुष्टि करता है.
उपयोगकर्ता के टास्क पढ़ना और उन्हें दिखाना
उपयोगकर्ता ने ऐप्लिकेशन को अपने टास्क का ऐक्सेस दिया हो. ऐप्लिकेशन में एक रीफ़्रेश टोकन होता है, जो OAuthTokenDao की मदद से ऐक्सेस किए जा सकने वाले डेटास्टोर में सेव होता है. PrintTaskListsTitlesServlet सर्वलेट, अब इन टोकन का इस्तेमाल करके उपयोगकर्ता के टास्क ऐक्सेस कर सकता है और उन्हें दिखा सकता है:
नीचे दी गई फ़ाइल में जोड़ा गया कोड सिंटैक्स हाइलाइट किया गया है. पहले से मौजूद कोड को धूसर रंग में दिखाया गया है.
package com.google.oauthsample; import ... /** * Simple sample Servlet which will display the tasks in the default task list of the user. */ @SuppressWarnings("serial") public class PrintTasksTitlesServlet extends HttpServlet { /** * The OAuth Token DAO implementation, used to persist the OAuth refresh token. * Consider injecting it instead of using a static initialization. Also we are * using a simple memory implementation as a mock. Change the implementation to * using your database system. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl(); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the current user // This is using App Engine's User Service but you should replace this to // your own user/login implementation UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); // If the user is not logged-in it is redirected to the login service, then back to this page if (user == null) { resp.sendRedirect(userService.createLoginURL(getFullRequestUrl(req))); return; } // Checking if we already have tokens for this user in store AccessTokenResponse accessTokenResponse = oauthTokenDao.getKeys(user.getEmail()); // If we don't have tokens for this user if (accessTokenResponse == null) { OAuthProperties oauthProperties = new OAuthProperties(); // Redirect to the Google OAuth 2.0 authorization endpoint resp.sendRedirect(new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()); return; }// जवाब में उपयोगकर्ता की टास्क सूचियों के शीर्षक प्रिंट करना resp.setContentType("text/plain"); resp.getWriter().append("उपयोगकर्ता " + user.getEmail() + " के लिए टास्क की सूचियों के शीर्षक:\n\n"); printTasksTitles(accessTokenResponse, resp.getWriter());/** * डिफ़ॉल्ट टास्क सूची में उपयोगकर्ताओं के टास्क की सूची पाने के लिए, Google Tasks API का इस्तेमाल करता है. * * @param accessTokenResponse OAuth 2.0 AccessTokenResponse ऑब्जेक्ट, जिसमें ऐक्सेस टोकन और रीफ़्रेश टोकन शामिल होता है. * @param output आउटपुट स्ट्रीम लेखक, जहां टास्क की सूचियों के टाइटल लिखने हैं * @return डिफ़ॉल्ट टास्क की सूची में उपयोगकर्ताओं के टास्क के टाइटल की सूची. * @throws IOException */ public void printTasksTitles(AccessTokenResponse accessTokenResponse, Writer output) throws IOException { // Tasks service को शुरू करना HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); OAuthProperties oauthProperties = new OAuthProperties(); GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource( accessTokenResponse.accessToken, transport, jsonFactory, oauthProperties.getClientId(), oauthProperties.getClientSecret(), accessTokenResponse.refreshToken); Tasks service = new Tasks(transport, accessProtectedResource, jsonFactory); // Tasks की सूचियों की क्वेरी करने के लिए, शुरू की गई Tasks API सेवा का इस्तेमाल करना com.google.api.services.tasks.model.Tasks tasks = service.tasks.list("@default").execute(); for (Task task : tasks.items) { output.append(task.title + "\n"); } } } } /** * Construct the request's URL without the parameter part. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getFullRequestUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = req.getServletPath(); String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); String queryString = (req.getQueryString() == null) ? "" : "?" + req.getQueryString(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo + queryString; }PrintTasksTitlesServlet.java फ़ाइलउपयोगकर्ता को उसके टास्क दिखेंगे:
उपयोगकर्ता के टास्कआवेदन का सैंपल
इस सैंपल ऐप्लिकेशन का कोड यहां से डाउनलोड किया जा सकता है. इसे देखें.