예제 #1
0
  public int addTitaniumFileAsPostData(String name, Object value) {
    try {
      if (value instanceof TiBaseFile) {
        TiBaseFile baseFile = (TiBaseFile) value;
        FileBody body =
            new FileBody(
                baseFile.getNativeFile(), TiMimeTypeHelper.getMimeType(baseFile.nativePath()));
        parts.put(name, body);
        return (int) baseFile.getNativeFile().length();
      } else if (value instanceof TiBlob) {
        TiBlob blob = (TiBlob) value;
        String mimeType = blob.getMimeType();
        File tmpFile =
            File.createTempFile(
                "tixhr", TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, ".txt"));
        FileOutputStream fos = new FileOutputStream(tmpFile);
        fos.write(blob.getBytes());
        fos.close();

        FileBody body = new FileBody(tmpFile, mimeType);
        parts.put(name, body);
        return blob.getLength();
      } else {
        if (value != null) {
          Log.e(LCAT, name + " is a " + value.getClass().getSimpleName());
        } else {
          Log.e(LCAT, name + " is null");
        }
      }
    } catch (IOException e) {
      Log.e(LCAT, "Error adding post data (" + name + "): " + e.getMessage());
    }
    return 0;
  }
예제 #2
0
 public Bitmap createBitmap(Object image) {
   if (image instanceof TiBlob) {
     TiBlob blob = (TiBlob) image;
     return TiUIHelper.createBitmap(blob.getInputStream());
   } else if (image instanceof FileProxy) {
     FileProxy file = (FileProxy) image;
     try {
       return TiUIHelper.createBitmap(file.getBaseFile().getInputStream());
     } catch (IOException e) {
       Log.e(
           LCAT,
           "Error creating drawable from file: " + file.getBaseFile().getNativeFile().getName(),
           e);
     }
   } else if (image instanceof String) {
     String url = proxy.getTiContext().resolveUrl(null, (String) image);
     TiBaseFile file =
         TiFileFactory.createTitaniumFile(proxy.getTiContext(), new String[] {url}, false);
     try {
       return TiUIHelper.createBitmap(file.getInputStream());
     } catch (IOException e) {
       Log.e(LCAT, "Error creating drawable from path: " + image.toString(), e);
     }
   } else if (image instanceof TiDict) {
     TiBlob blob = TiUIHelper.getImageFromDict((TiDict) image);
     if (blob != null) {
       return TiUIHelper.createBitmap(blob.getInputStream());
     } else {
       Log.e(LCAT, "Couldn't find valid image in object: " + image.toString());
     }
   }
   return null;
 }
예제 #3
0
  public void stop() {
    try {
      if (mp != null) {

        if (mp.isPlaying() || isPaused()) {
          if (DBG) {
            Log.d(LCAT, "audio is playing, stop()");
          }
          setState(STATE_STOPPING);
          mp.stop();
          setState(STATE_STOPPED);
          if (remote) {
            stopProgressTimer();
          }
          try {
            mp.prepare();
          } catch (IOException e) {
            Log.e(LCAT, "Error while preparing audio after stop(). Ignoring.");
          } catch (IllegalStateException e) {
            Log.w(LCAT, "Error while preparing audio after stop(). Ignoring.");
          }
        }

        if (isPaused()) {
          paused = false;
        }
      }
    } catch (Throwable t) {
      Log.e(LCAT, "Error : ", t);
    }
  }
  @Override
  public boolean handleMessage(Message msg) {
    if (msg.what == MSG_CHANGE) {
      value = tv.getText().toString();
      JSONObject o = new JSONObject();
      try {
        o.put("value", value);
        eventManager.invokeSuccessListeners(CHANGE_EVENT, o.toString());
      } catch (JSONException e) {
        Log.e(LCAT, "Error setting value: ", e);
      }
    } else if (msg.what == MSG_SETVALUE) {
      doSetValue((String) msg.obj);
    } else if (msg.what == MSG_CANCEL) {
      doSetValue((String) msg.obj);
      eventManager.invokeSuccessListeners(CANCEL_EVENT, null);
    } else if (msg.what == MSG_RETURN) {
      value = tv.getText().toString();
      JSONObject o = new JSONObject();
      try {
        o.put("value", value);
        eventManager.invokeSuccessListeners(RETURN_EVENT, o.toString());
      } catch (JSONException e) {
        Log.e(LCAT, "Error setting value: ", e);
      }
    }

    return super.handleMessage(msg);
  }
