Ejemplo n.º 1
0
  // Function use to load all Records from File when Application Execute.
  void populateArray() {

    try {
      fis = new FileInputStream("Bank.dat");
      dis = new DataInputStream(fis);
      // Loop to Populate the Array.
      while (true) {
        for (int i = 0; i < 6; i++) {
          records[rows][i] = dis.readUTF();
        }
        rows++;
      }
    } catch (Exception ex) {
      total = rows;
      if (total == 0) {
        JOptionPane.showMessageDialog(
            null,
            "Records File is Empty.\nEnter Records First to Display.",
            "BankSystem - EmptyFile",
            JOptionPane.PLAIN_MESSAGE);
        btnEnable();
      } else {
        try {
          dis.close();
          fis.close();
        } catch (Exception exp) {
        }
      }
    }
  }
Ejemplo n.º 2
0
  public void openFile(String filename) {
    try {
      FileInputStream input = new FileInputStream(filename);
      char x;

      for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
          x = (char) input.read();

          if (x == 'P') {
            puzzleBox[i][j].setText(String.valueOf((char) input.read()));
            puzzleBox[i][j].setEnabled(false);
          } else {
            x = (char) input.read();

            if (x == 'X') {
              puzzleBox[i][j].setText("");
              puzzleBox[i][j].setEnabled(true);
            } else {
              puzzleBox[i][j].setText(String.valueOf(x));
              puzzleBox[i][j].setEnabled(true);
            }
          }
        }

        x = (char) input.read();
        x = (char) input.read();
      }

      input.close();
    } catch (IOException ioException) {
      JOptionPane.showMessageDialog(this, "Error Opening File", "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
Ejemplo n.º 3
0
  /**
   * Loads the bytes in a file.
   *
   * @param name the file name
   * @return an array with the bytes in the file
   */
  public byte[] loadBytes(String name) throws IOException {
    FileInputStream in = null;

    in = new FileInputStream(name);
    try {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      int ch;
      while ((ch = in.read()) != -1) buffer.write(ch);
      return buffer.toByteArray();
    } finally {
      in.close();
    }
  }
Ejemplo n.º 4
0
  /** Procedure to set value for the code-swap strings */
  void getCodeSwapString() {
    File inputFile = new File(fileStr1);
    FileInputStream input = null;
    try {
      input = new FileInputStream(inputFile);
    } catch (FileNotFoundException fe) {
      System.err.println(fileStr1 + " not found. " + fe);
      // System.exit(-1);;
    }
    byte bt[] = new byte[(int) inputFile.length()];
    try {
      input.read(bt);
      textStr1 = new String(bt);
      input.close();
    } catch (IOException ie) {
      System.err.println("Can't read from the input stream " + ie);
      // System.exit(-1);;
    }

    inputFile = new File(fileStr2);
    try {
      input = new FileInputStream(inputFile);
    } catch (FileNotFoundException fe) {
      System.err.println(fileStr2 + " not found. " + fe);
      // System.exit(-1);;
    }
    try {
      bt = new byte[(int) inputFile.length()];
      input.read(bt);
      textStr2 = new String(bt);
      input.close();
    } catch (IOException ie) {
      System.err.println("Can't read from the input stream " + ie);
      // System.exit(-1);;
    }
  }
Ejemplo n.º 5
0
  private void addFont(String fontKey, String fontName, float scale) {
    try {
      fontName = fontName.toLowerCase();

      FileInputStream stream = new FileInputStream("data/fonts/ttf/" + fontName + ".ttf");

      Font f = Font.createFont(Font.TRUETYPE_FONT, stream);
      f = f.deriveFont(scale);

      fonts.put(fontKey, f);
      stream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 6
0
 // read a jpeg file into a buffered image
 protected static Image loadJPG(String filename) {
   FileInputStream in = null;
   try {
     in = new FileInputStream(filename);
   } catch (java.io.FileNotFoundException io) {
     System.out.println("File Not Found");
   }
   JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
   BufferedImage bi = null;
   try {
     bi = decoder.decodeAsBufferedImage();
     in.close();
   } catch (java.io.IOException io) {
     System.out.println("IOException");
   }
   return bi;
 }
Ejemplo n.º 7
0
 public static void convertCangjie() {
   try {
     int totalCangjieColumn = 6;
     FileInputStream fis = new FileInputStream("../../res/raw/cj");
     InputStreamReader input = new InputStreamReader(fis, "UTF-8");
     BufferedReader reader = new BufferedReader(input);
     String str = null;
     int index = 0;
     int total = 0;
     char column[] = new char[5];
     System.out.println("#define CANGJIE_COLUMN " + totalCangjieColumn);
     System.out.println("const jchar cangjie[][CANGJIE_COLUMN] = {");
     do {
       str = reader.readLine();
       if (str == null) break;
       index = str.indexOf('\t');
       if (index < 0) index = str.indexOf(' ');
       if (index > 0) {
         System.out.print("\t { ");
         for (int count = 0; count < 5; count++) {
           if (count < index) {
             column[count] = str.charAt(count);
             if (column[count] < 'a' || column[count] > 'z') column[count] = 0;
             if (((int) column[count]) >= 10 || ((int) column[count]) <= 99) System.out.print(' ');
             if (((int) column[count]) <= 9) System.out.print(' ');
             System.out.print(((int) column[count]));
           } else {
             System.out.print("  0");
           }
           System.out.print(", ");
         }
         System.out.println((int) str.charAt(index + 1) + " }, ");
         total++;
       }
     } while (str != null);
     System.out.println("};");
     System.out.println("jint cangjie_index[" + total + "];");
     System.out.println("jint cangjie_frequency[" + total + "];");
     reader.close();
     input.close();
     fis.close();
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  private AsmCodeGenerator initCodeGenerator(
      final String formFileName, final String className, final String testDataPath)
      throws Exception {
    String tmpPath = FileUtil.getTempDirectory();
    String formPath = testDataPath + formFileName;
    String javaPath = testDataPath + className + ".java";
    final int rc = Main.compile(new String[] {"-d", tmpPath, javaPath});

    assertEquals(0, rc);

    final String classPath = tmpPath + "/" + className + ".class";
    final File classFile = new File(classPath);

    assertTrue(classFile.exists());

    final LwRootContainer rootContainer = loadFormData(formPath);
    final AsmCodeGenerator codeGenerator =
        new AsmCodeGenerator(
            rootContainer,
            myClassFinder,
            myNestedFormLoader,
            false,
            new ClassWriter(ClassWriter.COMPUTE_FRAMES));
    final FileInputStream classStream = new FileInputStream(classFile);
    try {
      codeGenerator.patchClass(classStream);
    } finally {
      classStream.close();
      FileUtil.delete(classFile);
      final File[] inners =
          new File(tmpPath)
              .listFiles(
                  new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                      return name.startsWith(className + "$") && name.endsWith(".class");
                    }
                  });
      if (inners != null) {
        for (File file : inners) FileUtil.delete(file);
      }
    }
    return codeGenerator;
  }
Ejemplo n.º 9
0
 public static void zipDirectory(File directory, File base, ZipOutputStream zos)
     throws IOException {
   File[] files = directory.listFiles();
   byte[] buffer = new byte[8192];
   int read = 0;
   for (int i = 0, n = files.length; i < n; i++) {
     if (files[i].isDirectory()) {
       zipDirectory(files[i], base, zos);
     } else {
       FileInputStream in = new FileInputStream(files[i]);
       ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
       zos.putNextEntry(entry);
       while (-1 != (read = in.read(buffer))) {
         zos.write(buffer, 0, read);
       }
       in.close();
     }
   }
 }
Ejemplo n.º 10
0
  private void laden(Path saveName) throws IOException {
    Properties prop = new Properties();

    FileInputStream in = new FileInputStream(saveName.toString());
    prop.load(in);

    for (int i = 0; prop.containsKey(String.format("quellMenu%d", i)); i++)
      quellListModel.addElement(
          new ListItem(
              Paths.get(prop.getProperty(String.format("quellMenu%d", i))),
              Paths.get(prop.getProperty(String.format("quellMenu%d", i)))));
    for (int i = 0; prop.containsKey(String.format("zielMenu%d", i)); i++)
      zielListModel.addElement(
          new ListItem(
              Paths.get(prop.getProperty(String.format("zielMenu%d", i))),
              Paths.get(prop.getProperty(String.format("zielMenu%d", i)))));

    in.close();
  }
Ejemplo n.º 11
0
  protected static boolean vnmrjPassword(String strUser, char[] password) {
    boolean blogin = false;
    try {
      PasswordService objPassword = PasswordService.getInstance();
      String encrPassword = objPassword.encrypt(new String(password));
      if (pwprops == null) {
        String strPath = FileUtil.openPath(WUserUtil.PASSWORD);
        if (strPath == null) return blogin;
        pwprops = new Properties();
        FileInputStream fis = new FileInputStream(strPath);
        pwprops.load(fis);
        fis.close();
      }
      String stoPassword = pwprops.getProperty(strUser);
      if (encrPassword.equals(stoPassword)) blogin = true;
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
    }

    return blogin;
  }
Ejemplo n.º 12
0
  public void loadState(String extension) {
    String directory = cartridge.romFileName + extension;

    try {
      reset();

      FileInputStream fl = new FileInputStream(directory);
      DataInputStream sv = new DataInputStream(fl);

      // write cpu data
      loadData(sv, directory);

      // write battery ram
      cartridge.loadData(sv, directory);

      // write graphic memory
      graphicsChip.loadData(sv, directory);

      // writes io state
      ioHandler.loadData(sv, directory);

      sv.close();
      fl.close();

    } catch (FileNotFoundException ex) {
      System.out.println("Dmgcpu.loadState: Could not open file " + directory);
      System.out.println("Error Message: " + ex.getMessage());
      System.exit(-1);
    } catch (IOException ex) {
      System.out.println("Dmgcpu.loadState: Could not read file " + directory);
      System.out.println("Error Message: " + ex.getMessage());
      System.exit(-1);
    }

    System.out.println("Loaded stage!");
  }
Ejemplo n.º 13
0
  public static void convertQuick() {
    try {

      HashMap<String, ArrayList<Character>> charList = new HashMap<String, ArrayList<Character>>();

      Font font = new Font("Droid Sans Fallback", 16, Font.PLAIN);
      int totalQuickColumn = 3;
      FileInputStream fis = new FileInputStream("quick-classic.txt");
      InputStreamReader input = new InputStreamReader(fis, "UTF-8");
      BufferedReader reader = new BufferedReader(input);
      String str = null;
      int index = 0;
      int total = 0;
      ArrayList<String> keyList = new ArrayList<String>();
      System.out.println("#define QUICK_COLUMN " + totalQuickColumn);
      System.out.println("const jchar quick[][QUICK_COLUMN] = {");
      do {
        str = reader.readLine();
        if (str == null) break;
        index = str.indexOf('\t');
        if (index < 0) index = str.indexOf(' ');
        if (index > 0) {
          if (font.canDisplay(str.charAt(index + 1))) {
            StringBuffer sb = new StringBuffer();
            // System.out.print("\t { ");
            if ((int) str.charAt(1) == 9 || str.charAt(1) == ' ') {
              // System.out.print("'" + str.charAt(0) + "',   0, ");
              sb.append(str.charAt(0));
            } else {
              sb.append(str.charAt(0));
              sb.append(str.charAt(1));
              // System.out.print("'" + str.charAt(0) + "', '" + str.charAt(1) + "', ");
            }
            String key = sb.toString();
            // System.out.println((int) str.charAt(index + 1) + " }, ");
            Character ch = new Character(str.charAt(index + 1));

            if (!keyList.contains(key)) keyList.add(key);

            if (charList.containsKey(key)) {
              charList.get(key).add(ch);
            } else {
              ArrayList<Character> c = new ArrayList<Character>();
              c.add(ch);
              charList.put(key, c);
            }
            total++;
          }
        }
      } while (str != null);
      for (int count = 0; count < keyList.size(); count++) {
        String k = keyList.get(count);
        ArrayList<Character> l = charList.get(k);
        for (int loop = 0; loop < l.size(); loop++) {
          if (k.length() == 1) {
            System.out.println("\t { '" + k.charAt(0) + "',   0, " + l.get(loop) + " }, ");
          } else {
            System.out.println(
                "\t { '" + k.charAt(0) + "', '" + k.charAt(1) + "', " + l.get(loop) + " }, ");
          }
        }
      }
      System.out.println("};");
      System.out.println("jint quick_index[" + total + "];");
      System.out.println("jint quick_frequency[" + total + "];");
      reader.close();
      input.close();
      fis.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Ejemplo n.º 14
0
  public static void convertCangjieHK() {
    try {
      Font font = new Font("Droid Sans Fallback", 16, Font.PLAIN);
      ArrayList<String> codeList = new ArrayList<String>();
      HashMap<String, ArrayList<CangjieChar>> codeMap =
          new HashMap<String, ArrayList<CangjieChar>>();
      int totalCangjieColumn = 7;
      FileInputStream fis = new FileInputStream("cangjie3.txt");
      InputStreamReader input = new InputStreamReader(fis, "UTF-8");
      BufferedReader reader = new BufferedReader(input);
      String str = null;
      int index = 0;
      int total = 0;
      char column[] = new char[5];
      boolean hkchar = false;

      System.out.println("#define CANGJIE_COLUMN " + totalCangjieColumn);
      System.out.println("const jchar cangjie[][CANGJIE_COLUMN] = {");
      do {
        str = reader.readLine();
        if (str == null) break;
        if (str.compareTo("#####") == 0) {
          hkchar = true;
          continue;
        }
        index = str.indexOf('\t');
        if (index < 0) index = str.indexOf(' ');
        if (index > 0 && font.canDisplay(str.charAt(index + 1))) {
          int type = Character.getType(str.charAt(index + 1));
          if (Character.isLetter(str.charAt(index + 1))
              || type == Character.START_PUNCTUATION
              || type == Character.END_PUNCTUATION
              || type == Character.OTHER_PUNCTUATION
              || type == Character.MATH_SYMBOL
              || type == Character.DASH_PUNCTUATION
              || type == Character.CONNECTOR_PUNCTUATION
              || type == Character.OTHER_SYMBOL
              || type == Character.INITIAL_QUOTE_PUNCTUATION
              || type == Character.FINAL_QUOTE_PUNCTUATION
              || type == Character.SPACE_SEPARATOR) {
            // System.out.print("\t { ");
            // for (int count = 0; count < 5; count++) {
            //     if (count < index) {
            // 	column[count] = str.charAt(count);
            // 	if (column[count] < 'a' || column[count] > 'z') column[count] = 0;
            // 	if (((int) column[count]) >= 10 || ((int) column[count]) <= 99) System.out.print('
            // ');
            // 	if (((int) column[count]) <= 9) System.out.print(' ');
            // 	System.out.print(((int)	column[count]));
            //     } else {
            // 	System.out.print("  0");
            //     }
            //     System.out.print(", ");
            // }
            // System.out.println((int) str.charAt(index + 1) + " }, ");

            String cangjie = str.substring(0, index).trim();
            char ch = str.charAt(index + 1);
            if (!codeList.contains(cangjie)) codeList.add(cangjie);
            ArrayList<CangjieChar> list = null;
            if (codeMap.containsKey(cangjie)) {
              list = codeMap.get(cangjie);
            } else {
              list = new ArrayList<CangjieChar>();
            }
            CangjieChar cc = new CangjieChar(ch, hkchar);
            list.add(cc);
            codeMap.put(cangjie, list);

            total++;
          } else {
            System.err.println(
                "Character Not Found : "
                    + str.charAt(index + 1)
                    + " "
                    + Character.getType(str.charAt(index + 1)));
          }
        }
      } while (str != null);

      Collections.sort(codeList);

      for (int count0 = 0; count0 < codeList.size(); count0++) {
        String _str = codeList.get(count0);
        ArrayList<CangjieChar> ca = codeMap.get(_str);
        for (int count1 = 0; count1 < ca.size(); count1++) {
          for (int count2 = 0; count2 < 5; count2++) {
            if (count2 < _str.length()) System.out.print("'" + _str.charAt(count2) + "', ");
            else System.out.print("  0, ");
          }
          System.out.println(((int) ca.get(count1).c) + ", " + (ca.get(count1).hk ? 1 : 0) + ", ");
        }
      }

      System.out.println("};");
      System.out.println("jint cangjie_index[" + total + "];");
      System.out.println("jint cangjie_frequency[" + total + "];");
      reader.close();
      input.close();
      fis.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Ejemplo n.º 15
0
  public static void main(String[] arg) {
    if (arg.length != 2) {
      System.err.println("usage: java ScpTo file1 user@remotehost:file2");
      System.exit(-1);
    }

    FileInputStream fis = null;
    try {

      String lfile = arg[0];
      String user = arg[1].substring(0, arg[1].indexOf('@'));
      arg[1] = arg[1].substring(arg[1].indexOf('@') + 1);
      String host = arg[1].substring(0, arg[1].indexOf(':'));
      String rfile = arg[1].substring(arg[1].indexOf(':') + 1);

      JSch jsch = new JSch();
      Session session = jsch.getSession(user, host, 22);

      // username and password will be given via UserInfo interface.
      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      session.connect();

      boolean ptimestamp = true;

      // exec 'scp -t rfile' remotely
      String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile;
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      if (checkAck(in) != 0) {
        System.exit(0);
      }

      File _lfile = new File(lfile);

      if (ptimestamp) {
        command = "T " + (_lfile.lastModified() / 1000) + " 0";
        // The access time should be sent here,
        // but it is not accessible with JavaAPI ;-<
        command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
      }

      // send "C0644 filesize filename", where filename should not include '/'
      long filesize = _lfile.length();
      command = "C0644 " + filesize + " ";
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }

      // send a content of lfile
      fis = new FileInputStream(lfile);
      byte[] buf = new byte[1024];
      while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) break;
        out.write(buf, 0, len); // out.flush();
      }
      fis.close();
      fis = null;
      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }
      out.close();

      channel.disconnect();
      session.disconnect();

      System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbSaveLayer) {
      try {
        FileOutputStream fout = new FileOutputStream(jtfCengMing.getText() + ".wyf");
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(itemArray);
        oout.close();
        fout.close();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
    } else if (e.getSource() == jbLoadLayer) {
      try {
        FileInputStream fin = new FileInputStream(jtfCengMing.getText() + ".wyf");
        ObjectInputStream oin = new ObjectInputStream(fin);
        itemArray = (Item[][]) oin.readObject();

        oin.close();
        fin.close();
        this.flush();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
      lvp.repaint();
    } else if (e.getSource() == jbLoadAll) { // 全部铺上当前选中

      for (int row = 0; row < 40; row++) {
        for (int col = 0; col < 60; col++) {
          Item item = ((Item) (jl.getSelectedValue())).clone();
          itemArray[row][col] = item;
          if (item != null) {
            item.setPosition(col, row);
          }
        }
      }

      lvp.repaint();
    } else if (e.getSource() == jbCreate) { // 生成源代码

      try {
        FileOutputStream fout = null;
        DataOutputStream dout = null;
        fout = new FileOutputStream("maps.so");
        dout = new DataOutputStream(fout);
        int totalBlocks = 0;

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              totalBlocks++;
            }
          }
        }
        System.out.println("totalBlocks=" + totalBlocks);

        // 写入不空块的数量
        dout.writeInt(totalBlocks);

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              int w = item.w; // 元素的图片宽度
              int h = item.h; // 元素的图片高度
              int col = item.col; // 元素的地图列
              int row = item.row; // 元素的地图行
              int pCol = item.pCol; // 元素的占位列
              int pRow = item.pRow; // 元素的占位行
              String leiMing = item.leiMing; // 类名

              int[][] notIn = item.notIn; // 不可通过
              int[][] keYu = item.keYu; // 可遇矩阵

              // 计算图片下标
              int outBitmapInxex = 0;
              if (leiMing.equals("Grass")) {
                outBitmapInxex = 0;
              } else if (leiMing.equals("XiaoHua1")) {
                outBitmapInxex = 1;
              } else if (leiMing.equals("MuZhuang")) {
                outBitmapInxex = 2;
              } else if (leiMing.equals("XiaoHua2")) {
                outBitmapInxex = 3;
              } else if (leiMing.equals("Road")) {
                outBitmapInxex = 4;
              } else if (leiMing.equals("Jing")) {
                outBitmapInxex = 5;
              }

              dout.writeByte(outBitmapInxex); // 记录图片下标
              dout.writeByte(0); // 记录可遇标志 0-不可遇 底层都不可遇
              dout.writeByte(w); // 图片宽度
              dout.writeByte(h); // 图片高度
              dout.writeByte(col); // 总列数
              dout.writeByte(row); // 总行数
              dout.writeByte(pCol); // 占位列
              dout.writeByte(pRow); // 占位行

              int bktgCount = notIn.length; // 不可通过点的数量
              dout.writeByte(bktgCount); // 写入不可通过点的数量

              for (int k = 0; k < bktgCount; k++) {
                dout.writeByte(notIn[k][0]);
                dout.writeByte(notIn[k][1]);
              }
            }
          }
        }

        dout.close();
        fout.close();

      } catch (Exception ea) {
        ea.printStackTrace();
      }
    }
  }
