Neu-Implementierung gestartet

This commit is contained in:
2022-01-04 03:18:35 +01:00
parent 6b24f21147
commit 4dbfdcb5d9
20 changed files with 734 additions and 1040 deletions

View File

@@ -0,0 +1,14 @@
package de.srsoftware.belegscanner;
import java.io.IOException;
import de.srsoftware.belegscanner.gui.MainFrame;
public class Application {
public static void main(String[] args) throws IOException {
Configuration config = new Configuration(Constants.APPLICATION_NAME);
MainFrame app = new MainFrame(config);
app.setDefaultCloseOperation(MainFrame.EXIT_ON_CLOSE);
}
}

View File

@@ -0,0 +1,145 @@
package de.srsoftware.belegscanner;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Configuration {
private static final Logger LOG = LoggerFactory.getLogger(Configuration.class);
private File file;
private JSONObject json = new JSONObject();
public Configuration(String appName) throws IOException {
String home = System.getProperty("user.home");
String fileName = new StringBuilder().append(home).append(File.separator).append(".config").append(File.separator).append(appName).append(File.separator).append("config.json").toString();
file = new File(fileName);
if (file.exists()) {
LOG.info("{} found, loading…",file);
FileReader in = new FileReader(file);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(buffer);
in.transferTo(writer);
writer.close();
String jsonString = buffer.toString(StandardCharsets.UTF_8);
LOG.debug("Loaded json: {}",jsonString);
json = jsonString.startsWith("{") ? new JSONObject(jsonString) : new JSONObject();
in.close();
} else {
LOG.info("{} not found, creating new config.",file);
json = new JSONObject();
}
}
private void save() throws IOException {
LOG.debug("Trying to save config…");
File dir = file.getParentFile();
if (!dir.exists()) dir.mkdirs();
FileWriter out = new FileWriter(file);
json.write(out, 2, 0);
out.close();
}
public JSONArray getOrCreateArray(String key) {
LOG.debug("requesting {} from config.",key);
String[] parts = key.split("\\.");
JSONObject localJson = json;
boolean update = false;
JSONArray result = null;
for (int i=0; i<parts.length; i++) {
String localKey = parts[i];
LOG.debug("localKey = {}",localKey);
boolean lastPart = i == parts.length-1;
if (!localJson.has(localKey)) {
LOG.debug("{} not present in {}, creating…",localKey,localJson);
localJson.put(localKey, lastPart ? new JSONArray() : new JSONObject());
update = true;
}
if (lastPart) {
result = localJson.getJSONArray(localKey);
} else localJson = localJson.getJSONObject(localKey);
}
if (update) try {
save();
} catch (IOException ex) {
LOG.warn("Was not able to write config to {}!",file);
}
return result;
}
@SuppressWarnings("unchecked")
public <T> T get(String key) {
LOG.debug("requesting {} from config.",key);
String[] parts = key.split("\\.");
JSONObject localJson = json;
for (int i=0; i<parts.length; i++) {
String localKey = parts[i];
LOG.debug("localKey = {}",localKey);
boolean lastPart = i == parts.length-1;
if (!localJson.has(localKey)) return null;
if (lastPart) return (T) localJson.get(localKey);
localJson = localJson.getJSONObject(localKey);
}
return null;
}
@SuppressWarnings("unchecked")
public <T> T getOrCreate(String key, T preset) {
LOG.debug("requesting {} from config.",key);
String[] parts = key.split("\\.");
JSONObject localJson = json;
boolean update = false;
Object result = preset;
for (int i=0; i<parts.length; i++) {
String localKey = parts[i];
LOG.debug("localKey = {}",localKey);
boolean lastPart = i == parts.length-1;
if (!localJson.has(localKey)) {
LOG.debug("{} not present in {}, creating…",localKey,localJson);
localJson.put(localKey, lastPart ? preset : new JSONObject());
update = true;
}
if (lastPart) {
result = localJson.get(localKey);
} else localJson = localJson.getJSONObject(localKey);
}
if (update) try {
save();
} catch (IOException ex) {
LOG.warn("Was not able to write config to {}!",file);
}
return (T) result;
}
public void set(String key, Object value) {
LOG.debug("setting {} to {}",key,value);
String[] parts = key.split("\\.");
JSONObject localJson = json;
for (int i=0; i<parts.length; i++) {
String localKey = parts[i];
LOG.debug("localKey = {}",localKey);
boolean lastPart = i == parts.length-1;
if (!localJson.has(localKey)) {
LOG.debug("{} not present in {}, creating…",localKey,localJson);
localJson.put(localKey, lastPart ? value : new JSONObject());
}
if (lastPart) break;
localJson = localJson.getJSONObject(localKey);
}
LOG.debug("altered json: {}",json);
try {
save();
} catch (IOException ex) {
LOG.warn("Was not able to write config to {}!",file);
}
}
}

View File

@@ -0,0 +1,7 @@
package de.srsoftware.belegscanner;
public class Constants {
public static final String APPLICATION_NAME = "BelegScanner";
}

