Esempio n. 1
0
  private void getTrafficSpots() {
    controller.showProgressBar();
    String uploadWebsite =
        "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }
      // System.out.println("b"+b);
      try {
        JSONObject ff1 = new JSONObject(b.toString());
        String data1 = ff1.getString("locations");
        JSONArray jsonArray1 = new JSONArray(data1);
        Vector TrafficStatus = new Vector();
        for (int i = 0; i < jsonArray1.length(); i++) {

          System.out.println(jsonArray1.getJSONArray(i).getString(3));
          double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1));
          double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2));
          System.out.println(aDoubleLat + " " + aDoubleLon);
          TrafficStatus.addElement(
              new LocationPointer(
                  jsonArray1.getJSONArray(i).getString(3),
                  (float) aDoubleLon,
                  (float) aDoubleLat,
                  1,
                  true));
        }
        controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus));
      } catch (Exception E) {
        controller.setCurrentScreen(traf);
        new Thread() {
          public void run() {
            controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
          }
        }.start();
      }

    } catch (Exception e) {

      controller.setCurrentScreen(traf);
      new Thread() {
        public void run() {
          controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
        }
      }.start();
    }
  }
    /** Shows current tweet dialog and downloads user image */
    private void showTweet() {
      String text = current_tweet.getText();

      if (text != null) {
        String from = current_tweet.getFromUser();
        Alert a = new Alert("" + from, text, null, AlertType.INFO);

        a.setTimeout(Alert.FOREVER);
        display.setCurrent(a, this);
        String url = current_tweet.getProfileImageUrl();

        if (url != null) {
          // download and set user image to visible alert
          Image img;
          InputStream is = null;

          try {
            is = Connector.openInputStream(url);
            img = Image.createImage(is);
            a.setImage(img);
          } catch (Throwable t) { // do not show errors if image
            // download fails
          } finally {
            try {
              if (is != null) {
                is.close();
              }
            } catch (Throwable e) {
            }
          }
        }
      }
    }
