public void deployFromAssets(File dest) throws IOException {
    Context ctx = softContext.get();
    if (ctx != null) {
      ArrayList<String> paths = new ArrayList<String>();
      AssetManager am = ctx.getAssets();
      walkAssets(am, "", paths);

      // TODO clean old dir
      wipeDirectoryTree(dest);

      // copy from assets to dest dir
      BufferedInputStream bis = null;
      FileOutputStream fos = null;
      byte[] buf = new byte[8096];
      try {
        int len = paths.size();
        for (int i = 0; i < len; i++) {
          String path = paths.get(i);
          File f = new File(path);
          if (f.getName().indexOf(".") > -1) {
            bis = new BufferedInputStream(am.open(path), 8096);
            File df = new File(dest, path);
            Log.d(TAG, "Copying to: " + df.getAbsolutePath(), Log.DEBUG_MODE);
            fos = new FileOutputStream(df);

            int read = 0;
            while ((read = bis.read(buf)) != -1) {
              fos.write(buf, 0, read);
            }

            bis.close();
            bis = null;
            fos.close();
            fos = null;
          } else {
            File d = new File(dest, path);
            Log.d(TAG, "Creating directory: " + d.getAbsolutePath());
            d.mkdirs();
          }
        }
      } finally {
        if (bis != null) {
          try {
            bis.close();
          } catch (IOException e) {
            // Ignore
          }
          bis = null;
        }
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
            // Ignore
          }
          fos = null;
        }
      }
    }
  }
  private void initializePluginAPI(TiWebView webView) {
    try {
      synchronized (this.getClass()) {
        // Initialize
        if (enumPluginStateOff == null) {
          Class<?> webSettings = Class.forName("android.webkit.WebSettings");
          Class<?> pluginState = Class.forName("android.webkit.WebSettings$PluginState");

          Field f = pluginState.getDeclaredField("OFF");
          enumPluginStateOff = (Enum<?>) f.get(null);
          f = pluginState.getDeclaredField("ON");
          enumPluginStateOn = (Enum<?>) f.get(null);
          f = pluginState.getDeclaredField("ON_DEMAND");
          enumPluginStateOnDemand = (Enum<?>) f.get(null);
          internalSetPluginState = webSettings.getMethod("setPluginState", pluginState);
          // Hidden APIs
          // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/webkit/WebView.java;h=bbd8b95c7bea66b7060b5782fae4b3b2c4f04966;hb=4db1f432b853152075923499768639e14403b73a#l2558
          internalWebViewPause = webView.getClass().getMethod("onPause");
          internalWebViewResume = webView.getClass().getMethod("onResume");
        }
      }
    } catch (ClassNotFoundException e) {
      Log.e(TAG, "ClassNotFound: " + e.getMessage(), e);
    } catch (NoSuchMethodException e) {
      Log.e(TAG, "NoSuchMethod: " + e.getMessage(), e);
    } catch (NoSuchFieldException e) {
      Log.e(TAG, "NoSuchField: " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
      Log.e(TAG, "IllegalAccess: " + e.getMessage(), e);
    }
  }
  public TiUIDatePicker(final TiViewProxy proxy, Activity activity) {
    this(proxy);
    Log.d(TAG, "Creating a date picker", Log.DEBUG_MODE);

    DatePicker picker;
    // If it is not API Level 21 (Android 5.0), create picker normally.
    // If not, it will inflate a spinner picker to address a bug.
    if (Build.VERSION.SDK_INT != Build.VERSION_CODES.LOLLIPOP) {
      picker =
          new DatePicker(activity) {
            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
              super.onLayout(changed, left, top, right, bottom);
              TiUIHelper.firePostLayoutEvent(proxy);
            }
          };
    } else {
      // A bug where PickerCalendarDelegate does not send events to the
      // listener on API Level 21 (Android 5.0) for TIMOB-19192
      // https://code.google.com/p/android/issues/detail?id=147657
      // Work around is to use spinner view instead of calendar view in
      // in Android 5.0
      int datePickerSpinner;
      try {
        datePickerSpinner = TiRHelper.getResource("layout.titanium_ui_date_picker_spinner");
      } catch (ResourceNotFoundException e) {
        if (Log.isDebugModeEnabled()) {
          Log.e(TAG, "XML resources could not be found!!!");
        }
        return;
      }
      picker = (DatePicker) activity.getLayoutInflater().inflate(datePickerSpinner, null);
    }
    setNativeView(picker);
  }
  /*
   * Check whether a fresher location is available and update the GeomagneticField
   * that we use for correcting the magnetic heading. If the location is stale,
   * use it anyway but log a warning.
   */
  private void updateDeclination() {
    long currentTime = System.currentTimeMillis();

    if (currentTime - lastDeclinationCheck > DECLINATION_CHECK_INTERVAL) {
      String provider = tiLocation.locationManager.getBestProvider(locationCriteria, true);
      if (provider != null) {
        Location location = tiLocation.locationManager.getLastKnownLocation(provider);
        if (location != null) {
          if (geomagneticFieldLocation == null
              || (location.getTime() > geomagneticFieldLocation.getTime())) {
            geomagneticField =
                new GeomagneticField(
                    (float) location.getLatitude(),
                    (float) location.getLongitude(),
                    (float) (location.getAltitude()),
                    currentTime);
            geomagneticFieldLocation = location;
          }
        }
      }
      if (geomagneticFieldLocation == null) {
        Log.w(TAG, "No location fix available, can't determine compass trueHeading.");
      } else if (currentTime - geomagneticFieldLocation.getTime() > STALE_LOCATION_THRESHOLD) {
        Log.w(TAG, "Location fix is stale, compass trueHeading may be incorrect.");
      }
      lastDeclinationCheck = currentTime;
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String prefsName = DEFAULT_PREFS_RNAME;
    if (getIntent().hasExtra("prefsName")) {
      String name = getIntent().getExtras().getString("prefsName");
      if (name != null && name.length() > 0) {
        prefsName = name;
      }
    }

    // Find the layout file, do nothing if not found
    try {
      getPreferenceManager().setSharedPreferencesName(TiApplication.APPLICATION_PREFERENCES_NAME);
      int resid = TiRHelper.getResource("xml." + prefsName);
      if (resid != 0) {
        addPreferencesFromResource(resid);
      } else {
        Log.e(TAG, "xml." + prefsName + " preferences not found.");
        finish();
        return;
      }
    } catch (TiRHelper.ResourceNotFoundException e) {
      Log.e(TAG, "Error loading preferences: " + e.getMessage());
      finish();
      return;
    }
  }
    public void run() {
      boolean waitOnResume = false;
      try {
        if (paused) {
          synchronized (this) {
            KrollDict data = new KrollDict();
            proxy.fireEvent(TiC.EVENT_PAUSE, data);
            waitOnResume = true;
            wait();
          }
        }

        BitmapWithIndex b = loader.getBitmapQueue().take();
        Log.d(TAG, "set image: " + b.index, Log.DEBUG_MODE);
        setImage(b.bitmap);
        fireChange(b.index);

        // When the animation is paused, the timer will pause in the middle of a period.
        // When the animation resumes, the timer resumes from where it left off. As a result, it
        // will look like
        // one frame is left out when resumed (TIMOB-10207).
        // To avoid this, we force the thread to wait for one period on resume.
        if (waitOnResume) {
          Thread.sleep(currentDuration);
          waitOnResume = false;
        }
      } catch (InterruptedException e) {
        Log.e(TAG, "Loader interrupted");
      }
    }
    @Override
    protected void onPostExecute(Drawable d) {
      super.onPostExecute(d);

      if (d != null) {
        final Drawable fDrawable = d;

        // setImageDrawable has to run in the UI thread since it updates the UI
        TiMessenger.getMainMessenger()
            .post(
                new Runnable() {
                  @Override
                  public void run() {
                    setImageDrawable(fDrawable, token);
                  }
                });

      } else {
        if (Log.isDebugModeEnabled()) {
          String traceMsg = "Background image load returned null";
          if (proxy.hasProperty(TiC.PROPERTY_IMAGE)) {
            Object image = proxy.getProperty(TiC.PROPERTY_IMAGE);
            if (image instanceof String) {
              traceMsg += " (" + TiConvert.toString(image) + ")";
            }
          }
          Log.d(TAG, traceMsg);
        }
      }
    }
  @Override
  /**
   * When this activity stops, this method fires the javascript 'blur' and 'stop' events. Blur
   * events will only fire if the activity is not a tab activity.
   */
  protected void onStop() {
    inForeground = false;
    super.onStop();

    Log.d(TAG, "Activity " + this + " onStop", Log.DEBUG_MODE);

    if (getTiApp().isRestartPending()) {
      if (!isFinishing()) {
        finish();
      }
      return;
    }

    if (activityProxy != null) {
      activityProxy.fireSyncEvent(TiC.EVENT_STOP, null);
    }

    synchronized (lifecycleListeners.synchronizedList()) {
      for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
        try {
          TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_STOP);

        } catch (Throwable t) {
          Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
        }
      }
    }
    KrollRuntime.suggestGC();
  }
 public void setPluginState(int pluginState) {
   if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) {
     TiWebView webView = (TiWebView) getNativeView();
     WebSettings webSettings = webView.getSettings();
     if (webView != null) {
       try {
         switch (pluginState) {
           case PLUGIN_STATE_OFF:
             internalSetPluginState.invoke(webSettings, enumPluginStateOff);
             break;
           case PLUGIN_STATE_ON:
             internalSetPluginState.invoke(webSettings, enumPluginStateOn);
             break;
           case PLUGIN_STATE_ON_DEMAND:
             internalSetPluginState.invoke(webSettings, enumPluginStateOnDemand);
             break;
           default:
             Log.w(TAG, "Not a valid plugin state. Ignoring setPluginState request");
         }
       } catch (InvocationTargetException e) {
         Log.e(TAG, "Method not supported", e);
       } catch (IllegalAccessException e) {
         Log.e(TAG, "Illegal Access", e);
       }
     }
   }
 }