Ejemplo n.º 17
0
  /**
   * Parse the section file and fill in the Dbase.
   *
   * @return Success code
   */
  public void parse() throws Exception {
    JOAParameter tempProperties[] = new JOAParameter[100];
    FileInputStream in = null;
    DataInputStream inData = null;
    short inShort = 0;
    long bytesRead = 0;
    long bytesInFile = mFile.length();
    short[] sarray = new short[1];
    int mTotalStns = 0;

    EPSProgressDialog mProgress = new EPSProgressDialog(new Frame(), mProgressStr, Color.blue);
    mProgress.setVisible(true);

    // Get an epic key database specific to JOA
    EPIC_Key_DB mEpicKeyDB = new EPIC_Key_DB("joa_epic.key");

    // Get an epic key database specific to JOA
    EPIC_Key_DB mOrigEpicKeyDB = new EPIC_Key_DB("epic.key");

    // create a vector for temporary storage of the dbases
    Vector dBases = new Vector(100);

    try {
      in = new FileInputStream(mFile);
      BufferedInputStream bis = new BufferedInputStream(in, 1000000);
      inData = new DataInputStream(bis);

      // read version
      short vers = inData.readShort();
      bytesRead += 2;

      if (vers < 2) {
        FileImportException fiex = new FileImportException();
        String errStr = "Invalid version for a JOA binary file";
        fiex.setErrorType(errStr);
        throw fiex;
      }

      // read number of bytes in file description string
      inShort = inData.readShort();
      bytesRead += 2;

      // read the file description String
      byte buf[] = new byte[inShort];
      inData.read(buf, 0, inShort);
      String fileDescrip = new String(buf);
      bytesRead += inShort;

      // create a new open file object
      JOADataFile of = new JOADataFile(fileDescrip);

      // read the number of sections
      int numSections = inData.readShort();
      bytesRead += 2;

      // read each section
      JOASection sech;
      int ord = 0;
      for (int s = 0; s < numSections; s++) {
        mProgress.setPercentComplete(100.0 * ((double) bytesRead / (double) bytesInFile));

        // read the section header
        inShort = inData.readShort();
        bytesRead += 2;
        byte buf1[] = new byte[inShort];
        inData.read(buf1, 0, inShort);
        String sectionDescrip = new String(buf1);
        bytesRead += inShort;

        // read the ship code
        byte bufsc[] = new byte[2];
        bufsc[0] = inData.readByte();
        bufsc[1] = inData.readByte();
        String shipCode = new String(bufsc);
        bytesRead += 2;

        // read num casts
        int numCasts = inData.readShort();
        bytesRead += 2;

        // read num parameters
        int numVars = inData.readShort();
        bytesRead += 2;

        // quality code
        int qcStd = 1;
        if (vers == 4) {
          qcStd = inData.readShort();
          bytesRead += 2;
        }

        // create a new section
        of.mNumSections++;
        sech = new JOASection(of.mNumSections, sectionDescrip, shipCode, numCasts, numVars);

        if (vers == 2) {
          // read the properties
          byte bufv[] = new byte[4];
          for (int p = 0; p < numVars; p++) {
            // parameter name
            inData.read(bufv, 0, 4);
            String tempVar = new String(bufv);
            bytesRead += 4;

            // units
            inShort = inData.readShort();
            bytesRead += 2;

            String units = null;
            if (inShort > 0) {
              byte buf11[] = new byte[inShort];
              inData.read(buf11, 0, inShort);
              units = new String(buf11);
              bytesRead += inShort;
            }

            // convert varnames to UC
            tempVar.toUpperCase();

            // create new property
            tempProperties[p] = new JOAParameter(tempVar, units);

            // add this property to the section property list
            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits =
                  EPS_Util.paramNameToJOAUnits(false, tempProperties[0].mVarLabel);
            }

            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits = new String("na");
            }
            tempProperties[p].mCastOrObs = EPSConstants.ALL_OBS;

            // read the actual scale
            int actScale = inData.readShort();
            bytesRead += 2;

            if (actScale != 0) tempProperties[p].mActScale = 1.0 / (double) actScale;
            else tempProperties[p].mActScale = 1.0;

            // read the actual origin
            int actOrigin = inData.readShort();
            tempProperties[p].mActOrigin = (double) actOrigin * tempProperties[p].mActScale;

            // read reverse y
            int reverseY = inData.readShort();
            bytesRead += 2;

            if (reverseY == 0) tempProperties[p].mReverseY = false;
            else tempProperties[p].mReverseY = true;

            tempProperties[p].mWasCalculated = false;
          }
        } else {
          // read the properties
          String tempVar = null;
          for (int p = 0; p < numVars; p++) {
            // length of parameter name
            inShort = inData.readShort();
            bytesRead += 2;

            // parameter name
            if (inShort > 0) {
              byte buf13[] = new byte[inShort];
              inData.read(buf13, 0, inShort);
              tempVar = new String(buf13);
              bytesRead += inShort;
            }

            // units
            inShort = inData.readShort();
            bytesRead += 2;

            String units = null;
            if (inShort > 0) {
              byte buf11[] = new byte[inShort];
              inData.read(buf11, 0, inShort);
              units = new String(buf11);
              bytesRead += inShort;
            }

            // convert varnames to UC
            tempVar = tempVar.toUpperCase();

            // create new property
            tempProperties[p] = new JOAParameter(tempVar, units);

            // add this property to the section property list
            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits =
                  EPS_Util.paramNameToJOAUnits(false, tempProperties[0].mVarLabel);
            }

            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits = new String("na");
            }
            tempProperties[p].mCastOrObs = EPSConstants.ALL_OBS;

            // read the actual scale
            int actScale = inData.readShort();
            bytesRead += 2;
            if (actScale != 0) tempProperties[p].mActScale = 1.0 / (double) actScale;
            else tempProperties[p].mActScale = 1.0;

            // read the actual origin
            int actOrigin = inData.readShort();
            tempProperties[p].mActOrigin = (double) actOrigin * tempProperties[p].mActScale;

            // read reverse y
            int reverseY = inData.readShort();
            bytesRead += 2;
            if (reverseY == 0) tempProperties[p].mReverseY = false;
            else tempProperties[p].mReverseY = true;

            tempProperties[p].mWasCalculated = false;
          }
        }

        // read the cast headers
        for (int c = 0; c < numCasts; c++) {
          // read station number
          inShort = inData.readShort();
          bytesRead += 2;
          byte bufx[] = new byte[inShort];
          inData.read(bufx, 0, inShort);
          String stnNum = new String(bufx);
          bytesRead += inShort;

          // read cast number
          int castNum = inData.readShort();
          bytesRead += 2;

          double myLat = 0.0;
          double myLon = 0.0;
          if (vers == 2) {
            // read latitude/lon
            int lat = inData.readInt();
            bytesRead += 4;

            int lon = inData.readInt();
            bytesRead += 4;

            myLat = lat * 0.001;
            myLon = lon * 0.001;
          } else if (vers > 2) {
            // read latitude/lon
            myLat = inData.readDouble();
            bytesRead += 8;

            myLon = inData.readDouble();
            bytesRead += 4;
          }

          // read number of bottles
          int numBottles = inData.readShort();
          bytesRead += 2;

          // read the date
          int year = inData.readInt();
          bytesRead += 4;
          int month = inData.readInt();
          bytesRead += 4;
          int day = inData.readInt();
          bytesRead += 4;
          int hour = inData.readInt();
          bytesRead += 4;
          double min = inData.readDouble();
          bytesRead += 8;

          // read bottom
          int bottomdbar = inData.readInt();

          // read station quality
          int stnQual = inData.readShort();
          bytesRead += 2;

          ord++;
          JOAStation sh =
              new JOAStation(
                  ord,
                  shipCode,
                  stnNum,
                  castNum,
                  myLat,
                  myLon,
                  numBottles,
                  year,
                  month,
                  day,
                  hour,
                  min,
                  bottomdbar,
                  stnQual);
          sech.mStations.addElement(sh);
          sh.setType("JOA BOTTLE");

          // make a DBase object
          Dbase db = new Dbase();

          // add the global attributes
          db.addEPSAttribute(
              "CRUISE", EPCHAR, sech.mSectionDescription.length(), sech.mSectionDescription);
          db.addEPSAttribute("CAST", EPCHAR, sh.mStnNum.length(), sh.mStnNum);
          sarray[0] = (short) sh.mBottomDepthInDBARS;
          db.addEPSAttribute("WATER_DEPTH", EPSHORT, 1, sarray);
          db.addEPSAttribute("DATA_ORIGIN", EPCHAR, sech.mShipCode.length(), sech.mShipCode);
          String dType = sh.getType();
          if (dType == null) dType = "UNKN";
          db.addEPSAttribute("DATA_TYPE", EPCHAR, dType.length(), dType);
          sarray[0] = (short) stnQual;
          db.addEPSAttribute("STN_QUALITY", EPSHORT, 1, sarray);
          db.setDataType("JOA BOTTLE");

          // add to temporary collection
          dBases.addElement(db);
        }

        int start = mTotalStns;
        int end = sech.mStations.size() + mTotalStns;
        for (int sc = start; sc < end; sc++) {
          mProgress.setPercentComplete(100.0 * ((double) bytesRead / (double) bytesInFile));

          // get a dBase
          Dbase db = (Dbase) dBases.elementAt(sc);

          // get a station
          JOAStation sh = (JOAStation) sech.mStations.elementAt(sc - start);

          // create an array of arrays to store the data
          double[][] va = new double[sech.mNumVars][sh.mNumBottles];
          int[][] qc = new int[sech.mNumVars][sh.mNumBottles];
          short[] bqc = new short[sh.mNumBottles];
          int presPos = 0;

          // read the bottles
          for (int b = 0; b < sh.mNumBottles; b++) {
            // read the bottle quality code
            bqc[b] = inData.readShort();
            bytesRead += 2;

            for (int v = 0; v < sech.mNumVars; v++) {
              // store the position of the PRES variable
              if (tempProperties[v].mVarLabel.equals("PRES")) presPos = v;

              // get the measured parameter
              double dVarVal = EPSConstants.MISSINGVALUE;
              try {
                dVarVal = inData.readDouble();
              } catch (IOException e) {
                FileImportException fiex = new FileImportException();
                String errStr =
                    "Error reading the parameter data. "
                        + "\n"
                        + "Bottle #"
                        + b
                        + " Parameter #"
                        + v;
                fiex.setErrorType(errStr);
                throw fiex;
              }
              bytesRead += 8;

              // store the value in the multidimensional array
              va[v][b] = dVarVal;

              // get the quality flag
              short flag = (short) EPSConstants.MISSINGVALUE;

              try {
                flag = inData.readShort();
              } catch (IOException e) {
                FileImportException fiex = new FileImportException();
                String errStr =
                    "Error reading the parameter quality code. "
                        + "\n"
                        + "Bottle #"
                        + b
                        + " Parameter #"
                        + v;
                fiex.setErrorType(errStr);
                throw fiex;
              }
              bytesRead += 2;
              qc[v][b] = flag;
            } // for v
          } // for b

          // add the bottle quality codes as an attribute
          db.addEPSAttribute("BOTTLE_QUALITY_CODES", EPSHORT, sh.mNumBottles, bqc);

          // create the axes time = 0, depth = 1, lat = 2, lon = 3
          Axis timeAxis = new Axis();
          Axis zAxis = new Axis();
          Axis latAxis = new Axis();
          Axis lonAxis = new Axis();

          // time axis
          timeAxis.setName("time");
          timeAxis.setTime(true);
          timeAxis.setUnlimited(false);
          timeAxis.setAxisType(EPTAXIS);
          timeAxis.setLen(1);

          int hour = 0;
          if (sh.mHour != EPSConstants.MISSINGVALUE) hour = sh.mHour;

          double mins = 0;
          if (sh.mMinute != EPSConstants.MISSINGVALUE) mins = sh.mMinute;

          // make the time axis units
          String date = "days since ";
          int min = (int) mins;
          double fmin = mins - min;
          int secs = (int) (fmin * 60.0);
          double fsec = (fmin * 60.0) - secs;
          int msec = (int) (fsec * 1000.0);
          String fs = String.valueOf(fsec);
          fs = fs.substring(fs.indexOf(".") + 1, fs.length()).trim();
          int f = 0;
          if (fs != null && fs.length() > 0) f = Integer.valueOf(fs).intValue();

          // sprintf(time_string,"%04d-%02d-%02d %02d:%02d:%02d.%03d",yr,mon,day,hr,min,sec,f);
          String frmt =
              new String(
                  "{0,number,####}-{1,number,00}-{2,number,00} {3,number,00}:{4,number,00}:{5,number,00}.{6,number,000}");
          MessageFormat msgf = new MessageFormat(frmt);

          Object[] objs = {
            new Integer(sh.mYear),
            new Integer(sh.mMonth),
            new Integer(sh.mDay),
            new Integer(hour),
            new Integer(min),
            new Integer(secs),
            new Integer(f)
          };
          StringBuffer out = new StringBuffer();
          msgf.format(objs, out, null);
          String time_string = new String(out);
          date = date + time_string;
          timeAxis.addAttribute(0, "units", EPCHAR, date.length(), date);
          timeAxis.setUnits(date);
          GeoDate gd = null;
          try {
            gd = new GeoDate(sh.mMonth, sh.mDay, sh.mYear, hour, min, secs, msec);
            GeoDate[] ta = {gd};
            MultiArray tma = new ArrayMultiArray(ta);

            timeAxis.setData(tma);
            db.setAxis(timeAxis);
          } catch (Exception ex) {
            GeoDate[] ta = {new GeoDate()};
            MultiArray tma = new ArrayMultiArray(ta);

            timeAxis.setData(tma);
            db.setAxis(timeAxis);
          }

          // add the time axes variable
          EPSVariable var = new EPSVariable();
          var.setOname("time");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "units", EPCHAR, date.length(), date);
          var.setUnits(date);
          double[] vta = {0.0};
          MultiArray vtma = new ArrayMultiArray(vta);
          try {
            var.setData(vtma);
          } catch (Exception ex) {
          }
          db.addEPSVariable(var);

          // z axis
          zAxis.setName("depth");
          zAxis.setTime(false);
          zAxis.setUnlimited(false);
          zAxis.setLen(sh.mNumBottles);
          zAxis.setAxisType(EPZAXIS);
          zAxis.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.1");
          zAxis.addAttribute(1, "units", EPCHAR, 4, "dbar");
          zAxis.setUnits("dbar");
          zAxis.setFrmt("f10.1");
          // zAxis.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 1;
          zAxis.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          double[] za = new double[sh.mNumBottles];
          for (int b = 0; b < sh.mNumBottles; b++) {
            za[b] = va[presPos][b];
          }
          MultiArray zma = new ArrayMultiArray(za);
          zAxis.setData(zma);
          db.setAxis(zAxis);

          // add the z axes variables
          var = new EPSVariable();
          var.setOname("depth");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.1");
          var.addAttribute(1, "units", EPCHAR, 4, "dbar");
          var.setUnits("dbar");
          var.setFrmt("f10.1");
          // var.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 1;
          var.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          MultiArray zvma = new ArrayMultiArray(za);
          try {
            var.setData(zvma);
          } catch (Exception ex) {
          }
          db.addEPSVariable(var);

          // lat axis
          latAxis.setName("latitude");
          latAxis.setTime(false);
          latAxis.setUnlimited(false);
          latAxis.setLen(1);
          latAxis.setAxisType(EPYAXIS);
          latAxis.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          latAxis.addAttribute(1, "units", EPCHAR, 7, "degrees");
          latAxis.setUnits("degrees");
          latAxis.setFrmt("f10.4");
          // latAxis.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 500;
          latAxis.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          double lat = sh.mLat;
          double[] la = {lat};
          MultiArray lma = new ArrayMultiArray(la);
          latAxis.setData(lma);
          db.setAxis(latAxis);

          // add the y axes variable
          var = new EPSVariable();
          var.setOname("latitude");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          var.addAttribute(1, "units", EPCHAR, 7, "degrees");
          var.setUnits("degrees");
          var.setFrmt("f10.4");
          // var.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 500;
          var.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          MultiArray yvma = new ArrayMultiArray(la);
          try {
            var.setData(yvma);
          } catch (Exception ex) {
          }
          db.addEPSVariable(var);

          // lon axis
          lonAxis.setName("longitude");
          lonAxis.setTime(false);
          lonAxis.setUnlimited(false);
          lonAxis.setLen(1);
          lonAxis.setAxisType(EPXAXIS);
          lonAxis.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          lonAxis.addAttribute(1, "units", EPCHAR, 7, "degrees");
          lonAxis.setUnits("degrees");
          lonAxis.setFrmt("f10.4");
          // lonAxis.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 502;
          lonAxis.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          double lon = sh.mLon;
          double[] lla = {lon};
          lma = new ArrayMultiArray(lla);
          lonAxis.setData(lma);
          db.setAxis(lonAxis);

          // add the x axes variable
          var = new EPSVariable();
          var.setOname("longitude");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          var.addAttribute(1, "units", EPCHAR, 7, "degrees");
          var.setUnits("degrees");
          var.setFrmt("f10.4");
          // var.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 502;
          var.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          MultiArray xvma = new ArrayMultiArray(lla);
          try {
            var.setData(xvma);
          } catch (Exception ex) {
          }

          db.addEPSVariable(var);

          // add the measured variables
          for (int v = 0; v < sech.mNumVars; v++) {
            // if (presPos == v)
            //	continue;

            // create an array of measured EPSVariables for this database
            EPSVariable epsVar = new EPSVariable();

            // initialize the new EPSVariables
            // look this variable up in JOA EPIC_Key. find matching entry in original EPIC Key
            String oname = tempProperties[v].mVarLabel;
            String sname = null;
            String lname = null;
            String gname = null;
            String units = null;
            String ffrmt = null;
            int keyID = -99;
            int type = -99;
            try {
              keyID = mEpicKeyDB.findKey(tempProperties[v].mVarLabel);
              Key key = mOrigEpicKeyDB.findKey(keyID);
              gname = key.getGname();
              sname = key.getSname();
              lname = key.getLname();
              units = key.getUnits();
              ffrmt = key.getFrmt();
              type = key.getType();
            } catch (Exception e) {
              lname = tempProperties[v].mVarLabel;
              gname = tempProperties[v].mVarLabel;
              sname = tempProperties[v].mVarLabel;
              units = tempProperties[v].mUnits;
            }

            // make a new variable
            epsVar = new EPSVariable();

            epsVar.setOname(oname);
            epsVar.setSname(sname);
            epsVar.setLname(lname);
            epsVar.setGname(gname);
            epsVar.setDtype(EPDOUBLE);
            epsVar.setVclass(Double.TYPE);
            int numAttributes = 0;
            if (ffrmt != null) {
              epsVar.addAttribute(numAttributes++, "FORTRAN_format", EPCHAR, ffrmt.length(), ffrmt);
              epsVar.setFrmt(ffrmt);
            }
            if (units != null && units.length() > 0) {
              epsVar.addAttribute(numAttributes++, "units", EPCHAR, units.length(), units);
              epsVar.setUnits(units);
            }
            if (keyID >= 0) {
              sarray[0] = (short) type;
              // epsVar.addAttribute(numAttributes++, "type", EPSHORT, 1, sarray);
            }
            if (keyID >= 0) {
              sarray[0] = (short) keyID;
              epsVar.addAttribute(numAttributes++, "epic_code", EPSHORT, 1, sarray);
            }

            // add the quality code attribute
            String qcVar = oname + "_QC";
            epsVar.addAttribute(numAttributes++, "OBS_QC_VARIABLE", EPCHAR, qcVar.length(), qcVar);

            // connect variable to axis
            epsVar.setDimorder(0, 0);
            epsVar.setDimorder(1, 1);
            epsVar.setDimorder(2, 2);
            epsVar.setDimorder(3, 3);
            epsVar.setT(timeAxis);
            epsVar.setZ(zAxis);
            epsVar.setY(latAxis);
            epsVar.setX(lonAxis);

            // set the data
            // create storage for the measured variables
            double[][][][] vaa = new double[1][sh.mNumBottles][1][1];
            for (int b = 0; b < sh.mNumBottles; b++) {
              vaa[0][b][0][0] = va[v][b];
            }
            MultiArray mdma = new ArrayMultiArray(vaa);
            try {
              epsVar.setData(mdma);
            } catch (Exception ex) {
              System.out.println("throwing");
            }

            // add the variable to the database
            db.addEPSVariable(epsVar);

            // create the quality code variable
            epsVar = new EPSVariable();
            epsVar.setOname(oname + "_QC");
            epsVar.setSname(sname + "_QC");
            epsVar.setLname(sname + "_QC");
            epsVar.setGname(sname + "_QC");
            epsVar.setDtype(EPSHORT);
            epsVar.setVclass(Short.TYPE);

            // connect variable to axis
            epsVar.setDimorder(0, 0);
            epsVar.setDimorder(1, 1);
            epsVar.setDimorder(2, 2);
            epsVar.setDimorder(3, 3);
            epsVar.setT(timeAxis);
            epsVar.setZ(zAxis);
            epsVar.setY(latAxis);
            epsVar.setX(lonAxis);

            // set the data
            // create storage for the qc variables
            short[][][][] qcaa = new short[1][sh.mNumBottles][1][1];
            for (int b = 0; b < sh.mNumBottles; b++) {
              qcaa[0][b][0][0] = (short) qc[v][b];
            }
            MultiArray qcma = new ArrayMultiArray(qcaa);
            try {
              epsVar.setData(qcma);
            } catch (Exception ex) {
              System.out.println("throwing");
            }

            // add the qc variable to the database
            db.addEPSVariable(epsVar);
          } // for v
        }
        mTotalStns += numCasts;
      } // for sc

      // read the file comments
      StringBuffer sb = null;
      while (true) {
        try {
          // read continuation line
          inShort = inData.readShort();
          bytesRead += 2;

          if (inShort == 1) {
            // read number of bytes in file description string
            inShort = inData.readShort();
            bytesRead += 2;

            // read the file description String
            byte buf2[] = new byte[inShort];
            inData.read(buf2, 0, inShort);
            String commentLine = new String(buf2);
            bytesRead += inShort;

            if (sb == null) sb = new StringBuffer(commentLine);
            else sb.append(commentLine);
          }
        } catch (IOException e) {
          break;
        }
      } // while true

      if (sb != null) {
        // make attributes for the comments
        mOwnerDBase.setDataComment(new String(sb));
      }

      // make a sub database in the dbase
      mOwnerDBase.createSubEntries(mTotalStns, mFile.getName());
      for (int d = 0; d < mTotalStns; d++) {
        Dbase db = (Dbase) dBases.elementAt(d);
        mOwnerDBase.addSubEntry(db);
      }
      mProgress.setPercentComplete(100.0);
      mProgress.setVisible(false);
      mProgress.dispose();
      in.close();
    } catch (IOException e) {
      mProgress.setVisible(false);
      mProgress.dispose();
      throw e;
    }
  }