예제 #5
0
  public String getResponseText() {
    if (responseData != null && responseText == null) {
      byte[] data = responseData.getBytes();
      if (charset == null) {
        // Detect binary
        int binaryCount = 0;
        int len = data.length;

        if (len > 0) {
          for (int i = 0; i < len; i++) {
            byte b = data[i];
            if (b < 32 || b > 127) {
              if (b != '\n' && b != '\r' && b != '\t' && b != '\b') {
                binaryCount++;
              }
            }
          }

          if ((binaryCount * 100) / len >= IS_BINARY_THRESHOLD) {
            return null;
          }
        }

        charset = HTTP.DEFAULT_CONTENT_CHARSET;
      }

      try {
        responseText = new String(data, charset);
      } catch (UnsupportedEncodingException e) {
        Log.e(LCAT, "Unable to convert to String using charset: " + charset);
      }
    }

    return responseText;
  }
예제 #6
0
  @Override
  public void onError(Context context, String errorId) {
    Log.e(LCAT, "Error: " + errorId);

    KrollDict data = new KrollDict();
    data.put("errorId", errorId);
    C2dmModule.getInstance().fireEvent(ERROR_EVENT, data);
  }
예제 #7
0
  @Override
  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);

    // TODO report this to the user
    String text = "Javascript Error(" + errorCode + "): " + description;
    Log.e(LCAT, "Received on error" + text);
  }
예제 #8
0
 @Override
 public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
   super.onReceivedError(view, errorCode, description, failingUrl);
   String text = "Err(" + errorCode + ") " + description;
   TitaniumUIHelper.doKillOrContinueDialog(
       view.getContext(), "Resource Not Found", text, null, null);
   Log.e(LCAT, "Received on error" + text);
 }
 public void setBackgroundImageProperty(TiDict d, String property) {
   String path = TiConvert.toString(d, property);
   String url = tiContext.resolveUrl(null, path);
   TiBaseFile file = TiFileFactory.createTitaniumFile(tiContext, new String[] {url}, false);
   try {
     setBackgroundDrawable(new BitmapDrawable(TiUIHelper.createBitmap(file.getInputStream())));
   } catch (IOException e) {
     Log.e(LCAT, "Error creating background image from path: " + path.toString(), e);
   }
 }
 public void addTitaniumFileAsPostData(String name, ITitaniumFile value) {
   if (value instanceof TitaniumDelegate) {
     value = (ITitaniumFile) ((TitaniumDelegate) value).getObject();
   }
   if (value instanceof TitaniumBlob) {
     TitaniumBlob blob = (TitaniumBlob) value;
     FileBody body = new FileBody(blob.getFile(), blob.getContentType());
     parts.put(name, body);
   } else if (value instanceof TitaniumFile) {
     Log.e(LCAT, name + " is a TitaniumFile");
   } else if (value instanceof TitaniumResourceFile) {
     Log.e(LCAT, name + " is a TitaniumResourceFile");
   } else {
     if (value != null) {
       Log.e(LCAT, name + " is a " + value.getClass().getSimpleName());
     } else {
       Log.e(LCAT, name + " is null");
     }
   }
 }
예제 #11
0
 @Override
 public void onResume() {
   super.onResume();
   for (ITitaniumLifecycle listener : mediaObjects) {
     try {
       listener.onResume();
     } catch (Throwable t) {
       Log.e(LCAT, "Error in onResume", t);
     }
   }
 }
