Esempio n. 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.
    }
  }
Esempio n. 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);
 }
Esempio n. 5
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();
     }
   }
 }
Esempio n. 6
0
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
Esempio n. 7
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
Esempio n. 8
0
 private void seticon() {
   Image icon;
   try {
     InputStream data = MainFrame.class.getResourceAsStream("icon.png");
     icon = javax.imageio.ImageIO.read(data);
     data.close();
   } catch (IOException e) {
     throw (new Error(e));
   }
   setIconImage(icon);
 }
Esempio n. 9
0
  public final String readCommand(byte[] b)
      throws IOException, InterruptedException, MessagingNetworkException {
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;
      boolean d = false;
      for (; ; ) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int by = is.read();
        if (by == -1) throw new IOException("unexpected EOF");
        if (by == 10 && d) break;
        d = (by == 13);
        if (ofs < b.length) {
          b[ofs++] = (byte) by;
        }
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }
      if (b[ofs - 1] == 13) --ofs;

      String line = new String(b, 0, ofs, "ASCII");

      if (StringUtil.startsWith(line, "MSG")) {
        StringTokenizer st = new StringTokenizer(line);
        String len_s = null;
        while (st.hasMoreTokens()) {
          len_s = st.nextToken();
        }
        if (len_s == null) throw new AssertException("len_s is null");
        int len;
        try {
          len = Integer.parseInt(len_s);
        } catch (NumberFormatException ex) {
          ServerConnection.throwProtocolViolated("MSG length must be int");
          len = 0;
        }
        String msg = readMSG(len);
        line = line + "\r\n" + msg;
      }
      if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("S: " + line);
      return line;
    }
  }
  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);
  }
Esempio n. 11
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);
   }
 }
Esempio n. 12
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();
      }
    }
Esempio n. 13
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();
          }
        }
      }
    }
  }
Esempio n. 14
0
 /**
  * ** Reads the specified number of bytes from the specifed socket ** @param socket The socket
  * from which bytes are read ** @param length The number of bytes to read from the socket
  * ** @throws IOException if an error occured or the server has stopped
  */
 protected static byte[] socketReadBytes(Socket socket, int length) throws IOException {
   if (socket == null) {
     return null;
   } else if (length <= 0) {
     return new byte[0];
   } else {
     int dataLen = 0;
     byte data[] = new byte[length];
     InputStream input = socket.getInputStream();
     while (dataLen < length) {
       int ch = input.read();
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else {
         data[dataLen] = (byte) ch;
         dataLen++;
       }
     }
     return data;
   }
 }
Esempio n. 15
0
  private static void copyfile(String srFile, String dtFile) {
    try {
      File f1 = new File(srFile);
      File f2 = new File(dtFile);
      InputStream in = new FileInputStream(f1);

      // For Overwrite the file.
      OutputStream out = new FileOutputStream(f2);

      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
      }
      in.close();
      out.close();
      EIError.debugMsg("File copied " + srFile + " " + dtFile, EIError.ErrorLevel.Notice);
    } catch (Exception e) {
      EIError.debugMsg(
          "Couldn't copy file" + srFile + " " + dtFile + " " + e.getMessage(),
          EIError.ErrorLevel.Error);
    }
  }
Esempio n. 16
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;
  }
Esempio n. 17
0
 /**
  * Copy data from an input stream to an output stream.
  *
  * @param in Input stream.
  * @param out Output stream.
  * @throws IOException
  */
 public static void copy(InputStream in, OutputStream out) throws IOException {
   // Do not allow other threads to read from the
   // input or write to the output while copying is
   // taking place
   synchronized (in) {
     synchronized (out) {
       byte[] buffer = new byte[1024];
       while (true) {
         int bytesRead = in.read(buffer);
         if (bytesRead == -1) break;
         out.write(buffer, 0, bytesRead);
       }
     }
   }
 }
Esempio n. 18
0
 /**
  * ** Reads the bytes from the specifed socket until an eod-of-stream error occurs, or ** until
  * the maximum number of bytes has bee read. ** @param socket The socket from which bytes are read
  * ** @param baos The ByteArrayOutputStream to which the bytes are written ** @param maxLength The
  * number of bytes to read from the socket ** @return The number of bytes read if no exception has
  * occurred ** @throws IOException if an error occured or the server has stopped
  */
 protected static int socketReadBytes(Socket socket, ByteArrayOutputStream baos, int maxLength)
     throws IOException {
   if (socket == null) {
     return 0;
   } else if (maxLength == 0) {
     return 0;
   } else {
     int dataLen = 0;
     InputStream input = socket.getInputStream();
     while ((maxLength < 0) || (dataLen < maxLength)) {
       int ch = input.read();
       if (ch < 0) {
         // we've reached the end of input
         return dataLen;
       } else {
         if (baos != null) {
           baos.write(ch);
         }
         dataLen++;
       }
     }
     return dataLen;
   }
 }
