Search in sources :

Example 36 with MagicCard

use of org.magic.api.beans.MagicCard in project MtgDesktopCompanion by nicho92.

the class AbstractCardExport method importFromDeck.

protected List<MagicCardStock> importFromDeck(MagicDeck deck) {
    List<MagicCardStock> mcs = new ArrayList<>();
    for (MagicCard mc : deck.getMap().keySet()) {
        MagicCardStock stock = new MagicCardStock();
        stock.setMagicCard(mc);
        stock.setQte(deck.getMap().get(mc));
        stock.setComment("import from " + deck.getName());
        stock.setIdstock(-1);
        stock.setUpdate(true);
        mcs.add(stock);
    }
    return mcs;
}
Also used : MagicCard(org.magic.api.beans.MagicCard) ArrayList(java.util.ArrayList) MagicCardStock(org.magic.api.beans.MagicCardStock)

Example 37 with MagicCard

use of org.magic.api.beans.MagicCard in project MtgDesktopCompanion by nicho92.

the class MtgjsonProvider method generateBooster.

public Booster generateBooster(MagicEdition me) {
    logger.debug("opening booster for " + me);
    List<MagicCard> common = new ArrayList<>();
    List<MagicCard> uncommon = new ArrayList<>();
    List<MagicCard> rare = new ArrayList<>();
    List<MagicCard> lands = new ArrayList<>();
    Booster b = new Booster();
    try {
        if (cachedCardEds.get(me.getId()) == null)
            cachedCardEds.put(me.getId(), searchCardByCriteria("set", me.getId(), null, true));
        for (MagicCard mc : cachedCardEds.get(me.getId())) {
            if (mc.getEditions().get(0).getRarity().equalsIgnoreCase("common"))
                common.add(mc);
            if (mc.getEditions().get(0).getRarity().equalsIgnoreCase("uncommon"))
                uncommon.add(mc);
            if (mc.getEditions().get(0).getRarity().toLowerCase().contains("rare"))
                rare.add(mc);
            if (mc.getSupertypes().toString().toLowerCase().contains("basic") && mc.getTypes().toString().toLowerCase().contains("land"))
                lands.add(mc);
        }
        Collections.shuffle(lands);
        Collections.shuffle(common);
        Collections.shuffle(uncommon);
        Collections.shuffle(rare);
    } catch (Exception e) {
        logger.error("Error opening booster", e);
    }
    List<MagicCard> resList = new ArrayList<>();
    resList.addAll(common.subList(0, 11));
    resList.addAll(uncommon.subList(0, 3));
    resList.add(rare.get(0));
    if (!lands.isEmpty())
        resList.addAll(lands.subList(0, 1));
    b.setCards(resList);
    b.setEdition(me);
    return b;
}
Also used : MagicCard(org.magic.api.beans.MagicCard) Booster(org.magic.api.beans.Booster) ArrayList(java.util.ArrayList) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException)

Example 38 with MagicCard

use of org.magic.api.beans.MagicCard in project MtgDesktopCompanion by nicho92.

the class MtgjsonProvider method search.