Example #10
0
 public void release() {
   if (DBG) {
     Log.d(LCAT, "Releasing: " + this);
   }
   View nv = getNativeView();
   if (nv != null) {
     if (nv instanceof ViewGroup) {
       ViewGroup vg = (ViewGroup) nv;
       if (DBG) {
         Log.d(LCAT, "Group has: " + vg.getChildCount());
       }
       if (!(vg instanceof AdapterView<?>)) {
         vg.removeAllViews();
       }
     }
     Drawable d = nv.getBackground();
     if (d != null) {
       nv.setBackgroundDrawable(null);
       d.setCallback(null);
       if (d instanceof TiBackgroundDrawable) {
         ((TiBackgroundDrawable) d).releaseDelegate();
       }
       d = null;
     }
     nativeView = null;
     if (proxy != null) {
       proxy.setModelListener(null);
     }
   }
 }
  private void handleInsertItemsAt(int index, Object data) {
    if (data instanceof Object[]) {
      Object[] views = (Object[]) data;

      if (itemProperties == null) {
        itemProperties = new ArrayList<Object>(Arrays.asList(views));
      } else {
        if (index < 0 || index > itemProperties.size()) {
          Log.e(TAG, "Invalid index to handleInsertItem", Log.DEBUG_MODE);
          return;
        }
        int counter = index;
        for (Object view : views) {
          itemProperties.add(counter, view);
          counter++;
        }
      }
      // only process items when listview's properties is processed.
      if (getListView() == null) {
        preload = true;
        return;
      }

      itemCount += views.length;
      processData(views, index);
    } else {
      Log.e(TAG, "Invalid argument type to insertItemsAt", Log.DEBUG_MODE);
    }
  }
 private static StringBuilder readResourceFile(String fileName) {
   InputStream stream =
       TiWebViewBinding.class
           .getClassLoader()
           .getResourceAsStream("ti/modules/titanium/ui/widget/webview/" + fileName);
   BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
   StringBuilder code = new StringBuilder();
   try {
     for (String line = reader.readLine(); line != null; line = reader.readLine()) {
       code.append(line + "\n");
     }
   } catch (IOException e) {
     Log.e(TAG, "Error reading input stream", e);
     return null;
   } finally {
     if (stream != null) {
       try {
         stream.close();
       } catch (IOException e) {
         Log.w(TAG, "Problem closing input stream.", e);
       }
     }
   }
   return code;
 }
  @Override
  /**
   * When this activity starts, this method updates the current activity to this if necessary and
   * fire javascript 'start' and 'focus' events. Focus events will only fire if the activity is not
   * a tab activity.
   */
  protected void onStart() {
    inForeground = true;
    super.onStart();
    if (isFinishing()) {
      return;
    }

    // Newer versions of Android appear to turn this on by default.
    // Turn if off until an activity indicator is shown.
    setProgressBarIndeterminateVisibility(false);

    Log.d(TAG, "Activity " + this + " onStart", Log.DEBUG_MODE);

    TiApplication tiApp = getTiApp();

    if (tiApp.isRestartPending()) {
      if (!isFinishing()) {
        finish();
      }
      return;
    }

    updateTitle();

    if (activityProxy != null) {
      // we only want to set the current activity for good in the resume state but we need it right
      // now.
      // save off the existing current activity, set ourselves to be the new current activity
      // temporarily
      // so we don't run into problems when we give the proxy the event
      Activity tempCurrentActivity = tiApp.getCurrentActivity();
      tiApp.setCurrentActivity(this, this);

      activityProxy.fireEvent(TiC.EVENT_START, null);

      // set the current activity back to what it was originally
      tiApp.setCurrentActivity(this, tempCurrentActivity);
    }

    synchronized (lifecycleListeners.synchronizedList()) {
      for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
        try {
          TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_START);

        } catch (Throwable t) {
          Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
        }
      }
    }
    // store current configuration orientation
    // This fixed bug with double orientation chnage firing when activity starts in landscape
    previousOrientation = getResources().getConfiguration().orientation;
  }
 public void load(String url) {
   try {
     execute(url);
   } catch (RejectedExecutionException e) {
     Log.w(LCAT, "Thread pool rejected attempt to load image: " + url);
     Log.w(LCAT, "ADD Handler for retry");
   }
 }
  @Override
  /**
   * When this activity pauses, this method sets the current activity to null, fires a javascript
   * 'pause' event, and if the activity is finishing, remove all dialogs associated with it.
   */
  protected void onPause() {
    inForeground = false;
    super.onPause();
    isResumed = false;

    Log.d(TAG, "Activity " + this + " onPause", Log.DEBUG_MODE);

    TiApplication tiApp = getTiApp();
    if (tiApp.isRestartPending()) {
      releaseDialogs(true);
      if (!isFinishing()) {
        finish();
      }
      return;
    }

    if (!windowStack.empty()) {
      windowStack.peek().onWindowFocusChange(false);
    }

    TiApplication.updateActivityTransitionState(true);
    tiApp.setCurrentActivity(this, null);
    TiUIHelper.showSoftKeyboard(getWindow().getDecorView(), false);

    if (this.isFinishing()) {
      releaseDialogs(true);
    } else {
      // release non-persistent dialogs when activity hides
      releaseDialogs(false);
    }

    if (activityProxy != null) {
      activityProxy.fireSyncEvent(TiC.EVENT_PAUSE, null);
    }

    synchronized (lifecycleListeners.synchronizedList()) {
      for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
        try {
          TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_PAUSE);

        } catch (Throwable t) {
          Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
        }
      }
    }

    // Checkpoint for ti.end event
    if (tiApp != null) {
      tiApp.postAnalyticsEvent(TiAnalyticsEventFactory.createAppEndEvent());
    }
  }
    @Override
    protected Bitmap doInBackground(final ImageArgs... params) {
      final ImageArgs imageArgs = params[0];

      recycle = imageArgs.mRecycle;
      mNetworkURL = imageArgs.mNetworkURL;
      Bitmap bitmap = null;

      mUrl = imageArgs.mImageref.getUrl();

      if (mNetworkURL) {
        boolean getAsync = true;
        try {
          String imageUrl = TiUrl.getCleanUri(imageArgs.mImageref.getUrl()).toString();

          URI uri = new URI(imageUrl);
          getAsync = !TiResponseCache.peek(uri); // expensive, don't want to do in UI thread
        } catch (URISyntaxException e) {
          Log.e(TAG, "URISyntaxException for url " + imageArgs.mImageref.getUrl(), e);
          getAsync = false;
        } catch (NullPointerException e) {
          Log.e(TAG, "NullPointerException for url " + imageArgs.mImageref.getUrl(), e);
          getAsync = false;
        } catch (Exception e) {
          Log.e(TAG, "Caught exception for url" + imageArgs.mImageref.getUrl(), e);
        }
        if (getAsync) {
          //
          // We've got to start the download back on the UI thread, if we do it on one
          // of the AsyncTask threads it will throw an exception.
          //
          mAsync = true;

          TiMessenger.getMainMessenger()
              .post(
                  new Runnable() {
                    @Override
                    public void run() {
                      imageArgs.mImageref.getBitmapAsync(imageDownloadListener);
                    }
                  });

        } else {
          bitmap =
              (imageArgs.mImageref)
                  .getBitmap(
                      imageArgs.mView, imageArgs.mRequestedWidth, imageArgs.mRequestedHeight);
        }
      } else {
        bitmap =
            (imageArgs.mImageref)
                .getBitmap(imageArgs.mView, imageArgs.mRequestedWidth, imageArgs.mRequestedHeight);
      }
      return bitmap;
    }
  @Kroll.method
  public void selectAnnotation(Object[] args) {
    AnnotationProxy selAnnotation = null;
    String title = null;
    boolean animate = false;
    boolean center = true; // keep existing default behavior

    if (args != null && args.length > 0) {
      if (args[0] instanceof HashMap) {
        HashMap<String, Object> params = (HashMap) args[0];

        Object selectedAnnotation = params.get(TiC.PROPERTY_ANNOTATION);
        if (selectedAnnotation instanceof AnnotationProxy) {
          selAnnotation = (AnnotationProxy) selectedAnnotation;
          title = TiConvert.toString(selAnnotation.getProperty(TiC.PROPERTY_TITLE));
        } else {
          title = TiConvert.toString(params, TiC.PROPERTY_TITLE);
        }

        Object animateProperty = params.containsKey(TiC.PROPERTY_ANIMATE);
        if (animateProperty != null) {
          animate = TiConvert.toBoolean(animateProperty);
        }

        Object centerProperty = params.containsKey(TiC.PROPERTY_CENTER);
        if (centerProperty != null) {
          center = TiConvert.toBoolean(centerProperty);
        }

      } else {
        if (args[0] instanceof AnnotationProxy) {
          selAnnotation = (AnnotationProxy) args[0];
          title = TiConvert.toString(selAnnotation.getProperty(TiC.PROPERTY_TITLE));

        } else if (args[0] instanceof String) {
          title = TiConvert.toString(args[0]);
        }

        if (args.length > 1) {
          animate = TiConvert.toBoolean(args[1]);
        }
      }
    }

    if (title != null) {
      if (mapView == null) {
        Log.i(TAG, "calling selectedAnnotations.add", Log.DEBUG_MODE);
        selectedAnnotations.add(
            new TiMapView.SelectedAnnotation(title, selAnnotation, animate, center));
      } else {
        Log.i(TAG, "calling selectedAnnotations.add2", Log.DEBUG_MODE);
        mapView.selectAnnotation(true, title, selAnnotation, animate, center);
      }
    }
  }
 public void run() {
   try {
     BitmapWithIndex b = loader.getBitmapQueue().take();
     if (DBG) {
       Log.d(LCAT, "set image: " + b.index);
     }
     setImage(b.bitmap);
     fireChange(b.index);
   } catch (InterruptedException e) {
     Log.e(LCAT, "Loader interrupted");
   }
 }
  @Override
  /**
   * When the activity resumes, this method updates the current activity to this and fires a
   * javascript 'resume' event.
   */
  protected void onResume() {
    inForeground = true;
    super.onResume();
    if (isFinishing()) {
      return;
    }

    Log.d(TAG, "Activity " + this + " onResume", Log.DEBUG_MODE);

    TiApplication tiApp = getTiApp();
    if (tiApp.isRestartPending()) {
      if (!isFinishing()) {
        finish();
      }
      return;
    }

    if (!windowStack.empty()) {
      windowStack.peek().onWindowFocusChange(true);
    }

    tiApp.setCurrentActivity(this, this);
    TiApplication.updateActivityTransitionState(false);

    if (activityProxy != null) {
      // Fire the sync event with a timeout, so the main thread won't be blocked too long to get an
      // ANR. (TIMOB-13253)
      activityProxy.fireSyncEvent(TiC.EVENT_RESUME, null, 4000);
    }

    synchronized (lifecycleListeners.synchronizedList()) {
      for (OnLifecycleEvent listener : lifecycleListeners.nonNull()) {
        try {
          TiLifecycle.fireLifecycleEvent(this, listener, TiLifecycle.LIFECYCLE_ON_RESUME);

        } catch (Throwable t) {
          Log.e(TAG, "Error dispatching lifecycle event: " + t.getMessage(), t);
        }
      }
    }

    isResumed = true;

    // Checkpoint for ti.start event
    String deployType = tiApp.getAppProperties().getString("ti.deploytype", "unknown");
    tiApp.postAnalyticsEvent(TiAnalyticsEventFactory.createAppStartEvent(tiApp, deployType));
  }
  public TiUINativePicker(final TiViewProxy proxy, Activity activity) {
    this(proxy);

    int spinnerId;
    try {
      spinnerId = TiRHelper.getResource("layout.titanium_ui_spinner");
    } catch (ResourceNotFoundException e) {
      if (Log.isDebugModeEnabled()) {
        Log.e(TAG, "XML resources could not be found!!!");
      }
      return;
    }
    Spinner spinner = (Spinner) activity.getLayoutInflater().inflate(spinnerId, null);

    spinner.addOnLayoutChangeListener(
        new View.OnLayoutChangeListener() {
          @Override
          public void onLayoutChange(
              View v,
              int left,
              int top,
              int right,
              int bottom,
              int oldLeft,
              int oldTop,
              int oldRight,
              int oldBottom) {
            TiUIHelper.firePostLayoutEvent(proxy);
          }
        });

    spinner.setOnTouchListener(
        new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
              KrollDict data = new KrollDict();
              data.put(TiC.PROPERTY_X, event.getX());
              data.put(TiC.PROPERTY_Y, event.getY());
              fireEvent(TiC.EVENT_CLICK, data);
            }
            return false;
          }
        });

    setNativeView(spinner);
    refreshNativeView();
    preselectRows();

    spinner.setOnItemSelectedListener(this);
  }
 public void resumeWebView() {
   if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) {
     View v = getNativeView();
     if (v != null) {
       try {
         internalWebViewResume.invoke(v);
       } catch (InvocationTargetException e) {
         Log.e(TAG, "Method not supported", e);
       } catch (IllegalAccessException e) {
         Log.e(TAG, "Illegal Access", e);
       }
     }
   }
 }
  protected void handleSendMessage(int messageId) {
    try {
      Message message = TiMessenger.getMainMessenger().getHandler().obtainMessage(messageId, this);
      messenger.send(message);

    } catch (RemoteException e) {
      Log.e(TAG, "Unable to message creator. finishing.", e);
      finish();

    } catch (RuntimeException e) {
      Log.e(TAG, "Unable to message creator. finishing.", e);
      finish();
    }
  }