Esempio n. 19
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();
    }
  }
Esempio n. 20
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;
   }
 }
Esempio n. 21
0
  public static boolean showLicensing() {
    if (Config.getLicenseResource() == null) return true;
    ClassLoader cl = Main.class.getClassLoader();
    URL url = cl.getResource(Config.getLicenseResource());
    if (url == null) return true;

    String license = null;
    try {
      URLConnection con = url.openConnection();
      int size = con.getContentLength();
      byte[] content = new byte[size];
      InputStream in = new BufferedInputStream(con.getInputStream());
      in.read(content);
      license = new String(content);
    } catch (IOException ioe) {
      Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe);
      return false;
    }

    // Build dialog
    JTextArea ta = new JTextArea(license);
    ta.setEditable(false);
    final JDialog jd = new JDialog(_installerFrame, true);
    Container comp = jd.getContentPane();
    jd.setTitle(Config.getLicenseDialogTitle());
    comp.setLayout(new BorderLayout(10, 10));
    comp.add(new JScrollPane(ta), "Center");
    Box box = new Box(BoxLayout.X_AXIS);
    box.add(box.createHorizontalStrut(10));
    box.add(new JLabel(Config.getLicenseDialogQuestionString()));
    box.add(box.createHorizontalGlue());
    JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString());
    JButton exitButton = new JButton(Config.getLicenseDialogExitString());
    box.add(acceptButton);
    box.add(box.createHorizontalStrut(10));
    box.add(exitButton);
    box.add(box.createHorizontalStrut(10));
    jd.getRootPane().setDefaultButton(acceptButton);
    Box box2 = new Box(BoxLayout.Y_AXIS);
    box2.add(box);
    box2.add(box2.createVerticalStrut(5));
    comp.add(box2, "South");
    jd.pack();

    final boolean accept[] = new boolean[1];
    acceptButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            accept[0] = true;
            jd.hide();
            jd.dispose();
          }
        });

    exitButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            accept[0] = false;
            jd.hide();
            jd.dispose();
          }
        });

    // Apply any defaults the user may have, constraining to the size
    // of the screen, and default (packed) size.
    Rectangle size = new Rectangle(0, 0, 500, 300);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    size.width = Math.min(screenSize.width, size.width);
    size.height = Math.min(screenSize.height, size.height);
    // Center the window
    jd.setBounds(
        (screenSize.width - size.width) / 2,
        (screenSize.height - size.height) / 2,
        size.width,
        size.height);

    // Show dialog
    jd.show();

    return accept[0];
  }
Esempio n. 22
0
  public void fetchExternalJSLibrary(String targetURLString) {

    final URL targetURL;
    String targetFile = "";
    String s = null;

    InputStream is = null;
    BufferedReader dis = null;

    try {
      // ------------------------------------------------------------//
      // Step 2:  Create the URL.                                   //
      // ------------------------------------------------------------//
      // Note: Put your real URL here, or better yet, read it as a  //
      // command-line arg, or read it from a file.                  //
      // ------------------------------------------------------------//

      targetURL = new URL(targetURLString);

      // ----------------------------------------------//
      // Step 3:  Open an input stream from the url.  //
      // ----------------------------------------------//

      is = targetURL.openStream();

      // -------------------------------------------------------------//
      // Step 4:                                                     //
      // -------------------------------------------------------------//
      // Convert the InputStream to BufferedReader                   //
      // -------------------------------------------------------------//

      dis = new BufferedReader(new InputStreamReader(is));

      // ------------------------------------------------------------//
      // Step 5:                                                    //
      // ------------------------------------------------------------//
      // Now just read each record of the input stream, and print   //
      // it out.  Note that it's assumed that this problem is run   //
      // from a command-line, not from an application or applet.    //
      // ------------------------------------------------------------//

      while ((s = dis.readLine()) != null) {
        targetFile = targetFile + "\n" + s;
      }

      alert(targetFile);
      System.out.println(targetFile);

    } catch (MalformedURLException mue) {

      alert("Ouch - a MalformedURLException happened.");
      System.out.println("Ouch - a MalformedURLException happened.");
      mue.printStackTrace();
      System.exit(1);

    } catch (IOException ioe) {

      alert("Ouch - an IOException happened.");
      System.out.println("Ouch - an IOException happened.");
      ioe.printStackTrace();
      System.exit(1);

    } catch (Exception e) {
      alert("Ouch - Something wrong happened.");
      alert(e.toString());
      alert(e.getMessage());
    } finally {

      // ---------------------------------//
      // Step 6:  Close the InputStream  //
      // ---------------------------------//

      try {
        is.close();
        dis.close();
      } catch (IOException ioe) {
        // just going to ignore this one
      }
    } // end of 'finally' clause
  }
