Developer Tools - nicho92/MtgDesktopCompanion GitHub Wiki

Developer guide: shared service helper packages

This page is a quick reference for developers working with shared helper classes in src/main/java/org/magic/services/tools, src/main/java/org/magic/services/threads, src/main/java/org/magic/services/network, and src/main/java/org/magic/services/providers. These classes are used across the project, so prefer reusing them instead of duplicating file, UI, image, crypto, SQL, XML, threading, HTTP, icon, pricing, currency, or plugin-alias logic.

Package overview

org.magic.services.tools

Class Main responsibility
BeanTools Reflection and bean helpers: JSON export, property inspection, template replacement, cloning.
CardKingdomTools Card Kingdom-specific card name and set-name formatting.
Chrono Lightweight stopwatch for elapsed-time measurements.
CryptoUtils Encryption, hashes, Base64, secure random values, certificates, UUIDs.
FileTools Audited file I/O, ZIP handling, directory operations, temp files, JSON reads.
GithubUtils GitHub release API helper for update/release metadata.
ImagePoster Uploads an image URL to Postimages and returns the direct image link.
ImageTools Image detection, conversion, resize, blur, rotation, encoding, and rendering helpers.
MemoryTools Object memory-footprint helpers backed by GraphLayout.
MTG Convenience facade for core MTG Companion services: properties, language, plugins, notifications.
MTGArenaTools Parses MTG Arena detailed logs for account, collection, and deck payloads.
POMReader Reads Maven artifact version metadata from pom.properties.
SQLTools SQL DDL/DML string builder for project database tables using jOOQ.
UITools Swing/SwingX UI helpers, parsing/formatting helpers, table helpers, browser integration.
WooCommerceTools WooCommerce REST client wrapper and JSON attribute helpers.
XMLTools Secure XML DocumentBuilder creation and XPath node selection.

org.magic.services.threads

Class Main responsibility
ThreadManager Central executor, Swing worker, timer, and thread-pool monitoring helper.

org.magic.services.network

Class Main responsibility
IPTranslator Resolves public IP addresses to cached Location audit metadata.
MTGHttpClient Audited Apache HTTP client wrapper with shared cookies, redirects, and timeouts.
RequestBuilder Fluent request builder for GET/POST/PUT calls and response conversion.
URLTools Static URL, HTTP extraction, encoding, markdown, JSON, HTML, XML, and header helpers.

org.magic.services.providers

Class Main responsibility
ApilayerCurrencyConverter Currency conversion and quote-cache handling through the Apilayer endpoint.
IconsProvider Set icon and mana-symbol cache/provider.
LookAndFeelProvider Swing look-and-feel discovery and application helper.
MTGJsonPricerProvider MTGJSON AllPrices cache builder and price lookup helper.
PluginsAliasesProvider Remote/local plugin alias resolver for set IDs, set names, regexes, and conditions.

General usage notes

  • Most classes are static utility classes with private constructors. Do not instantiate them unless the class exposes stateful behavior (Chrono, GithubUtils, ImagePoster, MTGArenaTools, SQLTools).
  • FileTools records file access through AbstractTechnicalServiceManager. Use it when project code should appear in technical audit logs.
  • UITools should stay UI-focused. Avoid adding business logic there; prefer services or model classes.
  • CryptoUtils contains convenience helpers, but MD5 is legacy and should not be used for password storage. Use generatePasswordHash/verifyPassword for passwords.
  • GithubUtils, ImagePoster, URLTools, RequestBuilder, MTGHttpClient, IPTranslator, ApilayerCurrencyConverter, IconsProvider, and MTGJsonPricerProvider can perform network or heavy I/O work and should not be used from the Swing event-dispatch thread without a worker.
  • ThreadManager, MTGHttpClient, FileTools, and RequestBuilder.download create technical audit entries; prefer these central helpers when execution, network, or file operations should be visible in diagnostics.

BeanTools

Reflection helper for JavaBean-style objects. It uses Apache BeanUtils/PropertyUtils and the project JSON export implementation.

Function Description
toJson(Object o) Serializes an object through JsonExport. Useful for debugging or generic JSON payloads.
toMemory(Object o) Returns a printable memory layout summary using MemoryTools.statInstanceToString.
toString(Object o, String separator) Builds a line-by-line property dump using the supplied key/value separator. Logs and returns an empty/partial string on reflection errors.
describe(Object o) Returns a key-sorted Map<String,Object> of bean properties. Returns an empty map on failure.
readProperty(Object o, String k) Reads a nested bean property path, such as edition.set, returning null if it cannot be read.
createString(Object mc, String text) Replaces {property} tokens in a template with property values read from mc. Useful for card export naming patterns.
cloneBean(T ed) Performs an Apache BeanUtils shallow bean clone and propagates reflection exceptions.

CardKingdomTools

