package com.istreepetge.web.controllers;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.common.base.CharMatcher;
import com.istreepetge.models.IpCalendarEvent;
@Controller
public class OauthResponseHandler {
protected final Log logger = LogFactory.getLog(getClass());
@Value("#{apiproperties['clientId']}")
private String clientId;
@Value("#{apiproperties['clientSecret']}")
private String clientSecret;
@Value("#{apiproperties['redirectUrl']}")
private String redirectUrl;
@RequestMapping(value = "/oauth2callback.html", method = RequestMethod.GET)
public ModelAndView handleOauthResponse(
@RequestParam(value = "code") String code,
HttpServletRequest request) {
logger.info("Oauth response code is: " + code);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
ModelAndView mv = new ModelAndView();
try {
AccessTokenResponse googleResponse = new GoogleAuthorizationCodeGrant(
httpTransport, jsonFactory, clientId, clientSecret, code,
redirectUrl).execute();
String accessToken = googleResponse.accessToken;
String refreshToken = googleResponse.refreshToken;
HttpSession session = request.getSession();
session.setAttribute("accessToken", accessToken);
session.setAttribute("refreshToken", refreshToken);
IpCalendarEvent ice = new IpCalendarEvent();
mv.addObject("IpCalendarEvent", ice);
mv.addObject("code", accessToken);
} catch (IOException e) {
e.printStackTrace();
}
mv.setViewName("hello");
return mv;
}
}