예제 #12
0
 public void run() {
   try {
     if (notification == null) {
       notification = RingtoneManager.getRingtone(ctx, RingtoneManager.getDefaultUri(type));
     }
     if (notification != null) {
       notification.play();
     }
   } catch (Exception e) {
     Log.e(LCAT, "Error playing beep.", e);
   }
 }
예제 #13
0
  public ITitaniumVideo createVideoPlayer(final String jsonOptions) {
    ITitaniumVideo result = null;
    String errorCallback = null;
    try {
      JSONObject options = new JSONObject(jsonOptions);
      try {
        errorCallback = options.getString("error"); // callbacks will be added on JS side. to track
      } catch (JSONException e2) {
        Log.d(LCAT, "error callback not available");
      }

      String url = null;
      try {
        url = options.getString("contentURL");
        Uri uri = Uri.parse(url);
        String scheme = uri.getScheme();
        if (scheme == null
            || scheme.length() == 0
            || (scheme == null && !(new File(url).exists()))) {
          uri = Uri.parse(TitaniumUrlHelper.buildAssetUrlFromResourcesRoot(getActivity(), url));
        }
        Intent intent = new Intent(getActivity(), TitaniumVideoActivity.class);
        intent.setData(uri);
        TitaniumIntentWrapper videoIntent = new TitaniumIntentWrapper(intent);
        videoIntent.setWindowId(TitaniumIntentWrapper.createActivityName("VIDEO"));
        result = new TitaniumVideo(this, videoIntent);
      } catch (JSONException e2) {
        String msg = "contentURL is required.";
        Log.e(LCAT, msg);
        if (errorCallback != null) {
          invokeUserCallback(errorCallback, createJSONError(0, msg));
        }
      }

    } catch (JSONException e) {
      Log.e(LCAT, "Could not reconstruct options from JSON: ", e);
    }

    return result;
  }
 private BitmapDrawable createDrawable(Bitmap bitmap) {
   try {
     return new BitmapDrawable(bitmap);
   } catch (Throwable t) {
     try {
       Log.e(LCAT, t.getClass().getName() + ": " + t.getMessage(), t);
       return null;
     } catch (Exception e) {
       // ignore - logging failed
       return null;
     }
   }
 }
예제 #15
0
  protected String getModulePath() {
    KrollContext kroll = weakKrollContext.get();
    Scriptable scope = kroll.getScope();

    if (DBG) {
      Log.e(LCAT, "getModulePath(): " + getClassName());
    }
    if (target != null) {
      if (DBG) {
        Log.e(LCAT, "targetPath: " + target.getClass().getPackage().getName());
      }
      return target.getClass().getPackage().getName() + ".";
    }

    if (scope.getParentScope() == null) {
      return "ti.modules." + getClassName().toLowerCase() + ".";
    } else {
      return ((KrollObject) scope.getParentScope()).getModulePath()
          + getClassName().toLowerCase()
          + ".";
    }
  }
  @Kroll.getProperty
  @Kroll.method
  public TabProxy getActiveTab() {
    TabProxy activeTab = null;

    if (peekView() != null) {
      TiUITabGroup tg = (TiUITabGroup) peekView();
      int activeTabIndex = tg.getActiveTab();

      if (activeTabIndex < 0) {
        Log.e(LCAT, "unable to get active tab, invalid index returned: " + activeTabIndex);
      } else if (activeTabIndex >= tabs.size()) {
        Log.e(LCAT, "unable to get active tab, index is larger than tabs array: " + activeTabIndex);
      }
      activeTab = tabs.get(activeTabIndex);
    } else {
      if (initialActiveTab instanceof Number) {
        int tabsIndex = TiConvert.toInt(initialActiveTab);
        if (tabsIndex >= tabs.size()) {
          activeTab = tabs.get(tabsIndex);
        } else {
          Log.e(LCAT, "Unable to get active tab, initialActiveTab index is larger than tabs array");
        }
      } else if (initialActiveTab instanceof TabProxy) {
        activeTab = (TabProxy) initialActiveTab;
      } else {
        Log.e(LCAT, "Unable to get active tab, initialActiveTab is not recognized");
      }
    }

    if (activeTab == null) {
      String errorMessage =
          "Failed to get activeTab, make sure tabs are added first before calling getActiveTab()";
      Log.e(LCAT, errorMessage);
      throw new RuntimeException(errorMessage);
    }
    return activeTab;
  }
