Example #1
0
 public void abort() {
   if (readyState > READY_STATE_UNSENT && readyState < READY_STATE_DONE) {
     if (client != null) {
       if (DBG) {
         Log.d(LCAT, "Calling shutdown on clientConnectionManager");
       }
       aborted = true;
       if (handler != null) {
         handler.client = null;
         if (handler.is != null) {
           try {
             if (handler.entity.isStreaming()) {
               handler.entity.consumeContent();
             }
             handler.is.close();
           } catch (IOException e) {
             Log.i(LCAT, "Force closing HTTP content input stream", e);
           } finally {
             handler.is = null;
           }
         }
       }
       if (client != null) {
         client.getConnectionManager().shutdown();
         client = null;
       }
     }
   }
 }
Example #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;
 }
Example #3
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);
     }
   }
 }
  @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);
  }
 public void removeEventListener(String eventName, int listenerId) {
   if (eventName != null) {
     HashMap<Integer, KrollListener> listeners = eventListeners.get(eventName);
     if (listeners != null) {
       KrollListener listener = listeners.get(listenerId);
       if (listeners.remove(listenerId) == null) {
         if (DBG) {
           Log.w(TAG, "listenerId " + listenerId + " not for eventName '" + eventName + "'");
         }
       } else {
         dispatchOnEventChange(false, eventName, listeners.size(), listener.weakProxy.get());
         if (DBG) {
           Log.i(
               TAG,
               "listener with id "
                   + listenerId
                   + " with eventName '"
                   + eventName
                   + "' was removed.");
         }
       }
     }
   } else {
     throw new IllegalStateException("removeEventListener expects a non-null eventName");
   }
 }
  public void play() {
    try {
      if (mp == null) {
        setState(STATE_STARTING);
        initialize();
      }

      if (mp != null) {
        if (!isPlaying()) {
          if (DBG) {
            Log.d(LCAT, "audio is not playing, starting.");
          }
          setVolume(volume);
          if (DBG) {
            Log.d(LCAT, "Play: Volume set to " + volume);
          }
          mp.start();
          setState(STATE_PLAYING);
          paused = false;
          if (remote) {
            startProgressTimer();
          }
        }
        setState(STATE_PLAYING);
      }
    } catch (Throwable t) {
      Log.w(LCAT, "Issue while playing : ", t);
      reset();
    }
  }
  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);
    }
  }
Example #8
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;
  }
  public synchronized void postAnalyticsEvent(TiAnalyticsEvent event) {
    if (!collectAnalytics()) {
      if (DBG) {
        Log.i(LCAT, "Analytics are disabled, ignoring postAnalyticsEvent");
      }
      return;
    }

    if (DBG) {
      StringBuilder sb = new StringBuilder();
      sb.append("Analytics Event: type=")
          .append(event.getEventType())
          .append("\n event=")
          .append(event.getEventEvent())
          .append("\n timestamp=")
          .append(event.getEventTimestamp())
          .append("\n mid=")
          .append(event.getEventMid())
          .append("\n sid=")
          .append(event.getEventSid())
          .append("\n aguid=")
          .append(event.getEventAppGuid())
          .append("\n isJSON=")
          .append(event.mustExpandPayload())
          .append("\n payload=")
          .append(event.getEventPayload());
      Log.d(LCAT, sb.toString());
    }

    if (event.getEventType() == TiAnalyticsEventFactory.EVENT_APP_ENROLL) {
      if (needsEnrollEvent) {
        analyticsModel.addEvent(event);
        needsEnrollEvent = false;
        sendAnalytics();
        analyticsModel.markEnrolled();
      }
    } else if (event.getEventType() == TiAnalyticsEventFactory.EVENT_APP_START) {
      if (needsStartEvent) {
        analyticsModel.addEvent(event);
        needsStartEvent = false;
        sendAnalytics();
        lastAnalyticsTriggered = System.currentTimeMillis();
      }
      return;
    } else if (event.getEventType() == TiAnalyticsEventFactory.EVENT_APP_END) {
      needsStartEvent = true;
      analyticsModel.addEvent(event);
      sendAnalytics();
    } else {
      analyticsModel.addEvent(event);
      long now = System.currentTimeMillis();
      if (now - lastAnalyticsTriggered >= STATS_WAIT) {
        sendAnalytics();
        lastAnalyticsTriggered = now;
      }
    }
  }
  public TiApplication() {
    Log.checkpoint(LCAT, "checkpoint, app created.");
    _instance = this;

    needsEnrollEvent = false; // test is after DB is available
    needsStartEvent = true;
    loadBuildProperties();
    Log.i(LCAT, "Titanium " + buildVersion + " (" + buildTimestamp + " " + buildHash + ")");
  }
 @Override
 public void onChannelSelected(String channelName) {
   Log.d(LCAT, "inside onChannelSelected");
   Log.d(LCAT, "channelName: " + channelName);
   BranchUniversalObjectProxy self = BranchUniversalObjectProxy.this;
   KrollDict response = new KrollDict();
   response.put("channelName", channelName);
   self.fireEvent("bio:shareChannelSelected", response);
 }
