Beispiel #1
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;
  }
 public TestType1CFont(InputStream is) throws IOException {
   super();
   setPreferredSize(new Dimension(800, 800));
   addKeyListener(this);
   BufferedInputStream bis = new BufferedInputStream(is);
   int count = 0;
   ArrayList<byte[]> al = new ArrayList<byte[]>();
   byte b[] = new byte[32000];
   int len;
   while ((len = bis.read(b, 0, b.length)) >= 0) {
     byte[] c = new byte[len];
     System.arraycopy(b, 0, c, 0, len);
     al.add(c);
     count += len;
     b = new byte[32000];
   }
   data = new byte[count];
   len = 0;
   for (int i = 0; i < al.size(); i++) {
     byte from[] = al.get(i);
     System.arraycopy(from, 0, data, len, from.length);
     len += from.length;
   }
   pos = 0;
   //	printData();
   parse();
   // TODO: free up (set to null) unused structures (data, subrs, stack)
 }
  private Icon makeIcon(final String gifFile) throws IOException {
    /* Copy resource into a byte array.  This is
     * necessary because several browsers consider
     * Class.getResource a security risk because it
     * can be used to load additional classes.
     * Class.getResourceAsStream just returns raw
     * bytes, which we can convert to an image.
     */
    InputStream resource = MyImageView.class.getResourceAsStream(gifFile);

    if (resource == null) {
      System.err.println(MyImageView.class.getName() + "/" + gifFile + " not found!!.");
      return null;
    }
    BufferedInputStream in = new BufferedInputStream(resource);
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    int n;
    while ((n = in.read(buffer)) > 0) {
      out.write(buffer, 0, n);
    }
    in.close();
    out.flush();

    buffer = out.toByteArray();
    if (buffer.length == 0) {
      System.err.println("warning: " + gifFile + " is zero-length");
      return null;
    }
    return new ImageIcon(buffer);
  }
Beispiel #4
0
 // Take a tree of files starting in a directory in a zip file
 // and copy them to a disk directory, recreating the tree.
 private int unpackZipFile(
     File inZipFile, String directory, String parent, boolean suppressFirstPathElement) {
   int count = 0;
   if (!inZipFile.exists()) return count;
   parent = parent.trim();
   if (!parent.endsWith(File.separator)) parent += File.separator;
   if (!directory.endsWith(File.separator)) directory += File.separator;
   File outFile = null;
   try {
     ZipFile zipFile = new ZipFile(inZipFile);
     Enumeration zipEntries = zipFile.entries();
     while (zipEntries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) zipEntries.nextElement();
       String name = entry.getName().replace('/', File.separatorChar);
       if (name.startsWith(directory)) {
         if (suppressFirstPathElement) name = name.substring(directory.length());
         outFile = new File(parent + name);
         // Create the directory, just in case
         if (name.indexOf(File.separatorChar) >= 0) {
           String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1);
           File dirFile = new File(parent + p);
           dirFile.mkdirs();
         }
         if (!entry.isDirectory()) {
           System.out.println("Installing " + outFile);
           // Copy the file
           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
           BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
           int size = 1024;
           int n = 0;
           byte[] b = new byte[size];
           while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n);
           in.close();
           out.flush();
           out.close();
           // Count the file
           count++;
         }
       }
     }
     zipFile.close();
   } catch (Exception e) {
     System.err.println("...an error occured while installing " + outFile);
     e.printStackTrace();
     System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage());
     return -count;
   }
   System.out.println(count + " files were installed.");
   return count;
 }
