package util; import gui.GuiManager; import java.awt.Graphics2D; import java.awt.SystemColor; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.net.URL; import javax.swing.ImageIcon; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Text; /** * Helper class for loading resources. This should be error safe loaders with a * fall back in case the requested resource can't be found, or isn't of the * expected type. */ public class ResourceLoader { /** * Logger for this class */ private final static Logger LOGGER = Logger.getLogger(ResourceLoader.class); public static ImageData getImageData(String path) { ImageData _imgData = null; URL _url = ResourceLoader.class.getResource(path); if (_url == null) { LOGGER.error("Resource not found: " + path); return errorIcon("nope").getImageData(); } else { try { _imgData = new ImageData(_url.openStream()); } catch (Exception e) { LOGGER.error("Resource not loadable: " + path + ". See trace: ", e); return errorIcon("nope").getImageData(); } return _imgData; } } /** * Helper that will create an icon with given text. * @param errorText Text to render to icon * @return the icon */ private static Image errorIcon(String errorText) { GC gc = new GC(GuiManager.getDisplay()); Font font = new Font(GuiManager.getDisplay(), "Tahoma", 20, SWT.NORMAL); gc.setFont(font); // get dimensions of text Image image = new Image(GuiManager.getDisplay(), gc.stringExtent(errorText).x, gc.stringExtent(errorText).y); GC gc2 = new GC(image); gc2.setBackground(GuiManager.getDisplay().getSystemColor(SWT.COLOR_CYAN)); gc2.drawText(errorText, 0, 0); gc2.dispose(); return image; } /** * Tries to load the given resource treating it as a text file * * @param path * Resource path to load * @return content of the loaded resource as String */ public static String getTextFile(String path) { String fileContent = null; try { fileContent = IOUtils.toString(ResourceLoader.class .getResourceAsStream(path)); } catch (Exception e) { LOGGER.error("IO error while trying to load resource '" + path + "'. See trace: ", e); } if (fileContent != null) { return fileContent; } else { return "Resource '" + path + "' not found."; } } }