예제 #1
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 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);
  }
예제 #3
0
파일: Menu.java 프로젝트: 6xhhs/biolipsis
 /**
  * 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;
 }
예제 #4
0
파일: Menu.java 프로젝트: 6xhhs/biolipsis
 /**
  * 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;
 }
예제 #5
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)
         /*     */ {
           /*     */ }
       /*     */ }
     /*     */ }
   /*     */ }
  public String ReadLocalFile() throws IOException {
    FileConnection fc = null;
    InputStream is = null;
    StringBuffer sb = new StringBuffer();

    try {
      // String local_code = ReadLocalCode("expe");
      String local_code = "201102";
      String url = sFileSchema + sFSRoot + sLocalExpePrefix + local_code + sLocalDataExt;
      fc = (FileConnection) Connector.open(url, Connector.READ);
      if (fc == null) {
        SetMessages("[!] ERROR: fc == null.");
        System.out.println(GetMessages());
        return null;
      }
      if (!fc.exists()) {
        SetMessages("[!] ERROR: !fc.exists().");
        System.out.println(GetMessages());
        return null;
      }

      is = fc.openInputStream();
      int ch;
      while ((ch = is.read()) != -1) {
        sb.append((char) ch);
      }

      // System.out.println(sb.toString());
    } catch (ConnectionNotFoundException cnfex) {
      SetMessages(cnfex.toString());
      cnfex.printStackTrace();
    } catch (IOException ioex) {
      SetMessages(ioex.toString());
      ioex.printStackTrace();
    } catch (Exception ex) {
      SetMessages(ex.toString());
      ex.printStackTrace();
    } finally {
      if (is != null) {
        is.close();
      }

      if (fc != null) {
        fc.close();
      }
    }

    return sb.toString();
  }
  public String ReadOutputFile() throws IOException {
    FileConnection fc = null;
    InputStream is = null;
    StringBuffer sb = new StringBuffer();

    try {
      String url = sFileSchema + sFSRoot + sLocalOutputPrefix + "201101" + sOutputExt;
      fc = (FileConnection) Connector.open(url, Connector.READ_WRITE);
      if (fc == null) {
        SetMessages("[!] ERROR: fc == null.");
        System.out.println(GetMessages());
        return null;
      }
      if (!fc.exists()) {
        // SetMessages("[!] ERROR: !fc.exists().");
        // System.out.println(GetMessages());
        fc.create();
        return "";
      }

      is = fc.openInputStream();
      int ch;
      while ((ch = is.read()) != -1) {
        sb.append((char) ch);
      }
    } catch (ConnectionNotFoundException cnfex) {
      SetMessages(cnfex.toString());
      cnfex.printStackTrace();
    } catch (IOException ioex) {
      SetMessages(ioex.toString());
      ioex.printStackTrace();
    } catch (Exception ex) {
      SetMessages(ex.toString());
      ex.printStackTrace();
    } finally {
      if (is != null) {
        is.close();
      }

      if (fc != null) {
        fc.close();
      }
    }

    return sb.toString();
  }
예제 #8
0
 public void stop() {
   if (currentRoot != null) {
     try {
       currentRoot.close();
     } catch (IOException e) {
     }
   }
 }
  public Enumeration GetEnumRootList(String deviceDir) {
    FileConnection fc = null;
    InputStream is = null;
    Enumeration enumTraverse = null;

    try {
      fc = (FileConnection) Connector.open(sFileSchema + deviceDir);

      if (fc == null) {
        SetMessages("[!] ERROR: fc == null.");
        System.out.println(GetMessages());
        return null;
      }
      if (!fc.exists()) {
        SetMessages("[!] ERROR: !fc.exists().");
        System.out.println(GetMessages());
        return null;
      }

      enumTraverse = fc.list();
    } catch (IOException ioex) {
      SetMessages(ioex.toString());
      ioex.printStackTrace();
    } catch (Exception ex) {
      SetMessages(ex.toString());
      ex.printStackTrace();
    } finally {
      try {
        if (is != null) {
          is.close();
        }

        if (fc != null) {
          fc.close();
        }
      } catch (IOException ioex) {
        SetMessages(ioex.toString());
        ioex.printStackTrace();
      } catch (Exception ex) {
        SetMessages(ex.toString());
        ex.printStackTrace();
      }
    }

    return enumTraverse;
  }