private List<MagicCard> search(String jsquery, String att, String crit) {
    currentSet = new ArrayList<>();
    List<MagicCard> listCards = new ArrayList<>();
    logger.debug("searchCardByCriteria : " + jsquery);
    List<Map<String, Object>> cardsElement = ctx.withListeners(fr -> {
        if (fr.path().startsWith("$")) {
            currentSet.add(fr.path().substring(fr.path().indexOf("$[") + 3, fr.path().indexOf("]") - 1));
        }
        return null;
    }).read(jsquery, List.class);
    int indexSet = 0;
    for (Map<String, Object> map : cardsElement) {
        MagicCard mc = new MagicCard();
        if (map.get("name") != null)
            mc.setName(map.get("name").toString());
        mc.setFlippable(false);
        mc.setTranformable(false);
        if (map.get("multiverseid") != null)
            mc.setMultiverseid((int) (double) map.get("multiverseid"));
        mc.setId(String.valueOf(map.get("id")));
        mc.setText(String.valueOf(map.get("text")));
        if (map.get("cmc") != null)
            mc.setCmc((int) Double.parseDouble(String.valueOf(map.get("cmc"))));
        mc.setPower(String.valueOf(map.get("power")));
        mc.setToughness(String.valueOf(map.get("toughness")));
        mc.setFlavor(String.valueOf(map.get("flavor")));
        mc.setArtist(String.valueOf(map.get("artist")));
        mc.setLayout(String.valueOf(map.get("layout")));
        if (map.get("mciNumber") != null)
            mc.setMciNumber(String.valueOf(map.get("mciNumber")));
        if (map.get("originalText") != null)
            mc.setOriginalText(String.valueOf(map.get("originalText")));
        if (map.get("originalType") != null)
            mc.setOriginalType(String.valueOf(map.get("originalType")));
        if (map.get("supertypes") != null)
            mc.getSupertypes().addAll((List<String>) map.get("supertypes"));
        if (map.get("types") != null)
            mc.getTypes().addAll((List<String>) map.get("types"));
        if (map.get("subtypes") != null)
            mc.getSubtypes().addAll((List<String>) map.get("subtypes"));
        if (map.get("variations") != null)
            mc.getVariations().addAll((List<Integer>) map.get("variations"));
        if (map.get("colors") != null)
            mc.getColors().addAll((List<String>) map.get("colors"));
        if (map.get("colorIdentity") != null)
            mc.getColorIdentity().addAll((List<String>) map.get("colorIdentity"));
        if (map.get("watermark") != null)
            mc.setWatermarks(String.valueOf(map.get("watermark")));
        if (map.get("number") != null)
            mc.setNumber(String.valueOf(map.get("number")));
        if (map.get("gathererCode") != null)
            mc.setGathererCode(String.valueOf(map.get("gathererCode")));
        if (map.get("reserved") != null)
            mc.setReserved(Boolean.valueOf(String.valueOf(map.get("reserved"))));
        if (map.get("loyalty") != null) {
            try {
                mc.setLoyalty((int) Double.parseDouble(map.get("loyalty").toString()));
            } catch (Exception e) {
                mc.setLoyalty(0);
            }
        }
        if (map.get("manaCost") != null)
            mc.setCost(String.valueOf(map.get("manaCost")));
        else
            mc.setCost("");
        if (map.get("legalities") != null) {
            for (Map<String, Object> mapFormats : (List<Map>) map.get("legalities")) {
                MagicFormat mf = new MagicFormat();
                mf.setFormat(String.valueOf(mapFormats.get("format")));
                mf.setLegality(String.valueOf(mapFormats.get("legality")));
                mc.getLegalities().add(mf);
            }
        }
        if (map.get("rulings") != null) {
            for (Map<String, Object> mapRules : (List<Map>) map.get("rulings")) {
                MagicRuling mr = new MagicRuling();
                mr.setDate(String.valueOf(mapRules.get("date")));
                mr.setText(String.valueOf(mapRules.get("text")));
                mc.getRulings().add(mr);
            }
        }
        String codeEd;
        if (currentSet.size() == 1)
            codeEd = currentSet.get(0);
        else
            codeEd = currentSet.get(indexSet++);
        MagicEdition me = getSetById(codeEd);
        me.setRarity(String.valueOf(map.get("rarity")));
        me.setNumber(mc.getNumber());
        if (mc.getMultiverseid() != null)
            me.setMultiverse_id(String.valueOf(mc.getMultiverseid()));
        mc.getEditions().add(me);
        if (// mtgjson give null text for basic Land. Modify it for adding mana color
        me.getRarity().equals("Basic Land")) {
            mc.setText(mc.getOriginalText());
            switch(mc.getName()) {
                case "Plains":
                    mc.setText("{T} : Add {W} to your mana pool");
                    break;
                case "Island":
                    mc.setText("{T} : Add {U} to your mana pool");
                    break;
                case "Swamp":
                    mc.setText("{T} : Add {B} to your mana pool");
                    break;
                case "Mountain":
                    mc.setText("{T} : Add {R} to your mana pool");
                    break;
                case "Forest":
                    mc.setText("{T} : Add {G} to your mana pool");
                    break;
                default:
                    break;
            }
        }
        /*get other sets*/
        if (// too much elements, so, remove all re-printings information for basic lands
        !me.getRarity().equals("Basic Land") && map.get("printings") != null) {
            for (String print : (List<String>) map.get("printings")) {
                if (!print.equalsIgnoreCase(codeEd)) {
                    MagicEdition meO = getSetById(print);
                    if (mc.getMultiverseid() == null)
                        meO.setMultiverse_id(String.valueOf(0));
                    initOtherEditionCardsVar(mc, meO);
                    mc.getEditions().add(meO);
                }
            }
        }
        MagicCardNames defnames = new MagicCardNames();
        defnames.setLanguage("English");
        defnames.setName(mc.getName());
        if (mc.getMultiverseid() != null)
            defnames.setGathererId(mc.getMultiverseid());
        mc.getForeignNames().add(defnames);
        if (map.get("foreignNames") != null) {
            for (Map<String, Object> mapNames : (List<Map>) map.get("foreignNames")) {
                MagicCardNames fnames = new MagicCardNames();
                fnames.setLanguage(String.valueOf(mapNames.get("language")));
                fnames.setName(String.valueOf(mapNames.get("name")));
                if (mapNames.get("multiverseid") != null)
                    fnames.setGathererId((int) (double) mapNames.get("multiverseid"));
                mc.getForeignNames().add(fnames);
            }
        }
        if (map.get("names") != null) {
            ((List) map.get("names")).remove(mc.getName());
            String rotateName = ((List) map.get("names")).get(((List) map.get("names")).size() - 1).toString();
            mc.setRotatedCardName(rotateName);
            if (mc.getLayout().equals("flip"))
                mc.setFlippable(true);
        }
        if (mc.getLayout().equals("double-faced") || mc.getLayout().equals("meld"))
            mc.setTranformable(true);
        setChanged();
        notifyObservers(mc);
        listCards.add(mc);
    }
    currentSet.clear();
    if (att.equalsIgnoreCase("set"))
        cachedCardEds.put(crit, listCards);
    return listCards;
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) URL(java.net.URL) HashMap(java.util.HashMap) MagicCardNames(org.magic.api.beans.MagicCardNames) JsonProvider(com.jayway.jsonpath.spi.json.JsonProvider) ArrayList(java.util.ArrayList) ReadContext(com.jayway.jsonpath.ReadContext) AbstractCardsProvider(org.magic.api.interfaces.abstracts.AbstractCardsProvider) URLConnection(java.net.URLConnection) Configuration(com.jayway.jsonpath.Configuration) Map(java.util.Map) CacheProvider(com.jayway.jsonpath.spi.cache.CacheProvider) ZipEntry(java.util.zip.ZipEntry) Booster(org.magic.api.beans.Booster) EnumSet(java.util.EnumSet) MTGLogger(org.magic.services.MTGLogger) GsonJsonProvider(com.jayway.jsonpath.spi.json.GsonJsonProvider) MalformedURLException(java.net.MalformedURLException) GsonMappingProvider(com.jayway.jsonpath.spi.mapper.GsonMappingProvider) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) FileInputStream(java.io.FileInputStream) Option(com.jayway.jsonpath.Option) JsonPath(com.jayway.jsonpath.JsonPath) InputStreamReader(java.io.InputStreamReader) File(java.io.File) List(java.util.List) MagicEdition(org.magic.api.beans.MagicEdition) MagicRuling(org.magic.api.beans.MagicRuling) LRUCache(com.jayway.jsonpath.spi.cache.LRUCache) MappingProvider(com.jayway.jsonpath.spi.mapper.MappingProvider) MagicFormat(org.magic.api.beans.MagicFormat) MagicCard(org.magic.api.beans.MagicCard) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) Collections(java.util.Collections) InputStream(java.io.InputStream) MTGConstants(org.magic.services.MTGConstants) ArrayList(java.util.ArrayList) MagicEdition(org.magic.api.beans.MagicEdition) MagicFormat(org.magic.api.beans.MagicFormat) MagicCardNames(org.magic.api.beans.MagicCardNames) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) MagicCard(org.magic.api.beans.MagicCard) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MagicRuling(org.magic.api.beans.MagicRuling)