View File

@@ -0,0 +1,112 @@
package de.srsoftware.belegscanner.gui;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class FilterComboBoxText {
private JFrame frame;
private final JComboBox<String> comboBox = new JComboBox<>();
private static List<String>listForComboBox= new ArrayList<String>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FilterComboBoxText window = new FilterComboBoxText();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
listForComboBox.add("Lion");
listForComboBox.add("LionKing");
listForComboBox.add("Mufasa");
listForComboBox.add("Nala");
listForComboBox.add("KingNala");
listForComboBox.add("Animals");
listForComboBox.add("Anims");
listForComboBox.add("Fish");
listForComboBox.add("Jelly Fish");
listForComboBox.add("I am the boss");
}
public FilterComboBoxText() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 412, 165);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
comboBox.setEditable(true);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
}
});
for(String detail : listForComboBox) comboBox.addItem(detail);
final JTextField textfield = (JTextField) comboBox.getEditor().getEditorComponent();
textfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(!textfield.getText().isEmpty()){
comboBoxFilter(textfield.getText());
}
}
});
}
});
comboBox.setBounds(10, 39, 364, 29);
frame.getContentPane().add(comboBox);
}
public void comboBoxFilter(String enteredText) {
System.out.println(comboBox.getItemCount());
if (!comboBox.isPopupVisible()) {
comboBox.showPopup();
}
List<String> filterArray= new ArrayList<String>();
for (int i = 0; i < listForComboBox.size(); i++) {
if (listForComboBox.get(i).toLowerCase().contains(enteredText.toLowerCase())) {
filterArray.add(listForComboBox.get(i));
}
}
if (filterArray.size() > 0) {
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) comboBox.getModel();
model.removeAllElements();
model.addElement("");
for (String s: filterArray)
model.addElement(s);
JTextField textfield = (JTextField) comboBox.getEditor().getEditorComponent();
textfield.setText(enteredText);
}
}
}

View File

@@ -0,0 +1,118 @@
package de.srsoftware.belegscanner.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.srsoftware.belegscanner.Configuration;
public class MainFrame extends JFrame {
private static final Logger LOG = LoggerFactory.getLogger(MainFrame.class);
private static final long serialVersionUID = 210283601541223645L;
private static final String HOME = System.getProperty("user.home");
private static final Pattern MARKEN = Pattern.compile("\\$([a-zA-Z]+)");
private StatusBar statusBar;
private Toolbar toolbar;
private HashMap<String,String> fields = new HashMap<>();
private String path = "";
private String category ="";
private Date date = new Date();
private String patchedPath = "";
private Configuration config;
public MainFrame(Configuration config) {
this.config = config;
int width = config.getOrCreate("app.main.dimenstion.w",800);
int height = config.getOrCreate("app.main.dimenstion.h",600);
BorderLayout layout = new BorderLayout();
setLayout(layout);
toolbar = new Toolbar(config);
statusBar = new StatusBar();
add(toolbar,BorderLayout.EAST);
add(statusBar,BorderLayout.SOUTH);
toolbar.addCategoryListener(this::setCategory)
.addDateListener(this::setDate)
.addFieldListener(this::setField)
.addPathListener(this::setPath)
.addScanListener(this::scan);
setPreferredSize(new Dimension(width,height));
pack();
setVisible(true);
}
private void addFieldsFor(String path) {
Vector<String> marks = new Vector<>();
Matcher matches = MARKEN.matcher(path);
while (matches.find()) marks.add(matches.group(1));
toolbar.addFieldsFor(marks);
};
private void scan(ActionEvent ev) {
LOG.debug("Scanning into '{}'",patchedPath);
config.set("app.categories."+category+".path",path);
}
private void setCategory(String category) {
this.category = category;
updatePath();
}
private void setDate(Date date) {
this.date = date;
updatePath();
}
private void setField(String key, String val) {
fields.put(key, val);
updatePath();
}
private void setPath(String path) {
this.path = path;
updatePath();
}
@SuppressWarnings("deprecation")
private void updatePath() {
LOG.debug("updatePath() [path = {}]",path);
int year = 1900+date.getYear();
int month = date.getMonth()+1;
int day = date.getDate();
patchedPath = path.replace("$HOME",HOME)
.replace("$KATEGORIE", category)
.replace("$JAHR", year+"")
.replace("$MONAT", month<10 ? "0"+month : ""+month)
.replace("$TAG", day < 10 ? "0"+day : ""+day);
addFieldsFor(patchedPath);
for (Entry<String, String> entry : fields.entrySet()) patchedPath = patchedPath.replace("$"+entry.getKey(), entry.getValue());
statusBar.setPath(patchedPath);
}
}

View File

@@ -0,0 +1,27 @@
package de.srsoftware.belegscanner.gui;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StatusBar extends JPanel {
private static final Logger LOG = LoggerFactory.getLogger(StatusBar.class);
private static final long serialVersionUID = 8102800846089594705L;
private JLabel path;
public StatusBar() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(path = new JLabel());
}
public StatusBar setPath(String path) {
LOG.debug("setPath({})",path);
this.path.setText(path);
return this;
}
}

