@Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { // Parse Arguments for (Argument arg : aH.interpret(scriptEntry.getArguments())) { if (!scriptEntry.hasObject("action") && arg.matchesEnum(Action.values())) scriptEntry.addObject("action", Action.valueOf(arg.getValue().toUpperCase())); else if (!scriptEntry.hasObject("range") && arg.matchesPrimitive(aH.PrimitiveType.Double) && arg.matchesPrefix("range, r")) scriptEntry.addObject("range", arg.asElement()); else if (!scriptEntry.hasObject("id") && arg.matchesPrefix("id, i")) scriptEntry.addObject("id", arg.asElement()); else if (!scriptEntry.hasObject("location") && arg.matchesArgumentType(dLocation.class)) scriptEntry.addObject("location", arg.asType(dLocation.class)); else arg.reportUnhandled(); } // Check required arguments if (!scriptEntry.hasNPC()) throw new InvalidArgumentsException("NPC linked was missing or invalid."); if (!scriptEntry.hasObject("action")) throw new InvalidArgumentsException( "Must specify an 'Anchor Action'. Valid: " + Action.values()); }
@Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) { if (!scriptEntry.hasObject("action") && arg.matchesEnum(Action.values())) { scriptEntry.addObject("action", arg.asElement()); } else if (!scriptEntry.hasObject("group") && arg.matchesPrefix("group")) { scriptEntry.addObject("group", arg.asElement()); } else if (!scriptEntry.hasObject("world") && arg.matchesArgumentType(dWorld.class)) { scriptEntry.addObject("world", arg.asType(dWorld.class)); } else if (!scriptEntry.hasObject("permission")) { scriptEntry.addObject("permission", arg.asElement()); } } if (!scriptEntry.hasObject("group") && (!((BukkitScriptEntryData) scriptEntry.entryData).hasPlayer() || !((BukkitScriptEntryData) scriptEntry.entryData).getPlayer().isValid())) { throw new InvalidArgumentsException("Must have player context or a valid group!"); } if (!scriptEntry.hasObject("action")) { throw new InvalidArgumentsException("Must specify a valid action!"); } if (!scriptEntry.hasObject("permission")) { throw new InvalidArgumentsException("Must specify a permission!"); } }
private void updateProgress() { for (Action a : Action.values()) { if (a == currentAction) { // this is the current action showInProgress(a.viewId); } else if (a.ordinal() < currentAction.ordinal()) { // this action has completed showResult(a.viewId, results[a.ordinal()]); } else { // this action hasn't started showNotStarted(a.viewId); } } ChipsetDetection detection = ChipsetDetection.getDetection(); if (currentAction == Action.Finished) if (detection == null || detection.getWifiChipset() == null || detection.getWifiChipset().supportedModes == null || detection.getWifiChipset().supportedModes.contains(WifiMode.Adhoc) == false) { app.showNoAdhocDialog = true; LogActivity.logMessage( "detect", "Could not work out how to control your WiFi chipset. Relying on operating system, so no ad-hoc WiFi.", false); } }
private static Action scanAction() { while (true) { System.out.print("0-Salir 1-Nuevo 2-Editar 3-Eliminar 4-Consultar 5-Listar: "); String action = scanner.nextLine().trim(); if (action.matches("[012345]")) return Action.values()[Integer.parseInt(action)]; System.out.println("Opción inválida."); } }
public static Action getByName(String name, Action defaultAction) { for (Action action : Action.values()) { if (action.getName().equals(name)) { return action; } } return defaultAction; }
@JsonCreator public static Action fromString(String text) { if (text != null) { for (Action b : Action.values()) { if (text.equalsIgnoreCase(b.text)) { return b; } } } return null; }
@Override public void read(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion) { if (protocolVersion < ProtocolConstants.MINECRAFT_SNAPSHOT) { items = new Item[1]; Item item = items[0] = new Item(); item.displayName = item.username = readString(buf); action = !buf.readBoolean() ? Action.REMOVE_PLAYER : Action.ADD_PLAYER; item.ping = buf.readShort(); } else { action = Action.values()[DefinedPacket.readVarInt(buf)]; items = new Item[DefinedPacket.readVarInt(buf)]; for (int i = 0; i < items.length; i++) { Item item = items[i] = new Item(); item.setUuid(DefinedPacket.readUUID(buf)); switch (action) { case ADD_PLAYER: item.username = DefinedPacket.readString(buf); item.properties = new String[DefinedPacket.readVarInt(buf)][]; for (int j = 0; j < item.properties.length; j++) { String name = DefinedPacket.readString(buf); String value = DefinedPacket.readString(buf); if (buf.readBoolean()) { item.properties[j] = new String[] {name, value, DefinedPacket.readString(buf)}; } else { item.properties[j] = new String[] {name, value}; } } item.gamemode = DefinedPacket.readVarInt(buf); item.ping = DefinedPacket.readVarInt(buf); if (buf.readBoolean()) { item.displayName = DefinedPacket.readString(buf); } break; case UPDATE_GAMEMODE: item.gamemode = DefinedPacket.readVarInt(buf); break; case UPDATE_LATENCY: item.ping = DefinedPacket.readVarInt(buf); break; case UPDATE_DISPLAY_NAME: if (buf.readBoolean()) { item.displayName = DefinedPacket.readString(buf); } } } } }
private void attachEventHandlers() { for (final Action a : Action.values()) { final Button b = (Button) findViewById(a.res); if (a.repeat) { b.setOnTouchListener( new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: sender.send(a); break; case MotionEvent.ACTION_UP: sender.stop(a); break; } return false; } }); } else { b.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { sender.send(a); } }); } } SeekBar sb = (SeekBar) findViewById(R.id.pause); sb.setProgress(Sender.DEFAULT_PAUSE); sb.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) {} public void onStartTrackingTouch(SeekBar seekBar) {} public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { sender.setPause(progress); } }); }
private Action getAction() { return Action.values()[getArguments().getInt(ARGUMENT_ACTION)]; }
@Override protected Action doInBackground(Void... arg) { wakeLock.acquire(); try { ChipsetDetection detection = ChipsetDetection.getDetection(); while (true) { boolean result = false; boolean fatal = currentAction.fatal; try { Log.v("BatPhone", "Performing action " + currentAction); switch (currentAction) { case Unpacking: app.installFilesIfRequired(); result = true; break; case AdhocWPA: if (false) { // Get wifi manager WifiManager wm = (WifiManager) ServalBatPhoneApplication.context.getSystemService(Context.WIFI_SERVICE); // enable wifi wm.setWifiEnabled(true); WifiConfiguration wc = new WifiConfiguration(); wc.SSID = "*supplicant-test"; int res = wm.addNetwork(wc); Log.d("BatPhone", "add Network returned " + res); boolean b = wm.enableNetwork(res, true); Log.d("WifiPreference", "enableNetwork returned " + b); } break; case RootCheck: result = ServalBatPhoneApplication.context.coretask.hasRootPermission(); break; case Supported: // Start out by only looking for non-experimental // chipsets detection.identifyChipset(); result = detection.detected_chipsets.size() > 0; break; case Experimental: if (!results[Action.Supported.ordinal()]) { detection.inventSupport(); // this will not select a chipset detection.detect(true); result = detection.detected_chipsets.size() > 0; } break; case CheckSupport: result = testSupport(); break; case Finished: break; } } catch (Exception e) { result = false; Log.e("BatPhone", e.toString(), e); app.displayToastMessage(e.getMessage()); fatal = true; } results[currentAction.ordinal()] = result; Log.v("BatPhone", "Result " + result); if (fatal && !result) { fatalError = true; return currentAction; } if (currentAction == Action.Finished) { ServalBatPhoneApplication.wifiSetup = true; return currentAction; } this.publishProgress(currentAction); currentAction = Action.values()[currentAction.ordinal() + 1]; } } finally { wakeLock.release(); dismissTryExperimentalChipsetDialog(); } }
public class PreparationWizard extends Activity { public enum Action { NotStarted, Unpacking(R.id.starUnpack, true), AdhocWPA, RootCheck(R.id.starRoot), Supported(R.id.starChipsetSupported), Experimental(R.id.starChipsetExperimental), CheckSupport(R.id.starTestChipset), Finished; int viewId = 0; boolean fatal = false; Action() {} Action(int viewId) { this(viewId, false); } Action(int viewId, boolean fatal) { this.viewId = viewId; this.fatal = fatal; } } protected static final int DISMISS_PROGRESS_DIALOG = 0; protected static final int CREATE_PROGRESS_DIALOG = 1; public static Action currentAction = Action.NotStarted; public static boolean results[] = new boolean[Action.values().length]; public static boolean fatalError = false; private ServalBatPhoneApplication app; static PreparationWizard instance = null; private ProgressDialog progressDialog = null; AlertDialog alert = null; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case DISMISS_PROGRESS_DIALOG: if (progressDialog != null) progressDialog.cancel(); break; case CREATE_PROGRESS_DIALOG: progressDialog = ProgressDialog.show( instance, "", "Trying some educated guesses as to how to drive your WiFi chipset. If it takes more than a couple of minutes, or freezes, try rebooting the phone. I will remember not to try whichever guess got stuck.", true); progressDialog.setCancelable(false); break; } } }; public static void showTryExperimentalChipsetDialog() { instance.handler.sendEmptyMessage(CREATE_PROGRESS_DIALOG); } public static void dismissTryExperimentalChipsetDialog() { instance.handler.sendEmptyMessage(DISMISS_PROGRESS_DIALOG); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PreparationWizard.instance = this; setContentView(R.layout.preparationlayout); app = (ServalBatPhoneApplication) this.getApplication(); } @Override protected void onPause() { super.onPause(); } private void updateProgress() { for (Action a : Action.values()) { if (a == currentAction) { // this is the current action showInProgress(a.viewId); } else if (a.ordinal() < currentAction.ordinal()) { // this action has completed showResult(a.viewId, results[a.ordinal()]); } else { // this action hasn't started showNotStarted(a.viewId); } } ChipsetDetection detection = ChipsetDetection.getDetection(); if (currentAction == Action.Finished) if (detection == null || detection.getWifiChipset() == null || detection.getWifiChipset().supportedModes == null || detection.getWifiChipset().supportedModes.contains(WifiMode.Adhoc) == false) { app.showNoAdhocDialog = true; LogActivity.logMessage( "detect", "Could not work out how to control your WiFi chipset. Relying on operating system, so no ad-hoc WiFi.", false); } } @Override protected void onResume() { super.onResume(); updateProgress(); // Start by installing files and continuing if (currentAction == Action.NotStarted) new PreparationTask().execute(); } private void showInProgress(int item) { ImageView imageView = (ImageView) findViewById(item); if (imageView != null) { final AnimationDrawable yourAnimation; imageView.setBackgroundResource(R.drawable.preparation_progress); yourAnimation = (AnimationDrawable) imageView.getBackground(); imageView.setImageDrawable(yourAnimation); imageView.setVisibility(ImageView.VISIBLE); yourAnimation.start(); } return; } private void showNotStarted(int id) { ImageView imageView = (ImageView) findViewById(id); if (imageView != null) { imageView.setVisibility(ImageView.INVISIBLE); imageView.setImageResource(R.drawable.jetxee_tick_yellow); } return; } private void showResult(int id, Boolean result) { ImageView imageView = (ImageView) findViewById(id); int imageid; if (result) imageid = R.drawable.jetxee_tick_yellow; else imageid = R.drawable.jetxee_cross_yellow; if (imageView != null) { imageView.setImageResource(imageid); imageView.setBackgroundResource(0); imageView.setVisibility(ImageView.VISIBLE); } return; } public void installedFiles(boolean result) { if (result) return; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder .setMessage("Sorry, I couldn't extract all the files I needed.") .setCancelable(false) .setPositiveButton( "Quit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // Do nothing -- just let the user close the // activity. } }); AlertDialog alert = builder.create(); alert.show(); } public void checkedChipsetSupported(boolean result) { // XXX - Need to handle multiple detections here so that we can give the // user a choice, and then test that choice. if (result) { TextView t = (TextView) findViewById(R.id.labelChipsetSupported); t.setText("I think your WiFi is '" + ChipsetDetection.getDetection().getChipset() + "'."); t = (TextView) findViewById(R.id.labelChipsetExperimental); t.setText("Skipped check for experimental support, since we already support your handset."); } } public static boolean preparationRequired() { return ServalBatPhoneApplication.context.getState() == State.Installing; } class PreparationTask extends AsyncTask<Void, Action, Action> { private PowerManager.WakeLock wakeLock = null; PreparationTask() { PowerManager powerManager = (PowerManager) ServalBatPhoneApplication.context.getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "PREPARATION_WAKE_LOCK"); } private boolean testSupport() { ChipsetDetection detection = ChipsetDetection.getDetection(); List<Chipset> l = detection.detected_chipsets; boolean tryExperimental = false; while (true) { for (int i = 0; i < l.size(); i++) { Chipset c = l.get(i); if (c.isExperimental() != tryExperimental) continue; // only test scripts if we have root access, otherwise // assume the first one is correct if (results[Action.RootCheck.ordinal()]) { if (!c.supportedModes.contains(WifiMode.Adhoc)) continue; // Write a disable file that suppresses attempting // this detection again so that re-running the BatPhone // preparation wizard will not get stuck on the same // chipset every time File attemptFlag = new File(app.coretask.DATA_FILE_PATH + "/var/attempt_" + c.chipset); if (attemptFlag.exists()) { Log.v("BatPhone", "Skipping " + c.chipset + " as I think it failed before"); continue; } // If a chipset is marked experimental, then tell the // user. if (tryExperimental) PreparationWizard.showTryExperimentalChipsetDialog(); try { attemptFlag.createNewFile(); Log.v("BatPhone", "Trying to use chipset " + c.chipset); detection.setChipset(c); if (app.wifiRadio == null) app.wifiRadio = WiFiRadio.getWiFiRadio(app); // make sure we aren't still in adhoc mode from a // previous // install / test if (WifiMode.getWiFiMode() != WifiMode.Off) app.wifiRadio.setWiFiMode(WifiMode.Off); if (WifiMode.getWiFiMode() != WifiMode.Off) { throw new IllegalStateException("Could not turn wifi off"); } // test adhoc on & off try { app.wifiRadio.setWiFiMode(WifiMode.Adhoc); app.wifiRadio.setWiFiMode(WifiMode.Off); } finally { if (WifiMode.getWiFiMode() != WifiMode.Off) { attemptFlag = null; throw new IllegalStateException("Could not turn wifi off"); } } } catch (IOException e) { Log.e("BatPhone", e.toString(), e); } finally { // If we couldn't turn off wifi, just fail completely if (attemptFlag != null) attemptFlag.delete(); } } else { Log.v("BatPhone", "Assuming chipset " + c.chipset + " as there is no root access."); detection.setChipset(c); } Editor ed = app.settings.edit(); ed.putString("detectedChipset", c.chipset); ed.commit(); LogActivity.logMessage( "detect", "We will use the '" + c.chipset + "' script to control WiFi.", false); return true; } tryExperimental = !tryExperimental; if (tryExperimental == false) break; } detection.setChipset(null); Editor ed = app.settings.edit(); ed.putString("detectedChipset", "UnKnown"); ed.commit(); return false; } @Override protected Action doInBackground(Void... arg) { wakeLock.acquire(); try { ChipsetDetection detection = ChipsetDetection.getDetection(); while (true) { boolean result = false; boolean fatal = currentAction.fatal; try { Log.v("BatPhone", "Performing action " + currentAction); switch (currentAction) { case Unpacking: app.installFilesIfRequired(); result = true; break; case AdhocWPA: if (false) { // Get wifi manager WifiManager wm = (WifiManager) ServalBatPhoneApplication.context.getSystemService(Context.WIFI_SERVICE); // enable wifi wm.setWifiEnabled(true); WifiConfiguration wc = new WifiConfiguration(); wc.SSID = "*supplicant-test"; int res = wm.addNetwork(wc); Log.d("BatPhone", "add Network returned " + res); boolean b = wm.enableNetwork(res, true); Log.d("WifiPreference", "enableNetwork returned " + b); } break; case RootCheck: result = ServalBatPhoneApplication.context.coretask.hasRootPermission(); break; case Supported: // Start out by only looking for non-experimental // chipsets detection.identifyChipset(); result = detection.detected_chipsets.size() > 0; break; case Experimental: if (!results[Action.Supported.ordinal()]) { detection.inventSupport(); // this will not select a chipset detection.detect(true); result = detection.detected_chipsets.size() > 0; } break; case CheckSupport: result = testSupport(); break; case Finished: break; } } catch (Exception e) { result = false; Log.e("BatPhone", e.toString(), e); app.displayToastMessage(e.getMessage()); fatal = true; } results[currentAction.ordinal()] = result; Log.v("BatPhone", "Result " + result); if (fatal && !result) { fatalError = true; return currentAction; } if (currentAction == Action.Finished) { ServalBatPhoneApplication.wifiSetup = true; return currentAction; } this.publishProgress(currentAction); currentAction = Action.values()[currentAction.ordinal() + 1]; } } finally { wakeLock.release(); dismissTryExperimentalChipsetDialog(); } } private void stepProgress(Action a) { updateProgress(); boolean result = results[a.ordinal()]; switch (a) { case Unpacking: installedFiles(result); break; case Supported: checkedChipsetSupported(result); break; case CheckSupport: if (fatalError) { Intent intent = new Intent(ServalBatPhoneApplication.context, WifiJammedActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } break; case Finished: app.getReady(); // TODO tell user if we can't do Adhoc?? finish(); } } @Override protected void onProgressUpdate(Action... arg) { stepProgress(arg[0]); } @Override protected void onPostExecute(Action arg) { stepProgress(arg); } } }
@Override public void readFromClientData(ProtocolSupportPacketDataSerializer serializer) { entityId = serializer.readInt(); action = Action.values()[serializer.readByte()]; }
public static Action getAction(byte b) { for (Action a : Action.values()) { if (a.action == b) return a; } return null; }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Action ac = null; try { ac = Action.valueOf(req.getParameter("action")); } catch (Exception e) { resp.sendError( 400, "'action' parameter required, can be " + Arrays.toString(Action.values())); return; } // okay, we now know what we want to do switch (ac) { case submit: // 1st: validate inputs String email = req.getParameter("email"); String url = req.getParameter("url"); String intervalStr = req.getParameter("interval"); if (!Utils.isValidEmailAddress(email)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'email' parameter"); return; } if (!Utils.isValidUrl(url)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'url' parameter"); return; } if (!Utils.isValidInterval(intervalStr, intervals)) { resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "invalid 'interval' parameter, can be " + intervals.toString()); return; } // 2nd: put our task in the data store, but not enable it yet Entity job = new Entity("Job"); job.setProperty("url", url); job.setProperty("intervalSeconds", Integer.parseInt(intervalStr)); job.setProperty("email", email); job.setProperty("enabled", false); String id = UUID.randomUUID().toString(); job.setProperty("id", id); datastore.put(job); log.info( "New request: url=" + url + ",email=" + email + ",interval=" + intervalStr + ",id=" + id); // 3rd: send email to admin asking to confirm String confirmUrl = "http://" + Utils.HOSTNAME + "/pmc?action=enable&id=" + id; Utils.sendMail( email, "Hello.\n\nThis is the \"Poor Man's cron service\" at " + Utils.HOSTNAME + ".\nI have been asked (probably by you) to send a request to the URL " + url + " every " + intervalStr + " seconds.\nIf you think that's okay, please visit the following URL: " + confirmUrl + "\n\nBest, PMC"); // 4th: display some message on response stream. resp.getWriter() .write( "Okay, I have received your job. Please check your eMail for further instructions. "); resp.getWriter().close(); break; case enable: String enableid = req.getParameter("id"); // 1st: validate inputs if (!Utils.isValidId(enableid)) { resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter, should be a UUID"); return; } // 2nd: look if we know a job with that id List<Entity> jobs = datastore .prepare( new Query("Job") .setFilter(new FilterPredicate("id", FilterOperator.EQUAL, enableid))) .asList(withLimit(1)); if (jobs.size() < 1) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter"); return; } // 3rd: set job to be enabled Entity enableJob = jobs.get(0); enableJob.setProperty("enabled", true); datastore.put(enableJob); log.info("Enabled: id=" + enableid); // 4th: send confirmation mail String deleteLink = "http://" + Utils.HOSTNAME + "/pmc?action=delete&id=" + enableid; String viewLink = "http://" + Utils.HOSTNAME + "/pmc?action=view&id=" + enableid; Utils.sendMail( (String) enableJob.getProperty("email"), "Hello again!\n\nThis is the \"Poor Man's cron service\" at " + Utils.HOSTNAME + ".\nI have enabled your job to send a request to the URL " + enableJob.getProperty("url") + " every " + enableJob.getProperty("intervalSeconds") + " seconds.\nIf you want to see how your job is doing, and what your URL has to say, visit this page: " + viewLink + "\n\nIf you want to cancel this job again, please click on the following link: " + deleteLink + "\n\nIt would be advisable to keep this message, as it would otherwise be hard to stop me from accessing your URL.\n\nBest, PMC"); // 5th: display some message on response stream. resp.getWriter() .write( "Okay, I have enabled your job. Please check your eMail for further instructions. "); resp.getWriter().close(); break; case view: // TODO: implement me, pleaaase resp.getWriter().write("Not Implemented Yet."); resp.getWriter().close(); break; case delete: String deleteid = req.getParameter("id"); // 1st: validate inputs if (!Utils.isValidId(deleteid)) { resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter, should be a UUID"); return; } // 2nd: look if we know a job with that id List<Entity> jobsd = datastore .prepare( new Query("Job") .setFilter(new FilterPredicate("id", FilterOperator.EQUAL, deleteid))) .asList(withLimit(1)); if (jobsd.size() < 1) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid 'id' parameter"); return; } // 3rd: delete job datastore.delete(jobsd.get(0).getKey()); log.info("Deleted: id=" + deleteid); // 4th: display some message on response stream. resp.getWriter().write("Okay, I have deleted your job. Bye! "); resp.getWriter().close(); break; } }