Java: Serializing beginner problem :-( - java

I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!

The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}

If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.

On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.

in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}

I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.

Related

How to make ObjectInputStream read all objects from file in java?

I have a file which is storing objects and I have a *getAll() method which needs to return the List<Secretary>. But, I only see single object being printed in console.
I searched for the problem and tried 3 ways but it did not work.
The insert method for inserting object in file is:
#Override
public Secretary insert(Secretary t) {
try {
System.out.println("insert called");
FileOutputStream file = new FileOutputStream
(filename,true);
ObjectOutputStream out = new ObjectOutputStream
(file);
Method for serialization of object
out.writeObject(t);
out.close();
file.close();
return t;
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I have declared append mode as true as, my file was being replaced by new object when saving.
So,i need to fetch all object from file and need to assign to a list.I tried:
public class SecretaryDaoImpl implements SecretaryDAO{
private String filename = "secretary.txt";
private Secretary sec=null;
#Override
public List<Secretary> getAll() {
//Method 1
try {
Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
List<Secretary> secList=new ArrayList<>();
Method for deserialization of object
secList.add((Secretary)in.readObject());
in.close();
file.close();
System.out.println("Object has been deserialized\n"
+ "Data after Deserialization.");
System.out.println("secList is" +secList);
return secList;
}
catch (IOException ex) {
System.out.println("Secreatary file not found");
return null;
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
//Method 2
List<Secretary> secList=new ArrayList<>();
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream(filename);
objectinputstream = new ObjectInputStream(streamIn);
List<Secretary> readCase = (List<Secretary>) objectinputstream.readObject();
for(Secretary s:readCase){
secList.add(s);
}
System.out.println("seclist is" + secList);
return secList;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
try {
objectinputstream.close();
} catch (IOException ex) {
Logger.getLogger(SecretaryDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Method 3
try{
File file = new File(filename);
List<Secretary> list = new ArrayList<>();
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
list.add((Secretary) ois.readObject());
}
}
System.out.println("getall is"+list);
}
catch(Exception e){
}
return null;
}
}
I have commented out my code but here while posting in stackoverflow I have uncommented all the codes.
My Secretary.java is :
package com.npsc.entity;
import java.io.Serializable;
/**
*
* #author Ashwin
*/
public class Secretary implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
private int id;
private String userName;
private String password;
private Branch branch;
public String getUserName() {
return userName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Secretary(String userName, String password) {
this.userName = userName;
this.password = password;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
#Override
public String toString() {
return "Secretary{" + "id=" + id + ", userName=" + userName + ", password=" + password + ", branch=" + branch + '}';
}
}
While performing insert operation,my txt file saving objects is:
But,I am unable to read all the object and add in list.Where I am facing the problem?
You will need to store in the file, the number of Secretary objects to read back. You can then determine how many entities to read, and thus repopulate your list.
Something like:
List<Secretary> list;
private void persistList(ObjectOutputStream out) {
out.writeInt(list.size());
for (Secretary sec : list) {
out.writeObject(sec);
}
}
And then to read:
private List<Secretary> readFromStream(ObjectInputStream in) {
int numObjects = in.readInt();
List<Secretary> result = new ArrayList<>(numObjects);
for (int i = 0; i < numObjects; i++) {
result.add((Secretary)in.readObject());
}
return result;
}
This is just a sketch of the technique (and ignores error handling, stream opening/closing etc.); the main thing is to integrate the idea of recording the size of the list, then reading that many Secretaries into your existing code.
Write a List<Secretary> to file and read same back, then you will have all.
write (Secretary s) {
read List<Secretary> currentList ;
currentList.add(s)
write List<Secretary>
}

Writing and Reading to/from a file Objects stored in ArrayList

This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" +persons.size()+ "' Object to Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (Person) ois.readObject();
persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" +persons.size()+ "' Object from Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
public Person(String n, String s, String m, String t){
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}

Another serialization issue

I'm stuck trying to deserialize a list of Scores. I spent my entire day searching here but couldn't find a solution.. My code looks something like this:
public class Score implements Comparable<Score>, Serializable {
private String name;
private int score;
// .......
}
public class MySortedList<T> extends...implements...,Serializable {
private ArrayList<T> list;
// ....
}
public class ScoreManager {
private final String FILEPATH;
private final String FILENAME = "highscores.ser";
private MySortedList<Score> scoreList;
public ScoreManager() {
File workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
if ((scoreList = loadScores()) == null) {
scoreList = new MySortedList<Score>();
}
}
public void addScore(Score score) {
scoreList.add(score);
saveScores();
}
public MySortedList<Score> getScoreList() {
return scoreList;
}
private void saveScores() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(scoreList);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MySortedList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MySortedList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The loadScores() method returns just an empty MySortedList everytime.
However program succesfully creates the highscores.ser file in the correct place and I have absolutely no errors. Score objects are added correctly to the MySortedList object.
Any ideas? Perhaps worth mentioning that this is a part of a bigger program made in Swing. the methods in the ScoreManager class is called when the player dies
only if it can help, this code is working for me:
class Score implements Comparable<Score>, Serializable{
private int point;
public Score(int point) {
this.point = point;
}
public int getPoint(){
return point;
}
#Override
public int compareTo(Score o) {
if (o.getPoint() == this.getPoint())
return 0;
return this.point < o.getPoint() ? - 1 : 1;
}
public String toString() {
return "points: " + point;
}
}
class MyList<T> implements Serializable {
private ArrayList<T> list = new ArrayList<>();
public void add(T e){
list.add(e);
}
public void show() {
System.out.println(list);
}
}
public class Main {
File workingFolder;
String FILEPATH;
private final String FILENAME = "highscores.ser";
MyList<Score> list = new MyList<>();
public static void main(String[] args) {
Main main = new Main();
main.createFolder();
main.addItems();
main.saveScores();
MyList<Score> tempList = main.loadScores();
tempList.show();
main.addMoreItems();
main.saveScores();
tempList = main.loadScores();
tempList.show();
}
private void addItems() {
Score sc = new Score(10);
list.add(sc);
}
private void addMoreItems() {
Score sc1 = new Score(20);
list.add(sc1);
Score sc2 = new Score(30);
list.add(sc2);
}
private void createFolder() {
workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
}
private void saveScores() {
System.out.println("before save: " + list);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(list);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MyList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MyList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

JAVA Send an object to all clients

I try to make a chat. When a client send a message to the server, it is working, the server receives the message. So I would like to send this message all the clients. I tried many things but they are not working... Just the client which sends the message, it receives this message
Can You help me please ?
Thanks in advance
PS : Sorry for my bad English
This is the result in the console :
http://i.stack.imgur.com/VS2wf.png
MainClient
public class MainClient {
/**
* #param args the command line arguments
* #throws java.io.IOException
* #throws java.lang.ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean stop = false;
Socket socket;
Scanner nickScan;
String nick;
socket = new Socket(InetAddress.getLocalHost(), 2009);
System.out.println("Hi, what is your name ?");
nickScan = new Scanner(System.in);
nick = nickScan.nextLine();
User u = new User(nick, false, false, true);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(u);
EmissionThread e = new EmissionThread(u, socket);
e.start();
while(!stop){
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
}
//socket.close();//On ferme les connexions
}
}
MainServer
public class MainServer extends Thread {
public static void main(String[] args) throws InterruptedException, IOException {
// TODO code application logic here
ConnectionThread c = new ConnectionThread();
c.start();
}
}
ConnectionThread
public class ConnectionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
Session s = new Session("#upec");
public ConnectionThread() throws IOException {
this.socketserver = new ServerSocket(2009);
}
public ServerSocket getSocketserver() {
return socketserver;
}
#Override
public void run() {
while (!stop) {
try {
socketduserveur = socketserver.accept(); //On accepte les connexions
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
User u = (User)ois.readObject();
System.out.println(u.getNick() + " c'est connecté");
s.addUserList(u);
if (s.listAlone()) {
System.out.println("Vous etes admin");
u.setAdmin(true);
}
ReceptionThread r = new ReceptionThread(socketduserveur);
r.start();
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
ReceptionThread
public class ReceptionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
public ReceptionThread(Socket socketduserveur) {
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(ReceptionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
EmissionThread
public class EmissionThread extends Thread {
private User u;
private Socket socketduserveur;
private static final boolean stop = false;
public EmissionThread(User u, Socket socketduserveur) {
this.u = u;
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
Scanner msgScan;
String msg;
msgScan = new Scanner(System.in);
msg = msgScan.nextLine();
Message m = new Message(u.getNick(), msg);
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException ex) {
Logger.getLogger(EmissionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Message
public class Message implements Serializable {
private String nick;
private String msg;
public Message(String nick, String msg) {
this.nick = nick;
this.msg = msg;
}
}
Session
public class Session implements Serializable {
private String name;
private ArrayList<String> listSession = new ArrayList();
private ArrayList<User> listUser = new ArrayList();
public Session(String name) {
this.name = name;
}
public void addSession(String name){
listSession.add(name);
}
public void deleteSession(String name){
for(String s : listSession){
if(name.equals(s)){
listSession.remove(s);
}
}
}
public boolean existSession(String name){
for(String s : listSession){
if(name.equals(s)){
return true;
}
}
return false;
}
public void addUserList(User u){
listUser.add(u);
}
public boolean listAlone(){
int compteur = 0;
for(User u : listUser){
compteur++;
}
return compteur == 1;
}
}
User
public class User implements Serializable {
private String nick;
private final Session session;
private boolean admin, moderator, voice;
public User(String nick, boolean admin, boolean moderator, boolean voice) {
this.nick = nick;
this.admin = admin;
this.moderator = moderator;
this.voice = voice;
this.session = new Session("#upec");
}
}
You can use websockets on tomcat for this. If you download tomcat there is a chat app already built as an example

Get information about a page using facebook4j

Is there a possibility to get the String of the page's information in the about section?
An Example: https://www.facebook.com/FacebookDevelopers
Here is the info: "Build, grow, and monetize your app with Facebook. https://developers.facebook.com/"
I found out that the Facebook graph api supports this by the Field about on a Page.
Thanks for help in advance!
Best regards,
Dominic
you can below snippet code for getting facebook page information in java :
private static final String FacebookURL_PAGES = "me/accounts?fields=access_token,category,id,perms,picture{url},can_post,is_published,cover,fan_count,is_verified,can_checkin,global_brand_page_name,link,country_page_likes,is_always_open,is_community_page,new_like_count,overall_star_rating,name";
public List<FacebookPageModel> getPages(String accessToken) throws FacebookException, JSONException {
JSONObject posts = getBatch(accessToken,FacebookURL_PAGES);
Gson g =new Gson();
System.out.println(posts);
JSONArray postsData = posts.getJSONArray("data");
System.out.println(g.toJson(postsData));
return getPageList(postsData);
}
private JSONObject getBatch(String accessToken, String url) throws FacebookException{
Gson g = new Gson();
Facebook facebook = getFacebook(accessToken);
BatchRequests<BatchRequest> batch = new BatchRequests<BatchRequest>();
batch.add(new BatchRequest(RequestMethod.GET, url));
List<BatchResponse> results = facebook.executeBatch(batch);
BatchResponse result2 = results.get(0);
System.out.println(g.toJson(result2.asJSONObject()));
return result2.asJSONObject();
}
private Facebook getFacebook(String accessToken){
if(accessToken == null){
System.out.println("Access Token null while request for Facebook Instance !");
return null;
}
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId(appId, appSecret);
facebook.setOAuthPermissions("email,publish_stream, publish_actions");
facebook.setOAuthAccessToken(new AccessToken(accessToken, null));
return facebook;
}
private List<FacebookPageModel> getPageList(JSONArray pagesData) throws JSONException{
Gson g = new Gson();
List<FacebookPageModel> pages = new ArrayList<FacebookPageModel>();
SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = null;
for (int i = 0; i < pagesData.length(); i++) {
FacebookPageModel obj = new FacebookPageModel();
JSONObject page = pagesData.getJSONObject(i);
System.out.println(g.toJson(page));
try{
obj.setAccessToken(page.getString("access_token"));
}catch(Exception ee){
obj.setAccessToken(null);
}
try{
obj.setCategory(page.getString("category"));
}catch(Exception ee){
obj.setCategory(null);
}
try{
obj.setId(page.getString("id"));
}catch(Exception ee){
obj.setId(null);
}
try{
obj.setName(page.getString("name"));
}catch(Exception ee){
obj.setName(null);
}
try{
obj.setCanPost(page.getBoolean("can_post"));
}catch(Exception ee){
obj.setCanPost(false);
}
try{
JSONObject picture = page.getJSONObject("picture");
JSONObject pictureData = picture.getJSONObject("data");
obj.setPageProfilePic(pictureData.getString("url"));
}catch(Exception ee){
obj.setCanPost(false);
}
try{
obj.setPublished(page.getBoolean("is_published"));
}catch(Exception ee){
obj.setPublished(false);
}
try{
obj.setFanCount(page.getLong("fan_count"));
}catch(Exception ee){
obj.setFanCount(0L);
}
try{
obj.setVerified(page.getBoolean("is_verified"));
}catch(Exception ee){
obj.setVerified(false);
}
try{
obj.setCanCheckin(page.getBoolean("can_checkin"));
}catch(Exception ee){
obj.setCanCheckin(false);
}
try{
obj.setGlobalBranPageName(page.getString("global_brand_page_name"));
}catch(Exception ee){
obj.setGlobalBranPageName(null);
}
try{
obj.setPageLink(page.getString("link"));
}catch(Exception ee){
obj.setPageLink(null);
}
try{
obj.setNewLikeCount(page.getLong("new_like_count"));
}catch(Exception ee){
obj.setNewLikeCount(0L);
}
try{
obj.setOverallStarRating(page.getLong("overall_star_rating"));
}catch(Exception ee){
obj.setOverallStarRating(0L);
}
try{
obj.setOverallStarRating(page.getLong("overall_star_rating"));
}catch(Exception ee){
obj.setOverallStarRating(0L);
}
pages.add(obj);
}
System.out.println(g.toJson(pages));
return pages;
}
public class FacebookPageModel {
//access_token
private String accessToken;
//name
private String name;
//id
private String id;
//category
private String category;
// can_post
private boolean canPost;
private String pageProfilePic;
// is_published
private boolean isPublished;
// fan_count
private long fanCount;
// is_verified
private boolean isVerified;
// can_checkin
private boolean canCheckin;
// global_brand_page_name
private String globalBranPageName;
// link
private String pageLink;
// new_like_count
private long newLikeCount;
// overall_star_rating
private long overallStarRating;
public boolean isCanPost() {
return canPost;
}
public void setCanPost(boolean canPost) {
this.canPost = canPost;
}
public String getPageProfilePic() {
return pageProfilePic;
}
public void setPageProfilePic(String pageProfilePic) {
this.pageProfilePic = pageProfilePic;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean isPublished() {
return isPublished;
}
public void setPublished(boolean isPublished) {
this.isPublished = isPublished;
}
public long getFanCount() {
return fanCount;
}
public void setFanCount(long fanCount) {
this.fanCount = fanCount;
}
public boolean isVerified() {
return isVerified;
}
public void setVerified(boolean isVerified) {
this.isVerified = isVerified;
}
public boolean isCanCheckin() {
return canCheckin;
}
public void setCanCheckin(boolean canCheckin) {
this.canCheckin = canCheckin;
}
public String getGlobalBranPageName() {
return globalBranPageName;
}
public void setGlobalBranPageName(String globalBranPageName) {
this.globalBranPageName = globalBranPageName;
}
public String getPageLink() {
return pageLink;
}
public void setPageLink(String pageLink) {
this.pageLink = pageLink;
}
public long getNewLikeCount() {
return newLikeCount;
}
public void setNewLikeCount(long newLikeCount) {
this.newLikeCount = newLikeCount;
}
public long getOverallStarRating() {
return overallStarRating;
}
public void setOverallStarRating(long overallStarRating) {
this.overallStarRating = overallStarRating;
}
}

Categories

Resources