Normalizes MTG Companion card data into the naming conventions expected by Card Kingdom exports and lookups.

Function Description
getCKFormattedName(MTGCard card) Returns a Card Kingdom-compatible card name. Handles split/non-split layouts, tokens, selected accented characters, showcase/retro frame suffixes, promo suffixes, duel deck anthology naming, and a few known card-name exceptions.
getCKFormattedSet(MTGCard card) Returns a Card Kingdom-compatible set name. Uses PluginsAliasesProvider, adjusts token and showcase sets, normalizes Duel Decks Anthology, and maps selected promo cards to Promotional.

Chrono

Small stateful stopwatch around System.currentTimeMillis().

Function Description
Chrono() Creates a stopwatch instance. Call start() before reading elapsed time.
start() Stores the current timestamp.
stop() Returns elapsed seconds since start().
stopInMillisecond() Returns elapsed milliseconds since start().

CryptoUtils

Security and random utility methods. Most methods are static and return fallback values when the requested secure random algorithm is unavailable.

Function Description
encrypt(String strToEncrypt, String secret) Encrypts text using Jasypt AES256TextEncryptor with the provided password.
decrypt(String strToDecrypt, String secret) Decrypts text previously encrypted with the same secret.
getMD5(byte[] input) Computes a lowercase MD5 digest from bytes. Legacy/non-password use only.
generateMD5(String s) Computes an uppercase MD5 digest from a string. Legacy/non-password use only.
verifyPassword(String inputPassword, String storedHash) Checks a plaintext password against a BCrypt hash.
generatePasswordHash(String inputPassword) Creates a salted BCrypt password hash.
toBase64(byte[] str) Encodes bytes as Base64 text.
fromBase64(String s) Decodes Base64 text into bytes.
randomInt(int i) Returns a secure random integer below i, or -1 on algorithm failure.
randomLong() Returns a secure random long, or -1L on algorithm failure.
getCertificates(File keystoreFile, String password) Loads a keystore and returns all X.509 certificates it contains.
randomDouble() Returns a secure random double between 0.0 and 1.0, or -1.0 on failure.
randomDouble(double bound) Returns a secure random double below bound, or -1.0 on failure.
randomBoolean() Returns a secure random boolean, or false on failure.
randomString(Integer tokensize) Generates an alphanumeric secure random string of the requested length.
sha256Hex(String string) Computes a SHA-256 hex digest.
uuid() Returns a random UUID string.

FileTools

Central file helper. Many methods create FileAccessInfo entries for the technical audit service, so this class is preferred over raw Commons IO/Guava calls when audit visibility matters.

Function Description
saveFile(File f, byte[] content) Creates/touches a file, writes binary content, and records a create audit event.
linesCount(File f) Reads all lines with the default encoding and returns the count, or -1 on error.
saveFile(File f, String data) Writes text using the default project encoding.
saveFile(File f, String data, Charset enc) Writes text using a supplied encoding. The filename is sanitized before writing.
saveLargeFile(File f, String data, Charset enc) Streams text into a file using a buffer to avoid one large write call.
saveProperties(File f, Properties props) Stores Java properties and records a write audit event.
loadProperties(File f, Properties props) Clears and loads Java properties from a file.
deleteFile(File f) Deletes a sanitized filename and records a delete audit event.
readFileAsBinary(File f) Reads an entire file into a byte array.
readUTF8(ByteBuffer buf) Reads a length-prefixed UTF-8 string from a byte buffer.
readFile(File f) Reads text using the default project encoding. Returns an empty string if the file is missing.
readFile(File f, Charset charset) Reads text using a supplied encoding. Returns an empty string if the file is missing.
readJson(File f) Reads a file and parses the content as JSON through URLTools.toJson.
extractConfig(File fzip) Creates a ZIP archive of configuration files, excluding logs and data.
writeSetRecognition(File f, MTGEdition ed, int sizeOfSet, List<DescContainer> desc) Writes binary set-recognition data: set code, set size, descriptor count, and descriptor payloads.
getBuffer(File f) Reads a file into a flipped ByteBuffer.
unzip(File fileZip, File dest) Extracts a ZIP file into an existing destination directory and records read/write audit events.
unZipIt(File src, File dst) Extracts ZIP stream content into a destination file, then deletes the source archive. Logs errors instead of throwing them.
copyDirJarToDirectory(String path, File writeDirectory) Copies matching entries from the running application JAR into a directory.
readAllLines(File f) Reads all lines with the default project encoding and records a read audit event.
daysBetween(File temp) Returns days between the file's last modified time and now.
copyURLToFile(URL resource, File conf) Downloads a URL into a file and records a write audit event.
forceMkdir(File dataDir) Ensures a directory exists and records a create audit event.
cleanDirectory(File file) Removes all contents of a directory while keeping the directory.
sizeOfDirectory(File file) Returns recursive directory size in bytes.
deleteDirectory(File file) Deletes a directory recursively and records a delete audit event.
copyInputStreamToFile(InputStream content, File dest) Copies an input stream to a file and records a write audit event.
sizeOf(File file) Returns file or directory size in bytes.
moveFileToDirectory(File f, File dest, boolean b) Moves a file into a directory, delegating overwrite/create-directory behavior to Commons IO.
listFiles(File edDir, WildcardFileFilter wildcardFileFilter, IOFileFilter instance) Lists files matching the supplied wildcard and IO filters.
createTempFile(String string, String fileExtension) Creates an audited temporary file under MTGConstants.DATA_DIR/tmp.