Example 39 with MagicCard

use of org.magic.api.beans.MagicCard in project MtgDesktopCompanion by nicho92.

the class CockatriceTokenProvider method generateTokenFor.

@Override
public MagicCard generateTokenFor(MagicCard mc) {
    String expression = "//card[reverse-related=\"" + mc.getName() + "\"][not(contains(name,'emblem'))]";
    try {
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
        Element value = (Element) nodeList.item(0);
        MagicCard tok = new MagicCard();
        tok.setLayout(MagicCard.LAYOUT.Token.toString());
        tok.setCmc(0);
        tok.setName(value.getElementsByTagName("name").item(0).getTextContent());
        if (value.getElementsByTagName("color").item(0) != null) {
            tok.getColors().add(ColorParser.getNameByCode(value.getElementsByTagName("color").item(0).getTextContent()));
            tok.getColorIdentity().add("{" + value.getElementsByTagName("color").item(0).getTextContent() + "}");
        }
        String types = value.getElementsByTagName("type").item(0).getTextContent();
        if (types.toLowerCase().contains("legendary"))
            tok.getSupertypes().add("Legendary");
        if (types.toLowerCase().contains("artifact"))
            tok.getTypes().add("Artifact");
        if (types.toLowerCase().contains("creature"))
            tok.getTypes().add("Creature");
        tok.getTypes().add(MagicCard.LAYOUT.Token.toString());
        tok.getSubtypes().add(types.substring(types.indexOf("\u2014") + 1));
        if (value.getElementsByTagName("pt").item(0) != null) {
            tok.setPower(value.getElementsByTagName("pt").item(0).getTextContent().substring(0, value.getElementsByTagName("pt").item(0).getTextContent().indexOf('/')).trim());
            tok.setToughness(value.getElementsByTagName("pt").item(0).getTextContent().substring(value.getElementsByTagName("pt").item(0).getTextContent().indexOf('/') + 1).trim());
        }
        if (value.getElementsByTagName("text").item(0) != null)
            tok.setText(value.getElementsByTagName("text").item(0).getTextContent());
        tok.getEditions().add(mc.getEditions().get(0));
        tok.setNumber("T");
        NodeList sets = value.getElementsByTagName("set");
        for (int s = 0; s < sets.getLength(); s++) {
            String idSet = sets.item(s).getTextContent();
            if (idSet.equals(mc.getEditions().get(0).getId())) {
                MagicEdition ed = MTGControler.getInstance().getEnabledProviders().getSetById(idSet);
                tok.getEditions().add(ed);
            }
        }
        tok.setId(DigestUtils.sha1Hex(tok.getEditions().get(0).getId() + tok.getName()));
        return tok;
    } catch (XPathExpressionException e) {
        logger.error("erreur generate token for" + mc, e);
        return null;
    } catch (IOException e) {
        logger.error("getSetById error " + mc, e);
        return null;
    }
}
Also used : MagicCard(org.magic.api.beans.MagicCard) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) MagicEdition(org.magic.api.beans.MagicEdition) IOException(java.io.IOException)