예제 #10
0
 private void displayCurrentRoot() {
   try {
     setTitle(currentRoot.getURL());
     deleteAll();
     append(UPPER_DIR, null);
     Enumeration listOfDirs = currentRoot.list("*", false);
     while (listOfDirs.hasMoreElements()) {
       String currentDir = (String) listOfDirs.nextElement();
       if (currentDir.endsWith(FILE_SEPARATOR)) {
         append(currentDir, null);
       } else {
         append(currentDir, null);
       }
     }
   } catch (IOException e) {
   } catch (SecurityException e) {
   }
 }
  /**
   * 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;
  }
예제 #12
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());
      }
    }
  }
  /**
   * Gets the image given a path Source: {@link
   * http://supportforums.blackberry.com/t5/Java-Development/How-to-read-display-image-from-SD-card-on-Device/m-p/621671#M129277}
   */
  public Bitmap getImage(String path) {
    StringBuffer sb = new StringBuffer(1024);
    sb.append("file:///SDCard/").append(path);
    String filename = sb.toString();
    sb = null;
    Bitmap image = null;

    FileConnection fc = null;
    InputStream input = null;
    try {
      fc = (FileConnection) Connector.open(filename, Connector.READ_WRITE);
      if (fc.exists()) {
        input = fc.openInputStream();
        byte[] data = new byte[(int) fc.fileSize()];
        input.read(data);
        image = Bitmap.createBitmapFromPNG(data, 0, data.length);
      }
    } catch (Exception e) {
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (IOException e) {
        }
      }
      if (fc != null) {
        try {
          fc.close();
        } catch (Exception e) {
        }
      }
    }

    if (image == null) {
      return getImage(DEFAULT_IMAGE); // TODO: possible recursive loop
    }
    return image;
  }
예제 #14
0
  /**
   * This method reads from a text file and returns its contents
   *
   * @param fName Name of the file
   * @return returns the contents of the file if the file is found; null otherwise
   */
  public String readTextFile(String fName) {
    String result = null;
    FileConnection fconn = null;
    DataInputStream is = null;

    // read the file
    try {

      fconn = (FileConnection) Connector.open("file:///SDCard/BlackBerry/" + fName);
      is = fconn.openDataInputStream();
      byte[] data = IOUtilities.streamToBytes(is);
      result = new String(data);
      is
          .close(); // http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800563/How_To_-_Close_connections.html?nodeid=1261294&vernum=0
      fconn.close();

    } catch (Exception e) {

      System.out.println(e.getMessage());
    }

    return result; // return the file contents
  }
예제 #15
0
 private void openSelected() {
   int selectedIndex = getSelectedIndex();
   if (selectedIndex >= 0) {
     String selectedFile = getString(selectedIndex);
     if (selectedFile.endsWith(FILE_SEPARATOR)) {
       try {
         if (currentRoot == null) {
           currentRoot =
               (FileConnection) Connector.open("file:///" + selectedFile, Connector.READ);
         } else {
           currentRoot.setFileConnection(selectedFile);
         }
         displayCurrentRoot();
       } catch (IOException e) {
         System.out.println(e.getMessage());
       } catch (SecurityException e) {
         System.out.println(e.getMessage());
       }
     } else if (selectedFile.equals(UPPER_DIR)) {
       if (rootsList.contains(currentRoot.getPath() + currentRoot.getName())) {
         displayAllRoots();
       } else {
         try {
           currentRoot =
               (FileConnection) Connector.open("file://" + currentRoot.getPath(), Connector.READ);
           displayCurrentRoot();
         } catch (IOException e) {
           System.out.println(e.getMessage());
         }
       }
     } else {
       String url = currentRoot.getURL() + selectedFile;
       heartDiagApp.setSelectedFile(url);
       heartDiagApp.displayAndCalculate();
     }
   }
 }
  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];
  }
