Search in sources :

Example 1 with MagicCardNames

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

the class CardSearchPanel method initGUI.

private void initGUI() {
    logger.info("init search GUI");
    JPanel panelResultsCards;
    JPanel panelFilters;
    JPanel panelmana;
    JPanel editionDetailPanel;
    JPanel panneauHaut;
    JPanel panneauCard;
    JPanel panneauStat;
    JTextField txtFilter;
    JComboBox<MagicEdition> cboEdition;
    TableFilterHeader filterHeader;
    JButton btnClear;
    JButton btnSearch;
    JButton btnFilter;
    DefaultRowSorter<DefaultTableModel, Integer> sorterCards;
    DefaultRowSorter<DefaultTableModel, Integer> sorterPrice = new TableRowSorter<>(priceModel);
    sorterCards = new TableRowSorter<>(cardsModeltable);
    sorterCards.setComparator(7, (String num1, String num2) -> {
        try {
            num1 = num1.replaceAll("a", "").replaceAll("b", "").trim();
            num2 = num2.replaceAll("a", "").replaceAll("b", "").trim();
            if (Integer.parseInt(num1) > Integer.parseInt(num2))
                return 1;
            else
                return -1;
        } catch (NumberFormatException e) {
            return -1;
        }
    });
    List<MagicEdition> li = new ArrayList<>();
    try {
        li = MTGControler.getInstance().getEnabledProviders().loadEditions();
        Collections.sort(li);
    } catch (Exception e2) {
        logger.error("error no edition loaded", e2);
    }
    // //////INIT COMPONENTS
    JScrollPane scrollEditions = new JScrollPane();
    JScrollPane scrollThumbnails = new JScrollPane();
    JScrollPane scrollPaneRules = new JScrollPane();
    JScrollPane scrollPanePrices = new JScrollPane();
    JScrollPane scrollCards = new JScrollPane();
    JSplitPane panneauCentral = new JSplitPane();
    panneauStat = new JPanel();
    panneauHaut = new JPanel();
    panneauCard = new JPanel();
    editionDetailPanel = new JPanel();
    panelResultsCards = new JPanel();
    cmcChart = new CmcChartPanel();
    manaRepartitionPanel = new ManaRepartitionPanel();
    typeRepartitionPanel = new TypeRepartitionPanel();
    historyChartPanel = new HistoryPricesPanel();
    cardsPicPanel = new CardsPicPanel();
    rarityRepartitionPanel = new RarityRepartitionPanel();
    detailCardPanel = new MagicCardDetailPanel(new MagicCard());
    panelmana = new JPanel();
    panelFilters = new JPanel();
    ManaPanel pan = new ManaPanel();
    panelJson = new JSONPanel();
    tabbedCardsView = new JTabbedPane(JTabbedPane.TOP);
    tabbedCardsInfo = new JTabbedPane(JTabbedPane.TOP);
    thumbnailPanel = new HandPanel();
    thumbnailPanel.setBackground(MTGConstants.THUMBNAIL_BACKGROUND_COLOR);
    btnSearch = new JButton(MTGConstants.ICON_SEARCH);
    btnExport = new JButton(MTGConstants.ICON_EXPORT);
    btnFilter = new JButton(MTGConstants.ICON_FILTER);
    btnClear = new JButton(MTGConstants.ICON_CLEAR);
    cboQuereableItems = new JComboBox<>(new DefaultComboBoxModel<String>(MTGControler.getInstance().getEnabledProviders().getQueryableAttributs()));
    try {
        cboCollections = new JComboBox<>(new DefaultComboBoxModel<MagicCollection>(MTGControler.getInstance().getEnabledDAO().getCollections().toArray(new MagicCollection[MTGControler.getInstance().getEnabledDAO().getCollections().size()])));
    } catch (SQLException e2) {
        logger.error("could not load collections combobox", e2);
    }
    cboLanguages = new JComboBox<>();
    tablePrice = new JXTable();
    tableCards = new JXTable();
    lblLoading = new JLabel(MTGConstants.ICON_LOADING);
    JLabel lblFilter = new JLabel();
    listEdition = new JList<>();
    txtMagicSearch = new JTextField();
    txtRulesArea = new JTextArea();
    txtFilter = new JTextField();
    filterHeader = new TableFilterHeader(tableCards, AutoChoices.ENABLED);
    cboEdition = new JComboBox<>(new DefaultComboBoxModel<MagicEdition>(li.toArray(new MagicEdition[li.size()])));
    // //////MODELS
    listEdition.setModel(new DefaultListModel<MagicEdition>());
    tablePrice.setModel(priceModel);
    tableCards.setModel(cardsModeltable);
    // //////RENDERER
    tableCards.getColumnModel().getColumn(2).setCellRenderer(new ManaCellRenderer());
    tableCards.getColumnModel().getColumn(6).setCellRenderer(new EditionCellRenderer());
    cboEdition.setRenderer(new MagicEditionListRenderer());
    listEdition.setCellRenderer(new MagicEditionListRenderer());
    // ///////CONFIGURE COMPONENTS
    txtRulesArea.setLineWrap(true);
    txtRulesArea.setWrapStyleWord(true);
    txtRulesArea.setEditable(false);
    btnFilter.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("FILTER"));
    btnExport.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("EXPORT_RESULTS"));
    btnExport.setEnabled(false);
    filterHeader.setSelectionBackground(Color.LIGHT_GRAY);
    cboQuereableItems.addItem("collections");
    tablePrice.setRowSorter(sorterPrice);
    listEdition.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    thumbnailPanel.enableDragging(false);
    panneauCentral.setOrientation(JSplitPane.VERTICAL_SPLIT);
    panneauCentral.setRightComponent(tabbedCardsInfo);
    panneauCentral.setLeftComponent(tabbedCardsView);
    tableCards.setRowHeight(MTGConstants.TABLE_ROW_HEIGHT);
    tableCards.setRowSorter(sorterCards);
    // /////LAYOUT
    setLayout(new BorderLayout());
    panneauStat.setLayout(new GridLayout(2, 2, 0, 0));
    panneauCard.setLayout(new BorderLayout());
    editionDetailPanel.setLayout(new BorderLayout());
    panelResultsCards.setLayout(new BorderLayout(0, 0));
    panelmana.setLayout(new GridLayout(1, 0, 2, 2));
    FlowLayout flpanelFilters = (FlowLayout) panelFilters.getLayout();
    flpanelFilters.setAlignment(FlowLayout.LEFT);
    FlowLayout flowLayout = (FlowLayout) panneauHaut.getLayout();
    flowLayout.setAlignment(FlowLayout.LEFT);
    // /////DIMENSION
    thumbnailPanel.setThumbnailSize(new Dimension(179, 240));
    tabbedCardsInfo.setPreferredSize(new Dimension(0, 350));
    historyChartPanel.setPreferredSize(new Dimension(400, 10));
    cardsPicPanel.setPreferredSize(new Dimension(400, 10));
    tabbedCardsInfo.setMinimumSize(new Dimension(23, 200));
    scrollCards.setMinimumSize(new Dimension(0, 0));
    scrollThumbnails.getVerticalScrollBar().setUnitIncrement(10);
    txtFilter.setColumns(25);
    txtMagicSearch.setColumns(35);
    // /////VISIBILITY
    tableCards.setColumnControlVisible(true);
    filterHeader.setVisible(false);
    panelFilters.setVisible(false);
    lblLoading.setVisible(false);
    cboCollections.setVisible(false);
    tableCards.setShowVerticalLines(false);
    cboEdition.setVisible(false);
    // ////ADD PANELS
    for (String s : new String[] { "W", "U", "B", "R", "G", "C", "1" }) {
        final JButton btnG = new JButton();
        btnG.setToolTipText(s);
        if (s.equals("1"))
            btnG.setToolTipText("[0-9]*");
        btnG.setIcon(new ImageIcon(pan.getManaSymbol(s).getScaledInstance(15, 15, Image.SCALE_SMOOTH)));
        btnG.setForeground(btnG.getBackground());
        btnG.addActionListener(e -> {
            txtFilter.setText("\\{" + btnG.getToolTipText() + "}");
            sorterCards.setRowFilter(RowFilter.regexFilter(txtFilter.getText()));
        });
        panelmana.add(btnG);
    }
    scrollEditions.setViewportView(listEdition);
    scrollPanePrices.setViewportView(tablePrice);
    scrollCards.setViewportView(tableCards);
    scrollPaneRules.setViewportView(txtRulesArea);
    scrollThumbnails.setViewportView(thumbnailPanel);
    panneauHaut.add(cboQuereableItems);
    panneauHaut.add(cboCollections);
    panneauHaut.add(txtMagicSearch);
    panneauHaut.add(cboEdition);
    panneauHaut.add(btnSearch);
    panneauHaut.add(btnFilter);
    panneauHaut.add(btnExport);
    panneauHaut.add(lblLoading);
    panneauCard.add(cboLanguages, BorderLayout.NORTH);
    panneauCard.add(scrollEditions, BorderLayout.SOUTH);
    panneauCard.add(cardsPicPanel, BorderLayout.CENTER);
    panelResultsCards.add(panelFilters, BorderLayout.NORTH);
    panelResultsCards.add(scrollCards);
    magicEditionDetailPanel = new MagicEditionDetailPanel();
    editionDetailPanel.add(magicEditionDetailPanel, BorderLayout.CENTER);
    panelFilters.add(lblFilter);
    panelFilters.add(txtFilter);
    panelFilters.add(btnClear);
    panelFilters.add(panelmana);
    tabbedCardsInfo.addTab(MTGControler.getInstance().getLangService().getCapitalize("DETAILS"), null, detailCardPanel, null);
    tabbedCardsInfo.addTab(MTGControler.getInstance().getLangService().getCapitalize("EDITION"), null, editionDetailPanel, null);
    tabbedCardsInfo.addTab(MTGControler.getInstance().getLangService().getCapitalize("PRICES"), null, scrollPanePrices, null);
    tabbedCardsInfo.addTab(MTGControler.getInstance().getLangService().getCapitalize("RULES"), null, scrollPaneRules, null);
    tabbedCardsInfo.addTab(MTGControler.getInstance().getLangService().getCapitalize("PRICE_VARIATIONS"), null, historyChartPanel, null);
    if (MTGControler.getInstance().get("debug-json-panel").equalsIgnoreCase("true"))
        tabbedCardsInfo.addTab("Json", null, panelJson, null);
    panneauStat.add(cmcChart);
    panneauStat.add(manaRepartitionPanel);
    panneauStat.add(typeRepartitionPanel);
    panneauStat.add(rarityRepartitionPanel);
    tabbedCardsView.addTab(MTGControler.getInstance().getLangService().getCapitalize("RESULTS"), null, panelResultsCards, null);
    tabbedCardsView.addTab(MTGControler.getInstance().getLangService().getCapitalize("THUMBNAIL"), null, scrollThumbnails, null);
    tabbedCardsView.addTab(MTGControler.getInstance().getLangService().getCapitalize("STATS"), null, panneauStat, null);
    add(panneauHaut, BorderLayout.NORTH);
    add(panneauCard, BorderLayout.EAST);
    add(panneauCentral, BorderLayout.CENTER);
    // /////Right click
    try {
        initPopupCollection();
    } catch (Exception e2) {
        MTGLogger.printStackTrace(e2);
    }
    // /////Action listners
    cboEdition.addActionListener(ae -> txtMagicSearch.setText(((MagicEdition) cboEdition.getSelectedItem()).getId()));
    btnClear.addActionListener(ae -> {
        txtFilter.setText("");
        sorterCards.setRowFilter(null);
    });
    btnFilter.addActionListener(ae -> {
        if (panelFilters.isVisible()) {
            panelFilters.setVisible(false);
            filterHeader.setVisible(false);
        } else {
            panelFilters.setVisible(true);
            filterHeader.setVisible(true);
        }
    });
    cboQuereableItems.addActionListener(e -> {
        if (cboQuereableItems.getSelectedItem().toString().equalsIgnoreCase("set")) {
            txtMagicSearch.setVisible(false);
            cboEdition.setVisible(true);
            cboCollections.setVisible(false);
        } else if (cboQuereableItems.getSelectedItem().toString().equalsIgnoreCase("collections")) {
            txtMagicSearch.setVisible(false);
            cboEdition.setVisible(false);
            cboCollections.setVisible(true);
        } else {
            txtMagicSearch.setVisible(true);
            cboEdition.setVisible(false);
            cboCollections.setVisible(false);
        }
    });
    btnSearch.addActionListener(ae -> {
        Observer ob = new Observer() {

            @Override
            public void update(Observable o, Object arg) {
                cardsModeltable.addCard((MagicCard) arg);
            }
        };
        selectedEdition = null;
        if (txtMagicSearch.getText().equals("") && !cboCollections.isVisible())
            return;
        cardsModeltable.clear();
        new SwingWorker<Object, Object>() {

            protected Void doInBackground() {
                loading(true, MTGControler.getInstance().getLangService().getCapitalize("SEARCHING"));
                String searchName = txtMagicSearch.getText();
                try {
                    MTGControler.getInstance().getEnabledProviders().addObserver(ob);
                    if (cboCollections.isVisible())
                        cards = MTGControler.getInstance().getEnabledDAO().listCardsFromCollection((MagicCollection) cboCollections.getSelectedItem());
                    else
                        cards = MTGControler.getInstance().getEnabledProviders().searchCardByCriteria(cboQuereableItems.getSelectedItem().toString(), searchName, null, false);
                    if (cards.size() < 50)
                        Collections.sort(cards, new MagicCardComparator());
                    open(cards);
                    return null;
                } catch (Exception e) {
                    logger.error("Erreur search", e);
                    return null;
                }
            }

            @Override
            protected void done() {
                super.done();
                loading(false, "");
                cardsModeltable.fireTableDataChanged();
                btnExport.setEnabled(tableCards.getRowCount() > 0);
                MTGControler.getInstance().getEnabledProviders().removeObserver(ob);
            }
        }.execute();
    });
    tableCards.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent evt) {
            if (SwingUtilities.isRightMouseButton(evt)) {
                Point point = evt.getPoint();
                popupMenu.show(tableCards, (int) point.getX(), (int) point.getY());
            } else {
                try {
                    selectedCard = (MagicCard) tableCards.getValueAt(tableCards.getSelectedRow(), 0);
                    selectedEdition = selectedCard.getEditions().get(0);
                    updateCards();
                } catch (Exception e) {
                    logger.error(e);
                }
            }
        }
    });
    listEdition.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent mev) {
            selectedEdition = listEdition.getSelectedValue();
            ThreadManager.getInstance().execute(() -> {
                loading(true, MTGControler.getInstance().getLangService().getCapitalize("LOADING_EDITIONS"));
                try {
                    selectedCard = MTGControler.getInstance().getEnabledProviders().searchCardByCriteria("name", selectedCard.getName(), selectedEdition, false).get(0);
                    detailCardPanel.setMagicCard(selectedCard);
                    magicEditionDetailPanel.setMagicEdition(selectedEdition);
                } catch (Exception e) {
                    MTGLogger.printStackTrace(e);
                }
                // backcard
                cardsPicPanel.showPhoto(selectedCard);
                historyChartPanel.init(selectedCard, selectedEdition, selectedCard.getName());
                if (tabbedCardsInfo.getSelectedIndex() == INDEX_PRICES)
                    updatePrices();
                loading(false, "");
            }, "changeEdition");
        }
    });
    tablePrice.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent ev) {
            if (ev.getClickCount() == 2 && !ev.isConsumed()) {
                ev.consume();
                try {
                    String url = tablePrice.getValueAt(tablePrice.getSelectedRow(), CardsPriceTableModel.ROW_URL).toString();
                    Desktop.getDesktop().browse(new URI(url));
                } catch (Exception e) {
                    logger.error(e);
                }
            }
        }
    });
    cboLanguages.addItemListener(e -> {
        MagicCardNames selLang = (MagicCardNames) cboLanguages.getSelectedItem();
        try {
            if (e.getStateChange() == ItemEvent.SELECTED && selLang != null) {
                MagicEdition ed = (MagicEdition) BeanUtils.cloneBean(selectedEdition);
                ed.setMultiverse_id("" + selLang.getGathererId());
                logger.debug("change lang to " + selLang + " for " + ed);
                cardsPicPanel.showPhoto(selectedCard, ed);
            }
        } catch (Exception e1) {
            logger.error(e1);
        }
    });
    btnExport.addActionListener(ae -> {
        JPopupMenu menu = new JPopupMenu();
        for (final MTGCardsExport exp : MTGControler.getInstance().getEnabledDeckExports()) {
            JMenuItem it = new JMenuItem();
            it.setIcon(exp.getIcon());
            it.setText(exp.getName());
            it.addActionListener(exportEvent -> {
                JFileChooser jf = new JFileChooser(".");
                jf.setSelectedFile(new File("search" + exp.getFileExtension()));
                int result = jf.showSaveDialog(null);
                final File f = jf.getSelectedFile();
                if (result == JFileChooser.APPROVE_OPTION)
                    ThreadManager.getInstance().execute(() -> {
                        try {
                            loading(true, "export " + exp);
                            List<MagicCard> export = ((MagicCardTableModel) tableCards.getRowSorter().getModel()).getListCards();
                            exp.export(export, f);
                            loading(false, "");
                            JOptionPane.showMessageDialog(null, MTGControler.getInstance().getLangService().combine("EXPORT", "FINISHED"), exp.getName() + " " + MTGControler.getInstance().getLangService().get("FINISHED"), JOptionPane.INFORMATION_MESSAGE);
                        } catch (Exception e) {
                            logger.error(e);
                            loading(false, "");
                            JOptionPane.showMessageDialog(null, e, MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
                        }
                    }, "export search " + exp);
            });
            menu.add(it);
        }
        Component b = (Component) ae.getSource();
        Point p = b.getLocationOnScreen();
        menu.show(b, 0, 0);
        menu.setLocation(p.x, p.y + b.getHeight());
    });
    tabbedCardsInfo.addChangeListener(e -> {
        if (tabbedCardsInfo.getSelectedIndex() == INDEX_PRICES)
            updatePrices();
    });
    txtFilter.addActionListener(ae -> {
        String text = txtFilter.getText();
        if (text.length() == 0) {
            sorterCards.setRowFilter(null);
        } else {
            sorterCards.setRowFilter(RowFilter.regexFilter(text));
        }
    });
    thumbnailPanel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            DisplayableCard lab = (DisplayableCard) thumbnailPanel.getComponentAt(new Point(e.getX(), e.getY()));
            selectedCard = lab.getMagicCard();
            selectedEdition = lab.getMagicCard().getEditions().get(0);
            cardsPicPanel.showPhoto(selectedCard);
            updateCards();
        }
    });
    txtMagicSearch.addActionListener(e -> btnSearch.doClick());
}
Also used : JPanel(javax.swing.JPanel) JTextArea(javax.swing.JTextArea) MagicEdition(org.magic.api.beans.MagicEdition) ArrayList(java.util.ArrayList) HandPanel(org.magic.game.gui.components.HandPanel) EditionCellRenderer(org.magic.gui.renderer.EditionCellRenderer) BorderLayout(java.awt.BorderLayout) List(java.util.List) ArrayList(java.util.ArrayList) JList(javax.swing.JList) MagicCollection(org.magic.api.beans.MagicCollection) JXTable(org.jdesktop.swingx.JXTable) ManaCellRenderer(org.magic.gui.renderer.ManaCellRenderer) DefaultComboBoxModel(javax.swing.DefaultComboBoxModel) ManaRepartitionPanel(org.magic.gui.components.charts.ManaRepartitionPanel) JFileChooser(javax.swing.JFileChooser) JSplitPane(javax.swing.JSplitPane) File(java.io.File) ImageIcon(javax.swing.ImageIcon) FlowLayout(java.awt.FlowLayout) SQLException(java.sql.SQLException) DefaultTableModel(javax.swing.table.DefaultTableModel) JTabbedPane(javax.swing.JTabbedPane) MTGCardsExport(org.magic.api.interfaces.MTGCardsExport) DisplayableCard(org.magic.game.gui.components.DisplayableCard) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) URI(java.net.URI) GridLayout(java.awt.GridLayout) Observer(org.utils.patterns.observer.Observer) MagicCardComparator(org.magic.sorters.MagicCardComparator) HistoryPricesPanel(org.magic.gui.components.charts.HistoryPricesPanel) JMenuItem(javax.swing.JMenuItem) Component(java.awt.Component) TableRowSorter(javax.swing.table.TableRowSorter) JScrollPane(javax.swing.JScrollPane) MouseEvent(java.awt.event.MouseEvent) MouseAdapter(java.awt.event.MouseAdapter) JLabel(javax.swing.JLabel) RarityRepartitionPanel(org.magic.gui.components.charts.RarityRepartitionPanel) TableFilterHeader(net.coderazzi.filters.gui.TableFilterHeader) Dimension(java.awt.Dimension) Point(java.awt.Point) MagicCardNames(org.magic.api.beans.MagicCardNames) SQLException(java.sql.SQLException) TypeRepartitionPanel(org.magic.gui.components.charts.TypeRepartitionPanel) Observable(org.utils.patterns.observer.Observable) JPopupMenu(javax.swing.JPopupMenu) Point(java.awt.Point) MagicCard(org.magic.api.beans.MagicCard) CmcChartPanel(org.magic.gui.components.charts.CmcChartPanel) MagicEditionListRenderer(org.magic.gui.renderer.MagicEditionListRenderer)