View File

@@ -0,0 +1,195 @@
package de.srsoftware.belegscanner.gui;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.srsoftware.belegscanner.Configuration;
import de.srsoftware.tools.gui.DateChooser;
import de.srsoftware.tools.gui.SelectComboBox;
public class Toolbar extends JPanel {
private static final Logger LOG = LoggerFactory.getLogger(Toolbar.class);
public interface CategoryListener{
public void setCategory(String category);
}
public interface DateListener{
public void setDate(Date date);
}
public interface FieldListener{
public void setField(String name, String value);
}
public interface PathListener{
public void setPath(String path);
}
private static final long serialVersionUID = -5834326573752788233L;
private Vector<Object> categories = new Vector<>();
private Vector<Object> paths = new Vector<>();
private HashSet<CategoryListener> categoryListeners = new HashSet<>();
private HashSet<DateListener> dateListeners = new HashSet<>();
private HashSet<FieldListener> fieldListeners = new HashSet<>();
private HashSet<PathListener> pathListeners = new HashSet<>();
private HashSet<ActionListener> scanListeners = new HashSet<>();
private HashMap<String,Component> additonalComponents = new HashMap<>();
private DateChooser date;
private Configuration config;
private SelectComboBox pathPicker;
public Toolbar(Configuration config) {
this.config = config;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(datePicker());
add(input("Kategorie",categoryPicker(config)));
add(input("Pfad",pathPicker = pathPicker()));
add(scanButton());
add(externButton());
}
public void addFieldsFor(Vector<String> marks) {
LOG.debug("addFieldsFor({})",marks);
List<String> deleted = additonalComponents.keySet().stream().filter(key -> !marks.contains(key)).collect(Collectors.toList());
deleted.forEach(name -> remove(additonalComponents.remove(name)));
for (String name : marks) {
if (additonalComponents.containsKey(name)) continue;
List<Object> knownValues = List.of();
SelectComboBox valuePicker = new SelectComboBox(knownValues).onUpdateText(newText -> updateField(name,newText));
Component input = input(name, valuePicker);
add(input,getComponentCount()-2);
additonalComponents.put(name, input);
}
}
public Toolbar addCategoryListener(CategoryListener listener) {
categoryListeners.add(listener);
return this;
}
public Toolbar addDateListener(DateListener listener) {
dateListeners.add(listener);
return this;
}
public Toolbar addFieldListener(FieldListener listener) {
fieldListeners.add(listener);
return this;
}
public Toolbar addPathListener(PathListener listener){
pathListeners.add(listener);
return this;
}
public Toolbar addScanListener(ActionListener listener) {
scanListeners.add(listener);
return this;
}
private Component categoryPicker(Configuration config) {
JSONObject elements = config.getOrCreate("app.categories",new JSONObject());
elements.keySet().forEach(categories::add);
return new SelectComboBox(categories).onUpdateText(this::updateCat);
}
private Component datePicker() {
date = new DateChooser();
Dimension dim = new Dimension(400, 250);
date.setMaximumSize(dim);
date.addActionListener(ev -> dateListeners.forEach(listener -> listener.setDate(date.getSelectedDate())));
return date;
}
private JButton externButton() {
JButton btn = new JButton("extern öffnen");
return btn;
}
private Component input(String caption, Component component) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel(caption+" "));
panel.add(component);
return panel;
}
public Date getDate() {
return date.getSelectedDate();
}
private SelectComboBox pathPicker() {
JSONObject cats = config.getOrCreate("app.categories",new JSONObject());
for (String catName : cats.keySet()) {
JSONObject catInfo = cats.getJSONObject(catName);
if (catInfo.has("path")) paths.add(catInfo.get("path"));
}
paths.add("$HOME/$JAHR/$MONAT-$TAG - $KATEGORIE");
return new SelectComboBox(paths).onUpdateText(this::updatePath);
}
private Component scanButton() {
JButton scanButton = new JButton("scannen!");
scanButton.addActionListener(this::scanPressed);
return scanButton;
}
private void scanPressed(ActionEvent evt) {
scanListeners.forEach(l->l.actionPerformed(evt));
}
protected void updateCat(String newCat) {
LOG.debug("updateCat({})",newCat);
categoryListeners.forEach(l -> l.setCategory(newCat));
if (!newCat.isEmpty()) {
String path = config.get("app.categories."+newCat+".path");
LOG.debug("path: {}",path);
if (path != null) {
pathPicker.setSelectedItem(path);
updatePath(path);
}
}
}
private void updateField(String name, String val) {
LOG.debug("updateField({},{})",name,val);
fieldListeners.forEach(l -> l.setField(name,val));
}
protected void updatePath(String newPath) {
LOG.debug("updatePath({})",newPath);
pathListeners.forEach(l -> l.setPath(newPath));
}
}