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
Select Git revision

Target

Select target project
  • sfb1280/studychecker
1 result
Select Git revision
Show changes
package utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.io.InputStream;
public class CSV_Reader {
private String[] headers;
private String[][] entries;
public CSV_Reader(File csv) {
try {
read(csv, ",");
} catch (FileNotFoundException e) {
e.printStackTrace();
headers = null;
entries = null;
}
}
public CSV_Reader(File csv, String seperator) {
try {
read(csv, seperator);
} catch (FileNotFoundException e) {
e.printStackTrace();
headers = null;
entries = null;
}
}
public CSV_Reader(String[] headers, String[][] entries) {
this.headers = headers;
this.entries = entries;
}
private void read(File csv, String seperator) throws FileNotFoundException {
Scanner sc = new Scanner(csv);
headers = sc.nextLine().split(seperator);
for(int i = 0; i < headers.length; i++)
headers[i] = headers[i].trim();
LinkedList<String[]> entries = new LinkedList<String[]>();
while(sc.hasNext()) {
entries.add(arrayExpand(sc.nextLine().split(seperator)));
}
this.entries = new String[entries.size()][headers.length];
for(int i = 0; i < this.entries.length; i++) {
this.entries[i] = entries.removeFirst();
for(int i2 = 0; i2 < this.entries[i].length; i2++) {
this.entries[i][i2] = this.entries[i][i2].trim();
}
}
}
private String[] arrayExpand(String[] arr) {
if (arr.length < headers.length) {
String[] newArr = new String[headers.length];
for(int i = 0; i < arr.length; i++) {
newArr[i] = arr[i];
}
for(int i = arr.length; i < newArr.length; i++) {
newArr[i] = "";
}
return newArr;
}
return arr;
}
public int getColumn(String header) {
for(int i = 0; i < headers.length; i++) {
if (headers[i].equals(header)) return i;
}
return -1;
}
public int getMaxRows() {
if (entries == null) return 0;
return entries.length;
}
public String get(int column, int row) {
return entries[row][column];
}
public int getInt(int column, int row) {
return Integer.parseInt(get(column, row));
}
public int getInt(int column, int row, int defaultValue) {
try {
return getInt(column, row);
} catch(NumberFormatException ex) {
return defaultValue;
}
}
public void printInlineVersion() {
StringBuilder b = new StringBuilder();
b.append("private static CSV_Reader csv = new CSV_Reader(new String[] {");
for(int i = 0; i < headers.length; i++) {
b.append("\""+ headers[i] + "\"");
if (i < headers.length - 1)
b.append(", ");
}
b.append("}, new String[][] {");
for(int i = 0; i < entries.length; i++) {
b.append("new String[] {");
for(int j = 0; j < entries[i].length; j++) {
b.append("\"" + entries[i][j] + "\"");
if (j < entries[i].length - 1)
b.append(", ");
}
b.append("}");
if (i < entries.length - 1)
b.append(", ");
}
b.append("});");
System.out.println(b.toString());
for(String h : headers) {
String s = h + " header";
s = s.replaceAll(" ", "_");
s = s.toUpperCase();
s = "private static final int " + s + " = " + getColumn(h) + ";";
System.out.println(s);
}
}
public static CSV_Reader fromXLSX(File xlsx, String sheet) {
FileInputStream fis;
try {
fis = new FileInputStream(xlsx);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
LinkedList<CellData> cellDatas = null;
String[] sharedStrings = null;
while(ze != null) {
String fileName = ze.getName();
if ((sheet == null && fileName.contains("worksheets")) || (sheet != null && fileName.endsWith(sheet + ".xml"))) {
cellDatas = cellDataFromXLSXextractedXML(readZipEntryToString(zis));
} else if (fileName.endsWith("sharedStrings.xml")) {
sharedStrings = sharedStringsFromXML(readZipEntryToString(zis));
}
zis.closeEntry();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
fis.close();
int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, maxX = 0, maxY = 0;
for(CellData c : cellDatas) {
int x = c.getCol();
int y = c.getRow();
if (x < minX)
minX = x;
if (x > maxX)
maxX = x;
if (y < minY)
minY = y;
if (y > maxY)
maxY = y;
//replace String values
if(c.type == CellData.Type.STRING) {
int val = c.getValueInt();
if (val >= sharedStrings.length) {
System.out.println("Unknown String in xlsx");
continue;
}
c.value = sharedStrings[val];
}
}
int w = maxX - minX + 1;
int h = maxY - minY + 1;
String[] headers = new String[w];
String[][] values = new String[h - 1][w];
for(CellData c : cellDatas) {
int row = c.getRow() - minY;
if (row == 0) {
headers[c.getCol() - minX] = c.value;
} else {
values[row - 1][c.getCol() - minX] = c.value;
}
}
return new CSV_Reader(headers, values);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String readZipEntryToString(ZipInputStream zis) throws IOException {
byte[] buffer = new byte[1024];
int len;
StringBuilder xml = new StringBuilder();
while ((len = zis.read(buffer)) > 0) {
String str = new String(buffer, 0, len);
xml.append(str);
}
return xml.toString();
}
private static String[] sharedStringsFromXML(String xml) {
LinkedList<String> res = new LinkedList<>();
int index = 0;
while((index = xml.indexOf("<t", index)) != -1) {
index = xml.indexOf(">", index);
int end = xml.indexOf("</t>", index);
res.add(xml.substring(index + 1, end));
index = end;
}
return (String[]) res.toArray(new String[res.size()]);
}
private static LinkedList<CellData> cellDataFromXLSXextractedXML(String sheetXml) {
String sheetData = sheetXml.substring(sheetXml.indexOf("<sheetData>") + "<sheetData>".length(), sheetXml.indexOf("</sheetData>"));
LinkedList<CellData> cellData = new LinkedList<>();
int index = 0;
while((index = sheetData.indexOf("<c r=\"", index)) != -1) {
String cellID = sheetData.substring(index + 6, sheetData.indexOf('"', index + 6));
int endOfTag = sheetData.indexOf('>', index);
CellData.Type type = CellData.Type.NUMBER;
int typeString = sheetData.indexOf("t=\"s\"", index);
boolean isStr = typeString != -1 && typeString < endOfTag;
if (isStr) {
type = CellData.Type.STRING;
}
int typeDate = sheetData.indexOf("s=\"1\"", index);
boolean isDate = typeDate != -1 && typeDate < endOfTag;
if (isDate) {
type = CellData.Type.DATE;
}
int valOpen = sheetData.indexOf("<v>", endOfTag);
int valClose = sheetData.indexOf("</v>", valOpen);
if (valOpen == -1 || valClose == -1) {
index = endOfTag;
continue;
}
String value = sheetData.substring(valOpen + 3, valClose);
cellData.add(new CellData(cellID, value, type));
index = endOfTag;
}
return cellData;
}
private static class CellData {
private static final Calendar CALENDAR = Calendar.getInstance();
public static enum Type {NUMBER, STRING, DATE}
public String cellID;
public String value;
public Type type;
public CellData(String cellID, String value, Type type) {
this.cellID = cellID;
this.value = value;
this.type = type;
if (type == Type.DATE) {
if (this.value.contains(".")) {
this.value = this.value.substring(0, value.indexOf("."));
}
CALENDAR.set(1900, 0, 0, 0, 0, 0);
int addDays = getValueInt() - 1;
CALENDAR.add(Calendar.DATE, addDays);
this.value = SFB_Util.SFB_DATE_FORMATTER.format(CALENDAR.getTime());
}
}
private int getCol() {
String rev_id = new StringBuilder(cellID).reverse().toString();
int pos = 0;
while(Character.isDigit(rev_id.charAt(pos))) {
pos++;
}
int offs = pos;
int sum = 0;
if (rev_id.length() - pos > 1) sum += powInt(26, rev_id.length() - pos - 1);
while(pos < rev_id.length()) {
sum += (((int)rev_id.charAt(pos)) - ((int)'A')) * (powInt(26, pos - offs));
pos++;
}
return sum;
}
private int getRow() {
int pos = 0;
while(!Character.isDigit(cellID.charAt(pos))) {
pos++;
}
return Integer.parseInt(cellID.substring(pos));
}
public int getValueInt() {
return Integer.parseInt(value);
}
private int powInt(int base, int to) {
int res = 1;
for(int i = 0; i < to; i++) {
res *= base;
}
return res;
}
@Override
public String toString() {
return "Cell: [" + getCol() + ", " + getRow() + "]: " + value + " (type: " +type + ")";
}
}
}
\ No newline at end of file
package utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This class handles every kind of logging or debugging.
* Use static methods!
*
* @author Erik
*
*/
public final class Debug {
public static StringBuilder allLogFile = new StringBuilder();
public static PrintStream err = System.err;
public static PrintStream out = System.out;
public static PrintStream warning = System.out;
public static PrintStream logCopyPrintStream = null;
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm::ss");
private Debug() {
}
/**
* Changes the Debugmode to File Mode. Log, Error or Warning Calls are now Written into files instead of the system consol
* @param dirPath path of the Directory where the files should be placed.
*/
public static void ChangeToFileMode(String dirPath, boolean onlyOneFile) {
ChangeToFileMode(dirPath, onlyOneFile, "");
}
/**
* Changes the Debugmode to File Mode. Log, Error or Warning Calls are now Written into files instead of the system consol
* @param dirPath path of the Directory where the files should be placed.
* @param namePrefix Additional name prefix for the resulting log files.
*/
public static void ChangeToFileMode(String dirPath, boolean onlyOneFile, String namePrefix) {
File log = new File(dirPath + "\\" + namePrefix +"Log.txt");
File err = new File(dirPath + "\\" + namePrefix +"ErrorLog.txt");
File warning = new File(dirPath + "\\" + namePrefix +"WarningLog.txt");
boolean logNewCreated = false, errNewCreated = false, warningNewCreated = false;
try {
logNewCreated = log.createNewFile();
if (!onlyOneFile) {
errNewCreated = err.createNewFile();
warningNewCreated = warning.createNewFile();
}
} catch (IOException e) {
Error(e);
Error("Unable to create file");
}
try {
out = new PrintStream(new FileOutputStream(log));
if (!logNewCreated)out.println("\n-----------------------------------------\n");
if (!onlyOneFile) {
if (!errNewCreated)Debug.err.println("\n-----------------------------------------\n");
if (!warningNewCreated)Debug.warning.println("\n-----------------------------------------\n");
Debug.err = new PrintStream(new FileOutputStream(err));
Debug.warning = new PrintStream(new FileOutputStream(warning));
Error("");
Warning("");
} else {
Debug.err = Debug.out;
Debug.warning = Debug.out;
}
Log("");
} catch (FileNotFoundException e) {
Error(e);
}
}
/**
* Closes every currently opend Filestream (out, warning, error). No further logging possible!
*/
public static void CloseFileStreams() {
out.close();
if (out != warning) {
warning.close();
err.close();
}
}
public static void setLogCopyPrintStream(File f) {
try {
logCopyPrintStream = new PrintStream(new FileOutputStream(f, true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Changes the output of Log, Error or Warning to The System Consol
*/
public static void ChangeToConsolMode() {
out = System.out;
err = System.err;
warning = System.out;
}
/**
* Logs a String
* @param s
*/
public static void Log(String s) {
String log = "[" + DATE_FORMAT.format(new Date(System.currentTimeMillis())) + "] " + s;
out.println(log);
allLogFile.append(log + "\n");
if (logCopyPrintStream != null)
logCopyPrintStream.println("[" + DATE_FORMAT.format(new Date(System.currentTimeMillis())) + "] " + s);
}
/**
* Logs a Warning
* @param s warning
*/
public static void Warning(String s) {
if (warning == System.out) s = "[Warning] " + s;
s = "[" + DATE_FORMAT.format(new Date(System.currentTimeMillis())) + "] " + s;
warning.println(s);
allLogFile.append(s + "\n");
}
/**
* logs an Exception
* @param e exception
*/
public static void Error(Exception e) {
err.println("[" + DATE_FORMAT.format(new Date(System.currentTimeMillis())) + "]:");
e.printStackTrace(err);
allLogFile.append("[ERROR "+ DATE_FORMAT.format(new Date(System.currentTimeMillis())) + "]: " + e.getMessage() + "at \n");
for(StackTraceElement elem : e.getStackTrace()) {
allLogFile.append("\tat: " + elem.toString() + "\n");
}
}
/**
* logs an Error
* @param s error
*/
public static void Error(String s) {
s = "[" + DATE_FORMAT.format(new Date(System.currentTimeMillis())) + "] " +s;
err.println(s);
allLogFile.append(s + "\n");
}
/**
* Convertes the current Date with a certain dateFormat.
* @param dateFormat (Normally: dd.MM.yyyy HH:mm::ss)
* @return the formatted date
*/
public static String GetCurrentDate(String dateFormat) {
return new SimpleDateFormat(dateFormat).format(new Date(System.currentTimeMillis()));
}
}
package utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class SFB_CreateMeta {
//DATES = 2020-02-11
public static final String MALE = "male", FEMALE = "female", UNDEFINED = "undefined";
public static final String HEALTHY_TEST_SUBJ = "Healthy test subject";
public static final String HUMAN = "human", MICE = "Mice";
public static final String EYETRACKER = "Eyetracker", ECG = "ECG", EDA = "EDA", BEHAVIORAL = "Behavorial";
public String groupID = "A01";
public String experimentTitle = "Title";
public String creator = "";
public String contributor = "";
public String resourceType = "measured";
public String subjSpecies = "";
public String animalAndEthicsNo = "";
public String experimentDescription = "";
public String[] modality = new String[0];
public String[] sharedWith = new String[0];
public SFB_CreateMeta clone() {
SFB_CreateMeta meta = new SFB_CreateMeta();
meta.groupID = this.groupID;
meta.experimentTitle = this.experimentTitle;
meta.creator = this.creator;
meta.contributor = this.contributor;
meta.resourceType = this.resourceType;
meta.subjSpecies = this.subjSpecies;
meta.animalAndEthicsNo = this.animalAndEthicsNo;
meta.experimentDescription = this.experimentDescription;
meta.modality = Arrays.copyOf(this.modality, this.modality.length);
meta.sharedWith = Arrays.copyOf(this.sharedWith, this.sharedWith.length);
return meta;
}
@SuppressWarnings("unchecked")
public void createJSON(String subjID, String subjType, String subjSex, String subjAge, String recordDate, String folder, HashMap<String, String> additionalKeyValues) {
BufferedWriter writer;
JSONObject obj = new JSONObject();
//
//
//String form_txt_dub = format_txt_dub.getText().replaceAll(";", ",");
//String sub_txt_dub = subject_txt_dub.getText().replaceAll(";", ",");
//..........................................................................
obj.put("Software version", "20220517"); // Old-version: 20200909
//..........................................................................
// SFB meta data
obj.put("Group ID", groupID);
obj.put("Experiment title", experimentTitle);
obj.put("Creator", creator);
obj.put("Contributor", contributor);
obj.put("Record date", recordDate);
obj.put("Resource Type", resourceType);
obj.put("Modality", modality);
obj.put("Subject ID", subjID);
obj.put("Subject Species", subjSpecies);
obj.put("Subject type", subjType);
obj.put("Subject sex", subjSex);//(GENDER[index].equals("w") || GENDER[index].equals("f")) ? "female" : (GENDER[index].equals("m") ? "male" : "undefined"));
obj.put("Subject age", subjAge);
obj.put("Shared with", sharedWith);
obj.put("Animal|Ethics approval No.", animalAndEthicsNo);
obj.put("Extra information", "");
obj.put("Experiment Description", experimentDescription);
//............................................................................
//DublinCore
obj.put("DublinCore-Creator", creator);
obj.put("DublinCore-Contributor", contributor);
obj.put("DublinCore-Coverage", "");
obj.put("DublinCore-Date", "");
obj.put("DublinCore-Description", "");
obj.put("DublinCore-Format", "");
obj.put("DublinCore-Identifier", "");
obj.put("DublinCore-Language", "");
obj.put("DublinCore-Publisher", "");
obj.put("DublinCore-Relation", "");
obj.put("DublinCore-Rights", "");
obj.put("DublinCore-Source", "");
obj.put("DublinCore-Subject", "");
obj.put("DublinCore-Title", "");
obj.put("DublinCore-Type", "");
//..........................................................................
// DataCite
obj.put("DataCite-Identifier", "");
obj.put("DataCite-identifierType", "");
obj.put("DataCite-Title", "");
obj.put("DataCite-titleType", "");
obj.put("DataCite-creatorName", "");
obj.put("DataCite-creatorNameType", "");
obj.put("DataCite-creatorGivenName", "");
obj.put("DataCite-creatorFamilyName", "");
obj.put("DataCite-creatorNameIdentifier", "");
obj.put("DataCite-creatorNameIdentifierScheme", "");
obj.put("DataCite-creatorSchemeURI", "");
obj.put("DataCite-creatorAffiliation", "");
obj.put("DataCite-contributorType", "");
obj.put("DataCite-contributorName", "");
obj.put("DataCite-contributorNameType", "");
obj.put("DataCite-contributorGivenName", "");
obj.put("DataCite-contributorFamilyName", "");
obj.put("DataCite-contributorNameIdentifier", "");
obj.put("DataCite-contributorNameIdentifierScheme", "");
obj.put("DataCite-contributorSchemeURI", "");
obj.put("DataCite-contributorAffiliation", "");
obj.put("DataCite-Date","");
obj.put("DataCite-dateType","");
obj.put("DataCite-ResourceType","");
obj.put("DataCite-resourceTypeGeneral", "");
obj.put("DataCite-Publisher", "");
obj.put("DataCite-PublicationYear", "");
obj.put("DataCite-Subject", "");
obj.put("DataCite-subjectScheme", "");
obj.put("DataCite-subjectSchemeURI", "");
obj.put("DataCite-subjectValueURI", "");
obj.put("DataCite-Language", "");
obj.put("DataCite-alternateIdentifier", "");
obj.put("DataCite-alternateIdentifierType", "");
obj.put("DataCite-RelatedIdentifier", "");
obj.put("DataCite-relatedIdentifierType", "");
obj.put("DataCite-relationType", "");
obj.put("DataCite-Size", "");
obj.put("DataCite-Format", "");
obj.put("DataCite-Version", "");
obj.put("DataCite-Rights", "");
obj.put("DataCite-rightsURI", "");
obj.put("DataCite-rightsIdentifier", "");
obj.put("DataCite-rightsIdentifierScheme", "");
obj.put("DataCite-rightsSchemeURI", "");
obj.put("DataCite-Description", "");
obj.put("DataCite-descriptionType", "");
obj.put("DataCite-GeoLocationPlace", "");
obj.put("DataCite-FundingReference", "");
obj.put("DataCite-funderName","");
obj.put("DataCite-funderIdentifier", "");
obj.put("DataCite-funderIdentifierType","");
if (additionalKeyValues != null) {
for(Entry<String, String> entry : additionalKeyValues.entrySet()) {
obj.put(entry.getKey(), entry.getValue());
}
}
try {
writer = new BufferedWriter(new FileWriter(folder + File.separator + "meta.json",false));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
writer.write(gson.toJson(obj));
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package utils;
import java.io.File;
import java.util.LinkedList;
public class SFB_IterateStudy {
public String subjectPrefix = "sub-";
public String sessionPrefix = "ses-";
public interface OnSubjLambda {
void action(File subj);
}
public interface OnSessionLambda {
void action(File sessionFolder, int sessionIndex);
}
public interface OnModalityLambda {
void action(File modaltiyFolder, int session);
}
public interface OnModalityFileLambda {
void action(File file, int session);
}
private File studyFolder;
private OnSubjLambda onSubject;
private OnSessionLambda onSession;
private OnModalityLambda onModality;
private OnModalityFileLambda onModalityFile;
public SFB_IterateStudy (File study) {
this.studyFolder = study;
}
public void setOnSubjectLamda(OnSubjLambda func) {
onSubject = func;
}
public void setOnSessionLamda(OnSessionLambda func) {
onSession = func;
}
public void setOnModalityLamda(OnModalityLambda func) {
onModality = func;
}
public void setOnModalityFileLamda(OnModalityFileLambda func) {
onModalityFile = func;
}
public void iterate() {
subjectPrefix = subjectPrefix.toLowerCase();
sessionPrefix = sessionPrefix.toLowerCase();
File[] subjs = studyFolder.listFiles((File file) -> file.isDirectory() && file.getName().toLowerCase().startsWith(subjectPrefix));
for(File subj : subjs) {
if (onSubject != null) onSubject.action(subj);
iterateSessions(subj);
}
}
private void iterateSessions(File subj) {
File[] sessions = subj.listFiles((File file) -> file.isDirectory() && file.getName().toLowerCase().startsWith(sessionPrefix));
for(int i = 0; i < sessions.length; i++) {
if (onSession != null) onSession.action(sessions[i], i);
iterateModality(sessions[i], i);
}
if (sessions.length == 0) iterateModality(subj, -1);
}
private void iterateModality(File sessionFolder, int sessionIndex) {
File[] modalities = sessionFolder.listFiles((File file) -> file.isDirectory());
for(File modality : modalities) {
if (onModality != null) onModality.action(modality, sessionIndex);
iterateModalityFiles(modality, sessionIndex);
}
}
private void iterateModalityFiles(File modality, int sessionIndex) {
if (onModalityFile == null)return;
for(File f : modality.listFiles()) {
onModalityFile.action(f, sessionIndex);
}
}
public static LinkedList<File> filesNDirDeep(File baseFile, int n, boolean returnOnlyDirs) {
LinkedList<File> res = new LinkedList<File>();
_filesNDirDeep(baseFile, n, returnOnlyDirs, res);
return res;
}
private static void _filesNDirDeep(File baseFile, int n, boolean returnOnlyDirs, LinkedList<File> res) {
if (n == 0) {
File[] add;
if (returnOnlyDirs) {
add = baseFile.listFiles(pathname -> pathname.isDirectory());
} else {
add = baseFile.listFiles();
}
for(int i = 0; i < add.length; i++)
res.add(add[i]);
} else {
File[] subDirs = baseFile.listFiles(pathname -> pathname.isDirectory());
for(File f : subDirs) {
_filesNDirDeep(f, n - 1, returnOnlyDirs, res);
}
}
}
}
package utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class SFB_JSON_Util {
public interface JsonAction {
void action(JSONObject obj);
}
public interface JsonFunction<T> {
T function(JSONObject obj);
}
public static void performOnJson(File json, JsonAction action) {
JSONParser parser = new JSONParser();
FileReader in;
try {
in = new FileReader(json);
JSONObject obj = (JSONObject) parser.parse(in);
in.close();
action.action(obj);
BufferedWriter writer = new BufferedWriter(new FileWriter(json, false)); // false to overwrite
Gson gson = new GsonBuilder().setPrettyPrinting().create();
writer.write(gson.toJson(obj));
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//*/
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readInJson(File json, JsonAction action) {
JSONParser parser = new JSONParser();
FileReader in;
try {
in = new FileReader(json);
JSONObject obj = (JSONObject) parser.parse(in);
in.close();
action.action(obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static<T> T readFromJson(File json, String jsonKeyValue) {
JSONParser parser = new JSONParser();
FileReader in;
try {
in = new FileReader(json);
JSONObject obj = (JSONObject) parser.parse(in);
in.close();
return (T) obj.get(jsonKeyValue);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static <T> T readFromJson(File json, JsonFunction<T> func) {
JSONParser parser = new JSONParser();
FileReader in;
try {
in = new FileReader(json);
JSONObject obj = (JSONObject) parser.parse(in);
in.close();
return func.function(obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static JSONObject readFromJson(File json) {
JSONParser parser = new JSONParser();
FileReader in;
try {
in = new FileReader(json);
JSONObject obj = (JSONObject) parser.parse(in);
in.close();
return obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static JSONObject readFromJson(File json, Charset charset) {
JSONParser parser = new JSONParser();
InputStreamReader in;
try {
in = new InputStreamReader(new FileInputStream(json), charset);
JSONObject obj = (JSONObject) parser.parse(in);
in.close();
return obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static void setExperimentTitle(String title, JSONObject obj) {
obj.put("Experiment title", title);
obj.put("DublinCore-Title", title);
obj.put("DataCite-Title", title);
}
public static void setRecordDate(String date, JSONObject obj) {
obj.put("Record date", date);
obj.put("DublinCore-Date", date);
obj.put("DataCite-Date", date);
}
public static void setSubjectID(String subjID, JSONObject obj) {
obj.put("Subject ID", subjID);
}
public static void setAge(String age, JSONObject obj) {
obj.put("Subject age", age);
}
public enum Gender {
MALE("male"),
FEMALE("female"),
UNDEFINED("undefined");
private final String str;
private Gender(final String str) {this.str = str;}
@Override
public String toString() {
return str;
}
}
public static void setGender(Gender gender, JSONObject obj) {
obj.put("Subject sex", gender.toString());
}
public static Gender getGenderFromStringStartENG(String gen) {
gen = gen.toLowerCase();
if(gen.startsWith("m")) {
return Gender.MALE;
} else if (gen.startsWith("f")) {
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
public static Gender getGenderFromStringStartGER(String gen) {
gen = gen.toLowerCase();
if(gen.startsWith("m")) {
return Gender.MALE;
} else if (gen.startsWith("w")) {
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
public enum PatientType {
HEALTY_TEST_SUBJ("Healthy test subject"),
PATIENT("Patient"),
HEALTY_CONTROL_SUBJ("Healthy control subject");
private final String str;
private PatientType(final String str) {this.str = str;}
@Override
public String toString() {
return str;
}
}
public static void setPatientType(PatientType type, JSONObject obj) {
obj.put("Subject type", type.toString());
}
public enum Modality {
BEHAVIORAL("Behavorial"),
CALCIIUM_IMAGING("Calcium Imaging"),
ECG_PULSE("ECG|Pulse"),
EDA("EDA"),
EEG("EEG"),
EYETRACKING("Eyetracking"),
HISTOLOGY("Histology"),
HORMONE_MEASUREMENTS("Hormone measurements"),
LFP("LFP"),
MRI("MRI"),
QUESTIONNAIRES("Questionaires"),
RESPIRATION("Respiration"),
SINGLE_CELL_RECORDING("Single cell recording"),
TMS("TMS");
private final String str;
private Modality(final String str) {this.str = str;}
@Override
public String toString() {
return str;
}
}
public static void setModality(Modality[] mods, JSONObject obj) {
String[] strs = new String[mods.length];
for(int i = 0; i < mods.length; i++) {
strs[i] = mods[i].toString();
}
obj.put("Modality", strs);
}
}
package utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public final class SFB_Util {
public static final SimpleDateFormat SFB_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
private SFB_Util() {
}
public static File selectStudyFolder() {
return selectStudyFolder("Select Study folder");
}
public static File selectStudyFolder(String titleText) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(titleText);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Folder";
}
@Override
public boolean accept(File f) {
return f.isDirectory();
}
});
int success = fileChooser.showOpenDialog(null);
if (success == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile();
}
return null;
}
public static void showMsg(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
public static void copyRecursive(File dirSrc, File dirDes) {
dirDes.mkdir();
File[] files = dirSrc.listFiles();
for(File f : files) {
if (f.isDirectory()) {
File dir = combineFiles(dirDes, f);
dir.mkdir();
copyRecursive(f, dir);
} else {
if (true) {
try (
InputStream in = new BufferedInputStream(new FileInputStream(f));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(combineFiles(dirDes, f)))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
in.close();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
System.out.println(combineFiles(dirSrc, f).getAbsolutePath() + " Created: " + combineFiles(dirDes, f).createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static<T> T[] arrayConcat(T[] arrA, T[] arrB, Class<T> clazz) {
@SuppressWarnings("unchecked")
T[] arr = (T[]) Array.newInstance(clazz, arrA.length + arrB.length);
for(int i = 0; i < arrA.length; i++)
arr[i] = arrA[i];
for(int i = 0; i < arrB.length; i++)
arr[i + arrA.length] = arrB[i];
return arr;
}
public static File combineFiles(File path, File name) {
return new File(path.getAbsolutePath() + File.separator + name.getName());
}
public static boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
public static void removeStudyGroups(File folderOfTheGroups) {
File[] groups = folderOfTheGroups.listFiles(pathname -> pathname.isDirectory());
for(File g : groups) {
for(File data : g.listFiles()) {
int lastPoint = data.getName().lastIndexOf('.');
String name = data.getName().substring(0, lastPoint == -1 ? data.getName().length() : lastPoint);
String extension = lastPoint == -1 ? "" : data.getName().substring(lastPoint);
data.renameTo(new File(folderOfTheGroups.getAbsoluteFile() + "\\" + name + "_" + g.getName() + extension));
}
deleteDirectory(g);
}
}
public static File autoCompleteFile(File folder, String startsWith) {
File[] files = folder.listFiles(((dir, name) -> name.startsWith(startsWith)));
return files == null ? null : files[0];
}
public static void copy(File from, File to) throws IOException {
File copied = to;
try (
InputStream in = new BufferedInputStream(
new FileInputStream(from));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
}
public static void copySafe(File from, File to) {
try {
copy(from, to);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String convertDateToSFBFormat(String date, String currentDateFormat) {
SimpleDateFormat currentFormat = new SimpleDateFormat(currentDateFormat);
try {
return SFB_DATE_FORMATTER.format(currentFormat.parse(date));
} catch (java.text.ParseException e) {
System.err.println("Unable to format date: " + date);
return null;
}
}
public static String convertDateToSFBFormat(String date, String currentDateFormat, int addDays) {
SimpleDateFormat currentFormat = new SimpleDateFormat(currentDateFormat);
try {
return SFB_DATE_FORMATTER.format(addDays(currentFormat.parse(date), addDays));
} catch (java.text.ParseException e) {
System.err.println("Unable to format date: " + date);
return null;
}
}
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
public static int extractIntegerFromString(String s, int startIndex) {
char[] arr = s.toCharArray();
int currentIndex = startIndex;
if (startIndex < 0 || startIndex >= arr.length) {
return Integer.MIN_VALUE;
}
while(currentIndex < arr.length && Character.isDigit(arr[currentIndex])) {
currentIndex++;
}
try {
return Integer.parseInt(s.substring(startIndex, currentIndex));
} catch (NumberFormatException e) {
return Integer.MIN_VALUE;
}
}
}