예제 #17
0
  public Object createProxy(TiContext tiContext, Object[] args, String name) {
    Object o = null;
    String pname = buildProxyName(name);

    try {
      Class<?> c = Class.forName(pname);
      if (c != null) {
        Class<?>[] types = {TiContext.class, Object[].class};
        Constructor<?> ctor = c.getConstructor(types);
        if (ctor != null) {
          o = ctor.newInstance(tiContext, args);
        } else {
          Log.e(LCAT, "No valid constructor found");
        }
      } else {
        Log.e(LCAT, "No class for name " + pname);
      }
    } catch (Exception e) {
      Log.e(LCAT, "Error creating proxy " + pname + ": " + e.getMessage(), e);
    }

    return o;
  }
예제 #18
0
  protected void initialize() throws IOException {
    try {
      mp = new MediaPlayer();
      String url = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_URL));
      if (URLUtil.isAssetUrl(url)) {
        Context context = proxy.getTiContext().getTiApp();
        String path = url.substring(TiConvert.ASSET_URL.length());
        AssetFileDescriptor afd = null;
        try {
          afd = context.getAssets().openFd(path);
          // Why mp.setDataSource(afd) doesn't work is a problem for another day.
          // http://groups.google.com/group/android-developers/browse_thread/thread/225c4c150be92416
          mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } catch (IOException e) {
          Log.e(LCAT, "Error setting file descriptor: ", e);
        } finally {
          if (afd != null) {
            afd.close();
          }
        }
      } else {
        Uri uri = Uri.parse(url);
        if (uri.getScheme().equals(TiC.PROPERTY_FILE)) {
          mp.setDataSource(uri.getPath());
        } else {
          remote = true;
          mp.setDataSource(url);
        }
      }

      mp.setLooping(looping);
      mp.setOnCompletionListener(this);
      mp.setOnErrorListener(this);
      mp.setOnInfoListener(this);
      mp.setOnBufferingUpdateListener(this);

      mp.prepare(); // Probably need to allow for Async
      setState(STATE_INITIALIZED);

      setVolume(volume);
      if (proxy.hasProperty(TiC.PROPERTY_TIME)) {
        setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME)));
      }
    } catch (Throwable t) {
      Log.w(LCAT, "Issue while initializing : ", t);
      release();
      setState(STATE_STOPPED);
    }
  }
  public boolean dispatchEvent(String eventName, KrollDict data) {
    boolean dispatched = false;
    if (eventName != null) {
      Map<Integer, KrollListener> listeners = eventListeners.get(eventName);
      if (listeners != null) {
        if (data == null) {
          data = new KrollDict();
        }
        if (!data.containsKey("type")) {
          data.put("type", eventName);
        }

        Set<Entry<Integer, KrollListener>> listenerSet = listeners.entrySet();
        synchronized (eventListeners) {
          for (Entry<Integer, KrollListener> entry : listenerSet) {
            KrollListener listener = entry.getValue();
            if (proxy == null || (proxy != null && listener.isSameProxy(proxy))) {
              boolean invoked = false;
              try {
                if (listener.weakProxy.get() != null) {
                  if (!data.containsKey("source")) {
                    data.put("source", listener.weakProxy.get());
                  }
                  invoked = listener.invoke(eventName, data);
                }
              } catch (Exception e) {
                Log.e(
                    TAG,
                    "Error invoking listener with id "
                        + entry.getKey()
                        + " on eventName '"
                        + eventName
                        + "'",
                    e);
              }
              dispatched = dispatched || invoked;
            }
          }
        }
      } else {
        if (TRACE) {
          Log.w(TAG, "No listeners for eventName: " + eventName);
        }
      }
    } else {
      throw new IllegalStateException("dispatchEvent expects a non-null eventName");
    }
    return dispatched;
  }
  /* (non-Javadoc)
   * @see org.appcelerator.titanium.module.ITitaniumHttpClient#getResponseText()
   */
  public String getResponseText() {
    if (responseData != null && responseText == null) {
      if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
      }

      try {
        responseText = new String(responseData, charset);
      } catch (UnsupportedEncodingException e) {
        Log.e(LCAT, "Unable to convert to String using charset: " + charset);
      }
    }

    return responseText;
  }