GithubUtils

Singleton-style helper that reads MTG Desktop Companion GitHub release metadata from MTGConstants.MTG_DESKTOP_GITHUB_RELEASE_API.

Function Description
inst() Returns the singleton instance, creating it and fetching release metadata on first use.
setUpdateToPreRelease(boolean b) Includes or excludes prereleases when selecting the current release, then refreshes the selected release.
getReleases() Returns the cached GitHub releases JSON array.
getSelectedRelease() Returns the currently selected release JSON object.
setSelectedRelease(int index) Selects a release by index in the cached release array.
getReleaseURL() Returns the selected release HTML URL.
getReleaseContent() Returns the selected release body text.
getAuthor() Returns the selected release author's GitHub login.
getVersion() Returns the selected release tag name.
getVersionName() Returns the selected release display name.
getAvatar() Downloads and returns the selected release author's avatar image, or null on failure.
downloadCount() Sums download counts for the first asset of each release that has assets.

ImagePoster

Stateful Postimages upload helper. Use this from background workers because it performs HTTP calls.

Function Description
setExpirationDay(int expirationDay) Sets the Postimages expiration value used for subsequent uploads. Defaults to 1.
upload(String wallUrl) Posts an image URL to Postimages and returns the direct image URL from the response page. Throws IOException if upload or response parsing fails.

ImageTools

Image manipulation and conversion helpers for Swing icons, buffered images, encoded images, and card art processing.

Function Description
isImage(File f) Returns whether the file can be read as an image.
isImage(byte[] array) Returns whether the byte array can be read as an image.
isImage(Path f) Returns whether the path can be read as an image.
rotate(BufferedImage img, double angle) Rotates an image by degrees, expanding the output canvas to fit the result.
fastBlur(BufferedImage src, int radius, double scale) Downscales, blurs, and upscales an image for faster blur effects.
blurImage(BufferedImage src, int radius) Applies a convolution blur with the requested radius.
getScaledImage(BufferedImage src) Produces a scaled image sized for project card-image display conventions.
splitManaImage() Splits the bundled mana symbol sheet into individual buffered images.
toByteArray(BufferedImage o) Encodes a buffered image to bytes.
fromByteArray(byte[] imagebytes) Decodes bytes into a buffered image.
addOutline(ImageIcon sourceIcon,Color outlineColor, int thickness) Adds a border around an ImageIcon.
saveImage(BufferedImage img, File f, String format) Writes an image in the requested format.
trimAlpha(BufferedImage img) Crops transparent borders based on alpha content.
scaleResize(BufferedImage img, int width) Resizes an image to the given width while preserving aspect ratio.
mirroring(BufferedImage image) Returns a horizontally mirrored image.
initGraphics(Graphics2D g2d) Applies common quality rendering hints to a graphics context.
resize(Image img, int newH, int newW) Resizes an image to explicit height/width and returns a buffered image.
imageToBufferedImage(Image im) Converts any Image to a compatible BufferedImage.
joinBufferedImage(List<Image> imgs) Joins images horizontally into one image.
toImage(byte[] img) Decodes bytes into a buffered image.
resize(Icon icon, int newH, int newW) Resizes an icon to explicit height/width.
resize(Icon icon, Dimension d) Resizes an icon to a supplied dimension.
readBase64(String base) Decodes a Base64 data URL/string into a buffered image.
saveImageInPng(BufferedImage img, File f) Writes a PNG image with project-specific encoding settings.
toMM(double d) Converts pixels to millimeters using the configured DPI constant.
toPX(double val) Converts millimeters to pixels using the configured DPI constant.
readLocal(URL url) Reads an image from a local URL/resource.
read(File file) Reads a file into a buffered image.
read(byte[] imageInByte) Reads bytes into a buffered image.
read(InputStream inputStream) Reads an input stream into a buffered image.
write(BufferedImage bi, String formatName, ByteArrayOutputStream baos) Writes an image to an output stream in the requested format.
toImage(Icon icon) Paints an icon into a buffered image.

MemoryTools

Object memory inspection helpers based on Java Object Layout (GraphLayout).

