Get information about a page using facebook4j - java

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;
}
}

Related

How to upload a new version of a file by using WebScript?

I have a simple Spring application (front-end application) that loads files into the Alfresco repository. If the file already exists, its new version is not created.
Repository web script is presented below:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC =
"{http://www.firm.com/model/content/1.0}someDoc";
private static final String FIRM_DOC_FOLDER =
"workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FirmFile firmFile;
private FileFolderService fileFolderService;
private ContentService contentService;
protected Map<String, Object> executeImpl(WebScriptRequest req,
Status status) {
retrievePostRequestParams(req);
writeContent();
return null;
}
private void retrievePostRequestParams(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
String fieldValue = field.getValue();
if(fieldName.equalsIgnoreCase("firm_file")
&& field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
firmFile = new FirmFile(fileName, fileContent,
fileMimetype, FIRM_DOC);
}
}
}
private void writeContent() {
try {
NodeRef parentNodeRef = new NodeRef(FIRM_DOC_FOLDER);
NodeRef fileNodeRef = createFileNode(parentNodeRef,
firmFile.getFileName());
ContentWriter contentWriter = contentService.getWriter(fileNodeRef,
ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode,
fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
}
How to create a new version of a file with the same name by using Java-backed WebScript?
Does this solution correct?
Check if the file exists by using Lucene search: TYPE:"firm:doc" AND #cm\:name:contract.png; (for example) If exists, increment the property cm:versionLabel and create a new version of Node with all the properties (Actually, need to iterate through all the ResultSet and find NodeRef with max value of cm:versionLabel then increment it and create a new Node). Is there more elegant solution?
The solution can be represented as follows:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC = "{http://www.firm.com/model/content/1.0}doc";
private static final String FIRM_DOC_FOLDER = "workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FileFolderService fileFolderService;
private ContentService contentService;
private NodeService nodeService;
private SearchService searchService;
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
processUpload(req);
return null;
}
private void writeContent(NodeRef node, FirmFile firmFile) {
try {
ContentWriter contentWriter = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef checkIfNodeExists(String fileName) {
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE/*LANGUAGE_FTS_ALFRESCO*/,
"TYPE:\"firm:doc\" AND #cm\\:name:" + fileName.replaceAll(" ", "\\ ")+ "");
int len = resultSet.length();
if(len == 0) {
return null;
}
NodeRef node = resultSet.getNodeRef(0);
return node;
}
private NodeRef createNewNode(FirmFile firmFile) {
NodeRef parent = new NodeRef(FIRM_DOC_FOLDER);
NodeRef node = createFileNode(parent, firmFile.getFileName());
return node;
}
private void processUpload(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
if(fieldName.equalsIgnoreCase("firm_file") && field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
NodeRef node = checkIfNodeExists(fileName);
// POJO
FirmFile firm = new FirmFile(fileName, fileContent, fileMimetype, FIRM_DOC);
if(node == null) {
node = createNewNode(firmFile);
}
writeContent(node, firmFile);
}
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode, fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public NodeService getNodeService() {
return nodeService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public SearchService getSearchService() {
return searchService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
The content model must have a mandatory aspect cm:versionable:
<mandatory-aspects>
<aspect>cm:versionable</aspect>
</mandatory-aspects>

Parsion JSON String into JSONOBJECT in android [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Using GSON to parse a JSON with dynamic "key" and "value" in android
(2 answers)
Closed 5 years ago.
This is my JsonResponse , and since its not in array i am facing some difficulties , can any one help me out ? in android
{
"errorno": "0",
"responsemsg": "Login Success.",
"busid": "1234",
"returnmobileno": "1234567890"
}
try this
try {
JSONObject lJsonObject = new JSONObject(response);
String errorno = lJsonObject .getString("errorno");
String responsemsg = lJsonObject .getString("responsemsg");
String busid = response.lJsonObject ("busid");
String returnmobileno = lJsonObject .getString("returnmobileno");
} catch (JSONException e) {
e.printStackTrace();
}
Try this,
try {
String errorno = response.getString("errorno");
String responsemsg = response.getString("responsemsg");
String busid = response.getString("busid");
String returnmobileno = response.getString("returnmobileno");
Log.d(TAG, "errorno:" + errorno+" responsemsg:"+responsemsg+" busid:"+busid+" returnmobileno:"+returnmobileno);
} catch (JSONException e) {
e.printStackTrace();
}
use below code to pass your strong
serverData = gson.fromJson(response, ServerData.class);
in build.gradle -> dependencies
// retrofit, gson
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
public class ApiClient {
public static final String SERVER_BASE_URL = "http://example.com/abc/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(SERVER_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
#POST("appServices/getData.php")
#FormUrlEncoded
Call<ResponseBody> getAllDataJSONFromServer(#Field("vcode") String vcode);
}
public class ServerData implements Parcelable {
public static final Creator<ServerData> CREATOR = new Creator<ServerData>() {
#Override
public ServerData createFromParcel(Parcel in) {
return new ServerData(in);
}
#Override
public ServerData[] newArray(int size) {
return new ServerData[size];
}
};
private static final int VERSION = 1;
#SerializedName("errorno")
private String errorno;
#SerializedName(responsemsg)
private String responsemsg;
#SerializedName("busid")
private String busid;
#SerializedName("returnmobileno")
private String returnmobileno;
private void readFromParcel(Parcel in) {
if (in.readInt() == VERSION) {
errorno = in.readString();
responsemsg = in.readString();
busid = in.readString();
returnmobileno = in.readString();
}
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(VERSION);
parcel.writeString(errorno);
parcel.writeString(responsemsg);
parcel.writeString(busid);
parcel.writeString(returnmobileno);
}
#Override
public int describeContents() {
return 0;
}
public String getErrorno() {
return errorno;
}
public void setErrorno(String errorno) {
this.errorno = errorno;
}
public String getResponsemsg() {
return responsemsg;
}
public void setResponsemsg(String responsemsg) {
this.responsemsg = responsemsg;
}
public String getBusid() {
return busid;
}
public void setBusid(String busid) {
this.busid = busid;
}
public String getReturnmobileno() {
return returnmobileno;
}
public void setReturnmobileno(String returnmobileno) {
this.returnmobileno = returnmobileno;
}
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
// get and save all data from server
Call<ResponseBody> call = apiService.getAllDataJSONFromServer(local_vcode, local_cvcode, pckgName);
call.enqueue(new Callback<ResponseBody>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responsebody) {
try {
String response = responsebody.body().string();
serverData = gson.fromJson(response, ServerData.class); // this will fetch data to model class ServerData
if (serverData != null) {
// do the rest here...
String vcode = serverData.getVcode();
Log.e("~~~ vode = ", vcode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
progressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
try {
t.printStackTrace();
progressDialog.dismiss();
} catch (Exception ignored) {
}
}
});

How can i add a search bar in google maps v2 with a) suggestions b)drop down menu

I am building a taxi app similar to Uber.. I am using Android Studio and implementing code in Java. Java servlets and jsps for the server side with My sql as the DB.
Any links or code with my mentioned requirement would be of great help.
I want a search bar with suggestions with a drop down menu of pickup and drop off locations like the one in Uber app.?
Thanks in advance.
Create new activity and get input from user or use static input in order to query from google for nearby places
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/textsearch/json?");
sb.append("query=" + "Your input OR user input";
sb.append("&key=You Api key here");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
and create a PlacesTask class
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
And then create Paresetask
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlacesJSONParser placeJsonParser = new PlacesJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
if (customSearch) {
if (list.size() == 0) {
placesList.setVisibility(View.GONE);
error_text.setVisibility(View.VISIBLE);
error_text.setTextColor(getResources().getColor(R.color.error_message_color));
} else {
placesList.setVisibility(View.VISIBLE);
error_text.setVisibility(View.GONE);
}
mPlaceArrayList = new ArrayList<>();
mAdapter = new PlaceListAdapter(NearByPlaces.this, mPlaceArrayList, true);
placesList.setAdapter(mAdapter);
}
for (int i = 0; i < list.size(); i++) {
mNearByPlace = new NearByPlace();
HashMap<String, String> hmPlace = list.get(i);
mNearByPlace.setLatitude(hmPlace.get("lat"));
mNearByPlace.setLongitude(hmPlace.get("lng"));
mNearByPlace.setName(hmPlace.get("place_name"));
mNearByPlace.setVicinity(hmPlace.get("vicinity"));
mPlaceArrayList.add(mNearByPlace);
}
mAdapter.setPlaceArrayList(mPlaceArrayList);
}
}
and NearByPlace is
public class NearByPlace {
private String name;
private String address;
private String latitude;
private String longitude;
private String vicinity;
private String placeIcon;
public NearByPlace(){}
public String getPlaceIcon() {
return placeIcon;
}
public void setPlaceIcon(String placeIcon) {
this.placeIcon = placeIcon;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hope it will help you and you can resolve the minor errors in coz i copied and pasted code from one of my project..

Java Serialization not working how I expected

I am trying to serialize an ArrayList<Prescription> using an ObjectOutputStream
Here is the Prescription class:
import java.io.Serializable;
import java.util.Calendar;
public class Prescription implements Serializable {
private static final long serialVersionUID = 4432845389029948144L;
private String name;
private String dosage;
private int originalQuantity = 0;
private int quantityRemaining = 0;
private String prescribingPharmacy;
private long dateStarted = 0;
private boolean taken_AM = false;
private boolean taken_Noon = false;
private boolean taken_PM = false;
private boolean taken_Mon = false;
private boolean taken_Tue = false;
private boolean taken_Wed = false;
private boolean taken_Thu = false;
private boolean taken_Fri = false;
private boolean taken_Sat = false;
private boolean taken_Sun = false;
public Prescription(){
this.name = "Unknown";
}
public Prescription(String name, String dosage, int quantity, String pharmacy){
this.name = name;
this.dosage = dosage;
this.originalQuantity = quantity;
this.quantityRemaining = quantity;
this.prescribingPharmacy = pharmacy;
this.dateStarted = Calendar.getInstance().getTimeInMillis();
}
public void setTaken(boolean AM, boolean Noon, boolean PM){
this.taken_AM = AM;
this.taken_Noon = Noon;
this.taken_PM = PM;
}
public void setTaken(boolean Mon, boolean Tue, boolean Wed, boolean Thu,
boolean Fri, boolean Sat, boolean Sun){
this.taken_Mon = Mon;
this.taken_Tue = Tue;
this.taken_Wed = Wed;
this.taken_Thu = Thu;
this.taken_Fri = Fri;
this.taken_Sat = Sat;
this.taken_Sun = Sun;
}
public String getName(){
return this.name;
}
}
Yet, when I try to do this, I get a NotSerializableException on the Prescription class. This doesn't make any sense to me, as I am only using primitive data types and String.
Here is the function I am using to do the serialization:
public boolean saveToFile(){
try {
FileOutputStream fos = this.context.openFileOutput(LIST_SAVE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.pList);
oos.close();
} catch(FileNotFoundException e){
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
The code:
public static void main(String[] args) {
try {
List<Prescription> d = new ArrayList<Prescription>();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\temp\\Prescription.dat")));
d.add(new Prescription());
oos.writeObject(d);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
works without any exceptions with the class you posted, so there's something you're not telling us :-)

Java: Serializing beginner problem :-(

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.

Categories

Resources