Skip to content
Snippets Groups Projects
Commit eff65199 authored by Raphael GIRARDOT's avatar Raphael GIRARDOT
Browse files

Moved some classes and resources from reduction-tools to CDMABox

parent 44b9eaf4
Branches
Tags
No related merge requests found
Showing
with 3573 additions and 2 deletions
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
<groupId>fr.soleil.lib</groupId> <groupId>fr.soleil.lib</groupId>
<artifactId>CDMABox</artifactId> <artifactId>CDMABox</artifactId>
<version>1.2.0</version> <version>1.2.1</version>
<name>CDMA Box</name> <name>CDMA Box</name>
<description>This project contains various tools to access data through CDMA</description> <description>This project contains various tools to access data through CDMA</description>
......
package fr.soleil.cdma.box.manager;
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileSystemView;
import fr.soleil.cdma.box.util.GUIUtilities;
import fr.soleil.cdma.box.util.comparator.LongComparator;
import fr.soleil.data.mediator.Mediator;
import fr.soleil.data.source.AbstractDataSource;
import fr.soleil.data.source.BasicDataSource;
import fr.soleil.lib.project.ObjectUtils;
import fr.soleil.lib.project.SystemUtils;
import fr.soleil.lib.project.file.FileUtils;
import fr.soleil.lib.project.math.ArrayUtils;
import fr.soleil.lib.project.resource.MessageManager;
/**
* This manager is able to list the files of a particular directory. It interacts with the file view
*
* @author girardot
*/
public class FileListManager implements IFileManager {
private File[] availableFiles;
private final BasicDataSource<File[]> fileListSource;
private FileRefresher refresher;
private MessageManager messageManager;
private String workingPath;
private boolean waitForStability;
private String[] filteredExtensions;
public FileListManager(MessageManager messageManager, String... filteredExtensions) {
this.messageManager = messageManager;
this.filteredExtensions = filteredExtensions;
availableFiles = null;
workingPath = null;
fileListSource = new BasicDataSource<File[]>(null);
// Ignore duplication test as it is already managed by this FileListManager
fileListSource.setIgnoreDuplicationTest(true);
refresher = null;
waitForStability = true;
}
public File[] getAvailableFiles() {
return availableFiles;
}
/**
* Returns whether this {@link FileListManager} waits for a file stability before considering it
* as valid and adding it in file list
*
* @return A <code>boolean</code> value
*/
public boolean isWaitForStability() {
return waitForStability;
}
/**
* Sets whether this {@link FileListManager} should wait for a file stability before considering
* it as valid and adding it in file list
*
* @param waitForStability Whether to wait for file stability (<code>TRUE</code> to wait for
* stability)
*/
public void setWaitForStability(boolean waitForStability) {
this.waitForStability = waitForStability;
}
public MessageManager getMessageManager() {
return messageManager;
}
public void setMessageManager(MessageManager messageManager) {
this.messageManager = messageManager;
}
/**
* Returns the data source that handles the file list
*
* @return An {@link AbstractDataSource}
*/
public AbstractDataSource<File[]> getFileListSource() {
return fileListSource;
}
@Override
public String getWorkingPath() {
return workingPath;
}
@Override
public void setFile(File file) {
stopRefreshing();
workingPath = (file == null ? null : file.getAbsolutePath());
startRefreshing(true);
}
/**
* Starts the refreshing {@link Thread} if necessary
*/
public synchronized void startRefreshing() {
startRefreshing(false);
}
public synchronized void startRefreshing(boolean startWithNullFiles) {
String path = getWorkingPath();
if (refresher == null) {
initRefresher(path, startWithNullFiles);
} else {
if (!ObjectUtils.sameObject(path, refresher.getPath())) {
refresher.cancel();
initRefresher(path, startWithNullFiles);
}
}
}
/**
* Stops the refreshing {@link Thread} if necessary
*/
public synchronized void stopRefreshing() {
if (refresher != null) {
refresher.cancel();
refresher = null;
}
}
protected boolean hasFilteredExtensions(String... filteredExtensions) {
return ((filteredExtensions != null) && (filteredExtensions.length > 0));
}
private boolean checkExtension(String[] filteredExtensions, File file) {
boolean fileOk;
if (file == null) {
fileOk = false;
} else if (file.isDirectory()) {
fileOk = true;
} else if (hasFilteredExtensions(filteredExtensions)) {
fileOk = false;
String ext = FileUtils.getExtension(file);
if ((ext != null) && (!ext.isEmpty())) {
for (String extension : filteredExtensions) {
if (ext.equalsIgnoreCase(extension)) {
fileOk = true;
break;
}
}
}
} else {
fileOk = true;
}
return fileOk;
}
private File[] filterFileArray(File[] files, String... filteredExtensions) {
File[] filteredFiles;
if (hasFilteredExtensions(filteredExtensions) && (files != null) && (files.length > 0)) {
Collection<File> fileList = new ArrayList<>(files.length);
for (File file : files) {
if (checkExtension(filteredExtensions, file)) {
fileList.add(file);
}
}
filteredFiles = fileList.toArray(new File[fileList.size()]);
fileList.clear();
} else {
filteredFiles = files;
}
return filteredFiles;
}
public File[] filterFiles(File[] files) {
return filterFileArray(files, filteredExtensions);
}
private void initRefresher(String path, boolean startWithNullFiles) {
availableFiles = null;
refresher = new FileRefresher(path, null, startWithNullFiles);
refresher.execute();
}
protected void setAvailableFiles(File[] availableFiles) {
if (!ArrayUtils.equals(availableFiles, this.availableFiles)) {
this.availableFiles = availableFiles;
fileListSource.setData(availableFiles);
}
}
// ///////////// //
// Inner classes //
// ///////////// //
/**
* This refresher regularly checks the directory to update the available file list. A file is
* considered available when it became stable. This is typically used to avoid Nexus API
* crashes.
*/
private class FileRefresher extends SwingWorker<Void, File[]> {
private static final int DEFAULT_SLEEPING_TIME = 5;
public static final String SLEEPING_TIME_PROPERTY = "SLEEPING_TIME";
public static final String VERBOSE_PROPERTY = "VERBOSE_REFRESHER";
protected final HashMap<String, File> knownFiles;
protected final HashMap<String, Long> lastKnownLength;
protected final HashMap<String, Long> lastKnownModificationDate;
private String path;
private volatile boolean canceled;
private long secondsToSleep;
private final boolean verbose;
private final Component parentComponent;
private volatile boolean startWithNullFiles;
private FileRefresher(String path, Component parentComponent, boolean startWithNullFiles) {
super();
this.parentComponent = parentComponent;
canceled = false;
this.path = path;
this.startWithNullFiles = startWithNullFiles;
secondsToSleep = SystemUtils.getSystemIntProperty(SLEEPING_TIME_PROPERTY, DEFAULT_SLEEPING_TIME);
if (secondsToSleep < 1) {
secondsToSleep = DEFAULT_SLEEPING_TIME;
}
verbose = SystemUtils.getSystemBooleanProperty(VERBOSE_PROPERTY, false);
knownFiles = new HashMap<String, File>();
lastKnownLength = new HashMap<String, Long>();
lastKnownModificationDate = new HashMap<String, Long>();
}
public String getPath() {
return path;
}
@Override
protected Void doInBackground() {
if (startWithNullFiles) {
publish((File[]) null);
try {
// wait a little bit to let time to EDT
Thread.sleep(200);
} catch (InterruptedException e) {
cancel();
}
}
boolean error = false;
while ((!error) && (!isCanceled())) {
try {
File dir = new File(path);
if (dir.isDirectory()) {
build(path);
}
dir = null;
if (verbose) {
long hours, minutes, seconds;
hours = secondsToSleep / 3600;
minutes = (secondsToSleep % 3600) / 60;
seconds = secondsToSleep % 60;
StringBuilder infoBuffer = new StringBuilder();
infoBuffer.append(GUIUtilities.nowToString());
infoBuffer.append(" - ");
infoBuffer.append(
messageManager.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.done"));
infoBuffer.append("\n");
infoBuffer.append(
messageManager.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.next"));
if (hours > 0) {
infoBuffer.append(" ");
infoBuffer.append(hours);
infoBuffer.append(messageManager
.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.hours"));
}
if (minutes > 0) {
infoBuffer.append(" ");
infoBuffer.append(minutes);
infoBuffer.append(messageManager
.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.minutes"));
}
if (seconds > 0) {
infoBuffer.append(" ");
infoBuffer.append(seconds);
infoBuffer.append(messageManager
.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.seconds"));
}
System.out.println(infoBuffer.toString());
infoBuffer = null;
} // end if (verbose)
if (!isCanceled()) {
Thread.sleep(1000L * secondsToSleep);
}
} catch (Throwable t) {
error = true;
if (!isCanceled()) {
t.printStackTrace();
StringBuilder messageBuffer = new StringBuilder();
messageBuffer.append(
messageManager.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.Error"));
messageBuffer.append("\n");
messageBuffer.append(messageManager
.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.Error.Type"));
messageBuffer.append(t.getClass());
messageBuffer.append("\n");
messageBuffer.append(messageManager
.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.Error.Message"));
messageBuffer.append(t.getMessage());
JOptionPane.showMessageDialog(parentComponent, messageBuffer.toString(),
messageManager.getMessage("fr.soleil.cdma.box.Error"), JOptionPane.ERROR_MESSAGE);
System.err.println(messageBuffer.toString());
}
}
}
clean();
return null;
}
@Override
protected void process(List<File[]> chunks) {
for (File[] availableFiles : chunks) {
if (isCanceled()) {
// cancel ASAP
break;
}
if ((availableFiles == null) && startWithNullFiles) {
startWithNullFiles = false;
setAvailableFiles(null);
} else {
setAvailableFiles(availableFiles);
}
}
}
private void build(String buildPath) {
final ArrayList<File> resultList = new ArrayList<>();
FileSystemView fileSystemView = FileSystemView.getFileSystemView();
File dir = new File(buildPath);
String[] extensions = filteredExtensions;
if (dir.isDirectory() && (!isCanceled())) {
File[] dirFiles = null;
TreeMap<Long, Collection<File>> fileMap = new TreeMap<>(new LongComparator(true));
if (!isCanceled()) {
dirFiles = filterFileArray(fileSystemView.getFiles(dir, false), extensions);
}
if (dirFiles != null) {
for (File file : dirFiles) {
if (isCanceled()) {
break;
}
Long key = Long.valueOf(file.lastModified());
Collection<File> fileList = fileMap.get(key);
if (fileList == null) {
fileList = new ArrayList<>();
}
fileList.add(file);
fileMap.put(key, fileList);
}
}
Set<Long> keySet = fileMap.keySet();
for (Long lastModified : keySet) {
if (isCanceled()) {
break;
}
Collection<File> fileList = fileMap.get(lastModified);
for (File file : fileList) {
if (isCanceled()) {
break;
}
String filePath = file.getAbsolutePath();
String fileName = file.getName();
Long lastLength = lastKnownLength.get(filePath);
final StringBuilder buffer = new StringBuilder();
buffer.append(messageManager
.getMessage("fr.soleil.cdma.box.manager.FileListManager.Refresh.File.Check"));
buffer.append(fileName);
if (lastLength == null) {
// File is not known yet: register it
if (verbose) {
System.out.println(buffer.toString());
}
lastKnownLength.put(filePath, Long.valueOf(file.length()));
lastKnownModificationDate.put(filePath, lastModified);
knownFiles.put(filePath, file);
if (!waitForStability) {
resultList.add(file);
}
} // end if (lastLength == null)
else {
if (((lastLength.longValue() == file.length())
&& (ObjectUtils.sameObject(lastModified, lastKnownModificationDate.get(filePath))))
|| (!waitForStability)) {
if (verbose) {
System.out.println(buffer.toString());
}
resultList.add(knownFiles.get(filePath));
} // end if (lastLength.longValue() == file.length())
else {
// File changed: register its new version
lastKnownLength.put(filePath, Long.valueOf(file.length()));
lastKnownModificationDate.put(filePath, lastModified);
knownFiles.put(filePath, file);
}
} // end if (lastLength == null) ... else
if (isCanceled()) {
break;
}
} // end for (File file : fileList)
if (isCanceled()) {
break;
}
} // end for (Long lastModified : keySet)
fileMap.clear();
} // end if (dir.isDirectory())
if (!isCanceled()) {
publish(filterFileArray(resultList.toArray(new File[resultList.size()]), extensions));
resultList.clear();
}
}
public boolean isCanceled() {
return canceled;
}
public void cancel() {
canceled = true;
}
protected void clean() {
knownFiles.clear();
lastKnownLength.clear();
lastKnownModificationDate.clear();
path = null;
}
}
@Override
public void addMediator(Mediator<?> mediator) {
// not managed
}
@Override
public void removeMediator(Mediator<?> mediator) {
// not managed
}
}
/**
*
*/
package fr.soleil.cdma.box.util;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author viguier
*
*/
public class DataFormatter {
public static Format getNumberFormat(int precision) {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(precision);
return numberFormat;
}
public static String getNumberAsString(double number, int precision) {
Format format = getNumberFormat(precision);
return format.format(number);
}
public static String getDateAsTimestamp(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd" + "-" + "HH.mm.ss");
return dateFormat.format(date);
}
}
package fr.soleil.cdma.box.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import fr.soleil.cdma.box.action.ExpandAllAction;
import fr.soleil.cdma.box.action.ReloadAction;
import fr.soleil.lib.project.ObjectUtils;
import fr.soleil.lib.project.resource.MessageManager;
import fr.soleil.lib.project.swing.icons.DecorableIcon;
import fr.soleil.lib.project.swing.icons.Icons;
import fr.soleil.lib.project.swing.tree.ExpandableTree;
/**
* Tool class for graphic uses
*
* @author girardot
*/
public class GUIUtilities {
public static final GUIUtilities DEFAULT_UTILITIES = new GUIUtilities("fr.soleil.cdma.box.icons");
public static final SimpleDateFormat DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd HH'h'mm'm'ss's'SSS'ms'");
public static final String CRLF = System.getProperty("line.separator");
protected static final int SMALL_SIZE = 11;
protected static final int MEDIUM_SIZE = 12;
protected static final int BIG_SIZE = 14;
protected static final int HUGE_SIZE = 24;
public static final Font DEFAULT_FONT = new Font(Font.DIALOG, Font.PLAIN, SMALL_SIZE);
public static final Font DEFAULT_FONT_BOLD = new Font(Font.DIALOG, Font.BOLD, SMALL_SIZE);
public static final Font BIG_FONT = new Font(Font.DIALOG, Font.PLAIN, MEDIUM_SIZE);
public static final Font DESCRITPION_FONT = new Font(Font.DIALOG, Font.ITALIC, SMALL_SIZE);
public static final Font TITLE_FONT = new Font(Font.DIALOG, Font.BOLD, MEDIUM_SIZE);
public static final Font MANDATORY_FONT = new Font(Font.SERIF, Font.BOLD, BIG_SIZE);
public static final Font MAIN_TITLE_FONT = new Font(Font.DIALOG, Font.BOLD, HUGE_SIZE);
public static final Font HIGHLIGHT_FONT = new Font(Font.DIALOG, Font.BOLD | Font.ITALIC, SMALL_SIZE);
public static final Font INFO_FONT = new Font(Font.DIALOG, Font.ITALIC, SMALL_SIZE);
public static final Font ERROR_FONT = new Font(Font.DIALOG, Font.ITALIC | Font.BOLD, MEDIUM_SIZE);
public static final Font NO_VALUE_FONT = new Font(Font.DIALOG, Font.ITALIC, MEDIUM_SIZE);
public static final Color OK_COLOR = Color.WHITE;
public static final Color KO_COLOR = new Color(255, 220, 150);
public static final Color MESSAGE_COLOR = new Color(255, 255, 220);
public static final Color PROPERTY_FILE_EDITOR_COLOR = new Color(220, 230, 255);
public static final Color WARNING_COLOR = new Color(255, 190, 50);
public static final Color ERROR_COLOR = new Color(255, 50, 50);
public static final Color MANDATORY_COLOR = Color.RED;
public static final Color MAIN_TITLE_COLOR = new Color(50, 50, 255);
public static final Border DEFAULT_LINE_BORDER = new LineBorder(Color.BLACK, 1);
public static final Border HIGHLIGHTED_LINE_BORDER = new LineBorder(Color.BLACK, 2);
public static final Border ERROR_BORDER = new LineBorder(Color.RED, 2);
public static final Insets NO_MARGIN = new Insets(0, 0, 0, 0);
private final Icons icons;
public static final Insets GAP = new Insets(2, 2, 5, 2);
public static final JLabel createNameLabel(String text) {
return createNameLabel(text, SwingConstants.LEFT);
}
public static final JLabel createNameLabel(MessageManager messageManager, String key, String titleSeparatorKey,
int alignment) {
JLabel label;
if (messageManager == null) {
label = createNameLabel(ObjectUtils.EMPTY_STRING, alignment);
} else if (key == null) {
if (titleSeparatorKey == null) {
label = createNameLabel(ObjectUtils.EMPTY_STRING, alignment);
} else {
label = createNameLabel(messageManager.getMessage(titleSeparatorKey), alignment);
}
} else if (titleSeparatorKey == null) {
label = createNameLabel(messageManager.getMessage(key), alignment);
} else {
label = createNameLabel(new StringBuilder(messageManager.getMessage(key))
.append(messageManager.getMessage(titleSeparatorKey)).toString(), alignment);
}
return label;
}
public static final JLabel createNameLabel(String text, int alignment) {
JLabel label = new JLabel(text, alignment);
label.setFont(DEFAULT_FONT_BOLD);
return label;
}
public static final JLabel createValueLabel(String text) {
return createValueLabel(text, SwingConstants.LEFT);
}
public static final JLabel createValueLabel(String text, int alignment) {
JLabel label = new JLabel(text, alignment);
label.setFont(DEFAULT_FONT);
return label;
}
public static final JLabel createDescriptionLabel(String text) {
return createDescriptionLabel(text, SwingConstants.LEFT);
}
public static final JLabel createDescriptionLabel(String text, int alignment) {
JLabel label = new JLabel(text, alignment);
label.setFont(DESCRITPION_FONT);
return label;
}
public GUIUtilities(String iconPackage) {
icons = new Icons(iconPackage);
}
public static JScrollPane generateTreeScrollPane(ExpandableTree tree, MessageManager messageManager) {
JScrollPane scrollPane;
if (tree == null) {
scrollPane = null;
} else {
scrollPane = new JScrollPane(tree);
JPanel toolbar = new JPanel(new GridBagLayout());
toolbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
int column = 0;
JButton reloadButton = new JButton(
new ReloadAction(messageManager.getMessage("fr.soleil.cdma.box.view.Tree.Reload"), tree));
reloadButton.setMargin(NO_MARGIN);
GridBagConstraints reloadConstraints = new GridBagConstraints();
reloadConstraints.fill = GridBagConstraints.NONE;
reloadConstraints.gridx = column++;
reloadConstraints.gridy = 0;
reloadConstraints.weightx = 0;
reloadConstraints.weighty = 0;
reloadConstraints.insets = GAP;
toolbar.add(reloadButton, reloadConstraints);
JButton expandButton = new JButton(
new ExpandAllAction(messageManager.getMessage("fr.soleil.cdma.box.view.Tree.ExpandAll"),
messageManager.getMessage("fr.soleil.cdma.box.view.Tree.CollapseAll"), tree, true));
expandButton.setMargin(NO_MARGIN);
GridBagConstraints expandConstraints = new GridBagConstraints();
expandConstraints.fill = GridBagConstraints.NONE;
expandConstraints.gridx = column++;
expandConstraints.gridy = 0;
expandConstraints.weightx = 0;
expandConstraints.weighty = 0;
expandConstraints.insets = GAP;
toolbar.add(expandButton, expandConstraints);
JButton collapseButton = new JButton(
new ExpandAllAction(messageManager.getMessage("fr.soleil.cdma.box.view.Tree.ExpandAll"),
messageManager.getMessage("fr.soleil.cdma.box.view.Tree.CollapseAll"), tree, false));
collapseButton.setMargin(NO_MARGIN);
GridBagConstraints collapseConstraints = new GridBagConstraints();
collapseConstraints.fill = GridBagConstraints.NONE;
collapseConstraints.gridx = column++;
collapseConstraints.gridy = 0;
collapseConstraints.weightx = 0;
collapseConstraints.weighty = 0;
collapseConstraints.insets = GAP;
toolbar.add(collapseButton, collapseConstraints);
GridBagConstraints glueConstraints = new GridBagConstraints();
glueConstraints.fill = GridBagConstraints.BOTH;
glueConstraints.gridx = column++;
glueConstraints.gridy = 0;
glueConstraints.weightx = 1;
glueConstraints.weighty = 1;
glueConstraints.insets = GAP;
toolbar.add(Box.createGlue(), glueConstraints);
scrollPane.setColumnHeaderView(toolbar);
}
return scrollPane;
}
/**
* <br>
* <b>Name: getProfileColor <br>
* <b>Description: Returns the background color used for profiles.
*
* @author SOLEIL
* @return Color
*/
public static Color getPropertyFileEditorColor() {
return new Color(192, 192, 255);
}
/**
* <br>
* <b>Name: getPlotSubPanelsEtchedBorder <br>
* <b>Description: return titledborder
*
* @author SOLEIL
* @param name of type String
* @return TitledBorder
*/
public static TitledBorder getPlotSubPanelsEtchedBorder(String name) {
try {
Color fColor = new Color(99, 97, 156);
return BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), name, TitledBorder.LEFT,
TitledBorder.DEFAULT_POSITION, TITLE_FONT, fColor);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* <br>
* <b>Name: colorToString <br>
* <b>Description: return the string corresponding to the Color
*
* @author SOLEIL
* @param color of type Color
* @return String
*/
public static String colorToString(Color color) {
try {
if (color == null) {
return null;
} else {
String ret = "";
ret += color.getRed() + ",";
ret += color.getGreen() + ",";
ret += color.getBlue() + ",";
return ret;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* <br>
* <b>Name: isTest5OK <br>
* <b>Description: Replaces all occurences of <CODE>toReplace</CODE> <br>
* in <CODE>in</CODE> by <CODE>replacement</CODE>.
*
* @author SOLEIL
* @param in The string to alter.
* @param toReplace The string to replace.
* @param replacement The replacement string.
* @return The altered string.
*/
public static String replace(String in, String toReplace, String replacement) {
try {
int lgDelim = toReplace.length();
ArrayList<Integer> limitersList = new ArrayList<Integer>();
StringBuilder finalString;
int startIdx;
int listIdx;
// Looking for the string to replace
startIdx = 0;
do {
startIdx = in.indexOf(toReplace, startIdx);
if (startIdx >= 0) {
limitersList.add(new Integer(startIdx));
startIdx += lgDelim;
}
} while (startIdx >= 0);
// Check if there is something to do
if (limitersList.size() == 0) {
return in;
}
// Backwards replace
finalString = new StringBuilder(in);
listIdx = limitersList.size() - 1;
do {
startIdx = limitersList.get(listIdx--).intValue();
finalString.replace(startIdx, startIdx + lgDelim, replacement);
} while (listIdx >= 0);
return finalString.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* <br>
* <b>Name: write2 <br>
* <b>Description: check if test is OK
*
* @author SOLEIL
* @param pw
* @param s
* @param hasNewLine
* @throw Exception
*/
public static void write2(PrintWriter pw, String s, boolean hasNewLine) throws Exception {
try {
if (hasNewLine) {
pw.println(s);
} else {
pw.print(s);
}
pw.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* <br>
* <b>Name:getPlotSubPanelsLineBorder <br>
* <b>Description:
*
* @author SOLEIL
* @param name of type String
* @param lineColor of type Color
* @return TitledBorder
*/
public static TitledBorder getPlotSubPanelsLineBorder(String name, Color lineColor) {
try {
Color fColor = new Color(99, 97, 156);
return BorderFactory.createTitledBorder(BorderFactory.createLineBorder(lineColor, 1), name,
TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, TITLE_FONT, fColor);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* <br>
* <b>Name:getPlotSubPanelsLineBorder <br>
* <b>Description:
*
* @author SOLEIL
* @param name of type String
* @param textColor of type Color
* @param lineColor of type Color
* @return TitledBorder
*/
public static TitledBorder getPlotSubPanelsLineBorder(String name, Color textColor, Color lineColor) {
try {
return BorderFactory.createTitledBorder(BorderFactory.createLineBorder(lineColor, 1), name,
TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, TITLE_FONT, textColor);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public ImageIcon getIcon(String path) {
return icons.getIcon(path);
}
public DecorableIcon getDecorableIcon(String path, String decoration) {
return icons.getDecorableIcon(path, decoration);
}
/**
* Returns a formated {@link String} that represents the current moment
*
* @return a {@link String}
*/
public static String nowToString() {
return longToStringDate(System.currentTimeMillis());
}
public static String getApplicationNameAndVersion(MessageManager messageManager) {
return getApplicationNameAndVersion(messageManager, null);
}
public static String getApplicationNameAndVersion(MessageManager messageManager, String applicationName) {
return appendApplicationNameAndVersion(messageManager, applicationName, new StringBuilder()).toString();
}
public static StringBuilder appendApplicationNameAndVersion(MessageManager messageManager, String applicationName,
StringBuilder builder) {
if (builder == null) {
builder = new StringBuilder();
}
builder.append(applicationName == null || applicationName.trim().isEmpty()
? messageManager.getAppMessage("project.name")
: applicationName);
builder.append(" ");
appendApplicationVersion(messageManager, builder);
return builder;
}
public static StringBuilder appendApplicationName(MessageManager messageManager, String applicationName,
StringBuilder builder) {
if (builder == null) {
builder = new StringBuilder();
}
builder.append(applicationName == null || applicationName.trim().isEmpty()
? messageManager.getAppMessage("project.name")
: applicationName);
return builder;
}
public static StringBuilder appendApplicationVersion(MessageManager messageManager, StringBuilder builder) {
if (builder == null) {
builder = new StringBuilder();
}
builder.append(messageManager.getAppMessage("project.version"));
// XXX buildnumber plugin does not seem to work any more with maven 3
// builder.append(" (");
// builder.append(messageManager.getAppMessage("build.date"));
// builder.append(")");
return builder;
}
public static void setComponentVisible(Component comp, boolean visible) {
if (comp != null) {
if (comp instanceof JPanel) {
JPanel panel = (JPanel) comp;
for (int i = 0; i < panel.getComponentCount(); i++) {
setComponentVisible(panel.getComponent(i), visible);
}
}
comp.setVisible(visible);
}
}
/**
* Ensures a {@link Runnable} is executed in Event Dispatch Thread
*
* @param runnable The {@link Runnable} to execute in Event Dispatch Thread
*/
public static void invokeInEDT(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeLater(runnable);
}
}
/**
* Ensures a {@link Runnable} is executed in Event Dispatch Thread, and waits for the end of its execution.
*
* @param runnable The {@link Runnable} to execute in Event Dispatch Thread
* @throws InvocationTargetException If an exception is thrown while running <code>runnable</code>
* @throws InterruptedException If we're interrupted while waiting for the event dispatching thread to finish
* executing <code>runnable.run()</code>
*/
public static void invokeInEDTAndWait(Runnable runnable) throws InvocationTargetException, InterruptedException {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeAndWait(runnable);
}
}
/**
* Returns The {@link String} representation of date, given as a long
*
* @param the long that represents the expected date
* @return a {@link String}
*/
public static String longToStringDate(long when) {
String result;
synchronized (DATE_FORMATER) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(when);
result = DATE_FORMATER.format(cal.getTime());
cal = null;
}
return result;
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import fr.soleil.lib.project.resource.MessageManager;
public class CreationDateFileNodeComparator extends FileNodeComparator {
public CreationDateFileNodeComparator(boolean ascending, MessageManager messageManager) {
super(ascending, messageManager);
}
@Override
protected int compareNotNull(File f1, File f2) {
return FileComparisonUtils.compareExistingFilesCreationDate(ascending, f1, f2);
}
@Override
public String getName(boolean ascending) {
return ascending
? messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.creation.ascending")
: messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.creation.descending");
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.Collator;
public class FileComparisonUtils {
public static int compareExistingFilesLastModificationDate(boolean ascending, File f1, File f2) {
int result;
long l1 = f1.lastModified(), l2 = f2.lastModified();
if (ascending) {
result = Long.compare(l1, l2);
} else {
result = Long.compare(l2, l1);
}
return result;
}
public static int compareExistingFilesCreationDate(boolean ascending, File f1, File f2) {
int result;
BasicFileAttributes attr1, attr2;
try {
attr1 = Files.readAttributes(f1.toPath(), BasicFileAttributes.class);
} catch (IOException e) {
attr1 = null;
}
try {
attr2 = Files.readAttributes(f2.toPath(), BasicFileAttributes.class);
} catch (IOException e) {
attr2 = null;
}
if (attr1 == null) {
if (attr2 == null) {
result = 0;
} else {
result = -1;
}
} else if (attr2 == null) {
result = 1;
} else {
FileTime ft1 = attr1.creationTime(), ft2 = attr2.creationTime();
if (ft1 == null) {
if (ft2 == null) {
result = 0;
} else {
result = -1;
}
} else if (ft2 == null) {
result = 1;
} else if (ascending) {
result = Long.compare(ft1.toMillis(), ft2.toMillis());
} else {
result = Long.compare(ft2.toMillis(), ft1.toMillis());
}
}
return result;
}
public static int compareExistingFilesName(Collator collator, boolean ascending, File f1, File f2) {
int result;
if (ascending) {
result = collator.compare(f1.getName(), f2.getName());
} else {
result = collator.compare(f2.getName(), f1.getName());
}
return result;
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import java.util.Comparator;
import javax.swing.tree.DefaultMutableTreeNode;
import fr.soleil.cdma.box.view.tree.node.FileNode;
import fr.soleil.lib.project.ObjectUtils;
import fr.soleil.lib.project.resource.MessageManager;
/**
* A {@link FileNode} {@link Comparator}
*
* @author GIRARDOT
*/
public abstract class FileNodeComparator extends NamedComparator<DefaultMutableTreeNode> {
public FileNodeComparator(boolean ascending, MessageManager messageManager) {
super(ascending, messageManager);
}
/**
* Returns whether this {@link FileNodeComparator} compares in ascending order
*
* @return A <code>boolean</code> value.
*/
public boolean isAscending() {
return ascending;
}
@Override
public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) {
int result;
if (o1 == null) {
if (o2 == null) {
result = 0;
} else {
result = -1;
}
} else if (o2 == null) {
result = 1;
} else if (o1 instanceof FileNode) {
if (o2 instanceof FileNode) {
FileNode fn1 = (FileNode) o1;
FileNode fn2 = (FileNode) o2;
File f1 = fn1.getData(), f2 = fn2.getData();
if (f1 == null) {
if (f2 == null) {
result = 0;
} else {
result = -1;
}
} else if (f2 == null) {
result = 1;
} else {
result = compareNotNull(f1, f2);
if (!ascending) {
result *= -1;
}
}
} else {
result = 1;
}
} else if (o2 instanceof FileNode) {
result = -1;
} else {
result = 0;
}
return result;
}
/**
* Compares 2 {@link File}s
*
* @param f1 First {@link File}. Can not be <code>null</code>.
* @param f2 Second {@link File}. Can not be <code>null</code>.
* @return A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater
* than the second.
*/
protected abstract int compareNotNull(File f1, File f2);
@Override
public boolean equals(Object obj) {
boolean equals;
if (obj == null) {
equals = false;
} else if (obj == this) {
equals = true;
} else if (getClass().equals(obj.getClass())) {
equals = ((FileNodeComparator) obj).isAscending() == isAscending();
} else {
equals = false;
}
return equals;
}
@Override
public int hashCode() {
int code = 0xF11E20DE;
int mult = 0xC039;
code = code * mult + getClass().hashCode();
code = code * mult + ObjectUtils.generateHashCode(isAscending());
return code;
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import fr.soleil.lib.project.resource.MessageManager;
public class LastModificationDateFileNodeComparator extends FileNodeComparator {
public LastModificationDateFileNodeComparator(boolean ascending, MessageManager messageManager) {
super(ascending, messageManager);
}
@Override
protected int compareNotNull(File f1, File f2) {
return FileComparisonUtils.compareExistingFilesLastModificationDate(ascending, f1, f2);
}
@Override
public String getName(boolean ascending) {
return ascending
? messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.modification.ascending")
: messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.modification.descending");
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import java.text.Collator;
import fr.soleil.lib.project.resource.MessageManager;
public class NameFileNodeComparator extends FileNodeComparator {
protected final Collator collator;
public NameFileNodeComparator(boolean ascending, MessageManager messageManager) {
super(ascending, messageManager);
collator = Collator.getInstance();
}
@Override
protected int compareNotNull(File f1, File f2) {
return FileComparisonUtils.compareExistingFilesName(collator, ascending, f1, f2);
}
@Override
public String getName(boolean ascending) {
return ascending ? messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.name.ascending")
: messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.name.descending");
}
}
package fr.soleil.cdma.box.util.comparator;
import java.util.Comparator;
import fr.soleil.lib.project.resource.MessageManager;
public abstract class NamedComparator<T> implements Comparator<T> {
protected final MessageManager messageManager;
protected final String name;
protected final boolean ascending;
public NamedComparator(boolean ascending, MessageManager messageManager) {
this.ascending = ascending;
this.messageManager = messageManager;
this.name = getName(ascending);
}
protected abstract String getName(boolean ascending);
@Override
public final String toString() {
return name;
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import fr.soleil.cdma.box.view.UriView;
import fr.soleil.lib.project.resource.MessageManager;
public class UriCreationDateComparator extends UriFileComparator {
public UriCreationDateComparator(boolean ascending, MessageManager messageManager, UriView uriView) {
super(ascending, messageManager, uriView);
}
@Override
protected String getName(boolean ascending) {
return ascending
? messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.creation.ascending")
: messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.creation.descending");
}
@Override
protected int compareExistingFiles(File f1, File f2) {
return FileComparisonUtils.compareExistingFilesCreationDate(ascending, f1, f2);
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import java.lang.ref.WeakReference;
import javax.swing.tree.DefaultMutableTreeNode;
import fr.soleil.cdma.box.view.UriView;
import fr.soleil.comete.definition.widget.util.ITreeNode;
import fr.soleil.lib.project.ObjectUtils;
import fr.soleil.lib.project.resource.MessageManager;
public abstract class UriFileComparator extends NamedComparator<DefaultMutableTreeNode> {
protected final WeakReference<UriView> uriViewRef;
public UriFileComparator(boolean ascending, MessageManager messageManager, UriView uriView) {
super(ascending, messageManager);
uriViewRef = uriView == null ? null : new WeakReference<UriView>(uriView);
}
@Override
protected abstract String getName(boolean ascending);
@Override
public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) {
int result = 0;
if (o1 == null) {
if (o2 == null) {
result = 0;
} else {
result = -1;
}
} else if (o2 == null) {
result = 1;
} else {
UriView uriView = ObjectUtils.recoverObject(uriViewRef);
if (uriView == null) {
result = 0;
} else {
ITreeNode i1 = uriView.getTreeNode(o1), i2 = uriView.getTreeNode(o2);
File f1 = uriView.getFile(i1), f2 = uriView.getFile(i2);
if (f1 == null) {
if (f2 == null) {
result = compareNullFiles(f1, f2, i1, i2, o1, o2);
} else {
result = -1;
}
} else if (f2 == null) {
result = 1;
} else if (f1.exists()) {
if (f2.exists()) {
result = compareExistingFiles(f1, f2);
} else {
result = 1;
}
} else if (f2.exists()) {
result = -1;
} else {
result = 0;
}
}
}
return result;
}
protected abstract int compareExistingFiles(File f1, File f2);
protected int compareNullFiles(File f1, File f2, ITreeNode i1, ITreeNode i2, DefaultMutableTreeNode o1,
DefaultMutableTreeNode o2) {
return 0;
}
}
\ No newline at end of file
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import fr.soleil.cdma.box.view.UriView;
import fr.soleil.lib.project.resource.MessageManager;
public class UriLastModificationDateComparator extends UriFileComparator {
public UriLastModificationDateComparator(boolean ascending, MessageManager messageManager, UriView uriView) {
super(ascending, messageManager, uriView);
}
@Override
protected int compareExistingFiles(File f1, File f2) {
return FileComparisonUtils.compareExistingFilesLastModificationDate(ascending, f1, f2);
}
@Override
public String getName(boolean ascending) {
return ascending
? messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.modification.ascending")
: messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.date.modification.descending");
}
}
package fr.soleil.cdma.box.util.comparator;
import java.io.File;
import java.text.Collator;
import javax.swing.tree.DefaultMutableTreeNode;
import fr.soleil.cdma.box.view.UriView;
import fr.soleil.comete.definition.widget.util.ITreeNode;
import fr.soleil.lib.project.resource.MessageManager;
public class UriNameComparator extends UriFileComparator {
private final Collator collator;
public UriNameComparator(boolean ascending, MessageManager messageManager, UriView uriView) {
super(ascending, messageManager, uriView);
this.collator = Collator.getInstance();
}
@Override
protected int compareExistingFiles(File f1, File f2) {
return FileComparisonUtils.compareExistingFilesName(collator, ascending, f1, f2);
}
@Override
protected int compareNullFiles(File f1, File f2, ITreeNode i1, ITreeNode i2, DefaultMutableTreeNode o1,
DefaultMutableTreeNode o2) {
int result;
if (i1 == null) {
if (i2 == null) {
result = collator.compare(o1.toString(), o2.toString());
if (!ascending) {
result *= -1;
}
} else {
result = -1;
}
} else if (i2 == null) {
result = 1;
} else {
Object d1 = i1.getData(), d2 = i2.getData();
if (d1 == null) {
if (d2 == null) {
result = collator.compare(i1.toString(), i2.toString());
if (!ascending) {
result *= -1;
}
} else {
result = -1;
}
} else if (d2 == null) {
result = 1;
} else {
result = collator.compare(d1.toString(), d2.toString());
if (!ascending) {
result *= -1;
}
}
}
return result;
}
@Override
public String getName(boolean ascending) {
return ascending ? messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.name.ascending")
: messageManager.getMessage("fr.soleil.cdma.box.view.UriOrFileView.sort.name.descending");
}
}
package fr.soleil.cdma.box.view;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;
import org.slf4j.LoggerFactory;
import fr.soleil.cdma.box.data.sensor.ExperimentConfig;
import fr.soleil.cdma.box.exception.CDMAAccessException;
import fr.soleil.cdma.box.manager.AcquisitionManager;
import fr.soleil.cdma.box.target.IExperimentConfigTarget;
import fr.soleil.cdma.box.util.ProgressDialogContainer;
import fr.soleil.data.mediator.Mediator;
import fr.soleil.data.source.AbstractDataSource;
import fr.soleil.data.source.BasicDataSource;
import fr.soleil.data.target.TargetDelegate;
import fr.soleil.lib.project.awt.WindowUtils;
import fr.soleil.lib.project.resource.MessageManager;
import fr.soleil.lib.project.swing.dialog.ProgressDialog;
/**
* This is a view that allows to choose a Sensor in order to load an acquisition, using an {@link AcquisitionManager}
*
* @author girardot
*/
public class AcquisitionLoadingView extends JPanel implements ActionListener, IExperimentConfigTarget {
private static final long serialVersionUID = 5531594971108171912L;
protected JComboBox<String> detectorCombo;
protected JButton validateButton;
protected AcquisitionManager acquisitionManager;
protected final TargetDelegate targetDelegate;
protected ExperimentConfig experimentConfig;
protected ProgressDialogContainer progressDialogContainer;
protected MessageManager messageManager;
protected JLabel detectorLabel;
protected JPanel fieldsPanel;
protected AbstractDataSource<Boolean> loadingSource;
protected final List<String> detectorList;
protected int selectedSensorConfig = -1;
protected final String applicationId;
protected final Object experimentLock;
/**
* Constructor
*
* @param acquisitionManager The associated {@link AcquisitionManager}
* @param messageManager The {@link MessageManager} that recovers the texts to display
*/
public AcquisitionLoadingView(String applicationId, AcquisitionManager acquisitionManager,
MessageManager messageManager, ProgressDialogContainer progressDialogContainer) {
super();
this.applicationId = (applicationId == null ? Mediator.LOGGER_ACCESS : applicationId);
detectorList = new ArrayList<>();
targetDelegate = new TargetDelegate();
this.progressDialogContainer = progressDialogContainer;
if (progressDialogContainer == null) {
progressDialogContainer = new ProgressDialogContainer();
}
experimentConfig = null;
this.acquisitionManager = acquisitionManager;
if (messageManager == null) {
messageManager = new MessageManager("fr.soleil.cdma.box");
}
this.messageManager = messageManager;
loadingSource = new BasicDataSource<Boolean>(null);
experimentLock = new Object();
initComponents();
addComponents();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
detectorCombo.setEnabled(enabled);
validateButton.setEnabled(enabled);
detectorLabel.setEnabled(enabled);
}
/**
* Initializes the components to display
*/
protected void initComponents() {
detectorCombo = new JComboBox<>();
detectorCombo.addActionListener(this);
validateButton = new JButton(
messageManager.getMessage("fr.soleil.cdma.box.view.AcquisitionLoadingView.button.validate"));
validateButton.addActionListener(this);
detectorLabel = new JLabel(
messageManager.getMessage("fr.soleil.cdma.box.view.AcquisitionLoadingView.combo.detector"));
fieldsPanel = new JPanel(new GridBagLayout());
}
/**
* layouts all the components
*/
protected void addComponents() {
Insets labelInsets = new Insets(0, 0, 5, 5);
Insets comboInsets = new Insets(0, 0, 5, 0);
GridBagConstraints detectorLabelConstraints = new GridBagConstraints();
detectorLabelConstraints.fill = GridBagConstraints.BOTH;
detectorLabelConstraints.gridx = 0;
detectorLabelConstraints.gridy = 0;
detectorLabelConstraints.weightx = 0;
detectorLabelConstraints.weighty = 0;
detectorLabelConstraints.insets = labelInsets;
fieldsPanel.add(detectorLabel, detectorLabelConstraints);
GridBagConstraints detectorComboConstraints = new GridBagConstraints();
detectorComboConstraints.fill = GridBagConstraints.BOTH;
detectorComboConstraints.gridx = 1;
detectorComboConstraints.gridy = 0;
detectorComboConstraints.weightx = 1;
detectorComboConstraints.weighty = 0;
detectorComboConstraints.insets = comboInsets;
fieldsPanel.add(detectorCombo, detectorComboConstraints);
setLayout(new GridBagLayout());
GridBagConstraints fieldsPanelConstraints = new GridBagConstraints();
fieldsPanelConstraints.fill = GridBagConstraints.BOTH;
fieldsPanelConstraints.gridx = 0;
fieldsPanelConstraints.gridy = 0;
fieldsPanelConstraints.weightx = 1;
fieldsPanelConstraints.weighty = 1;
add(new JScrollPane(fieldsPanel), fieldsPanelConstraints);
GridBagConstraints validateButtonConstraints = new GridBagConstraints();
validateButtonConstraints.fill = GridBagConstraints.NONE;
validateButtonConstraints.gridx = 0;
validateButtonConstraints.gridy = 1;
validateButtonConstraints.anchor = GridBagConstraints.CENTER;
add(validateButton, validateButtonConstraints);
}
/**
* Returns the {@link AbstractDataSource} that indicates when Acquisition is being calculated
*
* @return An {@link AbstractDataSource} of {@link Boolean}
*/
public AbstractDataSource<Boolean> getLoadingSource() {
return loadingSource;
}
/**
* Returns the {@link ProgressDialog} used by this {@link AcquisitionLoadingView}
*
* @return A {@link ProgressDialog}
*/
protected ProgressDialog getProgressDialog() {
ProgressDialog progressDialog = progressDialogContainer.getProgressDialog(this);
progressDialog.setProgressIndeterminate(true);
progressDialog.setCancelable(acquisitionManager.getCdmaReader());
return progressDialog;
}
/**
* Updates the detector list displayed in the detector combo box
*/
protected void updateDetectorList() {
updateDetectorList(false);
}
/**
* Updates the detector list displayed in the detector combo box
*/
protected void updateDetectorList(boolean forceDirectTransmission) {
boolean directTransmission = forceDirectTransmission;
detectorCombo.removeActionListener(this);
detectorCombo.removeAllItems();
detectorList.clear();
if (experimentConfig != null) {
detectorList.addAll(experimentConfig.getDetectorList());
if (detectorList.size() == 0) {
directTransmission = true;
} else {
for (String detector : detectorList) {
detectorCombo.addItem(detector);
}
}
}
detectorCombo.addActionListener(this);
selectedSensorConfig = detectorCombo.getSelectedIndex();
if (directTransmission) {
validateAcquisitionLoading();
} else {
manageDialogClosing(getProgressDialog());
}
}
/**
* Prepares the {@link AcquisitionManager} and asks it to load acquisition
*
* @throws CDMAAccessException If a problem occurred during acquisition loading
*/
protected void loadAcquisition() throws CDMAAccessException {
acquisitionManager.setDetector(getSelectedDetector());
acquisitionManager.loadAcquisition();
}
/**
* Returns the detected to use
*
* @return A {@link String}
*/
protected String getSelectedDetector() {
String detector = null;
if (selectedSensorConfig > -1) {
detector = detectorList.get(selectedSensorConfig);
}
return detector;
}
/**
* Displays the loading dialog, and load acquisition in a {@link SwingWorker}
*
* @see #loadAcquisition()
*/
protected void validateAcquisitionLoading() {
final ProgressDialog dialog = getProgressDialog();
if (dialog != null) {
dialog.setTitle(messageManager.getMessage("fr.soleil.cdma.box.view.data.loading.scan"));
String detector = getSelectedDetector();
if (detector == null) {
dialog.setMainMessage(dialog.getTitle());
} else {
dialog.setMainMessage(String
.format(messageManager.getMessage("fr.soleil.cdma.box.view.data.loading.detector"), detector));
}
dialog.pack();
dialog.setLocationRelativeTo(WindowUtils.getWindowForComponent(this));
dialog.setVisible(true);
}
try {
loadingSource.setData(true);
} catch (Exception e) {
LoggerFactory.getLogger(applicationId).error("Could not set loadingSource", e);
}
SwingWorker<Void, Void> acquisitionWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
loadAcquisition();
return null;
}
@Override
protected void done() {
manageDialogClosing(dialog);
try {
loadingSource.setData(false);
} catch (Exception e) {
LoggerFactory.getLogger(applicationId).error("Could not set loadingSource", e);
}
}
};
acquisitionWorker.execute();
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == detectorCombo) {
selectedSensorConfig = detectorCombo.getSelectedIndex();
} else if (source == validateButton) {
validateAcquisitionLoading();
}
}
@Override
public void addMediator(Mediator<?> mediator) {
targetDelegate.addMediator(mediator);
}
@Override
public void removeMediator(Mediator<?> mediator) {
targetDelegate.removeMediator(mediator);
}
@Override
public void setExperimentConfig(ExperimentConfig experimentConfig) {
synchronized (experimentLock) {
if (this.experimentConfig == experimentConfig) {
manageDialogClosing(getProgressDialog());
} else {
this.experimentConfig = experimentConfig;
updateDetectorList();
}
}
}
protected void manageDialogClosing(ProgressDialog dialog) {
if (dialog != null) {
dialog.setVisible(false);
}
}
}
package fr.soleil.cdma.box.view;
import javax.swing.SwingWorker;
import org.slf4j.LoggerFactory;
import fr.soleil.cdma.box.data.sensor.ExperimentConfig;
import fr.soleil.cdma.box.manager.AcquisitionManager;
import fr.soleil.cdma.box.util.ProgressDialogContainer;
import fr.soleil.lib.project.resource.MessageManager;
import fr.soleil.lib.project.swing.dialog.ProgressDialog;
/**
* An {@link AcquisitionLoadingView} that displays nothing and immediately loads acquisition when it
* receives an {@link ExperimentConfig}
*
* @author girardot
*/
public class FakeAcquisitionLoadingView extends AcquisitionLoadingView {
private static final long serialVersionUID = -6791307141659194248L;
/**
* Constructor
*
* @param acquisitionManager The associated {@link AcquisitionManager}
* @param messageManager The {@link MessageManager} that recovers the texts to display
*/
public FakeAcquisitionLoadingView(String applicationId, AcquisitionManager acquisitionManager,
MessageManager messageManager, ProgressDialogContainer progressDialogContainer) {
super(applicationId, acquisitionManager, messageManager, progressDialogContainer);
}
@Override
protected void addComponents() {
// nothing to do;
}
// @Override
// protected void updateDetectorList() {
// // nothing to do;
// }
//
// @Override
// protected void updateRegionList() {
// // nothing to do;
// }
@Override
protected ProgressDialog getProgressDialog() {
return progressDialogContainer.getProgressDialog(this);
}
@Override
public void setExperimentConfig(ExperimentConfig experimentConfig) {
synchronized (experimentLock) {
if (this.experimentConfig != experimentConfig) {
this.experimentConfig = experimentConfig;
updateDetectorList(true);
} else {
manageDialogClosing(getProgressDialog());
}
}
}
/**
* Displays the loading dialog, and load acquisition in a {@link SwingWorker}
*
* @see #loadAcquisition()
*/
@Override
protected void validateAcquisitionLoading() {
try {
loadingSource.setData(true);
} catch (Exception e) {
LoggerFactory.getLogger(applicationId).error("Could not set loadingSource", e);
}
SwingWorker<Void, Void> acquisitionWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
loadAcquisition();
return null;
}
@Override
protected void done() {
try {
loadingSource.setData(false);
} catch (Exception e) {
LoggerFactory.getLogger(applicationId).error("Could not set loadingSource", e);
}
}
};
acquisitionWorker.execute();
}
}
This diff is collapsed.
package fr.soleil.cdma.box.view;
import java.awt.Color;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.slf4j.LoggerFactory;
import fr.soleil.cdma.box.data.acquisition.Acquisition;
import fr.soleil.cdma.box.data.scan.ScanData;
import fr.soleil.cdma.box.target.IAcquisitionTarget;
import fr.soleil.cdma.box.util.DataFormatter;
import fr.soleil.comete.definition.util.AbstractValueConvertor;
import fr.soleil.comete.swing.Slider;
import fr.soleil.data.mediator.Mediator;
import fr.soleil.data.source.AbstractDataSource;
import fr.soleil.data.source.BasicDataSource;
import fr.soleil.lib.project.resource.MessageManager;
import net.miginfocom.swing.MigLayout;
/**
* This view allow to select an {@link ScanData} of an {@link Acquisition} through a {@link Slider}
*
* @author girardot
*/
public class ScanExplorer extends JPanel implements IAcquisitionTarget, ChangeListener {
private static final long serialVersionUID = -4277814127198319028L;
private static final String SLIDER_FORMAT = "%.2f";
private final JLabel scanLabel;
private final Slider scanSlider;
private final JTextField scanTextField;
private final Dictionary<Integer, JLabel> defaultScanLabelTable;
private Acquisition acquisition;
private List<ScanData> copy;
private final BasicDataSource<ScanData> scanDataSource;
private final ScanConvertor scanConvertor;
private final MessageManager messageManager;
protected final String applicationId;
public ScanExplorer(String applicationId) {
this(applicationId, new MessageManager("fr.soleil.cdma.box"));
}
/**
* Constructor
*/
public ScanExplorer(String applicationId, MessageManager messageManager) {
super(new MigLayout());
this.applicationId = (applicationId == null ? Mediator.LOGGER_ACCESS : applicationId);
this.messageManager = messageManager;
scanDataSource = new BasicDataSource<ScanData>(null);
scanDataSource.setIgnoreDuplicationTest(true);
defaultScanLabelTable = new Hashtable<Integer, JLabel>();
defaultScanLabelTable.put(0, new JLabel("Unavailable"));
scanLabel = new JLabel();
scanConvertor = new ScanConvertor();
scanSlider = generateSlider();
cleanScanSlider();
scanTextField = new JTextField(9);
scanTextField.setEditable(false);
setScanTitle(null);
add(scanLabel, "shrink");
add(scanSlider, "growx, push");
add(scanTextField, "wmin 50");
}
public void setGlobalBackground(Color bg) {
setBackground(bg);
scanSlider.setBackground(bg);
scanTextField.setBackground(bg);
}
/**
* Returns the {@link AbstractDataSource} that knows the selected {@link ScanData}
*
* @return An {@link AbstractDataSource}
*/
public AbstractDataSource<ScanData> getScanDataSource() {
return scanDataSource;
}
@Override
public synchronized void setAcquisition(Acquisition acquisition) {
this.acquisition = acquisition;
copy = (acquisition == null ? null : acquisition.getScanDataList());
refresh();
}
/**
* Creates a correctly initialized {@link Slider}
*
* @return A {@link Slider}
*/
protected Slider generateSlider() {
Slider slider = new Slider();
slider.setAutoScaleOnMinorTicksToo(false);
slider.setPreferedMajorTickColor(Color.BLACK);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(1);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
return slider;
}
@Override
public void addMediator(Mediator<?> mediator) {
// not managed
}
@Override
public void removeMediator(Mediator<?> mediator) {
// not managed
}
@Override
public synchronized void stateChanged(ChangeEvent e) {
if ((e != null) && (e.getSource() == scanSlider) && (!scanSlider.isEditingData())) {
updateScan();
}
}
public void updateScan() {
int index = scanSlider.getValue();
ScanData scanData = null;
if (acquisition == null) {
cleanScanSlider();
} else {
if ((copy != null) && (index < copy.size())) {
scanData = copy.get(index);
}
if (scanData == null) {
setScanText("");
} else {
if (Double.isNaN(scanData.getEnergy())) {
setScanText(scanData.getScanName());
} else {
setScanText(DataFormatter.getNumberAsString(scanData.getEnergy(), 5));
}
}
}
try {
scanDataSource.setData(scanData);
} catch (Exception e) {
LoggerFactory.getLogger(applicationId).error("Could not set scanDataSource", e);
}
}
/**
* Sets the "scan" text and reset caret position in energy textfield
*
* @param text The text to set
*/
private void setScanText(String text) {
if ((scanTextField != null) && (text != null)) {
scanTextField.setText(text);
scanTextField.setToolTipText(text);
scanTextField.setCaretPosition(0);
}
}
public String getScanTitle() {
return scanLabel.getText();
}
public void setScanTitle(String title) {
if (title == null) {
scanLabel.setText(messageManager.getMessage("fr.soleil.cdma.box.view.ScanExplorer.title"));
} else {
scanLabel.setText(title);
}
}
/**
* Updates the energy slider, so that it is adapted to last set acquisition
*/
private void refresh() {
if (acquisition != null) {
if ((copy != null) && (!copy.isEmpty())) {
scanSlider.removeChangeListener(this);
Dictionary<?, ?> labels;
if (acquisition.isEnergyAcquisition()) {
scanSlider.setFormat(SLIDER_FORMAT);
scanSlider.setValueConvertor(scanConvertor);
labels = null;
} else {
scanSlider.setFormat(null);
scanSlider.setValueConvertor(null);
Dictionary<Integer, JLabel> tmp = new Hashtable<Integer, JLabel>();
for (int i = 0; i < copy.size(); i++) {
ScanData scan = copy.get(i);
JLabel scanLabel = new JLabel(Integer.toString(i));
scanLabel.setToolTipText(scan.getScanName());
scanLabel.setHorizontalAlignment(JLabel.CENTER);
scanLabel.setVerticalAlignment(JLabel.CENTER);
tmp.put(i, scanLabel);
}
labels = tmp;
}
scanSlider.setToolTipText(null);
scanSlider.setEnabled(true);
scanSlider.setMinimum(0);
scanSlider.setMaximum(copy.size() - 1);
scanSlider.setValue(0);
scanSlider.setLabelTable(labels);
scanSlider.setPaintLabels(true);
scanSlider.addChangeListener(this);
}
}
scanConvertor.revalidate();
updateScan();
}
/**
* Cleans the scan slider, as if no {@link ScanData} is available
*/
private void cleanScanSlider() {
scanSlider.removeChangeListener(this);
scanSlider.setFormat(null);
scanSlider.setValueConvertor(null);
setScanText("Unavailable");
scanSlider.setEnabled(false);
scanSlider.setValue(0);
scanSlider.setMinimum(0);
scanSlider.setMaximum(0);
scanSlider.setLabelTable(defaultScanLabelTable);
setScanText(scanSlider.getToolTipText());
scanSlider.addChangeListener(this);
}
protected class ScanConvertor extends AbstractValueConvertor {
@Override
public double convertValue(double value) {
double result = value;
int index = (int) value;
if (isValid() && (index > -1) && (index < copy.size())) {
result = copy.get(index).getEnergy();
}
return result;
}
@Override
public boolean isValid() {
return ((acquisition != null) && (acquisition.isEnergyAcquisition()) && (copy != null)
&& (!copy.isEmpty()));
}
public void revalidate() {
warnListeners();
}
}
}
This diff is collapsed.
...@@ -557,7 +557,7 @@ public abstract class DoubleClickUriTree extends Tree implements ITreeNodeListen ...@@ -557,7 +557,7 @@ public abstract class DoubleClickUriTree extends Tree implements ITreeNodeListen
CDMABoxUtils.addExperimentUri(uri, result, searchForChildrenExperiments, cdmaKeyFactory); CDMABoxUtils.addExperimentUri(uri, result, searchForChildrenExperiments, cdmaKeyFactory);
} catch (Exception e) { } catch (Exception e) {
LoggerFactory.getLogger(applicationId) LoggerFactory.getLogger(applicationId)
.trace(messageManager.getMessage("fr.soleil.fusion.uri.recovery.error"), e); .trace(messageManager.getMessage("fr.soleil.cdma.box.uri.recovery.error"), e);
continue; continue;
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment