Java tutorial
package eu.dirtyharry.androidopsiadmin; /** * Android OPSI Admin is an Android Interface to OPSI. * Copyright (C) 2011 Harald Fahrner * * * This file is part of Android OPSI Admin. * * Android OPSI Admin is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Android OPSI Admin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Android OPSI Admin. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Vibrator; import android.util.Log; import android.view.HapticFeedbackConstants; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class Main extends Activity { public String serverip; public String serverport; public String serverusername; public String serverpasswd; public boolean vibrate; public boolean customtags; public String choosendepot = ""; public String contents = ""; public String hosttocheck = ""; public boolean expanded = true; public boolean hostexistsinopsi = true; // public boolean dummymode; // public boolean offlinemode; // public String[] settings; public ArrayList<String> allclients = new ArrayList<String>(); public ArrayList<String> clientdescription = new ArrayList<String>(); public ArrayList<String> clientip = new ArrayList<String>(); public ArrayList<String> clientmac = new ArrayList<String>(); public ArrayList<String> clientnotes = new ArrayList<String>(); public ArrayList<String> clientinventory = new ArrayList<String>(); public ArrayList<String> clientlastseen = new ArrayList<String>(); public static String[] depots = new String[0]; public JSONObject opsiresult = new JSONObject(); public JSONObject pc = new JSONObject(); public ArrayList<String> resultconfignames = new ArrayList<String>(); public ArrayList<String> resultconfigvalues = new ArrayList<String>(); ChangeLog cl; public static String PACKAGE_NAME; public static String VERSION_NAME; private static final int GET_OPSI_CLIENT_REQUEST = 1001; private static final int GET_QR = 1002; private static final int SHOW_OPSI_DEPOT_REQUEST = 1003; private static final String SHORTCUT_ACTION = "shortcut"; public String doit = "false"; Thread checkUpdate = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); PACKAGE_NAME = this.getPackageName(); try { VERSION_NAME = Main.this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Eula.show(Main.this, getString(R.string.gen_lang_prefix)); cl = new ChangeLog(this); if (cl.firstRun()) cl.getLogDialog().show(); // FirstTimeUsageDialog.show(Main.this,"main_test","main_test.accepted"); // new Functions().noPreferences(Main.this, // getString(R.string.gen_title_error), // getString(R.string.gen_setpreferences)); // public SharedPreferences preferences = // Main.this.getSharedPreferences( // getPackageName() + "_preferences", MODE_PRIVATE); // CookieSyncManager.createInstance(this); SharedPreferences preferences = Main.this.getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE); serverip = preferences.getString("serverip", ""); serverport = preferences.getString("serverport", ""); serverusername = preferences.getString("serverusername", ""); serverpasswd = preferences.getString("serverpasswd", ""); vibrate = preferences.getBoolean("vibrate", true); customtags = preferences.getBoolean("qr_enable_custom_tags", false); String extra = ""; final Intent intent = getIntent(); if (intent.getAction().equals(SHORTCUT_ACTION)) { extra = intent.getStringExtra("shortcut"); } if (extra.equals(getString(R.string.la_allclients))) { getOpsiClientsTask(); } else if (extra.equals(getString(R.string.la_scanqr))) { Intent qrDroid = new Intent("la.droid.qr.scan"); qrDroid.putExtra("la.droid.qr.complete", true); try { startActivityForResult(qrDroid, GET_QR); } catch (ActivityNotFoundException activity) { Functions.qrDroidRequired(Main.this); } } } @Override public void onResume() { super.onResume(); // new Functions().noPreferences(Main.this, // getString(R.string.gen_title_error), // getString(R.string.gen_setpreferences)); SharedPreferences preferences = Main.this.getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE); serverip = preferences.getString("serverip", ""); serverport = preferences.getString("serverport", ""); serverusername = preferences.getString("serverusername", ""); serverpasswd = preferences.getString("serverpasswd", ""); vibrate = preferences.getBoolean("vibrate", true); customtags = preferences.getBoolean("qr_enable_custom_tags", false); // CookieSyncManager.getInstance().startSync(); // dummymode = preferences.getBoolean("dummymode", false); // offlinemode = preferences.getBoolean("offlinemode", false); } @Override protected void onPause() { super.onPause(); // CookieSyncManager.getInstance().stopSync(); } public void buttonListener(final View view) { if (vibrate) { view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); } // new Functions().noPreferences(Main.this, // getString(R.string.gen_title_error), // getString(R.string.gen_setpreferences)); if (!new Functions().checkPreferences(Main.this)) { new Functions().noPreferences(Main.this, getString(R.string.gen_title_error), getString(R.string.gen_setserverpreferences)); return; } // noPreferences(Main.this, // getString(R.string.gen_title_error), // getString(R.string.gen_setpreferences)); switch (view.getId()) { case R.id.bt_scanqr: // Intent intent = new // Intent("com.google.zxing.client.android.SCAN"); // intent.setPackage("com.google.zxing.client.android"); // intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // setResult(RESULT_OK, intent); // startActivityForResult(intent, 0); Intent qrDroid = new Intent("la.droid.qr.scan"); qrDroid.putExtra("la.droid.qr.complete", true); try { startActivityForResult(qrDroid, GET_QR); } catch (ActivityNotFoundException activity) { Functions.qrDroidRequired(Main.this); } break; case R.id.bt_getopsiclients: Log.d("Barcode", "getopsiclient"); // if (Networking.isConnected(Main.this)) { getOpsiClientsTask(); // } else { // Toast.makeText(Main.this, R.string.to_wifinotconnected, // Toast.LENGTH_LONG).show(); // } break; case R.id.bt_defineclientselection: if (Networking.isConnected(Main.this)) { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), getString(R.string.pd_getclients), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (GlobalVar.getInstance().getError().equals("null")) { if (doit.equals("serverdown")) { Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip), Toast.LENGTH_LONG).show(); } } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) { doit = "true"; Intent i = new Intent(Main.this, ShowOpsiClientFilter.class); startActivity(i); } else { doit = "serverdown"; } handler.sendEmptyMessage(0); } }; checkUpdate.start(); } else { Toast.makeText(Main.this, R.string.to_wifinotconnected, Toast.LENGTH_LONG).show(); } break; case R.id.bt_createopsiclient: // new Functions().notImplementet(Main.this); Intent i = new Intent(Main.this, ShowOpsiCreateClient.class); startActivity(i); break; case R.id.bt_showdepotconfig: // new Functions().notImplementet(Main.this); Log.d("Barcode", "depotconfig"); if (Networking.isConnected(Main.this)) { getOPSIDepots(); } else { Toast.makeText(Main.this, R.string.to_wifinotconnected, Toast.LENGTH_LONG).show(); } break; // case R.id.bt_test: // ArrayList<String> test = new ArrayList<String>(); // test.add("test1"); // test.add("test2"); // test.add("test3"); // test.add("test4"); // ShowOpsiClientOptionsButtonDialog buttondialog = new // ShowOpsiClientOptionsButtonDialog(Main.this,test); // buttondialog.setTitle("testtitle"); // buttondialog.show(); // break; } } public void getOpsiClientsTask() { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), getString(R.string.pd_getclients), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (GlobalVar.getInstance().getError().equals("null")) { if (doit.equals("true")) { Intent i = new Intent(Main.this, ShowOpsiClientsListView.class); Bundle b = new Bundle(); b.putStringArrayList("allclients", allclients); b.putStringArrayList("clientdescriptions", clientdescription); b.putStringArrayList("clientmacs", clientmac); b.putStringArrayList("clientnotes", clientnotes); b.putStringArrayList("clientips", clientip); b.putStringArrayList("clientinventorys", clientinventory); b.putStringArrayList("clientlastseens", clientlastseen); i.putExtras(b); startActivityForResult(i, GET_OPSI_CLIENT_REQUEST); } else if (doit.equals("serverdown")) { Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip), Toast.LENGTH_LONG).show(); } } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); // GlobalVar.getInstance().setError("null"); } } }; checkUpdate = new Thread() { public void run() { Looper.prepare(); if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) { getOpsiClients("rpc", serverip, serverport, "host_getHashes", serverusername, serverpasswd); doit = "true"; } else { doit = "serverdown"; // } handler.sendEmptyMessage(0); } }; checkUpdate.start(); // RTM ???? // checkUpdate.interrupt(); } public void getOpsiClients(final String serverorclient, final String ipaddress, final String port, final String method, final String user, final String passwd) { allclients.clear(); clientdescription.clear(); clientip.clear(); clientmac.clear(); clientnotes.clear(); clientinventory.clear(); clientlastseen.clear(); JSONArray getopsiproductactionstatusjsonparams = new JSONArray(); JSONObject opsiresult = new JSONObject(); opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject(serverorclient, ipaddress, port, method, getopsiproductactionstatusjsonparams, user, passwd); Log.d("Barcode", "error: " + GlobalVar.getInstance().getError()); if (GlobalVar.getInstance().getError().equals("null")) { try { JSONArray tmpopsiresultarray = opsiresult.getJSONArray("result"); JSONObject tmpopsiresultobject = new JSONObject(); if (tmpopsiresultarray.length() > 1) { for (int i = 0; i < tmpopsiresultarray.length(); i++) { tmpopsiresultobject = tmpopsiresultarray.getJSONObject(i); if (tmpopsiresultobject.getString("type").equals("OpsiClient")) { allclients.add(tmpopsiresultobject.getString("id")); if (tmpopsiresultobject.getString("description").equals("")) { clientdescription.add(getString(R.string.gen_notset)); } else { clientdescription.add(tmpopsiresultobject.getString("description")); } clientip.add(tmpopsiresultobject.getString("ipAddress")); clientmac.add(tmpopsiresultobject.getString("hardwareAddress")); clientnotes.add(tmpopsiresultobject.getString("notes")); clientinventory.add(tmpopsiresultobject.getString("inventoryNumber")); // new Functions(); // int dayssince = // Functions.getPassedDays(tmpopsiresultobject.getString("lastSeen")); // clientlastseen.add("" + dayssince); clientlastseen.add(tmpopsiresultobject.getString("lastSeen")); } else { continue; } } } else { GlobalVar.getInstance().setError("Keine OPSI Clients gefunden"); } // doit = true; } catch (JSONException e) { e.printStackTrace(); } } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } // } } public void getOPSIDepotConfig(final String depot) { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), String.format(getString(R.string.pd_getdepotconfigfor), depot), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (GlobalVar.getInstance().getError().equals("null")) { Intent i = new Intent(Main.this, ShowOpsiHostParamsListView.class); Bundle b = new Bundle(); b.putString("hostparams", opsiresult.toString()); b.putString("pc", choosendepot); b.putString("opsitype", "OpsiConfigserver"); i.putExtras(b); startActivityForResult(i, SHOW_OPSI_DEPOT_REQUEST); } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); JSONArray JSONparams = new JSONArray(); JSONparams.put(depot); opsiresult = new JSONObject(); opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip, serverport, "getDepot_hash", JSONparams, serverusername, serverpasswd); handler.sendEmptyMessage(0); } }; checkUpdate.start(); } public void getOPSIDepots() { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), getString(R.string.pd_getdepots), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (GlobalVar.getInstance().getError().equals("null")) { if (doit.equals("true")) { JSONArray result = new JSONArray(); try { result = opsiresult.getJSONArray("result"); depots = new String[result.length()]; for (int i = 0; i < result.length(); i++) { depots[i] = result.getString(i); } } catch (JSONException e) { e.printStackTrace(); } AlertDialog.Builder builder = new AlertDialog.Builder(Main.this); builder.setTitle(getString(R.string.gen_choose)); builder.setSingleChoiceItems(depots, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { dialog.dismiss(); String depot = depots[item]; choosendepot = depot; getOPSIDepotConfig(depot); } }); AlertDialog alert = builder.create(); alert.show(); } else if (doit.equals("serverdown")) { Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip), // serverip + " " // + getString(R.string.to_servernotrechable), Toast.LENGTH_LONG).show(); } } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); JSONArray JSONparams = new JSONArray(); if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) { opsiresult = new JSONObject(); opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip, serverport, "getDepotIds_list", JSONparams, serverusername, serverpasswd); doit = "true"; } else { doit = "serverdown"; // } handler.sendEmptyMessage(0); } }; checkUpdate.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (vibrate) { Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(50); } switch (item.getItemId()) { case R.id.menu_preferences: Log.d("Barcode", "display preferences"); new Functions().displayPreferences(Main.this); break; case R.id.menu_changelog: cl.getFullLogDialog().show(); // case R.id.menu_close: break; case R.id.menu_donate: Intent browse = new Intent(Intent.ACTION_VIEW, Uri .parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LJAYM3ND7MUQE")); startActivity(browse); // Toast.makeText(Main.this, "Spenden!", Toast.LENGTH_LONG).show(); // case R.id.menu_close: break; case R.id.menu_about: Intent about = new Intent(Main.this, ShowAbout.class); startActivity(about); // Toast.makeText(Main.this, "ber", Toast.LENGTH_LONG).show(); // case R.id.menu_close: break; } return super.onOptionsItemSelected(item); } public void event_opsisenddepotconfigchanges() { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), String.format(getString(R.string.pd_senddepotchangesfor), choosendepot), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (!GlobalVar.getInstance().getError().equals("null")) { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); JSONArray test = new JSONArray(); JSONObject params = new JSONObject(); try { params.put("id", choosendepot); params.put("type", "OpsiConfigserver"); for (int i = 0; i < resultconfignames.size(); i++) { params.put(resultconfignames.get(i), resultconfigvalues.get(i)); } } catch (JSONException e1) { e1.printStackTrace(); } test.put(params); opsiresult = new JSONObject(); opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip, serverport, "host_updateObject", test, serverusername, serverpasswd); try { if (!opsiresult.isNull("error")) { GlobalVar.getInstance().setError(opsiresult.getString("error")); } } catch (JSONException e) { e.printStackTrace(); } handler.sendEmptyMessage(0); } }; checkUpdate.start(); } // private class SendOpsiProductsToInstallTask extends // AsyncTask<String, Integer, Long> { // // ProgressDialog dialog; // int increment; // // Handler progressHandler = new Handler() { // public void handleMessage(Message msg) { // dialog.incrementProgressBy(increment); // } // }; // // @Override // protected void onPostExecute(Long result) { // dialog.dismiss(); // // alreadydone = ""; // // } // // @Override // protected void onPreExecute() { // // dialog = new ProgressDialog(Main.this); // dialog.setCancelable(true); // dialog.setMessage(getString(R.string.pd_loading)); // // set the progress to be horizontal // dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // // reset the bar to the default value of 0 // dialog.setProgress(0); // // // convert the text value to a integer // int maximum = 100; // // set the maximum value // dialog.setMax(maximum); // // display the progressbar // dialog.show(); // } // // @Override // protected Long doInBackground(String... param) { // if (!choosendepot.equals("")) { // // if (GlobalVar.getInstance().getError().equals("null")) { // if (resultconfignames != null && !resultconfignames.isEmpty()) { // Looper.prepare(); // // params[1] = params[0]; // int size = resultconfignames.size(); // increment = 100 / size; // // for (String resultproduct : resultproducts) { // JSONArray test = new JSONArray(); // JSONObject params = new JSONObject(); // // params.put("id", choosendepot); // params.put("type", "OpsiConfigserver"); // for (int i = 0; i < size; i++) { // // params.put(name, value) // // // test.put(resultproducts.get(i).replace(" ", "")); // // test.put(localornetboot); // // test.put(pc); // // test.put(""); // test.put(resultproductrequests.get(i).replace(" ", "")); // eu.dirtyharry.androidopsiadmin.Networking // .opsiGetJSONObject("rpc", serverip, serverport, // "productOnClient_create", test, // serverusername, serverpasswd); // progressHandler.sendMessage(progressHandler // .obtainMessage()); // } // } // } // return null; // } // } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GET_QR && resultCode == RESULT_OK) { contents = data.getExtras().getString("la.droid.qr.result"); if (checkQR(contents)) { try { pc = (JSONObject) new JSONTokener(contents).nextValue(); hosttocheck = pc.getString("dns"); } catch (JSONException e) { e.printStackTrace(); } final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), String.format(getString(R.string.pd_checkifopsiclientexists), hosttocheck), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { if (hostexistsinopsi && doit.equals("true")) { if (customtags) { Intent i = new Intent(Main.this, ShowBarcodeData.class); Bundle b = new Bundle(); b.putString("qrdata", contents); i.putExtras(b); startActivity(i); } else { Intent i = new Intent(Main.this, ShowOpsiClientOptions.class); Bundle b = new Bundle(); b.putString("qrdata", contents); i.putExtras(b); startActivity(i); } } else if (!hostexistsinopsi) { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), String.format(getString(R.string.general_noopsihost), hosttocheck), false); } else { Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip), Toast.LENGTH_LONG).show(); } dialog.dismiss(); } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); if (eu.dirtyharry.androidopsiadmin.Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) { doit = "true"; if (eu.dirtyharry.androidopsiadmin.Networking.checkIfHostExistsInOpsi(hosttocheck, serverip, serverport, serverusername, serverpasswd)) { hostexistsinopsi = true; } else { hostexistsinopsi = false; } } else { doit = "serverdown"; } handler.sendEmptyMessage(0); } }; checkUpdate.start(); } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), getString(R.string.at_novalidqr), false); } } else if (requestCode == GET_OPSI_CLIENT_REQUEST && resultCode == Activity.RESULT_OK) { if (data.getStringExtra("message").equals("refresh")) { getOpsiClientsTask(); } // } else if (requestCode == SHOW_OPSI_DEPOT_REQUEST // && resultCode == Activity.RESULT_OK) { // resultconfignames = data.getExtras().getStringArrayList( // "choosenones"); // resultconfigvalues = data.getExtras().getStringArrayList( // "choosenonesvalues"); // event_opsisenddepotconfigchanges(); } } public boolean checkQR(String qrstring) { if (qrstring.contains("dns")) { return true; } return false; } }