예제 #17
0
  private static boolean LoadWeiboImage(WeiboHeadImage _image) {

    String t_imageFilename = null;

    try {

      if (!sm_mainApp.isSDCardAvailable(false)) {
        return true;
      }

      if (fsm_largeHeadImage) {
        if (_image.m_isWeiboOrIM) {
          t_imageFilename =
              sm_mainApp.GetWeiboHeadImageDir(_image.m_weiboStyle) + _image.m_userID + "_l.png";
        } else {
          t_imageFilename =
              sm_mainApp.GetIMHeadImageDir(_image.m_weiboStyle) + _image.m_userID + "_l.png";
        }

      } else {
        if (_image.m_isWeiboOrIM) {
          t_imageFilename =
              sm_mainApp.GetWeiboHeadImageDir(_image.m_weiboStyle) + _image.m_userID + ".png";
        } else {
          t_imageFilename =
              sm_mainApp.GetIMHeadImageDir(_image.m_weiboStyle) + _image.m_userID + ".png";
        }
      }

      FileConnection t_fc = (FileConnection) Connector.open(t_imageFilename, Connector.READ_WRITE);
      try {
        if (t_fc.exists()) {
          InputStream t_fileIn = t_fc.openInputStream();
          try {

            byte[] t_data = new byte[(int) t_fc.fileSize()];
            sendReceive.ForceReadByte(t_fileIn, t_data, t_data.length);

            _image.m_headImage =
                EncodedImage.createEncodedImage(t_data, 0, t_data.length).getBitmap();
            _image.m_dataHash = t_data.length;

          } finally {
            t_fileIn.close();
            t_fileIn = null;
          }

          return true;
        }

      } finally {
        t_fc.close();
        t_fc = null;
      }
    } catch (Exception e) {
      debugOutput("LWI:" + t_imageFilename);
      exceptionOutput("LWI1", e);
    }

    return false;
  }
예제 #18
0
  private boolean getRootContent(String rootDir) {
    // #if polish.api.pdaapi
    try {
      // #debug debug
      logger.debug("List of files and directories under " + rootDir + ":");
      FileConnection fc = (FileConnection) Connector.open(rootDir, Connector.READ);
      // Get a filtered list of all files and directories.
      // True means: include hidden files.
      // To list just visible files and directories, use
      // list() with no arguments.
      if (!fc.exists()) {
        url = "file:///";
        return false;
      }
      if (!fc.isDirectory()) {
        // If it is not a directory,
        // Then we assume it must be an
        // Ok selection
        selectEntry();
        return true;
      }

      list = createEmptyList();
      urlList.removeAllElements();
      list.append(".", null);
      urlList.addElement(url);
      list.append("..", null);
      // urlList.addElement(url + "Directory Up");
      urlList.addElement(url);
      String fileName;
      String suffix;
      // #if polish.android
      // workaround for J2MEPolish 2.3 bug, jkpj 2012-03-15
      Enumeration filelist = fc.list("*", false);
      // #else
      Enumeration filelist = fc.list();
      // #endif
      while (filelist.hasMoreElements()) {
        fileName = (String) filelist.nextElement();
        // #debug debug
        logger.debug("found file: " + fileName);
        // add files too if not choose dir only
        // #if polish.android
        // was workaround for J2MEPolish before 2.3
        // FileConnection fc2 = (FileConnection) Connector.open(url + fileName);
        // if (fc2.isDirectory()) {
        //	fileName += "/";
        //	fc2.close();
        // }
        // #endif

        // only add entries matching the criteria
        boolean matching = false;
        if (fileName.endsWith("/")) {
          matching = true;
        } else if (chooseType != CHOOSE_DIRONLY) {
          // when there's no suffix to check for, each file is matching
          if (suffixes == null) {
            matching = true;
            // otherwise check if one of the ;-separated suffixes matches
          } else {
            for (int i = 0; i < suffixes.size(); i++) {
              suffix = (String) suffixes.elementAt(i);
              if (fileName.toLowerCase().endsWith(suffix.toLowerCase())) {
                matching = true;
              }
            }
          }
        }

        // insert matching entries in the appropriate list at the right index to have them sorted
        if (matching) {
          // System.out.println("Adding " + fileName);
          if (fileName.endsWith("/")) {
            dirs.insertElementAt(fileName, getSortIdx(dirs, fileName));
          } else {
            files.insertElementAt(fileName, getSortIdx(files, fileName));
          }
        }
      }

      // add sorted directory names to list and urlList
      for (int i = 0; i < dirs.size(); i++) {
        fileName = (String) dirs.elementAt(i);
        list.append(fileName, null);
        urlList.addElement(url + fileName);
      }
      dirs.removeAllElements();
      // add sorted filenames to list and urlList
      for (int i = 0; i < files.size(); i++) {
        fileName = (String) files.elementAt(i);
        list.append(fileName, null);
        urlList.addElement(url + fileName);
      }
      files.removeAllElements();

      fc.close();
      show();
    } catch (IOException ioe) {
      logger.error(ioe.getMessage());
    } catch (SecurityException e) {
      logger.error(e.getMessage());
    }
    // #endif
    return true;
  }