Beispiel #5
0
  public static int copyPlugin(JFrame frame, File source, String destFileName) {
    if (destFileName == null) destFileName = source.getName();
    if (!PluginCore.userPluginDir.exists()) {
      boolean created = PluginCore.userPluginDir.mkdirs();
      if (!created) {
        return UNABLE_TO_CREATE_DIR;
      }
    }
    File destFile = new File(PluginCore.userPluginDir, destFileName);
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(source));
      out = new BufferedOutputStream(new FileOutputStream(destFile));
      byte[] buf = new byte[1024];
      int count;
      while ((count = in.read(buf, 0, buf.length)) > 0) {
        out.write(buf, 0, count);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      return UNABLE_TO_COPY_FILE;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ignore) {
          // UNABLE_TO_COPY_FILE;
        }
      }

      if (out != null) {
        try {
          out.close();
        } catch (IOException ignore) {
          // UNABLE_TO_COPY_FILE;
        }
      }
    }
    return SUCCESS;
  }
 private static byte[] getFileAsBytes(String path) throws IOException {
   int len = 0;
   int totalLen = 0;
   Object streamOrError = FileManager.getInputStream(path, false, null, null);
   if (streamOrError instanceof String) {
     LogPanel.log((String) streamOrError);
     return null;
   }
   byte[] buf = new byte[1024];
   byte[] bytes = new byte[4096];
   BufferedInputStream bis = new BufferedInputStream((InputStream) streamOrError);
   while ((len = bis.read(buf)) > 0) {
     totalLen += len;
     if (totalLen >= bytes.length)
       bytes = ArrayUtil.ensureLength(bytes, totalLen * 2);
     System.arraycopy(buf, 0, bytes, totalLen - len, len);
   }
   bis.close();
   buf = new byte[totalLen];
   System.arraycopy(bytes, 0, buf, 0, totalLen);
   return buf;
 }
Beispiel #7
0
  public Image getImage(String sImage) {
    Image imReturn = null;
    try {
      if (jar == null) {
        imReturn = this.toolkit.createImage(this.getClass().getClassLoader().getResource(sImage));
      } else {
        //
        BufferedInputStream bis = new BufferedInputStream(jar.getInputStream(jar.getEntry(sImage)));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
        int b;
        while ((b = bis.read()) != -1) {
          buffer.write(b);
        }
        byte[] imageBuffer = buffer.toByteArray();
        imReturn = this.toolkit.createImage(imageBuffer);
        bis.close();
        buffer.close();
      }
    } catch (IOException ex) {

    }
    return imReturn;
  }
Beispiel #8
0
  /**
   * Loads PNG files and returns the result as an int[][]. The only PNG formats permitted are those
   * with up to 256 grays (including simple black and white) or indexed colors from an up to
   * 256-sized color table. Each integer value represents the gray level or the color table index
   * value of the pixel. The Y dimension is not flipped.
   */
  public static int[][] loadPNGFile(InputStream str) throws IOException {
    // read the bytes into a byte array
    BufferedInputStream stream = new BufferedInputStream(str);
    ArrayList list = new ArrayList();
    int count = 0;
    while (true) {
      byte[] buffer = new byte[16384 * 16];
      int len = stream.read(buffer);
      if (len <= 0) // all done
      break;
      else if (len < buffer.length) {
        byte[] buf2 = new byte[len];
        System.arraycopy(buffer, 0, buf2, 0, len);
        buffer = buf2;
      }
      count += len;
      list.add(buffer);
    }
    byte[] data = new byte[count];
    int cur = 0;
    for (int i = 0; i < list.size(); i++) {
      byte[] b = (byte[]) (list.get(i));
      System.arraycopy(b, 0, data, cur, b.length);
      cur += b.length;
    }

    // Next convert the byte array to a buffered image
    BufferedImage image = ((ToolkitImage) (new ImageIcon(data).getImage())).getBufferedImage();

    // Is the color model something we can use?
    int type = image.getType();
    if (type == BufferedImage.TYPE_BYTE_BINARY || type == BufferedImage.TYPE_BYTE_GRAY) {
      int w = image.getWidth();
      int h = image.getHeight();
      int[][] result = new int[w][h];
      // obviously this could be done more efficiently
      for (int i = 0; i < w; i++)
        for (int j = 0; j < h; j++) result[i][j] = (image.getRGB(i, j) & 0xFF);
      return result;
    } else if (type == BufferedImage.TYPE_BYTE_INDEXED) {
      Raster raster = image.getRaster();
      if (raster.getTransferType() != DataBuffer.TYPE_BYTE) // uh oh
      throw new IOException("Input Stream must contain an image with byte data if indexed.");
      byte[] pixel = new byte[1];
      int w = image.getWidth();
      int h = image.getHeight();
      int[][] result = new int[w][h];
      // obviously this could be done more efficiently
      for (int i = 0; i < w; i++)
        for (int j = 0; j < h; j++) {
          result[i][j] = ((byte[]) (raster.getDataElements(i, j, pixel)))[0];
          if (result[i][j] < 0) result[i][j] += 256;
        }
      return result;
    }
    // else if (type == TYPE_USHORT_GRAY)   // at present we don't handle shorts
    //    {
    //    }
    else
      throw new IOException(
          "Input Stream must contain a binary, byte-sized grayscale, or byte-sized indexed color scheme: "
              + image);
  }