Esempio n. 3
0
  public OutputStream openSession(String url, String name) {
    OutputStream oS = null;
    // #if polish.api.fileconnection
    try {
      url += name + ".gpx";
      // #debug info
      logger.info("Opening file " + url);
      session = Connector.open(url);
      FileConnection fileCon = (FileConnection) session;
      if (fileCon == null) throw new IOException("Couldn't open url " + url);
      if (!fileCon.exists()) {
        fileCon.create();
      } else {
        fileCon.truncate(0);
      }

      oS = fileCon.openOutputStream();
    } catch (IOException e) {
      logger.error(
          Locale.get(
                  "fileexportsession.CouldNotObtainConnection") /*Could not obtain connection with */
              + url
              + " ("
              + e.getMessage()
              + ")");
      e.printStackTrace();
    }
    // #endif
    return oS;
  }
 public void testFormat() {
   InputConnection conn = null;
   DataInputStream dis = null;
   try {
     conn = (InputConnection) Connector.open("scratchpad:///0");
     dis = conn.openDataInputStream();
     assertEquals("bytes per sector", 256, dis.readUnsignedShort());
     assertEquals("sector per cluster", 1, dis.readUnsignedByte());
     assertEquals("reserved sector", 1, dis.readUnsignedShort());
     assertEquals("number of fats", 1, dis.readUnsignedByte());
     assertEquals("root entries", 256, dis.readUnsignedShort());
     assertEquals("total sectors", 200, dis.readUnsignedShort());
     assertEquals("sector per fat", 100, dis.readUnsignedShort());
   } catch (IOException e) {
     fail(e.toString());
   } finally {
     if (dis != null)
       try {
         dis.close();
       } catch (IOException e) {
       }
     ;
     if (conn != null)
       try {
         conn.close();
       } catch (IOException e) {
       }
     ;
   }
 }
 public void run() {
   try {
     this.url += NetworkConfig.getConnectionParameters(this.settings.getConnectionMode());
     this.httpConnection = ((HttpConnection) Connector.open(this.url));
     this.httpConnection.setRequestMethod("DELETE");
     this.httpConnection.setRequestProperty("User-Agent", BrightBerry.useragent);
     this.httpConnection.setRequestProperty("Authorization", this.settings.getAuthHeader());
     this.httpConnection.setRequestProperty("x-rim-transcode-content", "none");
     int rc = httpConnection.getResponseCode();
     System.out.println("Response code: " + rc);
     if (rc == 200) {
       this.screen.callDelete(true);
     } else {
       if (rc == 503) {
         BrightBerry.displayAlert("Error", "BrightKite is too busy at the moment try again later");
         this.screen.callDelete(false);
       } else if (rc == 401 || rc == 403) {
         BrightBerry.errorUnauthorized();
       } else {
         this.screen.callDelete(false);
       }
     }
     if (this.httpConnection != null) {
       this.httpConnection.close();
     }
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
Esempio n. 6
0
  // start server
  public void startServer() throws IOException {

    // Create a UUID for SPP
    UUID uuid = new UUID(Config.uuid, true);
    System.out.println(uuid.toString());
    // Create the servicve url
    String connectionString = "btspp://localhost:" + uuid + ";name=Bluetooth SPP Server";

    // open server url
    StreamConnectionNotifier streamConnNotifier =
        (StreamConnectionNotifier) Connector.open(connectionString);

    // Wait for client connection
    System.out.println("\nServer Started. Waiting for clients to connect...");
    while (isRunning) {
      connection = streamConnNotifier.acceptAndOpen();
      System.out.println("Connection opened");
      RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
      System.out.println("Remote device address: " + dev.getBluetoothAddress());
      System.out.println("Remote device name: " + dev.getFriendlyName(true));

      inStream = connection.openInputStream();
      outStream = connection.openOutputStream();

      if ((dev.getFriendlyName(true) == Config.pairedDevice) || true) {
        new Receiver().start();
        new Sender().start();
      }
    }
    streamConnNotifier.close();
  }
 public void setBytes(int memoryOffset, byte[] buffer, int bufferOffset, int length) {
   if (length == 0) {
     return;
   }
   if ((memoryOffset & 1) == 1) {
     throw new IndexOutOfBoundsException("offset must be even");
   }
   if ((length & 1) == 1) {
     throw new IndexOutOfBoundsException("length must be even");
   }
   ensureInBounds(memoryOffset, buffer, bufferOffset, length);
   System.arraycopy(buffer, bufferOffset, bytes, memoryOffset, length);
   if (fileName == null) {
     return;
   }
   try {
     DataOutputStream output = Connector.openDataOutputStream("file://" + fileName);
     output.writeInt(startAddress.toUWord().toInt());
     output.writeInt(size);
     output.writeShort(purpose);
     output.write(bytes);
     output.close();
   } catch (IOException e) {
     throw new RuntimeException(e.getMessage());
   }
 }
Esempio n. 8
0
 private Image getAvatar() {
   HttpConnection httemp = null;
   InputStream istemp = null;
   Image avatar = null;
   try {
     httemp = (HttpConnection) Connector.open(url);
     if (HttpConnection.HTTP_OK != httemp.getResponseCode()) {
       throw new IOException();
     }
     istemp = httemp.openInputStream();
     byte[] avatarBytes = read(istemp, (int) httemp.getLength());
     // #sijapp cond.if modules_TRAFFIC is "true" #
     Traffic.getInstance().addInTraffic(avatarBytes.length);
     // #sijapp cond.end#
     avatar = javax.microedition.lcdui.Image.createImage(avatarBytes, 0, avatarBytes.length);
     avatarBytes = null;
   } catch (Exception e) {
   }
   try {
     httemp.close();
     istemp.close();
   } catch (Exception e) {
   }
   return avatar;
 }
  public void run() {
    String url = formPushListenUrl();
    try {
      socket = (ServerSocketConnection) Connector.open(url);
    } catch (IOException ex) {
      System.out.println("can't open the port, probably taken by another application " + ex);
      ex.printStackTrace();
    }

    while (running) {
      try {
        Object o = socket.acceptAndOpen();
        conn = (HttpServerConnection) o;
        inputStream = conn.openInputStream();
        pushInputStream = new MDSPushInputStream(conn, inputStream);
        process(pushInputStream);
      } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        if (running) {
          running = false;
        }
      } finally {
        Messaging.close(conn, pushInputStream, null);
      }
    }
  }
  /** Modified by Gabriele Bianchi 04/01/2006 */
  public void run() {
    StringBuffer connectorStringBuffer;
    if (Datas.isSSL) {
      connectorStringBuffer = new StringBuffer("ssl://");
    } else {
      connectorStringBuffer = new StringBuffer("socket://");
    }
    connectorStringBuffer.append(_hostname);
    connectorStringBuffer.append(":");
    connectorStringBuffer.append(_port);
    connectorStringBuffer.append("");

    String connectorString = connectorStringBuffer.toString().trim();
    System.out.println(connectorString);
    try {
      if (Datas.isSSL) {
        connection = (SecureConnection) Connector.open(connectorString);
      } else {
        connection = (StreamConnection) /*Connector.open*/ getConnectionForRequest(connectorString);
      }
      if (connection != null) {
        SocketConnection sc = (SocketConnection) connection;
        sc.setSocketOption(SocketConnection.KEEPALIVE, 2);
      }

      _cm.notifyConnect(connection, this.openInputStream(), this.openOutputStream());
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Connessione non riuscita:" + e.getMessage());
      _cm.notifyNoConnectionOn("I can't connect, server is unreachable");
      DebugStorage.getInstance().Log(0, "Can't connect, server is unreachable", e);
    }

    return;
  }
Esempio n. 11
0
  /**
   * This method writes to a text file
   *
   * @param fName Name of the file
   * @param text Text to store in the file
   */
  public void writeTextFile(String fName, String text) {
    DataOutputStream os = null;
    FileConnection fconn = null;

    try {

      fconn = (FileConnection) Connector.open("file:///SDCard/BlackBerry/" + fName);
      if (!fconn.exists()) {
        fconn.create();
      } else {
        fconn.truncate(0);
      }
      os = fconn.openDataOutputStream();
      System.out.println(text);
      os.write(text.getBytes());
    } catch (IOException e) {
      System.out.println(e.getMessage());
    } finally {
      try {
        if (null != os) os.close();
        if (null != fconn) fconn.close();
      } catch (IOException e) {
        System.out.println(e.getMessage());
      }
    }
  }
Esempio n. 12
0
  public static void main(String[] args) throws IOException {
    System.out.println("Main.main");

    LocalDevice localDevice = LocalDevice.getLocalDevice();

    localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service

    String address = "742F6896BDD2"; // A500
    UUID device_UUID = new UUID(address, false);
    String url = "btspp://localhost:" + device_UUID + ";name=A500";
    StreamConnectionNotifier server = (StreamConnectionNotifier) Connector.open(url);

    System.out.println("wait until client connects");
    StreamConnection connection = server.acceptAndOpen(); // Wait until client connects
    // === At this point, two devices should be connected ===//
    System.out.println("connected");
    DataInputStream dis = connection.openDataInputStream();

    char c;
    while (true) {
      c = dis.readChar();
      if (c == 'x') break;
    }

    connection.close();

    System.out.println("Main.end");
  }
Esempio n. 13
0
  private Image getImage(String str) throws IOException {
    String url = "http://" + controller.selectedCity.URL + "/cameras/images/" + str + ".jpg";
    System.out.println(url);
    InputStream iStrm = (InputStream) Connector.openInputStream(url);
    Image im = null;

    try {
      ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

      int ch;
      while ((ch = iStrm.read()) != -1) bStrm.write(ch);

      // Place into image array
      byte imageData[] = bStrm.toByteArray();

      // Create the image from the byte array
      im = Image.createImage(imageData, 0, imageData.length);

    } finally {
      // Clean up
      if (iStrm != null) iStrm.close();
    }

    return (im == null ? null : im);
  }
Esempio n. 14
0
 public void startApp() {
   if (mForm == null) {
     mForm = new Form(mAppID);
     mNumberEntry = new TextField("Connect To:", null, 256, TextField.PHONENUMBER);
     try {
       mInitialImage = Image.createImage(DEFAULT_IMAGE);
     } catch (Exception e) {
       System.out.println("start app err");
       e.printStackTrace();
     }
     mColorSquare =
         new ImageItem(null, mInitialImage, ImageItem.LAYOUT_DEFAULT, "waiting for image");
     mForm.append(mNumberEntry);
     mForm.append(mColorSquare);
     mForm.addCommand(mRedCommand);
     mForm.addCommand(mExitCommand);
     mForm.addCommand(mBlueCommand);
     mForm.setCommandListener(this);
   }
   Display.getDisplay(this).setCurrent(mForm);
   try {
     conn = (MessageConnection) Connector.open("mms://:" + mAppID);
     conn.setMessageListener(this);
   } catch (Exception e) {
     System.out.println("" + e);
   }
   if (conn != null) {
     startReceive();
   }
 }
  private int availableMessages() {
    String content;
    try {
      StreamConnection s = null;
      s = (StreamConnection) Connector.open(getAvailableUrl());
      HttpConnection httpConn = (HttpConnection) s;

      int status = httpConn.getResponseCode();

      if (status == HttpConnection.HTTP_OK) {
        // Is this html?

        InputStream input = s.openInputStream();

        byte[] data = new byte[256];
        int len = 0;
        int size = 0;
        StringBuffer raw = new StringBuffer();

        while (-1 != (len = input.read(data))) {
          // Exit condition for the thread. An IOException is
          // thrown because of the call to  httpConn.close(),
          // causing the thread to terminate.
          if (_stop) {
            httpConn.close();
            s.close();
            input.close();
          }
          raw.append(new String(data, 0, len));
          size += len;
        }

        //         raw.insert(0, "bytes received]\n");
        //       raw.insert(0, size);
        //     raw.insert(0, '[');
        content = raw.toString();
        input.close();
      } else {
        content = "response code = " + status;
      }
      s.close();
    } catch (IOCancelledException e) {
      System.out.println(e.toString());
      return inserted;
    } catch (Exception e) {
      System.out.println(e.toString());
      return inserted;
    }
    String intString = content;
    int i = 0;
    for (; i < content.length(); i++) {
      char aChar = content.charAt(i);
      if (aChar < '0' || aChar > '9') break;
    }
    if (i > 0) return Integer.parseInt(content.substring(0, i));
    return inserted;
  }
Esempio n. 16
0
 /**
  * Create a platform-specific HTTP network connection, and set the HTTP header with the
  * corresponding key-value pairs
  *
  * @param url
  * @param requestPropertyKeys - a list of header keys
  * @param requestPropertyValues - a list of associated header values
  * @throws IOException
  */
 public JMEHttpConn(
     final String url, final Vector requestPropertyKeys, final Vector requestPropertyValues)
     throws IOException {
   httpConnection = (HttpConnection) Connector.open(url);
   for (int i = 0; i < requestPropertyKeys.size(); i++) {
     httpConnection.setRequestProperty(
         (String) requestPropertyKeys.elementAt(i), (String) requestPropertyValues.elementAt(i));
   }
 }
  public Object invoke(Object obj, Object[] args) throws Exception {
    // input = (email address, subject, body, full attachment path)

    String email = (String) args[0].toString();
    String subject = (String) args[1].toString();
    String body = (String) args[2].toString();
    String attachment = (String) args[3].toString();
    String fName = attachment;
    byte[] data = null;
    FileConnection fconn = null;
    DataInputStream is = null;
    try {
      fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
      is = fconn.openDataInputStream();
      data = IOUtilities.streamToBytes(is);
      is.close();
      fconn.close();
    } catch (Exception ex) {
      Dialog.inform("Error in file path: " + ex.toString());
      return new Boolean(false);
    }
    // create a multipart
    Multipart mp = new Multipart();

    // create the file
    SupportedAttachmentPart sap =
        new SupportedAttachmentPart(mp, "application/x-example", attachment, data);

    TextBodyPart tbp = new TextBodyPart(mp, body);

    // add the file to the multipart
    mp.addBodyPart(tbp);
    mp.addBodyPart(sap);

    // create a message in the sent items folder
    Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);

    Message message = new Message(folders[0]);
    Address toAdd = new Address(email, "my email");
    Address toAdds[] = new Address[1];
    toAdds[0] = toAdd;
    message.addRecipients(Message.RecipientType.TO, toAdds);
    message.setSubject(subject);
    message.setContent(mp);
    Session session = Session.getDefaultInstance();
    Transport trans = session.getTransport();
    // add recipients to the message and send
    boolean sent = false;
    try {
      trans.send(message);
      sent = true;
    } catch (Exception e) {
      Dialog.inform("Error while sending: " + e.toString());
    }

    return new Boolean(sent);
  }
