Java tutorial
/************************************************************************************************* * Copyright (c) 2013, Lex @ le boxon de Lex: http://le-boxon-de-lex.fr * * This program is free software; you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it with Eclipse (or * a modified version of that library), containing parts covered by the terms of Eclipse Public * License (EPL), the licensors of this Program grant you additional permission to convey the * resulting work. Corresponding Source for a non-source form of such a combination shall include * the source code for the parts of D'Aplomb used as well as that of the covered work. ***************************************************************************************************/ package net.leboxondelex.daplomb.utils; import java.io.File; import java.io.FileFilter; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.leboxondelex.daplomb.Activator; import net.leboxondelex.daplomb.translations.Messages; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; /** * @author Lex */ public class Utils { public static final String IMG_SUFFIX = ".jpg"; private static final String INTEGER_PATTERN = "[0-9]+"; //$NON-NLS-1$ private static final String[] IMAGE_EXTENSIONS = { "png", "gif", "jpg", "jpeg" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ private static final String[] ALL_IMAGE_EXTENSIONS = { "*.png; *.jpg; *.jpeg; *.gif" }; //$NON-NLS-1$ private static final String[] WIN_VIDEO_EXTENSIONS = new String[] { "*.avi; *.mpg; *.mpeg; *.ogm; *.ts; *.m2v; *.divx; *.mkv; *.mp4", //$NON-NLS-1$ }; /** * Finds the image files in a directory. * @param directory * @return an array of files, never null */ public static File[] findImageFiles(File directory) { FileFilter imgFilter = new FileFilter() { @Override public boolean accept(File pathname) { boolean result = false; if (pathname.isFile()) result = hasImageExtension(pathname.getName()); return result; } }; File[] imgFiles = directory.listFiles(imgFilter); return imgFiles != null ? imgFiles : new File[0]; } /** * Opens a file browser to select image files. * @param shell * @return a list of image files, never null */ public static List<File> openImagesSelectionDialog(Shell shell) { FileDialog dlg = new FileDialog(shell, SWT.MULTI); dlg.setFilterExtensions(ALL_IMAGE_EXTENSIONS); dlg.setFilterNames(new String[] { "Fichiers Images" }); dlg.setText("Slectionnez les images que vous sohaitez ajouter au collage."); List<File> selectedFiles = new ArrayList<File>(); if (dlg.open() != null) { for (String name : dlg.getFileNames()) { File f = new File(dlg.getFilterPath(), name); selectedFiles.add(f); } } return selectedFiles; } /** * Opens a file browser to select image files. * @param shell * @return a list of image files, never null */ public static File openImageSelectionDialog(Shell shell) { FileDialog dlg = new FileDialog(shell, SWT.SINGLE); dlg.setFilterExtensions(ALL_IMAGE_EXTENSIONS); dlg.setFilterNames(new String[] { "Fichiers Images" }); dlg.setText("Slectionnez les images que vous sohaitez ajouter au collage."); File result = null; if (dlg.open() != null) result = new File(dlg.getFilterPath(), dlg.getFileName()); return result; } /** * @param name * @return true if the name ends with an image extension */ public static boolean hasImageExtension(String name) { String ext = ""; //$NON-NLS-1$ int index = name.lastIndexOf('.'); if (index > 0) ext = name.substring(index + 1).toLowerCase(); return Arrays.asList(IMAGE_EXTENSIONS).contains(ext); } /** * @param name a name to clean * @return a cleared name */ public static String generateCleanDirectoryName(String name) { int index = name.lastIndexOf('.'); if (index > 0) name = name.substring(0, index); name = name.replaceAll("([^-0-9a-zA-Z_])", ""); return name; } /** * Finds the image files in a directory. * @param directory * @return an array of files, never null */ public static File[] findSubDirectories(File directory) { FileFilter dirFilter = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() && !pathname.isHidden() && !pathname.getName().startsWith("."); //$NON-NLS-1$ } }; File[] files = directory.listFiles(dirFilter); return files != null ? files : new File[0]; } /** * Formats a file size as a string (Kb). * @param fileSize * @return a string */ public static String formatFileSize(long fileSize) { long size = fileSize / 1024; return String.valueOf(size); } /** * Creates an image descriptor * @param path * @return */ public static ImageDescriptor findImageDescriptor(String path) { Bundle bundle = FrameworkUtil.getBundle(Activator.class); URL url = FileLocator.find(bundle, new Path(path), null); ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(url); return imageDescriptor; } /** * @param s any string (can be null) * @return true if it is an integer, false otherwise */ public static boolean isInteger(String s) { return s != null && s.matches(INTEGER_PATTERN); } /** * Finds and loads a resource image. * @param path the local path, e.g. "icons/idle.jpg" * @return an image, or null if the path is invalid */ public static Image findResourceImage(String path) { Image result = null; InputStream is = null; try { URI uri = new URI("platform:/plugin/" + Activator.PLUGIN_ID + "/" + path); //$NON-NLS-1$ //$NON-NLS-2$ is = uri.toURL().openStream(); ImageData data = new ImageData(is); result = ImageUtils.loadImage(data); } catch (Exception e) { LogUtils.log("Error while loading an image.", e); //$NON-NLS-1$ } finally { IoUtils.closeQuietly(is); } return result; } /** * Opens a message dialog with a the inner i18n system. * @param parent * @param title * @param message * @return true if the user presses the "yes" button */ public static boolean showQuestion(Shell parent, String title, String message) { MessageDialog dialog = new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, new String[] { "Oui", "Non" }, 0); return dialog.open() == 0; } /** * Opens an error dialog with a the inner i18n system. * @param parent * @param title * @param message */ public static void showError(Shell parent, String title, String message) { MessageDialog dialog = new MessageDialog(parent, title, null, message, MessageDialog.ERROR, new String[] { "OK" }, 0); dialog.open(); } /** * Opens a dialog to rename a file. * @param file a file (not null) * @param shell a shell (not null) * @return true if the file was renamed, false otherwise */ public static boolean openRenameDialog(final File file, Shell shell) { IInputValidator inputValidator = new IInputValidator() { @Override public String isValid(String newText) { String result = null; if (!Utils.hasImageExtension(newText)) result = Messages.getString("FileViewer.8"); //$NON-NLS-1$ else if (new File(file.getParentFile(), newText).exists()) result = Messages.getString("FileViewer.9"); //$NON-NLS-1$ return result; } }; InputDialog dlg = new InputDialog(shell, Messages.getString("FileViewer.6"), //$NON-NLS-1$ Messages.getString("FileViewer.7"), //$NON-NLS-1$ file.getName(), inputValidator); boolean result = false; if (dlg.open() == Window.OK) { File newFile = new File(file.getParent(), dlg.getValue()); result = file.renameTo(newFile); if (!result) { StringBuilder sb = new StringBuilder(); sb.append("Could not move file "); //$NON-NLS-1$ sb.append(file); sb.append(" to "); //$NON-NLS-1$ sb.append(newFile); LogUtils.log(sb.toString()); } } return result; } /** * @param shell the parent shell * @return a video file, or null if no video was selected */ public static File selectVideoFile(Shell shell) { FileDialog dlg = new FileDialog(shell, SWT.SINGLE); dlg.setFilterExtensions(WIN_VIDEO_EXTENSIONS); dlg.setFilterNames(new String[] { "Fichiers vido" }); dlg.setText("Slectionner une vido ouvrir."); File result = null; if (dlg.open() != null) result = new File(dlg.getFilterPath(), dlg.getFileName()); return result; } /** * @param o1 * @param o2 * @return true either if both string are null or if they are equal */ public static boolean areEqual(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } }