コード例 #1
0
ファイル: DownloadPictures.java プロジェクト: joshhazel/mage
  @Override
  public void run() {
    this.cardIndex = 0;

    File base = new File(Constants.IO.imageBaseDir);
    if (!base.exists()) {
      base.mkdir();
    }

    Connection.ProxyType configProxyType =
        Connection.ProxyType.valueByText(
            PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None"));

    Proxy.Type type = Proxy.Type.DIRECT;
    switch (configProxyType) {
      case HTTP:
        type = Proxy.Type.HTTP;
        break;
      case SOCKS:
        type = Proxy.Type.SOCKS;
        break;
      case NONE:
      default:
        p = Proxy.NO_PROXY;
        break;
    }

    if (type != Proxy.Type.DIRECT) {
      try {
        String address = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_ADDRESS, "");
        Integer port =
            Integer.parseInt(
                PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_PORT, "80"));
        p = new Proxy(type, new InetSocketAddress(address, port));
      } catch (Exception ex) {
        throw new RuntimeException("Gui_DownloadPictures : error 1 - " + ex);
      }
    }

    if (p != null) {
      HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls();

      ArrayList<CardDownloadData> cardsToDownload = this.checkBox.isSelected() ? type2cards : cards;

      update(0, cardsToDownload.size());

      for (int i = 0; i < cardsToDownload.size() && !cancel; i++) {
        try {

          CardDownloadData card = cardsToDownload.get(i);

          log.info("Downloading card: " + card.getName() + " (" + card.getSet() + ")");

          String url;
          if (ignoreUrls.contains(card.getSet()) || card.isToken()) {
            if (card.getCollectorId() != 0) {
              continue;
            }
            url = cardImageSource.generateTokenUrl(card);
          } else {
            url = cardImageSource.generateURL(card);
          }

          if (url != null) {
            Logger.getLogger(this.getClass()).info(url);
            Runnable task = new DownloadTask(card, new URL(url), cardsToDownload.size());
            executor.execute(task);
          } else {
            synchronized (sync) {
              update(cardIndex + 1, cardsToDownload.size());
            }
          }

        } catch (Exception ex) {
          log.error(ex, ex);
        }
      }
      executor.shutdown();
      while (!executor.isTerminated()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ie) {
        }
      }
    }
    try {
      TVFS.umount();
    } catch (FsSyncException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null, "Couldn't unmount zip files", "Error", JOptionPane.ERROR_MESSAGE);
    } finally {
      System.gc();
    }
    closeButton.setText("Close");
  }
コード例 #2
0
ファイル: DownloadPictures.java プロジェクト: joshhazel/mage
    @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);
      }
    }
コード例 #3
0
ファイル: DownloadPictures.java プロジェクト: joshhazel/mage
  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<String>();
    type2SetsFilter.addAll(ConstructedFormats.getSetsByFormat(ConstructedFormats.STANDARD));

    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!");
            log.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!");
            log.error("Card has no set name and won't be sent to client:" + card);
          }
        }
      }

      allCardsUrls.addAll(getTokenCardUrls());
    } catch (Exception e) {
      log.error(e);
    }

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

    for (CardDownloadData card : cardsToDownload) {
      if (card.isToken()) {
        log.info("Card to download: " + card.getName() + " (Token) ");
      } else {
        try {
          log.info("Card to download: " + card.getName() + " (" + card.getSet() + ")");
        } catch (Exception e) {
          log.error(e);
        }
      }
    }

    return cardsToDownload;
  }