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.
    }
  }
Beispiel #2
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();
  }
 // 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);
 }
  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;
  }
Beispiel #5
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;
  }
Beispiel #6
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;
 }
Beispiel #7
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;
  }
Beispiel #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();
      }
    }
  }
Beispiel #9
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();
 }
Beispiel #10
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();
  }
Beispiel #11
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();
      }
    }
Beispiel #12
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);
   }
 }
  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);
  }
  /**
   * 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;
  }
Beispiel #15
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);
    }
  }
Beispiel #17
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;
   }
 }
Beispiel #18
0
  public static void main(String[] arg) {
    if (arg.length != 2) {
      System.err.println("usage: java ScpFrom user@remotehost:file1 file2");
      System.exit(-1);
    }

    FileOutputStream fos = null;
    try {

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

      String prefix = null;
      if (new File(lfile).isDirectory()) {
        prefix = lfile + File.separator;
      }

      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();

      // exec 'scp -f rfile' remotely
      String command = "scp -f " + 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();

      byte[] buf = new byte[1024];

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();

      while (true) {
        int c = checkAck(in);
        if (c != 'C') {
          break;
        }

        // read '0644 '
        in.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
          if (in.read(buf, 0, 1) < 0) {
            // error
            break;
          }
          if (buf[0] == ' ') break;
          filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
          in.read(buf, i, 1);
          if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
          }
        }

        // System.out.println("filesize="+filesize+", file="+file);

        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();

        // read a content of lfile
        fos = new FileOutputStream(prefix == null ? lfile : prefix + file);
        int foo;
        while (true) {
          if (buf.length < filesize) foo = buf.length;
          else foo = (int) filesize;
          foo = in.read(buf, 0, foo);
          if (foo < 0) {
            // error
            break;
          }
          fos.write(buf, 0, foo);
          filesize -= foo;
          if (filesize == 0L) break;
        }
        fos.close();
        fos = null;

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

        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
      }

      session.disconnect();

      System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fos != null) fos.close();
      } catch (Exception ee) {
      }
    }
  }
Beispiel #19
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];
  }
Beispiel #20
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];
  }
  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);
  }