예제 #1
0
  public void execute(final Context context, boolean force) {
    if (this.enabled(context) && this._action != null) {
      final Trigger me = this;

      Runnable r =
          new Runnable() {
            public void run() {
              try {
                BaseScriptEngine.runScript(context, me._action);
              } catch (Exception e) {
                LogManager.getInstance(context).logException(e);

                HashMap<String, Object> payload = new HashMap<String, Object>();
                payload.put("script", me._action);

                LogManager.getInstance(context).log("failed_trigger_script", payload);
              }
            }
          };

      Thread t = new Thread(new ThreadGroup("Triggers"), r, this.name(), 32768);
      t.start();

      HashMap<String, Object> payload = new HashMap<String, Object>();
      payload.put("name", this.name());
      payload.put("identifier", this.identifier());
      payload.put("action", this._action);

      LogManager.getInstance(context).log("pr_trigger_fired", payload);
    }
  }
예제 #2
0
  protected Object evaluateModel(Context context, Map<String, Object> snapshot) {
    try {
      return this._tree.fetchPrediction(snapshot);
    } catch (TreeNodeException e) {
      LogManager.getInstance(context).logException(e);
    }

    return null;
  }
예제 #3
0
  public boolean put(Context context, JSONObject obj, String key, Object value) {
    try {
      obj.put(key, value);

      return true;
    } catch (JSONException e) {
      LogManager.getInstance(context).logException(e);
    }

    return false;
  }
예제 #4
0
파일: Probe.java 프로젝트: benarito/sensor
  public static void loadProbeClasses(Context context) {
    String packageName = Probe.class.getPackage().getName();

    String[] probeClasses = context.getResources().getStringArray(R.array.probe_classes);

    for (String className : probeClasses) {
      try {
        Probe.registerProbeClass(Class.forName(packageName + "." + className));
      } catch (ClassNotFoundException e) {
        LogManager.getInstance(context).logException(e);
      }
    }
  }
예제 #5
0
  public Object get(Context context, JSONObject obj, String key) {
    try {
      Object value = obj.get(key);

      if (value instanceof JSONArray) value = JSONHelper.toList((JSONArray) value);
      else if (value instanceof JSONObject) value = JSONHelper.toPairs((JSONObject) value);

      return value;
    } catch (JSONException e) {
      LogManager.getInstance(context).logException(e);
    }

    return null;
  }
예제 #6
0
  private void fetchAuth(Context context) {
    String userId = EncryptionManager.getInstance().getUserHash(context);

    Intent intent = new Intent(context, OAuthActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    intent.putExtra(OAuthActivity.CONSUMER_KEY, context.getString(R.string.github_client_id));
    intent.putExtra(
        OAuthActivity.CONSUMER_SECRET, context.getString(R.string.github_client_secret));
    intent.putExtra(OAuthActivity.REQUESTER, "github");
    intent.putExtra(OAuthActivity.CALLBACK_URL, "http://tech.cbits.northwestern.edu/oauth/github");
    intent.putExtra(OAuthActivity.LOG_URL, LogManager.getInstance(context).getLogUrl(context));
    intent.putExtra(OAuthActivity.HASH_SECRET, userId);

    context.startActivity(intent);
  }
예제 #7
0
  public void handle(HttpRequest request, HttpResponse response, HttpContext argument)
      throws HttpException, IOException {
    if (BasicAuthHelper.isAuthenticated(request) == false) {
      BasicAuthHelper.unauthedResponse(response);

      return;
    }

    response.setStatusCode(HttpStatus.SC_OK);

    if (request instanceof HttpEntityEnclosingRequest) {
      HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;

      HttpEntity entity = enclosingRequest.getEntity();

      String entityString = EntityUtils.toString(entity);

      Uri u = Uri.parse("http://localhost/?" + entityString);

      JSONObject arguments = null;

      try {
        arguments = new JSONObject(URLDecoder.decode(u.getQueryParameter("json"), "UTF-8"));
      } catch (JSONException e) {
        LogManager.getInstance(this._context).logException(e);

        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

        StringEntity body = new StringEntity(e.toString());
        body.setContentType("text/plain");

        response.setEntity(body);

        return;
      }

      if (arguments != null) {
        try {
          JavaScriptEngine engine = new JavaScriptEngine(this._context);

          String action = arguments.getString("action");

          if ("fetch".equals(action)) {
            if (arguments.has("keys")) {
              JSONObject result = new JSONObject();
              result.put("status", "success");

              JSONArray keys = arguments.getJSONArray("keys");

              JSONObject values = new JSONObject();

              for (int i = 0; i < keys.length(); i++) {
                String key = keys.getString(i);

                String value = engine.fetchString(key);

                values.put(key, value);
              }

              result.put("values", values);

              StringEntity body = new StringEntity(result.toString(2));
              body.setContentType("application/json");

              response.setEntity(body);

              return;
            }
          } else if ("put".equals(action)) {
            JSONArray names = arguments.names();

            for (int i = 0; i < names.length(); i++) {
              String name = names.getString(i);

              if ("action".equals(name) == false) {
                String value = arguments.getString(name);

                if (value != null) engine.persistString(name, value);
              }
            }

            JSONObject result = new JSONObject();
            result.put("status", "success");

            StringEntity body = new StringEntity(result.toString(2));
            body.setContentType("application/json");

            response.setEntity(body);

            return;
          }
        } catch (JSONException e) {
          LogManager.getInstance(this._context).logException(e);

          response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

          StringEntity body = new StringEntity(e.toString());
          body.setContentType("text/plain");

          response.setEntity(body);

          return;
        }
      }
    }

    response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

    StringEntity body = new StringEntity(this._context.getString(R.string.error_malformed_request));
    body.setContentType("text/plain");

    response.setEntity(body);
  }
예제 #8
0
  @SuppressWarnings("deprecation")
  protected void onResume() {
    super.onResume();

    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    TextView userId = (TextView) this.findViewById(R.id.user_id_value);
    TextView probeStatus = (TextView) this.findViewById(R.id.probe_status_value);
    TextView uploadStatus = (TextView) this.findViewById(R.id.upload_status_value);
    TextView lastUpload = (TextView) this.findViewById(R.id.last_upload_value);
    TextView prVersion = (TextView) this.findViewById(R.id.pr_version_value);
    TextView gpsVersion = (TextView) this.findViewById(R.id.play_services_version_value);

    userId.setText("\"" + EncryptionManager.getInstance().getUserId(this) + "\"");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    boolean probeEnabled = prefs.getBoolean("config_probes_enabled", false);

    if (probeEnabled) probeStatus.setText(R.string.probe_status_enabled);
    else probeStatus.setText(R.string.probe_status_disabled);

    PurpleRobotApplication.fixPreferences(this, true);

    boolean uploadEnabled = prefs.getBoolean("config_enable_data_server", false);

    if (uploadEnabled) {
      boolean wifiOnly = prefs.getBoolean("config_restrict_data_wifi", true);

      if (wifiOnly) uploadStatus.setText(R.string.upload_status_enabled_wifi_only);
      else uploadStatus.setText(R.string.upload_status_enabled);
    } else uploadStatus.setText(R.string.upload_status_disabled);

    if (prefs.contains("http_last_upload") && prefs.contains("http_last_payload_size")) {
      long lastUploadTime = prefs.getLong("http_last_upload", 0);
      long lastPayloadSize = prefs.getLong("http_last_payload_size", 0) / 1024;

      SimpleDateFormat sdf = new SimpleDateFormat("MMM d - HH:mm:ss");

      String dateString = sdf.format(new Date(lastUploadTime));

      lastUpload.setText(
          String.format(this.getString(R.string.last_upload_format), dateString, lastPayloadSize));
    }

    if (prefs.getBoolean("config_enable_data_server", false)) {
      OutputPlugin plugin =
          OutputPluginManager.sharedInstance.pluginForClass(this, HttpUploadPlugin.class);

      if (plugin instanceof HttpUploadPlugin) {
        HttpUploadPlugin http = (HttpUploadPlugin) plugin;

        TextView uploadCount = (TextView) this.findViewById(R.id.pending_files_value);
        uploadCount.setText(this.getString(R.string.pending_files_file, http.pendingFilesCount()));
      }
    } else {
      OutputPlugin plugin =
          OutputPluginManager.sharedInstance.pluginForClass(
              this, StreamingJacksonUploadPlugin.class);

      if (plugin instanceof StreamingJacksonUploadPlugin) {
        StreamingJacksonUploadPlugin http = (StreamingJacksonUploadPlugin) plugin;

        TextView uploadCount = (TextView) this.findViewById(R.id.pending_files_value);
        uploadCount.setText(this.getString(R.string.pending_files_file, http.pendingFilesCount()));
      }
    }

    if (prefs.getBoolean("config_enable_log_server", false)) {
      TextView pendingEventsCount = (TextView) this.findViewById(R.id.pending_log_events_value);
      pendingEventsCount.setText(
          this.getString(
              R.string.pending_log_events_value,
              LogManager.getInstance(this).pendingEventsCount()));
    }

    try {
      PackageInfo pInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
      prVersion.setText(pInfo.versionName);
    } catch (NameNotFoundException e) {
      LogManager.getInstance(this).logException(e);
    }

    gpsVersion.setText("" + GoogleApiAvailability.GOOGLE_PLAY_SERVICES_VERSION_CODE);

    TextView okText = (TextView) this.findViewById(R.id.pr_error_none_value);
    LinearLayout errorList = (LinearLayout) this.findViewById(R.id.pr_error_list);
    errorList.removeAllViews();

    final SanityManager sanity = SanityManager.getInstance(this);

    if (sanity.getErrorLevel() != SanityCheck.OK) {
      errorList.setVisibility(View.VISIBLE);
      okText.setVisibility(View.GONE);

      Map<String, String> errors = sanity.errors();

      if (errors.size() > 0) {
        errorList.setVisibility(View.VISIBLE);

        for (String error : errors.keySet()) {
          TextView errorLine = new TextView(this);
          errorLine.setText(errors.get(error));
          errorLine.setTextColor(0xffff4444);
          errorLine.setTextSize(18);

          LinearLayout.LayoutParams layout =
              new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
          layout.setMargins(0, 0, 0, 10);
          errorLine.setLayoutParams(layout);

          final String errorKey = error;

          errorLine.setOnClickListener(
              new OnClickListener() {
                public void onClick(View view) {
                  sanity.runActionForAlert(errorKey);
                }
              });

          errorList.addView(errorLine);
        }
      }

      Map<String, String> warnings = sanity.warnings();

      if (warnings.size() > 0) {
        for (String error : warnings.keySet()) {
          TextView errorLine = new TextView(this);
          errorLine.setText(warnings.get(error));
          errorLine.setTextColor(0xffffbb33);
          errorLine.setTextSize(18);

          LinearLayout.LayoutParams layout =
              new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
          layout.setMargins(0, 0, 0, 10);
          errorLine.setLayoutParams(layout);

          final String errorKey = error;

          errorLine.setOnClickListener(
              new OnClickListener() {
                public void onClick(View view) {
                  sanity.runActionForAlert(errorKey);
                }
              });

          errorList.addView(errorLine);
        }
      }
    } else {
      errorList.setVisibility(View.GONE);
      okText.setVisibility(View.VISIBLE);
    }

    TextView triggerList = (TextView) this.findViewById(R.id.installed_triggers_value);

    StringBuilder triggerSb = new StringBuilder();

    List<Trigger> triggers = TriggerManager.getInstance(this).allTriggers();

    if (triggers.size() > 0) {
      for (Trigger trigger : triggers) {
        if (triggerSb.length() > 0) triggerSb.append("\n");

        triggerSb.append(trigger.getDiagnosticString(this));
      }

      triggerList.setText(triggerSb.toString());
    } else triggerList.setText(R.string.no_installed_triggers_label);

    TextView sensorsList = (TextView) this.findViewById(R.id.available_sensors_value);
    StringBuilder sb = new StringBuilder();

    SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);

    for (Sensor s : sensorManager.getSensorList(Sensor.TYPE_ALL)) {
      if (sb.length() > 0) sb.append("\n");

      sb.append(s.getName());
    }

    sensorsList.setText(sb.toString());

    String ipAddress = null;

    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

    if (wifiInfo != null) {
      int ip = wifiInfo.getIpAddress();

      ipAddress = Formatter.formatIpAddress(ip);
    } else {
      try {
        Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();

        NetworkInterface iface = null;

        while (ifaces.hasMoreElements()
            && (iface = ifaces.nextElement()) != null
            && ipAddress == null) {
          if (!iface.getName().equals("lo")) {
            Enumeration<InetAddress> ips = iface.getInetAddresses();
            InetAddress ipAddr = null;

            while (ips.hasMoreElements() && (ipAddr = ips.nextElement()) != null) {
              ipAddress = ipAddr.getHostAddress();
            }
          }
        }
      } catch (SocketException e) {
        LogManager.getInstance(this).logException(e);
      }
    }

    if (ipAddress != null) {
      TextView ipAddressView = (TextView) this.findViewById(R.id.ip_address_value);
      ipAddressView.setText(ipAddress);
    }
  }