Example #12
0
  public void handleTextAlign(String textAlign, String verticalAlign) {
    int valign = field ? Gravity.CENTER_VERTICAL : Gravity.TOP;
    int align = Gravity.LEFT;

    if (textAlign != null) {
      if ("left".equals(textAlign)) {
        align = Gravity.LEFT;
      } else if ("center".equals(textAlign)) {
        align = Gravity.CENTER_HORIZONTAL;
      } else if ("right".equals(textAlign)) {
        align = Gravity.RIGHT;
      } else {
        Log.w(LCAT, "Unsupported alignment: " + textAlign);
      }
    } else {
      // Nothing has been set - let's set if something was set previously
      // You can do this with shortcut syntax - but long term maint of code is easier if it's
      // explicit
      Log.w(
          LCAT,
          "No alignment set - old horiz align was: "
              + (tv.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK));

      if ((tv.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.NO_GRAVITY) {
        // Something was set before - so let's use it
        align = tv.getGravity() & Gravity.HORIZONTAL_GRAVITY_MASK;
      }
    }

    if (verticalAlign != null) {
      if ("top".equals(verticalAlign)) {
        valign = Gravity.TOP;
      } else if ("middle".equals(verticalAlign)) {
        valign = Gravity.CENTER_VERTICAL;
      } else if ("bottom".equals(verticalAlign)) {
        valign = Gravity.BOTTOM;
      } else {
        Log.w(LCAT, "Unsupported alignment: " + verticalAlign);
      }
    } else {
      // Nothing has been set - let's set if something was set previously
      // You can do this with shortcut syntax - but long term maint of code is easier if it's
      // explicit
      Log.w(
          LCAT,
          "No alignment set - old vert align was: "
              + (tv.getGravity() & Gravity.VERTICAL_GRAVITY_MASK));

      if ((tv.getGravity() & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.NO_GRAVITY) {
        // Something was set before - so let's use it
        valign = tv.getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
      }
    }

    tv.setGravity(valign | align);
  }
 public void scheduleRestart(int delay) {
   Log.w(LCAT, "Scheduling application restart");
   if (DBG) {
     Log.d(
         LCAT,
         "Here is call stack leading to restart. (NOTE: this is not a real exception, just a stack trace.) :");
     (new Exception()).printStackTrace();
   }
   if (getRootActivity() != null) {
     getRootActivity().restartActivity(delay);
   }
 }
  public void setEraseMode(Boolean toggle) {
    eraseState = toggle;

    if (eraseState) {
      Log.d(LCAT, "Setting Erase Mode to True.");
      tiPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    } else {
      Log.d(LCAT, "Setting Erase Mode to False.");
      tiPaint.setXfermode(null);
    }

    tiPaint.setAlpha(alphaState);
  }
  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;
  }
Example #16
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);
    }
  }
 @Override
 public void onLinkCreate(String url, BranchError error) {
   Log.d(LCAT, "inside onLinkCreate");
   BranchUniversalObjectProxy self = BranchUniversalObjectProxy.this;
   KrollDict response = new KrollDict();
   if (error == null) {
     Log.d(LCAT, "link to share: " + url);
     response.put("generatedLink", url);
   } else {
     String errorMessage = error.getMessage();
     Log.d(LCAT, errorMessage);
     response.put("error", errorMessage);
   }
   self.fireEvent("bio:generateShortUrl", response);
 }
 @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;
 }
Example #19
0
 public void sendError(String error) {
   Log.i(LCAT, "Sending error " + error);
   TiDict event = new TiDict();
   event.put("error", error);
   event.put("source", proxy);
   fireCallback(ON_ERROR, new Object[] {event});
 }
