Java tutorial
/* * Copyright (C) 2010 Koni * * This file is only usefull as part of WebSMS. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; If not, see <http://www.gnu.org/licenses/>. */ package com.rothconsulting.android.websms.connector.coopmobile; import java.net.HttpURLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.analytics.tracking.android.Fields; import com.google.analytics.tracking.android.GoogleAnalytics; import com.google.analytics.tracking.android.MapBuilder; import com.google.analytics.tracking.android.Tracker; import de.ub0r.android.websms.connector.common.Connector; import de.ub0r.android.websms.connector.common.ConnectorCommand; import de.ub0r.android.websms.connector.common.ConnectorSpec; import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec; import de.ub0r.android.websms.connector.common.Utils; import de.ub0r.android.websms.connector.common.Utils.HttpOptions; import de.ub0r.android.websms.connector.common.WebSMSException; /** * AsyncTask to manage IO to Coop Mobile API. * * @author koni */ public class ConnectorCoopMobile extends Connector { /** Tag for output. */ private static final String TAG = "Coop Mobile"; /** Dummy String */ private static final String DUMMY = "???"; /** Login URL with E-mail. */ private static final String URL_LOGIN = "https://coop.nth.ch/index/login"; /** SMS URL with E-Mail. */ private static final String URL_SENDSMS = "https://coop.nth.ch/smsbox/smsedit/lang/de"; /** SMS Credit */ private String SMS_CREDIT = DUMMY; /** HTTP User agent. */ private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0"; /** SMS Encoding */ private static final String ENCODING = "UTF-8"; /** Check whether this connector is bootstrapping. */ private static boolean inBootstrap = false; /** My Ad-ID */ private static final String AD_UNITID = "ca-app-pub-5619114666968507/9953800139"; /** My Analytics-ID */ private static final String ANALYTICS_ID = "UA-38114228-3"; private Tracker mGaTracker; private GoogleAnalytics mGaInstance; private void initAnalytics(final Context context) { // Get singleton. this.mGaInstance = GoogleAnalytics.getInstance(context); // To set the default tracker, use: // First get a tracker using a new property ID. Tracker newTracker = this.mGaInstance.getTracker(ANALYTICS_ID); // Then make newTracker the default tracker globally. this.mGaInstance.setDefaultTracker(newTracker); // Get default tracker. this.mGaTracker = this.mGaInstance.getDefaultTracker(); } /** * {@inheritDoc} */ @Override public final ConnectorSpec initSpec(final Context context) { final String name = context.getString(R.string.connector_coop_name); ConnectorSpec c = new ConnectorSpec(name); c.setAuthor(context.getString(R.string.connector_coop_author)); c.setBalance(null); c.setLimitLength(718); c.setAdUnitId(AD_UNITID); c.setCapabilities(ConnectorSpec.CAPABILITIES_BOOTSTRAP | ConnectorSpec.CAPABILITIES_UPDATE | ConnectorSpec.CAPABILITIES_SEND | ConnectorSpec.CAPABILITIES_PREFS); c.addSubConnector("sunrise", c.getName(), SubConnectorSpec.FEATURE_MULTIRECIPIENTS); return c; } /** * {@inheritDoc} */ @Override public final ConnectorSpec updateSpec(final Context context, final ConnectorSpec connectorSpec) { this.log("Start updateSpec"); final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); if (p.getBoolean(Preferences.PREFS_ENABLED, false)) { if (p.getString(Preferences.PREFS_USER, "").length() > 0 && p.getString(Preferences.PREFS_PASSWORD, "") // . .length() > 0) { connectorSpec.setReady(); } else { connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED); } } else { connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE); } this.log("End updateSpec"); return connectorSpec; } /** * {@inheritDoc} */ @Override protected final void doBootstrap(final Context context, final Intent intent) throws WebSMSException { this.log("Start doBootstrap"); if (inBootstrap && !this.SMS_CREDIT.equals(DUMMY)) { this.log("already in bootstrap: skip bootstrap"); return; } inBootstrap = true; final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); String username = p.getString(Preferences.PREFS_USER, ""); String password = p.getString(Preferences.PREFS_PASSWORD, ""); ArrayList<BasicNameValuePair> postParameter = new ArrayList<BasicNameValuePair>(); postParameter.add(new BasicNameValuePair("mail", username)); postParameter.add(new BasicNameValuePair("password", password)); this.sendData(URL_LOGIN, context, postParameter, false); this.log("End doBootstrap"); } /** * {@inheritDoc} */ @Override protected final void doUpdate(final Context context, final Intent intent) throws WebSMSException { this.log("Start doUpdate"); this.doBootstrap(context, intent); this.sendData(URL_SENDSMS, context, null, true); this.getSpec(context).setBalance(this.SMS_CREDIT); // Google analytics if (this.mGaTracker == null || this.mGaInstance == null) { this.initAnalytics(context); } // Google analytics if (this.mGaTracker != null) { this.mGaTracker.send( MapBuilder.createEvent(TAG, "doUpdate V3", "Balance: " + this.getSpec(context).getBalance(), 0L) .set(Fields.SESSION_CONTROL, "start").build()); } this.log("End doUpdate"); } /** * {@inheritDoc} */ @Override protected final void doSend(final Context context, final Intent intent) throws WebSMSException { this.log("Start doSend"); this.doBootstrap(context, intent); String char_counter = ""; String info_count = ""; String info_msg_0 = ""; String info_msg_1 = ""; String info_msg_2 = ""; String info_msg_3 = ""; String info_msg_4 = ""; String schedule_sms = "NORMAL"; DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy hh:mm"); String schedule_sms_time = formatter.format(new Date()); this.log("schedule_sms_time=" + schedule_sms_time); ConnectorCommand command = new ConnectorCommand(intent); // SMS Text String text = command.getText(); this.log("text.length()=" + text.length()); this.log("text=" + text); if (text != null) { if (text.length() <= 113) { info_count = "1"; char_counter = info_count + "/" + (113 - text.length()); info_msg_0 = text; } else if (text.length() > 113 && text.length() <= 259) { // 113+146 info_count = "2"; char_counter = info_count + "/" + (259 - text.length()); info_msg_0 = text.substring(0, 113); info_msg_1 = text.substring(113, text.length()); } else if (text.length() > 259 && text.length() <= 412) { // 259+153 info_count = "3"; char_counter = info_count + "/" + (412 - text.length()); info_msg_0 = text.substring(0, 113); info_msg_1 = text.substring(113, 259); info_msg_2 = text.substring(259, text.length()); } else if (text.length() > 412 && text.length() <= 565) { // 412+153 info_count = "4"; char_counter = info_count + "/" + (565 - text.length()); info_msg_0 = text.substring(0, 113); info_msg_1 = text.substring(113, 259); info_msg_2 = text.substring(259, 412); info_msg_3 = text.substring(412, text.length()); } else if (text.length() > 565) { // 565+153 = max. 718 info_count = "5"; char_counter = info_count + "/" + (718 - text.length()); info_msg_0 = text.substring(0, 113); info_msg_1 = text.substring(113, 259); info_msg_2 = text.substring(259, 412); info_msg_3 = text.substring(412, 565); info_msg_4 = text.substring(565, text.length()); } } this.log("char_counter=" + char_counter); this.log("info_count=" + info_count); // Building POST parameter ArrayList<BasicNameValuePair> postParameter = new ArrayList<BasicNameValuePair>(); postParameter.add(new BasicNameValuePair("char_counter", char_counter)); postParameter.add(new BasicNameValuePair("info_count", info_count)); postParameter.add(new BasicNameValuePair("info_msg_0", info_msg_0)); postParameter.add(new BasicNameValuePair("info_msg_1", info_msg_1)); postParameter.add(new BasicNameValuePair("info_msg_2", info_msg_2)); postParameter.add(new BasicNameValuePair("info_msg_3", info_msg_3)); postParameter.add(new BasicNameValuePair("info_msg_4", info_msg_4)); postParameter.add(new BasicNameValuePair("schedule_sms", schedule_sms)); postParameter.add(new BasicNameValuePair("schedule_sms_time", schedule_sms_time)); postParameter.add(new BasicNameValuePair("sms_text", text)); // SMS Recipients String[] to = command.getRecipients(); postParameter.add(new BasicNameValuePair("sendto[]", "")); // 1. leer int counter = 1; for (int i = 0; i < to.length; i++) { postParameter.add(new BasicNameValuePair("sendto[]", this.filterNumber(to[i]))); counter++; } if (counter % 2 != 0) { // wenn ungerade ein leerer hinzu postParameter.add(new BasicNameValuePair("sendto[]", "")); } this.log("to.length=" + to.length); this.log("to[0] =" + to[0]); this.log("postParameter = " + postParameter); // Google analytics if (this.mGaTracker == null || this.mGaInstance == null) { this.initAnalytics(context); } // Google analytics if (this.mGaTracker != null) { this.mGaTracker.send(MapBuilder.createEvent(TAG, "Send SMS V3", "sendData", 0L) .set(Fields.SESSION_CONTROL, "start").build()); } this.sendData(URL_SENDSMS, context, postParameter, true); this.log("End doSend"); } /** * Sending the SMS * * @param fullTargetURL * @param context * @param postParameter * @throws WebSMSException */ private void sendData(final String url, final Context context, final ArrayList<BasicNameValuePair> postParameter, final boolean parseHtml) throws WebSMSException { this.log("Start sendData"); try { this.log("URL: " + url); // send data this.log("prepare: getHttpClient(...)"); HttpOptions httpOptions = new HttpOptions(); httpOptions.url = url; httpOptions.userAgent = USER_AGENT; httpOptions.trustAll = true; this.log("UrlEncodedFormEntity()"); if (postParameter != null) { httpOptions.postData = new UrlEncodedFormEntity(postParameter, ENCODING); } this.log("send data: getHttpClient(...)"); HttpResponse response = Utils.getHttpClient(httpOptions); int respStatus = response.getStatusLine().getStatusCode(); this.log("response status=" + respStatus); this.log("response=\n" + response); if (respStatus != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + respStatus); } String htmlText = Utils.stream2str(response.getEntity().getContent()).trim(); if (htmlText == null || htmlText.length() == 0) { throw new WebSMSException(context, R.string.error_service); } this.log("----- Start HTTP RESPONSE--"); this.log(htmlText); this.log("----- End HTTP RESPONSE--"); if (parseHtml) { String guthaben = this.getGuthaben(htmlText, context); if (guthaben != null && !guthaben.equals("")) { this.SMS_CREDIT = guthaben; } this.getSpec(context).setBalance(this.SMS_CREDIT); } htmlText = null; } catch (Exception e) { Log.e(TAG, "Error sendData(...)", e); throw new WebSMSException(e.getMessage()); } } private String getGuthaben(final String htmlText, final Context context) { String guthaben = ""; int indexStartSMSCredit = htmlText.indexOf("noch verfgbar - "); if (indexStartSMSCredit > 0) { guthaben = htmlText.substring(indexStartSMSCredit + 17, indexStartSMSCredit + 20); } this.log("indexOf Guthaben= " + indexStartSMSCredit); this.log(" ------ Guthaben= " + guthaben); return guthaben; } private String filterNumber(final String number) { String result = "" + number; if (number != null && number.contains("<")) { int index1 = number.indexOf("<"); int index2 = number.indexOf(">"); result = result.substring(index1 + 1, index2); this.log("\n\n********** filterNumber=" + result + "\n\n"); } return result.trim(); } /** * central logger * * @param message */ private void log(final String message) { Log.d(TAG, message); } }