Example 2 with MagicCardNames

use of org.magic.api.beans.MagicCardNames 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 3 with MagicCardNames

use of org.magic.api.beans.MagicCardNames 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)

Example 4 with MagicCardNames

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

the class MagicTheGatheringIOProvider method generateCard.

private MagicCard generateCard(JsonObject obj) throws IOException {
    MagicCard mc = new MagicCard();
    if (obj.get("name") != null)
        mc.setName(obj.get("name").getAsString());
    if (obj.get("manaCost") != null)
        mc.setCost(obj.get("manaCost").getAsString());
    if (obj.get("text") != null)
        mc.setText(obj.get("text").getAsString());
    if (obj.get("originalText") != null)
        mc.setOriginalText(obj.get("originalText").getAsString());
    if (obj.get("id") != null)
        mc.setId(obj.get("id").getAsString());
    if (obj.get("artist") != null)
        mc.setArtist(obj.get("artist").getAsString());
    if (obj.get("cmc") != null)
        mc.setCmc(obj.get("cmc").getAsInt());
    if (obj.get("layout") != null)
        mc.setLayout(obj.get("layout").getAsString());
    if (obj.get("number") != null)
        mc.setNumber(obj.get("number").getAsString());
    if (obj.get("power") != null)
        mc.setPower(obj.get("power").getAsString());
    if (obj.get("toughness") != null)
        mc.setToughness(obj.get("toughness").getAsString());
    if (obj.get("loyalty") != null)
        mc.setLoyalty(obj.get("loyalty").getAsInt());
    if (obj.get("mciNumber") != null)
        mc.setMciNumber(String.valueOf(obj.get("mciNumber")));
    if (obj.get("colors") != null) {
        Iterator<JsonElement> it = obj.get("colors").getAsJsonArray().iterator();
        while (it.hasNext()) mc.getColors().add(it.next().getAsString());
    }
    if (obj.get("types") != null) {
        Iterator<JsonElement> it = obj.get("types").getAsJsonArray().iterator();
        while (it.hasNext()) mc.getTypes().add(it.next().getAsString());
    }
    if (obj.get("supertypes") != null) {
        Iterator<JsonElement> it = obj.get("supertypes").getAsJsonArray().iterator();
        while (it.hasNext()) mc.getSupertypes().add(it.next().getAsString());
    }
    if (obj.get("subtypes") != null) {
        Iterator<JsonElement> it = obj.get("subtypes").getAsJsonArray().iterator();
        while (it.hasNext()) mc.getSubtypes().add(it.next().getAsString());
    }
    if (obj.get("legalities") != null) {
        JsonArray arr = obj.get("legalities").getAsJsonArray();
        for (int i = 0; i < arr.size(); i++) {
            JsonObject k = arr.get(i).getAsJsonObject();
            MagicFormat format = new MagicFormat();
            format.setFormat(k.get("format").getAsString());
            format.setLegality(k.get("legality").getAsString());
            mc.getLegalities().add(format);
        }
    }
    if (obj.get("rulings") != null) {
        JsonArray arr = obj.get("rulings").getAsJsonArray();
        for (int i = 0; i < arr.size(); i++) {
            JsonObject k = arr.get(i).getAsJsonObject();
            MagicRuling rule = new MagicRuling();
            rule.setDate(k.get("date").getAsString());
            rule.setText(k.get("text").getAsString());
            mc.getRulings().add(rule);
        }
    }
    if (obj.get("names") != null) {
        JsonArray arr = obj.get("names").getAsJsonArray();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < arr.size(); list.add(arr.get(i++).getAsString())) {
        // TODO complete this function
        }
        list.remove(mc.getName());
        String rotateName = (list.get(list.size() - 1));
        mc.setRotatedCardName(rotateName);
        if (mc.getLayout().equals("flip"))
            mc.setFlippable(true);
        if (mc.getLayout().equals("double-faced") || mc.getLayout().equals("meld"))
            mc.setTranformable(true);
    }
    String currentSet = obj.get("set").getAsString();
    MagicEdition currentEd = getSetById(currentSet);
    if (obj.get("multiverseid") != null)
        currentEd.setMultiverse_id(obj.get("multiverseid").getAsString());
    if (obj.get("rarity") != null)
        currentEd.setRarity(obj.get("rarity").getAsString());
    currentEd.setNumber(mc.getNumber());
    mc.getEditions().add(0, currentEd);
    if (obj.get("printings") != null) {
        JsonArray arr = obj.get("printings").getAsJsonArray();
        for (int i = 0; i < arr.size(); i++) {
            String k = arr.get(i).getAsString();
            if (!k.equals(currentSet)) {
                MagicEdition ed = getSetById(k);
                initOtherEdVariable(mc, ed);
                mc.getEditions().add(ed);
            }
        }
    }
    MagicCardNames defaultMcn = new MagicCardNames();
    defaultMcn.setName(mc.getName());
    defaultMcn.setLanguage("English");
    try {
        defaultMcn.setGathererId(Integer.parseInt(currentEd.getMultiverse_id()));
    } catch (Exception e) {
        defaultMcn.setGathererId(0);
    }
    mc.getForeignNames().add(defaultMcn);
    if (obj.get("foreignNames") != null) {
        JsonArray arr = obj.get("foreignNames").getAsJsonArray();
        for (int i = 0; i < arr.size(); i++) {
            JsonObject lang = arr.get(i).getAsJsonObject();
            MagicCardNames mcn = new MagicCardNames();
            mcn.setName(lang.get("name").getAsString());
            mcn.setLanguage(lang.get("language").getAsString());
            if (lang.get("multiverseid") != null)
                mcn.setGathererId(lang.get("multiverseid").getAsInt());
            mc.getForeignNames().add(mcn);
        }
    }
    setChanged();
    notifyObservers(mc);
    return mc;
}
Also used : ArrayList(java.util.ArrayList) MagicEdition(org.magic.api.beans.MagicEdition) JsonObject(com.google.gson.JsonObject) MagicFormat(org.magic.api.beans.MagicFormat) MagicCardNames(org.magic.api.beans.MagicCardNames) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JsonArray(com.google.gson.JsonArray) MagicCard(org.magic.api.beans.MagicCard) JsonElement(com.google.gson.JsonElement) MagicRuling(org.magic.api.beans.MagicRuling)