Example #20
0
  public void onRegistrered(Context context, String registrationId) throws IOException {
    Log.d(LCAT, "Registered: " + registrationId);

    KrollDict data = new KrollDict();
    data.put("registrationId", registrationId);
    C2dmModule.getInstance().fireEvent(REGISTER_EVENT, data);
  }
 public void sendAnalytics() {
   if (analyticsIntent != null) {
     if (startService(analyticsIntent) == null) {
       Log.w(LCAT, "Analytics service not found.");
     }
   }
 }
Example #22
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;
  }
  private void addTabToGroup(TiUITabGroup tg, TabProxy tab) {
    TiTabActivity tta = weakActivity.get();
    if (tta == null) {
      if (DBG) {
        Log.w(LCAT, "Could not add tab because tab activity no longer exists");
      }
    }
    Drawable icon =
        TiDrawableReference.fromObject(getTiContext(), tab.getProperty(TiC.PROPERTY_ICON))
            .getDrawable();
    String tag = TiConvert.toString(tab.getProperty(TiC.PROPERTY_TAG));
    String title = TiConvert.toString(tab.getProperty(TiC.PROPERTY_TITLE));
    if (title == null) {
      title = "";
    }
    tab.setTabGroup(this);
    final WindowProxy vp = (WindowProxy) tab.getProperty(TiC.PROPERTY_WINDOW);
    vp.setTabGroupProxy(this);
    vp.setTabProxy(tab);
    if (tag != null && vp != null) {
      TabSpec tspec = tg.newTab(tag);
      if (icon == null) {
        tspec.setIndicator(title);
      } else {
        tspec.setIndicator(title, icon);
      }

      Intent intent = new Intent(tta, TiActivity.class);
      vp.fillIntentForTab(intent);

      tspec.setContent(intent);

      tg.addTab(tspec);
    }
  }
  public int addEventListener(String eventName, Object listener) {
    int listenerId = -1;
    int listenerCount = 0;

    if (eventName != null) {
      if (proxy != null) {
        if (listener != null) {
          synchronized (eventListeners) {
            HashMap<Integer, KrollListener> listeners = eventListeners.get(eventName);
            if (listeners == null) {
              listeners = new HashMap<Integer, KrollListener>();
              eventListeners.put(eventName, listeners);
            }

            listenerId = listenerIdGenerator.incrementAndGet();
            listeners.put(listenerId, new KrollListener(proxy, listener));
            if (DBG) {
              Log.d(TAG, "Added for eventName '" + eventName + "' with id " + listenerId);
            }

            listenerCount = listeners.size();
          }
          dispatchOnEventChange(true, eventName, listenerCount, proxy);
        } else {
          throw new IllegalStateException("addEventListener expects a non-null listener");
        }
      } else {
        throw new IllegalStateException("addEventListener expects a non-null KrollProxy");
      }
    } else {
      throw new IllegalStateException("addEventListener expects a non-null eventName");
    }

    return listenerId;
  }
Example #25
0
 @Override
 public void register(WebView webView) {
   String name = super.getModuleName();
   if (DBG) {
     Log.d(LCAT, "Registering TitaniumApp as " + name);
   }
   webView.addJavascriptInterface((ITitaniumApp) this, name);
 }
Example #26
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);
  }
 @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);
 }
 @Override
 public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) {
   Log.d(LCAT, "inside onLinkCreate");
   BranchUniversalObjectProxy self = BranchUniversalObjectProxy.this;
   KrollDict response = new KrollDict();
   if (error == null) {
     response.put("sharedLink", sharedLink);
     response.put("sharedChannel", sharedChannel);
     Log.d(LCAT, "sharedLink: " + sharedLink);
     Log.d(LCAT, "sharedChannel: " + sharedChannel);
   } else {
     String errorMessage = error.getMessage();
     Log.d(LCAT, errorMessage);
     response.put("error", errorMessage);
   }
   self.fireEvent("bio:shareLinkResponse", response);
 }
Example #29
0
 @Override
 public void put(int arg0, Scriptable arg1, Object arg2) {
   // TODO Auto-generated method stub
   super.put(arg0, arg1, arg2);
   if (DBG) {
     Log.w(LCAT, "Put[]");
   }
 }
  // Handle creation options
  @Override
  public void handleCreationDict(KrollDict options) {
    super.handleCreationDict(options);

    if (options.containsKey("message")) {
      Log.d(TAG, "example created with message: " + options.get("message"));
    }
  }