Example #1
0
 public static void runOnEventThread(Runnable r) {
   if (Application.isEventDispatchThread()) {
     r.run();
   } else {
     Application.getApplication().invokeLater(r);
   }
 }
 public void setProgressAnimationInfo(Bitmap bitmap, int numFrames) {
   this.progressBitmap = bitmap;
   this.numFrames = numFrames;
   this.frameWidth = this.progressBitmap.getWidth() / this.numFrames;
   this.application = Application.getApplication();
   this.animate = false;
   this.visible = true;
   this.timerID = -1;
 }
Example #3
0
 public boolean onClose() {
   // check whether we can close the application
   if (PushController.canQuit()) {
     return super.onClose();
   } else {
     Application.getApplication().requestBackground();
     return false;
   }
 }
  private void processPushMessage(final byte[] data) {
    Application.getApplication()
        .invokeLater(
            new Runnable() {
              public void run() {
                String msg = new String(data);
                LOG.TRACE("Triger sync on PUSH message [" + msg + " ]\n");

                String[] op;
                String[] ops = split(msg, "\n");
                for (int loop = 0; loop < ops.length; loop++) {
                  if (ops[loop].startsWith("do_sync")) {
                    op = splitOnce(ops[loop], "=");
                    if (op.length <= 1 || "all".equalsIgnoreCase(op[1])) {
                      SyncThread.doSyncAllSources();
                    } else if ((op[1] != null) && (op[1].length() > 0)) {
                      SyncThread.doSyncSource(op[1].trim());
                    }
                  } else if (ops[loop].startsWith("show_popup")) {
                    op = splitOnce(ops[loop], "=");
                    if (op.length > 1) {
                      showPopup(op[1]);
                    }
                  } else if (ops[loop].startsWith("vibrate")) {
                    op = splitOnce(ops[loop], "=");
                    if (op.length > 1) {
                      vibrate(op[1]);
                    } else {
                      vibrate("2500");
                    }
                  } else if (ops[loop].startsWith("play_file")) {
                    op = splitOnce(ops[loop], "=");
                    if (op.length > 1) {
                      op = splitOnce(op[1], ",");
                      if (op.length > 1) {
                        play_file(op[0], op[1]);
                      } else {
                        play_file(op[0], null);
                      }
                    }
                  }
                }
              }
            });
  }
 public SensorTest() {
   // Create the HelloWorldScreen and open it
   pushScreen(new SensorTestScreen());
   Sensor.addListener(Application.getApplication(), this, Sensor.HOLSTER);
 }
/** @author kwallis */
public class FunctionFileTransferUpload extends ScriptableFunction {

  public static final String NAME = "upload";
  private ScriptableFunction _onProgress;
  private ScriptableFunction _onError;
  private Scriptable _options;
  private final Application _application = Application.getApplication();

  public Object invoke(Object thiz, Object[] args) {

    final String remotePath = args[0].toString();
    final String localPath = args[1].toString();
    _onProgress = (ScriptableFunction) args[2];
    _onError = (ScriptableFunction) args[3];
    _options = (Scriptable) args[4];

    if (_onProgress != null) {
      _application.invokeLater(
          new Runnable() {
            public void run() {
              try {
                new Thread(
                        new Runnable() {
                          public void run() {

                            Object objToPassWithInvoke = null;

                            try {
                              byte[] b = readFile(localPath);
                              objToPassWithInvoke = postViaHttpConnection(remotePath, b);

                            } catch (IOException e) {
                              objToPassWithInvoke = e.getMessage();
                              // e.printStackTrace();
                            }
                            try {
                              if (objToPassWithInvoke != null) {
                                invokeCallback(objToPassWithInvoke);
                              }
                            } catch (final Exception e) {

                            } finally {

                            }
                          }
                        })
                    .start();
              } catch (final Exception e) {
              }
            }
          });
    }

    return Boolean.TRUE;
  }

  private String postViaHttpConnection(String url, byte[] b) throws IOException {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    int rc;

    try {
      c = (HttpConnection) Connector.open(url);

      // Set the request method and headers
      c.setRequestMethod(HttpConnection.POST);

      c.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31 GMT");
      c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

      c.setRequestProperty("Content-Language", "en-US");

      // Getting the output stream may flush the headers
      os = c.openOutputStream();
      os.write(b);
      os.flush(); // Optional, getResponseCode will flush

      // Getting the response code will open the connection,
      // send the request, and read the HTTP response headers.
      // The headers are stored until requested.
      rc = c.getResponseCode();

      if (rc != HttpConnection.HTTP_OK) {
        throw new IOException("HTTP response code: " + rc);
      }

      is = c.openInputStream();

      // Get the ContentType
      String type = c.getType();
      // processType(type);

      // Get the length and process the data
      int len = (int) c.getLength();
      if (len > 0) {
        int actual = 0;
        int bytesread = 0;
        byte[] data = new byte[len];
        while ((bytesread != len) && (actual != -1)) {
          actual = is.read(data, bytesread, len - bytesread);
          bytesread += actual;
        }
        String s = "";
        for (int i = 0; i < data.length; i++) {
          s = s + (char) data[i];
        }
        return s;
      }
      // else {
      // int ch;
      // while ((ch = is.read()) != -1) {
      // process((byte)ch);
      // }
      // }

    } catch (ClassCastException e) {
      throw new IllegalArgumentException("Not an HTTP URL");
    } finally {
      if (is != null) is.close();
      if (os != null) os.close();
      if (c != null) c.close();
    }

    return "Resp"; //
  }