Example 5 with MagicCardNames

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

the class CardSearchPanel method updateCards.

public void updateCards() {
    try {
        cboLanguages.removeAllItems();
        txtRulesArea.setText("");
        ((DefaultListModel<MagicEdition>) listEdition.getModel()).removeAllElements();
        for (MagicCardNames mcn : selectedCard.getForeignNames()) cboLanguages.addItem(mcn);
        for (MagicEdition me : selectedCard.getEditions()) ((DefaultListModel<MagicEdition>) listEdition.getModel()).addElement(me);
        detailCardPanel.setMagicCard(selectedCard, true);
        magicEditionDetailPanel.setMagicEdition(selectedCard.getEditions().get(0));
        for (MagicRuling mr : selectedCard.getRulings()) {
            txtRulesArea.append(mr.toString());
            txtRulesArea.append("\n");
        }
        if (tabbedCardsInfo.getSelectedIndex() == INDEX_PRICES)
            updatePrices();
        panelJson.show(selectedCard);
        ThreadManager.getInstance().execute(() -> historyChartPanel.init(selectedCard, selectedEdition, selectedCard.getName()), "load history for " + selectedEdition);
    } catch (Exception e1) {
        logger.error(e1);
    }
}
Also used : MagicEdition(org.magic.api.beans.MagicEdition) DefaultListModel(javax.swing.DefaultListModel) MagicCardNames(org.magic.api.beans.MagicCardNames) MagicRuling(org.magic.api.beans.MagicRuling) SQLException(java.sql.SQLException)

Aggregations

MagicCardNames (org.magic.api.beans.MagicCardNames)6 MagicEdition (org.magic.api.beans.MagicEdition)6 MagicCard (org.magic.api.beans.MagicCard)5 ArrayList (java.util.ArrayList)4 MagicFormat (org.magic.api.beans.MagicFormat)4 JsonArray (com.google.gson.JsonArray)3 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 IOException (java.io.IOException)3 MalformedURLException (java.net.MalformedURLException)3 MagicRuling (org.magic.api.beans.MagicRuling)3 File (java.io.File)2 InputStreamReader (java.io.InputStreamReader)2 URL (java.net.URL)2 List (java.util.List)2 JsonParser (com.google.gson.JsonParser)1 JsonReader (com.google.gson.stream.JsonReader)1 Configuration (com.jayway.jsonpath.Configuration)1 JsonPath (com.jayway.jsonpath.JsonPath)1 Option (com.jayway.jsonpath.Option)1