Function Description
statInstanceToString(Object classe) Returns a human-readable footprint summary for an object graph.
sizeOf(Object classe) Returns total object-graph size in bytes.

MTG

Convenience facade for common controller, language, plugin, and notification operations.

Function Description
readPropertyAsBoolean(String property) Reads an application property from MTGControler and parses it as a boolean.
lang(String key) Returns a localized string through LanguageService.
capitalize(String key, Object... o) Localizes a key with arguments, lowercases it, then capitalizes it.
capitalize(String key) Localizes a key, lowercases it, then capitalizes it.
getEnabledPlugin(Class<T> t) Returns the enabled plugin for a plugin type.
listEnabledPlugins(Class<T> t) Returns enabled plugins for a plugin type.
getPlugin(String name, Class<T> type) Returns a named plugin of the requested type.
listPlugins(Class<T> t) Returns all plugins of the requested type.
notifyError(String msg) Sends an error notification through the enabled notifier plugin.

MTGArenaTools

Parser for MTG Arena detailed log files. The constructor loads the log content once, and each read method extracts the last JSON payload for a known token.

Function Description
MTGArenaTools(File arenaFile) Reads the Arena log file into memory.
readCollection() Extracts and parses the PlayerInventory.GetPlayerCardsV3 JSON payload.
readDecks() Extracts and parses the Deck.GetDeckListsV3 JSON payload.
getAccount() Extracts the account name after Successfully logged in to account:.

POMReader

Maven metadata helper.

Function Description
readVersionFromPom(Class<?> clazz, String pomProperties) Reads pom.properties from the classpath using the supplied class loader and returns the version property, or null if unavailable.

SQLTools

jOOQ-backed SQL generator for database bootstrap/update code. Construct it with a SQLDialect matching the target database.

Function Description
SQLTools(SQLDialect dialect) Creates a DSLContext configured for the requested dialect.
selectAll(String tableName) Builds SELECT * FROM <tableName>.
insertDefaultCollections() Builds an insert statement for default collection names from MTGConstants.DEFAULT_COLLECTION_NAME.
createIndex(String table, String column) Builds a CREATE INDEX IF NOT EXISTS statement named idx_<table>_<column>.
insertMainContact() Builds an insert statement for the default main contact.
createCustomCards() Builds DDL for the customcards table.
createCustomSets() Builds DDL for the customsets table.
createTableTechnicalAudit() Builds DDL for the technicalAudit table.
createTableDecks() Builds DDL for the decks table.
createTableSealed() Builds DDL for the sealed table.
createTableNews() Builds DDL for the news table.
createTableAlerts() Builds DDL for the alerts table.
createTableStocks() Builds DDL for the stocks table.
createTableCollections() Builds DDL for the collections table.
createTableContacts() Builds DDL for the contacts table.
createTableTransactions() Builds DDL for the transactions table.
createTableGed() Builds DDL for the ged table.
createTableAnnounces() Builds DDL for the announces table.

UITools

Large collection of Swing/SwingX UI utilities plus shared parsing and formatting helpers. Keep UI behavior here, not domain workflows.