Esempio n. 18
0
 private GcfHttpRepresentation(String url, RequestInfo requestInfo, String eTag)
     throws IOException {
   this.originalRequest = requestInfo;
   DateTime requestTime = DateTime.now();
   connection = (HttpConnection) Connector.open(url);
   meta = new LiveGcfResponseInfo(connection, requestTime);
   connection.setRequestProperty(RequestHeaderName.IfNoneMatch.name(), eTag);
   is = connection.openInputStream();
 }
Esempio n. 19
0
  public void startApp() throws MIDletStateChangeException {
    System.out.println("Starting sensor gathering");
    BootloaderListenerService.getInstance()
        .start(); // monitor the USB (if connected) and recognize commands from host
    long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
    System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
    IAnalogInput sensor = EDemoBoard.getInstance().getAnalogInputs()[EDemoBoard.A4];

    DatagramConnection dgConnection = null;
    Datagram dg = null;
    try {
      // specify broadcast_port
      dgConnection = (DatagramConnection) Connector.open("radiogram://broadcast:" + BROADCAST_PORT);

      dg = dgConnection.newDatagram(50);
      System.out.println("Maxlength for Packet is : " + dgConnection.getMaximumLength());
    } catch (IOException ex) {
      System.out.println("Could not open radiogram broadcast connection");
      ex.printStackTrace();
      return;
    }
    int counter = 0;
    while (true) {
      try {

        // 9.8mV per inch
        double val = sensor.getVoltage();
        voltages[counter] = val;
        double sum = 0;
        for (int i = 0; i < voltages.length; i++) {
          sum += voltages[i];
        }
        System.out.println("Voltage average: " + sum / voltages.length);
        counter++;
        if (counter > 9) {
          counter = 0;
        }
        // System.out.println("Value in volts: "+ val);
        // double inches = val/0.0098;
        // System.out.println("Value in inches: "+ inches);
        // Write the string into the dataGram.
        // dg.reset();
        // dg.writeLong(ourAddr);
        // dg.writeDouble(val);

        // Send DataGram
        // dgConnection.send(dg);

        // Sleep for 200 milliseconds.
        Utils.sleep(50);
      } catch (IOException ex) {
        System.err.println("Caught " + ex + " while collecting/sending sensor sample.");
        ex.printStackTrace();
      }
    }
  }
  /**
   * Waits for file to be fully written to the file system before retrieving its file properties.
   *
   * @param filePath Full path of the image file
   * @throws IOException
   */
  private File getMediaFile(String filePath) {
    File file = new File(FileUtils.stripSeparator(filePath));

    // time begin waiting for file write
    long start = (new Date()).getTime();

    // wait for the file to be fully written, then grab its properties
    FileConnection fconn = null;
    try {
      fconn = (FileConnection) Connector.open(filePath, Connector.READ);
      if (fconn.exists()) {
        // wait for file to be fully written
        long fileSize = fconn.fileSize();
        long size = 0;
        Thread thisThread = Thread.currentThread();
        while (myThread == thisThread) {
          try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            break;
          }
          size = fconn.fileSize();
          if (fileSize != 0 && size == fileSize) {
            break;
          }
          fileSize = size;
        }
        Logger.log(
            this.getClass().getName()
                + ": "
                + filePath
                + " size="
                + Long.toString(fileSize)
                + " bytes");

        // retrieve file properties
        file.setLastModifiedDate(fconn.lastModified());
        file.setName(FileUtils.stripSeparator(fconn.getName()));
        file.setSize(fileSize);
        file.setType(MIMETypeAssociations.getMIMEType(filePath));
      }
    } catch (IOException e) {
      Logger.log(this.getClass().getName() + ": " + e);
    } finally {
      try {
        if (fconn != null) fconn.close();
      } catch (IOException ignored) {
      }
    }

    // log time it took to write the file
    long end = (new Date()).getTime();
    Logger.log(this.getClass().getName() + ": wait time=" + Long.toString(end - start) + " ms");

    return file;
  }
 private void startListener() {
   try {
     if (scn != null) scn.close();
     // <i><b>listen to requests on port 5060</b></i>
     scn = (SipConnectionNotifier) Connector.open("sip:5080");
     scn.setListener(this);
   } catch (IOException ex) {
     // <i><b>handle IOException</b></i>
   }
 }