Ejemplo n.º 18
0
  private static ImageData readPPM(File file) throws IOException, BadImageFileException {
    FileInputStream s = new FileInputStream(file);

    ImageData imageData;
    try {
      String S1 = readln(s);

      int width;
      int height;
      int bands;
      int dataType;
      if (S1.equals("P5") || S1.equals("P6")) {
        bands = S1.equals("P5") ? 1 : 3;
        String S2 = readln(s);
        String S3 = readln(s);

        String dimensions[] = S2.split("\\s");
        width = Integer.parseInt(dimensions[0]);
        height = Integer.parseInt(dimensions[1]);

        dataType = S3.equals("255") ? DataBuffer.TYPE_BYTE : DataBuffer.TYPE_USHORT;

        imageData = new ImageData(width, height, bands, dataType);
      } else if (S1.equals("P7")) {
        String WIDTH = "WIDTH ";
        String HEIGHT = "HEIGHT ";
        String DEPTH = "DEPTH ";
        String MAXVAL = "MAXVAL ";
        // String TUPLTYPE = "TUPLTYPE ";
        // String ENDHDR = "ENDHDR";
        String SWIDTH = readln(s);
        width = Integer.parseInt(SWIDTH.substring(WIDTH.length()));
        String SHEIGHT = readln(s);
        height = Integer.parseInt(SHEIGHT.substring(HEIGHT.length()));
        String SDEPTH = readln(s);
        bands = Integer.parseInt(SDEPTH.substring(DEPTH.length()));
        String SMAXVAL = readln(s);
        dataType =
            SMAXVAL.substring(MAXVAL.length()).equals("65535")
                ? DataBuffer.TYPE_USHORT
                : DataBuffer.TYPE_BYTE;
        // String STUPLTYPE = readln(s);
        // String SENDHDR = readln(s);
        imageData = new ImageData(width, height, bands, dataType);
      } else return null;

      int totalData = width * height * bands * (dataType == DataBuffer.TYPE_BYTE ? 1 : 2);

      FileChannel c = s.getChannel();

      if (file.length() != totalData + c.position()) {
        c.close();
        throw new BadImageFileException(file);
      }

      ByteBuffer bb = c.map(FileChannel.MapMode.READ_ONLY, c.position(), totalData);

      if (dataType == DataBuffer.TYPE_USHORT) {
        // bb.order(ByteOrder.BIG_ENDIAN);
        bb.order(ByteOrder.nativeOrder());
        bb.asShortBuffer().get((short[]) imageData.data);

        // Darty hack to prevent crash on Arch Linux (issue #125)
        if (ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN)
          for (int i = 0; i < ((short[]) imageData.data).length; ++i)
            ((short[]) imageData.data)[i] = Short.reverseBytes(((short[]) imageData.data)[i]);
      } else bb.get((byte[]) imageData.data);

      if (bb instanceof DirectBuffer) ((DirectBuffer) bb).cleaner().clean();

      c.close();
    } catch (Exception e) {
      e.printStackTrace();
      s.close();
      throw new BadImageFileException(file, e);
    } finally {
      s.close();
    }

    return imageData;
  }