Example 40 with MagicCard

use of org.magic.api.beans.MagicCard in project MtgDesktopCompanion by nicho92.

the class DeckbrewProvider method searchCardByCriteria.

public List<MagicCard> searchCardByCriteria(String att, String crit, MagicEdition me, boolean exact) throws IOException {
    crit = att + "=" + URLEncoder.encode(crit, encoding);
    String url = urldeckbrewJSON + "/cards?" + crit;
    Reader reader = new InputStreamReader(new URL(url).openStream(), encoding);
    List<MagicCard> retour = new ArrayList<>();
    JsonArray root = new JsonParser().parse(reader).getAsJsonArray();
    int page = 1;
    boolean gonextpage = true;
    while (gonextpage) {
        String pagination;
        if (crit == null)
            pagination = "?";
        else
            pagination = "&";
        URL u = null;
        if (root.size() == 100) {
            u = new URL(url + pagination + "page=" + page++);
            gonextpage = true;
        } else {
            u = new URL(url);
            gonextpage = false;
        }
        logger.info("Connexion to " + u);
        reader = new InputStreamReader(u.openStream(), encoding);
        root = new JsonParser().parse(reader).getAsJsonArray();
        for (int i = 0; i < root.size(); i++) {
            JsonObject e = root.get(i).getAsJsonObject();
            MagicCard mc = new MagicCard();
            if (e.get("name") != null)
                mc.setName(e.get("name").getAsString());
            if (e.get("id") != null)
                mc.setId(e.get("id").getAsString());
            if (e.get("cmc") != null)
                mc.setCmc(e.get("cmc").getAsInt());
            if (e.get("cost") != null)
                mc.setCost(e.get("cost").getAsString());
            if (e.get("text") != null)
                mc.setText(e.get("text").getAsString());
            if (e.get("power") != null)
                mc.setPower(e.get("power").getAsString());
            if (e.get("toughness") != null)
                mc.setToughness(e.get("toughness").getAsString());
            if (e.get("types") != null) {
                Iterator<JsonElement> it = e.get("types").getAsJsonArray().iterator();
                while (it.hasNext()) {
                    mc.getTypes().add(it.next().getAsString());
                }
            }
            if (e.get("subtypes") != null) {
                Iterator<JsonElement> it2 = e.get("subtypes").getAsJsonArray().iterator();
                while (it2.hasNext()) {
                    mc.getSubtypes().add(it2.next().getAsString());
                }
            }
            if (e.get("colors") != null) {
                Iterator<JsonElement> it3 = e.get("colors").getAsJsonArray().iterator();
                while (it3.hasNext()) {
                    mc.getColors().add(it3.next().getAsString());
                }
            }
            JsonArray editions = e.getAsJsonArray("editions");
            for (int j = 0; j < editions.size(); j++) {
                JsonObject obj = editions.get(j).getAsJsonObject();
                MagicEdition ed = getSetById(obj.get("set_id").getAsString());
                ed.setArtist(obj.get("artist").getAsString());
                ed.setMultiverse_id(obj.get("multiverse_id").getAsString());
                ed.setRarity(obj.get("rarity").getAsString());
                ed.setNumber(obj.get("number").getAsString());
                MagicCardNames name = new MagicCardNames();
                name.setName(mc.getName());
                name.setLanguage("English");
                name.setGathererId(Integer.parseInt(ed.getMultiverse_id()));
                mc.getForeignNames().add(name);
                mc.setLayout(obj.get("layout").getAsString());
                mc.getEditions().add(ed);
                mc.setNumber(ed.getNumber());
            }
            if (e.get("formats") != null) {
                JsonObject obj = e.get("formats").getAsJsonObject();
                for (Entry<String, JsonElement> k : obj.entrySet()) {
                    MagicFormat format = new MagicFormat();
                    format.setFormat(k.getKey());
                    format.setLegality(k.getValue().getAsString());
                    mc.getLegalities().add(format);
                }
            }
            setChanged();
            notifyObservers(mc);
            retour.add(mc);
        }
    }
    return retour;
}
Also used : InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) MagicEdition(org.magic.api.beans.MagicEdition) JsonReader(com.google.gson.stream.JsonReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JsonObject(com.google.gson.JsonObject) MagicFormat(org.magic.api.beans.MagicFormat) MagicCardNames(org.magic.api.beans.MagicCardNames) URL(java.net.URL) JsonArray(com.google.gson.JsonArray) MagicCard(org.magic.api.beans.MagicCard) JsonElement(com.google.gson.JsonElement) JsonParser(com.google.gson.JsonParser)

Aggregations

MagicCard (org.magic.api.beans.MagicCard)106 MagicEdition (org.magic.api.beans.MagicEdition)40 ArrayList (java.util.ArrayList)31 IOException (java.io.IOException)28 MagicDeck (org.magic.api.beans.MagicDeck)21 MagicCollection (org.magic.api.beans.MagicCollection)14 SQLException (java.sql.SQLException)12 Date (java.util.Date)11 MagicCardStock (org.magic.api.beans.MagicCardStock)10 DisplayableCard (org.magic.game.gui.components.DisplayableCard)10 JsonArray (com.google.gson.JsonArray)8 List (java.util.List)8 FileReader (java.io.FileReader)7 Before (org.junit.Before)7 BufferedReader (java.io.BufferedReader)6 File (java.io.File)6 FileWriter (java.io.FileWriter)6 MalformedURLException (java.net.MalformedURLException)6 PreparedStatement (java.sql.PreparedStatement)6 ResultSet (java.sql.ResultSet)6