Esempio n. 22
0
 public RfcommServer() throws IOException {
   // RFCOMMベースのサーバの開始。
   // - btspp:は PRCOMM 用なのでベースプロトコルによって変わる。
   server =
       (StreamConnectionNotifier)
           Connector.open("btspp://localhost:" + serverUUID, Connector.READ_WRITE, true);
   // ローカルデバイスにサービスを登録。必須ではない。
   ServiceRecord record = LocalDevice.getLocalDevice().getRecord(server);
   LocalDevice.getLocalDevice().updateRecord(record);
 }
Esempio n. 23
0
 /**
  * Este metodo recoje los datos para almacenar los puntajes
  *
  * @return
  * @throws IOException
  */
 public String lecturaScores() throws IOException {
   this.archivos = (FileConnection) Connector.open(archivoScores, Connector.READ_WRITE);
   this.scanner = archivos.openInputStream();
   data = new byte[512];
   scanner.read(data);
   scanner.close();
   archivos.close();
   String score = new String(data);
   return score;
 }
Esempio n. 24
0
 /**
  * Este metodo contiene los daots guardados
  *
  * @return
  * @throws IOException
  */
 public String lecturaSalvado() throws IOException {
   this.archivos1 = (FileConnection) Connector.open(archivoSalvado, Connector.READ_WRITE);
   this.scanner1 = archivos1.openInputStream();
   data1 = new byte[512];
   scanner1.read(data1);
   scanner1.close();
   archivos1.close();
   String score = new String(data1);
   return score;
 }