Function Description
getComponentIndex(Component component) Returns a component's index inside its parent, or -1 if not found.
humanReadableSize(long bytes) Formats byte counts as B, kB, MB, GB, or TB.
getPandomiumInstance() Lazily creates and starts a shared Pandomium browser instance.
buildCategorizedMenu(JPopupMenu menu, JMenuItem it, MTGCardsExport exp) Adds export menu items directly or under a category submenu.
browse(String uri) Opens a URI with Desktop.browse and logs failures.
createNewTable(TableModel mod, boolean enableFilter) Creates a configured JXTable with project defaults, optional filtering, column controls, renderers, drag support, and popup actions.
stringLineSplit(String s, boolean removeBlank) Splits a string by line separators, optionally removing blank lines.
createGridBagConstraints(Integer anchor, Integer fill, int col, int line) Creates GridBagConstraints with default spans, weights, and insets.
createGridBagConstraints(Integer anchor, Integer fill, int col, int line, int w, int h, double wx, double wy) Creates fully parameterized GridBagConstraints.
createSearchField() Creates a search text field with the localized placeholder text.
autocomplete(JTextField txtSearch) Adds word autocomplete behavior to a text field based on stringLineSplit.
createComboboxPlugins(Class<T> classe, boolean all) Creates a plugin combo box, optionally including all plugins or only enabled plugins.
createBindableJButton(String text, Icon ic, int key, String name) Creates a button and binds its keyboard shortcut.
bindJButton(JButton b, int key, String name) Registers a Ctrl+key binding that triggers the button click action.
createComboboxEditions(List<MTGEdition> value, SIZE s) Creates an edition combo box with an icon renderer sized by SIZE.
createComboboxEditions() Creates an edition combo box from the enabled cards provider's editions.
createCombobox(T[] items) Creates a combo box from an array with a standard autocomplete decorator.
createCombobox(List<T> items) Creates a combo box from a list with a standard autocomplete decorator.
createComboboxCollection() Creates a collection combo box from MTGControler collection names.
parseDouble(String text) Parses localized numeric text into a Double, returning 0.0 on parse failure.
roundDouble(double d) Rounds a double to two decimals.
formatDouble(Object f) Formats a number with default format and dot decimal separator.
formatDouble(Object f, Character separator) Formats a number with default format and custom decimal separator.
formatDouble(Object f, String format, Character separator) Formats a number with custom DecimalFormat pattern and separator.
initTableFilter(JXTable table) Adds a TableRowSorter, auto-complete row filter, and filter header to a table.
initTableVisibility(JXTable table, GenericTableModel<T> model) Adds the model's visibility menu to the table popup menu.
initCardToolTipTable(JTable table, Integer cardNamePos, Integer edPos, Integer idPos, Integer langPos) Adds card preview tooltip behavior to a table using model columns for card identity.
getTableSelections(JTable tableCards, int columnID) Returns selected model values from a column, converting view rows to model rows.
getTableSelection(JTable tableCards, int columnID) Returns the first selected model value from a column, or null.
getModelValueAt(JTable tableCards, int row, int column) Reads a table value after converting a view row to model row.
applyDefaultSelection(Component pane) Requests focus on the first button found in a component tree.
parseGMTDate(String gmtDate) Parses GMT HTTP-style dates with EEE, d MMM yyyy HH:mm:ss z.
parseDate(String indexDate) Parses a date with the default project date pattern.
parseDate(String indexDate, String format) Parses a date with a custom format and English locale.
parseDate(String indexDate, String format, Locale local) Parses a date with a custom format and locale.
formatDate(Date indexDate) Formats a date with the default project date pattern.
formatDate(Date indexDate, String format) Formats a date with a custom pattern.
formatDate(Instant date) Converts an instant to a date and formats it with the default project pattern.
formatDateTime(Date indexDate) Formats a date with the default project date-time pattern.
addTab(JTabbedPane pane, MTGUIComponent comp) Adds an MTGUIComponent tab with title and icon.
daysBetween(Instant d1, Instant d2) Returns the number of whole days between two instants.
getSelectedRows(JXTable table) Returns selected rows converted from view indexes to model indexes.
setSorter(JTable table, int i, NumberSorter numberSorter) Installs a row sorter and comparator for a column.
sort(JTable table, int index, SortOrder order) Applies a single-column sort order.
replaceSpecialCharacters(String str, String with) Replaces non-alphanumeric characters with the supplied replacement string.
createFlowPanel(JComponent... of) Creates a left-aligned flow panel containing components.
createFlowCenterPanel(JComponent... of) Creates a centered flow panel containing components.
generateRoundedIcon(Color color) Creates a small rounded color icon, typically for legends/status indicators.

WooCommerceTools

WooCommerce helper for account key generation, client creation, REST pagination, and JSON attribute payloads.

Function Description
generateKeysForWooCommerce() Generates a consumer key/secret pair using WooCommerce's ck_/cs_ prefixes and SHA-256 digests of UUIDs.
newClient(AccountAuthenticator p) Builds a WooCommerce client from an authenticator's KEY, SECRET, WEBSITE, and VERSION properties.
newClient(String key, String secret, String website, String version) Creates a configured WooCommerce client and overrides common REST methods for this project.
update(String endpointBase, int id, Map<String,Object> object) Client override: sends a PUT request to update an entity and returns the JSON object as a map.
create(String endpointBase, Map<String,Object> object) Client override: sends a POST request to create an entity and returns the JSON object as a map.
getAll(String endpoint) Client override: delegates to paginated getAll(endpoint, Map.of()).
getAll(String endpoint, Map<String,String> vars) Client override: retrieves paginated resources until a page returns fewer than 100 items.
get(String endpointBase, int id) Client override: fetches an entity by ID and returns the JSON object as a map.
delete(String endpointBase, int id) Client override: deletes an entity by ID.
batch(String endpointBase, Map<String,Object> object) Client override: sends a batch POST request and returns the JSON object as a map.
createAttributes(String key, String val, boolean visible) Creates a WooCommerce attribute JSON object with one option.
createAttributes(String key, String[] val, boolean visible) Creates a WooCommerce attribute JSON object with several options.
entryToJsonArray(String string, String value) Creates a one-entry JSON array object containing name and option properties.

XMLTools

XML helper designed to avoid common XXE/XML external entity issues.

Function Description
createSecureXMLDocumentBuilder() Creates a DocumentBuilder with external DTD/schema access disabled, secure processing enabled, XInclude disabled, and entity expansion disabled. Logs and returns null if builder creation fails.
parseNodes(Document doc, String expression) Evaluates an XPath expression against a DOM document and returns the result as a NodeList.