  private byte[] readFile(String path) {
    // scale file
    try {
      FileConnection fconn = (FileConnection) Connector.open(path);
      if (!fconn.exists()) {
        System.out.println("The file do not exist!");
      }
      InputStream input = fconn.openInputStream();
      int length = (int) fconn.fileSize(); // totalSize();

      // allocating a temporary Buffer.
      byte[] b = new byte[length];

      // reading data from a InputStream
      input.read(b, 0, length);

      fconn.close();
      return b;
    } catch (Exception ioe) {
      System.out.println(ioe.getMessage());
    }

    return new byte[0];
  }

  private void invokeCallback(Object objToPassWithInvoke) throws Exception {

    _onProgress.invoke(null, new Object[] {objToPassWithInvoke});
  }
}
  public Object eventOccurred(final Event event) {
    int eventId = event.getUID();
    switch (eventId) {
      case Event.EVENT_REDIRECT:
        {
          RedirectEvent e = (RedirectEvent) event;
          String referrer = e.getSourceURL();
          switch (e.getType()) {
            case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT:
              // Show redirect message.
              Application.getApplication()
                  .invokeAndWait(
                      new Runnable() {
                        public void run() {
                          Status.show(REDIRECT_MSG);
                        }
                      });
              break;

            case RedirectEvent.TYPE_JAVASCRIPT:
              break;

            case RedirectEvent.TYPE_META:
              // MSIE and Mozilla don't send a Referer for META Refresh.
              referrer = null;
              break;

            case RedirectEvent.TYPE_300_REDIRECT:
              // MSIE, Mozilla, and Opera all send the original request's Referer as the Referer for
              // the new request.
              Object eventSource = e.getSource();
              if (eventSource instanceof HttpConnection) {
                referrer = ((HttpConnection) eventSource).getRequestProperty(REFERER);
              }
              eventSource = null;
              break;
          }
          // Create the request, populate header with referrer and fire off the request.
          HttpHeaders requestHeaders = new HttpHeaders();
          requestHeaders.setProperty(REFERER, referrer);
          PrimaryResourceFetchThread thread =
              new PrimaryResourceFetchThread(e.getLocation(), requestHeaders, null, event, this);
          thread.start();
          e = null;
          referrer = null;
          requestHeaders = null;
          break;
        }
      case Event.EVENT_URL_REQUESTED:
        {
          UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event;
          String url = urlRequestedEvent.getURL();
          HttpHeaders header = urlRequestedEvent.getHeaders();
          PrimaryResourceFetchThread thread =
              new PrimaryResourceFetchThread(
                  url, header, urlRequestedEvent.getPostData(), event, this);
          thread.start();
          urlRequestedEvent = null;
          url = null;
          header = null;
          break;
        }
      case Event.EVENT_BROWSER_CONTENT_CHANGED:
        {
          // Browser field title might have changed update title.
          BrowserContentChangedEvent browserContentChangedEvent =
              (BrowserContentChangedEvent) event;
          if (browserContentChangedEvent.getSource() instanceof BrowserContent) {
            BrowserContent browserField = (BrowserContent) browserContentChangedEvent.getSource();
            String newTitle = browserField.getTitle();
            if (newTitle != null) {
              synchronized (getAppEventLock()) {
                _mainScreen.setTitle(newTitle);
              }
            }
            browserField = null;
            newTitle = null;
          }
          browserContentChangedEvent = null;
          break;
        }
      case Event.EVENT_CLOSE:
        // TODO: close the application
        break;

      case Event.EVENT_SET_HEADER: // No cache support.
      case Event.EVENT_SET_HTTP_COOKIE:
        String cookie = ((SetHttpCookieEvent) event).getCookie();
        if (cookie.startsWith(PHONEGAP_PROTOCOL)) {
          String response = commandManager.processInstruction(cookie);
          if ((response != null) && (response.trim().length() > 0)) {
            pendingResponses.addElement(response);
          }
          response = null;
        }
        cookie = null;
        break;
      case Event.EVENT_HISTORY: // TODO: No history support.. but we added our own history stack
        // implementation in ConnectionManager. Can we hook it up - then we'd have
        // access to window.history :o
      case Event.EVENT_EXECUTING_SCRIPT: // No progress bar is supported.
      case Event.EVENT_FULL_WINDOW: // No full window support.
      case Event.EVENT_STOP: // No stop loading support.
      default:
    }

    return null;
  }