Example #23
0
  @Kroll.method
  public String encode(HashMap args) {
    // encode text to cipher text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("plainText");
    String keyString = arg.getString("publicKey");
    byte[] encodedBytes = null;
    Key key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePublic(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.ENCRYPT_MODE, key);
      encodedBytes = c.doFinal(txt.getBytes());
    } catch (Exception e) {
      Log.e(TAG, "RSA encryption error " + e.toString());
    }

    return Base64.encodeToString(encodedBytes, Base64.NO_WRAP);
  }
Example #24
0
  @Kroll.method
  public String decode(HashMap args) {
    // decode string back to plain text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("cipherText");
    byte[] bytesEncoded = Base64.decode(txt, 0);
    String keyString = arg.getString("privateKey");
    PrivateKey key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      PKCS8EncodedKeySpec x509KeySpec = new PKCS8EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePrivate(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    byte[] decodedBytes = null;

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.DECRYPT_MODE, key);
      decodedBytes = c.doFinal(bytesEncoded);
    } catch (Exception e) {
      Log.e(TAG, "RSA decryption error " + e.toString());
      return "error";
    }
    return new String(decodedBytes);
  }
 private void handlesetDisplayHomeAsUp(boolean showHomeAsUp) {
   if (actionBar != null) {
     actionBar.setDisplayHomeAsUpEnabled(showHomeAsUp);
   } else {
     Log.w(TAG, "ActionBar is not enabled");
   }
 }
 private void handleHide() {
   if (actionBar != null) {
     actionBar.hide();
   } else {
     Log.w(TAG, "ActionBar is not enabled");
   }
 }
  @Kroll.method
  public void takeScreenshot(KrollFunction callback) {
    Activity a = TiApplication.getAppCurrentActivity();

    if (a == null) {
      Log.w(TAG, "Could not get current activity for takeScreenshot.", Log.DEBUG_MODE);
      callback.callAsync(getKrollObject(), new Object[] {null});
      return;
    }

    while (a.getParent() != null) {
      a = a.getParent();
    }

    Window w = a.getWindow();

    while (w.getContainer() != null) {
      w = w.getContainer();
    }

    KrollDict image = TiUIHelper.viewToImage(null, w.getDecorView());
    if (callback != null) {
      callback.callAsync(getKrollObject(), new Object[] {image});
    }
  }
  @Override
  public void onBackPressed() {
    synchronized (interceptOnBackPressedListeners.synchronizedList()) {
      for (interceptOnBackPressedEvent listener : interceptOnBackPressedListeners.nonNull()) {
        try {
          if (listener.interceptOnBackPressed()) {
            return;
          }

        } catch (Throwable t) {
          Log.e(TAG, "Error dispatching interceptOnBackPressed event: " + t.getMessage(), t);
        }
      }
    }

    TiWindowProxy topWindow = topWindowOnStack();

    // Prevent default Android behavior for "back" press
    // if the top window has a listener to handle the event.
    if (topWindow != null && topWindow.hasListeners(TiC.EVENT_ANDROID_BACK)) {
      topWindow.fireEvent(TiC.EVENT_ANDROID_BACK, null);

    } else {
      // If event is not handled by any listeners allow default behavior.
      super.onBackPressed();
    }
  }
  // Subclasses can override to handle post-creation (but pre-message fire) logic
  protected void windowCreated() {
    boolean fullscreen = getIntentBoolean(TiC.PROPERTY_FULLSCREEN, false);
    boolean navBarHidden = getIntentBoolean(TiC.PROPERTY_NAV_BAR_HIDDEN, false);
    boolean modal = getIntentBoolean(TiC.PROPERTY_MODAL, false);
    int softInputMode = getIntentInt(TiC.PROPERTY_WINDOW_SOFT_INPUT_MODE, -1);
    boolean hasSoftInputMode = softInputMode != -1;

    setFullscreen(fullscreen);
    setNavBarHidden(navBarHidden);

    if (modal) {
      if (Build.VERSION.SDK_INT < TiC.API_LEVEL_ICE_CREAM_SANDWICH) {
        // This flag is deprecated in API 14. On ICS, the background is not blurred but straight
        // black.
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
      }
    }

    if (hasSoftInputMode) {
      Log.d(TAG, "windowSoftInputMode: " + softInputMode, Log.DEBUG_MODE);
      getWindow().setSoftInputMode(softInputMode);
    }

    boolean useActivityWindow = getIntentBoolean(TiC.INTENT_PROPERTY_USE_ACTIVITY_WINDOW, false);
    if (useActivityWindow) {
      int windowId = getIntentInt(TiC.INTENT_PROPERTY_WINDOW_ID, -1);
      TiActivityWindows.windowCreated(this, windowId);
    }
  }
  @Override
  /**
   * When this activity restarts, this method updates the current activity to this and fires
   * javascript 'restart' event.
   */
  protected void onRestart() {
    inForeground = true;
    super.onRestart();

    Log.d(TAG, "Activity " + this + " onRestart", Log.DEBUG_MODE);

    TiApplication tiApp = getTiApp();
    if (tiApp.isRestartPending()) {
      if (!isFinishing()) {
        finish();
      }

      return;
    }

    if (activityProxy != null) {
      // we only want to set the current activity for good in the resume state but we need it right
      // now.
      // save off the existing current activity, set ourselves to be the new current activity
      // temporarily
      // so we don't run into problems when we give the proxy the event
      Activity tempCurrentActivity = tiApp.getCurrentActivity();
      tiApp.setCurrentActivity(this, this);

      activityProxy.fireSyncEvent(TiC.EVENT_RESTART, null);

      // set the current activity back to what it was originally
      tiApp.setCurrentActivity(this, tempCurrentActivity);
    }
  }