org.magic.services.threads

Threading helpers wrap background work in project audit metadata. Use these instead of ad-hoc threads when work should appear in technical diagnostics.

ThreadManager

Singleton executor manager for background tasks, Swing tasks, timers, and audit snapshots.

Function Description
getInstance() Returns the singleton manager.
executeThread(MTGRunnable task, String name) Names, stores, and executes an audited runnable on the configured executor.
submitThread(MTGRunnable task, String name) Names, stores, and submits an audited runnable, returning a Future<Object>.
submitCallable(Callable<V> task) Submits a plain callable to the executor and returns its typed future.
invokeLater(MTGRunnable task, String name) Names and stores an audited runnable, then queues it on the Swing event-dispatch thread.
runInEdt(SwingWorker<?, ?> runnable, String name) Executes a SwingWorker, creates task audit metadata, and updates the audit state as the worker starts, finishes, or is canceled.
initThreadPoolConfig(ThreadPoolConfig tpc) Builds the internal executor and thread factory from the supplied pool configuration.
stop() Shuts down the configured executor.
getFactory() Returns the current ThreadFactory.
toJson() Returns executor metrics and known task audit entries as JSON.
timer(MTGRunnable mtgRunnable, String name, int time, TimeUnit timeUnit) Schedules an audited runnable with a daemon Timer, after an initial five-minute delay.
sleep(int i) Sleeps the current thread and restores the interrupt flag if interrupted.

org.magic.services.network

Network helpers centralize HTTP configuration, response parsing, URL encoding, and network audit logging.

IPTranslator

Singleton location resolver for public IP addresses. Local, loopback, and site-local addresses return null.

Function Description
getInstance() Returns the singleton IP translator.
getLocationFor(String ip) Validates an IP address, resolves it through ip-api.com, caches the result, and returns a Location; returns null for private/invalid addresses or failures.

MTGHttpClient

Apache HTTP client wrapper with shared cookie context, default MTG Companion user agent, redirect handling, timeouts, and NetworkInfo audit storage.

Function Description
getHttpclient() Returns the underlying Apache HttpClient.
getResponse() Returns the last response executed by this client.
getHttpContext() Returns the HTTP context, including cookie and redirect state.
MTGHttpClient() Creates a pooled, redirect-aware client with project timeout and cookie settings.
toString(HttpResponse response) Reads a response entity as text and consumes the entity.
execute(RequestBuilder builder) Dispatches a RequestBuilder using its configured method.
doPut(String url, Map<String,String> entities, Map<String,String> headers) Sends a PUT request with URL-encoded form parameters.
doPut(String url, HttpEntity entities, Map<String,String> headers) Sends a PUT request with an explicit entity.
doPost(String url, Map<String,String> entities, Map<String,String> headers) Sends a POST request with URL-encoded form parameters.
doPost(String url, HttpEntity entities, Map<String,String> headers) Sends a POST request with an explicit entity.
doGet(String url, Map<String,String> headers, Map<String,String> entities) Sends a GET request with optional headers and query parameters.
doGet(String url) Sends a simple GET request.
getCookieValue(String cookieName) Returns the value of a named cookie from the client's cookie store.
getCookies() Returns all cookies currently stored by the client.

RequestBuilder

Fluent builder used throughout the project for HTTP calls and response conversion.

Function Description
METHOD Enum of supported methods: POST, GET, and PUT.
RequestBuilder() Creates a builder with empty header and content maps.
getUrl() / setUrl(String url) Reads or sets the request URL.
getMethod() Returns the selected HTTP method.
getHeaders() Returns the mutable header map.
getContent() Returns the mutable content/query-parameter map.
toContentString() Executes the request and returns the response entity as text.
toString() Formats the method, URL, headers, and content for diagnostics.
build() Static factory for a new builder.
get() / post() Selects the GET or POST method and returns the builder.
method(METHOD m) Sets the request method.
url(String u) / url(URI u) Sets the request URL from text or URI.
clearHeaders() / clearContents() Clears headers or content entries.
addHeaders(Map<String,String> headers2) Adds all supplied headers.
addHeader(String k, String c) Adds or replaces one header.
removeContent(String k) Removes one content/query entry.
updateContent(String k, String v) Replaces one content/query entry.
addContent(String k, String c) Adds or replaces one content/query entry.
setClient(MTGHttpClient client) Sets the HTTP client used by execute().
newClient() Creates and assigns a fresh MTGHttpClient.
toJson() Executes the request and parses the response as JSON; returns an error object on failure.
toImage() Executes the request and reads the response stream as a BufferedImage.
execute() Executes the request with the configured client.
clean() Clears headers/content, URL, and method for builder reuse.
toXml() Executes the request and parses the response with XMLTools.createSecureXMLDocumentBuilder().
toHtml() Executes the request and parses the response as Jsoup HTML.
getClient() Returns the configured client.
download(File dest) Downloads the response entity to a file through FileTools and logs size/duration.

