Example #1
0
  private void update(int card, int count) {
    this.cardIndex = card;

    if (cardIndex < count) {
      float mb = ((count - card) * cardImageSource.getAverageSize()) / 1024;
      bar.setString(
          String.format("%d of %d cards finished! Please wait! [%.1f Mb]", card, count, mb));
    } else {
      Iterator<CardDownloadData> cardsIterator = DownloadPictures.this.cards.iterator();
      while (cardsIterator.hasNext()) {
        CardDownloadData cardDownloadData = cardsIterator.next();
        TFile file = new TFile(CardImageUtils.generateImagePath(cardDownloadData));
        if (file.exists()) {
          cardsIterator.remove();
        }
      }
      count = DownloadPictures.this.cards.size();

      if (count == 0) {
        bar.setString("0 cards remaining! Please close!");
      } else {
        bar.setString(String.format("%d cards remaining! Please choose another source!", count));
        startDownloadButton.setEnabled(true);
      }
    }
  }
Example #2
0
 public static boolean checkForNewCards(List<CardInfo> allCards) {
   TFile file;
   for (CardInfo card : allCards) {
     if (card.getCardNumber() > 0 && !card.getSetCode().isEmpty()) {
       CardDownloadData url =
           new CardDownloadData(
               card.getName(),
               card.getSetCode(),
               card.getCardNumber(),
               card.usesVariousArt(),
               0,
               "",
               false,
               card.isDoubleFaced(),
               card.isNightCard());
       file = new TFile(CardImageUtils.generateImagePath(url));
       if (!file.exists()) {
         return true;
       }
     }
   }
   return false;
 }
Example #3
0
    @Override
    public void run() {
      StringBuilder filePath = new StringBuilder();
      File temporaryFile = null;
      TFile outputFile = null;
      try {
        filePath.append(Constants.IO.imageBaseDir);
        filePath
            .append(card.hashCode())
            .append(".")
            .append(card.getName().replace(":", "").replace("//", "-"))
            .append(".jpg");
        temporaryFile = new File(filePath.toString());
        String imagePath = CardImageUtils.generateImagePath(card);
        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);
        setUpConnection(httpConn);

        httpConn.connect();
        int responseCode = ((HttpURLConnection) httpConn).getResponseCode();
        if (responseCode == 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);
          }
        } else {
          logger.warn(
              "Image download for "
                  + card.getName()
                  + (!card.getDownloadName().equals(card.getName())
                      ? " downloadname: " + card.getDownloadName()
                      : "")
                  + "("
                  + card.getSet()
                  + ") failed - responseCode: "
                  + responseCode
                  + " url: "
                  + url.toString());
          if (logger
              .isDebugEnabled()) { // Shows the returned html from the request to the web server
            logger.debug(
                "Return ed HTML ERROR:\n"
                    + convertStreamToString(((HttpURLConnection) httpConn).getErrorStream()));
          }
        }

      } catch (AccessDeniedException e) {
        logger.error(
            "The file "
                + (outputFile != null
                    ? outputFile.toString()
                    : "to add the image of " + card.getName() + "(" + card.getSet() + ")")
                + " can't be accessed. Try rebooting your system to remove the file lock.");
      } catch (Exception e) {
        logger.error(e, e);
      } finally {
        if (temporaryFile != null) {
          temporaryFile.delete();
        }
      }
      synchronized (sync) {
        update(cardIndex + 1, count);
      }
    }
Example #4
0
  private static ArrayList<CardDownloadData> getNeededCards(List<CardInfo> allCards) {

    ArrayList<CardDownloadData> cardsToDownload = new ArrayList<>();

    /** read all card names and urls */
    ArrayList<CardDownloadData> allCardsUrls = new ArrayList<>();
    HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls();

    /** get filter for Standard Type 2 cards */
    Set<String> type2SetsFilter = new HashSet<>();
    List<String> constructedFormats =
        ConstructedFormats.getSetsByFormat(ConstructedFormats.STANDARD);
    if (constructedFormats != null && !constructedFormats.isEmpty()) {
      type2SetsFilter.addAll(constructedFormats);
    } else {
      logger.warn("No formats defined. Try connecting to a server first!");
    }

    int numberCardImages = allCards.size();

    try {
      offlineMode = true;

      for (CardInfo card : allCards) {
        if (card.getCardNumber() > 0
            && !card.getSetCode().isEmpty()
            && !ignoreUrls.contains(card.getSetCode())) {
          String cardName = card.getName();
          CardDownloadData url =
              new CardDownloadData(
                  cardName,
                  card.getSetCode(),
                  card.getCardNumber(),
                  card.usesVariousArt(),
                  0,
                  "",
                  false,
                  card.isDoubleFaced(),
                  card.isNightCard());
          if (url.getUsesVariousArt()) {
            url.setDownloadName(createDownloadName(card));
          }

          url.setFlipCard(card.isFlipCard());
          url.setSplitCard(card.isSplitCard());

          if (type2SetsFilter.contains(card.getSetCode())) {
            url.setType2(true);
          }

          allCardsUrls.add(url);
          if (card.isDoubleFaced()) {
            if (card.getSecondSideName() == null || card.getSecondSideName().trim().isEmpty()) {
              throw new IllegalStateException("Second side card can't have empty name.");
            }
            url =
                new CardDownloadData(
                    card.getSecondSideName(),
                    card.getSetCode(),
                    card.getCardNumber(),
                    card.usesVariousArt(),
                    0,
                    "",
                    false,
                    card.isDoubleFaced(),
                    true);
            allCardsUrls.add(url);
          }
          if (card.isFlipCard()) {
            if (card.getFlipCardName() == null || card.getFlipCardName().trim().isEmpty()) {
              throw new IllegalStateException("Flipped card can't have empty name.");
            }
            url =
                new CardDownloadData(
                    card.getFlipCardName(),
                    card.getSetCode(),
                    card.getCardNumber(),
                    card.usesVariousArt(),
                    0,
                    "",
                    false,
                    card.isDoubleFaced(),
                    card.isNightCard());
            url.setFlipCard(true);
            url.setFlippedSide(true);
            allCardsUrls.add(url);
          }
        } else if (card.getCardNumber() < 1) {
          System.err.println("There was a critical error!");
          logger.error("Card has no collector ID and won't be sent to client: " + card);
        } else if (card.getSetCode().isEmpty()) {
          System.err.println("There was a critical error!");
          logger.error("Card has no set name and won't be sent to client:" + card);
        }
      }
      allCardsUrls.addAll(getTokenCardUrls());

    } catch (Exception e) {
      logger.error(e);
    }
    int numberTokenImages = allCardsUrls.size() - numberCardImages;
    TFile file;

    /** check to see which cards we already have */
    for (CardDownloadData card : allCardsUrls) {
      file = new TFile(CardImageUtils.generateImagePath(card));
      if (!file.exists()) {
        cardsToDownload.add(card);
      }
    }

    logger.info(
        "Check download images (total cards: "
            + numberCardImages
            + ", total tokens: "
            + numberTokenImages
            + ") => Missing images: "
            + cardsToDownload.size());
    if (logger.isDebugEnabled()) {
      for (CardDownloadData card : cardsToDownload) {
        if (card.isToken()) {
          logger.debug("Card to download: " + card.getName() + " (Token) ");
        } else {
          try {
            logger.debug("Card to download: " + card.getName() + " (" + card.getSet() + ")");
          } catch (Exception e) {
            logger.error(e);
          }
        }
      }
    }

    return cardsToDownload;
  }
Example #5
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);
      }
    }