Example #1
2
  protected void runScript(String[] cmd, JTextArea txaMsg) {
    String strg = "";

    if (cmd == null) return;

    Process prcs = null;
    try {
      Messages.postDebug("Running script: " + cmd[2]);
      Runtime rt = Runtime.getRuntime();

      prcs = rt.exec(cmd);

      if (prcs == null) return;

      InputStream istrm = prcs.getInputStream();
      if (istrm == null) return;

      BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm));

      while ((strg = bfr.readLine()) != null) {
        // System.out.println(strg);
        strg = strg.trim();
        // Messages.postDebug(strg);
        strg = strg.toLowerCase();
        if (txaMsg != null) {
          txaMsg.append(strg);
          txaMsg.append("\n");
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
      Messages.postDebug(e.toString());
    } finally {
      // It is my understanding that these streams are left
      // open sometimes depending on the garbage collector.
      // So, close them.
      try {
        if (prcs != null) {
          OutputStream os = prcs.getOutputStream();
          if (os != null) os.close();
          InputStream is = prcs.getInputStream();
          if (is != null) is.close();
          is = prcs.getErrorStream();
          if (is != null) is.close();
        }
      } catch (Exception ex) {
        Messages.writeStackTrace(ex);
      }
    }
  }
  private void onOK() {
    try {
      InputStream in = new FileInputStream(inputFile);
      if (outputFile == null) {
        outputFile = new File(inputFile.getAbsolutePath() + "_");
      }
      OutputStream out = new FileOutputStream(outputFile);

      ANSIUnicodeConverter converter = new ANSIUnicodeConverter();
      converter.setDirection(ANSIUnicodeConverter.ANSI2UNICODE);
      StringBuffer output = new StringBuffer();

      final int BUFFER_SIZE = 1024 * 1024; // 1M
      byte[] buffer = new byte[BUFFER_SIZE];
      int currentPosition = 0;
      while (in.available() != 0) {
        int currentBufferSize = BUFFER_SIZE;
        if (in.available() < BUFFER_SIZE) {
          currentBufferSize = in.available();
        }
        in.read(buffer, currentPosition, currentBufferSize);
        currentBufferSize = currentBufferSize + currentBufferSize;
        converter.setInput(new String(buffer));

        out.write(converter.convert().getBytes());
      }

      in.close();
      out.close();
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Example #3
1
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
 // Essentially links an InputStream to the proper channels in the log box.
 private static void printOutput(InputStream in, SimpleAttributeSet set) {
   int i = 0;
   String s = "";
   try {
     while ((i = in.read()) != -1) {
       s += (char) i;
       // print(, set);
     }
   } catch (IOException io) {
     println("Error: IOException when reading InputStream " + in.toString(), progErr);
   }
   println(s);
 }
Example #5
1
  // tokenizes a string for PBM and PGM headers and plain PBM and PGM data.  If oneChar is true,
  // then
  // rather than parsing a whole string, a single character is read (not including whitespace or
  // comments)
  static String tokenizeString(InputStream stream, boolean oneChar) throws IOException {
    final int EOF = -1;

    StringBuilder b = new StringBuilder();
    int c;
    boolean inComment = false;

    while (true) {
      c = stream.read();
      if (c == EOF)
        throw new IOException(
            "Stream ended prematurely, before table reading was completed."); // no more tokens
      else if (inComment) {
        if (c == '\r' || c == '\n') // escape the comment
        inComment = false;
        else {
        } // do nothing
      } else if (Character.isWhitespace((char) c)) {
      } // do nothing
      else if (c == '#') // start of a comment
      {
        inComment = true;
      } else // start of a string
      {
        b.append((char) c);
        break;
      }
    }

    if (oneChar) return b.toString();

    // at this point we have a valid string.  We read until whitespace or a #
    while (true) {
      c = stream.read();
      if (c == EOF) break;
      else if (c == '#') // start of comment, read until a '\n'
      {
        while (true) {
          c = stream.read(); // could hit EOF, which is fine
          if (c == EOF) break;
          else if (c == '\r' || c == '\n') break;
        }
        // break;   // comments are not delimiters
      } else if (Character.isWhitespace((char) c)) break;
      else b.append((char) c);
    }
    return b.toString();
  }
Example #6
1
 public void run(String local, String remote, InputStream pin, OutputStream pout) {
   try {
     microphone = SoundMixerEnumerator.getInputLine(pcmformat, DefaultPhonePCMBlockSize);
   } catch (LineUnavailableException lue) {
     System.out.println(
         "\3b"
             + getClass().getName()
             + ".<init>:\n\tCould not create microphone input stream.\n\t"
             + lue);
   }
   try {
     speaker = SoundMixerEnumerator.getOutputLine(pcmformat, DefaultPhonePCMBlockSize);
   } catch (LineUnavailableException lue) {
     microphone.close();
     System.out.println(
         "\3b"
             + getClass().getName()
             + ".<init>:\n\tCould not create speaker output stream.\n\t"
             + lue);
   }
   if ((speaker == null) || (microphone == null)) {
     super.run(local, remote, pin, pout);
     return;
   }
   try {
     recorder = new Recorder(pout);
     recorder.start();
     gui = openMonitorGUI("Remote " + remote + " Local " + local);
     pin.skip(pin.available()); // waste whatever we couldn't process in time
     super.run(local, remote, new PhoneCallMonitorInputStream(pin), pout);
     recorder.interrupt();
     gui.dispose();
   } catch (Exception e) {
     System.out.println("3\b" + getClass().getName() + ".run:\n\t" + e);
     e.printStackTrace();
   } finally {
     deactivate();
     microphone.close();
     speaker.close();
     if (gui != null) {
       gui.dispose();
     }
   }
 }
Example #7
0
 private static Clip getClip(String wavFile) {
   String soundName = "sound\\" + wavFile + ".wav";
   InputStream sound = null;
   Clip clip = null;
   try {
     sound = new FileInputStream(soundName);
   } catch (FileNotFoundException ex) {
     sound = ClassLoader.getSystemResourceAsStream(soundName);
     if (sound == null) {
       System.out.println("Cant open file " + soundName);
       return null;
     }
   }
   try {
     AudioInputStream audioIn = AudioSystem.getAudioInputStream(sound);
     clip = AudioSystem.getClip();
     clip.open(audioIn);
   } catch (Exception ex) {
     System.out.println("Error in sound " + wavFile);
     System.out.println(ex.getMessage());
     if (clip != null) {
       clip.close();
       return null;
     }
     try {
       sound.close();
     } catch (IOException e) {
     }
   }
   return clip;
 }
Example #8
0
  /**
   * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file.
   *
   * @param f The jar file to extract from.
   * @return a temporary file to which the plugin.xml file has been copied.
   */
  public static File unpackPluginXML(File f) {
    InputStream in = null;
    OutputStream out = null;

    try {
      JarFile jar = new JarFile(f);
      ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE);
      if (entry == null) {
        return null;
      }
      File dest = File.createTempFile("jabref_plugin", ".xml");
      dest.deleteOnExit();

      in = new BufferedInputStream(jar.getInputStream(entry));
      out = new BufferedOutputStream(new FileOutputStream(dest));
      byte[] buffer = new byte[2048];
      for (; ; ) {
        int nBytes = in.read(buffer);
        if (nBytes <= 0) break;
        out.write(buffer, 0, nBytes);
      }
      out.flush();
      return dest;
    } catch (IOException ex) {
      ex.printStackTrace();
      return null;
    } finally {
      try {
        if (out != null) out.close();
        if (in != null) in.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
Example #9
0
  /** execute method之后,取返回的inputstream */
  private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception {
    int statusCode = client.getResponseCode();
    if (statusCode != HttpURLConnection.HTTP_OK) {
      throw new EnvException("Method failed: " + statusCode);
    }
    InputStream in = client.getResponseStream();
    if (in == null) {
      return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      Utils.copyBinaryTo(in, out);

      // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception
      byte[] bytes = out.toByteArray();
      // carl:格式一致传中文
      String message = new String(bytes, EncodeConstants.ENCODING_UTF_8);
      if (ComparatorUtils.equals(message, RemoteDeziConstants.NO_SUCH_RESOURCE)) {
        return null;
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.INVALID_USER)) {
        throw new EnvException(RemoteDeziConstants.INVALID_USER);
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) {
        JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Designer_file-is-locked"));
        return null;
      } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) {
      }
      return new ByteArrayInputStream(bytes);
    } finally {
      in.close();
      out.close();
      client.release();
    }
  }
  static int checkAck(InputStream in) throws IOException {
    int b = in.read();
    // b may be 0 for success,
    //          1 for error,
    //          2 for fatal error,
    //          -1
    if (b == 0) return b;
    if (b == -1) return b;

    if (b == 1 || b == 2) {
      StringBuffer sb = new StringBuffer();
      int c;
      do {
        c = in.read();
        sb.append((char) c);
      } while (c != '\n');
      if (b == 1) { // error
        System.out.print(sb.toString());
      }
      if (b == 2) { // fatal error
        System.out.print(sb.toString());
      }
    }
    return b;
  }
  @SuppressWarnings({"HardCodedStringLiteral"})
  @Nullable
  public static String getPropertyFromLaxFile(
      @NotNull final File file, @NotNull final String propertyName) {
    if (file.getName().endsWith(".properties")) {
      try {
        PropertyResourceBundle bundle;
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        try {
          bundle = new PropertyResourceBundle(fis);
        } finally {
          fis.close();
        }
        if (bundle.containsKey(propertyName)) {
          return bundle.getString(propertyName);
        }
        return null;
      } catch (IOException e) {
        return null;
      }
    }

    final String fileContent = getContent(file);

    // try to find custom config path
    final String propertyValue = findProperty(propertyName, fileContent);
    if (!StringUtil.isEmpty(propertyValue)) {
      return propertyValue;
    }

    return null;
  }
Example #12
0
  // Loads raw PGM files after the first-line header is stripped
  static int[][] loadRawPGM(InputStream stream) throws IOException {
    int width = tokenizeInt(stream);
    int height = tokenizeInt(stream);
    int maxVal = tokenizeInt(stream);
    if (width < 0) throw new IOException("Invalid width: " + width);
    if (height < 0) throw new IOException("Invalid height: " + height);
    if (maxVal <= 0) throw new IOException("Invalid maximum value: " + maxVal);

    // this single whitespace character will have likely already been consumed by reading maxVal
    // stream.read();  // must be a whitespace

    int[][] field = new int[width][height];
    for (int i = 0; i < height; i++)
      for (int j = 0; j < width; j++) {
        if (maxVal < 256) // one byte
        field[j][i] = stream.read();
        else if (maxVal < 65536) // two bytes
        field[j][i] =
              (stream.read() << 8) & stream.read(); // two bytes, most significant byte first
        else if (maxVal < 16777216) // three bytes -- this is nonstandard
        field[j][i] =
              (stream.read() << 16)
                  & (stream.read() << 8)
                  & stream.read(); // three bytes, most significant byte first
        else // four bytes -- this is nonstandard
        field[j][i] =
              (stream.read() << 24)
                  & (stream.read() << 16)
                  & (stream.read() << 8)
                  & stream.read(); // three bytes, most significant byte first
      }

    return field;
  }
  Ps2RealityControlCenter(String dir) throws IOException {

    try {
      byte[] abIcon;
      InputStream inputstreamIcon = this.getClass().getResourceAsStream("icon.gif");
      int iIconSize = inputstreamIcon.available();
      abIcon = new byte[iIconSize];
      inputstreamIcon.read(abIcon);
      this.setIconImage(new ImageIcon(abIcon).getImage());

    } catch (Exception ex) {
      // the default icon will be used
    }
    panelChooser = new Ps2RealityFileChooser(dir);
  }
Example #14
0
 public static boolean hashMatch(InputStream is, byte[] hash) throws IOException {
   boolean correct = true;
   for (int i = 0; i < hash.length; i++) {
     if (hash[i] != (byte) is.read()) correct = false;
   }
   return correct;
 }
Example #15
0
 public void load(ActionEvent e) {
   int returnVal = fc.showOpenDialog(this);
   if (returnVal != JFileChooser.APPROVE_OPTION) {
     return;
   }
   file = fc.getSelectedFile();
   try {
     InputStream in = new BufferedInputStream(new FileInputStream(file));
     Properties newWl = new Properties();
     newWl.load(in);
     in.close();
     setWordList(newWl);
   } catch (IOException ex) {
     handleException(ex);
   }
 }
Example #16
0
  // Loads raw PBM files after the first-line header is stripped
  static int[][] loadRawPBM(InputStream stream) throws IOException {
    int width = tokenizeInt(stream);
    int height = tokenizeInt(stream);
    if (width < 0) throw new IOException("Invalid width in PBM: " + width);
    if (height < 0) throw new IOException("Invalid height in PBM: " + height);

    // this single whitespace character will have likely already been consumed by reading height
    // stream.read();  // must be a whitespace

    int[][] field = new int[width][height];
    for (int i = 0; i < height; i++) {
      int data = 0;
      int count = 0;
      for (int j = 0; j < width; j++) {
        if (count == 0) {
          data = stream.read();
          count = 8;
        }
        count--;
        field[j][i] = (data >> count) & 0x1;
      }
    }

    return field;
  }
  /**
   * Loads an image from a given image identifier.
   *
   * @param imageID The identifier of the image.
   * @return The image for the given identifier.
   */
  @Override
  public byte[] getImageInBytes(String imageID) {
    InputStream in = getImageInputStream(imageID);

    if (in == null) return null;

    byte[] image = null;

    try {
      image = new byte[in.available()];
      in.read(image);
    } catch (IOException e) {
      logger.error("Failed to load image:" + imageID, e);
    }

    return image;
  }
Example #18
0
 // wonder if throwing error on end of stream f***s over other implementations? :P
 public static long readInteger(InputStream is) throws IOException {
   byte[] isr = new byte[8];
   for (int b = 0; b < isr.length; b++) {
     int r = is.read();
     if (r == -1) throw new IOException("readInt failed at end of stream");
     isr[b] = (byte) r;
   }
   ByteBuffer bb = ByteBuffer.wrap(isr);
   return bb.getLong();
 }
  public synchronized void loadProperties() {

    if (dataDir != null) {
      propertyFile = new File(dataDir, USER_FILENAME);
      // load font properties from last invocation
      if (propertyFile.exists()) {
        try {
          InputStream in = new FileInputStream(propertyFile);
          try {
            fontProps.load(in);
            fontManager.setFontProperties(fontProps);
          } finally {
            in.close();
          }
        } catch (IOException ex) {
          // check to make sure the storage relate dialogs can be shown
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.session.readError",
                ex);
          }
          // log the error
          if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Error loading font properties cache", ex);
          }
        } catch (IllegalArgumentException e) {
          // propblem parsing fontProps, reread teh file
          setupDefaultProperties();
          saveProperties();
        }
      }
      // If no font data, then read font data and save the new file.
      else {
        setupDefaultProperties();
        saveProperties();
      }
    }
  }