URLTools

Static network and URL helper. It also defines shared HTTP header-name and content-type constants such as HEADER_JSON, ACCEPT, USER_AGENT, CONTENT_TYPE, and AUTHORIZATION.

Function Description
getExternalIp() Returns the external IP from checkip.amazonaws.com, or 0.0.0.0 on failure.
parseLinksHeader(Header header) Parses RFC-style pagination link headers into a rel -> URL map.
decode(String s) URL-decodes text using the project default encoding.
encode(String s) URL-encodes text using the project default encoding.
toHtml(String content) Parses text into a Jsoup Document.
toJson(String content) Parses text into a Gson JsonElement.
toJson(InputStream content) Parses an input stream into a Gson JsonElement, returning null on read failure.
toHtmlFromMarkdown(String c) Converts Markdown, including GitHub-flavored tables, into HTML.
extractAsXml(String url) GETs a URL and parses the response as secure XML.
extractAsJson(String url) GETs a URL and parses the response as JSON, returning an error object on failure.
extractAsHtml(String url) GETs a URL and parses the response as Jsoup HTML.
extractAsInputStream(String url) GETs a URL and returns the response content as a new in-memory input stream.
extractAsString(String url) GETs a URL and returns the response body as text.
download(String url, File to) Downloads a URL to a file through RequestBuilder.download.
extractMarkdownAsHtml(String url) GETs Markdown from a URL and parses the rendered HTML into a Jsoup document.
extractAsImage(String url) Reads an image from a URL, file: URI, or protocol-relative URL.
isCorrectConnection(String url) Returns true when a GET request returns an HTTP 2xx status.
newClient() Creates a new MTGHttpClient.
getLocation(String url) Executes a GET and returns the first redirect location, or the original URL on failure.
readAsBinary(String url) GETs a URL and returns response bytes.
getInternalIP() Returns the local host IP address, or 127.0.0.1 on failure.
extractElementText(Element element) Safely returns element text or an empty string for null.
toText(InputStream content) Reads a UTF-8 input stream into text.
createSecHeaders() Returns a browser-like set of sec-* headers for providers that require them.

org.magic.services.providers

Providers in this package are shared support providers, not plugin implementations. They cache icons, aliases, look-and-feel metadata, exchange rates, and MTGJSON prices.

ApilayerCurrencyConverter

Currency converter backed by a cached Apilayer live response.

Function Description
ApilayerCurrencyConverter(String token) Creates a converter with an API token and initializes the local cache file path.
getCurrentCurrency() Returns the configured application currency, or the locale currency when no explicit currency is configured.
convertTo(Currency from, Double value) Converts a value from a source currency to the current application currency; null values become 0.0.
getCurrencyDateCache() Returns the cache file modification date, or null if no cache exists.
convert(Currency from, Currency to, double value) Converts between two Currency instances.
convert(String from, String to, double value) Converts between two currency codes, using USD as an intermediate currency when needed and returning the original value on failure.
clean() Deletes the cache file and reinitializes exchange rates.
getChanges() Returns the loaded currency-rate map.
isEnable() Returns whether the currencylayer-converter-enable property is set to true.
init() Loads rates from the cache or downloads them from Apilayer, then fills the rate map.

IconsProvider

Singleton cache/provider for set icons and mana symbols.

Function Description
clean() Clears the local set-icon cache directory.
getInstance() Returns the singleton icon provider, initializing caches on first use.
getSVGIcon(String id) Returns an SVG set icon, downloading it from Keyrune when not cached and falling back to PMTG1 on failure.
get24(String id) Returns the cached 24x24 set icon for an edition ID.
get16(String id) Returns the cached 16x16 set icon for an edition ID.
getManaSymbol(String el) Returns a mana symbol image by numeric index or symbol text, handling special combined symbols for Mox Lotus and Gleemax.

LookAndFeelProvider

Swing look-and-feel helper that discovers installed, Substance, JTattoo, and FlatLaf themes.

Function Description
LookAndFeelProvider() Creates a provider with an empty extra look-and-feel cache.
setLookAndFeel(Component ui, LookAndFeelInfo lookAndFeel, boolean saving) Applies a LookAndFeelInfo by class name and optionally saves the choice.
setLookAndFeel(Component ui, String lookAndFeel, boolean saving) Applies a look-and-feel class name, loads FlatLaf custom defaults, updates the component tree, and optionally saves the choice.
getStandardLookAndFeel() Returns the look-and-feels installed in UIManager.
getAllLookAndFeel() Returns installed look-and-feels plus discovered extra themes.
getExtraLookAndFeel() Discovers and caches Substance, JTattoo, and FlatLaf themes through reflection.
saveProperties(Object key, Object value) Writes a UI property into UIManager.
setFont(FontUIResource myFont) Applies a font resource across common Swing UI defaults.