예제 #19
0
 /*     */ public synchronized boolean initialize() {
   /*  42 */ FileConnection fileC = null;
   /*  43 */ InputStream is = null;
   /*  44 */ DataInputStream dIS = null;
   /*     */
   /*  46 */ this._favoritesList.removeAllElements();
   /*  47 */ this._blackballList.removeAllElements();
   /*  48 */ this._favoritesTable.clear();
   /*  49 */ this._dirty = false;
   /*     */ try {
     /*  51 */ String filename = getPath() + "WA_Favorites";
     /*  52 */ fileC = (FileConnection) Connector.open(filename, 1);
     /*  53 */ if (!fileC.exists()) {
       /*  54 */ int i = 1;
       /*     */ return i;
       /*     */ }
     /*  56 */ is = fileC.openInputStream();
     /*  57 */ dIS = new DataInputStream(is);
     /*     */ try
     /*     */ {
       /*     */ while (true) {
         /*  61 */ String newJid = dIS.readUTF();
         /*  62 */ int newVal = dIS.readInt();
         /*  63 */ if ((newVal == 1) || (newVal == 2)) {
           /*  64 */ this._favoritesTable.put(newJid, new Integer(newVal));
           /*  65 */ if (newVal == 1) /*  66 */ this._favoritesList.addElement(newJid);
           /*  67 */ else if (newVal == 2) /*  68 */ this._blackballList.addElement(newJid);
           /*     */ }
         /*     */ else {
           /*  71 */ Utilities.logData(
               "stored Favorites jid " + newJid + " found with unknown val " + newVal);
           /*     */ }
         /*     */
         /*     */ }
       /*     */
       /*     */ }
     /*     */ catch (EOFException j)
     /*     */ {
       /*  79 */ j = 1;
       /*     */
       /*  84 */ if (dIS != null)
         /*     */ try {
           /*  86 */ dIS.close();
           /*     */ }
         /*     */ catch (Exception x) {
           /*     */ }
       /*  90 */ if (is != null)
         /*     */ try {
           /*  92 */ is.close();
           /*     */ }
         /*     */ catch (Exception x) {
           /*     */ }
       /*  96 */ if (fileC != null)
         /*     */ try {
           /*  98 */ fileC.close();
         } catch (Exception x) {
           /*     */ }
       /* 100 */ return j;
       /*     */ }
     /*     */ }
   /*     */ catch (Throwable t)
   /*     */ {
     /*  81 */ Utilities.logData("favs init blew up with " + t.toString());
     /*  82 */ int j = 0;
     /*     */ return j;
     /*     */ }
   /*     */ finally
   /*     */ {
     /*  84 */ if (dIS != null)
       /*     */ try {
         /*  86 */ dIS.close();
         /*     */ }
       /*     */ catch (Exception x) {
         /*     */ }
     /*  90 */ if (is != null)
       /*     */ try {
         /*  92 */ is.close();
         /*     */ }
       /*     */ catch (Exception x) {
         /*     */ }
     /*  96 */ if (fileC != null)
       /*     */ try {
         /*  98 */ fileC.close();
       } catch (Exception x) {
         /*     */ }
     /*     */ }
   /* 100 */ throw localObject;
   /*     */ }
  public void run_0420() {
    FileConnection conn1 = null;
    int counter = 0;
    try {
      // Make a connection to the new file.
      conn1 =
          (FileConnection)
              Connector.open(
                  "file:///" + iRoot + "mainTestDir/test040/new042File.txt", Connector.READ_WRITE);
      counter = 1;
      System.out.println(" run_0420: counter = 1 ");
      if (conn1.exists()) throw new TestFailedException();
      counter = 2;
      System.out.println(" run_0420: counter = 2 ");
      conn1.create();
      counter = 3;
      System.out.println(" run_0420: counter = 3 ");
      OutputStream stream = conn1.openOutputStream();
      counter = 4;
      System.out.println(" run_0420: counter = 4 ");
      byte[] byteArray1 = new byte[50];
      for (int i = 0; i < byteArray1.length; ++i) byteArray1[i] = 55;
      counter = 5;
      System.out.println(" run_0420: counter = 5 ");
      stream.write(byteArray1);
      stream.close();
      counter = 6;
      System.out.println(" run_0420: counter = 6 ");
      // Re-open an OutputStream.
      stream = conn1.openOutputStream(conn1.fileSize());
      counter = 7;
      System.out.println(" run_0420: counter = 7 ");
      for (int i = 0; i < byteArray1.length; ++i) byteArray1[i] = 56;
      conn1.close();
      counter = 8;
      stream.write(byteArray1);
      counter = 9;
      stream.close();

      System.out.println(" Going to second part of run_0420");

      // Re-open a connection.
      conn1 =
          (FileConnection)
              Connector.open(
                  "file:///" + iRoot + "mainTestDir/test040/new042File.txt", Connector.READ_WRITE);
      counter = 10;
      System.out.println(" run_0420: counter = 10 ");
      if (!conn1.exists()) throw new TestFailedException();
      counter = 11;
      System.out.println(" run_0420: counter = 11 ");
      InputStream inStream = conn1.openInputStream();
      counter = 12;
      System.out.println(" run_0420: counter = 12 ");
      byte[] byteArray2 = new byte[110];
      int retValue = inStream.read(byteArray2);
      if (retValue != 100) throw new TestFailedException("retValue: " + retValue);
      counter = 13;
      System.out.println(" run_0420: counter = 13 ");
      for (int i = 0; i < retValue; ++i) {
        if (i < 50) {
          if (byteArray2[i] != 55)
            throw new TestFailedException("i: " + i + " byteArray2[i]: " + byteArray2[i]);
        } else if (i > 49) {
          if (byteArray2[i] != 56)
            throw new TestFailedException("i: " + i + " byteArray2[i]: " + byteArray2[i]);
        }
      } // end for
      counter = 14;
      conn1.close();
      inStream.close();

      assertTrue(" run_0420() ok ", true);
    } catch (Exception ex) {
      append(ex.toString());
      append("TEST FAILED!!! Case: run_0420() counter: " + counter + "\n");
      assertTrue(" run_0420() FAILED!!! Counter: " + counter, false);
    }
  } // end run_0420()
  public void run_1720() {
    FileConnection conn1 = null;
    int counter = 0;
    try {
      // 1 Opening a file.
      conn1 =
          (FileConnection)
              Connector.open(
                  "file:///" + iRoot + "mainTestDir/test170/readOnly.txt", Connector.READ_WRITE);
      counter = 1;
      InputStream stream = conn1.openInputStream();
      counter = 3;
      byte[] byteArray1 = new byte[500];
      int retValue = stream.read(byteArray1);
      counter = 4;
      if (retValue != 500) throw new TestFailedException("retValue: " + retValue);
      counter = 5;
      for (int i = 0; i < retValue; ++i) {
        if (byteArray1[i] != 56)
          throw new TestFailedException("byteArray1[i]: " + byteArray1[i] + "i: " + i);
      }
      conn1.setHidden(true);
      conn1.setHidden(true);
      counter = 6;
      boolean hiddenFlag = conn1.isHidden();
      if (hiddenFlag == false) throw new TestFailedException();
      counter = 7;
      try {
        stream.read(byteArray1);
        throw new TestFailedException();
      } catch (IOException ex) {
      }

      // Re-opening a InputStream.
      stream = conn1.openInputStream();
      counter = 71;
      byte[] byteArray12 = new byte[1601];
      retValue = stream.read(byteArray12);
      counter = 72;
      if (retValue != 1600) throw new TestFailedException("retValue: " + retValue);
      counter = 73;
      for (int i = 0; i < retValue; ++i) {
        if (byteArray12[i] != 56)
          throw new TestFailedException("byteArray12[i]: " + byteArray12[i] + "i: " + i);
      }
      stream.close();
      conn1.close();

      // 2 Re-open a file.
      conn1 =
          (FileConnection)
              Connector.open(
                  "file:///" + iRoot + "mainTestDir/test170/readOnly.txt", Connector.READ_WRITE);
      counter = 8;
      stream = conn1.openInputStream();
      counter = 9;
      byteArray1 = new byte[500];
      retValue = stream.read(byteArray1);
      counter = 10;
      if (retValue != 500) throw new TestFailedException("retValue: " + retValue);
      counter = 11;
      for (int i = 0; i < retValue; ++i) {
        if (byteArray1[i] != 56)
          throw new TestFailedException("byteArray1[i]: " + byteArray1[i] + "i: " + i);
      }
      counter = 12;
      conn1.setHidden(true);
      byte[] byteArray2 = new byte[1200];
      retValue = stream.read(byteArray2);
      counter = 13;
      if (retValue != 1100) throw new TestFailedException("retValue: " + retValue);
      counter = 14;
      for (int i = 0; i < retValue; ++i) {
        if (byteArray2[i] != 56)
          throw new TestFailedException("byteArray2[i]: " + byteArray2[i] + "i: " + i);
      }
      stream.close();
      conn1.close();

      // 3 Re-open a file.
      conn1 =
          (FileConnection)
              Connector.open(
                  "file:///" + iRoot + "mainTestDir/test170/readOnly.txt", Connector.READ_WRITE);
      stream = conn1.openInputStream();
      counter = 15;
      byteArray1 = new byte[500];
      retValue = stream.read(byteArray1);
      counter = 16;
      if (retValue != 500) throw new TestFailedException("retValue: " + retValue);
      counter = 17;
      for (int i = 0; i < retValue; ++i) {
        if (byteArray1[i] != 56)
          throw new TestFailedException("byteArray1[i]: " + byteArray1[i] + "i: " + i);
      }
      counter = 18;
      System.out.println(" Test 1720: COunter 8");
      conn1.setHidden(false);
      hiddenFlag = conn1.isHidden();
      if (hiddenFlag == true) throw new TestFailedException();
      counter = 19;
      try {
        stream.read(byteArray1);
        throw new TestFailedException();
      } catch (IOException ex) {
      }
      stream.close();
      conn1.close();

      assertTrue(" run_1720() ok ", true);
    } catch (Exception ex) {
      append(ex.toString());
      append("TEST FAILED!!! Case: run_1720() counter: " + counter + "\n");
      assertTrue(" run_1720() FAILED!!! Counter: " + counter, false);
    }
  }
