package kr.ac.kaist.resl.lilliput.core;
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import kr.ac.kaist.resl.lilliput.util.JSONHelper;
import kr.ac.kaist.resl.lilliput.util.MongoHelper;
import kr.ac.kaist.resl.lilliput.util.ONSHelper;
import org.json.JSONException;
import org.json.JSONObject;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.NamedFacebookType;
import com.restfb.types.User;
import edu.stanford.smi.protege.model.Project;
import edu.stanford.smi.protege.server.RemoteProjectManager;
import edu.stanford.smi.protegex.owl.model.OWLDatatypeProperty;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import edu.stanford.smi.protegex.owl.model.OWLNamedClass;
import edu.stanford.smi.protegex.owl.model.OWLObjectProperty;
import edu.stanford.smi.protegex.owl.model.RDFIndividual;
/**
* Servlet implementation class HumanRegistration
*/
public class HumanRegistration extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HumanRegistration() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String accessToken = (String)request.getParameter("accessToken");
String password = (String)request.getParameter("password");
String result = Registration(accessToken, password, "Facebook");
request.setAttribute("result", result);
RequestDispatcher dispatcher = request.getRequestDispatcher("ServiceResult.jsp");
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
public String Registration(String accessToken, String password, String from)
{
try {
//making facebookClient
FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
//fetch user
User user = facebookClient.fetchObject("me", User.class);
//creating json object of user
JSONHelper jhelper = new JSONHelper();
JSONObject jsonUser = jhelper.getJSONFromUser(user);
DatatypeFactory dataFactory = DatatypeFactory.newInstance();
XMLGregorianCalendar now = dataFactory.newXMLGregorianCalendar(new GregorianCalendar());
jsonUser.put("SyncTime", now.toString());
//creating json to save Human entity
String fid = jsonUser.getString("fid");
String em = jsonUser.getString("email");
String gender = jsonUser.getString("gender");
JSONObject Human = new JSONObject();
Human.put("email", em);
Human.put("fid", fid);
Human.put("password", password);
Human.put("from", from);
Human.put("gender", gender);
Human.put("picture", "https://graph.facebook.com/"+fid+"/picture");
Human.put("access_token", accessToken);
List<String> queryTypes = new ArrayList<String>();
//Ontology�� �ҷ���
RemoteProjectManager rpm = RemoteProjectManager.getInstance();
Project p = rpm.getProject("localhost:5100", "Lilliput", "1234", "IoTSocialGraph", true);
OWLModel owlModel = (OWLModel)p.getKnowledgeBase();
//fid�� �˻��Ǹ� late binded
//EPC�� �˻��Ǹ� already registrered
//�ƹ��͵� �ƴϸ� ���� ó��
MongoHelper mHelper = new MongoHelper();
//Check whether human is already saved
String objectIdOfDB = mHelper.isHumanSavedInDB(fid);
if( objectIdOfDB != null )
{
System.out.println(fid + " is already saved");
mHelper.close();
return "Error : " + fid + " is already saved";
}
//���� epc�� �����´�
String vacantEPC = mHelper.getVacantHumanEPCinDB(gender);
OWLNamedClass humanClass = owlModel.getOWLNamedClass("Human");
RDFIndividual humanInd = owlModel.getRDFIndividual(vacantEPC);
if( humanInd != null )
{
System.out.println(" UnexpectedError : Human is not in DB and Human is in ontology");
mHelper.close();
return " Unexpected Error : Human is not in DB and Human is in ontology";
}
else
{
humanInd = humanClass.createRDFIndividual(vacantEPC);
String result = mHelper.saveHumanEPCToDB(vacantEPC, Human);
if( result == null )
{
System.out.println(" Unexpected Error : Human cannot saved in DB");
mHelper.close();
return " Unexpected Error : Human cannot saved in DB" ;
}
}
//������ ����
// humanEPC <-- epc�� ��� ����
// ���� ������ ������
//for getting object id
queryTypes.add("email");
//creating json to save Information entity
String humanInformID = mHelper.saveToDB("HumanInformation", jsonUser, queryTypes);
System.out.println(humanInformID);
// �����ϰ� inform ID �� ������
//save to Ontology : Information
OWLNamedClass informClass = owlModel.getOWLNamedClass("HumanInformation");
RDFIndividual informInd = owlModel.getRDFIndividual(humanInformID);
if( informInd != null )
{
System.out.println(" Unexpected Error : Human information is made just before, but it's already existed in ontology ");
mHelper.close();
return " Unexpected Error : Human information is made just before, but it's already existed in ontology ";
}
else
{
informInd = informClass.createRDFIndividual(humanInformID);
//making relationship : Human - Information
OWLObjectProperty hasInform = owlModel.getOWLObjectProperty("hasHumanInformation");
humanInd.addPropertyValue(hasInform, informInd);
}
//���� ���� individual�� ����� ������� ���״�.
//ONS���� ���� �����´�
//Accessing ONS
String onsURL = "dns://[2002:8ff8:6a87::8ff8:6a87]";
String onsHost = getONSHostName(vacantEPC);
JSONObject onsReturn = ONSHelper.getNAPTRFromONS(onsURL, onsHost);
OWLDatatypeProperty acDT = owlModel.getOWLDatatypeProperty("AC");
//����Ʈ ����
humanInd.addPropertyValue(acDT, "Public");
if( onsReturn.isNull("epcis") == false )
{
wrappingEPCIS(owlModel, humanInd, onsReturn);
}
//���� ģ���� ó���Ѵ�
//fetch friends
Connection<User> myFriendConnections = facebookClient.fetchConnection("me/friends", User.class);
List<User> myFriends = myFriendConnections.getData();
System.out.println("my Friends");
OWLObjectProperty hasFriend = owlModel.getOWLObjectProperty("hasFriend");
OWLObjectProperty hasLover = owlModel.getOWLObjectProperty("hasLover");
//ģ���� DB�� �ִٸ� object ID�� ã�� ģ���� �����Ѵ�.
for(int i = 0 ; i < myFriends.size() ; i ++ )
{
String tfid = myFriends.get(i).getId();
String friendEPC = mHelper.isHumanSavedInDB(tfid);
RDFIndividual friendInd = owlModel.getRDFIndividual(friendEPC);
if(friendInd == null )
{
System.out.println( " your friend " + myFriends.get(i).getName() + " is not a member of Lilliput, yet");
continue;
}
else
{
humanInd.addPropertyValue(hasFriend, friendInd);
System.out.println( myFriends.get(i).getName() + " is now friend in Lilliput");
}
}
NamedFacebookType lover = user.getSignificantOther();
if( lover != null )
{
String lover_fid = lover.getId();
String lover_EPC = mHelper.isHumanSavedInDB(lover_fid);
RDFIndividual loverInd = owlModel.getRDFIndividual(lover_EPC);
if(loverInd == null)
{
System.out.println( " your lover " + lover.getName() + " is not a memeber of Lilliput, yet ");
}
else
{
humanInd.addPropertyValue(hasLover, loverInd);
System.out.println( lover.getName() + " is now lover in Lilliput");
}
}
mHelper.close();
p.dispose();
System.out.println("Human is succesfully registrated");
return fid + " is succesfully registrated";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
}
public boolean wrappingEPCIS(OWLModel owlModel, RDFIndividual humanInd,
JSONObject onsReturn) {
// TODO Auto-generated method stub
try{
String epcURL;
epcURL = onsReturn.getString("epcis");
OWLNamedClass epcisClass = owlModel.getOWLNamedClass("EPCISService");
OWLObjectProperty hasService = owlModel.getOWLObjectProperty("hasService");
//���� �ν��Ͻ� �����
RDFIndividual epcInd = epcisClass.createRDFIndividual(null);
//����
humanInd.addPropertyValue(hasService, epcInd);
OWLDatatypeProperty urlInd = owlModel.getOWLDatatypeProperty("epcisURL");
epcInd.addPropertyValue(urlInd, epcURL);
return true;
}catch(JSONException e)
{
e.printStackTrace();
return false;
}
}
public static String getONSHostName(String humanEPC)
{
//String epc = "urn:epc:id:gid:1.1.1";
//<option optionKey="1" grammar="objectclass '.' generalmanager '.gid.id.onsepc.com'">
String[] splitted = humanEPC.split(":");
String contents = splitted[4];
String[] elements = contents.split("\\.");
@SuppressWarnings("unused")
String serial = elements[2];
String objectclass = elements[1];
String generalmanager = elements[0];
String onsHost = objectclass + "." + generalmanager + ".gid.id.onsepc.com";
return onsHost;
}
}