Esempio n. 25
0
  /**
   * Opens the specified file and prepares it for reading data from.
   *
   * @param sFileName
   */
  public FileReader(String sFileName) {
    m_sFile = sFileName;

    try {
      m_fc = (FileConnection) Connector.open(m_sFile, Connector.READ);
      m_reader = new DataInputStream(m_fc.openInputStream());
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
Esempio n. 26
0
 /*     */ public synchronized void saveToDisk() /*     */ {
   /* 106 */ if (this._dirty)
   /*     */ {
     /* 109 */ FileConnection fileC = null;
     /* 110 */ OutputStream os = null;
     /* 111 */ DataOutputStream dOS = null;
     /*     */ try
     /*     */ {
       /* 114 */ String filename = getPath() + "WA_Favorites";
       /* 115 */ Utilities.logData("trying to open favs for write " + filename);
       /* 116 */ fileC = (FileConnection) Connector.open(filename, 3);
       /* 117 */ if (!fileC.exists()) {
         /* 118 */ fileC.create();
         /*     */ }
       /* 120 */ os = fileC.openOutputStream(0L);
       /* 121 */ dOS = new DataOutputStream(os);
       /*     */
       /* 124 */ for (int i = 0; i < this._favoritesList.size(); i++) {
         /* 125 */ String curJid = (String) this._favoritesList.elementAt(i);
         /* 126 */ dOS.writeUTF(curJid);
         /* 127 */ dOS.writeInt(1);
         /*     */ }
       /* 129 */ for (int i = 0; i < this._blackballList.size(); i++) {
         /* 130 */ String curJid = (String) this._blackballList.elementAt(i);
         /* 131 */ dOS.writeUTF(curJid);
         /* 132 */ dOS.writeInt(2);
         /*     */ }
       /* 134 */ dOS.flush();
       /* 135 */ this._dirty = false;
       /*     */ } catch (Throwable x) {
       /* 137 */ Utilities.logData("favorites save blew up with " + t.toString());
       /*     */ } finally {
       /* 139 */ if (dOS != null)
         /*     */ try {
           /* 141 */ dOS.close();
           /*     */ }
         /*     */ catch (Exception x) {
           /*     */ }
       /* 145 */ if (os != null)
         /*     */ try {
           /* 147 */ os.close();
           /*     */ }
         /*     */ catch (Exception x) {
           /*     */ }
       /* 151 */ if (fileC != null)
         /*     */ try {
           /* 153 */ fileC.close();
           /*     */ }
         /*     */ catch (Exception x)
         /*     */ {
           /*     */ }
       /*     */ }
     /*     */ }
   /*     */ }
Esempio n. 27
0
 /**
  * This method will open a filtered Http Connection.
  *
  * @see net.rim.device.api.io.FilterBaseInterface#openFilter(String, int, boolean)
  */
 public Connection openFilter(String name, int mode, boolean timeouts) throws IOException {
   try {
     final Request request = new Request(name);
     log.debug("Intercept krypsis request: " + name);
     final Response response = dispatchRequest(request);
     return response == null ? null : new KrypsisConnection(response, Main.HOST);
   } catch (RequestException e) {
     log.debug("Not a crypsis request. Pass it to the network");
     return Connector.open("http:" + name + ";usefilter=false", mode, timeouts);
   }
 }
Esempio n. 28
0
 public SimulatedNorFlashSector(String fileName) throws IOException {
   this.fileName = fileName;
   DataInputStream input = Connector.openDataInputStream("file://" + fileName);
   Address startAddress = Address.fromPrimitive(input.readInt());
   int size = input.readInt();
   int purpose = input.readShort();
   init(startAddress, size, purpose);
   bytes = new byte[input.available()];
   input.read(bytes, 0, bytes.length);
   input.close();
 }
Esempio n. 29
0
  public boolean sendEventSync(final Event event) {
    boolean succesfull = false;
    if (EchoProtocolManager.getInstance().getMyStation().isActive()) {
      try {
        // Creates a broadcast Datagram Connection
        dgConnection =
            (DatagramConnection)
                Connector.open(
                    "radiogram://"
                        + EchoProtocolManager.getInstance().getMyStation().getAddress().longValue()
                        + ":"
                        + DTSPORT);

        // Creates a Datagram using the above Connection
        final Datagram datagram = dgConnection.newDatagram(dgConnection.getMaximumLength());

        // Clean the Datagram
        datagram.reset();

        // Convert event to byte Array
        final byte[] eventArray = event.toByteArray();

        // Send Class Type
        datagram.writeUTF(event.getClass().getName());

        // Send length
        datagram.writeInt(eventArray.length);

        // Send array
        datagram.write(eventArray, 0, eventArray.length);

        // Send the datagram
        dgConnection.send(datagram);

        dgConnection.close();

        Logger.getInstance().debug("Event sent succefully");
        succesfull = true;

      } catch (Exception ex) {
        Logger.getInstance().debug("Unable to send event", ex);

        // Close the open connection
        try {
          dgConnection.close();
        } catch (Exception e) {
          // eat it
        }

        succesfull = false;
      }
    }
    return succesfull;
  }
Esempio n. 30
0
 public void execute() {
   String initDir = "file:///cv/";
   loadRoots();
   System.out.println("Init dir is NOT null.");
   try {
     currentRoot = (FileConnection) Connector.open(initDir, Connector.READ);
     displayCurrentRoot();
   } catch (IOException e) {
     System.out.println("Init dir is NOT null but EXCEPTION is thrown.");
     displayAllRoots();
   }
 }