Merge branch 'decouple-client'

Conflicts:
	Mage/src/mage/cards/repository/CardRepository.java
This commit is contained in:
North 2013-07-03 21:42:40 +03:00
commit 96ff08dc9a
34 changed files with 626 additions and 242 deletions

View file

@ -25,17 +25,6 @@
<artifactId>mage-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.mage</groupId>
<artifactId>mage-sets</artifactId>
<version>${project.version}</version>
</dependency>
<!-- for running embedded mage server -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-server</artifactId>
<version>${mage-version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.jspf</groupId>
<artifactId>jspf-core</artifactId>
@ -76,23 +65,13 @@
<artifactId>forms_rt</artifactId>
<version>7.0.3</version>
</dependency>
<!--
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<version>4.11</version>
<type>jar</type>
<scope>test</scope>
</dependency>
-->
<!--
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-theme-plugin</artifactId>
<version>0.5</version>
<scope>runtime</scope>
</dependency>
-->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-counter-plugin</artifactId>

View file

@ -25,22 +25,15 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* MageFrame.java
*
* Created on 15-Dec-2009, 9:11:37 PM
*/
package mage.client;
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TConfig;
import de.schlichtherle.truezip.fs.FsOutputOption;
import mage.cards.decks.Deck;
import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.cards.repository.CardScanner;
import mage.client.cards.BigCard;
import mage.client.chat.ChatPanel;
import mage.client.components.MageComponents;
@ -67,7 +60,6 @@ import mage.client.util.SettingsManager;
import mage.client.util.gui.ArrowBuilder;
import mage.client.util.MusicPlayer;
import mage.components.ImagePanel;
import mage.interfaces.Action;
import mage.interfaces.MageClient;
import mage.interfaces.callback.CallbackClient;
import mage.interfaces.callback.ClientCallback;
@ -75,7 +67,6 @@ import mage.remote.Connection;
import mage.remote.Connection.ProxyType;
import mage.remote.Session;
import mage.remote.SessionImpl;
import mage.server.Main;
import mage.utils.MageVersion;
import org.apache.log4j.Logger;
import org.mage.card.arcane.ManaSymbols;
@ -94,8 +85,10 @@ import java.awt.image.BufferedImage;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ -205,12 +198,6 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
session = new SessionImpl(this);
session.setEmbeddedMageServerAction(new Action() {
@Override
public void execute() {
Main.main(new String[]{});
}
});
callbackClient = new CallbackClientImpl(this);
connectDialog = new ConnectDialog();
desktopPane.add(connectDialog, JLayeredPane.POPUP_LAYER);
@ -480,28 +467,22 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
private void checkForNewImages() {
long beforeCall = System.currentTimeMillis();
List<CardInfo> cards = CardRepository.instance.getAllCards();
List<CardInfo> cards = CardRepository.instance.findCards(new CardCriteria());
logger.info("Card pool load time: " + ((System.currentTimeMillis() - beforeCall) / 1000 + " seconds"));
String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true");
String path = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null);
beforeCall = System.currentTimeMillis();
if (DownloadPictures.checkForNewCards(cards, path)) {
if (DownloadPictures.checkForNewCards(cards)) {
logger.info("Card images checking time: " + ((System.currentTimeMillis() - beforeCall) / 1000 + " seconds"));
if (JOptionPane.showConfirmDialog(null, "New cards are available. Do you want to download the images?", "New images available", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
DownloadPictures.startDownload(null, cards, path);
DownloadPictures.startDownload(null, cards);
}
}
}
public void btnImagesActionPerformed(java.awt.event.ActionEvent evt) {
List<CardInfo> cards = CardRepository.instance.getAllCards();
List<CardInfo> cards = CardRepository.instance.findCards(new CardCriteria());
String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true");
String path = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null);
DownloadPictures.startDownload(null, cards, path);
DownloadPictures.startDownload(null, cards);
}
public void btnSymbolsActionPerformed(java.awt.event.ActionEvent evt) {
@ -1005,7 +986,6 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
CardScanner.scan();
for (String arg : args) {
if (arg.startsWith(liteModeArg)) {
liteMode = true;

View file

@ -4,10 +4,12 @@ import mage.constants.CardType;
import mage.constants.ColoredManaSymbol;
import mage.Mana;
import mage.cards.Card;
import mage.cards.ExpansionSet;
import mage.cards.decks.Deck;
import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionRepository;
import mage.client.MageFrame;
import mage.client.util.gui.ColorsChooser;
import mage.client.util.sets.ConstructedFormats;
@ -28,8 +30,6 @@ import java.util.List;
import java.util.Random;
import java.util.UUID;
import mage.cards.ExpansionSet;
/**
* Generates random card pool and builds a deck.
*
@ -140,7 +140,7 @@ public class DeckGenerator {
List<String> setsToUse = ConstructedFormats.getSetsByFormat(format);
if (setsToUse.isEmpty()) {
// use all
setsToUse = CardRepository.instance.getSetCodes();
setsToUse = ExpansionRepository.instance.getSetCodes();
}
if (selectedColors.contains("X")) {
@ -226,7 +226,7 @@ public class DeckGenerator {
int tries = 0;
int count = 0;
while (count < cardsCount) {
Card card = cardPool.get(random.nextInt(cardPoolCount)).getCard();
Card card = cardPool.get(random.nextInt(cardPoolCount)).getMockCard();
if (cardFitsChosenColors(card, allowedColors)) {
spellCardPool.add(card);
count++;
@ -291,7 +291,7 @@ public class DeckGenerator {
int tries = 0;
int count = 0;
while (count < landsCount) {
Card card = landCards.get(random.nextInt(allCount)).getCard();
Card card = landCards.get(random.nextInt(allCount)).getMockCard();
if (cardCardProduceChosenColors(card, allowedColors)) {
nonBasicLandCardPool.add(card);
count++;
@ -378,7 +378,7 @@ public class DeckGenerator {
}
int randomInt = new Random().nextInt(cards.size());
return cards.get(randomInt).getCard();
return cards.get(randomInt).getMockCard();
}

View file

@ -310,7 +310,7 @@ public class CardSelector extends javax.swing.JPanel implements ComponentListene
else {
List<CardInfo> foundCards = CardRepository.instance.findCards(buildCriteria());
for (CardInfo cardInfo : foundCards) {
Card card = cardInfo.getCard();
Card card = cardInfo.getMockCard();
if (filter.match(card, null)) {
filteredCards.add(card);
}

View file

@ -182,7 +182,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
}
}
} else {
card = cardInfo != null ? cardInfo.getCard() : null;
card = cardInfo != null ? cardInfo.getMockCard() : null;
}
if (card != null) {
deck.getCards().add(card);
@ -201,7 +201,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
} else if (event.getEventName().equals("shift-double-click") && mode == DeckEditorMode.Constructed) {
SimpleCardView cardView = (SimpleCardView) event.getSource();
CardInfo cardInfo = CardRepository.instance.findCard(cardView.getExpansionSetCode(), cardView.getCardNumber());
Card card = cardInfo != null ? cardInfo.getCard() : null;
Card card = cardInfo != null ? cardInfo.getMockCard() : null;
if (card != null) {
deck.getSideboard().add(CardImpl.createCard(card.getClass()));
}

View file

@ -31,11 +31,11 @@ package mage.client.deckeditor.collection.viewer;
import mage.cards.Card;
import mage.cards.CardDimensions;
import mage.cards.MageCard;
import mage.client.MageFrame;
import mage.cards.CardImpl;
import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionRepository;
import mage.client.MageFrame;
import mage.client.cards.BigCard;
import mage.client.components.HoverButton;
import mage.client.plugins.impl.Plugins;
@ -226,7 +226,7 @@ public class MageBook extends JComponent {
Rectangle rectangle = new Rectangle();
rectangle.translate(OFFSET_X, OFFSET_Y);
for (int i = 0; i < Math.min(conf.CARDS_PER_PAGE / 2, size); i++) {
Card card = CardImpl.createCard(cards.get(i).getClassName());
Card card = cards.get(i).getMockCard();
addCard(new CardView(card), bigCard, null, rectangle);
rectangle = CardPosition.translatePosition(i, rectangle, conf);
}
@ -237,7 +237,7 @@ public class MageBook extends JComponent {
rectangle.setLocation(second_page_x, OFFSET_Y);
for (int i = conf.CARDS_PER_PAGE / 2; i < Math.min(conf.CARDS_PER_PAGE, size); i++) {
Card card = CardImpl.createCard(cards.get(i).getClassName());
Card card = cards.get(i).getMockCard();
addCard(new CardView(card), bigCard, null, rectangle);
rectangle = CardPosition.translatePosition(i - conf.CARDS_PER_PAGE / 2, rectangle, conf);
}
@ -301,7 +301,7 @@ public class MageBook extends JComponent {
this.setsToDisplay = ConstructedFormats.getSetsByFormat(format);
if (this.setsToDisplay.isEmpty()) {
// display all
this.setsToDisplay = CardRepository.instance.getSetCodes();
this.setsToDisplay = ExpansionRepository.instance.getSetCodes();
}
addSetTabs();
tabs.get(0).execute();

View file

@ -79,7 +79,7 @@ public class AddLandDialog extends MageDialog {
}
for (int i = 0; i < number; i++) {
Card land = cards.get(random.nextInt(cards.size())).getCard();
Card land = cards.get(random.nextInt(cards.size())).getMockCard();
deck.getCards().add(land);
}
}

View file

@ -301,7 +301,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
// Avatar
Image image = ImageHelper.getImageFromResources(DEFAULT_AVATAR_PATH);
topCardPanel = Plugins.getInstance().getMageCard(new CardView(CardRepository.instance.findCard("Forest").getCard()), bigCard, topCardDimension, gameId, true);
topCardPanel = Plugins.getInstance().getMageCard(new CardView(CardRepository.instance.findCard("Forest").getMockCard()), bigCard, topCardDimension, gameId, true);
topCardPanel.setVisible(false);
panelBackground.add(topCardPanel);

View file

@ -46,7 +46,7 @@ public class CardsViewUtil {
for (SimpleCardView simple: view.values()) {
CardInfo cardInfo = CardRepository.instance.findCard(simple.getExpansionSetCode(), simple.getCardNumber());
Card card = cardInfo != null ? cardInfo.getCard() : null;
Card card = cardInfo != null ? cardInfo.getMockCard() : null;
if (card != null) {
cards.put(simple.getId(), new CardView(card, simple.getId()));
}

View file

@ -52,7 +52,7 @@ public class DeckUtil {
Deck deck = new Deck();
for (SimpleCardView cardView : view.getCards().values()) {
CardInfo cardInfo = CardRepository.instance.findCard(cardView.getExpansionSetCode(), cardView.getCardNumber());
Card card = cardInfo != null ? cardInfo.getCard() : null;
Card card = cardInfo != null ? cardInfo.getMockCard() : null;
if (card != null) {
deck.getCards().add(card);
} else {
@ -61,7 +61,7 @@ public class DeckUtil {
}
for (SimpleCardView cardView : view.getSideboard().values()) {
CardInfo cardInfo = CardRepository.instance.findCard(cardView.getExpansionSetCode(), cardView.getCardNumber());
Card card = cardInfo != null ? cardInfo.getCard() : null;
Card card = cardInfo != null ? cardInfo.getMockCard() : null;
if (card != null) {
deck.getSideboard().add(card);
} else {

View file

@ -5,9 +5,8 @@ import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import mage.cards.ExpansionSet;
import mage.cards.Sets;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionInfo;
import mage.cards.repository.ExpansionRepository;
/**
* Utility class for constructed formats (expansions and other editions).
@ -16,7 +15,8 @@ import mage.cards.repository.CardRepository;
*/
public class ConstructedFormats {
private static final String[] constructedFormats = {"- All Sets", "- Standard", "- Extended", "- Modern",
private static final String[] constructedFormats = {
"- All Sets", "- Standard", "- Extended", "- Modern",
"Modern Masters",
"* Return to Ravnica Block", "Dragon's Maze", "Gatecrash", "Return to Ravnica",
"Magic 2013", "Planechase 2012",
@ -379,9 +379,7 @@ public class ConstructedFormats {
}
private static void buildLists() {
for (String setCode : CardRepository.instance.getSetCodes()) {
ExpansionSet set = Sets.findSet(setCode);
for (ExpansionInfo set : ExpansionRepository.instance.getAll()) {
if (set.getReleaseDate().after(standardDate)) {
standard.add(set.getCode());
}

View file

@ -1,6 +1,7 @@
package org.mage.card.arcane;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionRepository;
import mage.client.dialog.PreferencesDialog;
import mage.client.util.ImageHelper;
import mage.client.util.gui.BufferedImageBuilder;
@ -49,7 +50,7 @@ public class ManaSymbols {
} catch (Exception e) {
}
}
List<String> setCodes = CardRepository.instance.getSetCodes();
List<String> setCodes = ExpansionRepository.instance.getSetCodes();
for (String set : setCodes) {
File file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET + set + "-C.jpg");
try {
@ -106,7 +107,7 @@ public class ManaSymbols {
}
File file;
for (String set : CardRepository.instance.getSetCodes()) {
for (String set : ExpansionRepository.instance.getSetCodes()) {
file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET_SMALL);
if (!file.exists()) {
break;

View file

@ -29,6 +29,7 @@ public class WizardCardsImageSource implements CardImageSource {
public WizardCardsImageSource() {
sets = new HashMap<String, Map<String, String>>();
setsAliases = new HashMap<String, String>();
setsAliases.put("M14", "magic2014coreset/cig");
setsAliases.put("MMA", "modernmasters/cig");
setsAliases.put("DGM", "dragonsmaze/cig");
setsAliases.put("GTC", "gatecrash/cig");
@ -50,7 +51,6 @@ public class WizardCardsImageSource implements CardImageSource {
setsAliases.put("ARB", "alarareborn/spoiler");
setsAliases.put("CON", "conflux/spoiler");
setsAliases.put("ALA", "shardsofalara/spoiler");
setsAliases.put("HOP", "planechase/cig");
setsAliases.put("PC2", "planechase2012edition/cig");
}
@ -60,16 +60,16 @@ public class WizardCardsImageSource implements CardImageSource {
Document doc = Jsoup.connect("http://www.wizards.com/magic/tcg/article.aspx?x=mtg/tcg/" + setsAliases.get(cardSet)).get();
Elements cardsImages = doc.select("img[height$=370]");
for (int i = 0; i < cardsImages.size(); i++) {
String cardName = cardsImages.get(i).attr("title").replace("\u00C6", "AE").replace("\u2019", "'");
String cardName = normalizeName(cardsImages.get(i).attr("title"));
if (cardName != null && !cardName.isEmpty()) {
if (cardName.equals("Forest") || cardName.equals("Swamp") || cardName.equals("Mountain") || cardName.equals("Island") || cardName.equals("Plains")) {
int landNumber = 1;
while (setLinks.get(cardName + landNumber) != null) {
while (setLinks.get((cardName + landNumber).toLowerCase()) != null) {
landNumber++;
}
cardName += landNumber;
}
setLinks.put(cardName, cardsImages.get(i).attr("src"));
setLinks.put(cardName.toLowerCase(), cardsImages.get(i).attr("src"));
} else {
setLinks.put(Integer.toString(i), cardsImages.get(i).attr("src"));
}
@ -77,12 +77,12 @@ public class WizardCardsImageSource implements CardImageSource {
cardsImages = doc.select("img[height$=470]");
for (int i = 0; i < cardsImages.size(); i++) {
String cardName = cardsImages.get(i).attr("title").replace("\u00C6", "AE").replace("\u2019", "'");
String cardName = normalizeName(cardsImages.get(i).attr("title"));
if (cardName != null && !cardName.isEmpty()) {
String[] cardNames = cardName.replace(")", "").split(" \\(");
for (String name : cardNames) {
setLinks.put(name, cardsImages.get(i).attr("src"));
setLinks.put(name.toLowerCase(), cardsImages.get(i).attr("src"));
}
} else {
setLinks.put(Integer.toString(i), cardsImages.get(i).attr("src"));
@ -94,6 +94,18 @@ public class WizardCardsImageSource implements CardImageSource {
return setLinks;
}
private String normalizeName(String name) {
return name.replace("\u2014", "-").replace("\u2019", "'")
.replace("\u00C6", "AE").replace("\u00E6", "ae")
.replace("\u00C1", "A").replace("\u00E1", "a")
.replace("\u00C2", "A").replace("\u00E2", "a")
.replace("\u00D6", "O").replace("\u00F6", "o")
.replace("\u00DB", "U").replace("\u00FB", "u")
.replace("\u00DC", "U").replace("\u00FC", "u")
.replace("\u00E9", "e").replace("&", "//")
.replace("Hintreland Scourge", "Hinterland Scourge");
}
@Override
public String generateURL(CardDownloadData card) throws Exception {
Integer collectorId = card.getCollectorId();
@ -110,7 +122,7 @@ public class WizardCardsImageSource implements CardImageSource {
setLinks = getSetLinks(cardSet);
sets.put(cardSet, setLinks);
}
String link = setLinks.get(card.getDownloadName());
String link = setLinks.get(card.getDownloadName().toLowerCase());
if (link == null) {
if (setLinks.size() >= collectorId) {
link = setLinks.get(Integer.toString(collectorId - 1));

View file

@ -52,7 +52,6 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
private static boolean offlineMode = false;
private JCheckBox checkBox;
private final Object sync = new Object();
private String imagesPath;
private static CardImageSource cardImageSource;
@ -61,11 +60,11 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
private ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
startDownload(null, null, null);
startDownload(null, null);
}
public static void startDownload(JFrame frame, List<CardInfo> allCards, String imagesPath) {
ArrayList<CardDownloadData> cards = getNeededCards(allCards, imagesPath);
public static void startDownload(JFrame frame, List<CardInfo> allCards) {
ArrayList<CardDownloadData> cards = getNeededCards(allCards);
/*
* if (cards == null || cards.size() == 0) {
@ -73,7 +72,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
* "All card pictures have been downloaded."); return; }
*/
DownloadPictures download = new DownloadPictures(cards, imagesPath);
DownloadPictures download = new DownloadPictures(cards);
JDialog dlg = download.getDlg(frame);
dlg.setVisible(true);
dlg.dispose();
@ -97,9 +96,8 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
this.cancel = cancel;
}
public DownloadPictures(ArrayList<CardDownloadData> cards, String imagesPath) {
public DownloadPictures(ArrayList<CardDownloadData> cards) {
this.cards = cards;
this.imagesPath = imagesPath;
bar = new JProgressBar(this);
@ -186,12 +184,12 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
dlg = new JOptionPane(p0, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
}
public static boolean checkForNewCards(List<CardInfo> allCards, String imagesPath) {
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(), usesVariousArt(card), 0, false, card.isDoubleFaced(), card.isNightCard());
file = new TFile(CardImageUtils.getImagePath(url, imagesPath));
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;
}
@ -200,17 +198,12 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
return false;
}
private static boolean usesVariousArt(CardInfo card) {
String className = card.getClassName();
return Character.isDigit(className.charAt(className.length() - 1));
}
private static String createDownloadName(CardInfo card) {
String className = card.getClassName();
return className.substring(className.lastIndexOf('.') + 1);
}
private static ArrayList<CardDownloadData> getNeededCards(List<CardInfo> allCards, String imagesPath) {
private static ArrayList<CardDownloadData> getNeededCards(List<CardInfo> allCards) {
ArrayList<CardDownloadData> cardsToDownload = new ArrayList<CardDownloadData>();
@ -227,7 +220,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
if (card.getCardNumber() > 0 && !card.getSetCode().isEmpty()
&& !ignoreUrls.contains(card.getSetCode())) {
String cardName = card.getName();
CardDownloadData url = new CardDownloadData(cardName, card.getSetCode(), card.getCardNumber(), usesVariousArt(card), 0, false, card.isDoubleFaced(), card.isNightCard());
CardDownloadData url = new CardDownloadData(cardName, card.getSetCode(), card.getCardNumber(), card.usesVariousArt(), 0, false, card.isDoubleFaced(), card.isNightCard());
if (url.getUsesVariousArt()) {
url.setDownloadName(createDownloadName(card));
}
@ -237,17 +230,17 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
allCardsUrls.add(url);
if (card.isDoubleFaced()) {
// add second side for downloading
// it has the same expansion set code and card number as original one
// second side = true;
url = new CardDownloadData(card.getSecondSideName(), card.getSetCode(), card.getCardNumber(), usesVariousArt(card), 0, false, card.isDoubleFaced(), true);
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(), usesVariousArt(card), 0, false, card.isDoubleFaced(), card.isNightCard());
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);
@ -274,7 +267,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
* check to see which cards we already have
*/
for (CardDownloadData card : allCardsUrls) {
file = new TFile(CardImageUtils.getImagePath(card, imagesPath));
file = new TFile(CardImageUtils.generateImagePath(card));
if (!file.exists()) {
cardsToDownload.add(card);
}
@ -363,7 +356,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
@Override
public void run() {
File base = new File(this.imagesPath != null ? imagesPath : Constants.IO.imageBaseDir);
File base = new File(Constants.IO.imageBaseDir);
if (!base.exists()) {
base.mkdir();
}
@ -458,7 +451,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
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.getImagePath(card, imagesPath);
String imagePath = CardImageUtils.generateImagePath(card);
TFile outputFile = new TFile(imagePath);
if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs();
@ -562,7 +555,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
Iterator<CardDownloadData> cardsIterator = DownloadPictures.this.cards.iterator();
while (cardsIterator.hasNext()) {
CardDownloadData cardDownloadData = cardsIterator.next();
TFile file = new TFile(CardImageUtils.getImagePath(cardDownloadData, imagesPath));
TFile file = new TFile(CardImageUtils.generateImagePath(cardDownloadData));
if (file.exists()) {
cardsIterator.remove();
}

View file

@ -73,14 +73,21 @@ public class ImageCache {
CardDownloadData info = new CardDownloadData(name, set, collectorId, usesVariousArt, type);
String path;
if (collectorId == 0) {
info.setToken(true);
path = CardImageUtils.generateTokenImagePath(info);
} else {
path = CardImageUtils.generateImagePath(info);
}
String path = CardImageUtils.getImagePath(info);
if (path == null) {
return null;
}
TFile file = new TFile(path);
if (!file.exists()) {
return null;
}
if (thumbnail && path.endsWith(".jpg")) {
String thumbnailPath = buildThumbnailPath(path);

View file

@ -12,22 +12,16 @@ public class CardImageUtils {
private static HashMap<CardDownloadData, String> pathCache = new HashMap<CardDownloadData, String>();
/**
* Get path to image for specific card.
*
* @param card
* card to get path for
* @return String if image exists, else null
*/
public static String getImagePath(CardDownloadData card) {
String filePath;
TFile file;
public static String generateTokenImagePath(CardDownloadData card) {
if (card.isToken()) {
if (pathCache.containsKey(card)) {
return pathCache.get(card);
}
filePath = getTokenImagePath(card);
file = new TFile(filePath);
String filePath = getTokenImagePath(card);
TFile file = new TFile(filePath);
if (!file.exists()) {
filePath = searchForCardImage(card);
@ -36,36 +30,26 @@ public class CardImageUtils {
if (file.exists()) {
pathCache.put(card, filePath);
return filePath;
}
} else {
String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true");
String path = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null);
filePath = getImagePath(card, path);
file = new TFile(filePath);
}
if (file.exists()) {
return filePath;
} else {
return null;
}
}
private static String getTokenImagePath(CardDownloadData card) {
String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true");
String path = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null);
String filename = getImagePath(card, path);
String filename = generateImagePath(card);
TFile file = new TFile(filename);
if (!file.exists()) {
CardDownloadData updated = new CardDownloadData(card);
updated.setName(card.getName() + " 1");
filename = getImagePath(updated, path);
filename = generateImagePath(updated);
file = new TFile(filename);
if (!file.exists()) {
updated = new CardDownloadData(card);
updated.setName(card.getName() + " 2");
filename = getImagePath(updated, path);
filename = generateImagePath(updated);
}
}
@ -129,7 +113,10 @@ public class CardImageUtils {
}
}
public static String getImagePath(CardDownloadData card, String imagesPath) {
public static String generateImagePath(CardDownloadData card) {
String useDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_USE_DEFAULT, "true");
String imagesPath = useDefault.equals("true") ? null : PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PATH, null);
String imageDir = getImageDir(card, imagesPath);
String imageName;

View file

@ -30,6 +30,8 @@ package mage.interfaces;
import mage.MageException;
import mage.cards.decks.DeckCardLists;
import mage.cards.repository.CardInfo;
import mage.cards.repository.ExpansionInfo;
import mage.game.GameException;
import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions;
@ -50,6 +52,10 @@ public interface MageServer {
boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException;
void deregisterClient(String sessionId) throws MageException;
// update methods
List<ExpansionInfo> getMissingExpansionData(List<String> codes);
List<CardInfo> getMissingCardsData(List<String> classNames);
// user methods
boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException;
void sendFeedbackMessage(String sessionId, String username, String title, String type, String message, String email) throws MageException;

View file

@ -28,7 +28,6 @@
package mage.remote;
import mage.interfaces.Action;
import mage.remote.interfaces.*;
/**
@ -38,5 +37,4 @@ import mage.remote.interfaces.*;
*/
public interface Session extends ClientData, Connect, GamePlay, GameTypes, ServerState, ChatSession, Feedback, PlayerActions, Replays, Testable {
void setEmbeddedMageServerAction(Action embeddedMageServerAction);
}

View file

@ -31,11 +31,14 @@ package mage.remote;
import mage.MageException;
import mage.cards.decks.DeckCardLists;
import mage.cards.decks.InvalidDeckException;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionInfo;
import mage.cards.repository.ExpansionRepository;
import mage.constants.Constants.SessionState;
import mage.game.GameException;
import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions;
import mage.interfaces.Action;
import mage.interfaces.MageClient;
import mage.interfaces.MageServer;
import mage.interfaces.ServerState;
@ -71,18 +74,12 @@ public class SessionImpl implements Session {
private SessionState sessionState = SessionState.DISCONNECTED;
private Connection connection;
private Action embeddedMageServerAction;
private static boolean debugMode = false;
private static boolean standalone = true;
private boolean canceled = false;
static {
debugMode = System.getProperty("debug.mage") != null;
if (System.getProperty("skip.standalone") != null) {
standalone = false;
}
}
public SessionImpl(MageClient client) {
@ -107,11 +104,6 @@ public class SessionImpl implements Session {
@Override
public boolean connect() {
/*if (standalone && connection.getHost().equals("localhost")) {
runEmbeddedMageServer();
}*/
sessionState = SessionState.CONNECTING;
try {
System.setProperty("http.nonProxyHosts", "code.google.com");
@ -177,6 +169,7 @@ public class SessionImpl implements Session {
if (registerResult) {
sessionState = SessionState.CONNECTED;
serverState = server.getServerState();
updateDatabase();
logger.info(new StringBuilder("Connected as ").append(this.getUserName()).append(" to MAGE server at ").append(connection.getHost()).append(":").append(connection.getPort()).toString());
client.connected(new StringBuilder("Connected as ").append(this.getUserName()).append(" to ").append(connection.getHost()).append(":").append(connection.getPort()).append(" ").toString());
return true;
@ -205,13 +198,15 @@ public class SessionImpl implements Session {
return false;
}
private void runEmbeddedMageServer() {
if (embeddedMageServerAction != null) {
try {
embeddedMageServerAction.execute();
} catch (MageException e) {
logger.error(e);
}
private void updateDatabase() {
List<String> classNames = CardRepository.instance.getClassNames();
List<CardInfo> cards = server.getMissingCardsData(classNames);
CardRepository.instance.addCards(cards);
List<String> setCodes = ExpansionRepository.instance.getSetCodes();
List<ExpansionInfo> expansions = server.getMissingExpansionData(setCodes);
for (ExpansionInfo expansion : expansions) {
ExpansionRepository.instance.add(expansion);
}
}
@ -1195,11 +1190,6 @@ public class SessionImpl implements Session {
return false;
}
@Override
public void setEmbeddedMageServerAction(Action embeddedMageServerAction) {
this.embeddedMageServerAction = embeddedMageServerAction;
}
@Override
public boolean ping() {
try {
@ -1217,7 +1207,6 @@ public class SessionImpl implements Session {
return false;
}
}
class MageAuthenticator extends Authenticator {
private String username;

View file

@ -30,6 +30,10 @@ package mage.server;
import mage.MageException;
import mage.cards.decks.DeckCardLists;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionInfo;
import mage.cards.repository.ExpansionRepository;
import mage.game.GameException;
import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions;
@ -59,9 +63,6 @@ import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
//import mage.interfaces.Server;
/**
*
* @author BetaSteward_at_googlemail.com, noxx
@ -926,4 +927,20 @@ public class MageServerImpl implements MageServer {
}
return action.negativeResult();
}
@Override
public List<ExpansionInfo> getMissingExpansionData(List<String> codes) {
List<ExpansionInfo> result = new ArrayList<ExpansionInfo>();
for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) {
if (!codes.contains(expansionInfo.getCode())) {
result .add(expansionInfo);
}
}
return result;
}
@Override
public List<CardInfo> getMissingCardsData(List<String> classNames) {
return CardRepository.instance.getMissingCards(classNames);
}
}

View file

@ -98,6 +98,10 @@ public abstract class ExpansionSet implements Serializable {
return packageName;
}
public String getBlockName() {
return blockName;
}
@Override
public String toString() {
return name;

View file

@ -50,8 +50,8 @@ import mage.watchers.Watcher;
public abstract class SplitCard<T extends SplitCard<T>> extends CardImpl<T> {
private Card leftHalfCard;
private Card rightHalfCard;
protected Card leftHalfCard;
protected Card rightHalfCard;
public SplitCard(UUID ownerId, int cardNumber, String nameLeft, String nameRight, Rarity rarity, CardType[] cardTypes, String costsLeft, String costsRight, boolean fused) {
super(ownerId, cardNumber, new StringBuilder(nameLeft).append(" // ").append(nameRight).toString(), rarity, cardTypes, costsLeft + costsRight, (fused ?SpellAbilityType.SPLIT_FUSED:SpellAbilityType.SPLIT));

View file

@ -0,0 +1,25 @@
package mage.cards.mock;
import mage.abilities.AbilityImpl;
import mage.constants.AbilityType;
import mage.constants.Zone;
class MockAbility extends AbilityImpl<MockAbility> {
private final String text;
public MockAbility(String text) {
super(AbilityType.STATIC, Zone.ALL);
this.text = text;
}
@Override
public MockAbility copy() {
return this;
}
@Override
public String getRule(boolean all) {
return text;
}
}

View file

@ -0,0 +1,76 @@
package mage.cards.mock;
import java.util.List;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.cards.CardImpl;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
/**
* @author North
*/
public class MockCard extends CardImpl<MockCard> {
public MockCard(CardInfo card) {
super(null, card.getName());
this.cardNumber = card.getCardNumber();
this.expansionSetCode = card.getSetCode();
this.power = mageIntFromString(card.getPower());
this.toughness = mageIntFromString(card.getToughness());
this.rarity = card.getRarity();
this.cardType = card.getTypes();
this.subtype = card.getSubTypes();
this.supertype = card.getSupertypes();
this.usesVariousArt = card.usesVariousArt();
this.manaCost = new ManaCostsImpl(join(card.getManaCosts()));
this.color = card.getColor();
this.splitCard = card.isSplitCard();
this.flipCard = card.isFlipCard();
this.canTransform = card.isDoubleFaced();
this.nightCard = card.isNightCard();
if (card.getSecondSideName() != null && !card.getSecondSideName().isEmpty()) {
this.secondSideCard = new MockCard(CardRepository.instance.findCard(card.getSecondSideName()));
}
this.flipCardName = card.getFlipCardName();
for(String ruleText: card.getRules()) {
this.addAbility(textAbilityFromString(ruleText));
}
}
public MockCard(final MockCard card) {
super(card);
}
@Override
public MockCard copy() {
return new MockCard(this);
}
private MageInt mageIntFromString(String value) {
try {
int intValue = Integer.parseInt(value);
return new MageInt(intValue);
} catch (NumberFormatException e) {
return new MageInt(0, value);
}
}
private String join(List<String> strings) {
StringBuilder sb = new StringBuilder();
for (String string : strings) {
sb.append(string);
}
return sb.toString();
}
private Ability textAbilityFromString(final String text) {
return new MockAbility(text);
}
}

View file

@ -0,0 +1,100 @@
package mage.cards.mock;
import java.util.List;
import mage.MageInt;
import mage.abilities.Ability;
import mage.cards.SplitCard;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.constants.CardType;
/**
*
* @author North
*/
public class MockSplitCard extends SplitCard<MockSplitCard> {
public MockSplitCard(CardInfo card) {
super(null,
card.getCardNumber(),
getLeftHalfName(card),
getRightHalfName(card),
card.getRarity(),
card.getTypes().toArray(new CardType[0]),
join(card.getManaCosts()),
"",
join(card.getRules()).contains("Fuse"));
this.expansionSetCode = card.getSetCode();
this.power = mageIntFromString(card.getPower());
this.toughness = mageIntFromString(card.getToughness());
this.cardType = card.getTypes();
this.subtype = card.getSubTypes();
this.supertype = card.getSupertypes();
this.usesVariousArt = card.usesVariousArt();
this.color = card.getColor();
this.splitCard = card.isSplitCard();
this.flipCard = card.isFlipCard();
this.canTransform = card.isDoubleFaced();
this.nightCard = card.isNightCard();
if (card.getSecondSideName() != null && !card.getSecondSideName().isEmpty()) {
this.secondSideCard = new MockCard(CardRepository.instance.findCard(card.getSecondSideName()));
}
this.flipCardName = card.getFlipCardName();
for (String ruleText : card.getRules()) {
this.addAbility(textAbilityFromString(ruleText));
}
CardInfo leftHalf = CardRepository.instance.findCard(getLeftHalfName(card));
if(leftHalf != null) {
this.leftHalfCard = new MockCard(leftHalf);
}
CardInfo rightHalf = CardRepository.instance.findCard(getRightHalfName(card));
if(rightHalf != null) {
this.rightHalfCard = new MockCard(rightHalf);
}
}
public MockSplitCard(final MockSplitCard card) {
super(card);
}
@Override
public MockSplitCard copy() {
return new MockSplitCard(this);
}
private MageInt mageIntFromString(String value) {
try {
int intValue = Integer.parseInt(value);
return new MageInt(intValue);
} catch (NumberFormatException e) {
return new MageInt(0, value);
}
}
private static String join(List<String> strings) {
StringBuilder sb = new StringBuilder();
for (String string : strings) {
sb.append(string);
}
return sb.toString();
}
private Ability textAbilityFromString(final String text) {
return new MockAbility(text);
}
private static String getLeftHalfName(CardInfo card) {
return card.getName().split(" // ")[0];
}
private static String getRightHalfName(CardInfo card) {
return card.getName().split(" // ")[1];
}
}

View file

@ -171,7 +171,9 @@ public class CardCriteria {
public void buildQuery(QueryBuilder qb) throws SQLException {
Where where = qb.where();
int clausesCount = 0;
where.eq("nightCard", false);
where.eq("splitCardHalf", false);
int clausesCount = 2;
if (name != null) {
where.like("name", new SelectArg('%' + name + '%'));
clausesCount++;

View file

@ -38,8 +38,12 @@ import java.util.List;
import mage.constants.CardType;
import mage.constants.Rarity;
import mage.ObjectColor;
import mage.abilities.SpellAbility;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.mock.MockCard;
import mage.cards.mock.MockSplitCard;
import mage.constants.SpellAbilityType;
/**
*
@ -55,7 +59,7 @@ public class CardInfo {
protected int cardNumber;
@DatabaseField
protected String setCode;
@DatabaseField
@DatabaseField(unique = true)
protected String className;
@DatabaseField
protected String power;
@ -88,6 +92,8 @@ public class CardInfo {
@DatabaseField
protected boolean splitCard;
@DatabaseField
protected boolean splitCardHalf;
@DatabaseField
protected boolean flipCard;
@DatabaseField
protected boolean doubleFaced;
@ -115,7 +121,7 @@ public class CardInfo {
this.flipCard = card.isFlipCard();
this.flipCardName = card.getFlipCardName();
this.doubleFaced = card.canTransform();
this.doubleFaced = card.canTransform() && card.getSecondCardFace() != null;
this.nightCard = card.isNightCard();
Card secondSide = card.getSecondCardFace();
if (secondSide != null) {
@ -133,12 +139,33 @@ public class CardInfo {
this.setSuperTypes(card.getSupertype());
this.setManaCosts(card.getManaCost().getSymbols());
this.setRules(card.getRules());
SpellAbility spellAbility = card.getSpellAbility();
if (spellAbility != null) {
SpellAbilityType spellAbilityType = spellAbility.getSpellAbilityType();
if (spellAbilityType == SpellAbilityType.SPLIT_LEFT || spellAbilityType == SpellAbilityType.SPLIT_RIGHT) {
this.className = this.setCode + "." + this.name;
this.splitCardHalf = true;
}
}
}
public Card getCard() {
return CardImpl.createCard(className);
}
public Card getMockCard() {
if (this.splitCard) {
return new MockSplitCard(this);
} else {
return new MockCard(this);
}
}
public boolean usesVariousArt() {
return Character.isDigit(className.charAt(className.length() - 1));
}
public ObjectColor getColor() {
ObjectColor color = new ObjectColor();
color.setBlack(black);
@ -248,6 +275,10 @@ public class CardInfo {
return splitCard;
}
public boolean isSplitCardHalf() {
return splitCardHalf;
}
public boolean isFlipCard() {
return flipCard;
}

View file

@ -32,7 +32,6 @@ import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.io.File;
@ -54,7 +53,8 @@ public enum CardRepository {
instance;
private static final String JDBC_URL = "jdbc:sqlite:db/cards.db";
private static final long DB_VERSION = 9;
private static final String VERSION_ENTITY_NAME = "card";
private static final long CARD_DB_VERSION = 10;
private Random random = new Random();
private Dao<CardInfo, Object> cardDao;
@ -67,16 +67,10 @@ public enum CardRepository {
}
try {
ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL);
TableUtils.createTableIfNotExists(connectionSource, DatabaseVersion.class);
Dao<DatabaseVersion, Object> dbVersionDao = DaoManager.createDao(connectionSource, DatabaseVersion.class);
List<DatabaseVersion> dbVersions = dbVersionDao.queryForAll();
if (dbVersions.isEmpty() || dbVersions.get(0).getVersion() != DB_VERSION) {
boolean obsolete = RepositoryUtil.isDatabaseObsolete(connectionSource, VERSION_ENTITY_NAME, CARD_DB_VERSION);
if (obsolete) {
TableUtils.dropTable(connectionSource, CardInfo.class, true);
if (dbVersions.isEmpty()) {
DatabaseVersion dbVersion = new DatabaseVersion();
dbVersion.setVersion(DB_VERSION);
dbVersionDao.create(dbVersion);
}
}
TableUtils.createTableIfNotExists(connectionSource, CardInfo.class);
@ -123,20 +117,6 @@ public enum CardRepository {
return false;
}
public List<String> getSetCodes() {
List<String> setCodes = new ArrayList<String>();
try {
QueryBuilder<CardInfo, Object> qb = cardDao.queryBuilder();
qb.distinct().selectColumns("setCode");
List<CardInfo> results = cardDao.query(qb.prepare());
for (CardInfo card : results) {
setCodes.add(card.getSetCode());
}
} catch (SQLException ex) {
}
return setCodes;
}
public Set<String> getNames() {
Set<String> names = new TreeSet<String>();
try {
@ -183,8 +163,10 @@ public enum CardRepository {
try {
QueryBuilder<CardInfo, Object> qb = cardDao.queryBuilder();
qb.distinct().selectColumns("name");
Where where = qb.where();
where.and(where.not().like("types", '%' + CardType.CREATURE.name() +'%'),where.not().like("types", '%' + CardType.LAND.name() + '%'));
qb.where()
.not().like("types", '%' + CardType.CREATURE.name() + '%')
.and()
.not().like("types", '%' + CardType.LAND.name() + '%');
List<CardInfo> results = cardDao.query(qb.prepare());
for (CardInfo card : results) {
int result = card.getName().indexOf(" // ");
@ -228,6 +210,30 @@ public enum CardRepository {
return null;
}
public List<String> getClassNames() {
List<String> names = new ArrayList<String>();
try {
List<CardInfo> results = cardDao.queryForAll();
for (CardInfo card : results) {
names.add(card.getClassName());
}
} catch (SQLException ex) {
}
return names;
}
public List<CardInfo> getMissingCards(List<String> classNames) {
try {
QueryBuilder<CardInfo, Object> queryBuilder = cardDao.queryBuilder();
queryBuilder.where().not().in("className", classNames);
return cardDao.query(queryBuilder.prepare());
} catch (SQLException ex) {
}
return new ArrayList<CardInfo>();
}
/**
*
* @param name
@ -262,14 +268,4 @@ public enum CardRepository {
}
return new ArrayList<CardInfo>();
}
public List<CardInfo> getAllCards() {
try {
QueryBuilder<CardInfo, Object> queryBuilder = cardDao.queryBuilder();
return cardDao.query(queryBuilder.prepare());
} catch (SQLException ex) {
}
return new ArrayList<CardInfo>();
}
}

View file

@ -33,6 +33,7 @@ import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.ExpansionSet;
import mage.cards.Sets;
import mage.cards.SplitCard;
import mage.util.ClassScanner;
/**
@ -53,13 +54,19 @@ public class CardScanner {
List<String> packages = new ArrayList<String>();
for (ExpansionSet set : Sets.getInstance().values()) {
packages.add(set.getPackageName());
ExpansionRepository.instance.add(new ExpansionInfo(set));
}
for (Class c : ClassScanner.findClasses(packages, CardImpl.class)) {
if (!CardRepository.instance.cardExists(c.getCanonicalName())) {
Card card = CardImpl.createCard(c);
if (card != null && !card.isNightCard()) {
if (card != null) {
cardsToAdd.add(new CardInfo(card));
if (card instanceof SplitCard) {
SplitCard splitCard = (SplitCard) card;
cardsToAdd.add(new CardInfo(splitCard.getLeftHalfCard()));
cardsToAdd.add(new CardInfo(splitCard.getRightHalfCard()));
}
}
}
}

View file

@ -10,9 +10,20 @@ import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "version")
public class DatabaseVersion {
@DatabaseField
protected String entity;
@DatabaseField
protected Long version;
public String getEntity() {
return entity;
}
public void setEntity(String entity) {
this.entity = entity;
}
public Long getVersion() {
return version;
}

View file

@ -0,0 +1,59 @@
package mage.cards.repository;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import mage.cards.ExpansionSet;
import mage.constants.SetType;
import java.util.Date;
/**
*
* @author North
*/
@DatabaseTable(tableName = "expansion")
public class ExpansionInfo {
@DatabaseField(unique = true)
protected String name;
@DatabaseField(unique = true)
protected String code;
@DatabaseField
protected String blockName;
@DatabaseField
protected Date releaseDate;
@DatabaseField(dataType = DataType.ENUM_STRING)
protected SetType type;
public ExpansionInfo() {
}
public ExpansionInfo(ExpansionSet expansionSet) {
this.name = expansionSet.getName();
this.code = expansionSet.getCode();
this.blockName = expansionSet.getBlockName();
this.releaseDate = expansionSet.getReleaseDate();
this.type = expansionSet.getSetType();
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public String getBlockName() {
return blockName;
}
public Date getReleaseDate() {
return releaseDate;
}
public SetType getType() {
return type;
}
}

View file

@ -0,0 +1,73 @@
package mage.cards.repository;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author North
*/
public enum ExpansionRepository {
instance;
private static final String JDBC_URL = "jdbc:sqlite:db/cards.db";
private static final String VERSION_ENTITY_NAME = "expansion";
private static final long EXPANSION_DB_VERSION = 1;
private Dao<ExpansionInfo, Object> expansionDao;
private ExpansionRepository() {
File file = new File("db");
if (!file.exists()) {
file.mkdirs();
}
try {
ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL);
boolean obsolete = RepositoryUtil.isDatabaseObsolete(connectionSource, VERSION_ENTITY_NAME, EXPANSION_DB_VERSION);
if (obsolete) {
TableUtils.dropTable(connectionSource, ExpansionInfo.class, true);
}
TableUtils.createTableIfNotExists(connectionSource, ExpansionInfo.class);
expansionDao = DaoManager.createDao(connectionSource, ExpansionInfo.class);
} catch (SQLException ex) {
}
}
public void add(ExpansionInfo expansion) {
try {
expansionDao.create(expansion);
} catch (SQLException e) {
}
}
public List<String> getSetCodes() {
List<String> setCodes = new ArrayList<String>();
try {
List<ExpansionInfo> expansions = expansionDao.queryForAll();
for (ExpansionInfo expansion : expansions) {
setCodes.add(expansion.getCode());
}
} catch (SQLException ex) {
}
return setCodes;
}
public List<ExpansionInfo> getAll() {
try {
return expansionDao.queryForAll();
} catch (SQLException ex) {
}
return new ArrayList<ExpansionInfo>();
}
}

View file

@ -0,0 +1,34 @@
package mage.cards.repository;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import java.util.List;
/**
*
* @author North
*/
public class RepositoryUtil {
public static boolean isDatabaseObsolete(ConnectionSource connectionSource, String entityName, long version) throws SQLException {
TableUtils.createTableIfNotExists(connectionSource, DatabaseVersion.class);
Dao<DatabaseVersion, Object> dbVersionDao = DaoManager.createDao(connectionSource, DatabaseVersion.class);
QueryBuilder<DatabaseVersion, Object> queryBuilder = dbVersionDao.queryBuilder();
queryBuilder.where().eq("entity", new SelectArg(entityName)).and().eq("version", version);
List<DatabaseVersion> dbVersions = dbVersionDao.query(queryBuilder.prepare());
if (dbVersions.isEmpty()) {
DatabaseVersion dbVersion = new DatabaseVersion();
dbVersion.setEntity(entityName);
dbVersion.setVersion(version);
dbVersionDao.create(dbVersion);
}
return dbVersions.isEmpty();
}
}

View file

@ -76,6 +76,5 @@
<properties>
<mage-version>1.0.3</mage-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<netbeans.hint.license>mage</netbeans.hint.license>
</properties>
</project>