예제 #22
0
  public void filter16to32(short[] inPixels, int[] outPixels) {

    int srcWidth = width;
    int srcHeight = height;
    int srcWidth1 = width - 1;
    int srcHeight1 = height - 1;
    int outWidth = srcWidth;
    int outHeight = srcHeight;
    int outX, outY;
    int index = 0;
    // int[] outTempPixels = new int[outWidth];
    int outpix = 0;
    // enable cache
    if (enablecache) {
      if (cacheStream == null) {
        // if(Runtime.getRuntime().freeMemory()>(mCacheW*mCacheH*8))
        {
          cacheStream = openPreCacheResource(cachefilename);
        }
      }
    }

    // creaet cache
    FileConnection con = null;
    OutputStream os = null;
    if (precache) {
      String filename = System.currentTimeMillis() + "filter" + outWidth + "x" + outHeight + ".wrp";
      try {
        con = (FileConnection) Connector.open(System.getProperty("fileconn.dir.photos") + filename);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      if (con != null) {
        if (con.exists()) {
          try {
            con.delete();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        try {
          con.create();
          os = con.openOutputStream();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }

    outX = 0;
    outY = 0;
    float[] out = new float[2];
    mProgress = 0;

    for (int y = 0; y < outHeight; y++) {
      for (int x = 0; x < outWidth; x++) {
        if (cacheStream != null) {
          cacheTable((outX + x), (outY + y), out);
        }
        int srcX = (int) Math.floor(out[0]);
        int srcY = (int) Math.floor(out[1]);
        float xWeight = out[0] - srcX;
        float yWeight = out[1] - srcY;
        if (precache) {
          /*
           * try { os.write(float2Byte(out[0]));
           * os.write(float2Byte(out[1])); } catch (IOException e) {
           * // TODO Auto-generated catch block e.printStackTrace(); }
           */
          if (preCacheData == null) {
            int cacheSize = mCacheW * mCacheH * 2;
            preCacheData = new float[cacheSize];
          }
          int c = cacheMaping(x, y);
          preCacheData[c * 2] = out[0];
          preCacheData[c * 2 + 1] = out[1];
        }
        // System.out.println(out[0]+","+out[1]);
        short nw, ne, sw, se;

        if (srcX >= 0 && srcX < srcWidth1 && srcY >= 0 && srcY < srcHeight1) {
          // Easy case, all corners are in the image
          int i = srcWidth * srcY + srcX;
          nw = inPixels[i];
          ne = inPixels[i + 1];
          sw = inPixels[i + srcWidth];
          se = inPixels[i + srcWidth + 1];
        } else {
          // Some of the corners are off the image
          nw = getPixel16(inPixels, srcX, srcY, srcWidth, srcHeight);
          ne = getPixel16(inPixels, srcX + 1, srcY, srcWidth, srcHeight);
          sw = getPixel16(inPixels, srcX, srcY + 1, srcWidth, srcHeight);
          se = getPixel16(inPixels, srcX + 1, srcY + 1, srcWidth, srcHeight);
        }
        outpix = (outY + y) * width + (outX + x);
        outPixels[outpix] = bilinearInterpolate16to32(xWeight, yWeight, nw, ne, sw, se);
        // outTempPixels[x] = bilinearInterpolate(xWeight,yWeight, nw,
        // ne, sw, se);
      }
      // setRGB( dst, 0, y, transformedSpace.width, 1, outPixels );
      // System.arraycopy(outTempPixels, 0, outPixels, (outY + y) * width,
      // outWidth);
      if (y > 20) mProgress = (int) (((y * 100) / outHeight));
    }

    if (precache) {
      for (int i = 0; i < (mCacheW * mCacheH * 2); i++) {
        try {
          os.write(float2Byte(preCacheData[i]));
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      try {
        if (os != null) {
          os.close();
        }
        if (con != null) {
          con.close();
        }
      } catch (IOException io) {
      }
    }
  }
예제 #23
0
  /**
   * Gets the connection attribute of the CommonDS object
   *
   * @exception IOException Description of the Exception
   */
  void getConnection() throws IOException {
    boolean goodurl = false;

    if (locator == null) {
      throw (new IOException(this + ": connect() failed"));
    }

    contentType = null;
    String fileName = getRemainder(locator);

    if (fileName == null) {
      throw new IOException("bad url");
    }
    int i = fileName.lastIndexOf((int) ('.'));
    if (i != -1) {
      String ext = fileName.substring(i + 1).toLowerCase();
      contentType = Configuration.getConfiguration().ext2Mime(ext);
    }

    if (contentType == null) {
      contentType = "unknown";
    }

    try {
      if (locator.toLowerCase().startsWith("http:")) {
        HttpConnection httpCon = (HttpConnection) Connector.open(locator);
        int rescode = httpCon.getResponseCode();
        // If the response code of HttpConnection is in the range of
        // 4XX and 5XX, that means the connection failed.
        if (rescode >= 400) {
          httpCon.close();
          goodurl = false;
        } else {
          inputStream = httpCon.openInputStream();
          contentLength = httpCon.getLength();
          String ct = httpCon.getType().toLowerCase();
          if (contentType.equals("unknown")) {
            contentType = Configuration.getConfiguration().ext2Mime(ct);
          }
          httpCon.close();
          goodurl = true;
        }
      } else if (locator.startsWith("file:")) {
        // #ifdef USE_FILE_CONNECTION [
        FileConnection fileCon = (FileConnection) Connector.open(locator);
        if (fileCon.exists() && !fileCon.isDirectory() && fileCon.canRead()) {
          inputStream = fileCon.openInputStream();
          contentLength = fileCon.fileSize();
          fileCon.close();
          goodurl = true;
        } else {
          fileCon.close();
          goodurl = false;
        }
        // #else ] [
        // throw new IOException("file protocol isn't supported");
        // #endif ]
      } else if (locator.startsWith("rtp:")) {
        if (contentType.equals("unknown")) contentType = "content.rtp";
        inputStream = null;
        contentLength = -1;
        goodurl = true;
      } else if (locator.startsWith("rtsp:")) {
        if (contentType.equals("unknown")) contentType = "content.rtp";
        inputStream = null;
        contentLength = -1;
        goodurl = true;
      } else if (locator.equals(Manager.TONE_DEVICE_LOCATOR)
      // #ifndef ABB [
      // || locator.equals(Manager.MIDI_DEVICE_LOCATOR)
      // #endif ]
      ) {
        inputStream = null;
        contentLength = -1;
        goodurl = true;
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new IOException("failed to connect: " + ex.getMessage());
    }

    if (!goodurl) throw new IOException("bad url");
  }
  public boolean WriteLocalFile(String sWriteData, String sFileURL) throws IOException {
    FileConnection fc = null;
    DataOutputStream dos = null;
    // OutputStream os = null;
    // PrintStream ps = null;

    try {
      // If exists already, first delete file, a little clumsy.
      // fc = (FileConnection) Connector.open(fileURL.toString(), Connector.READ_WRITE);
      // String url = sFileSchema + sFSRoot + "expeout_201101" + sFileExt;
      String url = sFileSchema + sFSRoot + sLocalOutputPrefix + "201102" + sOutputExt;
      // fc = (FileConnection) Connector.open(url, Connector.READ_WRITE);
      fc = (FileConnection) Connector.open(sFileURL, Connector.READ_WRITE);
      // fc = (FileConnection) Connector.open(url, Connector.WRITE);
      if (!fc.exists()) {
        fc.create();
      }

      fc.truncate(0);

      dos = new DataOutputStream(fc.openOutputStream());
      // dos.writeUTF(sWriteData);
      // dos.write("ABCDE".getBytes());
      dos.write(sWriteData.getBytes());
      // os = fc.openOutputStream(Long.MAX_VALUE);
      // os = fc.openOutputStream();
      // ps = new PrintStream(os);
      // ps.println(sWriteData);

      SetSuccess(true);
    } catch (ConnectionNotFoundException cnfex) {
      SetSuccess(false);
      SetMessages(cnfex.toString());
      cnfex.printStackTrace();
    } catch (IOException ioex) {
      SetSuccess(false);
      SetMessages(ioex.toString());
      ioex.printStackTrace();
    } catch (Exception ex) {
      SetSuccess(false);
      SetMessages(ex.toString());
      ex.printStackTrace();
    } finally {
      /*if (ps != null) {
          ps.flush();
          ps.close();
      }
      if (os != null) {
          os.flush();
          os.close();
      }*/
      if (dos != null) {
        dos.flush();
        dos.close();
      }
      if (fc != null) {
        fc.close();
      }
    }

    return GetSuccess();
  }