Пример #1
0
  public String get_settings_array() {

    String jsontext = new String("");

    try {

      JSONObject obj = new JSONObject();

      for (int loop = 0; loop < network.settingsx.length; loop++) { // ******

        obj.put(loop, network.settingsx[loop]);
      } // *****************************************************************

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      jsontext = out.toString();
      System.out.println(jsonText);

    } catch (Exception e) {
      e.printStackTrace();
      statex = "0";
      jsontext = "error";
    }

    return jsontext;
  } // ******************************
Пример #2
0
  public void loadMap(String s) {

    try {
      InputStream in = getClass().getResourceAsStream(s);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      numCols = Integer.parseInt(br.readLine());
      numRows = Integer.parseInt(br.readLine());
      map = new int[numRows][numCols];
      width = numCols * tileSize;
      height = numRows * tileSize;

      xmin = GamePanel.WIDTH - width;
      xmax = 0;
      ymin = GamePanel.HEIGHT - height;
      ymax = 0;

      String delims = "\\s+";
      for (int row = 0; row < numRows; row++) {
        String line = br.readLine();
        String[] tokens = line.split(delims);
        for (int col = 0; col < numCols; col++) {
          map[row][col] = Integer.parseInt(tokens[col]);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #3
0
    public void
        run() { // **************************************************************************************

      try {

        restartApplication();

      } catch (Exception e) {
        e.printStackTrace();
      }
    } // runx***************************************************************************************************
Пример #4
0
  public String set_new_block(String array) {

    String jsontext = new String("");

    String update_token[] = new String[network.listing_size];

    try {

      JSONParser parserx = new JSONParser();
      Object objx = parserx.parse(array);
      JSONObject jsonObjectx = (JSONObject) objx;

      for (int loop = 0; loop < network.listing_size; loop++) { // ************

        update_token[loop] = (String) jsonObjectx.get(Integer.toString(loop));
        System.out.println("import " + update_token[loop]);
      } // *******************************************************************

    } catch (Exception e) {
      e.printStackTrace();
    }

    String testerx = new String("error");

    for (int loop = 0; loop < network.listing_size; loop++) { // ************
      try {
        if (update_token[loop].equals("0")) {}
      } catch (Exception e) {
        statex = "0";
        testerx = "1";
        jsontext = "e09 NullException";
      }
    } // *******************************************************************

    while (!testerx.equals("1")) {

      System.out.println("Mining send new block update >>>>");

      // String testg = krypton_net_client.send_new_block_update(update_token);
      // System.out.println("testg " + testg);

      // if(testg.equals("1") || testg.equals("0")){System.out.println("BREAK"); break;}

      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
      }
    } // while

    return jsontext;
  } // ***************************************
Пример #5
0
 public static void main(String argv[]) {
   try {
     String testName = "javatest";
     boolean doyuv = false;
     for (int i = 0; i < argv.length; i++) {
       if (argv[i].equalsIgnoreCase("-yuv")) doyuv = true;
       if (argv[i].substring(0, 1).equalsIgnoreCase("-h") || argv[i].equalsIgnoreCase("-?"))
         usage();
       if (argv[i].equalsIgnoreCase("-bi")) {
         bi = true;
         testName = "javabitest";
       }
     }
     if (doyuv) yuv = YUVENCODE;
     doTest(35, 39, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_444, testName);
     doTest(39, 41, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_444, testName);
     doTest(41, 35, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_422, testName);
     doTest(35, 39, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_422, testName);
     doTest(39, 41, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_420, testName);
     doTest(41, 35, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_420, testName);
     doTest(35, 39, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_440, testName);
     doTest(39, 41, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_440, testName);
     doTest(35, 39, bi ? onlyGrayBI : onlyGray, TJ.SAMP_GRAY, testName);
     doTest(39, 41, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_GRAY, testName);
     doTest(41, 35, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_GRAY, testName);
     if (!doyuv && !bi) bufSizeTest();
     if (doyuv && !bi) {
       yuv = YUVDECODE;
       doTest(48, 48, onlyRGB, TJ.SAMP_444, "javatest_yuv0");
       doTest(35, 39, onlyRGB, TJ.SAMP_444, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_422, "javatest_yuv0");
       doTest(39, 41, onlyRGB, TJ.SAMP_422, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_420, "javatest_yuv0");
       doTest(41, 35, onlyRGB, TJ.SAMP_420, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_440, "javatest_yuv0");
       doTest(35, 39, onlyRGB, TJ.SAMP_440, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_GRAY, "javatest_yuv0");
       doTest(35, 39, onlyRGB, TJ.SAMP_GRAY, "javatest_yuv1");
       doTest(48, 48, onlyGray, TJ.SAMP_GRAY, "javatest_yuv0");
       doTest(39, 41, onlyGray, TJ.SAMP_GRAY, "javatest_yuv1");
     }
   } catch (Exception e) {
     e.printStackTrace();
     exitStatus = -1;
   }
   System.exit(exitStatus);
 }
Пример #6
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
Пример #7
0
  public void loadTiles(String s) {
    try {
      tileset = ImageIO.read(getClass().getResourceAsStream(s));
      numTilesAcross = tileset.getWidth() / tileSize;
      tiles = new Tile[2][numTilesAcross];

      BufferedImage subimage;
      for (int col = 0; col < numTilesAcross; col++) {
        subimage = tileset.getSubimage(col * tileSize, 0, tileSize, tileSize);
        tiles[0][col] = new Tile(subimage, Tile.NORMAL);
        subimage = tileset.getSubimage(col * tileSize, tileSize, tileSize, tileSize);
        tiles[1][col] = new Tile(subimage, Tile.BLOCKED);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #8
0
 public void staga() {
   initialize();
   while (true) {
     try {
       update();
       checkCollisions();
       checkPopupCollision();
       checkEnvCollisions();
       checkRocketCollision();
       drawBuffer();
       drawScreen();
       Thread.sleep(15);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  public static boolean compressPic(String srcFilePath, String descFilePath) {
    File file = null;
    BufferedImage src = null;
    FileOutputStream out = null;
    ImageWriter imgWrier;
    ImageWriteParam imgWriteParams;

    // 指定写图片的方式为 jpg
    imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
    imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
    // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
    imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
    // 这里指定压缩的程度,参数qality是取值0~1范围内,
    imgWriteParams.setCompressionQuality((float) 0.1);
    imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
    ColorModel colorModel = ColorModel.getRGBdefault();
    // 指定压缩时使用的色彩模式
    imgWriteParams.setDestinationType(
        new javax.imageio.ImageTypeSpecifier(
            colorModel, colorModel.createCompatibleSampleModel(16, 16)));

    try {
      if (StringUtils.isBlank(srcFilePath)) {
        return false;
      } else {
        file = new File(srcFilePath);
        src = ImageIO.read(file);
        out = new FileOutputStream(descFilePath);

        imgWrier.reset();
        // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
        imgWrier.setOutput(ImageIO.createImageOutputStream(out));
        // 调用write方法,就可以向输入流写图片
        imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
        out.flush();
        out.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
Пример #10
0
  public String get_status() {

    String jsontext = new String("");

    try {

      JSONObject obj = new JSONObject();

      obj.put("version", network.versionx);
      obj.put("status", "active");
      obj.put("program_status", network.programst);
      obj.put("listing_size", network.listing_size);
      obj.put("buffer_size", network.send_buffer_size);
      obj.put("mining_status", network.mining_status);
      obj.put("key", network.base58_id);
      obj.put("tor_active", Integer.toString(network.tor_active));
      obj.put("last_block", network.last_block_id);
      obj.put("last_block_timestamp", network.last_block_timestamp);
      obj.put("last_block_hash", network.last_block_idx);
      obj.put("difficulty", Long.toString(network.difficultyx));
      obj.put("last_mining_id", network.last_block_mining_idx);
      obj.put("prev_mining_id", network.prev_block_mining_idx);
      obj.put("blocktimesx", network.blocktimesx);
      obj.put("my_token_total", Integer.toString(network.database_listings_owner));
      obj.put("last_block_time", network.last_block_time);
      obj.put("database_listings_total", network.database_listings_total);
      obj.put("database_unconfirmed_total", network.database_unconfirmed_total);

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      jsontext = out.toString();
      // System.out.println(jsonText);

    } catch (Exception e) {
      e.printStackTrace();
      statex = "0";
      jsontext = "error";
    }

    return jsontext;
  } // ***************************************
Пример #11
0
  // Goes online to get user authentication from Flickr.
  public void getAuthentication() {
    AuthInterface authInterface = flickr.getAuthInterface();

    try {
      frob = authInterface.getFrob();
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      URL authURL = authInterface.buildAuthenticationUrl(Permission.WRITE, frob);

      // open the authentication URL in a browser
      open(authURL.toExternalForm());
    } catch (Exception e) {
      e.printStackTrace();
    }

    println("You have 15 seconds to approve the app!");
    int startedWaiting = millis();
    int waitDuration = 15 * 1000; // wait 10 seconds
    while ((millis() - startedWaiting) < waitDuration) {
      // just wait
    }
    println("Done waiting");

    try {
      auth = authInterface.getToken(frob);
      println("Authentication success");
      // This token can be used until the user revokes it.
      token = auth.getToken();
      // save it for future use
      saveToken(token);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // complete authentication
    authenticateWithToken(token);
  }
Пример #12
0
  private IFD writeYCbCrImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_INT_RGB);
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      int ss = (param == null) ? 0x22 : param.getSubSampling();

      int ssh = (ss >> 4) & 0x0F;
      int ssv = ss & 0x0F;

      if (ssh
          < ssv) { // YCbCrSubsampleVert shall always be less than or equal to YCbCrSubsampleHoriz.
        throw new IOException(
            "Internal error: YCbCrSubsampleVert is not less than YCbCrSubsampleHoriz.");
      }

      //      int ww=((width +ssh-1)/ssh)*ssh;                                   // [1] p.92
      //      int hh=((height+ssv-1)/ssv)*ssv;
      int ww = width;
      int hh = height;

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(ww)); // 256
      ifd.add(new DEFactory.ImageLengthDE(hh)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(3);
      bpss.setBitsPerSample(0, 8); // Y
      bpss.setBitsPerSample(1, 8); // Cb
      bpss.setBitsPerSample(2, 8); // Cr
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(YCbCr)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      if (comp == JPEG) {
        maxrps = ((maxrps + 8 * ssv - 1) / (8 * ssv)) * (8 * ssv);
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(3)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279

      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStream os = baos;
      JPEGOutputStream jpegos = null;

      if (comp == JPEG) {
        jpegos = new JPEGOutputStream(baos);

        int quality = (param == null) ? 50 : (int) (param.getCompressionQuality() * 100);

        jpegos.setZZQuantizationTable(0, JPEGConstants.LQT, quality);
        jpegos.setZZQuantizationTable(1, JPEGConstants.CQT, quality);

        jpegos.setRawDCHuffmanTable(0, JPEGConstants.HLDCTable);
        jpegos.setRawACHuffmanTable(0, JPEGConstants.HLACTable);
        jpegos.setRawDCHuffmanTable(1, JPEGConstants.HCDCTable);
        jpegos.setRawACHuffmanTable(1, JPEGConstants.HCACTable);

        jpegos.defineQuantizationTables();
        jpegos.defineHuffmanTables();
        jpegos.close();

        DEFactory.JPEGTablesDE jpegtables = new DEFactory.JPEGTablesDE(baos.toByteArray());
        ifd.add(jpegtables); // 347

        baos.reset();

        os = jpegos;
      }

      //      CCIR Recommendation 601-1  LumaRed=299/1000 LumaGreen=587/1000 LumeBlue=114/1000
      //      Y  = ( LumaRed * R + LumaGreen * G + LumaBlue * B )
      //      Cb = ( B - Y ) / ( 2 - 2 * LumaBlue )
      //      Cr = ( R - Y ) / ( 2 - 2 * LumaRed )

      double LumaRed = 299.0 / 1000.0;
      double LumaGreen = 587.0 / 1000.0;
      double LumaBlue = 114.0 / 1000.0;

      DEFactory.YCbCrCoefficientsDE YCbCrCoeff = new DEFactory.YCbCrCoefficientsDE();
      YCbCrCoeff.setLumaRed(LumaRed); // Y
      YCbCrCoeff.setLumaGreen(LumaGreen); // Cb
      YCbCrCoeff.setLumaBlue(LumaBlue); // Cr
      ifd.add(YCbCrCoeff); // 529

      DEFactory.YCbCrSubSamplingDE YCbCrSubSampling = new DEFactory.YCbCrSubSamplingDE();
      YCbCrSubSampling.setHoriz(ssh);
      YCbCrSubSampling.setVert(ssv);
      ifd.add(YCbCrSubSampling); // 530

      double RfBY = 0;
      double RfWY = 255;
      double RfBCb = 128;
      double RfWCb = 255;
      double RfBCr = 128;
      double RfWCr = 255;

      DEFactory.ReferenceBlackWhiteDE ReferenceBlackWhite = new DEFactory.ReferenceBlackWhiteDE();
      ReferenceBlackWhite.setY(RfBY, RfWY);
      ReferenceBlackWhite.setCb(RfBCb, RfWCb);
      ReferenceBlackWhite.setCr(RfBCr, RfWCr);
      ifd.add(ReferenceBlackWhite); // 532

      TIFFYCbCrOutputStream ycbcros;
      if (jpegos == null) {
        ycbcros = new TIFFYCbCrOutputStream(os, width, ssv, ssh);
        os = new TIFFSubSamplingOutputStream(ycbcros, width, ssv, ssh);
      } else {
        ycbcros = new TIFFYCbCrOutputStream(os, width, 1, 1); // jpeg does own subsampling
        os = ycbcros;
      }

      ycbcros.setPositioning(1);
      ycbcros.setColourCoefficients(LumaRed, LumaGreen, LumaBlue);
      ycbcros.setRfBWY(RfBY, RfWY);
      ycbcros.setRfBWCb(RfBCb, RfWCb);
      ycbcros.setRfBWCr(RfBCr, RfWCr);

      WritableRaster raster = image.getRaster();
      DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
      int[] imgdata = (int[]) buffer.getData();

      int c = 0, index = 0;
      for (int y = 0; y < height; y += maxrps) {

        if ((height - y) < maxrps) {
          maxrps = height - y;
        }

        if (jpegos != null) {
          jpegos.startOfImage();
          int[] hv = {(ssh << 4) | ssv, 0x11, 0x11}; // (Hi<<4)|Vi
          int[] q = {0, 1, 1}; // quantization table Y=0, Cb=Cr=1
          //          jpegos.startOfFrame(((maxrps+ssv-1)/ssv)*ssv,ww,hv,q);
          jpegos.startOfFrame(maxrps, ww, hv, q);
          int[] sel = {0, 1, 1}; // DC,AC code table Y=0, Cb=Cr=1
          jpegos.startOfScan(sel);
        }

        for (int i = 0; i < maxrps; i++) {
          int x = 0;
          while (x < width) {
            c = imgdata[x + (y + i) * width];
            //            c = image.getRGB(x,y+i);
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
            x++;
          }
          while (x < ww) {
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
            x++;
          }
        }
        os.close();

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream
        baos.reset();
        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeYCbCrImage:\n\t" + e.getMessage());
    }
  }
Пример #13
0
  public void get_wallet_balance() { // **********************

    System.out.println("Get Balance...");

    rpcurl = lm.carbon_settings[10];

    rpcaddress = lm.rpcaddress_confirm;

    rpcuser = lm.carbon_settings[12];
    rpcpassword = lm.carbon_settings[13];

    System.out.println(rpcuser);
    System.out.println(rpcpassword);
    System.out.println(rpcaddress);

    String line = new String();
    String line2 = new String();

    String url1 =
        new String(
            "https://blockchain.info/merchant/"
                + rpcuser
                + "/address_balance?password="******"&address="
                + rpcaddress
                + "&confirmations=6");

    try {

      // Sets the authenticator that will be used by the networking code
      // when a proxy or an HTTP server asks for authentication.

      // Authenticator.setDefault(new CustomAuthenticator());
      System.out.println("GO0");

      URL url = new URL(url1);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

      System.out.println("GO1");

      // read text returned by server
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      // BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      // BufferedReader in = new BufferedReader(null);

      while ((line = in.readLine()) != null) {

        System.out.println(line);
        line2 = line2 + line;
      }

      in.close();

      JSONParser parser = new JSONParser();

      try {

        Object obj = parser.parse(line2);

        JSONObject jsonObject = (JSONObject) obj;

        String address = (String) jsonObject.get("address");
        System.out.println(address);

        String balance = (String) jsonObject.get("balance").toString();
        System.out.println(balance);
        lm.wallet_value_confirm = (long) Long.parseLong(balance);
        System.out.println("lm.wallet_value_confirm " + lm.wallet_value_confirm);

      } // try
      catch (ParseException e) {
        e.printStackTrace();
      }

    } // try
    catch (MalformedURLException e) {
      System.out.println("Malformed URL: " + e.getMessage());
    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  } // ***************test_for_sales()
Пример #14
0
  private IFD writeRGBImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_INT_RGB);
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(3);
      bpss.setBitsPerSample(0, 8); // red
      bpss.setBitsPerSample(1, 8); // green
      bpss.setBitsPerSample(2, 8); // blue
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(RGB)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      if (comp == JPEG) {
        maxrps = ((maxrps + 8 - 1) / 8) * 8;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(3)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279
      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStream os = baos;
      JPEGOutputStream jpegos = null;

      if (comp == JPEG) { // add JPEGTables tag
        jpegos = new JPEGOutputStream(baos);

        int quality = (param == null) ? 50 : (int) (param.getCompressionQuality() * 100);

        jpegos.setZZQuantizationTable(0, JPEGConstants.LQT, quality);
        jpegos.setRawDCHuffmanTable(0, JPEGConstants.HLDCTable);
        jpegos.setRawACHuffmanTable(0, JPEGConstants.HLACTable);

        jpegos.defineQuantizationTables();
        jpegos.defineHuffmanTables();
        jpegos.close();

        DEFactory.JPEGTablesDE jpegtables = new DEFactory.JPEGTablesDE(baos.toByteArray());
        ifd.add(jpegtables); // 347

        baos.reset();

        os = jpegos;
      }

      WritableRaster raster = image.getRaster();
      DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
      int[] imgdata = (int[]) buffer.getData();

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume rgb image.

        Each strip: evaluate r g b colour
                    save in byte array
                    write to image file
        */

        if ((height - y) < maxrps) {
          maxrps = height - y;
        }

        if (jpegos != null) { // jpeg: SOI,SOF,SOS marker
          jpegos.startOfImage();
          int[] hv = {0x11, 0x11, 0x11}; // (Hi<<4)|Vi
          int[] q = {0, 0, 0}; // quantization table 0
          jpegos.startOfFrame(maxrps, width, hv, q);
          int[] sel = {0, 0, 0}; // DC,AC code table 0
          jpegos.startOfScan(sel);
        }

        for (int i = 0; i < maxrps; i++) { // write RGB data
          for (int x = 0; x < width; x++) {
            int c = imgdata[x + (y + i) * width];
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
          }
        }
        os.close(); // jpeg: EOI marker

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream
        baos.reset();
        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeRGBImage:\n\t" + e.getMessage());
    }
  }
Пример #15
0
  private IFD writeCMYKImage(ImageOutputStream out, BufferedImage image, TIFFImageWriteParam param)
      throws IOException {
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(4);
      bpss.setBitsPerSample(0, 8); // cyan
      bpss.setBitsPerSample(1, 8); // magneta
      bpss.setBitsPerSample(2, 8); // yellow
      bpss.setBitsPerSample(3, 8); // key (black)
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(NOCOMPRESSION)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(CMYK)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(4)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279

      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume rgb image.

        Each strip: evaluate c m y k colour
                    save in byte array
                    write to image file
        */

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        for (int i = 0; i < maxrps; i++) {
          if ((y + i) == height) {
            break;
          } // last strip might have less rows
          for (int x = 0; x < width; x++) {
            int c = image.getRGB(x, y + i);

            int R = (c >> 16) & 0x00FF;
            int G = (c >> 8) & 0x00FF;
            int B = (c) & 0x00FF;

            if ((R == 255) && (G == 255) && (B == 255)) {
              baos.write(0);
              baos.write(0);
              baos.write(0);
              baos.write(0);
            } else {
              double C = 1.0 - R / 255.0;
              double M = 1.0 - G / 255.0;
              double Y = 1.0 - B / 255.0;

              double K = C;
              if (M < K) {
                K = M;
              }
              if (Y < K) {
                K = Y;
              }

              C = ((C - K) / (1.0 - K)) * 255.0;
              M = ((M - K) / (1.0 - K)) * 255.0;
              Y = ((Y - K) / (1.0 - K)) * 255.0;
              K *= 255.0;

              baos.write((int) C);
              baos.write((int) M);
              baos.write((int) Y);
              baos.write((int) K);
            }
          }
        }
        baos.close();

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream

        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeCMYKImage:\n\t" + e.getMessage());
    }
  }
Пример #16
0
    public void
        run() { // ************************************************************************************

      String jsonText2 = new String("");

      JSONObject obj_out = new JSONObject();

      ServerSocket welcomeSocket;

      while (true) {

        try { // *********************************************************

          welcomeSocket = new ServerSocket(network.api_port, 0, InetAddress.getByName("localhost"));
          Socket connectionSocket = welcomeSocket.accept();
          BufferedReader inFromClient =
              new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
          DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
          clientSentence = inFromClient.readLine();

          JSONParser parser = new JSONParser();

          try { // *********************************************************

            statex = "0";
            responsex = "e00";
            jsonText = "";

            if (!clientSentence.contains("")) {
              throw new EmptyStackException();
            }
            Object obj = parser.parse(clientSentence);

            jsonObject = (JSONObject) obj;

            String request = (String) jsonObject.get("request");

            String item_id = new String("");
            String item_array = new String("");
            String old_key = new String("");
            String node = new String("");
            try {
              item_id = (String) jsonObject.get("item_id").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_id...");
            }
            try {
              item_array = (String) jsonObject.get("item_array").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_array...");
            }
            try {
              old_key = (String) jsonObject.get("key").toString();
            } catch (Exception e) {
              System.out.println("extra info no key...");
            }
            try {
              node = (String) jsonObject.get("node").toString();
            } catch (Exception e) {
              System.out.println("extra info no node...");
            }

            while (network.database_in_use == 1 && !request.equals("status")) {

              System.out.println("Database in use...");
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
              }
            } // **************************************************************

            if (request.equals("status")) {
              statex = "1";
              responsex = get_status();
            } // ***************************
            else if (request.equals("get_version")) {
              statex = "1";
              responsex = network.versionx;
            } //
            else if (request.equals("get_tor_active")) {
              statex = "1";
              responsex = Integer.toString(network.tor_active);
            } //
            else if (request.equals("get_last_block")) {
              statex = "1";
              responsex = network.last_block_id;
            } //
            else if (request.equals("get_last_block_timestamp")) {
              statex = "1";
              responsex = network.last_block_timestamp;
            } //
            else if (request.equals("get_last_block_hash")) {
              statex = "1";
              responsex = network.last_block_idx;
            } //
            else if (request.equals("get_difficulty")) {
              statex = "1";
              responsex = Long.toString(network.difficultyx);
            } //
            else if (request.equals("get_last_mining_id")) {
              statex = "1";
              responsex = network.last_block_mining_idx;
            } //
            else if (request.equals("get_prev_mining_id")) {
              statex = "1";
              responsex = network.prev_block_mining_idx;
            } //
            else if (request.equals("get_last_unconfirmed_id")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_token_total")) {
              statex = "1";
              responsex = Integer.toString(network.database_listings_owner);
            } //
            else if (request.equals("get_my_id_list")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_ids_limit")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_token")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_settings")) {
              statex = "1";
              responsex = get_settings_array();
            } //
            else if (request.equals("get_mining_info")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_new_keys")) {
              statex = "1";
              responsex = build_keysx();
            } //
            else if (request.equals("delete_node")) {
              statex = "1";
              responsex = delete_node(node);
            } //
            else if (request.equals("delete_all_nodes")) {
              statex = "1";
              responsex = delete_all_nodes();
            } //
            else if (request.equals("set_new_node")) {
              statex = "1";
              responsex = set_new_node(node);
            } //
            else if (request.equals("set_old_key")) {
              statex = "1";
              responsex = set_old_key(old_key);
            } //
            else if (request.equals("set_new_block")) {
              statex = "1";
              responsex = set_new_block(item_array);
            } //
            else if (request.equals("set_edit_block")) {
              statex = "1";
              update_state = "set_edit_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("set_transfer_block")) {
              statex = "1";
              update_state = "set_transfer_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("system_restart")) {
              statex = "1";
              responsex = "restarting";
              toolkit = Toolkit.getDefaultToolkit();
              xtimerx = new Timer();
              xtimerx.schedule(new RemindTask_restart(), 0);
            } //
            else if (request.equals("system_exit")) {
              statex = "1";
              System.exit(0);
            } //
            else {
              statex = "0";
              responsex = "e01 UnknownRequestException";
            }

          } // try
          catch (ParseException e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e02 ParseException";
          } catch (Exception e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e03 Exception";
          }

          JSONObject obj = new JSONObject();
          obj.put("response", statex);
          try {
            obj.put("message", responsex);
          } catch (Exception e) {
            e.printStackTrace();
          }

          StringWriter outs = new StringWriter();
          obj.writeJSONString(outs);
          jsonText = outs.toString();
          System.out.println("SEND RESPONSE " + responsex);

          outToClient.writeBytes(jsonText + '\n');
          welcomeSocket.close();

        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Server ERROR x3");
        }
      } // **********while
    } // runx***************************************************************************************************
Пример #17
0
  private IFD writeBModHufImage(
      ImageOutputStream out, BufferedImage image, TIFFImageWriteParam param) throws IOException {
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257
      ifd.add(new DEFactory.CompressionDE(CCITTGROUP3MODHUFFMAN)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(WhiteIsZero)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per stripe
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279

      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume bilevel image (black/white[=-1])

        Each strip: count run length
                    encode into modified hufman codes
                    swap bits
                    save in byte array
                    write to image file
        */

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BitSwapOutputStream bsos = new BitSwapOutputStream(baos);
        ModHuffmanOutputStream mhos = new ModHuffmanOutputStream(bsos);

        RLEOutputStream rlos =
            new RLEOutputStream(mhos, 3); // rgb = 3 bytes per sample code word (not needed here)

        for (int i = 0; i < maxrps; i++) {
          if ((y + i) == height) {
            break;
          } // last strip might have less rows
          rlos.setStartCodeWord(-1); // white run first
          for (int x = 0; x < width; x++) {
            rlos.write(image.getRGB(x, y + i));
          }
          rlos.flush(); // write padding after ever image row
        }
        rlos.close();

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream

        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeBModHufImage:\n\t" + e.getMessage());
    }
  }
Пример #18
0
  public String update_token(String req_array) {

    System.out.println("Update");

    String jsonarry = new String("");

    try {

      JSONParser parser = new JSONParser();
      Object obj = parser.parse(req_array);
      JSONObject jsonObject = (JSONObject) obj;

      String id = (String) jsonObject.get("id");
      String hash_id = (String) jsonObject.get("hash_id");
      String sig_id = (String) jsonObject.get("sig_id");
      String date_id = (String) jsonObject.get("date_id");
      String owner_id = (String) jsonObject.get("owner_id");
      String owner_rating = (String) jsonObject.get("owner_rating");
      String currency = (String) jsonObject.get("currency");
      String custom_template = (String) jsonObject.get("custom_template");
      String custom_1 = (String) jsonObject.get("custom_1");
      String custom_2 = (String) jsonObject.get("custom_2");
      String custom_3 = (String) jsonObject.get("custom_3");
      String item_errors = (String) jsonObject.get("item_errors");
      String item_date_listed = (String) jsonObject.get("item_date_listed");
      String item_date_listed_day = (String) jsonObject.get("item_date_listed_da");
      String item_date_listed_int = (String) jsonObject.get("item_date_listed_int");
      String item_hits = (String) jsonObject.get("item_hits");
      String item_confirm_code = (String) jsonObject.get("item_confirm_code");
      String item_confirmed = (String) jsonObject.get("item_confirmed");
      String item_cost = (String) jsonObject.get("item_cost");
      String item_description = (String) jsonObject.get("item_description");
      String item_id = (String) jsonObject.get("item_id");
      String item_price = (String) jsonObject.get("item_price");
      String item_weight = (String) jsonObject.get("item_weight");
      String item_listing_id = (String) jsonObject.get("item_listing_id");
      String item_notes = (String) jsonObject.get("item_notes");
      String item_package_d = (String) jsonObject.get("item_package_d");
      String item_package_l = (String) jsonObject.get("item_package_l");
      String item_package_w = (String) jsonObject.get("item_package_w");
      String item_part_number = (String) jsonObject.get("item_part_number");
      String item_title = (String) jsonObject.get("item_title");
      String item_title_url = (String) jsonObject.get("item_title");
      String item_type = (String) jsonObject.get("item_type");
      String item_search_1 = (String) jsonObject.get("item_search_1");
      String item_search_2 = (String) jsonObject.get("item_search_2");
      String item_search_3 = (String) jsonObject.get("item_search_3");
      String item_site_id = (String) jsonObject.get("item_site_id");
      String item_site_url = (String) jsonObject.get("item_site_url");
      String item_picture_1 = (String) jsonObject.get("item_picture_1");
      String item_total_on_hand = (String) jsonObject.get("item_total_on_hand");
      String sale_payment_address = (String) jsonObject.get("sale_payment_address");
      String sale_payment_type = (String) jsonObject.get("sale_payment_type");
      String sale_fees = (String) jsonObject.get("sale_fees");
      String sale_id = (String) jsonObject.get("sale_id");
      String sale_seller_id = (String) jsonObject.get("sale_seller_id");
      String sale_status = (String) jsonObject.get("sale_status");
      String sale_tax = (String) jsonObject.get("sale_tax");
      String sale_shipping_company = (String) jsonObject.get("sale_shipping_company");
      String sale_shipping_in = (String) jsonObject.get("sale_shipping_in");
      String sale_shipping_out = (String) jsonObject.get("sale_shipping_out");
      String sale_source_of_sale = (String) jsonObject.get("sale_source_of_sale");
      String sale_total_sale_amount = (String) jsonObject.get("sale_total_sale_amount");
      String sale_tracking_number = (String) jsonObject.get("sale_tracking_number");
      String sale_transaction_id = (String) jsonObject.get("sale_transaction_id");
      String sale_transaction_info = (String) jsonObject.get("sale_transaction_info");
      String seller_address_1 = (String) jsonObject.get("seller_address_1");
      String seller_address_2 = (String) jsonObject.get("seller_address_2");
      String seller_address_city = (String) jsonObject.get("seller_address_city");
      String seller_address_state = (String) jsonObject.get("seller_address_state");
      String seller_address_zip = (String) jsonObject.get("seller_address_zip");
      String seller_address_country = (String) jsonObject.get("seller_address_country");
      String seller_id = (String) jsonObject.get("seller_id");
      String seller_ip = (String) jsonObject.get("seller_ip");
      String seller_email = (String) jsonObject.get("seller_email");
      String seller_first_name = (String) jsonObject.get("seller_first_name");
      String seller_last_name = (String) jsonObject.get("seller_last_name");
      String seller_notes = (String) jsonObject.get("seller_notes");
      String seller_phone = (String) jsonObject.get("seller_phone");
      String seller_logo = (String) jsonObject.get("seller_logo");
      String seller_url = (String) jsonObject.get("seller_url");

      try {
        if (currency.length() < 1) {}
      } catch (Exception e) {
        currency = new String("1");
      }
      try {
        if (custom_template.length() < 1) {}
      } catch (Exception e) {
        custom_template = new String("2");
      }
      try {
        if (custom_1.length() < 1) {}
      } catch (Exception e) {
        custom_1 = new String("3");
      }
      try {
        if (custom_2.length() < 1) {}
      } catch (Exception e) {
        custom_2 = new String("4");
      }
      try {
        if (custom_3.length() < 1) {}
      } catch (Exception e) {
        custom_3 = new String("5");
      }
      try {
        if (item_errors.length() < 1) {}
      } catch (Exception e) {
        item_errors = new String("6");
      }
      try {
        if (item_date_listed.length() < 1) {}
      } catch (Exception e) {
        item_date_listed = new String("7");
      }
      try {
        if (item_date_listed_day.length() < 1) {}
      } catch (Exception e) {
        item_date_listed_day = new String("8");
      }
      try {
        if (item_date_listed_int.length() < 1) {}
      } catch (Exception e) {
        item_date_listed_int = new String("9");
      }
      try {
        if (item_hits.length() < 1) {}
      } catch (Exception e) {
        item_hits = new String("10");
      }
      try {
        if (item_confirm_code.length() < 1) {}
      } catch (Exception e) {
        item_confirm_code = new String("11");
      }
      try {
        if (item_confirmed.length() < 1) {}
      } catch (Exception e) {
        item_confirmed = new String("12");
      }
      try {
        if (item_cost.length() < 1) {}
      } catch (Exception e) {
        item_cost = new String("13");
      }
      try {
        if (item_description.length() < 1) {}
      } catch (Exception e) {
        item_description = new String("14");
      }
      try {
        if (item_id.length() < 1) {}
      } catch (Exception e) {
        item_id = new String("15");
      }
      try {
        if (item_price.length() < 1) {}
      } catch (Exception e) {
        item_price = new String("16");
      }
      try {
        if (item_weight.length() < 1) {}
      } catch (Exception e) {
        item_weight = new String("17");
      }
      try {
        if (item_notes.length() < 1) {}
      } catch (Exception e) {
        item_notes = new String("18");
      }
      try {
        if (item_package_d.length() < 1) {}
      } catch (Exception e) {
        item_package_d = new String("19");
      }
      try {
        if (item_package_l.length() < 1) {}
      } catch (Exception e) {
        item_package_l = new String("20");
      }
      try {
        if (item_package_w.length() < 1) {}
      } catch (Exception e) {
        item_package_w = new String("21");
      }
      try {
        if (item_part_number.length() < 1) {}
      } catch (Exception e) {
        item_part_number = new String("22");
      }
      try {
        if (item_title.length() < 1) {}
      } catch (Exception e) {
        item_title = new String("23");
      }
      try {
        if (item_title_url.length() < 1) {}
      } catch (Exception e) {
        item_title_url = new String("24");
      }
      try {
        if (item_type.length() < 1) {}
      } catch (Exception e) {
        item_type = new String("25");
      }
      try {
        if (item_search_1.length() < 1) {}
      } catch (Exception e) {
        item_search_1 = new String("26");
      }
      try {
        if (item_search_2.length() < 1) {}
      } catch (Exception e) {
        item_search_2 = new String("27");
      }
      try {
        if (item_search_3.length() < 1) {}
      } catch (Exception e) {
        item_search_3 = new String("28");
      }
      try {
        if (item_site_url.length() < 1) {}
      } catch (Exception e) {
        item_site_url = new String("29");
      }
      try {
        if (item_picture_1.length() < 1) {}
      } catch (Exception e) {
        item_picture_1 = new String("30");
      }
      try {
        if (item_total_on_hand.length() < 1) {}
      } catch (Exception e) {
        item_total_on_hand = new String("31");
      }

      String tokenx[] = new String[network.listing_size];

      if (Integer.parseInt(id) >= network.base_int
          && Integer.parseInt(id) <= (network.hard_token_limit + network.base_int)) {

        krypton_database_get_token2 getxt = new krypton_database_get_token2();
        tokenx = getxt.get_token(id);

        // update the noose
        tokenx[3] = Long.toString(System.currentTimeMillis());

        tokenx[4] = network.settingsx[5];

        tokenx[6] = currency;
        tokenx[7] = custom_template;
        tokenx[8] = custom_1;
        tokenx[9] = custom_2;
        tokenx[10] = custom_3;
        tokenx[11] = item_errors;
        tokenx[12] = item_date_listed;
        tokenx[13] = item_date_listed_day;
        tokenx[14] = item_date_listed_int;
        tokenx[15] = item_hits;
        tokenx[16] = item_confirm_code;
        tokenx[17] = item_confirmed;
        tokenx[18] = item_cost;
        tokenx[19] = item_description;
        tokenx[20] = item_id;
        tokenx[21] = item_price;
        tokenx[22] = item_weight;

        tokenx[24] = item_notes;
        tokenx[25] = item_package_d;
        tokenx[26] = item_package_l;
        tokenx[27] = item_package_w;
        tokenx[28] = item_part_number;
        tokenx[29] = item_title;
        tokenx[30] = item_title_url;
        tokenx[31] = item_type;
        tokenx[32] = item_search_1;
        tokenx[33] = item_search_2;
        tokenx[34] = item_search_3;

        tokenx[36] = item_site_url;
        tokenx[37] = item_picture_1;
        tokenx[38] = item_total_on_hand;

        // to help with search
        tokenx[30] = tokenx[29].toLowerCase();

        // base 58
        if (update_state.equals("set_edit_block")) {
          tokenx[60] = network.base58_id;
        } else if (update_state.equals("set_transfer_block")) {
          tokenx[60] = seller_id;
        }

        // seller info
        tokenx[63] = network.settingsx[11]; // name
        tokenx[64] = network.settingsx[12]; // last
        tokenx[54] = network.settingsx[13]; // address
        tokenx[55] = network.settingsx[14]; // address2
        tokenx[56] = network.settingsx[15]; // city
        tokenx[57] = network.settingsx[16]; // state
        tokenx[58] = network.settingsx[17]; // zip
        tokenx[59] = network.settingsx[18]; // country

        tokenx[39] = network.settingsx[19]; // btc
        tokenx[62] = network.settingsx[20]; // email
        tokenx[66] = network.settingsx[21]; // phone
        tokenx[68] = network.settingsx[22]; // website

        // sign

        try {

          String build_hash = new String("");

          build_hash = tokenx[0];
          for (int loop = 3; loop < tokenx.length; loop++) {

            build_hash = build_hash + tokenx[loop]; // save everything else
          } // *************************************************

          String hashx = new String(build_hash);
          byte[] sha256_1x = MessageDigest.getInstance("SHA-256").digest(hashx.getBytes());
          System.out.println(Base64.toBase64String(sha256_1x));

          tokenx[1] = Base64.toBase64String(sha256_1x);

          byte[] message = Base64.toBase64String(sha256_1x).getBytes("UTF8");

          byte[] clear = Base64.decode(network.settingsx[4]);
          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
          KeyFactory fact = KeyFactory.getInstance("RSA");
          PrivateKey priv = fact.generatePrivate(keySpec);
          Arrays.fill(clear, (byte) 0);

          Signature sigx = Signature.getInstance("SHA1WithRSA"); // MD5WithRSA
          sigx.initSign(priv);
          sigx.update(message);
          byte[] signatureBytesx = sigx.sign();
          // System.out.println("Public: " + Base64.toBase64String(pub.getEncoded()));
          System.out.println("Singature: " + Base64.toBase64String(signatureBytesx));

          String signxx = Base64.toBase64String(signatureBytesx);

          tokenx[2] = signxx;

          byte[] keyxb3 = Base64.decode(tokenx[4]);

          X509EncodedKeySpec keySpecx3 = new X509EncodedKeySpec(keyxb3);
          KeyFactory factx3 = KeyFactory.getInstance("RSA");
          PublicKey pubx3 = factx3.generatePublic(keySpecx3);
          Arrays.fill(keyxb3, (byte) 0);

          Signature sigpk3 = Signature.getInstance("SHA1WithRSA"); // MD5WithRSA
          byte[] messagex3 = Base64.toBase64String(sha256_1x).getBytes("UTF8");

          byte[] signatureBytesx3 = Base64.decode(signxx);

          sigpk3.initVerify(pubx3);
          sigpk3.update(messagex3);

          boolean testsx = sigpk3.verify(signatureBytesx3);

          System.out.println("testsx " + testsx);

          if (testsx) {

            statex = "1";
            jsonarry = "Updated";

          } // ********
          else {

            statex = "0";
            jsonarry = "Update error. Information did not pass signature test.";
          } // **

          if (update_state.equals("set_edit_block")) {
            network.icon.displayMessage(
                "Krypton", "Token updated ID (" + tokenx[0] + ")", TrayIcon.MessageType.INFO);
          } else if (update_state.equals("set_transfer_block")) {
            network.icon.displayMessage(
                "Krypton", "Token transfer ID (" + tokenx[0] + ")", TrayIcon.MessageType.INFO);
          }

          // send the update
          tokenx_buffer = tokenx;
          toolkit = Toolkit.getDefaultToolkit();
          xtimerx = new Timer();
          xtimerx.schedule(new RemindTask_send_update(), 0);
          // send the update

        } catch (Exception e) {
          e.printStackTrace();
        }

      } // if
      else {
        System.out.println("Update item error cannot find item.");
        statex = "0";
        jsonarry = "Update item error cannot find item.";
      }

    } catch (Exception e) {
      e.printStackTrace();
      statex = "0";
      jsonarry = "Error";
    } // *****************

    return jsonarry;
  } // *****************
Пример #19
0
  public String get_item_array(String id) {

    String jsonarry;

    try {

      krypton_database_get_token getxt = new krypton_database_get_token();

      String token_array[] = new String[network.listing_size];
      token_array = getxt.get_token(id);

      JSONObject obj = new JSONObject();

      obj.put("id", token_array[0]);
      obj.put("hash_id", token_array[1]);
      obj.put("sig_id", token_array[2]);
      obj.put("date_id", token_array[3]);
      obj.put("owner_id", token_array[4]);
      obj.put("owner_rating", token_array[5]);
      obj.put("currency", token_array[6]);
      obj.put("custom_template", token_array[7]);
      obj.put("custom_1", token_array[8]);
      obj.put("custom_2", token_array[9]);
      obj.put("custom_3", token_array[10]);
      obj.put("item_errors", token_array[11]);
      obj.put("item_date_listed", token_array[12]);
      obj.put("item_date_listed_day", token_array[13]);
      obj.put("item_date_listed_int", token_array[14]);
      obj.put("item_hits", token_array[15]);
      obj.put("item_confirm_code", token_array[16]);
      obj.put("item_confirmed", token_array[17]);
      obj.put("item_cost", token_array[18]);
      obj.put("item_description", token_array[19]);
      obj.put("item_id", token_array[20]);
      obj.put("item_price", token_array[21]);
      obj.put("item_weight", token_array[22]);
      obj.put("item_listing_id", token_array[23]);
      obj.put("item_notes", token_array[24]);
      obj.put("item_package_d", token_array[25]);
      obj.put("item_package_l", token_array[26]);
      obj.put("item_package_w", token_array[27]);
      obj.put("item_part_number", token_array[28]);
      obj.put("item_title", token_array[29]);
      obj.put("item_title_url", token_array[30]);
      obj.put("item_type", token_array[31]);
      obj.put("item_search_1", token_array[32]);
      obj.put("item_search_2", token_array[33]);
      obj.put("item_search_3", token_array[34]);
      obj.put("item_site_id", token_array[35]);
      obj.put("item_site_url", token_array[36]);
      obj.put("item_picture_1", token_array[37]);
      obj.put("item_total_on_hand", token_array[38]);
      obj.put("sale_payment_address", token_array[39]);
      obj.put("sale_payment_type", token_array[40]);
      obj.put("sale_fees", token_array[41]);
      obj.put("sale_id", token_array[42]);
      obj.put("sale_seller_id", token_array[43]);
      obj.put("sale_status", token_array[44]);
      obj.put("sale_tax", token_array[45]);
      obj.put("sale_shipping_company", token_array[46]);
      obj.put("sale_shipping_in", token_array[47]);
      obj.put("sale_shipping_out", token_array[48]);
      obj.put("sale_source_of_sale", token_array[49]);
      obj.put("sale_total_sale_amount", token_array[50]);
      obj.put("sale_tracking_number", token_array[51]);
      obj.put("sale_transaction_id", token_array[52]);
      obj.put("sale_transaction_info", token_array[53]);
      obj.put("seller_address_1", token_array[54]);
      obj.put("seller_address_2", token_array[55]);
      obj.put("seller_address_city", token_array[56]);
      obj.put("seller_address_state", token_array[57]);
      obj.put("seller_address_zip", token_array[58]);
      obj.put("seller_address_country", token_array[59]);
      obj.put("seller_id", token_array[60]);
      obj.put("seller_ip", token_array[61]);
      obj.put("seller_email", token_array[62]);
      obj.put("seller_first_name", token_array[63]);
      obj.put("seller_last_name", token_array[64]);
      obj.put("seller_notes", token_array[65]);
      obj.put("seller_phone", token_array[66]);
      obj.put("seller_logo", token_array[67]);
      obj.put("seller_url", token_array[68]);

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      String jsonText = out.toString();
      System.out.println(jsonText);

      jsonarry = JSONValue.toJSONString(obj);

    } catch (Exception e) {

      e.printStackTrace();
      statex = "0";
      jsonarry = "Error";
    } // *****************

    return jsonarry;
  } // *************************************
Пример #20
0
  /**
   * Convert an image to RGB.
   *
   * @param inFile the file to convert.
   * @param outFile the output file, which may be same as inFile.
   * @return the static status result
   */
  public static AnonymizerStatus convert(File inFile, File outFile) {

    long fileLength = inFile.length();
    logger.debug("Entering DICOMPaletteImageConverter.convert");
    logger.debug("File length       = " + fileLength);

    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    File tempFile = null;
    byte[] buffer = new byte[4096];
    try {
      // Check that this is a known format.
      in = new BufferedInputStream(new FileInputStream(inFile));
      DcmParser parser = pFact.newDcmParser(in);
      FileFormat fileFormat = parser.detectFileFormat();
      if (fileFormat == null) {
        throw new IOException("Unrecognized file format: " + inFile);
      }

      // Get the dataset (excluding pixels) and leave the input stream open
      Dataset dataset = oFact.newDataset();
      parser.setDcmHandler(dataset.getDcmHandler());
      parser.parseDcmFile(fileFormat, Tags.PixelData);

      // Make sure this is an image
      if (parser.getReadTag() != Tags.PixelData) {
        close(in);
        return AnonymizerStatus.SKIP(inFile, "Not an image");
      }

      // Get the required parameters and make sure they are okay
      int numberOfFrames = getInt(dataset, Tags.NumberOfFrames, 1);
      int rows = getInt(dataset, Tags.Rows, 0);
      int columns = getInt(dataset, Tags.Columns, 0);
      String photometricInterpretation = getString(dataset, Tags.PhotometricInterpretation, "");
      if ((rows == 0) || (columns == 0)) {
        close(in);
        return AnonymizerStatus.SKIP(inFile, "Unable to get the rows and columns");
      }
      if (!photometricInterpretation.equals("PALETTE COLOR")) {
        close(in);
        return AnonymizerStatus.SKIP(
            inFile, "Unsupported PhotometricInterpretation: " + photometricInterpretation);
      }
      if (parser.getReadTag() != Tags.PixelData) {
        close(in);
        return AnonymizerStatus.SKIP(inFile, "No pixels");
      }

      // Get the encoding and set the parameters
      DcmDecodeParam fileParam = parser.getDcmDecodeParam();
      String fileEncodingUID = UIDs.ImplicitVRLittleEndian;
      FileMetaInfo fmi = dataset.getFileMetaInfo();
      if (fmi != null) fileEncodingUID = fmi.getTransferSyntaxUID();
      boolean isBigEndian = fileEncodingUID.equals(UIDs.ExplicitVRBigEndian);
      String encodingUID = UIDs.ExplicitVRLittleEndian;
      DcmEncodeParam encoding = (DcmEncodeParam) DcmDecodeParam.valueOf(encodingUID);
      boolean swap = (fileParam.byteOrder != encoding.byteOrder);

      if (encoding.encapsulated) {
        logger.debug("Encapsulated pixel data found");
        close(in);
        return AnonymizerStatus.SKIP(inFile, "Encapsulated pixel data not supported");
      }

      // Get the LUTs
      LUT red =
          new LUT(
              dataset.getInts(Tags.RedPaletteColorLUTDescriptor),
              dataset.getInts(Tags.RedPaletteColorLUTData));
      LUT green =
          new LUT(
              dataset.getInts(Tags.GreenPaletteColorLUTDescriptor),
              dataset.getInts(Tags.GreenPaletteColorLUTData));
      LUT blue =
          new LUT(
              dataset.getInts(Tags.BluePaletteColorLUTDescriptor),
              dataset.getInts(Tags.BluePaletteColorLUTData));

      // Set the PlanarConfiguration to 0
      dataset.putUS(Tags.PlanarConfiguration, 0);

      // Set the PhotometricInterpretation to RGB
      dataset.putCS(Tags.PhotometricInterpretation, "RGB");

      // Set the pixel parameters
      dataset.putUS(Tags.SamplesPerPixel, 3);
      dataset.putUS(Tags.BitsAllocated, 8);
      dataset.putUS(Tags.BitsStored, 8);
      dataset.putUS(Tags.HighBit, 7);

      // Remove the lookup tables and their descriptors
      dataset.remove(Tags.RedPaletteColorLUTDescriptor);
      dataset.remove(Tags.GreenPaletteColorLUTDescriptor);
      dataset.remove(Tags.BluePaletteColorLUTDescriptor);
      dataset.remove(Tags.RedPaletteColorLUTData);
      dataset.remove(Tags.GreenPaletteColorLUTData);
      dataset.remove(Tags.BluePaletteColorLUTData);

      // Save the dataset to a temporary file, and rename at the end.
      File tempDir = outFile.getParentFile();
      tempFile = File.createTempFile("DCMtemp-", ".anon", tempDir);
      out = new BufferedOutputStream(new FileOutputStream(tempFile));

      // Create and write the metainfo for the encoding we are using
      fmi = oFact.newFileMetaInfo(dataset, encodingUID);
      dataset.setFileMetaInfo(fmi);
      fmi.write(out);

      // Write the dataset as far as was parsed
      dataset.writeDataset(out, encoding);

      // Process the pixels
      int nPixels = numberOfFrames * rows * columns;
      int nPixelBytes = nPixels * 3 /*samplesPerPixel*/;
      int pad = nPixelBytes & 1;
      dataset.writeHeader(out, encoding, parser.getReadTag(), VRs.OB, nPixelBytes + pad);

      int pd;
      int b1, b2;
      int bytesPerFrame = rows * columns * 2;
      byte[] frameBytes = new byte[bytesPerFrame];
      for (int frame = 0; frame < numberOfFrames; frame++) {
        if (in.read(frameBytes, 0, frameBytes.length) != bytesPerFrame)
          throw new Exception("End of File");
        for (int p = 0; p < bytesPerFrame; ) {
          b1 = frameBytes[p++];
          b2 = frameBytes[p++];
          if (!swap) {
            pd = ((b2 & 0xff) << 8) | (b1 & 0xff);
          } else {
            pd = ((b1 & 0xff) << 8) | (b2 & 0xff);
          }
          out.write(red.get(pd));
          out.write(green.get(pd));
          out.write(blue.get(pd));
        }
      }
      if (pad != 0) out.write(0);
      logger.debug("Finished writing the pixels");

      // Skip everything after the pixels
      out.flush();
      out.close();
      in.close();
      outFile.delete();
      tempFile.renameTo(outFile);
      return AnonymizerStatus.OK(outFile, "");
    } catch (Exception e) {
      logger.debug("Exception while processing image.", e);

      // Close the input stream if it actually got opened.
      close(in);

      // Close the output stream if it actually got opened,
      // and delete the tempFile in case it is still there.
      try {
        if (out != null) {
          out.close();
          tempFile.delete();
        }
      } catch (Exception ex) {
        logger.warn("Unable to close the output stream.");
      }

      // Quarantine the object
      return AnonymizerStatus.QUARANTINE(inFile, e.getMessage());
    }
  }
Пример #21
0
  // Thread's run method aimed at creating a bitmap asynchronously
  public void run() {
    Drawing drawing = new Drawing();
    PicText rawPicText = new PicText();
    String s = ((PicText) element).getText();
    rawPicText.setText(s);
    drawing.add(
        rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former
                     // parent... (then pb with the view )
    drawing.setNotparsedCommands(
        "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{"
            + s
            + "}"
            + CR_LF
            + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight,  \\the\\jpicdepth }"
            + CR_LF);
    RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION;
    // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun);
    boolean isWriteTmpTeXfile = true;
    String bitmapExt = "png"; // [pending] preferences
    String cmdLine =
        "{i}/unix/tetex/create_bitmap.sh {p} {f} "
            + bitmapExt
            + " "
            + fileDPI; // [pending] preferences
    ContentType contentType = getContainer().getContentType();
    RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug
    RunExternalCommand command =
        new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile);
    command
        .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX
                // process has completed)

    if (wantToComputeLatexDimensions) {
      // load size of text:
      try {
        File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log");
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(logFile));
        } catch (FileNotFoundException fnfe) {
          System.out.println("Cannot find log file! " + fnfe.getMessage());
          System.out.println(logFile);
        } catch (IOException ioex) {
          System.out.println("Log file IO exception");
          ioex.printStackTrace();
        } // utile ?
        System.out.println("Log file created! file=" + logFile);
        getDimensionsFromLogFile(reader, (PicText) element);
        syncStringLocation(); // update dimensions
        syncBounds();
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that dimensions are available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (wantToGetBitMap) {
      // load image:
      try {
        File bitmapFile =
            new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt);
        this.image = ImageIO.read(bitmapFile);
        System.out.println(
            "Bitmap created! file="
                + bitmapFile
                + ", width="
                + image.getWidth()
                + "pixels, height="
                + image.getHeight()
                + "pixels");
        if (image == null) return;
        syncStringLocation(); // sets strx, stry, and dimensions of text
        syncBounds();
        // update the AffineTransform that will be applied to the bitmap before displaying on screen
        PicText te = (PicText) element;
        text2ModelTr.setToIdentity(); // reset
        PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
        text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
        text2ModelTr.translate(te.getLeftX(), te.getTopY());
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
        // [pending]  should do something special to avoid dividing by 0 or setting a rescaling
        // factor to 0 [non invertible matrix] (java will throw an exception)
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that bitmap is available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Пример #22
0
  public void write() {

    int navg = 8;
    //		int nshift=3;
    bookend = 8;

    numPgs = pdffile.getNumPages();

    files = new File[numPgs];

    int[] pixelsi = null;
    long[] sum = null;
    long[][] hist = null;
    BufferedImage bimage = null;

    //		BufferedImage simage = null;
    //	    float data[] = { 0.0625f, 0.125f, 0.0625f, 0.125f, 0.25f, 0.125f,
    //	            0.0625f, 0.125f, 0.0625f };
    //	    Kernel kernel = new Kernel(3, 3, data);
    //	    ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);

    done(0);
    for (int i = 0; i < numPgs; i++) {
      if (i > MAXPAGE) break;
      PDFPage page = getPage(i);
      if (i == 0) {
        w = (int) page.getBBox().getWidth();
        h = (int) page.getBBox().getHeight();
        rect = new Rectangle(0, 0, w, h);
        // w /= 2; h /=2;
        bimage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
        // simage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
        pixelsi = new int[h * w];
        sum = new long[h * w];
        hist = new long[navg][h * w];
        for (int j = 0; j < h * w; j++) {
          sum[j] = 0;
        }
        page1.countDown();
      }

      // generate page image
      Image image = pdffile.getPage(i).getImage(w, h, rect, null, true, true);
      // force complete loading
      image = new ImageIcon(image).getImage();
      // Copy image to buffered image
      Graphics g = bimage.createGraphics();
      // Paint the image onto the buffered image
      g.drawImage(image, 0, 0, null);
      g.dispose();

      // extract pixels into array
      bimage.getRGB(0, 0, w, h, pixelsi, 0, w);
      // Accumulate rolling averages
      int im = i % navg;
      int ii = i - navg / 2; // middle of averaging range
      for (int j = 0; j < h * w; j++) {
        int p = pixelsi[j], q = 0;

        // Expand packed 8x3 pixel to 16x3
        long r = 0, r2 = 0;
        r |= (p & 0xff);
        r <<= 16;
        p >>= 8;
        r |= (p & 0xff);
        r <<= 16;
        p >>= 8;
        r |= (p & 0xff);
        r = ~r;
        sum[j] += r; // rolling sum
        if (i >= navg) { // we have enough to average
          sum[j] -= hist[im][j]; // roll off the old
          hist[im][j] = r;
          r2 = (3 * sum[j] / navg + r) / 4;
          r = ~r2;
        } else {
          hist[im][j] = r;
        }

        // Repack averaged pixel
        q |= (r & 0xff);
        q <<= 8;
        r >>= 16;
        q |= (r & 0xff);
        q <<= 8;
        r >>= 16;
        q |= (r & 0xff);

        //	Average over number of images frames with a non-background pixel in this location.
        //  Note that we sum in complement space, so background is zero.
        //				if(i>=navg)
        //				nfg[j] -= fghist[im][j];
        //			nfg[j] += (fghist[im][j] = (q==-1) ? 0 : 1);
        //
        //				// If all pixels in history were background, this is easy...
        //				if(nfg[j]==0)
        //					q = -1;
        //
        //				else {
        //
        //					if(i>=navg) sum[k]-=hist[im][k];
        //					hist[im][k] = ~(p&0xff);
        //					sum[k] += hist[im][k];
        //					if(i>=navg)
        //						q += ~(((sum[k]/nfg[j])*3 + hist[iim][k])>>2);
        //					else if(i>=navg/2)
        //						q += ~(sum[k]/nfg[j] + hist[i-navg/2][k])>>1;
        //					else
        //						q += ~(sum[k]/nfg[j]);
        //					k++; q<<=8; p>>=8;
        //
        //					if(i>=navg) sum[k]-=hist[im][k];
        //					hist[im][k] = ~(p&0xff);
        //					sum[k] += hist[im][k];
        //					if(i>=navg)
        //						q += ~(((sum[k]/nfg[j])*3 + hist[iim][k])>>2);
        //				else if(i>=navg/2)
        //				q += ~((sum[k]/nfg[j] + hist[i-navg/2][k])>>1);
        //			else
        //				q += ~(sum[k]/nfg[j]);
        //			k++; q<<=8; p>>=8;
        //
        //					if(i>=navg) sum[k]-=hist[im][k];
        //					hist[im][k] = ~(p&0xff);
        //					sum[k] += hist[im][k];
        //					if(i>=navg)
        //						q += ~(((sum[k]/nfg[j])*3 + hist[iim][k])>>2);
        //					else if(i>=navg/2)
        //						q += ~((sum[k]/nfg[j] + hist[i-navg/2][k])>>1);
        //					else
        //						q += ~(sum[k]/nfg[j]);
        //					k++;
        //				}

        pixelsi[j] = q;
      }

      bimage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
      bimage.setRGB(0, 0, w, h, pixelsi, 0, w);

      // save it as a file
      if (i >= navg) {
        try {
          ImageIO.write(bimage, "png", imageFile(0, ii + 1));
        } catch (Exception e) {
          throw new RuntimeException(e.getMessage());
        }
      }

      done(ii + 1);
      // System.err.println("Page " + i + " " + (System.currentTimeMillis()-t0)/1000.);

      if (terminated) {
        System.err.println("Prematurely terminated");
        for (File f : files) f.delete();
        tmpdir.delete();
        break;
      }
    }
  }