Beispiel #9
0
    @Override
    public void run() {
      try {
        StringBuilder filePath = new StringBuilder();
        filePath.append(Constants.IO.imageBaseDir).append(File.separator);
        filePath
            .append(card.hashCode())
            .append(".")
            .append(card.getName().replace(":", "").replace("//", "-"))
            .append(".jpg");
        File temporaryFile = new File(filePath.toString());
        String imagePath = CardImageUtils.generateImagePath(card);
        TFile outputFile = new TFile(imagePath);
        if (!outputFile.exists()) {
          outputFile.getParentFile().mkdirs();
        }
        File existingFile = new File(imagePath.replaceFirst("\\w{3}.zip", ""));
        if (existingFile.exists()) {
          new TFile(existingFile).cp_rp(outputFile);
          synchronized (sync) {
            update(cardIndex + 1, count);
          }
          existingFile.delete();
          File parent = existingFile.getParentFile();
          if (parent != null && parent.isDirectory() && parent.list().length == 0) {
            parent.delete();
          }
          return;
        }
        BufferedOutputStream out;

        // Logger.getLogger(this.getClass()).info(url.toString());
        URLConnection httpConn = url.openConnection(p);
        httpConn.connect();
        if (((HttpURLConnection) httpConn).getResponseCode() == 200) {
          try (BufferedInputStream in =
              new BufferedInputStream(((HttpURLConnection) httpConn).getInputStream())) {
            // try (BufferedInputStream in = new
            // BufferedInputStream(url.openConnection(p).getInputStream())) {
            out = new BufferedOutputStream(new TFileOutputStream(temporaryFile));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
              // user cancelled
              if (cancel) {
                in.close();
                out.flush();
                out.close();
                temporaryFile.delete();
                return;
              }
              out.write(buf, 0, len);
            }
          }
          out.flush();
          out.close();

          if (card.isTwoFacedCard()) {
            BufferedImage image = ImageIO.read(temporaryFile);
            if (image.getHeight() == 470) {
              BufferedImage renderedImage = new BufferedImage(265, 370, BufferedImage.TYPE_INT_RGB);
              renderedImage.getGraphics();
              Graphics2D graphics2D = renderedImage.createGraphics();
              if (card.isTwoFacedCard() && card.isSecondSide()) {
                graphics2D.drawImage(image, 0, 0, 265, 370, 313, 62, 578, 432, null);
              } else {
                graphics2D.drawImage(image, 0, 0, 265, 370, 41, 62, 306, 432, null);
              }
              graphics2D.dispose();
              writeImageToFile(renderedImage, outputFile);
            } else {
              new TFile(temporaryFile).cp_rp(outputFile);
            }
            temporaryFile.delete();
          } else {
            new TFile(temporaryFile).cp_rp(outputFile);
            temporaryFile.delete();
          }
        } else {
          Logger.getLogger(this.getClass())
              .error(convertStreamToString(((HttpURLConnection) httpConn).getErrorStream()));
        }

      } catch (Exception e) {
        log.error(e, e);
      }

      synchronized (sync) {
        update(cardIndex + 1, count);
      }
    }