Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • sfb1280/studychecker
1 result
Show changes
Commits on Source (2)
Showing
with 28 additions and 1692 deletions
......@@ -8,5 +8,6 @@
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="lib/gson-2.10.1.jar"/>
<classpathentry kind="lib" path="lib/json-simple-1.1.1.jar"/>
<classpathentry kind="lib" path="lib/SFB_Lib_v20250324.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
File added
package assertion;
import java.io.File;
import java.util.LinkedList;
import utils.CSV_Reader;
import utils.SFB_JSON_Util;
public final class SFB_Assert {
private SFB_Assert() { }
public static void assertForAllMetaJson(String name, File basefolder, MetaJsonAssertion assertion) {
LinkedList<File> metas = getAllMetaJsonRecursive(basefolder);
if (metas.size() == 0)
System.out.println("[Warning] No meta data found during assertion: " + name);
boolean success = true;
for(File f:metas) {
if (!assertion.assertFile(f)) {
System.out.println("[FAILED: " + name + "] in: " + f.getAbsolutePath());
success = false;
break;
}
}
if (success)
System.out.println("Assertion successful: " + name);
}
public static void assertSubjectIDMatchesFolderName(String name, File basefolder) {
assertForAllMetaJson(name, basefolder, meta -> {
if (meta.getParent() == basefolder.getAbsolutePath())
return true;
String subjectID = SFB_JSON_Util.readFromJson(basefolder, "Subject ID");
subjectID = removeSubjPrefix(subjectID);
return meta.getAbsolutePath().contains(subjectID);
});
}
public static void assertAllMetaContain(String name, String key, String value, File basefolder) {
assertForAllMetaJson(name, basefolder, (meta) -> {
return SFB_JSON_Util.readFromJson(basefolder, key).equals(value);
});
}
public static void assertAllMetaNonEmpty(String name, String key, File basefolder) {
assertForAllMetaJson(name, basefolder, (meta) -> {
return SFB_JSON_Util.readFromJson(basefolder, key) != null;
});
}
public static void assertMetaTableContentCoherent(String name, CSV_Reader csv, int csvSubjectIDColoumnID, int csvColoumID, String metaField, File basefolder) {
assertForAllMetaJson(name, basefolder, (meta) -> {
return SFB_JSON_Util.readFromJson(meta, (obj) -> {
int row = -1;
@SuppressWarnings("unchecked")
String subjIdMeta = (String) obj.getOrDefault("Subject ID", null);
if (subjIdMeta == null || subjIdMeta.equals("")) {
System.out.println("Meta.Json SubjectID empty");
return false;
}
for(int i = 0; i < csv.getMaxRows(); i++) {
String subjID = csv.get(csvSubjectIDColoumnID, row);
subjID = removeSubjPrefix(subjID);
if (subjIdMeta.contains(subjID)) {
row = i;
break;
}
}
if (row == -1) {
System.out.println("Subject ID: " + subjIdMeta + " not found in JSON");
return false;
}
return csv.get(csvColoumID, row).equals(obj.get(metaField));
});
});
}
private static String removeSubjPrefix(String subjectID) {
int indexOfPrefix = subjectID.indexOf("sub-");
if (indexOfPrefix != 0)
subjectID = subjectID.substring(indexOfPrefix + 4);
return subjectID;
}
private static LinkedList<File> getAllMetaJsonRecursive(File base) {
LinkedList<File> res = new LinkedList<File>();
_getAllMetaJsonRecursive(base, res);
return res;
}
private static void _getAllMetaJsonRecursive(File currentDir, LinkedList<File> list) {
File metaJson = new File(currentDir.getAbsolutePath() + File.separator + "meta.json");
if (metaJson.exists())
list.add(metaJson);
for(File f:currentDir.listFiles(f -> f.isDirectory())) {
_getAllMetaJsonRecursive(f, list);
}
}
public interface MetaJsonAssertion {
public boolean assertFile(File metaJson);
}
}
......@@ -23,12 +23,13 @@ public class Main {
new LabelPanel("use \".\" to treat every folder as a subject folder", 11),
inputPanel
);
LabelPanel advancedSubjectSearchDescription = new LabelPanel("Checks all folders for possible subjects. (Refer to readme)", 11);
ConditionedPanel advancedSubjectSearchPanel = new ConditionedPanel("Advanced Subject Search", true, advancedSubjectSearchDescription);
ConditionedPanel isBIDSPanel = new ConditionedPanel("is BIDS format", false);
SimpleFrame frame = SimpleFrame.createStudyChooserFrame("Study Checker", "Study Base Folder", new JPanel[] {conditionedPanel, advancedSubjectSearchPanel}, (File baseFolder) -> {
SimpleFrame frame = SimpleFrame.createStudyChooserFrame("Study Checker", "Study Base Folder", new JPanel[] {isBIDSPanel, conditionedPanel, advancedSubjectSearchPanel}, (File baseFolder) -> {
if (baseFolder == null || !baseFolder.exists()) {
SimpleFrame.promt("Please select a valid study base folder");
return;
......@@ -51,7 +52,8 @@ public class Main {
}
checker.setAdvancedSubjectSearch(advancedSubjectSearchPanel.getOutput());
checker.setBIDSFormat(isBIDSPanel.getOutput());
String experimentName = baseFolder.getName();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH-mm-ss");
......
......@@ -11,6 +11,7 @@ public class StudyChecker {
private File dir;
private String subjPrefix = "sub-";
private boolean isBIDS = false;
public String[] knownModalities = new String[] {
"Behavorial",
......@@ -78,6 +79,10 @@ public class StudyChecker {
this.subjPrefix = prefix;
}
public void setBIDSFormat(boolean bidsFlag) {
this.isBIDS = bidsFlag;
}
public void check() {
File[] subjs = findSubjects();
......@@ -182,7 +187,8 @@ public class StudyChecker {
private void inSessionCheck(File sessionF) {
File[] modalities = sessionF.listFiles(f -> f.isDirectory());
inconsitentModalityError.checkSubj(sessionF, modalities, currentSessionIndex);
if (!isBIDS)
inconsitentModalityError.checkSubj(sessionF, modalities, currentSessionIndex);
for(File mod : modalities) {
......@@ -194,17 +200,19 @@ public class StudyChecker {
}
private void inModalityCheck(File modality) {
boolean nameKnown = false;
String nameLower = modality.getName().toLowerCase();
for(String m : knownModalities) {
if (m.equals(nameLower)) {
nameKnown = true;
break;
if (!isBIDS) { // BIDS has special modality names!
boolean nameKnown = false;
String nameLower = modality.getName().toLowerCase();
for(String m : knownModalities) {
if (m.equals(nameLower)) {
nameKnown = true;
break;
}
}
if (!nameKnown) {
unknownModalityError.add(modality, "Name: " + modality.getName());
}
}
if (!nameKnown) {
unknownModalityError.add(modality, "Name: " + modality.getName());
}
metaJsonErrorCheck(modality, true);
......@@ -222,8 +230,9 @@ public class StudyChecker {
noMetaDataInSubjectError.checkCurrentSubj();
SFB_JSON_Util.readInJson(metaJson, (obj) -> {
String subjID = (String) obj.getOrDefault("Subject ID", null);
if (!(currentSubjName.equals(subjID) || (subjPrefix + currentSubjName).equals(subjID))) {
@SuppressWarnings("unchecked")
String subjID = ((String) (obj.getOrDefault("Subject ID", ""))).trim();
if (!(currentSubjName.equals(subjID) || (currentSubjName).equals(subjPrefix + subjID) || (currentSubjName).equals("sub-" + subjID))) {
incorrectSubjectIDInMetaDataError.add(metaJson, currentSubjName + " != " + subjID);
}
......
package uiutils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import utils.Debug;
public class ButtonPanel extends JPanel{
private static final long serialVersionUID = 849541179312884049L;
private JButton btn;
public ButtonPanel(String text){
super();
btn = new JButton(text);
this.add(btn);
}
public ButtonPanel(String text, ActionListener list) {
this(text);
addActionListener(list);
}
public void addActionListener(ActionListener list) {
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Thread worker = new Thread(new Runnable() {
@Override
public void run() {
try {
list.actionPerformed(e);
} catch(Exception e) {
Debug.Error(e);
e.printStackTrace();
}
}
});
worker.start();
}
});
}
public void SetEnabled(boolean state){
btn.setEnabled(state);
}
}
package uiutils;
import java.awt.FlowLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
public class CheckboxPanel extends JPanel implements IOutput<Boolean>{
private static final long serialVersionUID = 186566928368140438L;
private JCheckBox checkBox;
public CheckboxPanel(String text, boolean ticked) {
super();
this.setLayout(new FlowLayout(FlowLayout.LEFT));
checkBox = new JCheckBox(text, ticked);
this.add(checkBox);
}
public CheckboxPanel setToolTip(String txt) {
this.checkBox.setToolTipText(txt);
return this;
}
@Override
public Boolean getOutput() {
return checkBox.isSelected();
}
}
package uiutils;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ComboSelectionPanel extends JPanel implements IOutput<String[]>{
private static final long serialVersionUID = -2030551269354521325L;
public static final String[] SFB_MODALITIES = new String[] {"Behavorial", "Calcium Imaging", "ECG|Pulse", "EDA", "EEG", "Eyetracking", "Histology", "Hormone measurements", "LFP", "MRI", "Questionaires", "Respiration", "Single cell recording", "TMS"};
private ComboSelections comboSel;
public ComboSelectionPanel(String text, String selectionEmptyText, String...selectionItems) {
super();
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(new JLabel(text));
comboSel = new ComboSelections(selectionEmptyText, selectionItems);
this.add(comboSel);
}
public ComboSelectionPanel setPrefSpinnerWidth(int width) {
comboSel.setPreferredSize(new Dimension(width, comboSel.getPreferredSize().height));
return this;
}
@Override
public String[] getOutput() {
return comboSel.GetSelectedStrings();
}
}
package uiutils;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JPopupMenu;
/**
* This is a custom component.
* This behaves as a multi-selection-JCombobox
*
*/
public class ComboSelections extends JButton{
/**
*
*/
private static final long serialVersionUID = -6963622395686623256L;
private JCheckBoxMenuItem[] menuItems;
private String[] strings;
private JPopupMenu menu;
private String nothingSelectedName;
private LinkedList<String> buttonTitleStrings = new LinkedList<>();
public ComboSelections(String menuButtonName, String[] strings) {
super(menuButtonName);
this.nothingSelectedName = menuButtonName;
menuItems = new JCheckBoxMenuItem[strings.length];
this.strings = strings.clone();
menu = new JPopupMenu();
for(int i = 0; i < strings.length; i++) {
menuItems[i] = new JCheckBoxMenuItem(strings[i]);
//menuItems[i].setSelected(true);
//menuItems[i].doClick();
menu.add(menuItems[i]);
}
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!menu.isVisible()) {
Point p = ComboSelections.this.getLocationOnScreen();
menu.setInvoker(ComboSelections.this);
menu.setLocation((int) p.getX(),
(int) p.getY() + ComboSelections.this.getHeight());
menu.setVisible(true);
} else {
menu.setVisible(false);
}
}
});
for(JCheckBoxMenuItem m : menuItems) {
m.addActionListener(new OpenAction(menu, this));
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JCheckBoxMenuItem source = (JCheckBoxMenuItem)e.getSource();
if (source.getState()) { // Add
buttonTitleStrings.add(source.getText());
} else { // remove
buttonTitleStrings.remove(source.getText());
}
UpdateButtonText();
}
});
}
}
/**
* Toggles certain entries of the Multicombobox
*
* @param entriesToToggle the entires to toggle
*/
public synchronized void ToggleEntries(String[] entriesToToggle) {
menu.setVisible(true);
for(JCheckBoxMenuItem m : menuItems) {
if (arrayContains(entriesToToggle, m.getText())) {
//m.setState(true);
m.setSelected(true);
buttonTitleStrings.add(m.getText());
}
}
menu.setVisible(false);
UpdateButtonText();
}
private boolean arrayContains(String[] arr, String elem) {
for(String s : arr) {
if (s.equals(elem))
return true;
}
return false;
}
/**
* Updates the Button Title text, so that it fits the buttonTitleStrings List
*/
private final void UpdateButtonText() {
String txt = "";
for(String s : buttonTitleStrings) {
txt += s + ", ";
}
if (txt.length() > 2) {
txt = txt.substring(0, txt.length() - 2);
} else {
txt = nothingSelectedName;
}
this.setText(txt);
}
private static class OpenAction implements ActionListener {
private JPopupMenu menu;
private JButton button;
private OpenAction(JPopupMenu menu, JButton button) {
this.menu = menu;
this.button = button;
}
@Override
public void actionPerformed(ActionEvent e) {
menu.show(button, 0, button.getHeight());
}
}
public String[] GetSelectedStrings(){
LinkedList<String> result = new LinkedList<>();
for(int i = 0; i < strings.length; i++) {
if (menuItems[i].getState())
result.add(strings[i]);
}
return result.toArray(new String[0]);
}
public static ComboSelections getModalitySelection() {
return new ComboSelections("Select", new String[] {"Behavorial", "Calcium Imaging", "ECG|Pulse", "EDA", "EEG", "Eyetracking", "Histology", "Hormone measurements", "LFP", "MRI", "Questionaires", "Respiration", "Single cell recording", "TMS"});
}
}
\ No newline at end of file
package uiutils;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
public class ConditionedPanel extends JPanel implements ActionListener, IOutput<Boolean>{
private static final long serialVersionUID = 9148401845646235697L;
private JCheckBox checkBox;
private JPanel[] interalPanels;
public ConditionedPanel(String text, boolean initalValue, JPanel...internalPanels) {
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
checkBox = new JCheckBox(text, initalValue);
checkBox.addActionListener(this);
this.add(leftJustify(checkBox));
JPanel[] borderLayoutPanel = new JPanel[internalPanels.length];
JPanel[] leftBorderLayoutOffsetPanel = new JPanel[internalPanels.length];
for(int i = 0; i < internalPanels.length; i++) {
borderLayoutPanel[i] = new JPanel(new BorderLayout());
leftBorderLayoutOffsetPanel[i] = new JPanel();
leftBorderLayoutOffsetPanel[i].setBorder(new EmptyBorder(0, 20, 0, 0));
borderLayoutPanel[i].add(leftBorderLayoutOffsetPanel[i], BorderLayout.WEST);
borderLayoutPanel[i].add(internalPanels[i], BorderLayout.CENTER);
this.add(leftJustify(borderLayoutPanel[i]));
}
this.interalPanels = internalPanels;
actionPerformed(null);
}
private Component leftJustify( JComponent panel ) {
Box b = Box.createHorizontalBox();
b.add( panel );
b.add( Box.createHorizontalGlue() );
return b;
}
@Override
public Boolean getOutput() {
return checkBox.isSelected();
}
public JPanel getInternalPanel() {
return interalPanels[0];
}
public JPanel[] getInternalPanels() {
return interalPanels;
}
@SuppressWarnings("unchecked")
public <T> T getInternalOutput() {
return ((IOutput<T>)interalPanels[0]).getOutput();
}
@SuppressWarnings("unchecked")
public <T> LinkedList<T> getInternalOutputs() {
LinkedList<T> list = new LinkedList<T>();
for(int i = 0; i < interalPanels.length; i++) {
list.add(((IOutput<T>)interalPanels[0]).getOutput());
}
return list;
}
@Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < interalPanels.length; i++) {
enableRecursive(interalPanels[i], checkBox.isSelected());
}
}
private void enableRecursive(Component comp, boolean enabled) {
comp.setEnabled(enabled);
if (comp instanceof Container) {
for(Component c : ((Container)(comp)).getComponents()) {
enableRecursive(c, enabled);
}
}
}
}
package uiutils;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
public class FileChooserPanel extends JPanel implements IOutput<File>, ActionListener{
private static final long serialVersionUID = 3136641561102977065L;
private JButton button;
private JLabel text;
private File out;
private int maxFilenameCharactersShown;
private boolean selectFile = false;
private String fileEnding = "";
public FileChooserPanel(String btnTxt) {
this(btnTxt, 30);
}
public FileChooserPanel(String btnTxt, int maxFilenameCharactersShown) {
super();
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.maxFilenameCharactersShown = maxFilenameCharactersShown;
button = new JButton(btnTxt);
button.addActionListener(this);
text = new JLabel("no folder selected");
this.add(button);
this.add(text);
}
public FileChooserPanel switchToFileSelect(String fileEndingFilter) {
selectFile = true;
this.fileEnding = fileEndingFilter;
text.setText("no file selected");
return this;
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
if (!selectFile) {
chooser.setDialogTitle("Select Folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
chooser.setDialogTitle("Select File");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "*" + fileEnding;
}
@Override
public boolean accept(File f) {
return f.getName().endsWith(fileEnding) || f.isDirectory();
}
});
}
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
out = chooser.getSelectedFile();
text.setText(out.getAbsolutePath().substring(
(int)Math.max(0, out.getAbsolutePath().length() - maxFilenameCharactersShown)));
this.revalidate();
}
}
@Override
public File getOutput() {
return out;
}
}
package uiutils;
public interface IOutput<T> {
T getOutput();
}
package uiutils;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.TextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.Document;
public class InputFieldPanel extends JPanel implements IOutput<String>{
private PlaceholderTextField txtField;
public InputFieldPanel(String text, String placeholder) {
super();
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(new JLabel(text));
txtField = new PlaceholderTextField();
txtField.setPlaceholder(placeholder);
setTextFieldprefWidth(150);
this.add(txtField);
}
public InputFieldPanel setTextFieldprefWidth(int width) {
txtField.setPreferredSize(new Dimension(width, txtField.getPreferredSize().height));
return this;
}
@Override
public String getOutput() {
return txtField.getText();
}
private class PlaceholderTextField extends JTextField {
private String placeholder;
public PlaceholderTextField() {
}
public PlaceholderTextField(
final Document pDoc,
final String pText,
final int pColumns)
{
super(pDoc, pText, pColumns);
}
public PlaceholderTextField(final int pColumns) {
super(pColumns);
}
public PlaceholderTextField(final String pText) {
super(pText);
}
public PlaceholderTextField(final String pText, final int pColumns) {
super(pText, pColumns);
}
public String getPlaceholder() {
return placeholder;
}
@Override
protected void paintComponent(final Graphics pG) {
super.paintComponent(pG);
if (placeholder == null || placeholder.length() == 0 || getText().length() > 0) {
return;
}
final Graphics2D g = (Graphics2D) pG;
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getDisabledTextColor());
g.drawString(placeholder, getInsets().left, pG.getFontMetrics()
.getMaxAscent() + getInsets().top);
}
public void setPlaceholder(final String s) {
placeholder = s;
}
}
}
package uiutils;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class LabelPanel extends JPanel {
private static final long serialVersionUID = -1976617261814898346L;
public LabelPanel(String text, int fontSize) {
super();
this.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel lbl = new JLabel(text);
Font lblFont = lbl.getFont();
lbl.setFont(new Font(lblFont.getFontName(), lblFont.getStyle(), fontSize));
this.add(lbl);
}
}
package uiutils;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class ProgressBar {
public static ProgressBar latest;
private static String FILE_SEPERATOR_REGEX = "\\\\";
private static int FILE_LABEL_HEIGHT = 30;
private JFrame progressBarWindow;
private JProgressBar progressBar;
private LinkedList<File[]> subDirs = new LinkedList<>();
private File baseFolder;
private int basePathLength;
private File currentSubDirPath;
private String[] currentSubDirPathSplit;
private JLabel currentFileLabel = null;
public ProgressBar(boolean showCurrentFile, String applicationTitle) {
progressBarWindow = new JFrame("Working...");
progressBarWindow.setLocationRelativeTo(null);
int windowHeight = 60;
if (showCurrentFile) {
windowHeight += FILE_LABEL_HEIGHT;
}
progressBarWindow.setSize(300, windowHeight);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
//progressBarWindow.add(progressBar);
JPanel bottomLine = new JPanel();
bottomLine.setLayout(new BorderLayout());
if (showCurrentFile) {
currentFileLabel = new JLabel("File: ...");
currentFileLabel.setPreferredSize(new Dimension(currentFileLabel.getPreferredSize().width, FILE_LABEL_HEIGHT));
bottomLine.add(currentFileLabel, BorderLayout.CENTER);
}
content.add(progressBar, BorderLayout.CENTER);
JButton reportABugButton = new JButton("Bug!");
reportABugButton.addActionListener((ActionEvent e) -> {
ReportABugWindow reportWindow = new ReportABugWindow(applicationTitle);
reportWindow.submit();
});
bottomLine.add(reportABugButton, BorderLayout.EAST);
content.add(bottomLine, BorderLayout.SOUTH);
progressBarWindow.add(content);
//progressBarWindow.add(reportABugButton);
progressBarWindow.setVisible(true);
latest = this;
}
public void setValueRaw(float val) {
progressBar.setValue((int)(val * 100));
}
public void setFinished() {
progressBar.setValue(100);
}
public void destroy() {
progressBarWindow.dispose();
}
public void setBaseFolder(File base) {
if (!base.isDirectory())
base = base.getParentFile();
currentSubDirPathSplit = base.getAbsolutePath().split(FILE_SEPERATOR_REGEX);
basePathLength = currentSubDirPathSplit.length;
currentSubDirPath = base;
baseFolder = base;
subDirs.clear();
//subDirs.add(base.listFiles((f) -> f.isDirectory()));
}
public void setCurrentFolder(File current) {
if (!current.isDirectory())
current = current.getParentFile();
if (current.equals(currentSubDirPath))
return;
String[] updatePathSplit = current.getAbsolutePath().split(FILE_SEPERATOR_REGEX);
int index = basePathLength;
File commonFile = baseFolder;
while(!(index >= currentSubDirPathSplit.length || index >= updatePathSplit.length) && currentSubDirPathSplit[index].equals(updatePathSplit[index])) {
commonFile = new File(commonFile.getAbsolutePath() + File.separator + updatePathSplit[index]);
index++;
}
//index--;
while (index - basePathLength + 1 < subDirs.size()) {
subDirs.removeLast();
}
while (updatePathSplit.length - basePathLength > subDirs.size()) {
subDirs.add(commonFile.listFiles((f) -> f.isDirectory()));
commonFile = new File(commonFile.getAbsolutePath() + File.separator + updatePathSplit[index]);
index++;
}
//Calculate index and shit
float currentShare = 1f;
float sumOfShares = 0;
int segment = basePathLength;
for(File[] dirs : subDirs) {
for(int i = 0; i < dirs.length; i++) {
if (dirs[i].getName().equals(updatePathSplit[segment])) {
currentShare /= dirs.length;
sumOfShares += currentShare * i;
break;
}
}
segment++;
}
currentSubDirPath = current;
currentSubDirPathSplit = updatePathSplit;
if (currentFileLabel != null)
currentFileLabel.setText("File: " + current.getAbsolutePath());
setValueRaw(sumOfShares);
}
public static void main(String[] args) {
ProgressBar bar = new ProgressBar(true, "hiu");
File start = new File("C:\\Users\\Erik\\Desktop");
bar.setBaseFolder(start);
iterateRecursive(start, bar);
bar.setFinished();
bar.destroy();
}
private static void iterateRecursive(File current, ProgressBar bar) {
File[] subD = current.listFiles((f) -> f.isDirectory());
for(File d : subD) {
bar.setCurrentFolder(d);
System.out.println(d.getAbsolutePath());
iterateRecursive(d, bar);
}
}
}
package uiutils;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.json.simple.JSONObject;
import utils.Debug;
public class ReportABugWindow extends SimpleFrame{
private static final long serialVersionUID = -9110093488807819801L;
private HashMap<String, IOutput<?>> nameToFieldTable;
private CheckboxPanel includeLogData;
private String applicationName;
// public static void main(String[] args) {
// new ReportABugWindow("TestAppl").submit();
// }
public ReportABugWindow(String applicationName) {
this(applicationName, 450);
}
@SuppressWarnings("unchecked")
public ReportABugWindow(String applicationName, int height) {
super("Report a bug!", 415, height, false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
nameToFieldTable = new HashMap<>();
this.applicationName = applicationName;
AddElement("description", new TextAreaPanel("Description:", "What unexpected behaviour did occur?", 40, 5));
AddElement("reproduction", new TextAreaPanel("Reproduction:", "How can the bug be reproduced? On what data was the operation performed?", 40, 5));
AddElement("contact", new InputFieldPanel("Contact:", "max.musterman@rub.de"));
super.addCenter(new LabelPanel("Including logging data is highly recommended and extremly usefuly for debugging!", 10));
includeLogData = new CheckboxPanel("Include Logging Data", true);
super.addCenter(includeLogData);
super.addCenterNoLeftalignment(new ButtonPanel("Submit", e -> {
if (JOptionPane.showConfirmDialog(null, "Information of data processing:\nGiven and said data will be forwared to the email sfb1280bug@rub.de!") == JOptionPane.OK_OPTION) {
JSONObject dataJson = createJSON();
if (includeLogData.getOutput()) {
String data = Debug.allLogFile.toString();
if (data.length() > 45000000) {
data = "...\n" + data.substring(data.length() - 45000000);
}
dataJson.put("log", data);
/*StringBuilder b = new StringBuilder();
for(int i = 0; i < 10000; i++)
b.append("VERY LONG MSG. ");
dataJson.put("log", b.toString());*/
}
// System.out.println("JSON: " + dataJson.toString());
try {
sendBugreport(dataJson);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Unable to reach Host!\nSadly the report could not be delivered!");
}
}
}));
}
public void AddElement(String jsonName, JPanel ioutputPanel) {
if (!(ioutputPanel instanceof IOutput<?>)) {
throw new RuntimeException("Only IOutput panels can be added!");
}
nameToFieldTable.put(jsonName, (IOutput<?>)ioutputPanel);
super.addCenter(ioutputPanel);
}
@SuppressWarnings("unchecked")
public JSONObject createJSON() {
JSONObject json = new JSONObject();
for(Entry<String, IOutput<?>> entry : nameToFieldTable.entrySet()) {
json.put(entry.getKey(), entry.getValue().getOutput().toString());
}
json.put("app", applicationName);
return json;
}
public void sendBugreport(JSONObject json) throws IOException {
setJsonHash(json);
URL url = new URL("http://sfb.dondevelops.de");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);
byte[] out = json.toJSONString().getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
int c = http.getResponseCode();
if (c == 200) {
JOptionPane.showMessageDialog(null, "Thank you for your feedback!\nYour report will be handled soon.");
} else {
System.out.println("CODE: " + c);
JOptionPane.showMessageDialog(null, "The report could not be delivered!\nThis may be due to technical problems. If possible try later or contact the developer of this application!");
}
}
@SuppressWarnings("unchecked")
private void setJsonHash(JSONObject json) {
byte[] passbytes = password.getBytes();
long currentTimeMS = System.currentTimeMillis();
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(currentTimeMS);
byte[] timeMSBytes = buffer.array();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(timeMSBytes);
byte[] timeBytesMD5 = md.digest();
for(int i = 0; i < passbytes.length; i++) {
passbytes[i] ^= timeBytesMD5[i % timeBytesMD5.length];
}
md = MessageDigest.getInstance("MD5");
md.update(passbytes);
byte[] passbytesMD5 = md.digest();
json.put("auth", bytesToHex(passbytesMD5));
json.put("timestamp", currentTimeMS +"");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
private String bytesToHex(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
sb.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
@Override
public void addCenter(JComponent comp) {
throw new RuntimeException("Please do not use this method directly, use: AddElement instead");
}
@Override
public void addCenterNoLeftalignment(JComponent comp) {
throw new RuntimeException("Please do not use this method directly, use: AddElement instead");
}
private static final String password = "5d6tzuv+1bSja";
}
This diff is collapsed.
package uiutils;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
public class SimpleFrame extends JFrame{
private static ImageIcon SFB_ICON = new ImageIcon(SFB_Logo_Data.reconstructImageBytes());
static {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch(Exception ignored){
System.out.println("Look & Feel not found!\nInstalled look and Feels:");
for(LookAndFeelInfo lafinfo : UIManager.getInstalledLookAndFeels()) {
System.out.println(lafinfo.getClassName());
}
}
}
private static final long serialVersionUID = -2324030003688548237L;
private JPanel centerPanel;
private JPanel leftPanel;
private JPanel topPanel;
private JPanel bottomPanel;
private JPanel rightPanel;
public SimpleFrame(String title, int minWidth, int minHeight) {
this(title, minWidth, minHeight, true);
}
public SimpleFrame(String title, int minWidth, int minHeight, boolean addBugButton) {
super();
this.setIconImage(SFB_ICON.getImage());
this.setTitle(title);
getContentPane().setLayout(new BorderLayout());
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
centerPanel.setAlignmentX(LEFT_ALIGNMENT);
this.add(centerPanel, BorderLayout.CENTER);
leftPanel = new JPanel();
this.add(leftPanel, BorderLayout.WEST);
topPanel = new JPanel();
this.add(topPanel, BorderLayout.NORTH);
rightPanel = new JPanel();
this.add(rightPanel, BorderLayout.EAST);
if (addBugButton) {
JButton reportABugButton = new JButton("Bug!");
reportABugButton.addActionListener((ActionEvent e) -> {
ReportABugWindow reportWindow = new ReportABugWindow(title);
reportWindow.submit();
});
rightPanel.add(reportABugButton);
}
bottomPanel = new JPanel();
this.add(bottomPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setMinimumSize(new Dimension(minWidth, minHeight));
}
public void submit() {
this.pack();
centerPanel.setAlignmentX(LEFT_ALIGNMENT);
this.setVisible(true);
}
public static void promt(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
public void addCenter(JComponent comp) {
centerPanel.add(leftJustify(comp));
}
public void addCenterNoLeftalignment(JComponent comp) {
centerPanel.add(comp);
}
public void setMargins(int hMargins, int vMargins) {
leftPanel.setBorder(new EmptyBorder(0, hMargins, 0, 0));
rightPanel.setBorder(new EmptyBorder(0, 0, 0, hMargins));
bottomPanel.setBorder(new EmptyBorder(vMargins, 0, 0, 0));
topPanel.setBorder(new EmptyBorder(0, 0, vMargins, 0));
}
public void addBorder(Container c) {
for(Component comp : c.getComponents()) {
if (comp instanceof JComponent) {
((JComponent)comp).setBorder(BorderFactory.createLineBorder(Color.black));
}
if (comp instanceof Container) {
addBorder((Container)comp);
}
}
}
private Component leftJustify( JComponent panel ) {
Box b = Box.createHorizontalBox();
b.add( panel );
b.add( Box.createHorizontalGlue() );
return b;
}
public static void main(String[] args) throws IOException {
SimpleFrame frame = new SimpleFrame("TTT", 400,300);
frame.addCenter(new LabelPanel("berschrift", 30));
frame.addCenter(new FileChooserPanel("hi HI"));
frame.addCenter(new InputFieldPanel("SFB_CODES", "codes here"));
frame.addCenter(new ComboSelectionPanel("Modalities", "Select", ComboSelectionPanel.SFB_MODALITIES));
frame.addCenter(new ConditionedPanel("Test", true, new FileChooserPanel("hi"), new FileChooserPanel("hi2")));
frame.addCenterNoLeftalignment(new ButtonPanel("hi", null));
frame.addCenter(new TextAreaPanel("HI","test", 50, 3));
///frame.setMargins(50, 20);
frame.submit();
}
public static void initLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch(Exception ignored){
System.out.println("Look & Feel not found!\nInstalled look and Feels:");
for(LookAndFeelInfo lafinfo : UIManager.getInstalledLookAndFeels()) {
System.out.println(lafinfo.getClassName());
}
}
}
public interface IPerform {
public void perform(File f);
}
public static SimpleFrame createStudyChooserFrame(String name, IPerform action) {
return createStudyChooserFrame(name, "Study Folder", action);
}
public static SimpleFrame createStudyChooserFrame(String name, String fileChooserText, IPerform action) {
return createStudyChooserFrame(name, fileChooserText, new JPanel[0], action);
}
public static SimpleFrame createStudyChooserFrame(String name, String fileChooserText, JPanel[] additionalPanels, IPerform action) {
SimpleFrame s = new SimpleFrame(name, 300, 200);
LabelPanel header = new LabelPanel(name, 32);
FileChooserPanel chooser = new FileChooserPanel(fileChooserText);
LabelPanel plsWaitText = new LabelPanel("Processing...\nThis may take some time", 10);
plsWaitText.setVisible(false);
ButtonPanel submit = new ButtonPanel("Submit");
submit.addActionListener(e -> {
submit.SetEnabled(false);
plsWaitText.setVisible(true);
Dimension originalSize = s.getSize();
s.setSize(originalSize.width, originalSize.height + 20);
action.perform(chooser.getOutput());
submit.SetEnabled(true);
plsWaitText.setVisible(false);
s.setSize(originalSize.width, originalSize.height);
});
s.addCenter(header);
s.addCenter(chooser);
for(JPanel p : additionalPanels)
s.addCenter(p);
s.addCenterNoLeftalignment(submit);
s.addCenterNoLeftalignment(plsWaitText);
return s;
}
}
package uiutils;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeListener;
public class SpinnerINTPanel extends JPanel implements IOutput<Integer>{
private static final long serialVersionUID = -2030532269354521325L;
private JSpinner spinner;
public SpinnerINTPanel(String text, int startValue, int min, int max, int step) {
super();
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(new JLabel(text));
spinner = new JSpinner(new SpinnerNumberModel(startValue, min, max, step));
setPrefSpinnerWidth(55);
this.add(spinner);
}
public SpinnerINTPanel setPrefSpinnerWidth(int width) {
spinner.setPreferredSize(new Dimension(width, spinner.getPreferredSize().height));
return this;
}
@Override
public Integer getOutput() {
return (int)spinner.getValue();
}
}
package uiutils;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextAreaPanel extends JPanel implements IOutput<String> {
private static final long serialVersionUID = 5857892221079489896L;
public JTextArea textArea;
public TextAreaPanel(String text, String default_Text, int columns, int rows) {
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(leftJustify(new JLabel(text)));
if (columns <= 0) {
textArea = new JTextArea();
textArea.setRows(rows);
} else {
textArea = new JTextArea(rows, columns);
}
textArea.setText(default_Text);
textArea.setLineWrap(true);
// textArea.setPreferredSize(new Dimension(rows * 5, columns * 10));
// textArea.setMaximumSize(new Dimension(rows * 5, columns * 10));
// textArea.setMinimumSize(new Dimension(rows * 5, columns * 10));
JScrollPane scroll = new JScrollPane(textArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(leftJustify(scroll));
textArea.invalidate();
scroll.invalidate();
textArea.repaint();
scroll.repaint();
}
private Component leftJustify( JComponent panel ) {
Box b = Box.createHorizontalBox();
b.add( panel );
b.add( Box.createHorizontalGlue() );
return b;
}
@Override
public String getOutput() {
return textArea.getText();
}
}