0)
- authMethods = authMethods.concat(""+getString(R.string.authMethod_text_server)+" "+aServerID+"
");
- }
- }
- Certificate tempcert = aAuthMethod.getCAcert();
- if (tempcert!=null)
- {
- String certString = tempcert.toString();
- int start=certString.indexOf("CN=");
- int finish=certString.indexOf("Validity");
- if (start>0 && finish>0) {
- certString = certString.substring(start, finish);
- authMethods = authMethods.concat(""+getString(R.string.authMethod_text_certcn)+" "+certString+"
");
- }
- }
- }
- }
- else
- {
- authMethods = authMethods.concat(""+getString(R.string.authMethod_text_error1)+"
");
- authMethods = authMethods.concat(getString(R.string.authMethod_text_error2));
- }
-
- summary_template = ""+getString(R.string.summary_text_title)+"
" +
- ""+getString(R.string.summary_text_provider)+"" + aProfile.getDisplayName() + "
" +
- ""+getString(R.string.summary_text_description)+"" + aProfile.getDescription() + "
" +
- //"IdentityProvider:" + aProfile.getEAPIdP_ID() + "
" +
- wifiSettings +
- authMethods +
- supportHTML;
-
- }
- else
- {
- summary_template = "
"+getString(R.string.profileMissing_title)+"
" +
- ""+getString(R.string.profileMissing_text1)+"" + aProfile.getError() + "
" +"
";
- }
-
- } catch (Exception e)
- {
- summary_template = ""+getString(R.string.config_file_error)+"
"+getString(R.string.config_file_text);
- }
- }
- else
- {
- //no profiles
- eduroamCAT.debug("profiles null");
- summary_template = ""+getString(R.string.config_file_error)+"
" +
- ""+getString(R.string.config_file_text2)+"
";
- }
-
- Spanned sp_summary = Html.fromHtml(summary_template);
- summaryView.setText(sp_summary);
- summaryView.setMovementMethod(new ScrollingMovementMethod());
- //summaryView.setScrollBarStyle(BIND_ABOVE_CLIENT);
- }
-
- //Discard button press
- public void onDiscardClick(View view)
- {
-
- if (eduroamCAT.profiles!=null)
- {
- eduroamCAT.wifiProfile.setConfigError(getString(R.string.config_discarded));
- for(int s=0; s0 && eduroamCAT.wifiProfile.hasError()==false)
- {
- //String wifiTmp=eduroamCAT.wifiProfile.getSSID()+":("+eduroamCAT.wifiProfile.getAuthType()+"/"+eduroamCAT.wifiProfile.getEncryptionType();
- String wifiTmp=eduroamCAT.wifiProfile.getSSID()+":";
- eduroamCAT.debug("committing2:profile size="+eduroamCAT.profiles.size());
- for (int profilescount=0; profilescount0)
- {
- eduroamCAT.debug("committing auth method:"+aProfile.getNumberAuthenticationMethods());
- for (int i=0;i0)
- if (!eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).isError())
- {
- String terms=eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getTermsOfUse();
- String message=getString(R.string.profile_install_confirm);
- if (terms.length()>0) message=getString(R.string.profile_install_confirm2)+terms;
- new AlertDialog.Builder(this)
- .setTitle(getString(R.string.profile_install_title))
- .setMessage(message)
- .setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- eduroamCAT.debug("YES Install Profile");
- Intent start = new Intent(getApplicationContext(),eduroamCAT.class);
- commitProfile();
- //finish()
- startActivity(start);
- finish();
- }
- })
- .setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- eduroamCAT.debug("NO Install Profile");
- eduroamCAT.profiles.clear();
- eduroamCAT.wifiProfile.hasError();
- //destroy instead of error?
- }
- })
- //.setIcon(R.drawable.ic_dialog_alert)
- .show();
- // finish();
- }
-
- if (eduroamCAT.profiles!=null)
- if (eduroamCAT.profiles.size()>0)
- if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).isError())
- {
- //if eap-tls, request pin again
- int lastAuthMethod = 0;
- lastAuthMethod = eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getNumberAuthenticationMethods();
- if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getAuthenticationMethod(lastAuthMethod-1).getOuterEAPType()==13)
- if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getAuthenticationMethod(lastAuthMethod-1).getClientPrivateKey()==null)
- {
- requestKeypass(getString(R.string.pinDialog),getString(R.string.pinDialog),this, clientCert);
- }
- }
- }
-
- /**
- * Set up the {@link android.app.ActionBar}.
- */
- private void setupActionBar() {
-
- getActionBar().setDisplayHomeAsUpEnabled(true);
-
- }
-
- public static void requestKeypass(String message, String title, final Activity activ, final NodeList clientCertx)
- {
- // Set an EditText view to get user input
- final EditText input = new EditText(activ);
-
- new AlertDialog.Builder(activ)
- .setTitle(title)
- .setMessage(message)
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- String pin = input.getText().toString();
- eduroamCAT.debug("PIN=" + pin);
- String certstring = "";
- Element Clientcert = null;
- if (clientCertx.getLength()>0) clientCert = clientCertx;
- if (clientCert.getLength() > 0) {
- for (int s = 0; s < clientCert.getLength(); s++) {
- Clientcert = (Element) clientCert.item(s);
- String tmp = null;
- tmp = Clientcert.getTextContent().trim();
-
- //get recent eap-tld profile, and add the client sert to any eap-tls auth methods
- if (eduroamCAT.profiles != null)
- if (eduroamCAT.profiles.size() > 0) {
- //get last profile added
- ConfigProfile aProfile = eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1);
- if (aProfile.getNumberAuthenticationMethods() > 0) {
- eduroamCAT.debug("eap-tls auth methods:" + aProfile.getNumberAuthenticationMethods());
- for (int i = 0; i < aProfile.getNumberAuthenticationMethods(); i++) {
- AuthenticationMethod aAuthMethod = aProfile.getAuthenticationMethod(i);
- eduroamCAT.debug("got auth method with eap inner=" + aAuthMethod.getOuterEAPType());
- if (aAuthMethod.getOuterEAPType() == 13)
- try {
- eduroamCAT.debug("adding client cert:" + tmp + "with pin " + pin);
- if (aAuthMethod.loadClientCert(tmp, Clientcert.getAttribute("format"), Clientcert.getAttribute("encoding"), pin)) {
- aAuthMethod.setClientCertPass(pin);
- aAuthMethod.clearConfigError();
- aProfile.removeAuthenticationMethod(i);
- aProfile.addAuthenticationMethod(aAuthMethod);
- eduroamCAT.profiles.set(eduroamCAT.profiles.size() - 1, aProfile);
- eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1).clearConfigError();
- } else {
- eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1).setConfigError("Client cert error");
- Toast.makeText(activ, activ.getString(R.string.pinFailed), Toast.LENGTH_LONG).show();
- }
- } catch (KeyStoreException e) {
- e.printStackTrace();
- eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1).setConfigError("Client cert error");
- Toast.makeText(activ, activ.getString(R.string.pinFailed), Toast.LENGTH_LONG).show();
- }
- }
- }
- }
- }
- }
- }
- })
- .setNegativeButton(R.string.discard_button, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- //cancel install of
- eduroamCAT.debug("User discard...");
- }
- })
- .setView(input)
- .show();
- }
-
- public ArrayList parseProfile(String config) throws IOException, ParserConfigurationException, SAXException
- {
- ArrayList profiles = new ArrayList();
- //parse XML
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder configBuilder = factory.newDocumentBuilder();
- InputSource is = new InputSource(new StringReader(config));
- Document parsedConfig = configBuilder.parse(is);
-
- eduroamCAT.debug("Builder="+configBuilder.toString());
- if (parsedConfig.getXmlVersion()=="1.0") eduroamCAT.debug("Version OK");
- else { eduroamCAT.debug("Version Invalid"); return profiles; }
-
-
- //Iterate each EAPIdP in EAPIdPList
- //Element root = parsedConfig.getDocumentElement();
- NodeList EAPIdP_list = parsedConfig.getElementsByTagName("EAPIdentityProvider");
- for(int i=0; i0)
- for(int j=0; j0)
- {
- Element eapMethod = (Element) authList.item(0);
- //eduroamCAT.debug("eapMethod="+eapMethod.getTextContent().trim());
- newAuthMethod.setOuterEAPType(Integer.parseInt(eapMethod.getTextContent().trim()));
- }
- else newAuthMethod.setConfigError(getString(R.string.error_with)+"Outer EAP Type");
- eduroamCAT.debug("Got OuterEAPType="+newAuthMethod.getOuterEAPType());
-
-// //get server side credential
- NodeList serverSideCredentials = authElement.getElementsByTagName("ServerSideCredential");
- if (serverSideCredentials.getLength()>0)
- {
- eduroamCAT.debug("Got ServerSideCredentials");
-
- //get CA cert
- NodeList CA = authElement.getElementsByTagName("CA");
- String certstring="";
- Element CAcert=null;
- if (CA.getLength()>0) {
- for(int s=0; s0)
- for(int s=0; s0)
- for(int k=0; k0) {
- eduroamCAT.debug("ClientSideCredential cert="+clientSide.toString());
- Element clientSideElement = (Element) clientSide.item(0);
- Boolean allow_save = true;
- allow_save = Boolean.valueOf(clientSideElement.getAttribute("allow_save"));
- for(int k=0; k0)
- {
- Element anonIDvalue = (Element) anonID.item(0);
- newAuthMethod.setAnonID(anonIDvalue.getTextContent(),allow_save);
- eduroamCAT.debug("Got anonID="+anonIDvalue.getTextContent());
- }
-
- //get Client cert
- //get keypass from user
- clientCert = authElement.getElementsByTagName("ClientCertificate");
- if (clientCert.getLength()>0) requestKeypass(getString(R.string.pinDialog),getString(R.string.pinDialog),this,clientCert);
- }
- }
-
- //add new authentication mode to config
- config1x.addAuthenticationMethod(newAuthMethod);
- }
- else
- {
- config1x.setConfigError(getString(R.string.error_with)+"Outer Authentication Method");
- }
-
- eduroamCAT.debug("AuthenticatoinMethod Count="+config1x.getNumberAuthenticationMethods());
-
- //***************************************************************CredentialApplicability
- NodeList credApplic = EAPIdP_ID.getElementsByTagName("CredentialApplicability");
- if (credApplic.getLength()>0)
- for(int s=0; s0)
- for(int m=0; m0)
- {
- Element ssidElement = (Element) ssid.item(0);
- ssidValue=ssidElement.getTextContent();
- }
- minRSNProto = IEEE80211prop.getElementsByTagName("MinRSNProto");
- if (minRSNProto.getLength()>0)
- {
- Element minRSNProtoElement = (Element) minRSNProto.item(0);
- minRSNProtoValue = minRSNProtoElement.getTextContent();
- }
- eduroamCAT.debug("Got SSID with proto:"+ssidValue+"/"+minRSNProtoValue);
-
- //if (IEEE80211prop.getTextContent().length()>0) config1x.setHelpdeskEmail(IEEE80211prop.getTextContent(), ssif);
- }
- }
-
- //***************************************************************PROVIDER INFO
- NodeList providerInfo = EAPIdP_ID.getElementsByTagName("ProviderInfo");
- if (providerInfo.getLength()==1)
- {
- Element providerElement = (Element) providerInfo.item(0);
-
- NodeList displayNameList = providerElement.getElementsByTagName("DisplayName");
- if (displayNameList.getLength()>0)
- for(int s=0; s0)
- {
- String displayNameLang = "";
- displayNameLang = displayName.getAttribute("lang");
- if (displayNameLang.length()>0) config1x.setDisplayName(displayName.getTextContent().trim(),displayNameLang);
- else config1x.setDisplayName(displayName.getTextContent().trim(),"en");
- }
- eduroamCAT.debug("Got Display Name:"+config1x.getDisplayName());
- }
-
- NodeList descriptionList = providerElement.getElementsByTagName("Description");
- if (descriptionList.getLength()>0)
- for(int s=0; s0)
- {
- String descriptionLang = "";
- descriptionLang = description.getAttribute("lang");
- if (descriptionLang.length()>0) config1x.setDescription(description.getTextContent().trim(),descriptionLang);
- else config1x.setDescription(description.getTextContent().trim(),"en");
- }
- eduroamCAT.debug("Got Description:"+config1x.getDescription());
- }
- //***************************************************************PROVIDER LOCATION
- NodeList locationList = providerElement.getElementsByTagName("ProviderLocation");
- double longitude=0, latitude=0;
- if (locationList.getLength()>0)
- {
- for(int s=0; s0) {
- Element lat = (Element) latList.item(0);
- try {
- Number number = format.parse(lat.getTextContent());
- longitude = number.doubleValue();
- }
- catch (ParseException e) {
- eduroamCAT.debug("latitude parse error");
- }
- }
-
- NodeList longList = location.getElementsByTagName("Longitude");
- if (longList.getLength()>0) {
- Element location2 = (Element) longList.item(0);
- try {
- Number number = format.parse(location2.getTextContent());
- longitude = number.doubleValue();
- }
- catch (ParseException e) {
- eduroamCAT.debug("longitude parse error");
- }
- }
- }
-
- if (latitude!=0 && longitude!=0)
- {
- config1x.setLocation(latitude,longitude);
- eduroamCAT.debug("Got Location:"+config1x.getLocation());
- }
- }
-
- //***************************************************************PROVIDER LOCATION
- NodeList logoList = providerElement.getElementsByTagName("ProviderLogo");
- if (logoList.getLength()>0)
- for(int s=0; s0 && logoEncoding.length()>0)
- config1x.setLogo(logo.getTextContent(),logoMime,logoEncoding);
- eduroamCAT.debug("Got logo:"+config1x.getLogo());
- }
- //***************************************************************TERMS OF USE
- NodeList touList = providerElement.getElementsByTagName("TermsOfUse");
- if (touList.getLength()>0)
- for(int s=0; s0) config1x.setTermsOfUse(tou.getTextContent().trim());
- eduroamCAT.debug("Got Terms of Use:"+config1x.getTermsOfUse());
- }
-
- //***************************************************************HELPDESK
-
- NodeList helpdeskList = providerElement.getElementsByTagName("Helpdesk");
- if (helpdeskList.getLength()>0) {
- for(int h=0; i0)
- for(int m=0; m0) config1x.setHelpdeskEmail(aemail.getTextContent(), lang);
- }
-
- NodeList webList = helpdeskItem.getElementsByTagName("WebAddress");
- if (webList.getLength()>0)
- for(int m=0; m0) config1x.setHelpdeskURL(aweb.getTextContent(), lang);
- }
-
- NodeList phoneList = helpdeskItem.getElementsByTagName("Phone");
- if (phoneList.getLength()>0)
- for(int m=0; m0) config1x.setHelpdeskPhone(aphone.getTextContent(), lang);
- }
- }
- config1x.setHelpdeskInfo(true);
- eduroamCAT.debug("Got Helpdesk Email="+config1x.getSupportEmails());
- eduroamCAT.debug("Got Helpdesk Web="+config1x.getHelpdeskURL());
- eduroamCAT.debug("Got Helpdesk Phone="+config1x.getHelpdeskPhoneNumber(""));
- }
- }
- profiles.add(config1x);
- }
-
-
- eduroamCAT.debug("Number of profiles="+profiles.size());
- return profiles;
- }
-
-
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
-
-
- return true;
- }
-
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case android.R.id.home:
- // This ID represents the Home or Up button. In the case of this
- // activity, the Up button is shown. Use NavUtils to allow users
- // to navigate up one level in the application structure. For
- // more details, see the Navigation pattern on Android Design:
- //
- // http://developer.android.com/design/patterns/navigation.html#up-vs-back
- //
- NavUtils.navigateUpFromSameTask(this);
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
-
- @Override
- public void onDestroy()
- {
- Log.d("eduroamCAT", "***** EAPMetadata onDestroy()");
- super.onDestroy();
- //finish();
- }
-
- @Override
- protected void onResume()
- {
- Log.d("eduroamCAT", "***** EAPMetadata onResume()");
- super.onResume();
- }
-
- @Override
- protected void onRestart()
- {
- Log.d("eduroamCAT", "***** EAPMetadata onRestart()");
- super.onRestart();
- }
-
- @Override
- protected void onPause()
- {
- Log.d("eduroamCAT", "***** EAPMetadata onPause()");
- //finish();
- super.onPause();
- }
-
- @Override
- protected void onStart() {
- Log.d("eduroamCAT", "***** EAPMetadata onStart()");
- super.onStart();
- }
-
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.security.KeyStoreException;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Locale;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.Environment;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.support.v4.app.ActivityCompat;
+import android.support.v4.content.ContextCompat;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.support.v4.app.NavUtils;
+import android.text.Html;
+import android.text.Spanned;
+import android.text.method.ScrollingMovementMethod;
+import android.widget.Toast;
+
+public class EAPMetadata extends Activity {
+
+ static Button discard,install;
+ ProfilesStorage db = new ProfilesStorage(this);
+ String keyPass=""; //default to nothing to start (optional)
+ //global clietn cert value for retry
+ static NodeList clientCert;
+ private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
+
+ public boolean testExternalStorage()
+ {
+ String state = Environment.getExternalStorageState();
+ if (Environment.MEDIA_MOUNTED.equals(state)) {
+ return true;
+ }
+ else return false;
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
+ switch (requestCode) {
+ case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
+ if (grantResults.length > 0
+ && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ this.recreate();
+ } else {
+ Toast.makeText(this, this.getString(R.string.storagePermission), Toast.LENGTH_LONG).show();
+ }
+ return;
+ }
+ }
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ // Show the Up button in the action bar.
+ setupActionBar();
+ if (getIntent().getBooleanExtra("EXIT", false))
+ {
+ finish();
+ }
+ eduroamCAT.debug("Starting onCreate for EAPMetadata class...");
+ setContentView(R.layout.activity_eapmetadata);
+ Intent configIntent = getIntent();
+ InputStream configIn = null;
+ boolean configFileError = false;
+ String pathToDownload ="";
+ eduroamCAT.debug("Got eap-config:"+configIntent.getDataString());
+
+ //check real-time permissions for storage
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
+ eduroamCAT.debug("No External Storage permissions");
+ ActivityCompat.requestPermissions(this,
+ new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
+ MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
+ configFileError=true;
+ Toast.makeText(this, this.getString(R.string.storagePermission), Toast.LENGTH_LONG).show();
+ }
+ else configFileError=false;
+
+ if (configIntent.getDataString().contains("http://") || configIntent.getDataString().contains("https://"))
+ {
+ //download file to sdcard
+ if (testExternalStorage()) {
+ try {
+ //delte file if already exists
+ String path = Environment.getExternalStorageDirectory().getPath() + "/EAPConfig/";
+ File file = new File(path);
+ File outputFile = new File(file, "eduroam.eap-config");
+ if (outputFile.exists())
+ {
+ Boolean deleteResult = outputFile.delete();
+ eduroamCAT.debug("delete file before download:" + deleteResult);
+ }
+ //if (downloadEAPFile(configIntent.getDataString(),"eduroam.eap-config")) configFileError=false;
+ //else configFileError=true;
+ new DownloadEAPConfig().execute(configIntent.getDataString());
+ pathToDownload=Environment.getExternalStorageDirectory().getPath()+"/EAPConfig/eduroam.eap-config";
+ eduroamCAT.debug("Downloaded to:"+pathToDownload);
+ } catch (Exception e) {
+ eduroamCAT.debug("Error downloading file:"+configIntent.getDataString());
+ configFileError=true;
+ e.printStackTrace();
+ }
+ }
+ else
+ {
+ eduroamCAT.debug("Error reading external storage:"+configIntent.getDataString());
+ configFileError=true;
+ }
+ }
+ String aBuffer = "";
+ if (configFileError==false) {
+ int loop=0;
+ while (loop<10) {
+ try {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e2) {
+ // TODO Auto-generated catch block
+ e2.printStackTrace();
+ }
+ if (pathToDownload.length()>0)
+ {
+ eduroamCAT.debug("downloaded?:"+eduroamCAT.downloaded);
+ if (!eduroamCAT.downloaded) { loop++; continue; }
+ configIn = new FileInputStream(pathToDownload);
+ eduroamCAT.debug("using path:"+pathToDownload);
+ }
+ else {
+ configIn = getContentResolver().openInputStream(configIntent.getData());
+ eduroamCAT.debug("Using intent get data");
+ }
+ //http://stackoverflow.com/questions/14364091/retrieve-file-path-from-caught-downloadmanager-intent <---- change for download files in 4.2
+
+ BufferedReader myReader = new BufferedReader(new InputStreamReader(configIn));
+ String aDataRow = "";
+
+ try {
+ while ((aDataRow = myReader.readLine()) != null) {
+ aBuffer += aDataRow + "\n";
+ }
+ } catch (IOException e) {
+ eduroamCAT.debug("Config File read error.");
+ //finish();
+ configFileError=true;
+ e.printStackTrace();
+ }
+
+ if (configFileError==false) {
+ //Build Array of Vales from profile
+ try {
+ eduroamCAT.profiles=parseProfile(aBuffer);
+ } catch (SAXException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ //finish();
+ } catch (ParserConfigurationException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ //finish();
+ }
+
+ //Build WiFi Profile
+ //default to eduroam settings
+ if (eduroamCAT.wifiProfile==null) eduroamCAT.wifiProfile = new WiFiProfile();
+ if (eduroamCAT.wifiProfile!=null && db.numberOfRowsWiFi()<1) {
+ eduroamCAT.wifiProfile.isOK();
+ eduroamCAT.wifiProfile.setSSID("eduroam");
+ eduroamCAT.wifiProfile.setAuthType("WPA2");
+ eduroamCAT.wifiProfile.setEncryptionType("CCMP");
+ eduroamCAT.wifiProfile.setAutojoin(true);
+ eduroamCAT.wifiProfile.setSSIDPriority(1);
+ if (eduroamCAT.wifiProfile.hasError()==false) {
+ eduroamCAT.debug("WiFi Profile OK");
+ //add to DB
+ long result = db.insertWiFi("0", eduroamCAT.wifiProfile.getSSID(), eduroamCAT.wifiProfile.getAuthType(),eduroamCAT.wifiProfile.getEncryptionType(),eduroamCAT.wifiProfile.getSSIDPriority(), 1);
+ eduroamCAT.debug("DB INSET INTO WIFI:"+result);
+ }
+ else eduroamCAT.debug("WiFi Profile Error!");
+ }
+ else
+ {
+ eduroamCAT.debug("WiFi Profile Found in DB!");
+ eduroamCAT.wifiProfile=db.getWiFi(0);
+ eduroamCAT.debug("SSID FOUND="+eduroamCAT.wifiProfile.getSSID());
+ //load????
+ //eduroamCAT.debug("Exiting...!");
+ //finish();
+ }
+ break;
+ }
+ else
+ {
+ eduroamCAT.debug("Config File error");
+ }
+
+ } catch (IOException e1) {
+ eduroamCAT.debug("Config File access error");
+ e1.printStackTrace();
+
+ }
+ loop++;
+ }
+ }
+
+ TextView summaryView = (TextView) findViewById(R.id.configSummary);
+ String summary_template="";
+ //check if more than zero profiles in profiles
+ if (eduroamCAT.profiles!=null && eduroamCAT.wifiProfile!=null)
+ {
+ try {
+ ConfigProfile aProfile = eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1);
+
+ if (aProfile.isError()==false) {
+
+ String supportHTML="";
+ if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).hasHelpdeskInfo())
+ {
+ String web = "";
+ if (aProfile.getHelpdeskURL()!=null) web = aProfile.getHelpdeskURL().toString();
+ supportHTML=""+getString(R.string.supportHTML_text1)+"
"+
+ ""+getString(R.string.supportHTML_text_email)+"" + aProfile.getSupportEmails() + "
" +
+ ""+getString(R.string.supportHTML_text_phone)+"" + aProfile.getHelpdeskPhoneNumber("") + "
" +
+ ""+getString(R.string.supportHTML_text_tou)+"" + aProfile.getTermsOfUse() + "
" +
+ ""+getString(R.string.supportHTML_text_web)+"" + web + "
";
+ }
+
+ String wifiSettings="";
+ //wifiSettings="WiFi Settings
SSID="+eduroamCAT.wifiProfile.getSSID()+" Auth:"+eduroamCAT.wifiProfile.getAuthType()+" Encryption="+eduroamCAT.wifiProfile.getEncryptionType() + "
";
+
+ String authMethods="";
+ if (aProfile.getNumberAuthenticationMethods()>0)
+ {
+ eduroamCAT.debug("************************************************:got auth method");
+ for (int i=0;i"+getString(R.string.authMethod_text_title) + count +"");
+ String outer="";
+ String inner="";
+ if (aAuthMethod.getOuterEAPType()==25) outer="/PEAP";
+ if (aAuthMethod.getOuterEAPType()==21) outer="/TTLS";
+ if (aAuthMethod.getOuterEAPType()==13) outer="/TLS";
+ if (aAuthMethod.getOuterEAPType()==52) outer="/PWD";
+ authMethods = authMethods.concat(""+getString(R.string.authMethod_text_eapmethod)+" "+aAuthMethod.getOuterEAPType()+outer+"
");
+ if (aAuthMethod.getInnerEAPType()>0)
+ if (aAuthMethod.getInnerEAPType()==1) inner="/PAP";
+ if (aAuthMethod.getInnerEAPType()==26) inner="/MSCHAPv2";
+ if (aAuthMethod.getInnerEAPType()==6) inner="/GTC";
+ authMethods = authMethods.concat(""+getString(R.string.authMethod_text_innereapmethod)+" "+aAuthMethod.getInnerEAPType()+inner+"
");
+ if (aAuthMethod.getAnonID().length()>0)
+ authMethods = authMethods.concat(""+getString(R.string.authMethod_text_server)+" "+aAuthMethod.getAnonID()+"
");
+ if (aAuthMethod.getServerIDs().size()>0)
+ {
+ ArrayList serverID = aAuthMethod.getServerIDs();
+ for (int s=0;s0)
+ authMethods = authMethods.concat(""+getString(R.string.authMethod_text_server)+" "+aServerID+"
");
+ }
+ }
+ Certificate tempcert = aAuthMethod.getCAcert();
+ if (tempcert!=null)
+ {
+ String certString = tempcert.toString();
+ int start=certString.indexOf("CN=");
+ int finish=certString.indexOf("Validity");
+ if (start>0 && finish>0) {
+ certString = certString.substring(start, finish);
+ authMethods = authMethods.concat(""+getString(R.string.authMethod_text_certcn)+" "+certString+"
");
+ }
+ }
+ }
+ }
+ else
+ {
+ authMethods = authMethods.concat(""+getString(R.string.authMethod_text_error1)+"
");
+ authMethods = authMethods.concat(getString(R.string.authMethod_text_error2));
+ }
+
+ summary_template = ""+getString(R.string.summary_text_title)+"
" +
+ ""+getString(R.string.summary_text_provider)+"" + aProfile.getDisplayName() + "
" +
+ ""+getString(R.string.summary_text_description)+"" + aProfile.getDescription() + "
" +
+ //"IdentityProvider:" + aProfile.getEAPIdP_ID() + "
" +
+ wifiSettings +
+ authMethods +
+ supportHTML;
+
+ }
+ else
+ {
+ summary_template = "
"+getString(R.string.profileMissing_title)+"
" +
+ ""+getString(R.string.profileMissing_text1)+"" + aProfile.getError() + "
" +"
";
+ }
+
+ } catch (Exception e)
+ {
+ summary_template = ""+getString(R.string.config_file_error)+"
"+getString(R.string.config_file_text);
+ }
+ }
+ else
+ {
+ //no profiles
+ eduroamCAT.debug("profiles null");
+ summary_template = ""+getString(R.string.config_file_error)+"
" +
+ ""+getString(R.string.config_file_text2)+"
";
+ }
+
+ Spanned sp_summary = Html.fromHtml(summary_template);
+ summaryView.setText(sp_summary);
+ summaryView.setMovementMethod(new ScrollingMovementMethod());
+ //summaryView.setScrollBarStyle(BIND_ABOVE_CLIENT);
+ }
+
+ //Discard button press
+ public void onDiscardClick(View view)
+ {
+
+ if (eduroamCAT.profiles!=null)
+ {
+ eduroamCAT.wifiProfile.setConfigError(getString(R.string.config_discarded));
+ for(int s=0; s0 && eduroamCAT.wifiProfile.hasError()==false)
+ {
+ //String wifiTmp=eduroamCAT.wifiProfile.getSSID()+":("+eduroamCAT.wifiProfile.getAuthType()+"/"+eduroamCAT.wifiProfile.getEncryptionType();
+ String wifiTmp=eduroamCAT.wifiProfile.getSSID()+":";
+ eduroamCAT.debug("committing2:profile size="+eduroamCAT.profiles.size());
+ for (int profilescount=0; profilescount0)
+ {
+ eduroamCAT.debug("committing auth method:"+aProfile.getNumberAuthenticationMethods());
+ for (int i=0;i0)
+ if (!eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).isError())
+ {
+ String terms=eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getTermsOfUse();
+ String message=getString(R.string.profile_install_confirm);
+ if (terms.length()>0) message=getString(R.string.profile_install_confirm2)+terms;
+ new AlertDialog.Builder(this)
+ .setTitle(getString(R.string.profile_install_title))
+ .setMessage(message)
+ .setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ eduroamCAT.debug("YES Install Profile");
+ Intent start = new Intent(getApplicationContext(),eduroamCAT.class);
+ commitProfile();
+ //finish()
+ startActivity(start);
+ finish();
+ }
+ })
+ .setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ eduroamCAT.debug("NO Install Profile");
+ eduroamCAT.profiles.clear();
+ eduroamCAT.wifiProfile.hasError();
+ //destroy instead of error?
+ }
+ })
+ //.setIcon(R.drawable.ic_dialog_alert)
+ .show();
+ // finish();
+ }
+
+ if (eduroamCAT.profiles!=null)
+ if (eduroamCAT.profiles.size()>0)
+ if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).isError())
+ {
+ //if eap-tls, request pin again
+ int lastAuthMethod = 0;
+ lastAuthMethod = eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getNumberAuthenticationMethods();
+ if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getAuthenticationMethod(lastAuthMethod-1).getOuterEAPType()==13)
+ if (eduroamCAT.profiles.get(eduroamCAT.profiles.size()-1).getAuthenticationMethod(lastAuthMethod-1).getClientPrivateKey()==null)
+ {
+ requestKeypass(getString(R.string.pinDialog),getString(R.string.pinDialog),this, clientCert);
+ }
+ }
+ }
+
+ /**
+ * Set up the {@link android.app.ActionBar}.
+ */
+ private void setupActionBar() {
+
+ getActionBar().setDisplayHomeAsUpEnabled(true);
+
+ }
+
+ public static void requestKeypass(String message, String title, final Activity activ, final NodeList clientCertx)
+ {
+ // Set an EditText view to get user input
+ final EditText input = new EditText(activ);
+
+ new AlertDialog.Builder(activ)
+ .setTitle(title)
+ .setMessage(message)
+ .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ String pin = input.getText().toString();
+ eduroamCAT.debug("PIN=" + pin);
+ String certstring = "";
+ Element Clientcert = null;
+ if (clientCertx.getLength()>0) clientCert = clientCertx;
+ if (clientCert.getLength() > 0) {
+ for (int s = 0; s < clientCert.getLength(); s++) {
+ Clientcert = (Element) clientCert.item(s);
+ String tmp = null;
+ tmp = Clientcert.getTextContent().trim();
+
+ //get recent eap-tld profile, and add the client sert to any eap-tls auth methods
+ if (eduroamCAT.profiles != null)
+ if (eduroamCAT.profiles.size() > 0) {
+ //get last profile added
+ ConfigProfile aProfile = eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1);
+ if (aProfile.getNumberAuthenticationMethods() > 0) {
+ eduroamCAT.debug("eap-tls auth methods:" + aProfile.getNumberAuthenticationMethods());
+ for (int i = 0; i < aProfile.getNumberAuthenticationMethods(); i++) {
+ AuthenticationMethod aAuthMethod = aProfile.getAuthenticationMethod(i);
+ eduroamCAT.debug("got auth method with eap inner=" + aAuthMethod.getOuterEAPType());
+ if (aAuthMethod.getOuterEAPType() == 13)
+ try {
+ eduroamCAT.debug("adding client cert:" + tmp + "with pin " + pin);
+ if (aAuthMethod.loadClientCert(tmp, Clientcert.getAttribute("format"), Clientcert.getAttribute("encoding"), pin)) {
+ aAuthMethod.setClientCertPass(pin);
+ aAuthMethod.clearConfigError();
+ aProfile.removeAuthenticationMethod(i);
+ aProfile.addAuthenticationMethod(aAuthMethod);
+ eduroamCAT.profiles.set(eduroamCAT.profiles.size() - 1, aProfile);
+ eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1).clearConfigError();
+ } else {
+ eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1).setConfigError("Client cert error");
+ Toast.makeText(activ, activ.getString(R.string.pinFailed), Toast.LENGTH_LONG).show();
+ }
+ } catch (KeyStoreException e) {
+ e.printStackTrace();
+ eduroamCAT.profiles.get(eduroamCAT.profiles.size() - 1).setConfigError("Client cert error");
+ Toast.makeText(activ, activ.getString(R.string.pinFailed), Toast.LENGTH_LONG).show();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ })
+ .setNegativeButton(R.string.discard_button, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ //cancel install of
+ eduroamCAT.debug("User discard...");
+ }
+ })
+ .setView(input)
+ .show();
+ }
+
+ public ArrayList parseProfile(String config) throws IOException, ParserConfigurationException, SAXException
+ {
+ ArrayList profiles = new ArrayList();
+ //parse XML
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder configBuilder = factory.newDocumentBuilder();
+ InputSource is = new InputSource(new StringReader(config));
+ Document parsedConfig = configBuilder.parse(is);
+
+ eduroamCAT.debug("Builder="+configBuilder.toString());
+ if (parsedConfig.getXmlVersion()=="1.0") eduroamCAT.debug("Version OK");
+ else { eduroamCAT.debug("Version Invalid"); return profiles; }
+
+
+ //Iterate each EAPIdP in EAPIdPList
+ //Element root = parsedConfig.getDocumentElement();
+ NodeList EAPIdP_list = parsedConfig.getElementsByTagName("EAPIdentityProvider");
+ for(int i=0; i0)
+ for(int j=0; j0)
+ {
+ Element eapMethod = (Element) authList.item(0);
+ //eduroamCAT.debug("eapMethod="+eapMethod.getTextContent().trim());
+ newAuthMethod.setOuterEAPType(Integer.parseInt(eapMethod.getTextContent().trim()));
+ }
+ else newAuthMethod.setConfigError(getString(R.string.error_with)+"Outer EAP Type");
+ eduroamCAT.debug("Got OuterEAPType="+newAuthMethod.getOuterEAPType());
+
+// //get server side credential
+ NodeList serverSideCredentials = authElement.getElementsByTagName("ServerSideCredential");
+ if (serverSideCredentials.getLength()>0)
+ {
+ eduroamCAT.debug("Got ServerSideCredentials");
+
+ //get CA cert
+ NodeList CA = authElement.getElementsByTagName("CA");
+ String certstring="";
+ Element CAcert=null;
+ if (CA.getLength()>0) {
+ for(int s=0; s0)
+ for(int s=0; s0)
+ for(int k=0; k0) {
+ eduroamCAT.debug("ClientSideCredential cert="+clientSide.toString());
+ Element clientSideElement = (Element) clientSide.item(0);
+ Boolean allow_save = true;
+ allow_save = Boolean.valueOf(clientSideElement.getAttribute("allow_save"));
+ for(int k=0; k0)
+ {
+ Element anonIDvalue = (Element) anonID.item(0);
+ newAuthMethod.setAnonID(anonIDvalue.getTextContent(),allow_save);
+ eduroamCAT.debug("Got anonID="+anonIDvalue.getTextContent());
+ }
+
+ //get Client cert
+ //get keypass from user
+ clientCert = authElement.getElementsByTagName("ClientCertificate");
+ if (clientCert.getLength()>0) requestKeypass(getString(R.string.pinDialog),getString(R.string.pinDialog),this,clientCert);
+ }
+ }
+
+ //add new authentication mode to config
+ config1x.addAuthenticationMethod(newAuthMethod);
+ }
+ else
+ {
+ config1x.setConfigError(getString(R.string.error_with)+"Outer Authentication Method");
+ }
+
+ eduroamCAT.debug("AuthenticatoinMethod Count="+config1x.getNumberAuthenticationMethods());
+
+ //***************************************************************CredentialApplicability
+ NodeList credApplic = EAPIdP_ID.getElementsByTagName("CredentialApplicability");
+ if (credApplic.getLength()>0)
+ for(int s=0; s0)
+ for(int m=0; m0)
+ {
+ Element ssidElement = (Element) ssid.item(0);
+ ssidValue=ssidElement.getTextContent();
+ }
+ minRSNProto = IEEE80211prop.getElementsByTagName("MinRSNProto");
+ if (minRSNProto.getLength()>0)
+ {
+ Element minRSNProtoElement = (Element) minRSNProto.item(0);
+ minRSNProtoValue = minRSNProtoElement.getTextContent();
+ }
+ eduroamCAT.debug("Got SSID with proto:"+ssidValue+"/"+minRSNProtoValue);
+
+ //if (IEEE80211prop.getTextContent().length()>0) config1x.setHelpdeskEmail(IEEE80211prop.getTextContent(), ssif);
+ }
+ }
+
+ //***************************************************************PROVIDER INFO
+ NodeList providerInfo = EAPIdP_ID.getElementsByTagName("ProviderInfo");
+ if (providerInfo.getLength()==1)
+ {
+ Element providerElement = (Element) providerInfo.item(0);
+
+ NodeList displayNameList = providerElement.getElementsByTagName("DisplayName");
+ if (displayNameList.getLength()>0)
+ for(int s=0; s0)
+ {
+ String displayNameLang = "";
+ displayNameLang = displayName.getAttribute("lang");
+ if (displayNameLang.length()>0) config1x.setDisplayName(displayName.getTextContent().trim(),displayNameLang);
+ else config1x.setDisplayName(displayName.getTextContent().trim(),"en");
+ }
+ eduroamCAT.debug("Got Display Name:"+config1x.getDisplayName());
+ }
+
+ NodeList descriptionList = providerElement.getElementsByTagName("Description");
+ if (descriptionList.getLength()>0)
+ for(int s=0; s0)
+ {
+ String descriptionLang = "";
+ descriptionLang = description.getAttribute("lang");
+ if (descriptionLang.length()>0) config1x.setDescription(description.getTextContent().trim(),descriptionLang);
+ else config1x.setDescription(description.getTextContent().trim(),"en");
+ }
+ eduroamCAT.debug("Got Description:"+config1x.getDescription());
+ }
+ //***************************************************************PROVIDER LOCATION
+ NodeList locationList = providerElement.getElementsByTagName("ProviderLocation");
+ double longitude=0, latitude=0;
+ if (locationList.getLength()>0)
+ {
+ for(int s=0; s0) {
+ Element lat = (Element) latList.item(0);
+ try {
+ Number number = format.parse(lat.getTextContent());
+ longitude = number.doubleValue();
+ }
+ catch (ParseException e) {
+ eduroamCAT.debug("latitude parse error");
+ }
+ }
+
+ NodeList longList = location.getElementsByTagName("Longitude");
+ if (longList.getLength()>0) {
+ Element location2 = (Element) longList.item(0);
+ try {
+ Number number = format.parse(location2.getTextContent());
+ longitude = number.doubleValue();
+ }
+ catch (ParseException e) {
+ eduroamCAT.debug("longitude parse error");
+ }
+ }
+ }
+
+ if (latitude!=0 && longitude!=0)
+ {
+ config1x.setLocation(latitude,longitude);
+ eduroamCAT.debug("Got Location:"+config1x.getLocation());
+ }
+ }
+
+ //***************************************************************PROVIDER LOCATION
+ NodeList logoList = providerElement.getElementsByTagName("ProviderLogo");
+ if (logoList.getLength()>0)
+ for(int s=0; s0 && logoEncoding.length()>0)
+ config1x.setLogo(logo.getTextContent(),logoMime,logoEncoding);
+ eduroamCAT.debug("Got logo:"+config1x.getLogo());
+ }
+ //***************************************************************TERMS OF USE
+ NodeList touList = providerElement.getElementsByTagName("TermsOfUse");
+ if (touList.getLength()>0)
+ for(int s=0; s0) config1x.setTermsOfUse(tou.getTextContent().trim());
+ eduroamCAT.debug("Got Terms of Use:"+config1x.getTermsOfUse());
+ }
+
+ //***************************************************************HELPDESK
+
+ NodeList helpdeskList = providerElement.getElementsByTagName("Helpdesk");
+ if (helpdeskList.getLength()>0) {
+ for(int h=0; i0)
+ for(int m=0; m0) config1x.setHelpdeskEmail(aemail.getTextContent(), lang);
+ }
+
+ NodeList webList = helpdeskItem.getElementsByTagName("WebAddress");
+ if (webList.getLength()>0)
+ for(int m=0; m0) config1x.setHelpdeskURL(aweb.getTextContent(), lang);
+ }
+
+ NodeList phoneList = helpdeskItem.getElementsByTagName("Phone");
+ if (phoneList.getLength()>0)
+ for(int m=0; m0) config1x.setHelpdeskPhone(aphone.getTextContent(), lang);
+ }
+ }
+ config1x.setHelpdeskInfo(true);
+ eduroamCAT.debug("Got Helpdesk Email="+config1x.getSupportEmails());
+ eduroamCAT.debug("Got Helpdesk Web="+config1x.getHelpdeskURL());
+ eduroamCAT.debug("Got Helpdesk Phone="+config1x.getHelpdeskPhoneNumber(""));
+ }
+ }
+ profiles.add(config1x);
+ }
+
+
+ eduroamCAT.debug("Number of profiles="+profiles.size());
+ return profiles;
+ }
+
+
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+
+
+ return true;
+ }
+
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case android.R.id.home:
+ // This ID represents the Home or Up button. In the case of this
+ // activity, the Up button is shown. Use NavUtils to allow users
+ // to navigate up one level in the application structure. For
+ // more details, see the Navigation pattern on Android Design:
+ //
+ // http://developer.android.com/design/patterns/navigation.html#up-vs-back
+ //
+ NavUtils.navigateUpFromSameTask(this);
+ return true;
+ }
+ return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public void onDestroy()
+ {
+ Log.d("eduroamCAT", "***** EAPMetadata onDestroy()");
+ super.onDestroy();
+ //finish();
+ }
+
+ @Override
+ protected void onResume()
+ {
+ Log.d("eduroamCAT", "***** EAPMetadata onResume()");
+ super.onResume();
+ }
+
+ @Override
+ protected void onRestart()
+ {
+ Log.d("eduroamCAT", "***** EAPMetadata onRestart()");
+ super.onRestart();
+ }
+
+ @Override
+ protected void onPause()
+ {
+ Log.d("eduroamCAT", "***** EAPMetadata onPause()");
+ //finish();
+ super.onPause();
+ }
+
+ @Override
+ protected void onStart() {
+ Log.d("eduroamCAT", "***** EAPMetadata onStart()");
+ super.onStart();
+ }
+
+}
diff --git a/src/uk/ac/swansea/eduroamcat/GEOIP.java b/src/uk/ac/swansea/eduroamcat/GEOIP.java
index 38429a4..afea89a 100644
--- a/src/uk/ac/swansea/eduroamcat/GEOIP.java
+++ b/src/uk/ac/swansea/eduroamcat/GEOIP.java
@@ -1,147 +1,147 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import android.app.Activity;
-import android.os.AsyncTask;
-import android.text.Html;
-import android.text.Spanned;
-import android.view.View;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.util.EntityUtils;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.util.Locale;
-
-/**
- * Created by AyresGJ on 26/02/2016.
- * GeoIP lookup using https://cat.eduroam.org/user/API.php?lang=pl&action=locateUser
- */
-public class GEOIP extends AsyncTask {
-
- String country="";
- String region="";
- public Double latx,longx;
- private Boolean hasLocation=false;
- Activity activity;
-
-
- public GEOIP(Activity activity)
- {
- this.activity=activity;
- }
-
- //set user facing text to warn GeoIP starting. May incur permissions request.
- protected void onPreExecute() {
- super.onPreExecute();
- eduroamCAT.debug("starting geoip...");
- String loadingProfiles = activity.getString(R.string.scad_geoip_trying);
- Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_geoip_title)+"
" + loadingProfiles);
- if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
- if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
- }
-
- //deal with result
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- eduroamCAT.debug("GeoIP result:"+result);
- if (result.length() > 0) {
- try {
- if (ConfigureFragment.idptext != null)
- ConfigureFragment.idptext.setVisibility(View.VISIBLE);
- JSONObject item = new JSONObject(result);
- //eduroamCAT.debug("JSON GEOIP Length " + item.length());
- String country = "";
- country = item.getString("country");
- if (item.has("geo")) {
- if (item.optJSONArray("geo") != null) {
- //multiple lat/long pairs
- JSONArray geo = item.optJSONArray("geo");
- for (int j = 0; j < geo.length(); j++) {
- JSONObject geo_multi = geo.getJSONObject(j);
- latx = geo_multi.getDouble("lat");
- longx = geo_multi.getDouble("lon");
- }
- } else {
- //one lat/long pair
- JSONObject geo = item.getJSONObject("geo");
- latx = geo.getDouble("lat");
- longx = geo.getDouble("lon");
- }
- //eduroamCAT.debug("GEOIP GOT: " + latx + " and " + longx);
- hasLocation=true;
- ViewProfiles.adapter.notifyDataSetChanged();
- }
- } catch (JSONException e) {
- String error_message = "";
- if (result.length() > 0) error_message = "Error=" + result;
- Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_geoip_failed)+"
" + error_message);
- if (ConfigureFragment.idptext != null)
- ConfigureFragment.idptext.setText(idp_nearby);
- if (ConfigureFragment.scadProgress != null)
- ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
- //eduroamCAT.alertUser("GeoIP Failed","GeoIP Failed",activity);
- }
- }
- else
- {
- eduroamCAT.debug("NO result for GEOIP lookup");
- }
-
- if (result.length()>0)
- {
- ConfigureFragment.setupSCAD();
- String loadingProfiles = activity.getString(R.string.scad_geoip_success);
- Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_geoip_title)+"
" + loadingProfiles);
- if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
- if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
- }
- }
-
-
- @Override
- protected String doInBackground(String... params) {
- String str = "";
- HttpResponse response;
- HttpClient myClient = new DefaultHttpClient();
- String lang="";
- lang = Locale.getDefault().getLanguage();
- HttpPost myConnection = new HttpPost("https://cat.eduroam.org/user/API.php?lang=pl&action=locateUser");
- try {
- eduroamCAT.debug("Getting geoip location from cat.eduroam.org ");
- response = myClient.execute(myConnection);
- str = EntityUtils.toString(response.getEntity(), "UTF-8");
- //eduroamCAT.debug("Content="+str);
- } catch (Exception e) {
- eduroamCAT.debug(e.getMessage());
- }
- return str;
- }
-
- //set only if location from CAT via GEOIP success
- public boolean hasLocation()
- {
- return hasLocation;
- }
-
- //get latitude value
- public Double getLatitude()
- {
- return latx;
- }
-
- //get longitude
- public Double getLongitude()
- {
- return longx;
- }
-
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+import android.text.Html;
+import android.text.Spanned;
+import android.view.View;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.Locale;
+
+/**
+ * Created by AyresGJ on 26/02/2016.
+ * GeoIP lookup using https://cat.eduroam.org/user/API.php?lang=pl&action=locateUser
+ */
+public class GEOIP extends AsyncTask {
+
+ String country="";
+ String region="";
+ public Double latx,longx;
+ private Boolean hasLocation=false;
+ Activity activity;
+
+
+ public GEOIP(Activity activity)
+ {
+ this.activity=activity;
+ }
+
+ //set user facing text to warn GeoIP starting. May incur permissions request.
+ protected void onPreExecute() {
+ super.onPreExecute();
+ eduroamCAT.debug("starting geoip...");
+ String loadingProfiles = activity.getString(R.string.scad_geoip_trying);
+ Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_geoip_title)+"
" + loadingProfiles);
+ if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
+ if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
+ }
+
+ //deal with result
+ protected void onPostExecute(String result) {
+ super.onPostExecute(result);
+ eduroamCAT.debug("GeoIP result:"+result);
+ if (result.length() > 0) {
+ try {
+ if (ConfigureFragment.idptext != null)
+ ConfigureFragment.idptext.setVisibility(View.VISIBLE);
+ JSONObject item = new JSONObject(result);
+ //eduroamCAT.debug("JSON GEOIP Length " + item.length());
+ String country = "";
+ country = item.getString("country");
+ if (item.has("geo")) {
+ if (item.optJSONArray("geo") != null) {
+ //multiple lat/long pairs
+ JSONArray geo = item.optJSONArray("geo");
+ for (int j = 0; j < geo.length(); j++) {
+ JSONObject geo_multi = geo.getJSONObject(j);
+ latx = geo_multi.getDouble("lat");
+ longx = geo_multi.getDouble("lon");
+ }
+ } else {
+ //one lat/long pair
+ JSONObject geo = item.getJSONObject("geo");
+ latx = geo.getDouble("lat");
+ longx = geo.getDouble("lon");
+ }
+ //eduroamCAT.debug("GEOIP GOT: " + latx + " and " + longx);
+ hasLocation=true;
+ ViewProfiles.adapter.notifyDataSetChanged();
+ }
+ } catch (JSONException e) {
+ String error_message = "";
+ if (result.length() > 0) error_message = "Error=" + result;
+ Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_geoip_failed)+"
" + error_message);
+ if (ConfigureFragment.idptext != null)
+ ConfigureFragment.idptext.setText(idp_nearby);
+ if (ConfigureFragment.scadProgress != null)
+ ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
+ //eduroamCAT.alertUser("GeoIP Failed","GeoIP Failed",activity);
+ }
+ }
+ else
+ {
+ eduroamCAT.debug("NO result for GEOIP lookup");
+ }
+
+ if (result.length()>0)
+ {
+ ConfigureFragment.setupSCAD();
+ String loadingProfiles = activity.getString(R.string.scad_geoip_success);
+ Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_geoip_title)+"
" + loadingProfiles);
+ if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
+ if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
+ }
+ }
+
+
+ @Override
+ protected String doInBackground(String... params) {
+ String str = "";
+ HttpResponse response;
+ HttpClient myClient = new DefaultHttpClient();
+ String lang="";
+ lang = Locale.getDefault().getLanguage();
+ HttpPost myConnection = new HttpPost("https://cat.eduroam.org/user/API.php?lang=pl&action=locateUser");
+ try {
+ eduroamCAT.debug("Getting geoip location from cat.eduroam.org ");
+ response = myClient.execute(myConnection);
+ str = EntityUtils.toString(response.getEntity(), "UTF-8");
+ //eduroamCAT.debug("Content="+str);
+ } catch (Exception e) {
+ eduroamCAT.debug(e.getMessage());
+ }
+ return str;
+ }
+
+ //set only if location from CAT via GEOIP success
+ public boolean hasLocation()
+ {
+ return hasLocation;
+ }
+
+ //get latitude value
+ public Double getLatitude()
+ {
+ return latx;
+ }
+
+ //get longitude
+ public Double getLongitude()
+ {
+ return longx;
+ }
+
+}
diff --git a/src/uk/ac/swansea/eduroamcat/IdP.java b/src/uk/ac/swansea/eduroamcat/IdP.java
index ff70373..ff87db8 100644
--- a/src/uk/ac/swansea/eduroamcat/IdP.java
+++ b/src/uk/ac/swansea/eduroamcat/IdP.java
@@ -1,179 +1,179 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.util.EntityUtils;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import android.graphics.Bitmap;
-import android.os.AsyncTask;
-import android.view.View;
-
-public class IdP extends AsyncTask {
-
- public String title;
- public float distance;
- public int id;
- public List profileID = new ArrayList();
- public List profileDisplay = new ArrayList();
- public List profileRedirected = new ArrayList();
- public List downloads = new ArrayList();
- //public List profileHasLogo = new ArrayList();
- public boolean profileHasLogo = false;
- public String profileRedirect="";
- public String download;
- String jsonString = "";
- String androidID="";
- String lang="en";
- public Bitmap logo;
-
- public IdP(String title, int id, float distance)
- {
- this.title=title;
- this.id=id;
- this.distance=distance;
- int currentapiVersion = android.os.Build.VERSION.SDK_INT;
- if (currentapiVersion == 26) androidID="android_oreo";
- else if (currentapiVersion == 25) androidID="android_nougat";
- else if (currentapiVersion == 24) androidID="android_marshmallow";
- else if (currentapiVersion == 23) androidID="android_marshmallow";
- else if (currentapiVersion == 22) androidID="android_lollipop";
- else if (currentapiVersion == 21) androidID="android_lollipop";
- else if (currentapiVersion == 20) androidID="android_kitkat";
- else if (currentapiVersion == 19) androidID="android_kitkat";
- else if (currentapiVersion == 18) androidID="android_43";
- else androidID="android_kitkat";
-
- lang= Locale.getDefault().getLanguage();
- }
-
- public int getDistance()
- {
- return Math.round(this.distance/1000);
- }
-
- public void getProfileID()
- {
- //https://cat.eduroam.org/user/API.php?action=listProfiles&id=1
- }
-
- public String getName()
- {
- return title;
- }
-
- protected void onPreExecute() {
- super.onPreExecute();
- //String loadingProfiles = getString(R.string.loading_profiles);
- //http://stackoverflow.com/questions/11814060/onpostexecute-getresources-getstring-nullpointerexception
-// String loadingProfiles = "Loading Profiles...";
-// Spanned idp_nearby = Html.fromHtml("SCAD Discovery...
" + loadingProfiles);
-// if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
-// if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
- }
-
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- //eduroamCAT.debug("RESULT="+result);
- try {
- JSONObject allJSON = new JSONObject(result);
- if (allJSON.has("data")) {
- eduroamCAT.debug("adding download link...");
- JSONArray item = allJSON.getJSONArray("data");
- //eduroamCAT.debug("data="+item.toString());
- if (item.length()>1) {
- for (int j=0; j
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import android.graphics.Bitmap;
+import android.os.AsyncTask;
+import android.view.View;
+
+public class IdP extends AsyncTask {
+
+ public String title;
+ public float distance;
+ public int id;
+ public List profileID = new ArrayList();
+ public List profileDisplay = new ArrayList();
+ public List profileRedirected = new ArrayList();
+ public List downloads = new ArrayList();
+ //public List profileHasLogo = new ArrayList();
+ public boolean profileHasLogo = false;
+ public String profileRedirect="";
+ public String download;
+ String jsonString = "";
+ String androidID="";
+ String lang="en";
+ public Bitmap logo;
+
+ public IdP(String title, int id, float distance)
+ {
+ this.title=title;
+ this.id=id;
+ this.distance=distance;
+ int currentapiVersion = android.os.Build.VERSION.SDK_INT;
+ if (currentapiVersion == 26) androidID="android_oreo";
+ else if (currentapiVersion == 25) androidID="android_nougat";
+ else if (currentapiVersion == 24) androidID="android_marshmallow";
+ else if (currentapiVersion == 23) androidID="android_marshmallow";
+ else if (currentapiVersion == 22) androidID="android_lollipop";
+ else if (currentapiVersion == 21) androidID="android_lollipop";
+ else if (currentapiVersion == 20) androidID="android_kitkat";
+ else if (currentapiVersion == 19) androidID="android_kitkat";
+ else if (currentapiVersion == 18) androidID="android_43";
+ else androidID="android_kitkat";
+
+ lang= Locale.getDefault().getLanguage();
+ }
+
+ public int getDistance()
+ {
+ return Math.round(this.distance/1000);
+ }
+
+ public void getProfileID()
+ {
+ //https://cat.eduroam.org/user/API.php?action=listProfiles&id=1
+ }
+
+ public String getName()
+ {
+ return title;
+ }
+
+ protected void onPreExecute() {
+ super.onPreExecute();
+ //String loadingProfiles = getString(R.string.loading_profiles);
+ //http://stackoverflow.com/questions/11814060/onpostexecute-getresources-getstring-nullpointerexception
+// String loadingProfiles = "Loading Profiles...";
+// Spanned idp_nearby = Html.fromHtml("SCAD Discovery...
" + loadingProfiles);
+// if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
+// if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
+ }
+
+ protected void onPostExecute(String result) {
+ super.onPostExecute(result);
+ //eduroamCAT.debug("RESULT="+result);
+ try {
+ JSONObject allJSON = new JSONObject(result);
+ if (allJSON.has("data")) {
+ eduroamCAT.debug("adding download link...");
+ JSONArray item = allJSON.getJSONArray("data");
+ //eduroamCAT.debug("data="+item.toString());
+ if (item.length()>1) {
+ for (int j=0; j
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import android.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-import android.util.TypedValue;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.ImageView;
-import android.widget.LinearLayout;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import java.util.ArrayList;
-import java.util.Locale;
-
-public class ProfileAdapter extends ArrayAdapter {
-
- public ProfileAdapter(Context context, ArrayList idps) {
- super(context, 0, idps);
- }
-
- String lang= Locale.getDefault().getLanguage();
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- final IdP aIdP = getItem(position);
- // Check if an existing view is being reused, otherwise inflate the view
- if (convertView == null) {
- convertView = LayoutInflater.from(getContext()).inflate(R.layout.profile_item, parent, false);
- }
- // Lookup view for data population
- TextView firstLine = (TextView) convertView.findViewById(R.id.firstLine);
- TextView secondLine = (TextView) convertView.findViewById(R.id.secondLine);
- ImageView logo = (ImageView) convertView.findViewById(R.id.icon);
- if (aIdP.profileHasLogo) {
- //eduroamCAT.debug("has logo set");
- logo.setImageBitmap(aIdP.logo);
- }
-
- // Populate the data into the template view using the data object
- firstLine.setText(aIdP.getName());
- if (aIdP.getDistance() < 1000)
- secondLine.setText(getContext().getString(R.string.distance) + "=" + aIdP.getDistance() + "Km");
- else secondLine.setText("");
-
- if (aIdP.profileID.size() > 1) {
- //add buttons for multiple profiles
- LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.profiles);
- RelativeLayout item = (RelativeLayout) convertView.findViewById(R.id.itemlayout);
- ViewGroup.LayoutParams params = item.getLayoutParams();
- params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
- TextView idpName = new TextView(getContext());
- idpName.setText(aIdP.getName() + ":");
- idpName.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
- layout.removeAllViews();
- layout.addView(idpName);
- for (final String profile : aIdP.profileDisplay) {
- Button btnTag = new Button(getContext());
- btnTag.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
- btnTag.setText(profile);
- btnTag.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- Uri uri = Uri.parse(aIdP.getDownload(profile));
- eduroamCAT.debug("Click Download:"+uri.toString());
- Intent download = new Intent(getContext(), EAPMetadata.class);
- download.setData(uri);
- getContext().startActivity(download);
- eduroamCAT.debug("started activity");
- }
- });
- layout.addView(btnTag);
- }
- }
- return convertView;
- }
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.util.TypedValue;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+import java.util.ArrayList;
+import java.util.Locale;
+
+public class ProfileAdapter extends ArrayAdapter {
+
+ public ProfileAdapter(Context context, ArrayList idps) {
+ super(context, 0, idps);
+ }
+
+ String lang= Locale.getDefault().getLanguage();
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ final IdP aIdP = getItem(position);
+ // Check if an existing view is being reused, otherwise inflate the view
+ if (convertView == null) {
+ convertView = LayoutInflater.from(getContext()).inflate(R.layout.profile_item, parent, false);
+ }
+ // Lookup view for data population
+ TextView firstLine = (TextView) convertView.findViewById(R.id.firstLine);
+ TextView secondLine = (TextView) convertView.findViewById(R.id.secondLine);
+ ImageView logo = (ImageView) convertView.findViewById(R.id.icon);
+ if (aIdP.profileHasLogo) {
+ //eduroamCAT.debug("has logo set");
+ logo.setImageBitmap(aIdP.logo);
+ }
+
+ // Populate the data into the template view using the data object
+ firstLine.setText(aIdP.getName());
+ if (aIdP.getDistance() < 1000)
+ secondLine.setText(getContext().getString(R.string.distance) + "=" + aIdP.getDistance() + "Km");
+ else secondLine.setText("");
+
+ if (aIdP.profileID.size() > 1) {
+ //add buttons for multiple profiles
+ LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.profiles);
+ RelativeLayout item = (RelativeLayout) convertView.findViewById(R.id.itemlayout);
+ ViewGroup.LayoutParams params = item.getLayoutParams();
+ params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
+ TextView idpName = new TextView(getContext());
+ idpName.setText(aIdP.getName() + ":");
+ idpName.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
+ layout.removeAllViews();
+ layout.addView(idpName);
+ for (final String profile : aIdP.profileDisplay) {
+ Button btnTag = new Button(getContext());
+ btnTag.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ btnTag.setText(profile);
+ btnTag.setOnClickListener(new View.OnClickListener() {
+ public void onClick(View v) {
+ Uri uri = Uri.parse(aIdP.getDownload(profile));
+ eduroamCAT.debug("Click Download:"+uri.toString());
+ Intent download = new Intent(getContext(), EAPMetadata.class);
+ download.setData(uri);
+ getContext().startActivity(download);
+ eduroamCAT.debug("started activity");
+ }
+ });
+ layout.addView(btnTag);
+ }
+ }
+ return convertView;
+ }
}
\ No newline at end of file
diff --git a/src/uk/ac/swansea/eduroamcat/ProfileAttributes.java b/src/uk/ac/swansea/eduroamcat/ProfileAttributes.java
index 6df074f..0cade42 100644
--- a/src/uk/ac/swansea/eduroamcat/ProfileAttributes.java
+++ b/src/uk/ac/swansea/eduroamcat/ProfileAttributes.java
@@ -1,112 +1,112 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-
-import java.util.Locale;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.util.EntityUtils;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import android.os.AsyncTask;
-
-
-public class ProfileAttributes extends AsyncTask {
-
- int profileID;
- int profile;
- int status=1;
- String redirect;
- String jsonString = "";
- boolean redirected=false;
- String androidID="";
- IdP aIdP;
-
- public ProfileAttributes (int profileID,IdP idp)
- {
- this.profileID=profileID;
- this.aIdP=idp;
- //eduroamCAT.debug("profile attributes....");
- int currentapiVersion = android.os.Build.VERSION.SDK_INT;
- if (currentapiVersion == 26) androidID="android_oreo";
- else if (currentapiVersion == 25) androidID="android_nougat";
- else if (currentapiVersion == 24) androidID="android_marshmallow";
- else if (currentapiVersion == 23) androidID="android_marshmallow";
- else if (currentapiVersion == 22) androidID="android_lollipop";
- else if (currentapiVersion == 21) androidID="android_lollipop";
- else if (currentapiVersion == 20) androidID="android_kitkat";
- else if (currentapiVersion == 19) androidID="android_kitkat";
- else if (currentapiVersion == 18) androidID="android_43";
- else androidID="android_kitkat";
- }
-
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- redirect="0";
- try {
- JSONObject allJSON = new JSONObject(result);
- if (allJSON.has("data")) {
- JSONObject item1 = allJSON.getJSONObject("data");
- JSONArray item = item1.getJSONArray("devices");
- if (item.length() > 1) {
- for (int j = 0; j < item.length(); j++) {
- JSONObject iditem = (JSONObject) item.get(j);
- String os = iditem.getString("id");
- if (os.equals(androidID) || os.equals("0")) {
- redirect = iditem.getString("redirect");
- aIdP.profileRedirect=redirect;
- status = iditem.getInt("status");
- if (redirect.length()>1) redirected=true;
- //eduroamCAT.debug("redirect for os=" + os + "="+ redirect);
- }
- }
- } else {
- JSONObject iditem = (JSONObject) item.get(0);
- String os = iditem.getString("id");
- if (os.equals(androidID) || os.equals("0")) {
- redirect = iditem.getString("redirect");
- aIdP.profileRedirect=redirect;
- status = iditem.getInt("status");
- if (redirect.length()>1) redirected=true;
- //eduroamCAT.debug("redirect for os=" + os + "="+ redirect);
- }
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- aIdP.profileRedirected.add(redirect);
- if (redirect.length()>0) aIdP.updateDisplay();
- }
-
-
- @Override
- protected String doInBackground(String... params) {
- String str = "";
- HttpResponse response;
- HttpClient myClient = new DefaultHttpClient();
- String lang="";
- lang = Locale.getDefault().getLanguage();
- //HttpPost myConnection = new HttpPost("https://cat-test.eduroam.org/branch/user/API.php?action=profileAttributes&id="+profileID+"&lang="+lang);
- HttpPost myConnection = new HttpPost("https://cat.eduroam.org/user/API.php?action=profileAttributes&id="+profileID+"&lang="+lang);
- try {
- //eduroamCAT.debug("Getting profile attributes "+profileID);
- response = myClient.execute(myConnection);
- str = EntityUtils.toString(response.getEntity(), "UTF-8");
- //eduroamCAT.debug("Content="+str);
- } catch (Exception e) {
- eduroamCAT.debug(e.getMessage());
- }
- this.jsonString=str;
- return str;
- }
-
-
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+
+import java.util.Locale;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import android.os.AsyncTask;
+
+
+public class ProfileAttributes extends AsyncTask {
+
+ int profileID;
+ int profile;
+ int status=1;
+ String redirect;
+ String jsonString = "";
+ boolean redirected=false;
+ String androidID="";
+ IdP aIdP;
+
+ public ProfileAttributes (int profileID,IdP idp)
+ {
+ this.profileID=profileID;
+ this.aIdP=idp;
+ //eduroamCAT.debug("profile attributes....");
+ int currentapiVersion = android.os.Build.VERSION.SDK_INT;
+ if (currentapiVersion == 26) androidID="android_oreo";
+ else if (currentapiVersion == 25) androidID="android_nougat";
+ else if (currentapiVersion == 24) androidID="android_marshmallow";
+ else if (currentapiVersion == 23) androidID="android_marshmallow";
+ else if (currentapiVersion == 22) androidID="android_lollipop";
+ else if (currentapiVersion == 21) androidID="android_lollipop";
+ else if (currentapiVersion == 20) androidID="android_kitkat";
+ else if (currentapiVersion == 19) androidID="android_kitkat";
+ else if (currentapiVersion == 18) androidID="android_43";
+ else androidID="android_kitkat";
+ }
+
+ protected void onPostExecute(String result) {
+ super.onPostExecute(result);
+ redirect="0";
+ try {
+ JSONObject allJSON = new JSONObject(result);
+ if (allJSON.has("data")) {
+ JSONObject item1 = allJSON.getJSONObject("data");
+ JSONArray item = item1.getJSONArray("devices");
+ if (item.length() > 1) {
+ for (int j = 0; j < item.length(); j++) {
+ JSONObject iditem = (JSONObject) item.get(j);
+ String os = iditem.getString("id");
+ if (os.equals(androidID) || os.equals("0")) {
+ redirect = iditem.getString("redirect");
+ aIdP.profileRedirect=redirect;
+ status = iditem.getInt("status");
+ if (redirect.length()>1) redirected=true;
+ //eduroamCAT.debug("redirect for os=" + os + "="+ redirect);
+ }
+ }
+ } else {
+ JSONObject iditem = (JSONObject) item.get(0);
+ String os = iditem.getString("id");
+ if (os.equals(androidID) || os.equals("0")) {
+ redirect = iditem.getString("redirect");
+ aIdP.profileRedirect=redirect;
+ status = iditem.getInt("status");
+ if (redirect.length()>1) redirected=true;
+ //eduroamCAT.debug("redirect for os=" + os + "="+ redirect);
+ }
+ }
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ aIdP.profileRedirected.add(redirect);
+ if (redirect.length()>0) aIdP.updateDisplay();
+ }
+
+
+ @Override
+ protected String doInBackground(String... params) {
+ String str = "";
+ HttpResponse response;
+ HttpClient myClient = new DefaultHttpClient();
+ String lang="";
+ lang = Locale.getDefault().getLanguage();
+ //HttpPost myConnection = new HttpPost("https://cat-test.eduroam.org/branch/user/API.php?action=profileAttributes&id="+profileID+"&lang="+lang);
+ HttpPost myConnection = new HttpPost("https://cat.eduroam.org/user/API.php?action=profileAttributes&id="+profileID+"&lang="+lang);
+ try {
+ //eduroamCAT.debug("Getting profile attributes "+profileID);
+ response = myClient.execute(myConnection);
+ str = EntityUtils.toString(response.getEntity(), "UTF-8");
+ //eduroamCAT.debug("Content="+str);
+ } catch (Exception e) {
+ eduroamCAT.debug(e.getMessage());
+ }
+ this.jsonString=str;
+ return str;
+ }
+
+
+}
diff --git a/src/uk/ac/swansea/eduroamcat/ProfileLogo.java b/src/uk/ac/swansea/eduroamcat/ProfileLogo.java
index 5ea303f..bace3e4 100644
--- a/src/uk/ac/swansea/eduroamcat/ProfileLogo.java
+++ b/src/uk/ac/swansea/eduroamcat/ProfileLogo.java
@@ -1,54 +1,54 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import java.io.InputStream;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.os.AsyncTask;
-
-
-public class ProfileLogo extends AsyncTask {
-
- int idpID;
- int profile;
- String androidID="";
- IdP aIdP;
-
- public ProfileLogo (int idpID,IdP idp)
- {
- this.idpID=idpID;
- this.aIdP=idp;
- //eduroamCAT.debug("profile logo....");
- }
-
- protected void onPostExecute(Bitmap result) {
- super.onPostExecute(result);
- if (result!=null) {
- aIdP.logo = result;
- //eduroamCAT.debug("got logo for " + idpID + " and got " + result.toString());
- }
- ViewProfiles.adapter.notifyDataSetChanged();
-
-}
-
-
- @Override
- protected Bitmap doInBackground(String... params) {
- Bitmap logo = null;
- String url = "https://cat.eduroam.org/user/API.php?action=sendLogo&id="+idpID+"";
- try {
- //eduroamCAT.debug("Getting profile logo "+idpID);
- InputStream in = new java.net.URL(url).openStream();
- logo = BitmapFactory.decodeStream(in);
- } catch (Exception e) {
- eduroamCAT.debug(e.getMessage());
- }
- return logo;
- }
-
-
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import java.io.InputStream;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.os.AsyncTask;
+
+
+public class ProfileLogo extends AsyncTask {
+
+ int idpID;
+ int profile;
+ String androidID="";
+ IdP aIdP;
+
+ public ProfileLogo (int idpID,IdP idp)
+ {
+ this.idpID=idpID;
+ this.aIdP=idp;
+ //eduroamCAT.debug("profile logo....");
+ }
+
+ protected void onPostExecute(Bitmap result) {
+ super.onPostExecute(result);
+ if (result!=null) {
+ aIdP.logo = result;
+ //eduroamCAT.debug("got logo for " + idpID + " and got " + result.toString());
+ }
+ ViewProfiles.adapter.notifyDataSetChanged();
+
+}
+
+
+ @Override
+ protected Bitmap doInBackground(String... params) {
+ Bitmap logo = null;
+ String url = "https://cat.eduroam.org/user/API.php?action=sendLogo&id="+idpID+"";
+ try {
+ //eduroamCAT.debug("Getting profile logo "+idpID);
+ InputStream in = new java.net.URL(url).openStream();
+ logo = BitmapFactory.decodeStream(in);
+ } catch (Exception e) {
+ eduroamCAT.debug(e.getMessage());
+ }
+ return logo;
+ }
+
+
+}
diff --git a/src/uk/ac/swansea/eduroamcat/ProfilesStorage.java b/src/uk/ac/swansea/eduroamcat/ProfilesStorage.java
index ad394f0..a0a30d7 100644
--- a/src/uk/ac/swansea/eduroamcat/ProfilesStorage.java
+++ b/src/uk/ac/swansea/eduroamcat/ProfilesStorage.java
@@ -1,422 +1,422 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import java.io.UnsupportedEncodingException;
-import java.security.KeyStoreException;
-import java.util.ArrayList;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.database.DatabaseUtils;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteOpenHelper;
-import android.util.Log;
-
-public class ProfilesStorage extends SQLiteOpenHelper {
-
- private static final String DATABASE_NAME = "eduroamProfiles.db";
- private static final int DATABASE_VERSION = 2;
-
- //EAP CONFIG TABLE
- public static final String TABLE_NAME_EAP = "eapProfiles";
- public static final String COLUMN_ID_EAP = "id_eap";
- public static final String COLUMN_COMMENT = "comment";
-
- //AUTH CONFIG TABLE
- public static final String TABLE_NAME_AUTH = "authProfiles";
- public static final String COLUMN_ID_AUTH = "id_auth";
- public static final String COLUMN_COMMENT_AUTH = "comment";
-
- //WIFI CONFIG TABLE
- public static final String TABLE_NAME_WIFI = "wifiProfiles";
- public static final String COLUMN_ID_WIFI = "id_wifi";
- public static final String COLUMN_COMMENT2 = "comment";
-
- //USER TABLE
- public static final String TABLE_NAME_USER = "userProfiles";
- public static final String COLUMN_ID_USER = "id_user";
-
- // Database creation sql statement
- private static final String DATABASE_CREATE_EAP = "create table IF NOT EXISTS "
- + TABLE_NAME_EAP + "("
- + COLUMN_ID_EAP
- + " integer primary key autoincrement, "
- + "EAPIdP_ID"
- + " text, "
- + "displayName"
- + " text, "
- + "displayNameLang"
- + " text, "
- + "description"
- + " text, "
- + "logo"
- + " text, "
- + "terms"
- + " text, "
- + "emails"
- + " text, "
- + "phone"
- + " text, "
- + "web"
- + " text"
- + ");";
-
- private static final String DATABASE_CREATE_AUTH = "create table IF NOT EXISTS "
- + TABLE_NAME_AUTH + "("
- + COLUMN_ID_AUTH
- + " integer primary key autoincrement, "
- + COLUMN_ID_EAP
- + " integer, "
- + "outterEAPType"
- + " integer,"
- + "innerEAPType"
- + " integer,"
- + "innerNonEAPType"
- + " integer,"
- + "CAencoding"
- + " text,"
- + "CAformat"
- + " text,"
- + "serverIDs"
- + " text,"
- + "clientCert"
- + " text,"
- + "clientCertEncoding"
- + " text,"
- + "clientCertFormat"
- + " text,"
- + "anonID"
- + " text,"
- + "anonID_save"
- + " integer,"
- + "CAcert"
- + " text,"
- + "clientCertPass"
- + " text"
- + ");";
-
- private static final String DATABASE_CREATE_WIFI = "create table IF NOT EXISTS "
- + TABLE_NAME_WIFI + "("
- + COLUMN_ID_WIFI
- + " integer primary key autoincrement, "
- + COLUMN_ID_EAP
- + " integer, "
- + "ssid"
- + " text,"
- + "authType"
- + " text,"
- + "encType"
- + " text,"
- + "ssidPriority"
- + " integer,"
- + "autoJoin"
- + " integer"
- + ");";
-
- private static final String DATABASE_CREATE_USER = "create table IF NOT EXISTS "
- + TABLE_NAME_USER + "("
- + COLUMN_ID_USER
- + " integer primary key autoincrement, "
- + "username"
- + " text"
- + ");";
-
- public ProfilesStorage(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
-
- @Override
- public void onCreate(SQLiteDatabase database) {
- database.execSQL(DATABASE_CREATE_EAP);
- database.execSQL(DATABASE_CREATE_AUTH);
- database.execSQL(DATABASE_CREATE_WIFI);
- database.execSQL(DATABASE_CREATE_USER);
- eduroamCAT.debug("Created DBs");
- }
-
- public long insertWiFi (String ID_EAP, String ssid, String authType, String encType, int ssidPriority, int autoJoin)
- {
- SQLiteDatabase db = this.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("ID_EAP", ID_EAP);
- contentValues.put("ssid", ssid);
- contentValues.put("authType", authType);
- contentValues.put("encType", encType);
- contentValues.put("ssidPriority", ssidPriority);
- contentValues.put("autoJoin", autoJoin);
- long result = db.insert(TABLE_NAME_WIFI, null, contentValues);
- db.close();
- return result;
- }
-
- public long insertEAP (String EAPIdP_ID, String displayName, String displayNameLang, String description, String logo, String terms, String emails,
- String phone, String web)
- {
- SQLiteDatabase db = this.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("EAPIdP_ID", EAPIdP_ID);
- contentValues.put("displayName", displayName);
- contentValues.put("displayNameLang", displayNameLang);
- contentValues.put("description", description);
- contentValues.put("logo", logo);
- contentValues.put("terms", terms);
- contentValues.put("emails", emails);
- contentValues.put("phone", phone);
- contentValues.put("web", web);
- long result = db.insert(TABLE_NAME_EAP, null, contentValues);
- db.close();
- return result;
- }
-
- public long insertAuth (String ID_EAP, int outterEAPType, int innerEAPType, int innerNonEAPType, String CAencoding, String CAformat,
- String serverIDs, String clientCert, String clientCertEncoding, String clientCertFormat, String clientCertPass, String anonID, int anonID_save, String CAcert)
- {
- SQLiteDatabase db = this.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("ID_EAP", ID_EAP);
- contentValues.put("outterEAPType", outterEAPType);
- contentValues.put("innerEAPType", innerEAPType);
- contentValues.put("innerNonEAPType", innerNonEAPType);
- contentValues.put("CAencoding", CAencoding);
- contentValues.put("CAformat", CAformat);
- contentValues.put("serverIDs", serverIDs);
- contentValues.put("clientCert", clientCert);
- contentValues.put("clientCertEncoding", clientCertEncoding);
- contentValues.put("clientCertFormat", clientCertFormat);
- contentValues.put("anonID", anonID);
- contentValues.put("anonID_save", anonID_save);
- contentValues.put("CAcert", CAcert);
- contentValues.put("clientCertPass", clientCertPass);
- long result = db.insert(TABLE_NAME_AUTH, null, contentValues);
- db.close();
- return result;
- }
-
- public long insertUSER (String username)
- {
- SQLiteDatabase db = this.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("username", username);
- long result = db.insert(TABLE_NAME_USER, null, contentValues);
- db.close();
- return result;
- }
-
- public WiFiProfile getWiFi(int id){
- WiFiProfile temp = new WiFiProfile();
- SQLiteDatabase db = this.getReadableDatabase();
- Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI+" where ID_EAP ="+id+"", null );
- if (res.moveToFirst()){
- res.moveToFirst();
- temp.isOK();
- temp.setSSID(res.getString(2));
- temp.setAuthType(res.getString(3));
- temp.setEncryptionType(res.getString(4));
- temp.setSSIDPriority(res.getInt(5));
- if (res.getInt(6)==1) temp.setAutojoin(true);
- else temp.setAutojoin(false);
- }
- else
- {
- temp.hasError();
- return temp;
- }
- db.close();
- return temp;
- }
-
- public WiFiProfile getWiFi(String ssid){
- WiFiProfile temp = new WiFiProfile();
- SQLiteDatabase db = this.getReadableDatabase();
- Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI+" where ssid ='"+ssid+"'", null );
- if (res.moveToFirst()){
- res.moveToFirst();
- temp.isOK();
- temp.setSSID(res.getString(2));
- temp.setAuthType(res.getString(3));
- temp.setEncryptionType(res.getString(4));
- temp.setSSIDPriority(res.getInt(5));
- if (res.getInt(6)==1) temp.setAutojoin(true);
- else temp.setAutojoin(false);
- }
- else
- {
- temp.hasError();
- return temp;
- }
- db.close();
- return temp;
- }
-
- public ArrayList getWiFi_all(){
- ArrayList templist = new ArrayList();
- SQLiteDatabase db = this.getReadableDatabase();
- //Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI+" where ID_EAP ="+id+"", null );
- Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI, null );
- if (res.moveToFirst()){
- res.moveToFirst();
- while (!res.isAfterLast())
- {
- WiFiProfile temp = new WiFiProfile();
- temp.isOK();
- temp.setSSID(res.getString(2));
- templist.add(temp.getSSID());
- temp=null;
- res.moveToNext();
- eduroamCAT.debug("loop");
- }
- }
- else
- {
- return templist;
- }
- db.close();
- return templist;
- }
-
- public ArrayList getEAPProfiles(){
- SQLiteDatabase db = this.getReadableDatabase();
- ArrayList tempProfiles = new ArrayList();
- Cursor res = db.rawQuery( "select * from "+TABLE_NAME_EAP, null );
- if (res.moveToFirst()){
- while (!res.isAfterLast())
- {
- ConfigProfile tempProfile = new ConfigProfile();
- tempProfile.setEAPIdP_ID(res.getString(1));
- tempProfile.setDisplayName(res.getString(2), res.getString(3));
- tempProfile.setDescription(res.getString(4),"");
- if (res.getString(5).length()>0) tempProfile.setLogo(res.getString(5), "", "jpg");
- if (res.getString(6).length()>0) tempProfile.setTermsOfUse(res.getString(6));
- if (res.getString(7).length()>0) { tempProfile.setHelpdeskEmail(res.getString(7), ""); tempProfile.setHelpdeskInfo(true); }
- if (res.getString(8).length()>0) { tempProfile.setHelpdeskPhone(res.getString(8), ""); tempProfile.setHelpdeskInfo(true); }
- if (res.getString(9).length()>0) { tempProfile.setHelpdeskURL(res.getString(9), ""); tempProfile.setHelpdeskInfo(true); }
- //look up any auth methods for eap profile
- Cursor res2 = db.rawQuery( "select * from "+TABLE_NAME_AUTH+" where ID_EAP='"+tempProfile.getEAPIdP_ID()+"'", null );
- if (res2.moveToFirst()){
- while (!res2.isAfterLast())
- {
- AuthenticationMethod tempAuthMethod = new AuthenticationMethod();
- if (res2.getInt(2)>0) tempAuthMethod.setOuterEAPType(res2.getInt(2));
- if (res2.getInt(3)>0) tempAuthMethod.setInnerEAPType(res2.getInt(3));
- if (res2.getInt(4)>0) tempAuthMethod.setInnerNonEAPType(res2.getInt(4));
- try {
- if (res2.getString(13).length()>0) tempAuthMethod.setCAcert(res2.getString(13), res2.getString(6), res2.getString(5));
- eduroamCAT.debug("CERT="+res2.getString(13)+" format="+res2.getString(6)+" encoding="+res2.getString(5));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- if (res2.getString(7).length()>0) {
- String[] temp = res2.getString(7).split(";");
- for (int x = 0; x < temp.length; x++) {
- tempAuthMethod.addServerID(temp[x]);
- }
- }
- if (res2.getString(11).length()>0) tempAuthMethod.setAnonID(res2.getString(11), true);
- if (res2.getString(8).length()>0)
- try {
- tempAuthMethod.loadClientCert(res2.getString(8), res2.getString(10), res2.getString(9),res2.getString(14));
- } catch (KeyStoreException e) {
- e.printStackTrace();
- }
- tempProfile.addAuthenticationMethod(tempAuthMethod);
- res2.moveToNext();
- }
- }
- tempProfiles.add(tempProfile);
- res.moveToNext();
- }
- }
- else
- {
- return tempProfiles;
- }
- db.close();
- return tempProfiles;
- }
-
- public String getUser(){
- String username="";
- SQLiteDatabase db = this.getReadableDatabase();
- Cursor res = db.rawQuery( "select * from "+TABLE_NAME_USER, null );
- if (res.moveToLast()){
- res.moveToLast();
- username=res.getString(1);
- }
- else
- {
- return "";
- }
- db.close();
- return username;
- }
-
-
- public boolean deleteWiFi ()
- {
- SQLiteDatabase db = this.getWritableDatabase();
- db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_WIFI);
- db.execSQL(DATABASE_CREATE_WIFI);
- db.close();
- return true;
- }
-
- public boolean deleteAllProfiles ()
- {
- SQLiteDatabase db = this.getWritableDatabase();
- db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_EAP);
- db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_AUTH);
- db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_USER);
- db.execSQL(DATABASE_CREATE_EAP);
- db.execSQL(DATABASE_CREATE_AUTH);
- db.execSQL(DATABASE_CREATE_USER);
- db.close();
- return true;
- }
-
- public int numberOfRowsWiFi(){
- SQLiteDatabase db = this.getReadableDatabase();
- int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_WIFI);
- db.close();
- return numRows;
- }
-
- public int numberOfRowsEAP(){
- SQLiteDatabase db = this.getReadableDatabase();
- int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_EAP);
- db.close();
- return numRows;
- }
-
- public int numberOfRowsAUTH(){
- SQLiteDatabase db = this.getReadableDatabase();
- int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_AUTH);
- db.close();
- return numRows;
- }
-
- public int numberOfRowsUSER(){
- int numRows=0;
- SQLiteDatabase db = this.getReadableDatabase();
- db.execSQL(DATABASE_CREATE_USER);
- numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_USER);
- db.close();
- return numRows;
- }
-
-
- //Need to handle this, and see how data can be migrated on upgrade
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- Log.w(ProfilesStorage.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
- db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_EAP);
- db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_AUTH);
- db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_WIFI);
- db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_USER);
- onCreate(db);
- }
-
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import java.io.UnsupportedEncodingException;
+import java.security.KeyStoreException;
+import java.util.ArrayList;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.DatabaseUtils;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.util.Log;
+
+public class ProfilesStorage extends SQLiteOpenHelper {
+
+ private static final String DATABASE_NAME = "eduroamProfiles.db";
+ private static final int DATABASE_VERSION = 2;
+
+ //EAP CONFIG TABLE
+ public static final String TABLE_NAME_EAP = "eapProfiles";
+ public static final String COLUMN_ID_EAP = "id_eap";
+ public static final String COLUMN_COMMENT = "comment";
+
+ //AUTH CONFIG TABLE
+ public static final String TABLE_NAME_AUTH = "authProfiles";
+ public static final String COLUMN_ID_AUTH = "id_auth";
+ public static final String COLUMN_COMMENT_AUTH = "comment";
+
+ //WIFI CONFIG TABLE
+ public static final String TABLE_NAME_WIFI = "wifiProfiles";
+ public static final String COLUMN_ID_WIFI = "id_wifi";
+ public static final String COLUMN_COMMENT2 = "comment";
+
+ //USER TABLE
+ public static final String TABLE_NAME_USER = "userProfiles";
+ public static final String COLUMN_ID_USER = "id_user";
+
+ // Database creation sql statement
+ private static final String DATABASE_CREATE_EAP = "create table IF NOT EXISTS "
+ + TABLE_NAME_EAP + "("
+ + COLUMN_ID_EAP
+ + " integer primary key autoincrement, "
+ + "EAPIdP_ID"
+ + " text, "
+ + "displayName"
+ + " text, "
+ + "displayNameLang"
+ + " text, "
+ + "description"
+ + " text, "
+ + "logo"
+ + " text, "
+ + "terms"
+ + " text, "
+ + "emails"
+ + " text, "
+ + "phone"
+ + " text, "
+ + "web"
+ + " text"
+ + ");";
+
+ private static final String DATABASE_CREATE_AUTH = "create table IF NOT EXISTS "
+ + TABLE_NAME_AUTH + "("
+ + COLUMN_ID_AUTH
+ + " integer primary key autoincrement, "
+ + COLUMN_ID_EAP
+ + " integer, "
+ + "outterEAPType"
+ + " integer,"
+ + "innerEAPType"
+ + " integer,"
+ + "innerNonEAPType"
+ + " integer,"
+ + "CAencoding"
+ + " text,"
+ + "CAformat"
+ + " text,"
+ + "serverIDs"
+ + " text,"
+ + "clientCert"
+ + " text,"
+ + "clientCertEncoding"
+ + " text,"
+ + "clientCertFormat"
+ + " text,"
+ + "anonID"
+ + " text,"
+ + "anonID_save"
+ + " integer,"
+ + "CAcert"
+ + " text,"
+ + "clientCertPass"
+ + " text"
+ + ");";
+
+ private static final String DATABASE_CREATE_WIFI = "create table IF NOT EXISTS "
+ + TABLE_NAME_WIFI + "("
+ + COLUMN_ID_WIFI
+ + " integer primary key autoincrement, "
+ + COLUMN_ID_EAP
+ + " integer, "
+ + "ssid"
+ + " text,"
+ + "authType"
+ + " text,"
+ + "encType"
+ + " text,"
+ + "ssidPriority"
+ + " integer,"
+ + "autoJoin"
+ + " integer"
+ + ");";
+
+ private static final String DATABASE_CREATE_USER = "create table IF NOT EXISTS "
+ + TABLE_NAME_USER + "("
+ + COLUMN_ID_USER
+ + " integer primary key autoincrement, "
+ + "username"
+ + " text"
+ + ");";
+
+ public ProfilesStorage(Context context) {
+ super(context, DATABASE_NAME, null, DATABASE_VERSION);
+ }
+
+ @Override
+ public void onCreate(SQLiteDatabase database) {
+ database.execSQL(DATABASE_CREATE_EAP);
+ database.execSQL(DATABASE_CREATE_AUTH);
+ database.execSQL(DATABASE_CREATE_WIFI);
+ database.execSQL(DATABASE_CREATE_USER);
+ eduroamCAT.debug("Created DBs");
+ }
+
+ public long insertWiFi (String ID_EAP, String ssid, String authType, String encType, int ssidPriority, int autoJoin)
+ {
+ SQLiteDatabase db = this.getWritableDatabase();
+ ContentValues contentValues = new ContentValues();
+ contentValues.put("ID_EAP", ID_EAP);
+ contentValues.put("ssid", ssid);
+ contentValues.put("authType", authType);
+ contentValues.put("encType", encType);
+ contentValues.put("ssidPriority", ssidPriority);
+ contentValues.put("autoJoin", autoJoin);
+ long result = db.insert(TABLE_NAME_WIFI, null, contentValues);
+ db.close();
+ return result;
+ }
+
+ public long insertEAP (String EAPIdP_ID, String displayName, String displayNameLang, String description, String logo, String terms, String emails,
+ String phone, String web)
+ {
+ SQLiteDatabase db = this.getWritableDatabase();
+ ContentValues contentValues = new ContentValues();
+ contentValues.put("EAPIdP_ID", EAPIdP_ID);
+ contentValues.put("displayName", displayName);
+ contentValues.put("displayNameLang", displayNameLang);
+ contentValues.put("description", description);
+ contentValues.put("logo", logo);
+ contentValues.put("terms", terms);
+ contentValues.put("emails", emails);
+ contentValues.put("phone", phone);
+ contentValues.put("web", web);
+ long result = db.insert(TABLE_NAME_EAP, null, contentValues);
+ db.close();
+ return result;
+ }
+
+ public long insertAuth (String ID_EAP, int outterEAPType, int innerEAPType, int innerNonEAPType, String CAencoding, String CAformat,
+ String serverIDs, String clientCert, String clientCertEncoding, String clientCertFormat, String clientCertPass, String anonID, int anonID_save, String CAcert)
+ {
+ SQLiteDatabase db = this.getWritableDatabase();
+ ContentValues contentValues = new ContentValues();
+ contentValues.put("ID_EAP", ID_EAP);
+ contentValues.put("outterEAPType", outterEAPType);
+ contentValues.put("innerEAPType", innerEAPType);
+ contentValues.put("innerNonEAPType", innerNonEAPType);
+ contentValues.put("CAencoding", CAencoding);
+ contentValues.put("CAformat", CAformat);
+ contentValues.put("serverIDs", serverIDs);
+ contentValues.put("clientCert", clientCert);
+ contentValues.put("clientCertEncoding", clientCertEncoding);
+ contentValues.put("clientCertFormat", clientCertFormat);
+ contentValues.put("anonID", anonID);
+ contentValues.put("anonID_save", anonID_save);
+ contentValues.put("CAcert", CAcert);
+ contentValues.put("clientCertPass", clientCertPass);
+ long result = db.insert(TABLE_NAME_AUTH, null, contentValues);
+ db.close();
+ return result;
+ }
+
+ public long insertUSER (String username)
+ {
+ SQLiteDatabase db = this.getWritableDatabase();
+ ContentValues contentValues = new ContentValues();
+ contentValues.put("username", username);
+ long result = db.insert(TABLE_NAME_USER, null, contentValues);
+ db.close();
+ return result;
+ }
+
+ public WiFiProfile getWiFi(int id){
+ WiFiProfile temp = new WiFiProfile();
+ SQLiteDatabase db = this.getReadableDatabase();
+ Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI+" where ID_EAP ="+id+"", null );
+ if (res.moveToFirst()){
+ res.moveToFirst();
+ temp.isOK();
+ temp.setSSID(res.getString(2));
+ temp.setAuthType(res.getString(3));
+ temp.setEncryptionType(res.getString(4));
+ temp.setSSIDPriority(res.getInt(5));
+ if (res.getInt(6)==1) temp.setAutojoin(true);
+ else temp.setAutojoin(false);
+ }
+ else
+ {
+ temp.hasError();
+ return temp;
+ }
+ db.close();
+ return temp;
+ }
+
+ public WiFiProfile getWiFi(String ssid){
+ WiFiProfile temp = new WiFiProfile();
+ SQLiteDatabase db = this.getReadableDatabase();
+ Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI+" where ssid ='"+ssid+"'", null );
+ if (res.moveToFirst()){
+ res.moveToFirst();
+ temp.isOK();
+ temp.setSSID(res.getString(2));
+ temp.setAuthType(res.getString(3));
+ temp.setEncryptionType(res.getString(4));
+ temp.setSSIDPriority(res.getInt(5));
+ if (res.getInt(6)==1) temp.setAutojoin(true);
+ else temp.setAutojoin(false);
+ }
+ else
+ {
+ temp.hasError();
+ return temp;
+ }
+ db.close();
+ return temp;
+ }
+
+ public ArrayList getWiFi_all(){
+ ArrayList templist = new ArrayList();
+ SQLiteDatabase db = this.getReadableDatabase();
+ //Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI+" where ID_EAP ="+id+"", null );
+ Cursor res = db.rawQuery( "select * from "+TABLE_NAME_WIFI, null );
+ if (res.moveToFirst()){
+ res.moveToFirst();
+ while (!res.isAfterLast())
+ {
+ WiFiProfile temp = new WiFiProfile();
+ temp.isOK();
+ temp.setSSID(res.getString(2));
+ templist.add(temp.getSSID());
+ temp=null;
+ res.moveToNext();
+ eduroamCAT.debug("loop");
+ }
+ }
+ else
+ {
+ return templist;
+ }
+ db.close();
+ return templist;
+ }
+
+ public ArrayList getEAPProfiles(){
+ SQLiteDatabase db = this.getReadableDatabase();
+ ArrayList tempProfiles = new ArrayList();
+ Cursor res = db.rawQuery( "select * from "+TABLE_NAME_EAP, null );
+ if (res.moveToFirst()){
+ while (!res.isAfterLast())
+ {
+ ConfigProfile tempProfile = new ConfigProfile();
+ tempProfile.setEAPIdP_ID(res.getString(1));
+ tempProfile.setDisplayName(res.getString(2), res.getString(3));
+ tempProfile.setDescription(res.getString(4),"");
+ if (res.getString(5).length()>0) tempProfile.setLogo(res.getString(5), "", "jpg");
+ if (res.getString(6).length()>0) tempProfile.setTermsOfUse(res.getString(6));
+ if (res.getString(7).length()>0) { tempProfile.setHelpdeskEmail(res.getString(7), ""); tempProfile.setHelpdeskInfo(true); }
+ if (res.getString(8).length()>0) { tempProfile.setHelpdeskPhone(res.getString(8), ""); tempProfile.setHelpdeskInfo(true); }
+ if (res.getString(9).length()>0) { tempProfile.setHelpdeskURL(res.getString(9), ""); tempProfile.setHelpdeskInfo(true); }
+ //look up any auth methods for eap profile
+ Cursor res2 = db.rawQuery( "select * from "+TABLE_NAME_AUTH+" where ID_EAP='"+tempProfile.getEAPIdP_ID()+"'", null );
+ if (res2.moveToFirst()){
+ while (!res2.isAfterLast())
+ {
+ AuthenticationMethod tempAuthMethod = new AuthenticationMethod();
+ if (res2.getInt(2)>0) tempAuthMethod.setOuterEAPType(res2.getInt(2));
+ if (res2.getInt(3)>0) tempAuthMethod.setInnerEAPType(res2.getInt(3));
+ if (res2.getInt(4)>0) tempAuthMethod.setInnerNonEAPType(res2.getInt(4));
+ try {
+ if (res2.getString(13).length()>0) tempAuthMethod.setCAcert(res2.getString(13), res2.getString(6), res2.getString(5));
+ eduroamCAT.debug("CERT="+res2.getString(13)+" format="+res2.getString(6)+" encoding="+res2.getString(5));
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ if (res2.getString(7).length()>0) {
+ String[] temp = res2.getString(7).split(";");
+ for (int x = 0; x < temp.length; x++) {
+ tempAuthMethod.addServerID(temp[x]);
+ }
+ }
+ if (res2.getString(11).length()>0) tempAuthMethod.setAnonID(res2.getString(11), true);
+ if (res2.getString(8).length()>0)
+ try {
+ tempAuthMethod.loadClientCert(res2.getString(8), res2.getString(10), res2.getString(9),res2.getString(14));
+ } catch (KeyStoreException e) {
+ e.printStackTrace();
+ }
+ tempProfile.addAuthenticationMethod(tempAuthMethod);
+ res2.moveToNext();
+ }
+ }
+ tempProfiles.add(tempProfile);
+ res.moveToNext();
+ }
+ }
+ else
+ {
+ return tempProfiles;
+ }
+ db.close();
+ return tempProfiles;
+ }
+
+ public String getUser(){
+ String username="";
+ SQLiteDatabase db = this.getReadableDatabase();
+ Cursor res = db.rawQuery( "select * from "+TABLE_NAME_USER, null );
+ if (res.moveToLast()){
+ res.moveToLast();
+ username=res.getString(1);
+ }
+ else
+ {
+ return "";
+ }
+ db.close();
+ return username;
+ }
+
+
+ public boolean deleteWiFi ()
+ {
+ SQLiteDatabase db = this.getWritableDatabase();
+ db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_WIFI);
+ db.execSQL(DATABASE_CREATE_WIFI);
+ db.close();
+ return true;
+ }
+
+ public boolean deleteAllProfiles ()
+ {
+ SQLiteDatabase db = this.getWritableDatabase();
+ db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_EAP);
+ db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_AUTH);
+ db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME_USER);
+ db.execSQL(DATABASE_CREATE_EAP);
+ db.execSQL(DATABASE_CREATE_AUTH);
+ db.execSQL(DATABASE_CREATE_USER);
+ db.close();
+ return true;
+ }
+
+ public int numberOfRowsWiFi(){
+ SQLiteDatabase db = this.getReadableDatabase();
+ int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_WIFI);
+ db.close();
+ return numRows;
+ }
+
+ public int numberOfRowsEAP(){
+ SQLiteDatabase db = this.getReadableDatabase();
+ int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_EAP);
+ db.close();
+ return numRows;
+ }
+
+ public int numberOfRowsAUTH(){
+ SQLiteDatabase db = this.getReadableDatabase();
+ int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_AUTH);
+ db.close();
+ return numRows;
+ }
+
+ public int numberOfRowsUSER(){
+ int numRows=0;
+ SQLiteDatabase db = this.getReadableDatabase();
+ db.execSQL(DATABASE_CREATE_USER);
+ numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME_USER);
+ db.close();
+ return numRows;
+ }
+
+
+ //Need to handle this, and see how data can be migrated on upgrade
+ @Override
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+ Log.w(ProfilesStorage.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_EAP);
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_AUTH);
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_WIFI);
+ db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_USER);
+ onCreate(db);
+ }
+
}
\ No newline at end of file
diff --git a/src/uk/ac/swansea/eduroamcat/SCAD.java b/src/uk/ac/swansea/eduroamcat/SCAD.java
index 12742b0..7905c6c 100644
--- a/src/uk/ac/swansea/eduroamcat/SCAD.java
+++ b/src/uk/ac/swansea/eduroamcat/SCAD.java
@@ -1,303 +1,303 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Locale;
-import org.json.JSONArray;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.util.EntityUtils;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.Manifest;
-import android.app.Activity;
-import android.content.pm.PackageManager;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.support.v4.app.ActivityCompat;
-import android.support.v4.content.ContextCompat;
-import android.text.Html;
-import android.text.Spanned;
-import android.view.View;
-import android.widget.Toast;
-
-//Supplicant Configuration Discovery Process
-public class SCAD extends AsyncTask {
-
- private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 0;
- public static float MAX_DISTANCE = 30000;
- String locationProvider = LocationManager.NETWORK_PROVIDER;
- LocationManager locationManager;
- public double lat,longx=0;
- JSONObject json = null;
- String jsonString = "";
- static public ArrayList IdPs = new ArrayList();
- Location lastKnownLocation;
- Boolean hasAccuracy=false;
- String lang= Locale.getDefault().getLanguage();
- LocationListener locationListener;
- boolean network_enabled = false;
- Activity activity;
- GEOIP geoip;
- String search="";
-
- public SCAD(Activity activity,String search)
- {
- //set location
- this.activity=activity;
- this.search=search;
- //check for location permission as result of new tark sdk above sdk 23
- if (ContextCompat.checkSelfPermission(this.activity, Manifest.permission.ACCESS_COARSE_LOCATION)
- != PackageManager.PERMISSION_GRANTED) {
- eduroamCAT.debug("No Location permissions");
- // Permission is not granted
- ActivityCompat.requestPermissions(this.activity,
- new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
- MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
-
- //try geoip...
- //geoip = new GEOIP(activity);
- //geoip.execute();
- startLocationService();
- hasAccuracy = false;
- eduroamCAT.debug("Location Service permission not grantted, trying GEOIP....");
- }
- else {
- startLocationService();
- }
- }
-
- public void startLocationService()
- {
- if (ContextCompat.checkSelfPermission(this.activity, Manifest.permission.ACCESS_COARSE_LOCATION)
- == PackageManager.PERMISSION_GRANTED) {
- eduroamCAT.debug("Location Service setup....");
- locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
- // Define a listener that responds to location updates
-
- locationListener = new LocationListener() {
- public void onLocationChanged(Location location) {
- // Called when a new location is found by the network location provider.
- }
-
- public void onStatusChanged(String provider, int status, Bundle extras) {
- }
-
- public void onProviderEnabled(String provider) {
- hasAccuracy = true;
- }
-
- public void onProviderDisabled(String provider) {
- hasAccuracy = false;
- }
- };
-
- if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); }
- else {
- eduroamCAT.debug("No Network_Provider...");
- hasAccuracy = false;
- }
-
- try {
- network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
- } catch (Exception ex) {
- eduroamCAT.debug("Location Service Disabled....");
- hasAccuracy = false;
- }
-
- ConfigureFragment.setupSCAD();
- //locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
- if (search.length() < 3) {
- lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
- if (lastKnownLocation != null) {
- lat = lastKnownLocation.getLatitude();
- longx = lastKnownLocation.getLongitude();
- eduroamCAT.debug("Last Known Location=" + lat + "," + longx);
- eduroamCAT.debug("Last Known Location Accuracy=" + lastKnownLocation.getAccuracy());
- hasAccuracy = lastKnownLocation.hasAccuracy();
- } else {
- geoip = new GEOIP(activity);
- geoip.execute();
- //lat = 0;
- //longx = 0;
- hasAccuracy = false;
- eduroamCAT.debug("Location Service failed, trying GEOIP....");
- }
- }
-
- if (search.length() > 2) {
- lat = 0;
- longx = 0;
- MAX_DISTANCE = 999999999;
- }
- }
- geoip = new GEOIP(activity);
- geoip.execute();
- hasAccuracy = false;
- eduroamCAT.debug("Location Service no permitted, trying GEOIP....");
- }
-
- public void setLocation(Double latx, Double longx)
- {
- this.lat=latx;
- this.longx=longx;
- }
-
- private void addIdP(Double latnow, Double lonnow, String title, int id, float [] distance)
- {
- if (distance[0]>0 && id>0 && title.length()>0 && distance[0](){
- public int compare(IdP s1, IdP s2) {
- return (int) ((int) s1.distance - s2.distance);
- }
- });
- //eduroamCAT.debug("Number of IdPs="+IdPs.size());
- if (IdPs.size()<1) {
- IdP tmpidp = new IdP(activity.getString(R.string.manual_search_fail),0,0);
- tmpidp.profileRedirect="0";
- ViewProfiles.adapter.add(tmpidp);
- String locationServiceCheck="";
- if (!hasAccuracy) locationServiceCheck=""+activity.getString(R.string.scad_geoip_insufficient)+"";
- if (!network_enabled) locationServiceCheck=""+activity.getString(R.string.scad_geoip_noloc)+"";
- String idp_nearby = ""+activity.getString(R.string.scad_geoip_no_configs_title)+"
";
- if (search.length()==0) {
- int maxdistance = 0;
- maxdistance = (int) MAX_DISTANCE / 1000;
- idp_nearby += activity.getString(R.string.scad_geoip_no_configs_message, maxdistance);
- }
- idp_nearby+="
"+locationServiceCheck;
- Spanned idp_nearby2=Html.fromHtml(idp_nearby);
- if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby2);
- if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
- }
- else
- {
- String loadingProfiles = activity.getString(R.string.scad_geoip_success);
- Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_title)+"
" + loadingProfiles);
- if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
- if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
- }
- //stop location service
- if (locationManager !=null) locationManager.removeUpdates(locationListener);
- }
-
- @Override
- protected String doInBackground(String... aurl) {
- String str = "";
- HttpResponse response;
- HttpClient myClient = new DefaultHttpClient();
- HttpPost myConnection = new HttpPost("https://cat.eduroam.org/user/API.php?action=listAllIdentityProviders&lang="+lang);
- try {
- eduroamCAT.debug("Getting list of all providers from API");
- response = myClient.execute(myConnection);
- //eduroamCAT.debug("Response="+response.getStatusLine());
- str = EntityUtils.toString(response.getEntity(), "UTF-8");
- //eduroamCAT.debug("Content="+str);
- } catch (Exception e) {
- eduroamCAT.debug(e.getMessage());
- return "Can not contact cat.eduroam.org";
- }
- this.jsonString=str;
- return str;
- }
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Locale;
+import org.json.JSONArray;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.Manifest;
+import android.app.Activity;
+import android.content.pm.PackageManager;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.support.v4.app.ActivityCompat;
+import android.support.v4.content.ContextCompat;
+import android.text.Html;
+import android.text.Spanned;
+import android.view.View;
+import android.widget.Toast;
+
+//Supplicant Configuration Discovery Process
+public class SCAD extends AsyncTask {
+
+ private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 0;
+ public static float MAX_DISTANCE = 30000;
+ String locationProvider = LocationManager.NETWORK_PROVIDER;
+ LocationManager locationManager;
+ public double lat,longx=0;
+ JSONObject json = null;
+ String jsonString = "";
+ static public ArrayList IdPs = new ArrayList();
+ Location lastKnownLocation;
+ Boolean hasAccuracy=false;
+ String lang= Locale.getDefault().getLanguage();
+ LocationListener locationListener;
+ boolean network_enabled = false;
+ Activity activity;
+ GEOIP geoip;
+ String search="";
+
+ public SCAD(Activity activity,String search)
+ {
+ //set location
+ this.activity=activity;
+ this.search=search;
+ //check for location permission as result of new tark sdk above sdk 23
+ if (ContextCompat.checkSelfPermission(this.activity, Manifest.permission.ACCESS_COARSE_LOCATION)
+ != PackageManager.PERMISSION_GRANTED) {
+ eduroamCAT.debug("No Location permissions");
+ // Permission is not granted
+ ActivityCompat.requestPermissions(this.activity,
+ new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
+ MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
+
+ //try geoip...
+ //geoip = new GEOIP(activity);
+ //geoip.execute();
+ startLocationService();
+ hasAccuracy = false;
+ eduroamCAT.debug("Location Service permission not grantted, trying GEOIP....");
+ }
+ else {
+ startLocationService();
+ }
+ }
+
+ public void startLocationService()
+ {
+ if (ContextCompat.checkSelfPermission(this.activity, Manifest.permission.ACCESS_COARSE_LOCATION)
+ == PackageManager.PERMISSION_GRANTED) {
+ eduroamCAT.debug("Location Service setup....");
+ locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
+ // Define a listener that responds to location updates
+
+ locationListener = new LocationListener() {
+ public void onLocationChanged(Location location) {
+ // Called when a new location is found by the network location provider.
+ }
+
+ public void onStatusChanged(String provider, int status, Bundle extras) {
+ }
+
+ public void onProviderEnabled(String provider) {
+ hasAccuracy = true;
+ }
+
+ public void onProviderDisabled(String provider) {
+ hasAccuracy = false;
+ }
+ };
+
+ if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
+ locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); }
+ else {
+ eduroamCAT.debug("No Network_Provider...");
+ hasAccuracy = false;
+ }
+
+ try {
+ network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
+ } catch (Exception ex) {
+ eduroamCAT.debug("Location Service Disabled....");
+ hasAccuracy = false;
+ }
+
+ ConfigureFragment.setupSCAD();
+ //locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
+ if (search.length() < 3) {
+ lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
+ if (lastKnownLocation != null) {
+ lat = lastKnownLocation.getLatitude();
+ longx = lastKnownLocation.getLongitude();
+ eduroamCAT.debug("Last Known Location=" + lat + "," + longx);
+ eduroamCAT.debug("Last Known Location Accuracy=" + lastKnownLocation.getAccuracy());
+ hasAccuracy = lastKnownLocation.hasAccuracy();
+ } else {
+ geoip = new GEOIP(activity);
+ geoip.execute();
+ //lat = 0;
+ //longx = 0;
+ hasAccuracy = false;
+ eduroamCAT.debug("Location Service failed, trying GEOIP....");
+ }
+ }
+
+ if (search.length() > 2) {
+ lat = 0;
+ longx = 0;
+ MAX_DISTANCE = 999999999;
+ }
+ }
+ geoip = new GEOIP(activity);
+ geoip.execute();
+ hasAccuracy = false;
+ eduroamCAT.debug("Location Service no permitted, trying GEOIP....");
+ }
+
+ public void setLocation(Double latx, Double longx)
+ {
+ this.lat=latx;
+ this.longx=longx;
+ }
+
+ private void addIdP(Double latnow, Double lonnow, String title, int id, float [] distance)
+ {
+ if (distance[0]>0 && id>0 && title.length()>0 && distance[0](){
+ public int compare(IdP s1, IdP s2) {
+ return (int) ((int) s1.distance - s2.distance);
+ }
+ });
+ //eduroamCAT.debug("Number of IdPs="+IdPs.size());
+ if (IdPs.size()<1) {
+ IdP tmpidp = new IdP(activity.getString(R.string.manual_search_fail),0,0);
+ tmpidp.profileRedirect="0";
+ ViewProfiles.adapter.add(tmpidp);
+ String locationServiceCheck="";
+ if (!hasAccuracy) locationServiceCheck=""+activity.getString(R.string.scad_geoip_insufficient)+"";
+ if (!network_enabled) locationServiceCheck=""+activity.getString(R.string.scad_geoip_noloc)+"";
+ String idp_nearby = ""+activity.getString(R.string.scad_geoip_no_configs_title)+"
";
+ if (search.length()==0) {
+ int maxdistance = 0;
+ maxdistance = (int) MAX_DISTANCE / 1000;
+ idp_nearby += activity.getString(R.string.scad_geoip_no_configs_message, maxdistance);
+ }
+ idp_nearby+="
"+locationServiceCheck;
+ Spanned idp_nearby2=Html.fromHtml(idp_nearby);
+ if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby2);
+ if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
+ }
+ else
+ {
+ String loadingProfiles = activity.getString(R.string.scad_geoip_success);
+ Spanned idp_nearby = Html.fromHtml(""+activity.getString(R.string.scad_title)+"
" + loadingProfiles);
+ if (ConfigureFragment.idptext!=null) ConfigureFragment.idptext.setText(idp_nearby);
+ if (ConfigureFragment.scadProgress!=null) ConfigureFragment.scadProgress.setVisibility(View.VISIBLE);
+ }
+ //stop location service
+ if (locationManager !=null) locationManager.removeUpdates(locationListener);
+ }
+
+ @Override
+ protected String doInBackground(String... aurl) {
+ String str = "";
+ HttpResponse response;
+ HttpClient myClient = new DefaultHttpClient();
+ HttpPost myConnection = new HttpPost("https://cat.eduroam.org/user/API.php?action=listAllIdentityProviders&lang="+lang);
+ try {
+ eduroamCAT.debug("Getting list of all providers from API");
+ response = myClient.execute(myConnection);
+ //eduroamCAT.debug("Response="+response.getStatusLine());
+ str = EntityUtils.toString(response.getEntity(), "UTF-8");
+ //eduroamCAT.debug("Content="+str);
+ } catch (Exception e) {
+ eduroamCAT.debug(e.getMessage());
+ return "Can not contact cat.eduroam.org";
+ }
+ this.jsonString=str;
+ return str;
+ }
+}
diff --git a/src/uk/ac/swansea/eduroamcat/StatusFragment.java b/src/uk/ac/swansea/eduroamcat/StatusFragment.java
index 78eede3..239d6fb 100644
--- a/src/uk/ac/swansea/eduroamcat/StatusFragment.java
+++ b/src/uk/ac/swansea/eduroamcat/StatusFragment.java
@@ -1,279 +1,279 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.Fragment;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.text.Html;
-import android.text.Spanned;
-import android.text.method.ScrollingMovementMethod;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-
-public class StatusFragment extends Fragment implements OnClickListener {
-
- ToggleButton toggleWifi;
- ToggleButton verboseDebug;
- Button quickConnect,duplicate;
- public static boolean verbose = false;
- static TextView textStatus, statusInfo;
- static int debugSize = 0;
- static boolean wifiOn = true;
- private static String debugText = "";
-
- Activity activity = getActivity();
-
- public static void setDebug(String msg)
- {
- eduroamCAT.debug("USER TEXT:"+msg);
- msg=msg.concat("\n");
- debugText=debugText.concat(msg);
- //debugText=debugText+msg+"\n";
- updateText();
- }
-
- public static Boolean isWiFiToggled()
- {
- return wifiOn;
- }
-
- public static String getDebug()
- {
- return debugText;
- }
-
- public String latestSummary()
- {
- //Update the status inforamtion
- String summaryText="";
- if (getActivity()!=null)
- try {
- String currentSSID=eduroamCAT.wifiCon.getCurrentSSID();
- String bSSID=eduroamCAT.wifiCon.getCurrentBSSID();
- String rss=eduroamCAT.wifiCon.getCurrentRSS();
- String reason=eduroamCAT.wifiCon.getFailReason();
- String failReason="";
- if (reason!=null) failReason=getActivity().getString(R.string.status_failure)+reason+"
";
- String linkSpeed=eduroamCAT.wifiCon.getLinkSpeed()+"Mbs";
- String ip=eduroamCAT.wifiCon.getIPAddress();
- String mac=eduroamCAT.wifiCon.getDeviceWiFiMac();
- String supState=eduroamCAT.wifiCon.getSupplicantState();
- if (supState==null || supState.length()<1) supState="Unknown";
- String supDetailed = eduroamCAT.wifiCon.getDetailedSupplicantState();
- if (supDetailed==null || supDetailed.length()<1) supDetailed="Unknown";
- summaryText=""+getActivity().getString(R.string.status_title)+"";
- summaryText+="SSID:"+currentSSID+" BSSID :"+bSSID+"
Signal Strength:"+rss+"dBm Link Speed:"+linkSpeed+"
";
- summaryText+=getActivity().getString(R.string.status_connection)+""+eduroamCAT.wifiCon.getWifiState()+" ("+eduroamCAT.wifiCon.getWifiStateDetailed()+")
";
- summaryText+=getActivity().getString(R.string.status_supplicant)+""+supState+"("+supDetailed+")
";
- summaryText+=getActivity().getString(R.string.status_wifi)+""+eduroamCAT.wifiCon.checkWifiEnabled()+""+getActivity().getString(R.string.status_supplicant_ok)+""+ eduroamCAT.wifiCon.isSupplicantOK()+"
";
- summaryText+=failReason;
- if (eduroamCAT.currentapiVersion<23) summaryText+=getActivity().getString(R.string.status_ip)+""+ip+""+getActivity().getString(R.string.status_mac)+""+mac+"
";
- else summaryText+=getActivity().getString(R.string.status_ip)+""+ip+"
";
- summaryText+="
";
- Spanned statusSummary = Html.fromHtml(summaryText);
- if (statusInfo!=null) statusInfo.setText(statusSummary);
- }
- catch (Exception e)
- {
- eduroamCAT.debug("latestSummary Exception:"+e);
- }
- return summaryText;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- // Inflate the layout for this fragment
-
- super.onCreate(savedInstanceState);
- View v = inflater.inflate(R.layout.fragment_status, container, false);
- textStatus = (TextView) v.findViewById(R.id.textStatus);
- textStatus.setMovementMethod(new ScrollingMovementMethod());
- statusInfo = (TextView) v.findViewById(R.id.statusInfo);
- verboseDebug = (ToggleButton) v.findViewById(R.id.toggleVerbose);
- verboseDebug.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- if (verbose)
- {
- eduroamCAT.debug("debug Toggle OFF");
- }
- else
- {
- eduroamCAT.debug("debug Toggle ON");
- }
- verbose =!verbose;
- }
- }
- );
-
- //quick connect button
- quickConnect = (Button) v.findViewById(R.id.quickConnect);
- quickConnect.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- eduroamCAT.debug("Quick Connect Pressed");
- if (eduroamCAT.profiles!=null && eduroamCAT.wifiProfile!=null) {
- eduroamCAT.reconnect();
- }
- else
- {
- eduroamCAT.debug("No profiles found");
- //Toast.makeText(v.getContext(), "No profiles found to use. Please install a profile first.",3).show();
- eduroamCAT.alertUser(getString(R.string.profile_install_missing),getString(R.string.profile_failed),getActivity());
- }
- //eduroamCAT.wifiCon.checkSSID("eduroam");
- }
- }
- );
-
- toggleWifi = (ToggleButton) v.findViewById(R.id.toggleWifi);
- toggleWifi.setOnClickListener(this);
- if (!eduroamCAT.wifiCon.checkWifiEnabled())
- {
- //if (toggleWifi.isChecked()) toggleWifi.toggle();
- toggleWifi.setChecked(false);
- wifiOn = false;
- eduroamCAT.debug("WiFi OFF on detailed Activity Create");
- }
- else
- {
- toggleWifi.setChecked(true);
- eduroamCAT.debug("WiFi ON on detailed Activity Create");
- wifiOn = true;
- }
-
- //duplicate button
- duplicate = (Button) v.findViewById(R.id.duplicateButton);
- if (eduroamCAT.isAdvancedMode())
- {
- duplicate.setVisibility(View.VISIBLE);
- duplicate.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- eduroamCAT.debug("Duplicate Pressed");
- if (eduroamCAT.profiles!=null && eduroamCAT.wifiProfile!=null) {
- AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
-
- alert.setTitle("Duplicate");
- alert.setMessage("What SSID to duplicate eduroam to?");
-
- // Set an EditText view to get user input
- final EditText input = new EditText(getActivity());
- alert.setView(input);
-
- alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- String value = input.getText().toString();
- ProfilesStorage db = new ProfilesStorage(getActivity());
- //Build WiFi Profile
- //default to eduroam settings
- WiFiProfile wifiProfile_dup = null;
- wifiProfile_dup = new WiFiProfile();
- if (eduroamCAT.wifiProfile!=null) {
- wifiProfile_dup.isOK();
- wifiProfile_dup.setSSID(value);
- wifiProfile_dup.setAuthType("WPA2");
- wifiProfile_dup.setEncryptionType("CCMP");
- wifiProfile_dup.setAutojoin(true);
- wifiProfile_dup.setSSIDPriority(db.numberOfRowsWiFi()+1);
- if (wifiProfile_dup.hasError()==false) {
- eduroamCAT.debug("Duplicate WiFi Profile OK:"+value);
- //add to DB
- long result = db.insertWiFi("0", wifiProfile_dup.getSSID(), wifiProfile_dup.getAuthType(),wifiProfile_dup.getEncryptionType(),wifiProfile_dup.getSSIDPriority(), 1);
- eduroamCAT.debug("DB INSET INTO WIFI:"+result);
- }
- else eduroamCAT.debug("WiFi Profile Error!");
- }
- }
- });
-
- alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- // Canceled.
- }
- });
-
- alert.show();
- //ConnectFragment.duplicate();
- }
- else
- {
- eduroamCAT.debug("No profiles found");
- eduroamCAT.alertUser(getString(R.string.profile_install_missing),getString(R.string.profile_failed),getActivity());
- }
- //eduroamCAT.wifiCon.checkSSID("eduroam");
- }
- }
- );
-
- }
- else duplicate.setVisibility(View.GONE);
-
- latestSummary();
- return v;
- }
-
- //button clicks
- public void onClick(View view)
- {
- switch (view.getId())
- {
- case R.id.toggleVerbose:
- if (verbose)
- {
- eduroamCAT.debug("debug Toggle OFF");
- }
- else
- {
- eduroamCAT.debug("debug Toggle ON");
- }
- verbose =!verbose;
- break;
- case R.id.toggleWifi:
- if (wifiOn)
- {
- //turn wifi off
- eduroamCAT.debug("wifi Toggle OFF");
- eduroamCAT.wifiCon.setWifiOFF();
- }
- else
- {
- //turn wifi on
- eduroamCAT.debug("wifi Toggle ON");
- eduroamCAT.wifiCon.setWifiON();
- }
- wifiOn=!wifiOn;
- break;
- default:
- break;
- }
- updateText();
- }
-
- public static void updateText()
- {
- if (textStatus!=null){
- //Log.d("eduroamcat", "debugsize="+debugSize+" and getDebug="+getDebug().length());
-// if (debugSize
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Fragment;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.text.Html;
+import android.text.Spanned;
+import android.text.method.ScrollingMovementMethod;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+public class StatusFragment extends Fragment implements OnClickListener {
+
+ ToggleButton toggleWifi;
+ ToggleButton verboseDebug;
+ Button quickConnect,duplicate;
+ public static boolean verbose = false;
+ static TextView textStatus, statusInfo;
+ static int debugSize = 0;
+ static boolean wifiOn = true;
+ private static String debugText = "";
+
+ Activity activity = getActivity();
+
+ public static void setDebug(String msg)
+ {
+ eduroamCAT.debug("USER TEXT:"+msg);
+ msg=msg.concat("\n");
+ debugText=debugText.concat(msg);
+ //debugText=debugText+msg+"\n";
+ updateText();
+ }
+
+ public static Boolean isWiFiToggled()
+ {
+ return wifiOn;
+ }
+
+ public static String getDebug()
+ {
+ return debugText;
+ }
+
+ public String latestSummary()
+ {
+ //Update the status inforamtion
+ String summaryText="";
+ if (getActivity()!=null)
+ try {
+ String currentSSID=eduroamCAT.wifiCon.getCurrentSSID();
+ String bSSID=eduroamCAT.wifiCon.getCurrentBSSID();
+ String rss=eduroamCAT.wifiCon.getCurrentRSS();
+ String reason=eduroamCAT.wifiCon.getFailReason();
+ String failReason="";
+ if (reason!=null) failReason=getActivity().getString(R.string.status_failure)+reason+"
";
+ String linkSpeed=eduroamCAT.wifiCon.getLinkSpeed()+"Mbs";
+ String ip=eduroamCAT.wifiCon.getIPAddress();
+ String mac=eduroamCAT.wifiCon.getDeviceWiFiMac();
+ String supState=eduroamCAT.wifiCon.getSupplicantState();
+ if (supState==null || supState.length()<1) supState="Unknown";
+ String supDetailed = eduroamCAT.wifiCon.getDetailedSupplicantState();
+ if (supDetailed==null || supDetailed.length()<1) supDetailed="Unknown";
+ summaryText=""+getActivity().getString(R.string.status_title)+"";
+ summaryText+="SSID:"+currentSSID+" BSSID :"+bSSID+"
Signal Strength:"+rss+"dBm Link Speed:"+linkSpeed+"
";
+ summaryText+=getActivity().getString(R.string.status_connection)+""+eduroamCAT.wifiCon.getWifiState()+" ("+eduroamCAT.wifiCon.getWifiStateDetailed()+")
";
+ summaryText+=getActivity().getString(R.string.status_supplicant)+""+supState+"("+supDetailed+")
";
+ summaryText+=getActivity().getString(R.string.status_wifi)+""+eduroamCAT.wifiCon.checkWifiEnabled()+""+getActivity().getString(R.string.status_supplicant_ok)+""+ eduroamCAT.wifiCon.isSupplicantOK()+"
";
+ summaryText+=failReason;
+ if (eduroamCAT.currentapiVersion<23) summaryText+=getActivity().getString(R.string.status_ip)+""+ip+""+getActivity().getString(R.string.status_mac)+""+mac+"
";
+ else summaryText+=getActivity().getString(R.string.status_ip)+""+ip+"
";
+ summaryText+="
";
+ Spanned statusSummary = Html.fromHtml(summaryText);
+ if (statusInfo!=null) statusInfo.setText(statusSummary);
+ }
+ catch (Exception e)
+ {
+ eduroamCAT.debug("latestSummary Exception:"+e);
+ }
+ return summaryText;
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ // Inflate the layout for this fragment
+
+ super.onCreate(savedInstanceState);
+ View v = inflater.inflate(R.layout.fragment_status, container, false);
+ textStatus = (TextView) v.findViewById(R.id.textStatus);
+ textStatus.setMovementMethod(new ScrollingMovementMethod());
+ statusInfo = (TextView) v.findViewById(R.id.statusInfo);
+ verboseDebug = (ToggleButton) v.findViewById(R.id.toggleVerbose);
+ verboseDebug.setOnClickListener(new OnClickListener() {
+
+ public void onClick(View v) {
+ if (verbose)
+ {
+ eduroamCAT.debug("debug Toggle OFF");
+ }
+ else
+ {
+ eduroamCAT.debug("debug Toggle ON");
+ }
+ verbose =!verbose;
+ }
+ }
+ );
+
+ //quick connect button
+ quickConnect = (Button) v.findViewById(R.id.quickConnect);
+ quickConnect.setOnClickListener(new OnClickListener() {
+
+ public void onClick(View v) {
+ eduroamCAT.debug("Quick Connect Pressed");
+ if (eduroamCAT.profiles!=null && eduroamCAT.wifiProfile!=null) {
+ eduroamCAT.reconnect();
+ }
+ else
+ {
+ eduroamCAT.debug("No profiles found");
+ //Toast.makeText(v.getContext(), "No profiles found to use. Please install a profile first.",3).show();
+ eduroamCAT.alertUser(getString(R.string.profile_install_missing),getString(R.string.profile_failed),getActivity());
+ }
+ //eduroamCAT.wifiCon.checkSSID("eduroam");
+ }
+ }
+ );
+
+ toggleWifi = (ToggleButton) v.findViewById(R.id.toggleWifi);
+ toggleWifi.setOnClickListener(this);
+ if (!eduroamCAT.wifiCon.checkWifiEnabled())
+ {
+ //if (toggleWifi.isChecked()) toggleWifi.toggle();
+ toggleWifi.setChecked(false);
+ wifiOn = false;
+ eduroamCAT.debug("WiFi OFF on detailed Activity Create");
+ }
+ else
+ {
+ toggleWifi.setChecked(true);
+ eduroamCAT.debug("WiFi ON on detailed Activity Create");
+ wifiOn = true;
+ }
+
+ //duplicate button
+ duplicate = (Button) v.findViewById(R.id.duplicateButton);
+ if (eduroamCAT.isAdvancedMode())
+ {
+ duplicate.setVisibility(View.VISIBLE);
+ duplicate.setOnClickListener(new OnClickListener() {
+
+ public void onClick(View v) {
+ eduroamCAT.debug("Duplicate Pressed");
+ if (eduroamCAT.profiles!=null && eduroamCAT.wifiProfile!=null) {
+ AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
+
+ alert.setTitle("Duplicate");
+ alert.setMessage("What SSID to duplicate eduroam to?");
+
+ // Set an EditText view to get user input
+ final EditText input = new EditText(getActivity());
+ alert.setView(input);
+
+ alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ String value = input.getText().toString();
+ ProfilesStorage db = new ProfilesStorage(getActivity());
+ //Build WiFi Profile
+ //default to eduroam settings
+ WiFiProfile wifiProfile_dup = null;
+ wifiProfile_dup = new WiFiProfile();
+ if (eduroamCAT.wifiProfile!=null) {
+ wifiProfile_dup.isOK();
+ wifiProfile_dup.setSSID(value);
+ wifiProfile_dup.setAuthType("WPA2");
+ wifiProfile_dup.setEncryptionType("CCMP");
+ wifiProfile_dup.setAutojoin(true);
+ wifiProfile_dup.setSSIDPriority(db.numberOfRowsWiFi()+1);
+ if (wifiProfile_dup.hasError()==false) {
+ eduroamCAT.debug("Duplicate WiFi Profile OK:"+value);
+ //add to DB
+ long result = db.insertWiFi("0", wifiProfile_dup.getSSID(), wifiProfile_dup.getAuthType(),wifiProfile_dup.getEncryptionType(),wifiProfile_dup.getSSIDPriority(), 1);
+ eduroamCAT.debug("DB INSET INTO WIFI:"+result);
+ }
+ else eduroamCAT.debug("WiFi Profile Error!");
+ }
+ }
+ });
+
+ alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ // Canceled.
+ }
+ });
+
+ alert.show();
+ //ConnectFragment.duplicate();
+ }
+ else
+ {
+ eduroamCAT.debug("No profiles found");
+ eduroamCAT.alertUser(getString(R.string.profile_install_missing),getString(R.string.profile_failed),getActivity());
+ }
+ //eduroamCAT.wifiCon.checkSSID("eduroam");
+ }
+ }
+ );
+
+ }
+ else duplicate.setVisibility(View.GONE);
+
+ latestSummary();
+ return v;
+ }
+
+ //button clicks
+ public void onClick(View view)
+ {
+ switch (view.getId())
+ {
+ case R.id.toggleVerbose:
+ if (verbose)
+ {
+ eduroamCAT.debug("debug Toggle OFF");
+ }
+ else
+ {
+ eduroamCAT.debug("debug Toggle ON");
+ }
+ verbose =!verbose;
+ break;
+ case R.id.toggleWifi:
+ if (wifiOn)
+ {
+ //turn wifi off
+ eduroamCAT.debug("wifi Toggle OFF");
+ eduroamCAT.wifiCon.setWifiOFF();
+ }
+ else
+ {
+ //turn wifi on
+ eduroamCAT.debug("wifi Toggle ON");
+ eduroamCAT.wifiCon.setWifiON();
+ }
+ wifiOn=!wifiOn;
+ break;
+ default:
+ break;
+ }
+ updateText();
+ }
+
+ public static void updateText()
+ {
+ if (textStatus!=null){
+ //Log.d("eduroamcat", "debugsize="+debugSize+" and getDebug="+getDebug().length());
+// if (debugSize
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import android.app.ActionBar;
-import android.app.ActionBar.Tab;
-import android.app.Fragment;
-import android.app.FragmentTransaction;
-import android.content.Context;
-
-class TabsListener implements ActionBar.TabListener {
- public Fragment fragment;
- public Context context;
-
- public TabsListener(Fragment fragment, Context context) {
- this.fragment = fragment;
- this.context = context;
-
- }
-
- public void onTabSelected(Tab tab, FragmentTransaction ft) {
- ft.replace(R.id.start_activity, fragment);
- }
-
- @Override
- public void onTabReselected(Tab tab, FragmentTransaction ft) {
-
- }
-
- @Override
- public void onTabUnselected(Tab tab, FragmentTransaction ft) {
- ft.remove(fragment);
-
- }
-
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import android.app.ActionBar;
+import android.app.ActionBar.Tab;
+import android.app.Fragment;
+import android.app.FragmentTransaction;
+import android.content.Context;
+
+class TabsListener implements ActionBar.TabListener {
+ public Fragment fragment;
+ public Context context;
+
+ public TabsListener(Fragment fragment, Context context) {
+ this.fragment = fragment;
+ this.context = context;
+
+ }
+
+ public void onTabSelected(Tab tab, FragmentTransaction ft) {
+ ft.replace(R.id.start_activity, fragment);
+ }
+
+ @Override
+ public void onTabReselected(Tab tab, FragmentTransaction ft) {
+
+ }
+
+ @Override
+ public void onTabUnselected(Tab tab, FragmentTransaction ft) {
+ ft.remove(fragment);
+
+ }
+
}
\ No newline at end of file
diff --git a/src/uk/ac/swansea/eduroamcat/ViewProfiles.java b/src/uk/ac/swansea/eduroamcat/ViewProfiles.java
index b72b6c2..b8d011b 100644
--- a/src/uk/ac/swansea/eduroamcat/ViewProfiles.java
+++ b/src/uk/ac/swansea/eduroamcat/ViewProfiles.java
@@ -1,137 +1,137 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.text.InputType;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.CompoundButton;
-import android.widget.EditText;
-import android.widget.ListView;
-import android.widget.SimpleCursorAdapter;
-import android.widget.Switch;
-
-public class ViewProfiles extends Activity {
-
- SimpleCursorAdapter mAdapter;
- static ProfileAdapter adapter;
- static SCAD scad = null;
- static ListView listView = null;
- Switch switch_search;
- private String searchText="";
- String search="";
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_view_profiles);
- listView = (ListView) findViewById(R.id.list);
- switch_search = (Switch) findViewById(R.id.switch1);
- switch_search.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView,
- boolean isChecked) {
- if(isChecked){
- AlertDialog.Builder builder = new AlertDialog.Builder(ViewProfiles.this);
- builder.setTitle(getString(R.string.manual_search));
- final EditText input = new EditText(ViewProfiles.this);
- input.setInputType(InputType.TYPE_CLASS_TEXT);
- builder.setView(input);
- builder.setPositiveButton(getString(R.string.search), new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- searchText = input.getText().toString();
- if (searchText.length()>2) {
- search = searchText;
- if (search != null) search = search.trim();
- adapter.clear();
- scad = new SCAD(ViewProfiles.this, search);
- scad.execute();
- }
- }
- });
- builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.cancel();
- }
- });
- builder.show();
- }else{
- search="";
- adapter.clear();
- }
-
- }
- });
- scad = new SCAD(this,search);
- scad.execute();
- adapter = new ProfileAdapter(this, SCAD.IdPs);
- listView.setAdapter(adapter);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView> parent, final View view, int position, long id)
- {
- eduroamCAT.debug("Click in listview");
- Intent download = new Intent(getApplicationContext(), EAPMetadata.class);
- if (!adapter.getItem(position).profileRedirect.equals("0") && adapter.getItem(position).profileRedirect.length()>0) {
- String url=adapter.getItem(position).profileRedirect;
- if (url.contains("http")==false)
- url="http://"+url;
- Uri uri = Uri.parse(url);
- //launch browser for a redirect
- eduroamCAT.debug("redirect click:"+adapter.getItem(position).title +" and "+uri.toString());
- if (url.toString().length()>0) {
- Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
- startActivity(browserIntent);
- }
- }
- else {
- if (adapter.getItem(position).profileID.size() == 1) {
- if (adapter.getItem(position).download.length() > 0) {
- Uri uri = Uri.parse(adapter.getItem(position).download);
- eduroamCAT.debug("Click Download:" + uri.toString());
- download.setData(uri);
- startActivity(download);
- eduroamCAT.debug("started activity");
- }
- }
- }
- }
-
- });
- adapter.notifyDataSetChanged();
- }
-
- @Override
- public void onPause() {
- super.onPause(); // Always call the superclass method first
- }
-
- @Override
- public void onResume() {
- super.onResume(); // Always call the superclass method first
- eduroamCAT.debug("resumed viewProfiles");
- if (adapter.getCount()>0) {
- adapter.notifyDataSetChanged();
- }
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- SCAD.MAX_DISTANCE=30000;
- }
-
-
-
- }
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.text.InputType;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.ListView;
+import android.widget.SimpleCursorAdapter;
+import android.widget.Switch;
+
+public class ViewProfiles extends Activity {
+
+ SimpleCursorAdapter mAdapter;
+ static ProfileAdapter adapter;
+ static SCAD scad = null;
+ static ListView listView = null;
+ Switch switch_search;
+ private String searchText="";
+ String search="";
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_view_profiles);
+ listView = (ListView) findViewById(R.id.list);
+ switch_search = (Switch) findViewById(R.id.switch1);
+ switch_search.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView,
+ boolean isChecked) {
+ if(isChecked){
+ AlertDialog.Builder builder = new AlertDialog.Builder(ViewProfiles.this);
+ builder.setTitle(getString(R.string.manual_search));
+ final EditText input = new EditText(ViewProfiles.this);
+ input.setInputType(InputType.TYPE_CLASS_TEXT);
+ builder.setView(input);
+ builder.setPositiveButton(getString(R.string.search), new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ searchText = input.getText().toString();
+ if (searchText.length()>2) {
+ search = searchText;
+ if (search != null) search = search.trim();
+ adapter.clear();
+ scad = new SCAD(ViewProfiles.this, search);
+ scad.execute();
+ }
+ }
+ });
+ builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.cancel();
+ }
+ });
+ builder.show();
+ }else{
+ search="";
+ adapter.clear();
+ }
+
+ }
+ });
+ scad = new SCAD(this,search);
+ scad.execute();
+ adapter = new ProfileAdapter(this, SCAD.IdPs);
+ listView.setAdapter(adapter);
+ listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> parent, final View view, int position, long id)
+ {
+ eduroamCAT.debug("Click in listview");
+ Intent download = new Intent(getApplicationContext(), EAPMetadata.class);
+ if (!adapter.getItem(position).profileRedirect.equals("0") && adapter.getItem(position).profileRedirect.length()>0) {
+ String url=adapter.getItem(position).profileRedirect;
+ if (url.contains("http")==false)
+ url="http://"+url;
+ Uri uri = Uri.parse(url);
+ //launch browser for a redirect
+ eduroamCAT.debug("redirect click:"+adapter.getItem(position).title +" and "+uri.toString());
+ if (url.toString().length()>0) {
+ Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
+ startActivity(browserIntent);
+ }
+ }
+ else {
+ if (adapter.getItem(position).profileID.size() == 1) {
+ if (adapter.getItem(position).download.length() > 0) {
+ Uri uri = Uri.parse(adapter.getItem(position).download);
+ eduroamCAT.debug("Click Download:" + uri.toString());
+ download.setData(uri);
+ startActivity(download);
+ eduroamCAT.debug("started activity");
+ }
+ }
+ }
+ }
+
+ });
+ adapter.notifyDataSetChanged();
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause(); // Always call the superclass method first
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume(); // Always call the superclass method first
+ eduroamCAT.debug("resumed viewProfiles");
+ if (adapter.getCount()>0) {
+ adapter.notifyDataSetChanged();
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ SCAD.MAX_DISTANCE=30000;
+ }
+
+
+
+ }
diff --git a/src/uk/ac/swansea/eduroamcat/WiFiProfile.java b/src/uk/ac/swansea/eduroamcat/WiFiProfile.java
index 3f8b496..fd7fbc0 100644
--- a/src/uk/ac/swansea/eduroamcat/WiFiProfile.java
+++ b/src/uk/ac/swansea/eduroamcat/WiFiProfile.java
@@ -1,123 +1,123 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-public class WiFiProfile {
-
- private boolean error=true;
- private String errorMessage="No Profile";
- private String ssid="";
- private String authType;
-// private String groupCypher;
-// private String keyManagement;
-// private String cypherType;
- private String encType;
- private int ssidPriority=999;
- private boolean autoJoin = true;
-
-
- //set error message
- public void setConfigError(String errorMessage)
- {
- this.error=true;
- this.errorMessage=errorMessage;
- }
-
- //Return if error or not
- public boolean hasError()
- {
- return this.error;
- }
-
- //Set no error
- public void isOK()
- {
- this.error=false;
- }
-
- //return error message if message exists
- public String getError()
- {
- if (errorMessage.length()>0) return errorMessage;
- else return "";
- }
-
- //set EAPIdP ID string
- public void setSSID(String ssidx)
- {
- if (ssidx.length()>0){
- this.ssid=ssidx;
- }
- else setConfigError("Error with SSID length:="+ssidx);
- }
-
- //return EAPIdP ID String
- public String getSSID()
- {
- return ssid;
- }
-
- //set Auth Type
- public void setAuthType(String auth)
- {
- if (auth.length()>0)
- {
- this.authType=auth;
- }
- else setConfigError("Error with auth length:="+auth);
- }
-
- //get auth
- public String getAuthType()
- {
- return authType;
- }
-
- //set Encryption Type
- public void setEncryptionType(String enc)
- {
- if (enc.length()>0)
- {
- this.encType=enc;
- }
- else setConfigError("Error with encryption type length:="+enc);
- }
-
- //get Encryption Type
- public String getEncryptionType()
- {
- return encType;
- }
-
- //set SSID Priority
- public void setSSIDPriority(int priority)
- {
- if (priority>-1)
- {
- this.ssidPriority=priority;
- }
- else setConfigError("Error with ssid priority:="+priority);
- }
-
- //get ssid priority
- public int getSSIDPriority()
- {
- return ssidPriority;
- }
-
- //set SSID auto Join
- public void setAutojoin(boolean join)
- {
- this.autoJoin=join;
- }
-
- //get ssid autojoin
- public boolean isAutoJoin()
- {
- return autoJoin;
- }
-
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+public class WiFiProfile {
+
+ private boolean error=true;
+ private String errorMessage="No Profile";
+ private String ssid="";
+ private String authType;
+// private String groupCypher;
+// private String keyManagement;
+// private String cypherType;
+ private String encType;
+ private int ssidPriority=999;
+ private boolean autoJoin = true;
+
+
+ //set error message
+ public void setConfigError(String errorMessage)
+ {
+ this.error=true;
+ this.errorMessage=errorMessage;
+ }
+
+ //Return if error or not
+ public boolean hasError()
+ {
+ return this.error;
+ }
+
+ //Set no error
+ public void isOK()
+ {
+ this.error=false;
+ }
+
+ //return error message if message exists
+ public String getError()
+ {
+ if (errorMessage.length()>0) return errorMessage;
+ else return "";
+ }
+
+ //set EAPIdP ID string
+ public void setSSID(String ssidx)
+ {
+ if (ssidx.length()>0){
+ this.ssid=ssidx;
+ }
+ else setConfigError("Error with SSID length:="+ssidx);
+ }
+
+ //return EAPIdP ID String
+ public String getSSID()
+ {
+ return ssid;
+ }
+
+ //set Auth Type
+ public void setAuthType(String auth)
+ {
+ if (auth.length()>0)
+ {
+ this.authType=auth;
+ }
+ else setConfigError("Error with auth length:="+auth);
+ }
+
+ //get auth
+ public String getAuthType()
+ {
+ return authType;
+ }
+
+ //set Encryption Type
+ public void setEncryptionType(String enc)
+ {
+ if (enc.length()>0)
+ {
+ this.encType=enc;
+ }
+ else setConfigError("Error with encryption type length:="+enc);
+ }
+
+ //get Encryption Type
+ public String getEncryptionType()
+ {
+ return encType;
+ }
+
+ //set SSID Priority
+ public void setSSIDPriority(int priority)
+ {
+ if (priority>-1)
+ {
+ this.ssidPriority=priority;
+ }
+ else setConfigError("Error with ssid priority:="+priority);
+ }
+
+ //get ssid priority
+ public int getSSIDPriority()
+ {
+ return ssidPriority;
+ }
+
+ //set SSID auto Join
+ public void setAutojoin(boolean join)
+ {
+ this.autoJoin=join;
+ }
+
+ //get ssid autojoin
+ public boolean isAutoJoin()
+ {
+ return autoJoin;
+ }
+
}
\ No newline at end of file
diff --git a/src/uk/ac/swansea/eduroamcat/WifiConfigAPI18.java b/src/uk/ac/swansea/eduroamcat/WifiConfigAPI18.java
index 95f859c..727b1fb 100644
--- a/src/uk/ac/swansea/eduroamcat/WifiConfigAPI18.java
+++ b/src/uk/ac/swansea/eduroamcat/WifiConfigAPI18.java
@@ -1,288 +1,288 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-package uk.ac.swansea.eduroamcat;
-
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import android.annotation.TargetApi;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiEnterpriseConfig;
-import android.net.wifi.WifiEnterpriseConfig.Eap;
-import android.net.wifi.WifiEnterpriseConfig.Phase2;
-import android.net.wifi.WifiManager;
-
-@TargetApi(18)
-public class WifiConfigAPI18 {
-
- WifiManager wifi;
-
- public WifiConfigAPI18()
- {
- wifi = eduroamCAT.getWifiManager();
- }
-
- private void debug(String msg)
- {
- StatusFragment.setDebug(msg);
- }
-
-
- public boolean saveEapConfig(String userName,String passString, AuthenticationMethod aAuth)
- //public void saveEapConfig(String userName,String passString, String sSID)
- {
-
- /*Create a WifiConfig*/
- WifiConfiguration selectedConfig = new WifiConfiguration();
- WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
-
- //get Authentication Method
- if (aAuth.isError())
- {
- eduroamCAT.debug("AuthenticationMethod error");
- return false;
- }
-
- /*AP Name*/
- selectedConfig.SSID = "\""+eduroamCAT.wifiProfile.getSSID()+"\"";
- debug("Configuring connection to:"+eduroamCAT.wifiProfile.getSSID());
-
- /*Priority*/
- selectedConfig.priority = eduroamCAT.wifiProfile.getSSIDPriority();
- debug("Setting SSID priority to "+eduroamCAT.wifiProfile.getSSIDPriority());
-
- /*Enable Hidden SSID*/
- //selectedConfig.hiddenSSID = true;
-
- selectedConfig.allowedAuthAlgorithms.clear();
- selectedConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
-
- /*Key Mgmnt*/
- selectedConfig.allowedKeyManagement.clear();
- //selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
- selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
-
- /*Group Ciphers*/
- selectedConfig.allowedGroupCiphers.clear();
- if (eduroamCAT.wifiProfile.getEncryptionType().equals("CCMP")) {
- selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
- selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
- }
- if (eduroamCAT.wifiProfile.getEncryptionType().equals("TKIP")) selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
- debug("Setting Encryption to:"+eduroamCAT.wifiProfile.getEncryptionType());
-
- /*Pairwise ciphers*/
- selectedConfig.allowedPairwiseCiphers.clear();
- if (eduroamCAT.wifiProfile.getEncryptionType().equals("CCMP")) selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
- if (eduroamCAT.wifiProfile.getEncryptionType().equals("TKIP")) selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP );
-
- /*Protocols*/
- selectedConfig.allowedProtocols.clear();
- if (eduroamCAT.wifiProfile.getAuthType().equals("WPA2")) selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
- if (eduroamCAT.wifiProfile.getAuthType().equals("WPA")) selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
- debug("Setting Authentication to:"+eduroamCAT.wifiProfile.getAuthType());
-
- //http://stackoverflow.com/questions/18016446/setting-the-eap-method-in-enterpriseconfig-on-android-4-3
- //http://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml
-
- /*EAP method*/
- String outter="";
- eduroamCAT.debug("Outter:"+aAuth.getOuterEAPType());
- if (aAuth.getOuterEAPType() == 25) {
- outter="PEAP";
- enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
- }
- else if (aAuth.getOuterEAPType() == 21) {
- outter="TTLS";
- enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TTLS);
- }
- else if (aAuth.getOuterEAPType() == 13) {
- outter="TLS";
- enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
- }
- else if (aAuth.getOuterEAPType() == 52) {
- outter="PWD";
- enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PWD);
- }
- else {
- outter="ERROR";
- eduroamCAT.debug("ERROR:no outter eap type");
- enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
- return false;
- }
-
- debug("Setting Outter EAP Method to:"+outter);
- if (enterpriseConfig.getEapMethod()==Eap.PEAP) debug("Set to PEAP OK");
- if (enterpriseConfig.getEapMethod()==Eap.PWD) debug("Set to PWD OK");
- if (enterpriseConfig.getEapMethod()==Eap.TLS) debug("Set to TLS OK");
- if (enterpriseConfig.getEapMethod()==Eap.TTLS) debug("Set to TTLS OK");
- if (enterpriseConfig.getEapMethod()==Eap.PWD) debug("Set to PWD OK");
-
- /*EAP Phase 2*/
- eduroamCAT.debug("Inner="+aAuth.getInnerEAPType());
- String phase2="none";
- if (aAuth.getInnerEAPType() == 26) {
- enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.MSCHAPV2);
- phase2="MSCHAPv2";
- eduroamCAT.debug("Setting to "+phase2);
- }
- else if (aAuth.getInnerEAPType() == 6) {
- enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
- phase2="GTC";
- eduroamCAT.debug("Setting to "+phase2);
- }
- else if (aAuth.getInnerEAPType() == 1) {
- enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.PAP);
- phase2="PAP";
- eduroamCAT.debug("Setting to "+phase2);
- }
- else if (aAuth.getInnerNonEAPType()==0) {
- phase2="NONE";
- eduroamCAT.debug("Setting to "+phase2);
- }
- else {
- eduroamCAT.debug("ERROR:no inner eap type");
- phase2="ERROR";
- return false;
- }
-
- debug("Set Phase2 to:"+phase2);
- if (enterpriseConfig.getPhase2Method()==Phase2.MSCHAPV2) debug("Set to MSCHAPv2 OK");
- if (enterpriseConfig.getPhase2Method()==Phase2.GTC) debug("Set to GTC OK");
- if (enterpriseConfig.getPhase2Method()==Phase2.PAP) debug("Set to PAP OK");
-
- /*Anon ID*/
- if (aAuth.getAnonID().length()>0) enterpriseConfig.setAnonymousIdentity(aAuth.getAnonID());
- debug("Set Anon to:"+aAuth.getAnonID());
-
- /*Cert*/
- if (aAuth.getCAcert() != null && aAuth.getCAcert().toString().length()>0)
- try
- {
- debug("Setting cert:"+aAuth.getCAcert().toString());
- eduroamCAT.debug("Installing cert...");
- enterpriseConfig.setCaCertificate((X509Certificate) aAuth.getCAcert());
- eduroamCAT.debug("Cert installed="+enterpriseConfig.getCaCertificate());
- }
- catch (IllegalArgumentException e) {
- eduroamCAT.debug("cert install error:\n" + e);
- eduroamCAT.debug("for cert:\n" + aAuth.getCAcert().toString());
- eduroamCAT.debug("Length:\n" + aAuth.getCAcert().toString().length());
- }
-
- //test comma delimited!
- if (aAuth.getServerIDs().size()>0)
- {
- String subjectMatch="";
- if (aAuth.getServerIDs().size()>1)
- {
- String subjectMatch_next=aAuth.getServerIDs().get(0);
- String subjectMatch_new="";
- if (subjectMatch_next.indexOf(".")>0){
- subjectMatch_new=subjectMatch_next.substring(subjectMatch_next.indexOf("."));
- subjectMatch=subjectMatch_new;
- }
- for (int serverCount=0; serverCount0)
- subjectMatch_new=subjectMatch_next.substring(subjectMatch_next.indexOf("."));
- if (subjectMatch.equals(subjectMatch_new)) continue;
- else {
- //error with serverIDs
- StatusFragment.setDebug("ServerID error with profile:"+subjectMatch+" and "+subjectMatch_new);
- eduroamCAT.debug("ServerID error with profile:"+subjectMatch+" and "+subjectMatch_new);
- subjectMatch="";
- break;
- }
- }
- }
- else subjectMatch=aAuth.getServerIDs().get(0);
-
- enterpriseConfig.setSubjectMatch(subjectMatch);
- eduroamCAT.debug("subjectMatch="+subjectMatch);
- //enterpriseConfig.setSubjectMatch("bouncer.swan.ac.uk;radauth.swan.ac.uk;radauth2.swan.ac.uk");
- //enterpriseConfig.setSubjectMatch("C=GB, ST=Wales, L=Swansea, O=Swansea University, OU=ISS/emailAddress=postmaster@swansea.ac.uk, CN=Swansea University Certificate Authority");
- //enterpriseConfig.setSubjectMatch("radauth.swan.ac.uk bouncer.swan.ac.uk radauth2.swan.ac.uk");
- //enterpriseConfig.setSubjectMatch("radauth.swan.ac.uk");
- }
-
- //User Cert
- if (aAuth.getOuterEAPType()==13)
- if (aAuth.getClientPrivateKey() != null)
- try
- {
- debug("Setting client cert:"+aAuth.getClientPrivateKey().toString());
- eduroamCAT.debug("Installing client cert...");
- //if api >26
- //enterpriseConfig.setClientKeyEntry(aAuth.getClientPrivateKey(), aAuth.getClientChain());
- //else
- enterpriseConfig.setClientKeyEntry(aAuth.getClientPrivateKey(), aAuth.getClientCert());
- eduroamCAT.debug("Client Cert installed="+enterpriseConfig.getClientCertificate());
- }
- catch (IllegalArgumentException e) {
- eduroamCAT.debug("cert install error:\n" + e);
- eduroamCAT.debug("for cert:\n" + aAuth.getClientPrivateKey().toString());
- eduroamCAT.debug("Length:\n" + aAuth.getClientPrivateKey().toString().length());
- }
-
- /*User and pass if not TLS*/
- if (aAuth.getOuterEAPType()!=13) {
- enterpriseConfig.setIdentity(userName);
- debug("Using Username:"+userName);
- enterpriseConfig.setPassword(passString);
- }
-
- //just identity for TLS
- if (aAuth.getOuterEAPType()==13) {
- if (userName!=null) {
- if (userName.length() == 0)
- if (aAuth.getClientPrivateKeySubjectCN() != null && aAuth.getClientPrivateKeySubjectCN().length() > 0) {
- userName = aAuth.getClientPrivateKeySubjectCN();
- }
- }
- else
- {
- if ( aAuth.getClientPrivateKeySubjectCN() != null && aAuth.getClientPrivateKeySubjectCN().length()>0) {
- userName = aAuth.getClientPrivateKeySubjectCN();
- }
- }
- enterpriseConfig.setIdentity(userName);
- debug("Using Username:" + userName);
- }
-
- selectedConfig.enterpriseConfig=enterpriseConfig;
-
- //Add network profile
- int res = wifi.addNetwork(selectedConfig);
- boolean enabled = false;
- if (res<0) {
- //failure
- debug("Adding profile ("+eduroamCAT.wifiProfile.getSSID()+") FAILED, returned " + res );
- }
- else
- {
- debug("Successfully added ("+eduroamCAT.wifiProfile.getSSID()+"), Network id=" + res );
- try {
- boolean c = wifi.saveConfiguration();
- debug("Saving configuration... " + c);
- enabled = wifi.enableNetwork(res, true);
- debug("Setting (" + eduroamCAT.wifiProfile.getSSID() + ") to Enabled returned " + enabled);
- }
- catch (Exception e)
- {
- eduroamCAT.debug("caught error with save eap config and enable " + e);
- }
- }
-
- debug("FINISHED SETUP FOR IDENTITY:"+selectedConfig.enterpriseConfig.getIdentity());
- if (selectedConfig.status==WifiConfiguration.Status.CURRENT) debug("Current****");
- if (selectedConfig.status==WifiConfiguration.Status.DISABLED) debug("Disabled****");
- if (selectedConfig.status==WifiConfiguration.Status.ENABLED) debug("Enabled****");
-
- return enabled;
-
- }
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+package uk.ac.swansea.eduroamcat;
+
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import android.annotation.TargetApi;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiEnterpriseConfig;
+import android.net.wifi.WifiEnterpriseConfig.Eap;
+import android.net.wifi.WifiEnterpriseConfig.Phase2;
+import android.net.wifi.WifiManager;
+
+@TargetApi(18)
+public class WifiConfigAPI18 {
+
+ WifiManager wifi;
+
+ public WifiConfigAPI18()
+ {
+ wifi = eduroamCAT.getWifiManager();
+ }
+
+ private void debug(String msg)
+ {
+ StatusFragment.setDebug(msg);
+ }
+
+
+ public boolean saveEapConfig(String userName,String passString, AuthenticationMethod aAuth)
+ //public void saveEapConfig(String userName,String passString, String sSID)
+ {
+
+ /*Create a WifiConfig*/
+ WifiConfiguration selectedConfig = new WifiConfiguration();
+ WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
+
+ //get Authentication Method
+ if (aAuth.isError())
+ {
+ eduroamCAT.debug("AuthenticationMethod error");
+ return false;
+ }
+
+ /*AP Name*/
+ selectedConfig.SSID = "\""+eduroamCAT.wifiProfile.getSSID()+"\"";
+ debug("Configuring connection to:"+eduroamCAT.wifiProfile.getSSID());
+
+ /*Priority*/
+ selectedConfig.priority = eduroamCAT.wifiProfile.getSSIDPriority();
+ debug("Setting SSID priority to "+eduroamCAT.wifiProfile.getSSIDPriority());
+
+ /*Enable Hidden SSID*/
+ //selectedConfig.hiddenSSID = true;
+
+ selectedConfig.allowedAuthAlgorithms.clear();
+ selectedConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
+
+ /*Key Mgmnt*/
+ selectedConfig.allowedKeyManagement.clear();
+ //selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
+ selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
+
+ /*Group Ciphers*/
+ selectedConfig.allowedGroupCiphers.clear();
+ if (eduroamCAT.wifiProfile.getEncryptionType().equals("CCMP")) {
+ selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
+ selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
+ }
+ if (eduroamCAT.wifiProfile.getEncryptionType().equals("TKIP")) selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
+ debug("Setting Encryption to:"+eduroamCAT.wifiProfile.getEncryptionType());
+
+ /*Pairwise ciphers*/
+ selectedConfig.allowedPairwiseCiphers.clear();
+ if (eduroamCAT.wifiProfile.getEncryptionType().equals("CCMP")) selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
+ if (eduroamCAT.wifiProfile.getEncryptionType().equals("TKIP")) selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP );
+
+ /*Protocols*/
+ selectedConfig.allowedProtocols.clear();
+ if (eduroamCAT.wifiProfile.getAuthType().equals("WPA2")) selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
+ if (eduroamCAT.wifiProfile.getAuthType().equals("WPA")) selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
+ debug("Setting Authentication to:"+eduroamCAT.wifiProfile.getAuthType());
+
+ //http://stackoverflow.com/questions/18016446/setting-the-eap-method-in-enterpriseconfig-on-android-4-3
+ //http://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml
+
+ /*EAP method*/
+ String outter="";
+ eduroamCAT.debug("Outter:"+aAuth.getOuterEAPType());
+ if (aAuth.getOuterEAPType() == 25) {
+ outter="PEAP";
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
+ }
+ else if (aAuth.getOuterEAPType() == 21) {
+ outter="TTLS";
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TTLS);
+ }
+ else if (aAuth.getOuterEAPType() == 13) {
+ outter="TLS";
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
+ }
+ else if (aAuth.getOuterEAPType() == 52) {
+ outter="PWD";
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PWD);
+ }
+ else {
+ outter="ERROR";
+ eduroamCAT.debug("ERROR:no outter eap type");
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
+ return false;
+ }
+
+ debug("Setting Outter EAP Method to:"+outter);
+ if (enterpriseConfig.getEapMethod()==Eap.PEAP) debug("Set to PEAP OK");
+ if (enterpriseConfig.getEapMethod()==Eap.PWD) debug("Set to PWD OK");
+ if (enterpriseConfig.getEapMethod()==Eap.TLS) debug("Set to TLS OK");
+ if (enterpriseConfig.getEapMethod()==Eap.TTLS) debug("Set to TTLS OK");
+ if (enterpriseConfig.getEapMethod()==Eap.PWD) debug("Set to PWD OK");
+
+ /*EAP Phase 2*/
+ eduroamCAT.debug("Inner="+aAuth.getInnerEAPType());
+ String phase2="none";
+ if (aAuth.getInnerEAPType() == 26) {
+ enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.MSCHAPV2);
+ phase2="MSCHAPv2";
+ eduroamCAT.debug("Setting to "+phase2);
+ }
+ else if (aAuth.getInnerEAPType() == 6) {
+ enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
+ phase2="GTC";
+ eduroamCAT.debug("Setting to "+phase2);
+ }
+ else if (aAuth.getInnerEAPType() == 1) {
+ enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.PAP);
+ phase2="PAP";
+ eduroamCAT.debug("Setting to "+phase2);
+ }
+ else if (aAuth.getInnerNonEAPType()==0) {
+ phase2="NONE";
+ eduroamCAT.debug("Setting to "+phase2);
+ }
+ else {
+ eduroamCAT.debug("ERROR:no inner eap type");
+ phase2="ERROR";
+ return false;
+ }
+
+ debug("Set Phase2 to:"+phase2);
+ if (enterpriseConfig.getPhase2Method()==Phase2.MSCHAPV2) debug("Set to MSCHAPv2 OK");
+ if (enterpriseConfig.getPhase2Method()==Phase2.GTC) debug("Set to GTC OK");
+ if (enterpriseConfig.getPhase2Method()==Phase2.PAP) debug("Set to PAP OK");
+
+ /*Anon ID*/
+ if (aAuth.getAnonID().length()>0) enterpriseConfig.setAnonymousIdentity(aAuth.getAnonID());
+ debug("Set Anon to:"+aAuth.getAnonID());
+
+ /*Cert*/
+ if (aAuth.getCAcert() != null && aAuth.getCAcert().toString().length()>0)
+ try
+ {
+ debug("Setting cert:"+aAuth.getCAcert().toString());
+ eduroamCAT.debug("Installing cert...");
+ enterpriseConfig.setCaCertificate((X509Certificate) aAuth.getCAcert());
+ eduroamCAT.debug("Cert installed="+enterpriseConfig.getCaCertificate());
+ }
+ catch (IllegalArgumentException e) {
+ eduroamCAT.debug("cert install error:\n" + e);
+ eduroamCAT.debug("for cert:\n" + aAuth.getCAcert().toString());
+ eduroamCAT.debug("Length:\n" + aAuth.getCAcert().toString().length());
+ }
+
+ //test comma delimited!
+ if (aAuth.getServerIDs().size()>0)
+ {
+ String subjectMatch="";
+ if (aAuth.getServerIDs().size()>1)
+ {
+ String subjectMatch_next=aAuth.getServerIDs().get(0);
+ String subjectMatch_new="";
+ if (subjectMatch_next.indexOf(".")>0){
+ subjectMatch_new=subjectMatch_next.substring(subjectMatch_next.indexOf("."));
+ subjectMatch=subjectMatch_new;
+ }
+ for (int serverCount=0; serverCount0)
+ subjectMatch_new=subjectMatch_next.substring(subjectMatch_next.indexOf("."));
+ if (subjectMatch.equals(subjectMatch_new)) continue;
+ else {
+ //error with serverIDs
+ StatusFragment.setDebug("ServerID error with profile:"+subjectMatch+" and "+subjectMatch_new);
+ eduroamCAT.debug("ServerID error with profile:"+subjectMatch+" and "+subjectMatch_new);
+ subjectMatch="";
+ break;
+ }
+ }
+ }
+ else subjectMatch=aAuth.getServerIDs().get(0);
+
+ enterpriseConfig.setSubjectMatch(subjectMatch);
+ eduroamCAT.debug("subjectMatch="+subjectMatch);
+ //enterpriseConfig.setSubjectMatch("bouncer.swan.ac.uk;radauth.swan.ac.uk;radauth2.swan.ac.uk");
+ //enterpriseConfig.setSubjectMatch("C=GB, ST=Wales, L=Swansea, O=Swansea University, OU=ISS/emailAddress=postmaster@swansea.ac.uk, CN=Swansea University Certificate Authority");
+ //enterpriseConfig.setSubjectMatch("radauth.swan.ac.uk bouncer.swan.ac.uk radauth2.swan.ac.uk");
+ //enterpriseConfig.setSubjectMatch("radauth.swan.ac.uk");
+ }
+
+ //User Cert
+ if (aAuth.getOuterEAPType()==13)
+ if (aAuth.getClientPrivateKey() != null)
+ try
+ {
+ debug("Setting client cert:"+aAuth.getClientPrivateKey().toString());
+ eduroamCAT.debug("Installing client cert...");
+ //if api >26
+ //enterpriseConfig.setClientKeyEntry(aAuth.getClientPrivateKey(), aAuth.getClientChain());
+ //else
+ enterpriseConfig.setClientKeyEntry(aAuth.getClientPrivateKey(), aAuth.getClientCert());
+ eduroamCAT.debug("Client Cert installed="+enterpriseConfig.getClientCertificate());
+ }
+ catch (IllegalArgumentException e) {
+ eduroamCAT.debug("cert install error:\n" + e);
+ eduroamCAT.debug("for cert:\n" + aAuth.getClientPrivateKey().toString());
+ eduroamCAT.debug("Length:\n" + aAuth.getClientPrivateKey().toString().length());
+ }
+
+ /*User and pass if not TLS*/
+ if (aAuth.getOuterEAPType()!=13) {
+ enterpriseConfig.setIdentity(userName);
+ debug("Using Username:"+userName);
+ enterpriseConfig.setPassword(passString);
+ }
+
+ //just identity for TLS
+ if (aAuth.getOuterEAPType()==13) {
+ if (userName!=null) {
+ if (userName.length() == 0)
+ if (aAuth.getClientPrivateKeySubjectCN() != null && aAuth.getClientPrivateKeySubjectCN().length() > 0) {
+ userName = aAuth.getClientPrivateKeySubjectCN();
+ }
+ }
+ else
+ {
+ if ( aAuth.getClientPrivateKeySubjectCN() != null && aAuth.getClientPrivateKeySubjectCN().length()>0) {
+ userName = aAuth.getClientPrivateKeySubjectCN();
+ }
+ }
+ enterpriseConfig.setIdentity(userName);
+ debug("Using Username:" + userName);
+ }
+
+ selectedConfig.enterpriseConfig=enterpriseConfig;
+
+ //Add network profile
+ int res = wifi.addNetwork(selectedConfig);
+ boolean enabled = false;
+ if (res<0) {
+ //failure
+ debug("Adding profile ("+eduroamCAT.wifiProfile.getSSID()+") FAILED, returned " + res );
+ }
+ else
+ {
+ debug("Successfully added ("+eduroamCAT.wifiProfile.getSSID()+"), Network id=" + res );
+ try {
+ boolean c = wifi.saveConfiguration();
+ debug("Saving configuration... " + c);
+ enabled = wifi.enableNetwork(res, true);
+ debug("Setting (" + eduroamCAT.wifiProfile.getSSID() + ") to Enabled returned " + enabled);
+ }
+ catch (Exception e)
+ {
+ eduroamCAT.debug("caught error with save eap config and enable " + e);
+ }
+ }
+
+ debug("FINISHED SETUP FOR IDENTITY:"+selectedConfig.enterpriseConfig.getIdentity());
+ if (selectedConfig.status==WifiConfiguration.Status.CURRENT) debug("Current****");
+ if (selectedConfig.status==WifiConfiguration.Status.DISABLED) debug("Disabled****");
+ if (selectedConfig.status==WifiConfiguration.Status.ENABLED) debug("Enabled****");
+
+ return enabled;
+
+ }
+}
diff --git a/src/uk/ac/swansea/eduroamcat/eduroamCAT.java b/src/uk/ac/swansea/eduroamcat/eduroamCAT.java
index 150a371..a220383 100644
--- a/src/uk/ac/swansea/eduroamcat/eduroamCAT.java
+++ b/src/uk/ac/swansea/eduroamcat/eduroamCAT.java
@@ -1,454 +1,454 @@
-//*******************
-//Author: Gareth Ayres
-//SENSE Project
-//https://github.com/GEANT/CAT-Android
-//*******************
-
-package uk.ac.swansea.eduroamcat;
-
-import java.util.ArrayList;
-import java.util.List;
-import android.app.NotificationManager;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
-import android.os.Bundle;
-import android.app.ActionBar;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.Fragment;
-import android.app.FragmentTransaction;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.NotificationCompat;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.WindowManager;
-import android.widget.Toast;
-import android.net.Uri;
-
-public class eduroamCAT extends FragmentActivity implements ActionBar.TabListener
-{
- private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
- //final static vars
- private static WifiManager wifi = null;
- static WifiController wifiCon = null;
- static BroadcastReceiver wifiStatus = null;
- static WifiConfigAPI18 wifiConfig18 = null;
- static WiFiProfile wifiProfile = null;
- static ArrayList profiles = null;
- final Intent configIntent = getIntent();
- final IntentFilter intentFilter = new IntentFilter();
- ProfilesStorage db = new ProfilesStorage(this);
- static String state="";
- final static String appSSID="eduroam";
- final Fragment connectFragment = new ConnectFragment();
- final Fragment configureFragment = new ConfigureFragment();
- final static Fragment statusFragment = new StatusFragment();
- private static boolean advanced_mode= false;
- public static boolean downloaded=false;
- public final static int currentapiVersion = android.os.Build.VERSION.SDK_INT;
-
- //Debug method to print to logd
- public static void debug(String msg)
- {
- if (BuildConfig.DEBUG) Log.d("eduroamCAT", msg);
- }
-
- //get advanced mode toggled
- public static boolean isAdvancedMode()
- {
- return advanced_mode;
- }
-
- //Defines WiFi Manager
- public static WifiManager getWifiManager()
- {
- return wifi;
- }
-
- public static void setSummary()
- {
- ((StatusFragment) statusFragment).latestSummary();
- }
-
- //reconect if profile installed
- public static void reconnect()
- {
- List currentConfigs;
- if (wifi.isWifiEnabled())
- {
- currentConfigs = wifi.getConfiguredNetworks();
- for (WifiConfiguration currentConfig : currentConfigs)
- {
- eduroamCAT.debug(currentConfig.SSID);
- if (currentConfig.SSID.equals("\"eduroam\""))
- {
- wifi.disconnect();
- boolean enabled = wifi.enableNetwork(currentConfig.networkId, true);
- debug("Setting ("+currentConfig.SSID+") to Enabled returned " + enabled );
- }
- }
- }
- }
-
- public void loadProfiles()
- {
- if (db.numberOfRowsEAP()>0)
- {
- profiles=db.getEAPProfiles();
- }
- else
- {
- debug("No profiles found in DB");
- }
- }
-
- public static void setState(String statea)
- {
- state=statea;
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_start);
- eduroamCAT.debug("Starting on create for main activity");
- //set focus off text fields
-// this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
-
- //setup the action bar (tabs at top of app)
- final ActionBar actionBar = getActionBar();
- actionBar.setTitle(R.string.app_name);
-
-// //hide ActionBar when not used
-// getWindow().
-// getDecorView().
-// setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
-
- //Action Bar Tabs
- actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
-
- // create new tabs and set up the titles of the tabs
- ActionBar.Tab connectTab = actionBar.newTab().setText(getString(R.string.title_tab1));
- ActionBar.Tab configureTab = actionBar.newTab().setText(getString(R.string.title_tab2));
- ActionBar.Tab statusTab = actionBar.newTab().setText(getString(R.string.title_tab3));
-
- // bind the fragments to the tabs - set up tabListeners for each tab
- connectTab.setTabListener(new TabsListener(connectFragment,getApplicationContext()));
- configureTab.setTabListener(new TabsListener(configureFragment,getApplicationContext()));
- statusTab.setTabListener(new TabsListener(statusFragment,getApplicationContext()));
-
-
- // add the tabs to the action bar
- actionBar.addTab(connectTab);
- actionBar.addTab(configureTab);
- actionBar.addTab(statusTab);
-
- //Setup WiFi Module
- if (wifi==null) wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
-
- //Setup wifi status broadcast receivers
- if (wifiStatus==null) wifiStatus = new WifiStatus(getSystemService(Context.CONNECTIVITY_SERVICE));
-
- //setup some intents for debugging wireless, supplicant and network state
-
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
- intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
- intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- intentFilter.addAction(WifiManager.EXTRA_SUPPLICANT_ERROR);
- intentFilter.addAction(WifiManager.EXTRA_SUPPLICANT_CONNECTED);
- intentFilter.addAction(WifiManager.EXTRA_WIFI_STATE);
- intentFilter.addAction(WifiManager.EXTRA_WIFI_INFO);
- registerReceiver(wifiStatus, intentFilter);
- //Initial checks
- if (wifiCon==null) wifiCon = new WifiController(this,getSystemService(Context.CONNECTIVITY_SERVICE));
- if (wifiCon.isWifiEnabled() && wifiCon.isSupplicantOK())
- {
- //ok
- debug("Wifi and Supplicant OK...");
- StatusFragment.setDebug(getString(R.string.status_wifi_supp_ok));
- //ConnectFragment.setStatus("WiFi Adapter OK");
- }
- else
- {
- //no ok, warn user
- Toast.makeText(this, getString(R.string.status_wifi_disabled),Toast.LENGTH_SHORT).show();
- StatusFragment.setDebug(getString(R.string.status_wifi_supp_problem));
- debug("WiFi disabled on device...");
- //ConnectFragment.setStatus("WiFi Adapter disbaled");
- }
-
- //WiFi Profile
- if (wifiProfile==null) wifiProfile = new WiFiProfile();
- //DB check for wifi profile
- if (db.numberOfRowsWiFi()>0)
- {
- debug("num rows wifi="+db.numberOfRowsWiFi());
- eduroamCAT.wifiProfile=db.getWiFi(0);
- debug("SSID FOUND="+eduroamCAT.wifiProfile.getSSID());
- }
- else
- {
- debug("num rows wifi="+db.numberOfRowsWiFi());
- eduroamCAT.wifiProfile.hasError();
- }
-
- //wifiConfig = new WifiConfig();
- if (wifiConfig18==null) wifiConfig18 = new WifiConfigAPI18();
-
-
- //EAP Profile
- ArrayList profiles = new ArrayList ();
- //draw tabs on top of app
-
- if (profiles.isEmpty() && db.numberOfRowsEAP()>0 && db.numberOfRowsAUTH()>0)
- {
- loadProfiles();
- actionBar.setSelectedNavigationItem(0);
- //nothing yet
- }
- else
- {
- debug("No prfoiles found...");
- actionBar.setSelectedNavigationItem(1);
- }
-
- actionBar.show();
- }
-
-
- public static void alertUser(String message, String title, Activity activ)
- {
- new AlertDialog.Builder(activ)
- .setTitle(title)
- .setMessage(message)
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- eduroamCAT.debug("OK clicked");
- }
- })
- .show();
- }
-
- public static void notifyConnected(Activity activ,Context context)
- {
- NotificationManager notificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
- int mId=1;
- NotificationCompat.Builder mBuilder =
- new NotificationCompat.Builder(activ)
- .setSmallIcon(R.drawable.ic_launcher)
- .setContentTitle(activ.getString(R.string.notification_title_connected))
- .setContentText(activ.getString(R.string.notification_message_connected));
- notificationManager.notify(mId, mBuilder.build());
- }
-
- @Override
- //Menu in top right of app
- public boolean onCreateOptionsMenu(Menu menu)
- {
- // Inflate the menu; this adds items to the action bar if it is present.
-
- //Add menu opetion in rop right of app
- MenuInflater inflater = getMenuInflater();
- //inflater.inflate(R.menu.settings, menu);
- inflater.inflate(R.menu.selectfile, menu);
- inflater.inflate(R.menu.advanced, menu);
- inflater.inflate(R.menu.support, menu);
- inflater.inflate(R.menu.about, menu);
- inflater.inflate(R.menu.version, menu);
- //inflater.inflate(R.menu.exit, menu);
- return true;
- }
-
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- // Restore the previously serialized current tab position.
- if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
- getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
- }
- registerReceiver(wifiStatus, intentFilter);
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- // Serialize the current tab position.
- outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
- .getSelectedNavigationIndex());
- }
-
- public void onTabSelected(ActionBar.Tab tab,
- FragmentTransaction fragmentTransaction) {
-
- }
-
- public void onTabUnselected(ActionBar.Tab tab,
- FragmentTransaction fragmentTransaction) {
- }
-
- public void onTabReselected(ActionBar.Tab tab,
- FragmentTransaction fragmentTransaction) {
- }
-
- //This method controls the buttons in the top right of the app
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.settings:
- Toast.makeText(this, getString(R.string.settings_menu),
- Toast.LENGTH_LONG).show();
- return true;
- case R.id.version:
- PackageInfo pInfo;
- String version="unknown";
- try {
- pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
- version = pInfo.versionName;
- } catch (NameNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Toast.makeText(this,"Version:"+version,
- Toast.LENGTH_LONG).show();
- return true;
- case R.id.advanced:
- Toast.makeText(this, getString(R.string.advanced_menu),
- Toast.LENGTH_LONG).show();
- if (advanced_mode) {
- Toast.makeText(this, getString(R.string.advanced_off),
- Toast.LENGTH_LONG).show();
- advanced_mode=false;
- }
- else {
- advanced_mode=true;
- Toast.makeText(this, getString(R.string.advanced_on),
- Toast.LENGTH_LONG).show();
- }
- Intent intent = getIntent();
- finish();
- startActivity(intent);
- return true;
- case R.id.selectfile:
- Toast.makeText(this, getString(R.string.select_menu),
- Toast.LENGTH_LONG).show();
- Intent selectIntent = new Intent()
- .setType("*/*")
- .setAction(Intent.ACTION_GET_CONTENT);
- startActivityForResult(Intent.createChooser(selectIntent, "Select a file"), 123);
- return true;
- case R.id.support:
- if (db.numberOfRowsEAP()>0)
- {
- if (profiles.size()>0 && profiles!=null)
- if (profiles.get(0).hasHelpdeskInfo())
- {
- String displayName="";
- String helpEmail="";
- String helpPhone="";
- String helpURL="";
- if (profiles.get(0).getHelpdeskURL()!=null) { helpURL=profiles.get(0).getHelpdeskURL().toString(); }
- if (profiles.get(0).getHelpdeskPhoneNumber()!=null) { helpPhone=profiles.get(0).getHelpdeskPhoneNumber();}
- if (profiles.get(0).getSupportEmails()!=null) { helpEmail=profiles.get(0).getSupportEmails(); }
- if (profiles.get(0).getDisplayName()!=null) { displayName=profiles.get(0).getDisplayName();}
- String message=getString(R.string.support_message2,displayName);
- message+=" ";
- message+=getString(R.string.support_message3)+"\n";
- if (helpEmail.length()>0) message+=getString(R.string.support_email)+helpEmail+"\n";
- if (helpPhone.length()>0) message+=getString(R.string.support_phone)+helpPhone+"\n";
- if (helpURL.length()>0) message+=getString(R.string.support_web)+helpURL;
- alertUser(message,getString(R.string.support_title),this);
- }
- else alertUser(getString(R.string.support_message1),getString(R.string.support_title),this);
- }
- else alertUser(getString(R.string.support_message1),getString(R.string.support_title),this);
- return true;
- case R.id.about:
- alertUser(getString(R.string.about_text),getString(R.string.support_title),this);
- return true;
-
-// case R.id.exit:
-// Intent intent = new Intent(Intent.ACTION_MAIN);
-// intent.addCategory(Intent.CATEGORY_HOME);
-// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-// startActivity(intent);
-// finish();
-// //System.exit(0);
-// return true;
- }
- return false;
- }
-
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if(requestCode==123 && resultCode==RESULT_OK) {
- Uri selectedfile = data.getData();
- eduroamCAT.debug("Got eap-config uri of:"+selectedfile);
- //content://com.android.providers.downloads.documents/document/8
- Intent download = new Intent(this, EAPMetadata.class);
- download.setData(selectedfile);
- startActivity(download);
- eduroamCAT.debug("started activity");
- }
- }
-
- @Override
- public void onDestroy()
- {
- Log.d("eduroamCAT", "***** mainActivity onDestroy()");
- try
- {
- unregisterReceiver(wifiStatus);
- }
- catch (Exception e)
- {
- debug("Already unregistered reciever...");
- }
- super.onDestroy();
- finish();
- }
-
- @Override
- protected void onResume()
- {
- registerReceiver(wifiStatus, intentFilter);
- Log.d("eduroamCAT", "***** mainActivity onResume()");
- debug("num rows wifi="+db.numberOfRowsWiFi());
- super.onResume();
- }
-
- @Override
- protected void onRestart()
- {
- registerReceiver(wifiStatus, intentFilter);
- Log.d("eduroamCAT", "***** mainActivity onRestart()");
- super.onRestart();
- }
-
- @Override
- protected void onPause()
- {
- Log.d("eduroamCAT", "***** mainActivity onPause()");
- unregisterReceiver(wifiStatus);
- super.onPause();
- }
-
- @Override
- protected void onStart() {
- registerReceiver(wifiStatus, intentFilter);
- Log.d("eduroamCAT", "***** mainActivity onStart()");
- super.onStart();
- }
-
-}
+//*******************
+//Author: Gareth Ayres
+//SENSE Project
+//https://github.com/GEANT/CAT-Android
+//*******************
+
+package uk.ac.swansea.eduroamcat;
+
+import java.util.ArrayList;
+import java.util.List;
+import android.app.NotificationManager;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.os.Bundle;
+import android.app.ActionBar;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Fragment;
+import android.app.FragmentTransaction;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.NotificationCompat;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.WindowManager;
+import android.widget.Toast;
+import android.net.Uri;
+
+public class eduroamCAT extends FragmentActivity implements ActionBar.TabListener
+{
+ private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
+ //final static vars
+ private static WifiManager wifi = null;
+ static WifiController wifiCon = null;
+ static BroadcastReceiver wifiStatus = null;
+ static WifiConfigAPI18 wifiConfig18 = null;
+ static WiFiProfile wifiProfile = null;
+ static ArrayList