예제 #21
0
 @Kroll.method
 public boolean openURL(String url) {
   if (DBG) {
     Log.d(LCAT, "Launching viewer for: " + url);
   }
   Uri uri = Uri.parse(url);
   Intent intent = new Intent(Intent.ACTION_VIEW, uri);
   try {
     getTiContext().getActivity().startActivity(intent);
     return true;
   } catch (ActivityNotFoundException e) {
     Log.e(LCAT, "Activity not found: " + url, e);
   }
   return false;
 }
예제 #22
0
  protected Object loadModule(String name) {
    Object p = null;

    String moduleName = createModuleName(name);
    if (DBG) {
      Log.d(LCAT, "Module: " + moduleName);
    }

    try {
      Class<?> c = Class.forName(moduleName);
      if (c != null) {

        Constructor<?>[] ctors = c.getConstructors();
        if (ctors.length == 1) {
          Constructor<?> ctor = ctors[0];
          Class<?>[] types = ctor.getParameterTypes();
          if (types.length == 0) {
            p = ctor.newInstance();
          } else if (types.length == 1) {
            p = ctor.newInstance(weakKrollContext.get().getTiContext());
          } else {
            Log.e(LCAT, "No valid constructor found.");
          }
        } else {
          Log.w(LCAT, "Modules currently requires only one contructor in a module.");
        }
      }
    } catch (Exception e) {
      Log.e(LCAT, "No Module for name " + name + " expected " + moduleName);
    }

    if (p != null && p instanceof TiModule) {
      TiModule m = (TiModule) p;
    }
    return p;
  }
예제 #23
0
  public DocumentProxy getResponseXML() {
    // avoid eating up tons of memory if we have a large binary data blob
    if (TiMimeTypeHelper.isBinaryMimeType(contentType)) {
      return null;
    }
    if (responseXml == null && (responseData != null || responseText != null)) {
      try {
        responseXml = XMLModule.parse(proxy.getTiContext(), getResponseText());
      } catch (Exception e) {
        Log.e(LCAT, "Error parsing XML", e);
      }
    }

    return responseXml;
  }
예제 #24
0
 @Override
 public void onDestroy() {
   super.onDestroy();
   try {
     for (ITitaniumLifecycle listener : mediaObjects) {
       try {
         listener.onDestroy();
       } catch (Throwable t) {
         Log.e(LCAT, "Error in onDestroy", t);
       }
     }
   } finally {
     mediaObjects.clear();
     mediaObjects = null;
   }
 }