Example #20
0
 public static void hashpipe(InputStream is, OutputStream os, long len, MessageDigest md)
     throws IOException {
   byte[] buf = new byte[SMALL_BUFF];
   long read = 0;
   while (read < len) {
     int thisRead = is.read(buf, 0, (int) Math.min(SMALL_BUFF, len - read));
     read += thisRead;
     os.write(buf, 0, thisRead);
     md.update(buf, 0, thisRead);
   }
 }
Example #21
0
  static byte[] readStream(InputStream input) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    int read;
    byte[] buffer = new byte[256];

    while ((read = input.read(buffer, 0, 256)) != -1) {
      bytes.write(buffer, 0, read);
    }

    return bytes.toByteArray();
  }
Example #22
0
    public void run() {
      try {
        final byte[] lBuf = new byte[1024];
        int lBytesRead;

        while (in.read(lBuf, 0, 1) != -1) {
          synchronized (JConsole.this) {
            lBytesRead = in.read(lBuf, 1, 1023) + 1;
            print(new String(lBuf, 0, lBytesRead), attr);

            while (in.available() > 0) {
              lBytesRead = in.read(lBuf);
              print(new String(lBuf, 0, lBytesRead), attr);
            }
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Example #23
0
  public void setData(String text) {
    if (text != null && text.length() > 0) {
      InputStream in = null;
      try {
        Object result = null;
        Drawing drawing = createDrawing();
        // Try to read the data using all known input formats.
        for (InputFormat fmt : drawing.getInputFormats()) {
          try {
            fmt.read(in, drawing);
            in = new ByteArrayInputStream(text.getBytes("UTF8"));
            result = drawing;
            break;
          } catch (IOException e) {
            result = e;
          }
        }
        if (result instanceof IOException) {
          throw (IOException) result;
        }

        setDrawing(drawing);
      } catch (Throwable e) {
        getDrawing().removeAllChildren();
        SVGTextFigure tf = new SVGTextFigure();
        tf.setText(e.getMessage());
        tf.setBounds(new Point2D.Double(10, 10), new Point2D.Double(100, 100));
        getDrawing().add(tf);
        e.printStackTrace();
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException ex) {
            ex.printStackTrace();
          }
        }
      }
    }
  }
Example #24
0
  public static void copyFolder(File src, File dest, JLabel updatelbl, JLabel updatelbl2)
      throws IOException {

    if (src.isDirectory()) {

      if (!dest.exists()) {
        dest.mkdir();
        updatelbl.setText("Directory copied from " + src + "  to " + dest);
      }

      String files[] = src.list();

      for (String file : files) {

        File srcFile = new File(src, file);
        File destFile = new File(dest, file);
        // recursive copy
        copyFolder(srcFile, destFile, updatelbl, updatelbl2);
      }

    } else {

      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dest);

      byte[] buffer = new byte[1024];

      int length;

      while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
      }

      in.close();
      out.close();
      updatelbl.setText("File copied from " + src);
      updatelbl2.setText(" to " + dest);
    }
  }
  private static void copyFileFromJar(String sourceFileName, File target) {
    try {
      JarFile jar = new JarFile(privateInstance.getHome());
      ZipEntry entry = jar.getEntry(sourceFileName);

      InputStream inputStream = new BufferedInputStream(jar.getInputStream(entry));
      OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target));
      byte[] buffer = new byte[4096];
      for (; ; ) {
        int nBytes = inputStream.read(buffer);
        if (nBytes <= 0) break;
        outputStream.write(buffer, 0, nBytes);
      }
      outputStream.flush();
      outputStream.close();
      inputStream.close();
    } catch (FileNotFoundException e) {
      JOptionPane.showMessageDialog(null, e);
    } catch (IOException e) {
      JOptionPane.showMessageDialog(null, e);
    }
  }