Ejemplo n.º 19
0
    public void runEvaluator() {
      int nSize = r.getNodeCount();
      nodeValues = new Double[nSize];
      allValues = new Double[nSize][];
      for (int i = 0; i < nSize; i++) {
        allValues[i] = new Double[nSize];
      }

      // get Oj's
      double[] o = new double[nSize];
      if (orgFile == null) {
        for (int i = 0; i < nSize; i++) {
          o[i] = 1.0;
        }
      } else {
        try {
          FileInputStream fis = new FileInputStream(orgFile);
          InputStreamReader isr = new InputStreamReader(fis);
          BufferedReader in = new BufferedReader(isr, 8096);
          String line = in.readLine();

          // try to guess delimiters
          String delim = " ";
          if (line.indexOf('\t') != 0) {
            delim = "\t";
          } else if (line.indexOf(',') != 0) {
            delim = ",";
          }
          Hashtable values = new Hashtable();
          while (line != null) {
            StringTokenizer st = new StringTokenizer(line, delim);
            line = in.readLine();
            String key = st.nextToken().trim();
            if (st.hasMoreTokens()) {
              try {
                Double d = Double.valueOf(st.nextToken());
                values.put(key, d);
              } catch (NumberFormatException nfe) {
                // ignore?
              }
            }
          }
          fis.close();
          TreeSet missingActors = new TreeSet();
          for (int i = 0; i < nSize; i++) {
            String actorName = r.getParent().getActor(i).getName();
            Double oValue = (Double) values.get(actorName);
            if (oValue == null) {
              missingActors.add(actorName);
              o[i] = 1.0;
            } else {
              o[i] = oValue.doubleValue();
            }
          }
          if (missingActors.size() > 0) {
            String errorMsg = "Couldn't find organization values for ";
            if (missingActors.size() <= 10) {
              Iterator iter = missingActors.iterator();
              errorMsg += "'" + iter.next() + "'";
              while (iter.hasNext()) {
                errorMsg += ", '" + iter.next() + "'";
              }
              errorMsg += ".";
            } else {
              errorMsg += missingActors.size() + " actors.";
            }
            JFrame f = new JFrame();
            JOptionPane.showMessageDialog(
                f, errorMsg, "Missing Values", JOptionPane.WARNING_MESSAGE);
          }
        } catch (IOException ioe) {
          Application.handleNonFatalThrowable(ioe);
        }
      }

      // i think i need to calculate all p_ij's
      double[][] p = new double[nSize][];
      for (int i = 0; i < nSize; i++) {
        p[i] = new double[nSize];
        double i_out = 0.0;
        for (int j = 0; j < nSize; j++) {
          if ((i != j) || (!ignoreDiagonals)) {
            if (investments == OUTBOUND || investments == BOTH) {
              i_out += r.getTieStrength(i, j);
            }
            if (investments == INBOUND || investments == BOTH) {
              i_out += r.getTieStrength(j, i);
            }
          }
        }

        for (int j = 0; j < nSize; j++) {
          p[i][j] = 0.0;
          if (i_out != 0.0) {
            if (investments == OUTBOUND || investments == BOTH) {
              p[i][j] += r.getTieStrength(i, j) / i_out;
            }
            if (investments == INBOUND || investments == BOTH) {
              p[i][j] += r.getTieStrength(j, i) / i_out;
            }
          }
        }
      }

      switch (type) {
          // implementation of Burt (1992: 64) equation 2.7
        case CONSTRAINT:
          for (int i = 0; i < nSize; i++) {
            double i_total = 0.0;
            allValues[i][i] = new Double(Double.NaN);
            for (int j = 0; j < nSize; j++) {
              if (i != j) {
                double c_sum = p[i][j];
                for (int q = 0; q < nSize; q++) {
                  if ((q != i) && (q != j)) {
                    c_sum += p[i][q] * p[q][j];
                  }
                }
                double c_ij = c_sum * c_sum * o[j];
                i_total += c_ij;
                allValues[i][j] = new Double(c_ij);
              }
            }
            nodeValues[i] = new Double(i_total);
          }
          break;

        case EFFECTIVE_SIZE:
          break;
      }
    }