예제 #25
0
  @Override
  public boolean shouldOverrideUrlLoading(final WebView view, String url) {
    if (DBG) {
      Log.d(LCAT, "url=" + url);
    }

    if (URLUtil.isAssetUrl(url) || URLUtil.isContentUrl(url) || URLUtil.isFileUrl(url)) {
      // go through the proxy to ensure we're on the UI thread
      webView.getProxy().setProperty("url", url, true);
      return true;
    } else if (url.startsWith(WebView.SCHEME_TEL)) {
      Log.i(LCAT, "Launching dialer for " + url);
      Intent dialer =
          Intent.createChooser(new Intent(Intent.ACTION_DIAL, Uri.parse(url)), "Choose Dialer");
      webView.getProxy().getTiContext().getActivity().startActivity(dialer);
      return true;
    } else if (url.startsWith(WebView.SCHEME_MAILTO)) {
      Log.i(LCAT, "Launching mailer for " + url);
      Intent mailer =
          Intent.createChooser(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)), "Send Message");
      webView.getProxy().getTiContext().getActivity().startActivity(mailer);
      return true;
    } else if (url.startsWith(WebView.SCHEME_GEO)) {
      Log.i(LCAT, "Launching app for " + url);
      /*geo:latitude,longitude
      geo:latitude,longitude?z=zoom
      geo:0,0?q=my+street+address
      geo:0,0?q=business+near+city
      */
      Intent geoviewer =
          Intent.createChooser(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), "Choose Viewer");
      webView.getProxy().getTiContext().getActivity().startActivity(geoviewer);
      return true;
    } else {
      String extension = MimeTypeMap.getFileExtensionFromUrl(url);
      String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
      if (mimeType != null) {
        return shouldHandleMimeType(mimeType, url);
      }

      if (DBG) {
        Log.e(LCAT, "NEED to Handle " + url);
      }
      return super.shouldOverrideUrlLoading(view, url);
    }
  }
 protected void dispatchOnEventChange(
     boolean added, String eventName, int count, KrollProxy proxy) {
   for (WeakReference<OnEventListenerChange> ref : eventChangeListeners) {
     OnEventListenerChange l = ref.get();
     if (l != null) {
       try {
         if (added) {
           l.eventListenerAdded(eventName, count, proxy);
         } else {
           l.eventListenerRemoved(eventName, count, proxy);
         }
       } catch (Throwable t) {
         Log.e(TAG, "Error invoking OnEventChangeListener: " + t.getMessage(), t);
       }
     }
   }
 }
예제 #27
0
  @Override
  public String readLine() throws IOException {
    String result = null;

    if (!opened) {
      throw new IOException("Must open before calling readLine");
    }
    if (binary) {
      throw new IOException("File opened in binary mode, readLine not available.");
    }

    try {
      result = inreader.readLine();
    } catch (IOException e) {
      Log.e(LCAT, "Error reading a line from the file: ", e);
    }

    return result;
  }
예제 #28
0
 @Override
 public List<String> getDirectoryListing() {
   List<String> listing = new ArrayList<String>();
   try {
     String lpath = TiFileHelper2.joinSegments("Resources", path);
     if (lpath.endsWith("/")) {
       lpath = lpath.substring(0, lpath.lastIndexOf("/"));
     }
     String[] names = getTiContext().getActivity().getAssets().list(lpath);
     if (names != null) {
       int len = names.length;
       for (int i = 0; i < len; i++) {
         listing.add(names[i]);
       }
     }
   } catch (IOException e) {
     Log.e(LCAT, "Error while getting a directory listing: " + e.getMessage(), e);
   }
   return listing;
 }
 /**
  * Start blocking the current thread with a busy loop that blocks on an internal CountDownLatch.
  *
  * <p>Another thread or entry point will need to call {@link #stopBlocking()} for this method to
  * return. While looping, the queue will also dispatch messages.
  */
 public void startBlocking() {
   synchronized (this) {
     if (isBlocking()) return;
     resetLatch();
     blockCount.incrementAndGet();
   }
   int timeout = 0;
   try {
     while (!blockingLatch.await(timeout, TimeUnit.MILLISECONDS)) {
       if (messageQueue.size() == 0) {
         timeout = 50;
       } else {
         dispatchPendingMessages();
       }
     }
   } catch (InterruptedException e) {
     Log.e(TAG, "interrupted while blocking", e);
   }
   dispatchPendingMessages();
   blockCount.decrementAndGet();
 }
예제 #30
0
  private void handleURLEncodedData(UrlEncodedFormEntity form) {
    AbstractHttpEntity entity = null;
    if (data != null) {
      try {
        entity = new StringEntity(data, "UTF-8");
      } catch (Exception ex) {
        // FIXME
        Log.e(LCAT, "Exception, implement recovery: ", ex);
      }
    } else {
      entity = form;
    }

    Header header = request.getFirstHeader("Content-Type");
    if (header == null) {
      entity.setContentType("application/x-www-form-urlencoded");
    } else {
      entity.setContentType(header.getValue());
    }

    HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request;
    e.setEntity(entity);
  }