Java tutorial
/* * The MIT License (MIT) * * Copyright (c) 2016 Akash Kumar * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.skydeveloper.tikona; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import me.skydeveloper.tikona.helper.HttpManger; import me.skydeveloper.tikona.helper.HttpRequest; import me.skydeveloper.tikona.helper.SelfcareDOMParser; import me.skydeveloper.tikona.helper.TikonaDOMParser; import me.skydeveloper.tikona.helper.TikonaSessionParser; import me.skydeveloper.tikona.model.TikonaSession; import me.skydeveloper.tikona.model.TikonaUri; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import android.support.v4.app.Fragment; public class SessionTab extends Fragment { private static final String REQUEST_DATA = "http://1.254.254.254"; static TextView sessionStart; static TextView sessionDuration; static TextView sessionUsage; static TextView remainingUsage; private List<TikonaUri> tikonaUrl; private List<TikonaSession> tikonaSession; private ProgressDialog popupLoader; private SharedPreferences urlPreferences; private SharedPreferences.Editor urlEditor; private SharedPreferences sessionPreferences; private SharedPreferences.Editor sessionEditor; private SharedPreferences selfcarePreferences; private SharedPreferences.Editor selfcareEditor; private TextView lastCheckedAt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //return super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.session, container, false); popupLoader = new ProgressDialog(getActivity()); urlPreferences = getActivity().getSharedPreferences("url", Activity.MODE_PRIVATE); sessionPreferences = getActivity().getSharedPreferences("session", Activity.MODE_PRIVATE); selfcarePreferences = getActivity().getSharedPreferences("selfcare", Activity.MODE_PRIVATE); sessionStart = (TextView) view.findViewById(R.id.sessionStartValue); sessionDuration = (TextView) view.findViewById(R.id.sessionDurationValue); sessionUsage = (TextView) view.findViewById(R.id.sessionUsageValue); lastCheckedAt = (TextView) getActivity().findViewById(R.id.checkedAt); remainingUsage = (TextView) view.findViewById(R.id.remainigUsageValue); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getURLs(); } /** * Create Background task to get urlPreferences from http://1.254.254.254 */ public void getURLs() { if (HttpManger .isOnline((ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE))) { HttpRequest request = new HttpRequest(); request.setMethod("GET"); request.setUri(REQUEST_DATA); GetURLs getURLs = new GetURLs(); getURLs.execute(request); } else { Snackbar.make(getView(), "Your are not connected to wifi #1", Snackbar.LENGTH_LONG).show(); //Snackbar.make(getView().getView(), "Your are not connected to wifi #1", Snackbar.LENGTH_LONG).show(); } } /** * Checks if connected to Wifi/Data and create background task which calls HttpManager class */ public void fetchSessionDetails() { if (HttpManger .isOnline((ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE))) { String login_url = urlPreferences.getString("login_url", ""); Log.d("login_url", login_url); if (!login_url.isEmpty()) { HttpRequest request = new HttpRequest(); request.setMethod("GET"); request.setUri(login_url); GetSession getSession = new GetSession(); getSession.execute(request); } } else { Toast.makeText(getActivity(), "You are not connected to wifi #2", Toast.LENGTH_SHORT).show(); } } /** * Updates Session Details returned from TikonaSession */ protected void updateSessionDetails() { if (tikonaSession != null) { for (TikonaSession session : tikonaSession) { if (session.isLoggedIn()) { sessionStart.setText(session.getSessionStart()); sessionDuration.setText(session.getSessionDuration()); sessionUsage.setText(session.getSessionUsage()); long sessionStartMilli = 0; try { //TODO => Manage session when session is null error 100 - Logged in but button is not visible if (session.getSessionStart() != null) { Date sessionDateTime = new SimpleDateFormat("MM/dd/yyy HH:mm:ss", Locale.ENGLISH) .parse(session.getSessionStart()); sessionStartMilli = sessionDateTime.getTime(); } } catch (ParseException e) { e.printStackTrace(); } long currentTime = selfcarePreferences.getLong("lastCheckedAt", 0); /*SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d h:mm:ss", Locale.ENGLISH); String dateTime = null; try { Date date2 = dateFormat.parse(date.toString()); dateTime = dateFormat.format(date); } catch (ParseException e) { e.printStackTrace(); }*/ Date date = new Date(System.currentTimeMillis()); lastCheckedAt.setText(date.toString()); Log.d("timeTest", sessionStartMilli + ""); Log.d("timeTest", currentTime + ""); //Log.d("timeTest",currentTime + ""); if (sessionStartMilli > currentTime) { if (!selfcarePreferences.getString("username", "").equals("") && !selfcarePreferences.getString("password", "").equals("")) { remainingUsage.setText("Fetching details ..."); HttpRequest data = new HttpRequest(); data.setMethod("POST"); data.setUri("https://selfcare.tikona.in/EncryptData.do"); String username = selfcarePreferences.getString("username", ""); String password = selfcarePreferences.getString("password", ""); data.setParam("data", username + "~" + password); Selfcare selfcareData = new Selfcare(); selfcareData.execute(data); } else {// TextView remainingUsage = (TextView) getView().findViewById(R.id.remainigUsageValue); remainingUsage.setText(R.string.ltvd); //TODO => Uncomment this once selfcare login is fixed /*remainingUsage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), SelfcareLogin.class); startActivity(intent); } });*/ } } else {//If we already have selfcare data String balance = selfcarePreferences.getString("balance", "");//Already processed String current = sessionUsage.getText().toString().replace("MB", "").replace("GB", "") .replace("KB", "").replace("B", "").trim(); int remainingData = 0; if (current.length() >= 1 && !balance.equals("You are now on secondary policy")) { remainingData = Integer.parseInt(balance) - Integer.parseInt(current); if (remainingData > 0) { remainingUsage.setText(remainingData + " MB"); } else { remainingUsage.setText(R.string.secondaryPolicy); } } else { remainingUsage.setText(R.string.secondaryPolicy); } //FOR SCREENSHOT PURPOSES /*TextView test = (TextView) getActivity().findViewById(R.id.userid); test.setText("11XXXXXX"); TextView test2 = (TextView) getActivity().findViewById(R.id.name); test2.setText("Guest User");*/ } sessionEditor = sessionPreferences.edit(); sessionEditor.putString("sessionStart", session.getSessionStart()); sessionEditor.putString("sessionDuration", session.getSessionDuration()); sessionEditor.putString("sessionUsage", session.getSessionUsage()); sessionEditor.apply(); Snackbar.make(getView(), "Session details updated", Snackbar.LENGTH_LONG).show(); } else if (!session.isLogoutButtonVisibility()) { Toast.makeText(getActivity(), "Empty Response. This happens when logout button is not visible on login page. There is nothing can be done. :( ", Toast.LENGTH_LONG).show(); } else if (session.isCacheError()) { Toast.makeText(getActivity(), "Empty response. Happens randomly not my fault :) Try after some time", Toast.LENGTH_LONG).show(); //TODO => Extract method for updating selfcare easily } else { Toast.makeText(getActivity(), "You are not logged in. Redirecting to login page", Toast.LENGTH_LONG).show(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(REQUEST_DATA)); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getActivity(), "No Browser found", Toast.LENGTH_SHORT).show(); } } Log.d("Session Start => ", "" + session.getSessionStart()); Log.d("Session Duration => ", "" + session.getSessionDuration()); Log.d("Session Usage => ", "" + session.getSessionUsage()); Log.d("IsLoggedIn => ", "" + session.isLoggedIn()); Log.d("LogoutButtonStatus => ", "" + session.isLogoutButtonVisibility()); break;//TODO => Temporary solution to prevent multiple loops } } } /** * Updates Selfcare Data into View and SharedPreferences * * @param selfcareData Array of data from selfcare.tikona.in */ protected void updateSelfcareData(ArrayList<String> selfcareData) { if (selfcareData != null) { //Calculating Remaining Session Usage //TODO => Use regEx instead String balance = selfcareData.get(0).replace("MB", "").replace("GB", "").replace("KB", "") .replace("B", "").trim(); String current = sessionUsage.getText().toString().replace("MB", "").replace("GB", "").replace("KB", "") .replace("B", "").trim(); int remainingData = 0; if (current.length() > 1 && !balance.equals("You are now on secondary policy")) { remainingData = Integer.parseInt(balance) - Integer.parseInt(current); if (remainingData > 0) { remainingUsage.setText(remainingData + " MB"); } else { remainingUsage.setText(R.string.secondaryPolicy); } } else { remainingUsage.setText(selfcareData.get(0)); } selfcareEditor = selfcarePreferences.edit(); selfcareEditor.putLong("lastCheckedAt", System.currentTimeMillis()); selfcareEditor.putString("balance", balance); if (selfcareData.size() > 5) {//Regular User selfcareEditor.putString("totalOutstanding", selfcareData.get(1)); selfcareEditor.putString("lastBillAmount", selfcareData.get(2)); selfcareEditor.putString("lastBillDate", selfcareData.get(3)); selfcareEditor.putString("dueDate", selfcareData.get(4)); selfcareEditor.putString("lastPaymentAmount", selfcareData.get(5)); selfcareEditor.putString("lastPaymentDate", selfcareData.get(6)); selfcareEditor.putString("user_name", selfcareData.get(7)); } else {//New User selfcareEditor.putString("totalOutstanding", selfcareData.get(1)); selfcareEditor.putString("lastPaymentAmount", selfcareData.get(2)); selfcareEditor.putString("lastPaymentDate", selfcareData.get(3)); selfcareEditor.putString("user_name", selfcareData.get(4)); selfcareEditor.putString("lastBillAmount", "-"); selfcareEditor.putString("lastBillDate", "-"); selfcareEditor.putString("dueDate", "-"); } selfcareEditor.apply(); } else { remainingUsage.setText(R.string.loginErrorMsg); selfcareEditor = selfcarePreferences.edit(); selfcareEditor.clear(); selfcareEditor.apply(); Toast.makeText(getActivity(), "Username/Password is incorrect. Please try again", Toast.LENGTH_LONG) .show(); } } //BACKGROUND TASKS /** * Fetch Session URL */ private class GetURLs extends AsyncTask<HttpRequest, String, String> { @Override protected void onPreExecute() { popupLoader.setTitle("Please wait"); popupLoader.setMessage("Warming up..."); popupLoader.show(); popupLoader.setCancelable(false); } @Override protected String doInBackground(HttpRequest... params) { String response = HttpManger.makeRequest(params[0]); Log.d("resonsonse in ", response); if (response.length() > 2 && !response.equals("timeout")) { tikonaUrl = TikonaDOMParser.parseURL(response); String login_url = null; String status_url = null; String logout_url = null; for (TikonaUri url : tikonaUrl) { login_url = url.getLogin_url(); status_url = url.getStatus_url(); logout_url = url.getLogout_url(); } urlEditor = urlPreferences.edit(); urlEditor.putString("login_url", login_url); urlEditor.putString("status_url", status_url); urlEditor.putString("logout_url", logout_url); urlEditor.apply(); //return tikonaSession; return "200"; } else { return response; } } @Override protected void onPostExecute(String s) { popupLoader.hide(); Log.d("response", s); /*if (!s.equals("200")) { Toast.makeText(getActivity(), "HTTP Response Code " + s, Toast.LENGTH_SHORT).show(); }*/ if (s.equals("timeout")) { Toast.makeText(getActivity(), "You are not connected to Tikona Network", Toast.LENGTH_LONG).show(); } else { //Session fetch fetchSessionDetails(); } } } /** * Get Session Details */ private class GetSession extends AsyncTask<HttpRequest, String, List<TikonaSession>> { @Override protected void onPreExecute() { popupLoader.setTitle("Please wait.."); popupLoader.setMessage("Getting session details"); popupLoader.setCancelable(true); popupLoader.show(); } @Override protected List<TikonaSession> doInBackground(HttpRequest... params) { String currentSession = HttpManger.makeRequest(params[0]); Log.d("responseLoginURL", currentSession); String login_url = null; tikonaSession = TikonaSessionParser.getSession(currentSession); //GETTING REMAINING SESSION DATA USAGE & BILLING INFORMATION return tikonaSession; } @Override protected void onPostExecute(List<TikonaSession> session) { if (session == null || session.isEmpty()) { Toast.makeText(getActivity(), "Empty Response.", Toast.LENGTH_LONG).show(); } else { updateSessionDetails(); } popupLoader.hide(); } } /** * Get SelfcareData */ private class Selfcare extends AsyncTask<HttpRequest, String, ArrayList<String>> { @Override protected void onPreExecute() { super.onPreExecute(); popupLoader.setTitle("Please wait.."); popupLoader.setMessage("Getting Selfcare details"); popupLoader.setCancelable(false); popupLoader.show(); } @Override protected ArrayList<String> doInBackground(HttpRequest... params) { String encryptData = HttpManger.makeRequest(params[0]) + "\r\n"; Log.d("encryptData1", encryptData);//Todo => Its not logging anything find out why try { Log.d("encryptData2", URLEncoder.encode(encryptData, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Log.d("loginTest", selfcarePreferences.getString("username", "")); //Log.d("loginTest", sessionPreferences.getString("password", "")); HttpRequest request = new HttpRequest(); request.setMethod("POST"); request.setUri("https://selfcare.tikona.in/loginAction.do"); request.setParam("username", selfcarePreferences.getString("username", "")); request.setParam("password", selfcarePreferences.getString("password", "")); request.setParam("submitbutton", "");//Just for fail safe in this param become necessary request.setParam("data", encryptData); String selfcareResponse = HttpManger.makeRequest(request); Log.d("selfcareResponse", selfcareResponse); return SelfcareDOMParser.parse(selfcareResponse); } @Override protected void onPostExecute(ArrayList<String> s) { super.onPostExecute(s); updateSelfcareData(s); popupLoader.hide(); } } private class Logout extends AsyncTask<HttpRequest, String, String> { @Override protected void onPreExecute() { popupLoader.setTitle("Please wait.."); popupLoader.setMessage("Logging out current session"); popupLoader.show(); popupLoader.setCancelable(true); } @Override protected String doInBackground(HttpRequest... params) { return HttpManger.makeRequest(params[0]); } @Override protected void onPostExecute(String s) { Log.d("response", s); if (s.length() > 2 && !s.isEmpty()) { //Session is logged out Toast.makeText(getActivity(), "Your session has been logged out", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "Error while logout.. Please try again later", Toast.LENGTH_LONG) .show(); } popupLoader.hide(); } } }