Browse Source

More ParseTask stuff

pull/24/head
Ezerous 8 years ago
parent
commit
dc0506a5ac
  1. 66
      app/src/main/java/gr/thmmy/mthmmy/activities/board/BoardActivity.java
  2. 60
      app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java
  3. 14
      app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java
  4. 7
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  5. 4
      app/src/main/java/gr/thmmy/mthmmy/session/SessionManager.java
  6. 25
      app/src/main/java/gr/thmmy/mthmmy/utils/ParseTask.java

66
app/src/main/java/gr/thmmy/mthmmy/activities/board/BoardActivity.java

@ -13,7 +13,6 @@ import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
@ -21,17 +20,15 @@ import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Objects;
import javax.net.ssl.SSLHandshakeException;
import gr.thmmy.mthmmy.R;
import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Board;
import gr.thmmy.mthmmy.model.Bookmark;
import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.model.Topic;
import gr.thmmy.mthmmy.utils.ParseTask;
import gr.thmmy.mthmmy.utils.exceptions.ParseException;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMoreListener {
@ -176,47 +173,15 @@ public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMo
* <p>BoardTask's {@link AsyncTask#execute execute} method needs a boards's url as String
* parameter!</p>
*/
private class BoardTask extends AsyncTask<String, Void, Void> {
private class BoardTask extends ParseTask {
@Override
protected void onPreExecute() {
if (!isLoadingMore) progressBar.setVisibility(ProgressBar.VISIBLE);
if (newTopicFAB.getVisibility() != View.GONE) newTopicFAB.setEnabled(false);
}
@Override
protected Void doInBackground(String... boardUrl) {
Request request = new Request.Builder()
.url(boardUrl[0])
.build();
try {
Response response = client.newCall(request).execute();
parseBoard(Jsoup.parse(response.body().string()));
} catch (SSLHandshakeException e) {
Timber.w("Certificate problem (please switch to unsafe connection).");
} catch (Exception e) {
Timber.e(e, "Exception");
}
return null;
}
@Override
protected void onPostExecute(Void voids) {
if (boardTitle == null || Objects.equals(boardTitle, "")
|| !Objects.equals(boardTitle, parsedTitle)) {
boardTitle = parsedTitle;
toolbar.setTitle(boardTitle);
thisPageBookmark = new Bookmark(boardTitle, ThmmyPage.getBoardId(boardUrl));
}
//Parse was successful
++pagesLoaded;
if (newTopicFAB.getVisibility() != View.GONE) newTopicFAB.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
boardAdapter.notifyDataSetChanged();
isLoadingMore = false;
}
private void parseBoard(Document boardPage) {
@Override //TODO should throw ParseException
public void parse(Document boardPage) throws ParseException {
parsedTitle = boardPage.select("div.nav a.nav").last().text();
//Removes loading item
@ -320,5 +285,26 @@ public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMo
}
}
}
@Override
protected void postParsing(ResultCode result) {
//TODO if (result == ResultCode.SUCCESS)...
if (boardTitle == null || Objects.equals(boardTitle, "")
|| !Objects.equals(boardTitle, parsedTitle)) {
boardTitle = parsedTitle;
toolbar.setTitle(boardTitle);
thisPageBookmark = new Bookmark(boardTitle, ThmmyPage.getBoardId(boardUrl));
}
//Parse was successful
++pagesLoaded;
if (newTopicFAB.getVisibility() != View.GONE) newTopicFAB.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
boardAdapter.notifyDataSetChanged();
isLoadingMore = false;
}
}
}

60
app/src/main/java/gr/thmmy/mthmmy/activities/main/forum/ForumFragment.java

@ -10,16 +10,13 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@ -29,12 +26,11 @@ import gr.thmmy.mthmmy.base.BaseFragment;
import gr.thmmy.mthmmy.model.Board;
import gr.thmmy.mthmmy.model.Category;
import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.ParseTask;
import gr.thmmy.mthmmy.utils.exceptions.ParseException;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
/**
@ -153,9 +149,8 @@ public class ForumFragment extends BaseFragment
//---------------------------------------ASYNC TASK-----------------------------------
private class ForumTask extends AsyncTask<Void, Void, Integer> {
private class ForumTask extends ParseTask {
private HttpUrl forumUrl = SessionManager.forumUrl; //may change upon collapse/expand
private Document document;
private final List<Category> fetchedCategories;
@ -167,43 +162,16 @@ public class ForumFragment extends BaseFragment
progressBar.setVisibility(ProgressBar.VISIBLE);
}
protected Integer doInBackground(Void... voids) {
Request request = new Request.Builder()
@Override
protected Request prepareRequest(String... params) {
return new Request.Builder()
.url(forumUrl)
.build();
try {
Response response = client.newCall(request).execute();
document = Jsoup.parse(response.body().string());
parse(document);
categories.clear();
categories.addAll(fetchedCategories);
fetchedCategories.clear();
return 0;
} catch (ParseException e) {
Timber.e(e, "ParseException");
return 1;
} catch (IOException e) {
Timber.i(e, "Network Error");
return 2;
} catch (Exception e) {
Timber.e(e, "Exception");
return 3;
}
}
protected void onPostExecute(Integer result) {
if (result == 0)
forumAdapter.notifyParentDataSetChanged(false);
else if (result == 2)
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(ProgressBar.INVISIBLE);
}
private void parse(Document document) throws ParseException {
@Override
public void parse(Document document) throws ParseException {
Elements categoryBlocks = document.select(".tborder:not([style])>table[cellpadding=5]");
if (categoryBlocks.size() != 0) {
for(Element categoryBlock: categoryBlocks)
@ -229,9 +197,21 @@ public class ForumFragment extends BaseFragment
}
else
throw new ParseException("Parsing failed");
categories.clear();
categories.addAll(fetchedCategories);
fetchedCategories.clear();
}
@Override
protected void postParsing(ParseTask.ResultCode result) {
if (result == ResultCode.SUCCESS)
forumAdapter.notifyParentDataSetChanged(false);
progressBar.setVisibility(ProgressBar.INVISIBLE);
}
public void setUrl(String string)
public void setUrl(String string) //TODO delete and simplify e.g. in prepareRequest possible?
{
forumUrl = HttpUrl.parse(string);
}

14
app/src/main/java/gr/thmmy/mthmmy/activities/main/recent/RecentFragment.java

@ -10,7 +10,6 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
@ -28,7 +27,6 @@ import gr.thmmy.mthmmy.utils.CustomRecyclerView;
import gr.thmmy.mthmmy.utils.ParseTask;
import gr.thmmy.mthmmy.utils.exceptions.ParseException;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.Request;
import timber.log.Timber;
@ -143,13 +141,6 @@ public class RecentFragment extends BaseFragment {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
@Override
protected Request prepareRequest(String... strings) {
return new Request.Builder()
.url(strings[0])
.build();
}
@Override
public void parse(Document document) throws ParseException
{
@ -187,12 +178,9 @@ public class RecentFragment extends BaseFragment {
@Override
protected void onPostExecute(ParseTask.ResultCode result) {
protected void postParsing(ParseTask.ResultCode result) {
if (result == ResultCode.SUCCESS)
recentAdapter.notifyDataSetChanged();
else if (result == ResultCode.NETWORK_ERROR)
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show(); //Fixme, sometimes activity isn't ready
progressBar.setVisibility(ProgressBar.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);

7
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java

@ -49,7 +49,6 @@ import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.utils.ParseHelpers;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
@ -698,10 +697,10 @@ public class TopicActivity extends BaseActivity {
//subject = document.select("input[name=subject]").first().attr("value");
topic = document.select("input[name=topic]").first().attr("value");
} catch (IOException e) {
Timber.e("Post failed.", e);
Timber.e(e,"Post failed.");
return false;
} catch (Selector.SelectorParseException e) {
Timber.e("Post failed.", e);
Timber.e(e,"Post failed.");
return false;
}
@ -735,7 +734,7 @@ public class TopicActivity extends BaseActivity {
return true;
}
} catch (IOException e) {
Timber.e("Post failed.", e);
Timber.e(e,"Post failed.");
return false;
}
}

4
app/src/main/java/gr/thmmy/mthmmy/session/SessionManager.java

@ -317,7 +317,7 @@ public class SessionManager {
if (userName != null && !userName.isEmpty())
return userName;
Timber.e("ParseException", new ParseException("Parsing failed(username extraction)"));
Timber.e(new ParseException("Parsing failed(username extraction)"),"ParseException");
return "User"; //return a default username
}
@ -341,7 +341,7 @@ public class SessionManager {
if (link != null && !link.isEmpty())
return link;
}
Timber.e("ParseException", new ParseException("Parsing failed(logoutLink extraction)"));
Timber.e(new ParseException("Parsing failed(logoutLink extraction)"),"ParseException");
return "https://www.thmmy.gr/smf/index.php?action=logout"; //return a default link
}
//----------------------------------OTHER FUNCTIONS END-----------------------------------------

25
app/src/main/java/gr/thmmy/mthmmy/utils/ParseTask.java

@ -1,6 +1,7 @@
package gr.thmmy.mthmmy.utils;
import android.os.AsyncTask;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
@ -9,16 +10,30 @@ import java.io.IOException;
import gr.thmmy.mthmmy.base.BaseApplication;
import gr.thmmy.mthmmy.utils.exceptions.ParseException;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
/**
* An {@link AsyncTask} class to be inherited for asynchronous parsing.
* Do NOT override doInBackground() and onPostExecute directly.
* Default usage while executing is ParseTask.execute(urlToParse), however feel free to override
* and modify prepareRequest() as needed.
*/
public abstract class ParseTask extends AsyncTask<String, Void, ParseTask.ResultCode> {
protected enum ResultCode {
SUCCESS, PARSING_ERROR, NETWORK_ERROR, OTHER_ERROR
}
protected abstract void parse (Document document) throws ParseException;
protected abstract void postParsing (ParseTask.ResultCode result); //ResultCode.NETWORK_ERROR is handled automatically
protected Request prepareRequest(String... params) {
return new Request.Builder()
.url(params[0])
.build();
}
@Override
protected ResultCode doInBackground(String... params) {
Request request = prepareRequest(params);
@ -42,7 +57,11 @@ public abstract class ParseTask extends AsyncTask<String, Void, ParseTask.Result
}
}
protected abstract Request prepareRequest(String... params);
protected abstract void parse (Document document) throws ParseException;
@Override
protected void onPostExecute(ParseTask.ResultCode result) {
if (result == ResultCode.NETWORK_ERROR)
Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "Network error", Toast.LENGTH_SHORT).show();
postParsing(result);
}
}

Loading…
Cancel
Save