Esempio n. 23
0
  /** Determine JDK level of an applet. */
  private void findAppletJDKLevel(Applet applet) {
    // To determine the JDK level of an applet, the
    // most reliable way is to check the major version
    // of the applet class file.

    // synchronized on applet class object, so calling from
    // different instances of the same applet will be
    // serialized.
    Class<?> appletClass = applet.getClass();

    synchronized (appletClass) {
      // Determine if the JDK level of an applet has been
      // checked before.
      Boolean jdk11Target = loader.isJDK11Target(appletClass);
      Boolean jdk12Target = loader.isJDK12Target(appletClass);

      // if applet JDK level has been checked before, retrieve
      // value and return.
      if (jdk11Target != null || jdk12Target != null) {
        jdk11Applet = (jdk11Target == null) ? false : jdk11Target.booleanValue();
        jdk12Applet = (jdk12Target == null) ? false : jdk12Target.booleanValue();
        return;
      }

      String name = appletClass.getName();

      // first convert any '.' to '/'
      name = name.replace('.', '/');

      // append .class
      final String resourceName = name + ".class";

      byte[] classHeader = new byte[8];

      try (InputStream is =
          AccessController.doPrivileged(
              (PrivilegedAction<InputStream>) () -> loader.getResourceAsStream(resourceName))) {

        // Read the first 8 bytes of the class file
        int byteRead = is.read(classHeader, 0, 8);

        // return if the header is not read in entirely
        // for some reasons.
        if (byteRead != 8) return;
      } catch (IOException e) {
        return;
      }

      // Check major version in class file header
      int major_version = readShort(classHeader, 6);

      // Major version in class file is as follows:
      //   45 - JDK 1.1
      //   46 - JDK 1.2
      //   47 - JDK 1.3
      //   48 - JDK 1.4
      //   49 - JDK 1.5
      if (major_version < 46) jdk11Applet = true;
      else if (major_version == 46) jdk12Applet = true;

      // Store applet JDK level in AppContext for later lookup,
      // e.g. page switch.
      loader.setJDK11Target(appletClass, jdk11Applet);
      loader.setJDK12Target(appletClass, jdk12Applet);
    }
  }
Esempio n. 24
0
  /** Unpacks a resource to a temp. file */
  public static File unpackInstaller(String resourceName) {
    // Array to hold all results (this code is slightly more
    // generally that it needs to be)
    File[] results = new File[1];
    URL[] urls = new URL[1];

    // Determine size of download
    ClassLoader cl = Main.class.getClassLoader();
    urls[0] = cl.getResource(Config.getInstallerResource());
    if (urls[0] == null) {
      Config.trace("Could not find resource: " + Config.getInstallerResource());
      return null;
    }

    int totalSize = 0;
    int totalRead = 0;
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        try {
          URLConnection connection = urls[i].openConnection();
          totalSize += connection.getContentLength();
        } catch (IOException ioe) {
          Config.trace("Got exception: " + ioe);
          return null;
        }
      }
    }

    // Unpack each file
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        // Create temp. file to store unpacked file in
        InputStream in = null;
        OutputStream out = null;
        try {
          // Use extension from URL (important for dll files)
          String extension = new File(urls[i].getFile()).getName();
          int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1;
          if (lastdotidx == -1) {
            extension = ".dat";
          } else {
            extension = extension.substring(lastdotidx);
          }

          // Create output stream
          results[i] = File.createTempFile("jre", extension);
          results[i].deleteOnExit();
          out = new FileOutputStream(results[i]);

          // Create inputstream
          URLConnection connection = urls[i].openConnection();
          in = connection.getInputStream();

          int read = 0;
          byte[] buf = new byte[BUFFER_SIZE];
          while ((read = in.read(buf)) != -1) {
            out.write(buf, 0, read);
            // Notify delegate
            totalRead += read;
            if (totalRead > totalSize && totalSize != 0) totalSize = totalRead;

            // Update UI
            if (totalSize != 0) {
              int percent = (100 * totalRead) / totalSize;
              setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent));
            }
          }
        } catch (IOException ie) {
          Config.trace("Got exception while downloading resource: " + ie);
          for (int j = 0; j < results.length; j++) {
            if (results[j] != null) results[j].delete();
          }
          return null;
        } finally {
          try {
            if (in != null) in.close();
            if (out != null) out.close();
          } catch (IOException io) {
            /* ignore */
          }
        }
      }
    }

    setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK));
    return results[0];
  }
Esempio n. 25
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();
  }