Example #8
0
  public Object eventOccurred(Event event) {

    int eventId = event.getUID();

    switch (eventId) {
      case Event.EVENT_URL_REQUESTED:
        {
          UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event;
          String absoluteUrl = urlRequestedEvent.getURL();

          if (urlRequestedEvent.getPostData() == null
              || urlRequestedEvent.getPostData().length == 0) m_app.addToHistory(absoluteUrl, null);

          PrimaryResourceFetchThread thread =
              new PrimaryResourceFetchThread(
                  absoluteUrl,
                  urlRequestedEvent.getHeaders(),
                  urlRequestedEvent.getPostData(),
                  event);
          thread.start();

          break;
        }
      case Event.EVENT_BROWSER_CONTENT_CHANGED:
        {

          // browser field title might have changed update title
          /*BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event;

          if (browserContentChangedEvent.getSource() instanceof BrowserContent) {
              BrowserContent browserField = (BrowserContent) browserContentChangedEvent.getSource();
              String newTitle = browserField.getTitle();
              if (newTitle != null) {
                  synchronized (getAppEventLock())
              	//synchronized (Application.getEventLock())
                  {
                  	_mainScreen.setTitle(newTitle);
                  }
              }
          }*/

          break;
        }
      case Event.EVENT_REDIRECT:
        {
          RedirectEvent e = (RedirectEvent) event;
          String referrer = e.getSourceURL();
          String absoluteUrl = e.getLocation();

          switch (e.getType()) {
            case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT:
              // show redirect message
              Application.getApplication()
                  .invokeAndWait(
                      new Runnable() {
                        public void run() {
                          Status.show("You are being redirected to a different page...");
                        }
                      });

              break;

            case RedirectEvent.TYPE_JAVASCRIPT:
              break;
            case RedirectEvent.TYPE_META:
              // MSIE and Mozilla don't send a Referer for META Refresh.
              referrer = null;
              break;
            case RedirectEvent.TYPE_300_REDIRECT:
              // MSIE, Mozilla, and Opera all send the original
              // request's Referer as the Referer for the new
              // request.

              m_app.addToHistory(absoluteUrl, referrer);
              Object eventSource = e.getSource();
              if (eventSource instanceof HttpConnection) {
                referrer = ((HttpConnection) eventSource).getRequestProperty("referer");
              }
              break;
          }

          HttpHeaders requestHeaders = new HttpHeaders();
          requestHeaders.setProperty("referer", referrer);
          PrimaryResourceFetchThread thread =
              new PrimaryResourceFetchThread(absoluteUrl, requestHeaders, null, event);
          thread.start();
          break;
        }
      case Event.EVENT_CLOSE:
        // TODO: close the application
        break;

      case Event.EVENT_SET_HEADER:
      case Event.EVENT_SET_HTTP_COOKIE:
        {
          String cookie = ((SetHttpCookieEvent) event).getCookie();
          String strUrl = ((SetHttpCookieEvent) event).getURL();
          m_app.setCookie(strUrl, cookie);
          /*
          String response = processAjaxCall(cookie);
          if (response != null)
          	synchronized (pendingResponses) {
          		pendingResponses.addElement(response);
          	}
          response = null;
            	cookie = null;*/
          break;
        }
      case Event.EVENT_HISTORY: // no history support
      case Event.EVENT_EXECUTING_SCRIPT: // no progress bar is supported
      case Event.EVENT_FULL_WINDOW: // no full window support
      case Event.EVENT_STOP: // no stop loading support
      default:
    }

    return null;
  }
  /* @Override */
  public Object invoke(final Object thiz, final Object[] args) throws Exception {

    String contentArg = null;
    ScriptableFunction onGenerateArg = null;
    ScriptableFunction onErrorArg = null;
    Scriptable optionsArg = null;

    if (args.length < 2) {
      throw new IllegalArgumentException("Missing Captured Callback");
    } else {
      contentArg = (String) args[0];
      onGenerateArg = (ScriptableFunction) args[1];
      if (args.length > 2) {
        onErrorArg = (ScriptableFunction) args[2];
        if (args.length > 3) {
          optionsArg = (Scriptable) args[3];
        }
      }
    }

    final String contents = contentArg;
    final ScriptableFunction generatededCallback = onGenerateArg;
    final ScriptableFunction errorCallback = onErrorArg;
    final Scriptable options = optionsArg;

    Application.getApplication()
        .invokeLater(
            new Runnable() {

              private final String[] ALLOWED_EXTENSIONS = {"jpq", "jpeg", "png"};

              public void run() {

                FileConnection fconn = null;
                try {
                  MultiFormatWriter writer = new MultiFormatWriter();

                  int width = 50;
                  int height = 50;
                  BarcodeFormat format = BarcodeFormat.QR_CODE;
                  Hashtable hints = new Hashtable(2);
                  String filePath = "file:///SDCard/";
                  String fileName = "" + (new Date()).getTime();
                  String fileExtension = "png";

                  if (options != null) {
                    Object widthObj = options.getField("width");
                    if (widthObj != UNDEFINED) {
                      width = ((Integer) widthObj).intValue();
                    }

                    Object heightObj = options.getField("height");
                    if (heightObj != UNDEFINED) {
                      height = ((Integer) heightObj).intValue();
                    }

                    Object formatObj = options.getField("format");
                    if (formatObj != UNDEFINED) {
                      format = BarcodeFormat.valueOf(((String) formatObj).toUpperCase());
                    }

                    // Hints
                    Object charSetObj = options.getField("characterSet");
                    if (charSetObj != UNDEFINED) {
                      hints.put(EncodeHintType.CHARACTER_SET, (String) charSetObj);
                    }
                    Object errorCorrectionObj = options.getField("errorCorrection");
                    if (errorCorrectionObj != UNDEFINED) {
                      hints.put(EncodeHintType.ERROR_CORRECTION, (Integer) errorCorrectionObj);
                    }

                    Object filePathObj = options.getField("filePath");
                    if (filePathObj != UNDEFINED) {
                      String filePathOrig = (String) filePathObj;
                      fileExtension = filePathOrig.substring(filePathOrig.lastIndexOf('.') + 1);
                      fileName =
                          filePathOrig.substring(
                              filePathOrig.lastIndexOf('/') + 1, filePathOrig.lastIndexOf('.'));
                      filePath = filePathOrig.substring(0, filePathOrig.lastIndexOf('/'));

                      boolean validExtension = false;
                      for (int i = 0; i < ALLOWED_EXTENSIONS.length; i++) {
                        validExtension |= fileExtension.equals(ALLOWED_EXTENSIONS[i]);
                      }
                      if (!validExtension) {
                        fileExtension = "png";
                      }
                    }
                  }

                  ByteMatrix bm;
                  try {
                    bm = writer.encode(contents, format, width, height, hints);
                  } catch (ClassCastException cce) {
                    throw new Exception(
                        "ZXing Barcode Writer FAILURE - try different paramteres and pray");
                  }
                  // Bitmap b = BarcodeBitmap.createBitmap(bm,0);
                  Bitmap b = new Bitmap(width, height);

                  byte[][] array = bm.getArray();
                  // iterate through the matrix and draw the pixels to the image
                  // a Jeff and BT super hack to make generating a barcode work
                  for (int y = 0; y < height; y++) {
                    int[] argbArray = new int[width];
                    for (int x = 0; x < width; x++) {
                      int grayValue = array[y][x] & 0xff;
                      int pixel = (grayValue == 0 ? 0xFF000000 : 0xFFFFFFFF);
                      argbArray[x] = pixel;
                    }
                    b.setARGB(argbArray, 0, width, 0, y, width, 1);
                  }

                  fconn =
                      (FileConnection)
                          Connector.open(
                              filePath + "/" + fileName + "." + fileExtension,
                              Connector.READ_WRITE);

                  if (fconn.exists()) {
                    fileName += (new Date()).getTime();
                    fconn.close();
                    fconn =
                        (FileConnection)
                            Connector.open(
                                filePath + "//" + fileName + "." + fileExtension,
                                Connector.READ_WRITE);
                  }

                  fconn.create();

                  OutputStream outputStream = fconn.openOutputStream();
                  EncodedImage encodedImage;
                  if (fileExtension.equals("jpg") || fileExtension.equals("jpeg")) {
                    encodedImage = JPEGEncodedImage.encode(b, 100);
                  } else {
                    encodedImage = PNGEncodedImage.encode(b);
                  }
                  byte[] imageBytes = encodedImage.getData();
                  outputStream.write(imageBytes);
                  outputStream.close();

                  fconn.close();
                  Object[] args = {filePath + "//" + fileName + "." + fileExtension};
                  generatededCallback.invoke(thiz, args);

                } catch (Exception e) {
                  throwError(e);
                } finally {
                  try {
                    fconn.close();
                  } catch (IOException e) {
                    throwError(e);
                  }
                }
              }

              public void throwError(Exception e) {
                if (errorCallback != null) {

                  try {
                    errorCallback.invoke(thiz, new Object[] {new ErrorObject(-1, e.getMessage())});
                  } catch (Exception e1) {
                  }
                }
              }
            });

    return UNDEFINED;
  }