예제 #9
0
  public boolean onOptionsItemSelected(MenuItem item) {
    final int itemId = item.getItemId();

    if (itemId == android.R.id.home) {
      this.onBackPressed();
    }
    if (itemId == R.id.menu_email_item) {
      StringBuilder message = new StringBuilder();

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

      String newline = System.getProperty("line.separator");

      message.append(this.getString(R.string.user_id_label));
      message.append(newline);
      message.append("\"" + EncryptionManager.getInstance().getUserId(this) + "\"");

      message.append(newline);
      message.append(newline);

      message.append(this.getString(R.string.probe_status_label));
      message.append(newline);

      boolean probeEnabled = prefs.getBoolean("config_probes_enabled", false);

      if (probeEnabled) message.append(this.getString(R.string.probe_status_enabled));
      else message.append(this.getString(R.string.probe_status_disabled));

      message.append(newline);
      message.append(newline);

      message.append(this.getString(R.string.upload_status_label));
      message.append(newline);

      PurpleRobotApplication.fixPreferences(this, true);

      boolean uploadEnabled = prefs.getBoolean("config_enable_data_server", false);

      if (uploadEnabled) {
        boolean wifiOnly = prefs.getBoolean("config_restrict_data_wifi", true);

        if (wifiOnly) message.append(this.getString(R.string.upload_status_enabled_wifi_only));
        else message.append(this.getString(R.string.upload_status_enabled));
      } else message.append(this.getString(R.string.upload_status_disabled));

      message.append(newline);
      message.append(newline);

      message.append(this.getString(R.string.last_upload_label));
      message.append(newline);

      if (prefs.contains("http_last_upload") && prefs.contains("http_last_payload_size")) {
        long lastUploadTime = prefs.getLong("http_last_upload", 0);
        long lastPayloadSize = prefs.getLong("http_last_payload_size", 0) / 1024;

        SimpleDateFormat sdf = new SimpleDateFormat("MMM d - HH:mm:ss");

        String dateString = sdf.format(new Date(lastUploadTime));

        message.append(
            String.format(
                this.getString(R.string.last_upload_format), dateString, lastPayloadSize));
      } else message.append(this.getString(R.string.last_upload_placeholder));

      message.append(newline);
      message.append(newline);

      OutputPlugin plugin =
          OutputPluginManager.sharedInstance.pluginForClass(this, HttpUploadPlugin.class);

      if (plugin instanceof HttpUploadPlugin) {
        HttpUploadPlugin http = (HttpUploadPlugin) plugin;

        message.append(this.getString(R.string.robot_pending_count_label));
        message.append(newline);
        message.append(this.getString(R.string.pending_files_file, http.pendingFilesCount()));

        message.append(newline);
        message.append(newline);
      }

      message.append(this.getString(R.string.pr_errors_label));
      message.append(newline);

      final SanityManager sanity = SanityManager.getInstance(this);

      if (sanity.getErrorLevel() != SanityCheck.OK) {
        Map<String, String> errors = sanity.errors();

        if (errors.size() > 0) {
          for (String error : errors.keySet()) {
            message.append(errors.get(error));
            message.append(newline);
          }

          message.append(newline);
        }

        Map<String, String> warnings = sanity.warnings();

        if (warnings.size() > 0) {
          for (String error : warnings.keySet()) {
            message.append(warnings.get(error));
            message.append(newline);
          }

          message.append(newline);
        }
      } else {
        message.append(this.getString(R.string.pr_errors_none_label));
        message.append(newline);
      }

      message.append(newline);

      message.append(this.getString(R.string.pr_version_label));
      message.append(newline);

      try {
        PackageInfo pInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
        message.append(pInfo.versionName);
      } catch (NameNotFoundException e) {
        LogManager.getInstance(this).logException(e);
      }

      message.append(newline);
      message.append(newline);

      message.append(this.getString(R.string.play_services_version_label));
      message.append(newline);
      message.append("" + GoogleApiAvailability.GOOGLE_PLAY_SERVICES_VERSION_CODE);
      message.append(newline);
      message.append(newline);

      message.append(this.getString(R.string.available_sensors_label));
      message.append(newline);

      StringBuilder sb = new StringBuilder();

      SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);

      for (Sensor s : sensorManager.getSensorList(Sensor.TYPE_ALL)) {
        if (sb.length() > 0) sb.append("\n");

        sb.append(s.getName());
      }

      message.append(sb.toString());

      try {
        Intent intent = new Intent(Intent.ACTION_SEND);

        intent.setType("message/rfc822");
        intent.putExtra(Intent.EXTRA_SUBJECT, this.getString(R.string.email_diagnostic_subject));
        intent.putExtra(Intent.EXTRA_TEXT, message.toString());

        SchemeConfigFile scheme = new SchemeConfigFile(this);

        File cacheDir = this.getExternalCacheDir();
        File configFile = new File(cacheDir, "config.scm");

        FileOutputStream fout = new FileOutputStream(configFile);

        fout.write(scheme.toString().getBytes(Charset.defaultCharset().name()));

        fout.flush();
        fout.close();

        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(configFile));

        this.startActivity(intent);
      } catch (ActivityNotFoundException e) {
        try {
          Intent mailIntent =
              new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:[email protected]"));
          mailIntent.putExtra(
              Intent.EXTRA_SUBJECT, this.getString(R.string.email_diagnostic_subject));
          mailIntent.putExtra(Intent.EXTRA_TEXT, message.toString());

          this.startActivity(mailIntent);
        } catch (ActivityNotFoundException ex) {
          Toast.makeText(this, R.string.toast_mail_not_found, Toast.LENGTH_LONG).show();
        }
      } catch (IOException e) {
        LogManager.getInstance(this).logException(e);
      }
    }

    return true;
  }