Example #26
0
  public java.util.List<String> readTextFromJar(String s) {
    InputStream is = null;
    BufferedReader br = null;
    String line;
    ArrayList<String> list = new ArrayList<String>();

    try {
      is = getClass().getResourceAsStream(s);
      br = new BufferedReader(new InputStreamReader(is));
      while (null != (line = br.readLine())) {
        list.add(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (br != null) br.close();
        if (is != null) is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return list;
  }
Example #27
0
  public void ClosePort() {
    if (portOpened) {
      if (serialPort != null) {
        try {
          // Close the I/O streams.
          out.close();
          in.close();
          // Close the port.
          serialPort.removeEventListener();
          serialPort.close();
        } catch (IOException e) {
          // Don't care
        }
      }

      ClearLog();
      portOpened = false;
      portConfirmed = false;
      previewPane.setConnected(false);
      UpdateMenuBar();
    }
  }
Example #28
0
 // Deal with something robot has sent.
 public void serialEvent(SerialPortEvent events) {
   switch (events.getEventType()) {
     case SerialPortEvent.DATA_AVAILABLE:
       try {
         final byte[] buffer = new byte[1024];
         int len = in.read(buffer);
         if (len > 0) {
           String line2 = new String(buffer, 0, len);
           Log("<span style='color:#FFA500'>" + line2.replace("\n", "<br>") + "</span>");
           line3 += line2;
           // wait for the cue ("> ") to send another command
           if (line3.lastIndexOf(cue) != -1) {
             if (ConfirmPort()) {
               line3 = "";
               SendFileCommand();
             }
           }
         }
       } catch (IOException e) {
       }
       break;
   }
 }
  public static void main(String[] args) {
    // read filename and N 2 parameters
    String fileName = args[0];
    N = Integer.parseInt(args[1]);

    // output two images, one original image at left, the other result image at right
    BufferedImage imgOriginal =
        new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
    BufferedImage img = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);

    try {
      File file = new File(fileName);
      InputStream is = new FileInputStream(file);

      long len = file.length();
      byte[] bytes = new byte[(int) len];

      int offset = 0;
      int numRead = 0;
      while (offset < bytes.length
          && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
      }

      int ind = 0;
      for (int y = 0; y < IMAGE_HEIGHT; y++) {
        for (int x = 0; x < IMAGE_WIDTH; x++) {
          // for reading .raw image to show as a rgb image
          byte r = bytes[ind];
          byte g = bytes[ind];
          byte b = bytes[ind];

          // set pixel for display original image
          int pixOriginal = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
          imgOriginal.setRGB(x, y, pixOriginal);
          ind++;
        }
      }
      is.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    int[] vectorSpace = calculateVectorSpace(imgOriginal);

    // quantization
    for (int y = 0; y < IMAGE_HEIGHT; y++) {
      for (int x = 0; x < IMAGE_WIDTH; x++) {
        int clusterId = vectorSpace[IMAGE_WIDTH * y + x];
        img.setRGB(x, y, clusters[clusterId].getPixel());
      }
    }

    // Use a panel and label to display the image
    JPanel panel = new JPanel();
    panel.add(new JLabel(new ImageIcon(imgOriginal)));
    panel.add(new JLabel(new ImageIcon(img)));

    JFrame frame = new JFrame("Display images");

    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
Example #30
0
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    double sfreq = 20000.0;
    gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null);
    String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"};
    gd.addChoice("PSF Type?", psfchoice, psfchoice[0]);
    String[] filetypechoice = {
      "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File"
    };
    gd.addChoice("File Type?", filetypechoice, filetypechoice[0]);
    boolean ch2green = true;
    gd.addCheckbox("Ch2 is green?", ch2green);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    sfreq = gd.getNextNumber();
    int psfflag = gd.getNextChoiceIndex();
    int fileflag = gd.getNextChoiceIndex();
    ch2green = gd.getNextBoolean();
    int nfiles = 0;
    Object[] histograms = null;
    int xmax = 0;
    int ymax = 0;
    String[] names = null;
    if (fileflag < 2) {
      jdataio ioclass = new jdataio();
      File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
      if (filearray.length == 0) {
        return;
      }
      String dir = filearray[0].getAbsolutePath();
      int sepindex = dir.lastIndexOf(File.separator);
      String newdir = dir.substring(0, sepindex + 1);
      OpenDialog.setDefaultDirectory(newdir);
      nfiles = filearray.length / 2;
      if (nfiles > 25) {
        nfiles = 25;
      }
      histograms = new Object[nfiles];
      names = organize_c3_files(filearray);
      for (int i = 0; i < nfiles; i++) {
        try {
          int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0);
          int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0);
          int length3 = (int) (((double) filearray[2 * i].length()) / 2.0);
          int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0);
          InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i]));
          InputStream instream2 =
              new BufferedInputStream(new FileInputStream(filearray[2 * i + 1]));
          if (fileflag == 0) {
            int[] pmdata = new int[length1];
            int[] pmdata2 = new int[length2];
            if (!ioclass.skipstreambytes(instream, 128)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.skipstreambytes(instream2, 128)) {
              showioerror();
              instream2.close();
              return;
            }
            if (!ioclass.readintelintfile(instream, length1, pmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelintfile(instream2, length2, pmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000);
            } else {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000);
            }
          } else {
            float[] tmdata = new float[length3];
            float[] tmdata2 = new float[length4];
            if (!ioclass.readintelshortfile(instream, length3, tmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata);
            } else {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2);
            }
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
          instream.close();
          instream2.close();
        } catch (IOException e) {
          showioerror();
          return;
        }
      }
    } else {
      if (fileflag == 2) {
        ImageWindow iw = WindowManager.getCurrentWindow();
        float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
        float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
        sfreq = 1.0 / ((double) tempxvals[0][1]);
        nfiles = trajectories.length / 2;
        if (nfiles > 25) {
          nfiles = 25;
        }
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        histograms = new Object[nfiles];
        for (int i = 0; i < nfiles; i++) {
          names[i] = "trajectory " + (i + 1);
          if (ch2green) {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]);
          } else {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]);
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      } else {
        // here we read tab delimited lines from files
        jdataio ioclass = new jdataio();
        File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
        if (filearray.length == 0) {
          return;
        }
        String dir = filearray[0].getAbsolutePath();
        int sepindex = dir.lastIndexOf(File.separator);
        String newdir = dir.substring(0, sepindex + 1);
        OpenDialog.setDefaultDirectory(newdir);
        nfiles = filearray.length;
        if (nfiles > 25) {
          nfiles = 25;
        }
        histograms = new Object[nfiles];
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        for (int i = 0; i < nfiles; i++) {
          try {
            names[i] = filearray[i].getName();
            BufferedReader d = new BufferedReader(new FileReader(filearray[i]));
            String[] lines = new String[256];
            int counter = 0;
            do {
              lines[counter] = d.readLine();
              counter++;
            } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256);
            int numcolumns = 0;
            for (int j = 0; j < counter - 1; j++) {
              int temp = getncolumns(lines[j]);
              if (temp > numcolumns) {
                numcolumns = temp;
              }
            }
            float[][] temphist2 = null;
            if (ch2green) {
              temphist2 = new float[numcolumns][counter - 1];
            } else {
              temphist2 = new float[counter - 1][numcolumns];
            }
            for (int k = 0; k < counter - 1; k++) {
              float[] temp = tab_delim2float(lines[k]);
              for (int j = 0; j < numcolumns; j++) {
                if (ch2green) {
                  temphist2[j][k] = temp[j];
                } else {
                  temphist2[k][j] = temp[j];
                }
              }
            }
            histograms[i] = temphist2;
            d.close();
          } catch (IOException e) {
            showioerror();
            return;
          }
        }
        for (int i = 0; i < nfiles; i++) {
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      }
    }
    // note that here x is green and y is red
    float[][][] pch = new float[nfiles][xmax][ymax];
    for (int i = 0; i < nfiles; i++) {
      for (int j = 0; j < ((float[][]) histograms[i]).length; j++) {
        for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) {
          pch[i][j][k] = ((float[][]) histograms[i])[j][k];
        }
      }
    }

    final PCH2DFitWindow cw = new PCH2DFitWindow();
    cw.init(names, pch, psfflag);

    final Frame f = new Frame("PCH 2D Analysis");
    f.setLocation(10, 10);
    f.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            f.dispose();
          }
        });

    f.add(cw);
    f.pack();
    f.setResizable(false);
    Insets ins = f.getInsets();
    cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65;
    cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right;
    f.setSize(cw.totalSize);
    f.setVisible(true);
    cw.requestFocus();
  }