package com.cib.yym.homepage.service.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.Logger;
import com.cib.yym.homepage.common.CacheManager;
import com.cib.yym.homepage.common.CacheManagerFactory;
import com.cib.yym.homepage.service.ReadItLaterConfigLoader;
import com.cib.yym.homepage.service.ReadItLaterService;
import com.yym.sina.weibo.WeiboServiceImpl;
public class ReadItLaterServiceImpl implements ReadItLaterService{
private static final Logger log = Logger.getLogger(ReadItLaterServiceImpl.class.getName());
@Override
public boolean authenticate(String user, String password) {
String authUrl = null;
String apiKey = null;
try {
CacheManager cache = CacheManagerFactory.getCacheManager();
if(cache.getCachedData(CacheManager.MAP_READITLATER_CONFIG, "authUrl") != null)
{
authUrl = (String)cache.getCachedData(CacheManager.MAP_READITLATER_CONFIG, "authUrl");
apiKey = (String)cache.getCachedData(CacheManager.MAP_READITLATER_CONFIG, "apiKey");
log.info("cache hit authUrl="+authUrl);
}else
{
//read it from config directly
authUrl = ReadItLaterConfigLoader.getInstance().getValue("authUrl");
apiKey = ReadItLaterConfigLoader.getInstance().getValue("apiKey");
log.info("no authUrl in cache");
}
} catch (Exception e) {
e.printStackTrace();
}
URL url;
try {
authUrl = authUrl+"apikey="+apiKey
+"&username="+user
+"&password="+password;
url = new URL(authUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.connect();
//BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
//String result = "";
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
//http://readitlaterlist.com/api/docs/#response
//200 - Request was successful
return true;
// String line;
// while ((line = reader.readLine()) != null) {
// result = result + line;
// }
// reader.close();
//
// log.info("result="+result);
} else {
// Server returned HTTP error code.
/**
* 400 - Invalid request, please make sure you follow the documentation for proper syntax
* 401 - Username and/or password is incorrect
* 403 - Rate limit exceeded, please wait a little bit before resubmitting
* 503 - Read It Later's sync server is down for scheduled maintenance.
*/
log.info("error http code:"+connection.getResponseCode());
return false;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}