MTGJsonPricerProvider

Singleton helper that downloads MTGJSON AllPrices, builds vendor-specific cache files, and returns prices for MTG cards.

Function Description
SUPPORT Enum of supported price channels: PAPER and MTGO.
STOCK Enum of supported stock types: RETAIL and BUYLIST.
VENDOR Enum of supported vendors: CARDKINGDOM, TCGPLAYER, CARDHOARDER, CARDMARKET, CARDSPHERE, and MANAPOOL.
MTGJsonPricerProvider() Creates the Gson engine and vendor caches, downloading the main data file when missing.
getInstance() Returns the singleton provider, creating it on first use.
getVersion() Reads the MTGJSON metadata section and returns a Meta object, or null on failure.
loadData(VENDOR v) Loads a vendor-specific cache, rebuilding it from AllPrices when missing or expired.
getPriceFor(MTGCard card, VENDOR v) Returns the latest normal and foil prices found for a card/vendor pair.
expirationDay(Integer maxday) Overrides the vendor cache expiration threshold when a non-null value is supplied.

Meta

Package-private metadata bean for the MTGJSON file.

Function Description
toString() Formats the metadata as date plus version.
getDate() / setDate(String date) Reads or sets the metadata date.
getVersion() / setVersion(String version) Reads or sets the metadata version.

PriceEntry

Package-private price-entry bean used while building and reading vendor caches.

Function Description
getSupport() / setSupport(SUPPORT support) Reads or sets the price support channel.
getVendor() / setVendor(VENDOR v) Reads or sets the source vendor.
getStock() / setStock(STOCK stock) Reads or sets the stock type.
toString() Formats vendor/support/stock/foil/currency/latest-price information.
PriceEntry() Creates an entry with an empty sorted stock-price map.
isFoil() / setFoil(boolean foil) Reads or sets foil status.
getStockPrices() / setStockPrices(NavigableMap<String,Double> stockPrices) Reads or replaces the dated price map.
setCurrency(Currency currency) / setCurrency(String currency) Sets the entry currency from a Currency object or code.
getCurrency() Returns the entry currency.

Data

Package-private MTGJSON card-price aggregate.

Function Description
Data() Creates an aggregate with an empty price-entry list.
getPrices() Returns all price entries for the card.
listPricesByFoil(Boolean v) Filters prices by foil status.
toString() Formats the MTGJSON ID and all price entries.
getMtgjsonId() / setMtgjsonId(String mtgjsonId) Reads or sets the MTGJSON card ID.

PluginsAliasesProvider

Singleton resolver for plugin aliases loaded from the aliases JSON file/URL.

Function Description
inst() Returns the singleton aliases provider.
getReversedSetIdFor(MTGPlugin plug, MTGEdition set) Resolves a project edition ID back to a plugin-specific set ID.
getReversedSetIdFor(MTGPlugin plug, String setId) Resolves a project set ID string back to a plugin-specific set ID string.
getReversedSetNameFor(MTGPlugin plug, String setName) Resolves a project set name back to a plugin-specific set name.
getReversedConditionFor(MTGPlugin plug, String conditionName, EnumCondition defaultCondition) Resolves a provider condition string back to an EnumCondition, returning the default when unavailable.
getRegexFor(MTGPlugin plug, String k) Returns a plugin regex by key, falling back to the plugin default regex.
getConditionFor(MTGPlugin plug, EnumCondition condition) Resolves a project condition enum to a plugin condition string.
getConditionFor(MTGPlugin plug, EnumCondition condition, String defaults) Resolves a condition enum with a caller-provided fallback.
getSetNameFor(MTGPlugin plug, MTGEdition ed) Resolves an edition to a plugin set name.
getSetIdFor(MTGPlugin plug, MTGEdition ed) Resolves an edition to a plugin set ID.
getSetIdFor(MTGPlugin plug, String ed) Resolves a set ID string to a plugin set ID.
getSetNameFor(MTGPlugin plug, String ed) Resolves a set name string to a plugin set name.

When adding new helpers

  1. Add new helper methods to the most specific existing class. If the method mixes concerns, create a new service instead of expanding a broad utility class.
  2. Prefer methods that accept explicit inputs and return values instead of reading global state.
  3. Keep network and filesystem operations out of the Swing event-dispatch thread.
  4. Add tests for parsing, formatting, and transformation helpers when behavior can be validated without starting the full application.
  5. Update this page when adding, removing, or changing public helper methods in org.magic.services.tools, org.magic.services.threads, org.magic.services.network, or org.magic.services.providers.
⚠️ **GitHub.com Fallback** ⚠️