Merge pull request #38 from informatik-ag-ngl/f/server_config

Added config for the server and improved config mechanism.
Additionally:
- fixed small bug in both EnvoyLog and envoy.server.Startup
- fixed bug not exiting receiver thread when the server does not send anymore
- added access authorization for issues
- added option to disable attachments and groups on both client and server
- "finalized" every class that allows doing so
This commit is contained in:
delvh 2020-08-23 22:13:35 +02:00 committed by GitHub
commit a6e5b3d77d
95 changed files with 623 additions and 400 deletions

View File

@ -17,7 +17,7 @@ import envoy.client.ui.Startup;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class Main { public final class Main {
private static final boolean debug = false; private static final boolean debug = false;

View File

@ -3,10 +3,8 @@ package envoy.client.data;
import static java.util.function.Function.identity; import static java.util.function.Function.identity;
import java.io.File; import java.io.File;
import java.util.logging.Level;
import envoy.data.Config; import envoy.data.Config;
import envoy.data.ConfigItem;
/** /**
* Implements a configuration specific to the Envoy Client with default values * Implements a configuration specific to the Envoy Client with default values
@ -19,7 +17,7 @@ import envoy.data.ConfigItem;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class ClientConfig extends Config { public final class ClientConfig extends Config {
private static ClientConfig config; private static ClientConfig config;
@ -33,15 +31,13 @@ public class ClientConfig extends Config {
} }
private ClientConfig() { private ClientConfig() {
items.put("server", new ConfigItem<>("server", "s", identity(), null, true)); super(".envoy");
items.put("port", new ConfigItem<>("port", "p", Integer::parseInt, null, true)); put("server", "s", identity());
items.put("localDB", new ConfigItem<>("localDB", "db", File::new, new File("localDB"), true)); put("port", "p", Integer::parseInt);
items.put("ignoreLocalDB", new ConfigItem<>("ignoreLocalDB", "nodb", Boolean::parseBoolean, false, false)); put("localDB", "db", File::new);
items.put("homeDirectory", new ConfigItem<>("homeDirectory", "h", File::new, new File(System.getProperty("user.home"), ".envoy"), true)); put("ignoreLocalDB", "nodb", Boolean::parseBoolean);
items.put("fileLevelBarrier", new ConfigItem<>("fileLevelBarrier", "fb", Level::parse, Level.OFF, true)); put("user", "u", identity());
items.put("consoleLevelBarrier", new ConfigItem<>("consoleLevelBarrier", "cb", Level::parse, Level.OFF, true)); put("password", "pw", identity());
items.put("user", new ConfigItem<>("user", "u", identity()));
items.put("password", new ConfigItem<>("password", "pw", identity()));
} }
/** /**
@ -68,24 +64,6 @@ public class ClientConfig extends Config {
*/ */
public Boolean isIgnoreLocalDB() { return (Boolean) items.get("ignoreLocalDB").get(); } public Boolean isIgnoreLocalDB() { return (Boolean) items.get("ignoreLocalDB").get(); }
/**
* @return the directory in which all local files are saves
* @since Envoy Client v0.2-alpha
*/
public File getHomeDirectory() { return (File) items.get("homeDirectory").get(); }
/**
* @return the minimal {@link Level} to log inside the log file
* @since Envoy Client v0.2-alpha
*/
public Level getFileLevelBarrier() { return (Level) items.get("fileLevelBarrier").get(); }
/**
* @return the minimal {@link Level} to log inside the console
* @since Envoy Client v0.2-alpha
*/
public Level getConsoleLevelBarrier() { return (Level) items.get("consoleLevelBarrier").get(); }
/** /**
* @return the user name * @return the user name
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha

View File

@ -17,11 +17,11 @@ import envoy.event.GroupMessageStatusChange;
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>GroupChat.java</strong><br> * File: <strong>GroupChat.java</strong><br>
* Created: <strong>05.07.2020</strong><br> * Created: <strong>05.07.2020</strong><br>
* *
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class GroupChat extends Chat { public final class GroupChat extends Chat {
private final User sender; private final User sender;
@ -41,13 +41,10 @@ public class GroupChat extends Chat {
public void read(WriteProxy writeProxy) throws IOException { public void read(WriteProxy writeProxy) throws IOException {
for (int i = messages.size() - 1; i >= 0; --i) { for (int i = messages.size() - 1; i >= 0; --i) {
final GroupMessage gmsg = (GroupMessage) messages.get(i); final GroupMessage gmsg = (GroupMessage) messages.get(i);
if (gmsg.getSenderID() != sender.getID()) { if (gmsg.getSenderID() != sender.getID()) if (gmsg.getMemberStatuses().get(sender.getID()) == MessageStatus.READ) break;
if (gmsg.getMemberStatuses().get(sender.getID()) == MessageStatus.READ) break; else {
else { gmsg.getMemberStatuses().replace(sender.getID(), MessageStatus.READ);
gmsg.getMemberStatuses().replace(sender.getID(), MessageStatus.READ); writeProxy.writeMessageStatusChange(new GroupMessageStatusChange(gmsg.getID(), MessageStatus.READ, Instant.now(), sender.getID()));
writeProxy
.writeMessageStatusChange(new GroupMessageStatusChange(gmsg.getID(), MessageStatus.READ, Instant.now(), sender.getID()));
}
} }
} }
unreadAmount = 0; unreadAmount = 0;

View File

@ -22,7 +22,7 @@ import envoy.util.SerializationUtils;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.2-alpha * @since Envoy Client v0.2-alpha
*/ */
public class Settings { public final class Settings {
// Actual settings accessible by the rest of the application // Actual settings accessible by the rest of the application
private Map<String, SettingsItem<?>> items; private Map<String, SettingsItem<?>> items;
@ -139,7 +139,9 @@ public class Settings {
* before * before
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public void setDownloadSavedWithoutAsking(boolean autosaveDownload) { ((SettingsItem<Boolean>) items.get("autoSaveDownloads")).set(autosaveDownload); } public void setDownloadSavedWithoutAsking(boolean autosaveDownload) {
((SettingsItem<Boolean>) items.get("autoSaveDownloads")).set(autosaveDownload);
}
/** /**
* @return the path where downloads should be saved * @return the path where downloads should be saved

View File

@ -17,7 +17,7 @@ import javax.swing.JComponent;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public class SettingsItem<T> implements Serializable { public final class SettingsItem<T> implements Serializable {
private T value; private T value;
private String userFriendlyName, description; private String userFriendlyName, description;

View File

@ -24,7 +24,7 @@ import java.util.function.Supplier;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class SystemCommand implements OnCall { public final class SystemCommand implements OnCall {
protected int relevance; protected int relevance;

View File

@ -14,7 +14,7 @@ import java.util.function.Consumer;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class SystemCommandBuilder { public final class SystemCommandBuilder {
private int numberOfArguments; private int numberOfArguments;
private Consumer<List<String>> action; private Consumer<List<String>> action;

View File

@ -11,7 +11,7 @@ import envoy.event.Event;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.2-alpha * @since Envoy Client v0.2-alpha
*/ */
public class MessageCreationEvent extends Event<Message> { public final class MessageCreationEvent extends Event<Message> {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;

View File

@ -11,7 +11,7 @@ import envoy.event.Event;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.2-alpha * @since Envoy Client v0.2-alpha
*/ */
public class MessageModificationEvent extends Event<Message> { public final class MessageModificationEvent extends Event<Message> {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;

View File

@ -10,7 +10,7 @@ import envoy.event.Event;
* @author: Maximilian K&aumlfer * @author: Maximilian K&aumlfer
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public class SendEvent extends Event<Event<?>> { public final class SendEvent extends Event<Event<?>> {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;

View File

@ -10,7 +10,7 @@ import envoy.event.Event;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.2-alpha * @since Envoy Client v0.2-alpha
*/ */
public class ThemeChangeEvent extends Event<String> { public final class ThemeChangeEvent extends Event<String> {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;

View File

@ -29,7 +29,7 @@ import envoy.util.SerializationUtils;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.1-alpha * @since Envoy Client v0.1-alpha
*/ */
public class Client implements Closeable { public final class Client implements Closeable {
// Connection handling // Connection handling
private Socket socket; private Socket socket;
@ -164,6 +164,13 @@ public class Client implements Closeable {
// Process ProfilePicChanges // Process ProfilePicChanges
receiver.registerProcessor(ProfilePicChange.class, eventBus::dispatch); receiver.registerProcessor(ProfilePicChange.class, eventBus::dispatch);
// Process requests to not send any more attachments as they will not be shown to
// other users
receiver.registerProcessor(NoAttachments.class, eventBus::dispatch);
// Process group creation results - they might have been disabled on the server
receiver.registerProcessor(GroupCreationResult.class, eventBus::dispatch);
// Send event // Send event
eventBus.register(SendEvent.class, evt -> { eventBus.register(SendEvent.class, evt -> {
try { try {

View File

@ -12,14 +12,14 @@ import envoy.util.EnvoyLog;
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>GroupMessageStatusChangePocessor.java</strong><br> * File: <strong>GroupMessageStatusChangePocessor.java</strong><br>
* Created: <strong>03.07.2020</strong><br> * Created: <strong>03.07.2020</strong><br>
* *
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class GroupMessageStatusChangeProcessor implements Consumer<GroupMessageStatusChange> { public final class GroupMessageStatusChangeProcessor implements Consumer<GroupMessageStatusChange> {
private static final Logger logger = EnvoyLog.getLogger(GroupMessageStatusChangeProcessor.class); private static final Logger logger = EnvoyLog.getLogger(GroupMessageStatusChangeProcessor.class);
@Override @Override
public void accept(GroupMessageStatusChange evt) { public void accept(GroupMessageStatusChange evt) {
if (evt.get().ordinal() < MessageStatus.RECEIVED.ordinal()) logger.warning("Received invalid group message status change " + evt); if (evt.get().ordinal() < MessageStatus.RECEIVED.ordinal()) logger.warning("Received invalid group message status change " + evt);

View File

@ -16,7 +16,7 @@ import envoy.util.EnvoyLog;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public class MessageStatusChangeProcessor implements Consumer<MessageStatusChange> { public final class MessageStatusChangeProcessor implements Consumer<MessageStatusChange> {
private static final Logger logger = EnvoyLog.getLogger(MessageStatusChangeProcessor.class); private static final Logger logger = EnvoyLog.getLogger(MessageStatusChangeProcessor.class);

View File

@ -13,11 +13,11 @@ import envoy.util.EnvoyLog;
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>ReceivedGroupMessageProcessor.java</strong><br> * File: <strong>ReceivedGroupMessageProcessor.java</strong><br>
* Created: <strong>13.06.2020</strong><br> * Created: <strong>13.06.2020</strong><br>
* *
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class ReceivedGroupMessageProcessor implements Consumer<GroupMessage> { public final class ReceivedGroupMessageProcessor implements Consumer<GroupMessage> {
private static final Logger logger = EnvoyLog.getLogger(ReceivedGroupMessageProcessor.class); private static final Logger logger = EnvoyLog.getLogger(ReceivedGroupMessageProcessor.class);

View File

@ -15,7 +15,7 @@ import envoy.event.EventBus;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public class ReceivedMessageProcessor implements Consumer<Message> { public final class ReceivedMessageProcessor implements Consumer<Message> {
@Override @Override
public void accept(Message message) { public void accept(Message message) {

View File

@ -22,7 +22,9 @@ import envoy.util.SerializationUtils;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public class Receiver extends Thread { public final class Receiver extends Thread {
private boolean isAlive = true;
private final InputStream in; private final InputStream in;
private final Map<Class<?>, Consumer<?>> processors = new HashMap<>(); private final Map<Class<?>, Consumer<?>> processors = new HashMap<>();
@ -49,7 +51,7 @@ public class Receiver extends Thread {
@Override @Override
public void run() { public void run() {
while (true) { while (isAlive)
try { try {
// Read object length // Read object length
final byte[] lenBytes = new byte[4]; final byte[] lenBytes = new byte[4];
@ -64,6 +66,12 @@ public class Receiver extends Thread {
// Catch LV encoding errors // Catch LV encoding errors
if (len != bytesRead) { if (len != bytesRead) {
// Server has stopped sending, i.e. because he went offline
if (bytesRead == -1) {
isAlive = false;
logger.log(Level.INFO, "Lost connection to the server. Exiting receiver...");
continue;
}
logger.log(Level.WARNING, logger.log(Level.WARNING,
String.format("LV encoding violated: expected %d bytes, received %d bytes. Discarding object...", len, bytesRead)); String.format("LV encoding violated: expected %d bytes, received %d bytes. Discarding object...", len, bytesRead));
continue; continue;
@ -87,7 +95,6 @@ public class Receiver extends Thread {
} catch (final Exception e) { } catch (final Exception e) {
logger.log(Level.SEVERE, "Error on receiver thread", e); logger.log(Level.SEVERE, "Error on receiver thread", e);
} }
}
} }
/** /**
@ -102,7 +109,7 @@ public class Receiver extends Thread {
/** /**
* Adds a map of object processors to this {@link Receiver}. * Adds a map of object processors to this {@link Receiver}.
* *
* @param processors the processors to add the processors to add * @param processors the processors to add the processors to add
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */

View File

@ -22,7 +22,7 @@ import envoy.util.EnvoyLog;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public class WriteProxy { public final class WriteProxy {
private final Client client; private final Client client;
private final LocalDB localDB; private final LocalDB localDB;
@ -68,9 +68,7 @@ public class WriteProxy {
* *
* @since Envoy Client v0.3-alpha * @since Envoy Client v0.3-alpha
*/ */
public void flushCache() { public void flushCache() { localDB.getCacheMap().getMap().values().forEach(Cache::relay); }
localDB.getCacheMap().getMap().values().forEach(Cache::relay);
}
/** /**
* Delivers a message to the server if online. Otherwise the message is cached * Delivers a message to the server if online. Otherwise the message is cached

View File

@ -22,7 +22,7 @@ import javafx.scene.layout.GridPane;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class ClearableTextField extends GridPane { public final class ClearableTextField extends GridPane {
private final TextField textField; private final TextField textField;
@ -88,82 +88,82 @@ public class ClearableTextField extends GridPane {
* @see javafx.scene.control.TextInputControl#promptTextProperty() * @see javafx.scene.control.TextInputControl#promptTextProperty()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final StringProperty promptTextProperty() { return textField.promptTextProperty(); } public StringProperty promptTextProperty() { return textField.promptTextProperty(); }
/** /**
* @return the current prompt text * @return the current prompt text
* @see javafx.scene.control.TextInputControl#getPromptText() * @see javafx.scene.control.TextInputControl#getPromptText()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final String getPromptText() { return textField.getPromptText(); } public String getPromptText() { return textField.getPromptText(); }
/** /**
* @param value the prompt text to display * @param value the prompt text to display
* @see javafx.scene.control.TextInputControl#setPromptText(java.lang.String) * @see javafx.scene.control.TextInputControl#setPromptText(java.lang.String)
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final void setPromptText(String value) { textField.setPromptText(value); } public void setPromptText(String value) { textField.setPromptText(value); }
/** /**
* @return the current property of the tooltip * @return the current property of the tooltip
* @see javafx.scene.control.Control#tooltipProperty() * @see javafx.scene.control.Control#tooltipProperty()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final ObjectProperty<Tooltip> tooltipProperty() { return textField.tooltipProperty(); } public ObjectProperty<Tooltip> tooltipProperty() { return textField.tooltipProperty(); }
/** /**
* @param value the new tooltip * @param value the new tooltip
* @see javafx.scene.control.Control#setTooltip(javafx.scene.control.Tooltip) * @see javafx.scene.control.Control#setTooltip(javafx.scene.control.Tooltip)
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final void setTooltip(Tooltip value) { textField.setTooltip(value); } public void setTooltip(Tooltip value) { textField.setTooltip(value); }
/** /**
* @return the current tooltip * @return the current tooltip
* @see javafx.scene.control.Control#getTooltip() * @see javafx.scene.control.Control#getTooltip()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final Tooltip getTooltip() { return textField.getTooltip(); } public Tooltip getTooltip() { return textField.getTooltip(); }
/** /**
* @return the current property of the context menu * @return the current property of the context menu
* @see javafx.scene.control.Control#contextMenuProperty() * @see javafx.scene.control.Control#contextMenuProperty()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final ObjectProperty<ContextMenu> contextMenuProperty() { return textField.contextMenuProperty(); } public ObjectProperty<ContextMenu> contextMenuProperty() { return textField.contextMenuProperty(); }
/** /**
* @param value the new context menu * @param value the new context menu
* @see javafx.scene.control.Control#setContextMenu(javafx.scene.control.ContextMenu) * @see javafx.scene.control.Control#setContextMenu(javafx.scene.control.ContextMenu)
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final void setContextMenu(ContextMenu value) { textField.setContextMenu(value); } public void setContextMenu(ContextMenu value) { textField.setContextMenu(value); }
/** /**
* @return the current context menu * @return the current context menu
* @see javafx.scene.control.Control#getContextMenu() * @see javafx.scene.control.Control#getContextMenu()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final ContextMenu getContextMenu() { return textField.getContextMenu(); } public ContextMenu getContextMenu() { return textField.getContextMenu(); }
/** /**
* @param value whether this ClearableTextField should be editable * @param value whether this ClearableTextField should be editable
* @see javafx.scene.control.TextInputControl#setEditable(boolean) * @see javafx.scene.control.TextInputControl#setEditable(boolean)
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final void setEditable(boolean value) { textField.setEditable(value); } public void setEditable(boolean value) { textField.setEditable(value); }
/** /**
* @return the current property whether this ClearableTextField is editable * @return the current property whether this ClearableTextField is editable
* @see javafx.scene.control.TextInputControl#editableProperty() * @see javafx.scene.control.TextInputControl#editableProperty()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final BooleanProperty editableProperty() { return textField.editableProperty(); } public BooleanProperty editableProperty() { return textField.editableProperty(); }
/** /**
* @return whether this {@code ClearableTextField} is editable * @return whether this {@code ClearableTextField} is editable
* @see javafx.scene.control.TextInputControl#isEditable() * @see javafx.scene.control.TextInputControl#isEditable()
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public final boolean isEditable() { return textField.isEditable(); } public boolean isEditable() { return textField.isEditable(); }
} }

View File

@ -24,7 +24,7 @@ import envoy.util.EnvoyLog;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class IconUtil { public final class IconUtil {
private IconUtil() {} private IconUtil() {}
@ -160,7 +160,7 @@ public class IconUtil {
BufferedImage image = null; BufferedImage image = null;
try { try {
image = ImageIO.read(IconUtil.class.getResource(path)); image = ImageIO.read(IconUtil.class.getResource(path));
} catch (IOException e) { } catch (final IOException e) {
EnvoyLog.getLogger(IconUtil.class).log(Level.WARNING, String.format("Could not load image at path %s: ", path), e); EnvoyLog.getLogger(IconUtil.class).log(Level.WARNING, String.format("Could not load image at path %s: ", path), e);
} }
return image; return image;

View File

@ -2,7 +2,6 @@ package envoy.client.ui;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -19,7 +18,6 @@ import envoy.data.GroupMessage;
import envoy.data.Message; import envoy.data.Message;
import envoy.event.GroupMessageStatusChange; import envoy.event.GroupMessageStatusChange;
import envoy.event.MessageStatusChange; import envoy.event.MessageStatusChange;
import envoy.exception.EnvoyException;
import envoy.util.EnvoyLog; import envoy.util.EnvoyLog;
/** /**
@ -57,30 +55,13 @@ public final class Startup extends Application {
@Override @Override
public void start(Stage stage) throws Exception { public void start(Stage stage) throws Exception {
try { try {
// Load the configuration from client.properties first config.loadAll(Startup.class, "client.properties", getParameters().getRaw().toArray(new String[0]));
final Properties properties = new Properties(); EnvoyLog.initialize(config);
properties.load(Startup.class.getClassLoader().getResourceAsStream("client.properties")); } catch (final IllegalStateException e) {
config.load(properties);
// Override configuration values with command line arguments
final String[] args = getParameters().getRaw().toArray(new String[0]);
if (args.length > 0) config.load(args);
// Check if all mandatory configuration values have been initialized
if (!config.isInitialized()) throw new EnvoyException("Configuration is not fully initialized");
} catch (final Exception e) {
new Alert(AlertType.ERROR, "Error loading configuration values:\n" + e); new Alert(AlertType.ERROR, "Error loading configuration values:\n" + e);
logger.log(Level.SEVERE, "Error loading configuration values: ", e); logger.log(Level.SEVERE, "Error loading configuration values: ", e);
e.printStackTrace();
System.exit(1); System.exit(1);
} }
// Setup logger for the envoy package
EnvoyLog.initialize(config);
EnvoyLog.attach("envoy");
EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier());
logger.log(Level.INFO, "Envoy starting..."); logger.log(Level.INFO, "Envoy starting...");
// Initialize the local database // Initialize the local database

View File

@ -18,7 +18,7 @@ import envoy.event.EventBus;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.2-alpha * @since Envoy Client v0.2-alpha
*/ */
public class StatusTrayIcon { public final class StatusTrayIcon {
/** /**
* The {@link TrayIcon} provided by the System Tray API for controlling the * The {@link TrayIcon} provided by the System Tray API for controlling the
@ -85,12 +85,12 @@ public class StatusTrayIcon {
public void show() { public void show() {
try { try {
SystemTray.getSystemTray().add(trayIcon); SystemTray.getSystemTray().add(trayIcon);
} catch (AWTException e) {} } catch (final AWTException e) {}
} }
/** /**
* Removes the icon from the system tray. * Removes the icon from the system tray.
* *
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public void hide() { SystemTray.getSystemTray().remove(trayIcon); } public void hide() { SystemTray.getSystemTray().remove(trayIcon); }

View File

@ -87,6 +87,12 @@ public final class ChatScene implements Restorable {
@FXML @FXML
private Button rotateButton; private Button rotateButton;
@FXML
private Button messageSearchButton;
@FXML
private Button newGroupButton;
@FXML @FXML
private TextArea messageTextArea; private TextArea messageTextArea;
@ -108,9 +114,6 @@ public final class ChatScene implements Restorable {
@FXML @FXML
private Label topBarStatusLabel; private Label topBarStatusLabel;
@FXML
private Button messageSearchButton;
@FXML @FXML
private ImageView clientProfilePic; private ImageView clientProfilePic;
@ -129,7 +132,7 @@ public final class ChatScene implements Restorable {
private AudioRecorder recorder; private AudioRecorder recorder;
private boolean recording; private boolean recording;
private Attachment pendingAttachment; private Attachment pendingAttachment;
private boolean postingPermanentlyDisabled; private boolean postingPermanentlyDisabled;
private final SystemCommandsMap messageTextAreaCommands = new SystemCommandsMap(); private final SystemCommandsMap messageTextAreaCommands = new SystemCommandsMap();
@ -237,6 +240,21 @@ public final class ChatScene implements Restorable {
break; break;
} }
}); });
// Disable attachment button if server says attachments will be filtered out
eventBus.register(NoAttachments.class, e -> {
Platform.runLater(() -> {
attachmentButton.setDisable(true);
voiceButton.setDisable(true);
final var alert = new Alert(AlertType.ERROR);
alert.setTitle("No attachments possible");
alert.setHeaderText("Your current server does not support attachments.");
alert.setContentText("If this is unplanned, please contact your server administrator.");
alert.showAndWait();
});
});
eventBus.register(GroupCreationResult.class, e -> Platform.runLater(() -> { newGroupButton.setDisable(!e.get()); }));
} }
/** /**

View File

@ -6,10 +6,8 @@ import java.util.logging.Logger;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Alert; import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import envoy.client.data.LocalDB; import envoy.client.data.LocalDB;
import envoy.client.event.SendEvent; import envoy.client.event.SendEvent;
@ -20,6 +18,7 @@ import envoy.client.ui.listcell.ListCellFactory;
import envoy.data.User; import envoy.data.User;
import envoy.event.ElementOperation; import envoy.event.ElementOperation;
import envoy.event.EventBus; import envoy.event.EventBus;
import envoy.event.GroupCreationResult;
import envoy.event.contact.ContactOperation; import envoy.event.contact.ContactOperation;
import envoy.event.contact.UserSearchRequest; import envoy.event.contact.UserSearchRequest;
import envoy.event.contact.UserSearchResult; import envoy.event.contact.UserSearchResult;
@ -42,7 +41,7 @@ import envoy.util.EnvoyLog;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class ContactSearchScene { public final class ContactSearchScene {
@FXML @FXML
private ClearableTextField searchBar; private ClearableTextField searchBar;
@ -50,6 +49,9 @@ public class ContactSearchScene {
@FXML @FXML
private ListView<User> userList; private ListView<User> userList;
@FXML
private Button newGroupButton;
private SceneContext sceneContext; private SceneContext sceneContext;
private LocalDB localDB; private LocalDB localDB;
@ -86,6 +88,7 @@ public class ContactSearchScene {
eventBus.register(UserSearchResult.class, eventBus.register(UserSearchResult.class,
response -> Platform.runLater(() -> { userList.getItems().clear(); userList.getItems().addAll(response.get()); })); response -> Platform.runLater(() -> { userList.getItems().clear(); userList.getItems().addAll(response.get()); }));
eventBus.register(ContactOperation.class, handler); eventBus.register(ContactOperation.class, handler);
eventBus.register(GroupCreationResult.class, e -> Platform.runLater(() -> { newGroupButton.setDisable(!e.get()); }));
} }
/** /**

View File

@ -21,6 +21,7 @@ import envoy.data.Group;
import envoy.data.User; import envoy.data.User;
import envoy.event.EventBus; import envoy.event.EventBus;
import envoy.event.GroupCreation; import envoy.event.GroupCreation;
import envoy.event.GroupCreationResult;
import envoy.util.Bounds; import envoy.util.Bounds;
/** /**
@ -39,7 +40,7 @@ import envoy.util.Bounds;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class GroupCreationScene { public final class GroupCreationScene {
@FXML @FXML
private Button createButton; private Button createButton;
@ -54,6 +55,8 @@ public class GroupCreationScene {
private LocalDB localDB; private LocalDB localDB;
private String groupName;
private static final EventBus eventBus = EventBus.getInstance(); private static final EventBus eventBus = EventBus.getInstance();
@FXML @FXML
@ -61,6 +64,18 @@ public class GroupCreationScene {
userList.setCellFactory(new ListCellFactory<>(ContactControl::new)); userList.setCellFactory(new ListCellFactory<>(ContactControl::new));
userList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); userList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
groupNameField.setClearButtonListener(e -> { groupNameField.getTextField().clear(); createButton.setDisable(true); }); groupNameField.setClearButtonListener(e -> { groupNameField.getTextField().clear(); createButton.setDisable(true); });
eventBus.register(GroupCreationResult.class, e -> Platform.runLater(() -> {
if (e.get()) new Alert(AlertType.INFORMATION, String.format("Group '%s' successfully created.", groupName)).showAndWait();
else {
createButton.setDisable(true);
final var alert = new Alert(AlertType.ERROR);
alert.setTitle("Groups are not allowed");
alert.setHeaderText("Cannot create group as your current server disabled this feature");
alert.setContentText("If this is unplanned, please contact your server administrator.");
alert.showAndWait();
sceneContext.pop();
}
}));
} }
/** /**
@ -119,10 +134,7 @@ public class GroupCreationScene {
alert.setTitle("Create Group?"); alert.setTitle("Create Group?");
alert.setHeaderText("Proceed?"); alert.setHeaderText("Proceed?");
alert.showAndWait().filter(btn -> btn == ButtonType.OK).ifPresent(btn -> createGroup(name)); alert.showAndWait().filter(btn -> btn == ButtonType.OK).ifPresent(btn -> createGroup(name));
} else { } else createGroup(name);
new Alert(AlertType.INFORMATION, String.format("Group '%s' successfully created.", name)).showAndWait();
createGroup(name);
}
} }
/** /**
@ -133,9 +145,9 @@ public class GroupCreationScene {
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
private void createGroup(String name) { private void createGroup(String name) {
groupName = name;
eventBus.dispatch(new SendEvent( eventBus.dispatch(new SendEvent(
new GroupCreation(name, userList.getSelectionModel().getSelectedItems().stream().map(User::getID).collect(Collectors.toSet())))); new GroupCreation(name, userList.getSelectionModel().getSelectedItems().stream().map(User::getID).collect(Collectors.toSet()))));
sceneContext.pop();
} }
/** /**

View File

@ -18,7 +18,7 @@ import envoy.client.ui.settings.*;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class SettingsScene { public final class SettingsScene {
@FXML @FXML
private ListView<SettingsPane> settingsList; private ListView<SettingsPane> settingsList;

View File

@ -23,7 +23,7 @@ import envoy.data.Group;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class ChatControl extends HBox { public final class ChatControl extends HBox {
/** /**
* @param chat the chat to display * @param chat the chat to display
@ -36,7 +36,7 @@ public class ChatControl extends HBox {
ImageView contactProfilePic; ImageView contactProfilePic;
if (chat.getRecipient() instanceof Group) contactProfilePic = new ImageView(IconUtil.loadIconThemeSensitive("group_icon", 32)); if (chat.getRecipient() instanceof Group) contactProfilePic = new ImageView(IconUtil.loadIconThemeSensitive("group_icon", 32));
else contactProfilePic = new ImageView(IconUtil.loadIconThemeSensitive("user_icon", 32)); else contactProfilePic = new ImageView(IconUtil.loadIconThemeSensitive("user_icon", 32));
Rectangle clip = new Rectangle(); final var clip = new Rectangle();
clip.setWidth(32); clip.setWidth(32);
clip.setHeight(32); clip.setHeight(32);
clip.setArcHeight(32); clip.setArcHeight(32);
@ -44,7 +44,7 @@ public class ChatControl extends HBox {
contactProfilePic.setClip(clip); contactProfilePic.setClip(clip);
getChildren().add(contactProfilePic); getChildren().add(contactProfilePic);
// spacing // spacing
Region leftSpacing = new Region(); final var leftSpacing = new Region();
leftSpacing.setPrefSize(8, 0); leftSpacing.setPrefSize(8, 0);
leftSpacing.setMinSize(8, 0); leftSpacing.setMinSize(8, 0);
leftSpacing.setMaxSize(8, 0); leftSpacing.setMaxSize(8, 0);

View File

@ -18,7 +18,7 @@ import envoy.data.User;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class ContactControl extends VBox { public final class ContactControl extends VBox {
/** /**
* @param contact the contact to display * @param contact the contact to display
@ -36,9 +36,7 @@ public class ContactControl extends VBox {
final var statusLabel = new Label(status); final var statusLabel = new Label(status);
statusLabel.getStyleClass().add(status.toLowerCase()); statusLabel.getStyleClass().add(status.toLowerCase());
getChildren().add(statusLabel); getChildren().add(statusLabel);
} else { } else getChildren().add(new Label(contact.getContacts().size() + " members"));
getChildren().add(new Label(contact.getContacts().size() + " members"));
}
getStyleClass().add("listElement"); getStyleClass().add("listElement");
} }
} }

View File

@ -24,7 +24,6 @@ import envoy.client.data.Settings;
import envoy.client.ui.AudioControl; import envoy.client.ui.AudioControl;
import envoy.client.ui.IconUtil; import envoy.client.ui.IconUtil;
import envoy.client.ui.SceneContext; import envoy.client.ui.SceneContext;
import envoy.data.GroupMessage; import envoy.data.GroupMessage;
import envoy.data.Message; import envoy.data.Message;
import envoy.data.Message.MessageStatus; import envoy.data.Message.MessageStatus;
@ -42,7 +41,7 @@ import envoy.util.EnvoyLog;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class MessageControl extends Label { public final class MessageControl extends Label {
private boolean ownMessage; private boolean ownMessage;
@ -179,7 +178,7 @@ public class MessageControl extends Label {
} }
/** /**
* @param localDB the localDB used by the current user * @param localDB the localDB used by the current user
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public static void setLocalDB(LocalDB localDB) { MessageControl.localDB = localDB; } public static void setLocalDB(LocalDB localDB) { MessageControl.localDB = localDB; }

View File

@ -21,7 +21,7 @@ import envoy.event.IssueProposal;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class BugReportPane extends OnlyIfOnlineSettingsPane { public final class BugReportPane extends OnlyIfOnlineSettingsPane {
private final Label titleLabel = new Label("Suggest a title for the bug:"); private final Label titleLabel = new Label("Suggest a title for the bug:");
private final TextField titleTextField = new TextField(); private final TextField titleTextField = new TextField();

View File

@ -17,7 +17,7 @@ import envoy.client.ui.SceneContext;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class DownloadSettingsPane extends SettingsPane { public final class DownloadSettingsPane extends SettingsPane {
/** /**
* Constructs a new {@code DownloadSettingsPane}. * Constructs a new {@code DownloadSettingsPane}.

View File

@ -16,7 +16,7 @@ import envoy.event.EventBus;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class GeneralSettingsPane extends SettingsPane { public final class GeneralSettingsPane extends SettingsPane {
/** /**
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta

View File

@ -35,7 +35,7 @@ import envoy.util.EnvoyLog;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class UserSettingsPane extends OnlyIfOnlineSettingsPane { public final class UserSettingsPane extends OnlyIfOnlineSettingsPane {
private boolean profilePicChanged, usernameChanged, validPassword; private boolean profilePicChanged, usernameChanged, validPassword;
private byte[] currentImageBytes; private byte[] currentImageBytes;

View File

@ -10,7 +10,7 @@ package envoy.client.util;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class IssueUtil { public final class IssueUtil {
/** /**
* *

View File

@ -15,7 +15,7 @@ import javafx.scene.Node;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class ReflectionUtil { public final class ReflectionUtil {
private ReflectionUtil() {} private ReflectionUtil() {}

View File

@ -1,4 +1,6 @@
server=localhost server=localhost
port=8080 port=8080
localDB=localDB localDB=localDB
consoleLevelBarrier=FINER consoleLevelBarrier=FINER
fileLevelBarrier=OFF
ignoreLocalDB=false

View File

@ -62,7 +62,7 @@
<Insets /> <Insets />
</HBox.margin> </HBox.margin>
</Button> </Button>
<Button mnemonicParsing="false" prefWidth="100.0" text="New Group"> <Button fx:id="newGroupButton" mnemonicParsing="false" prefWidth="100.0" text="New Group">
<HBox.margin> <HBox.margin>
<Insets /> <Insets />
</HBox.margin> </HBox.margin>

View File

@ -34,7 +34,7 @@
wrapText="true" /> wrapText="true" />
</tooltip> </tooltip>
</ClearableTextField> </ClearableTextField>
<Button mnemonicParsing="false" <Button fx:id="newGroupButton" mnemonicParsing="false"
onAction="#newGroupButtonClicked" prefHeight="26.0" onAction="#newGroupButtonClicked" prefHeight="26.0"
prefWidth="139.0" text="New Group"> prefWidth="139.0" text="New Group">
<HBox.margin> <HBox.margin>

View File

@ -14,7 +14,7 @@ import java.io.Serializable;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class Attachment implements Serializable { public final class Attachment implements Serializable {
/** /**
* Defines the type of the attachment. * Defines the type of the attachment.

View File

@ -1,15 +1,25 @@
package envoy.data; package envoy.data;
import java.io.File;
import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import envoy.exception.EnvoyException; import envoy.util.EnvoyLog;
/** /**
* Manages all application settings that are set during application startup by * Manages all application settings that are set during application startup by
* either loading them from the {@link Properties} file * either loading them from the {@link Properties} file (default values)
* {@code client.properties} or parsing them from the command line arguments of * {@code client.properties} or parsing them from the command line arguments of
* the application.<br> * the application.
* <br> * <p>
* All items inside the {@code Config} are supposed to either be supplied over
* default value or over command line argument. Developers that fail to provide
* default values will be greeted with an error message the next time they try
* to start Envoy...
* <p>
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>Config.java</strong><br> * File: <strong>Config.java</strong><br>
* Created: <strong>12 Oct 2019</strong><br> * Created: <strong>12 Oct 2019</strong><br>
@ -21,60 +31,109 @@ public class Config {
protected Map<String, ConfigItem<?>> items = new HashMap<>(); protected Map<String, ConfigItem<?>> items = new HashMap<>();
private boolean modificationDisabled;
protected Config(String folderName) {
final var rootDirectory = new File(System.getProperty("user.home"), folderName);
put("homeDirectory", "home", File::new);
((ConfigItem<File>) get("homeDirectory")).setValue(rootDirectory);
put("fileLevelBarrier", "fb", Level::parse);
put("consoleLevelBarrier", "cb", Level::parse);
}
/** /**
* Parses config items from a properties object. * Parses config items from a properties object.
* *
* @param properties the properties object to parse * @param properties the properties object to parse
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public void load(Properties properties) { private void load(Properties properties) {
items.entrySet() items.entrySet().stream().filter(e -> properties.containsKey(e.getKey()))
.stream() .forEach(e -> e.getValue().parse(properties.getProperty(e.getKey())));
.filter(e -> properties.containsKey(e.getKey()))
.forEach(e -> e.getValue().parse(properties.getProperty(e.getKey())));
} }
/** /**
* Parses config items from an array of command line arguments. * Parses config items from an array of command line arguments.
* *
* @param args the command line arguments to parse * @param args the command line arguments to parse
* @throws EnvoyException if the command line arguments contain an unknown token * @throws IllegalStateException if a malformed command line argument has been
* supplied
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public void load(String[] args) throws EnvoyException { private void load(String[] args) {
for (int i = 0; i < args.length; i++) for (int i = 0; i < args.length; i++)
for (ConfigItem<?> item : items.values()) for (final ConfigItem<?> item : items.values())
if (args[i].startsWith("--")) { if (args[i].startsWith("--")) {
if (args[i].length() == 2) throw new EnvoyException("Malformed command line argument at position " + i); if (args[i].length() == 2)
throw new IllegalStateException(
"Malformed command line argument at position " + i + ": " + args[i]);
final String commandLong = args[i].substring(2); final String commandLong = args[i].substring(2);
if (item.getCommandLong().equals(commandLong)) { if (item.getCommandLong().equals(commandLong)) {
item.parse(args[++i]); item.parse(args[++i]);
break; break;
} }
} else if (args[i].startsWith("-")) { } else if (args[i].startsWith("-")) {
if (args[i].length() == 1) throw new EnvoyException("Malformed command line argument at position " + i); if (args[i].length() == 1)
throw new IllegalStateException(
"Malformed command line argument at position " + i + ": " + args[i]);
final String commandShort = args[i].substring(1); final String commandShort = args[i].substring(1);
if (item.getCommandShort().equals(commandShort)) { if (item.getCommandShort().equals(commandShort)) {
item.parse(args[++i]); item.parse(args[++i]);
break; break;
} }
} else throw new EnvoyException("Malformed command line argument at position " + i); } else
throw new IllegalStateException(
"Malformed command line argument at position " + i + ": " + args[i]);
} }
/** /**
* Initializes config items from a map. * Supplies default values from the given .properties file and parses the
* * configuration from an array of command line arguments.
* @param items the items to include in this config *
* @param declaringClass the class calling this method
* @param propertiesFilePath the path to where the .properties file can be found
* - will be only the file name if it is located
* directly inside the {@code src/main/resources}
* folder
* @param args the command line arguments to parse
* @throws IllegalStateException if this method is getting called again or if a
* malformed command line argument has been
* supplied
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public void load(Map<String, ConfigItem<?>> items) { this.items.putAll(items); } public void loadAll(Class<?> declaringClass, String propertiesFilePath, String[] args) {
if (modificationDisabled)
throw new IllegalStateException("Cannot change config after isInitialized has been called");
// Load the defaults from the given .properties file first
final var properties = new Properties();
try {
properties.load(declaringClass.getClassLoader().getResourceAsStream(propertiesFilePath));
} catch (final IOException e) {
EnvoyLog.getLogger(Config.class).log(Level.SEVERE, "An error occurred when reading in the configuration: ",
e);
}
load(properties);
// Override configuration values with command line arguments
if (args.length > 0)
load(args);
// Check if all configuration values have been initialized
isInitialized();
// Disable further editing of the config
modificationDisabled = true;
}
/** /**
* @return {@code true} if all mandatory config items are initialized * @throws IllegalStateException if a {@link ConfigItem} has not been
* initialized
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public boolean isInitialized() { private void isInitialized() {
return items.values().stream().filter(ConfigItem::isMandatory).map(ConfigItem::get).noneMatch(Objects::isNull); if (items.values().stream().map(ConfigItem::get).anyMatch(Objects::isNull))
throw new IllegalStateException("config item(s) has/ have not been initialized:"
+ items.values().stream().filter(configItem -> configItem.get() == null)
.map(ConfigItem::getCommandLong).collect(Collectors.toSet()));
} }
/** /**
@ -82,5 +141,46 @@ public class Config {
* @return the config item with the specified name * @return the config item with the specified name
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public ConfigItem<?> get(String name) { return items.get(name); } public ConfigItem<?> get(String name) {
return items.get(name);
}
/**
* Shorthand for <br>
* {@code items.put(commandName, new ConfigItem<>(commandName, commandShort, parseFunction, defaultValue))}.
*
* @param <T> the type of the {@link ConfigItem}
* @param commandName the key for this config item as well as its long name
* @param commandShort the abbreviation of this config item
* @param parseFunction the {@code Function<String, T>} that parses the value
* from a string
* @since Envoy Common v0.2-beta
*/
protected <T> void put(String commandName, String commandShort, Function<String, T> parseFunction) {
items.put(commandName, new ConfigItem<>(commandName, commandShort, parseFunction));
}
/**
* @return the directory in which all local files are saves
* @since Envoy Client v0.2-beta
*/
public File getHomeDirectory() {
return (File) items.get("homeDirectory").get();
}
/**
* @return the minimal {@link Level} to log inside the log file
* @since Envoy Client v0.2-beta
*/
public Level getFileLevelBarrier() {
return (Level) items.get("fileLevelBarrier").get();
}
/**
* @return the minimal {@link Level} to log inside the console
* @since Envoy Client v0.2-beta
*/
public Level getConsoleLevelBarrier() {
return (Level) items.get("consoleLevelBarrier").get();
}
} }

View File

@ -4,8 +4,10 @@ import java.util.function.Function;
/** /**
* Contains a single {@link Config} value as well as the corresponding command * Contains a single {@link Config} value as well as the corresponding command
* line arguments and its default value.<br> * line arguments and its default value.
* <br> * <p>
* All {@code ConfigItem}s are automatically mandatory.
* <p>
* Project: <strong>envoy-clientChess</strong><br> * Project: <strong>envoy-clientChess</strong><br>
* File: <strong>ConfigItem.javaEvent.java</strong><br> * File: <strong>ConfigItem.javaEvent.java</strong><br>
* Created: <strong>21.12.2019</strong><br> * Created: <strong>21.12.2019</strong><br>
@ -14,11 +16,10 @@ import java.util.function.Function;
* @param <T> the type of the config item's value * @param <T> the type of the config item's value
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class ConfigItem<T> { public final class ConfigItem<T> {
private final String commandLong, commandShort; private final String commandLong, commandShort;
private final Function<String, T> parseFunction; private final Function<String, T> parseFunction;
private final boolean mandatory;
private T value; private T value;
@ -29,30 +30,12 @@ public class ConfigItem<T> {
* @param commandShort the short command line argument to set this value * @param commandShort the short command line argument to set this value
* @param parseFunction the {@code Function<String, T>} that parses the value * @param parseFunction the {@code Function<String, T>} that parses the value
* from a string * from a string
* @param defaultValue the optional default value to set before parsing
* @param mandatory indicated that this config item must be initialized with
* a non-null value
* @since Envoy Common v0.1-beta
*/
public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction, T defaultValue, boolean mandatory) {
this.commandLong = commandLong;
this.commandShort = commandShort;
this.parseFunction = parseFunction;
this.mandatory = mandatory;
value = defaultValue;
}
/**
* Initializes an optional {@link ConfigItem} without a default value.
*
* @param commandLong the long command line argument to set this value
* @param commandShort the short command line argument to set this value
* @param parseFunction the {@code Function<String, T>} that parses the value
* from a string
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction) { public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction) {
this(commandLong, commandShort, parseFunction, null, false); this.commandLong = commandLong;
this.commandShort = commandShort;
this.parseFunction = parseFunction;
} }
/** /**
@ -84,9 +67,8 @@ public class ConfigItem<T> {
public T get() { return value; } public T get() { return value; }
/** /**
* @return {@code true} if this {@link ConfigItem} is mandatory for successful * @param value the value to set
* application initialization * @since Envoy Common v0.2-beta
* @since Envoy Common v0.1-beta
*/ */
public boolean isMandatory() { return mandatory; } protected void setValue(T value) { this.value = value; }
} }

View File

@ -12,7 +12,7 @@ import java.io.Serializable;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class IDGenerator implements Serializable { public final class IDGenerator implements Serializable {
private final long end; private final long end;
private long current; private long current;

View File

@ -16,13 +16,13 @@ import envoy.data.Message.MessageStatus;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class MessageBuilder { public final class MessageBuilder {
// Mandatory properties without default values // Mandatory properties without default values
private final long senderID, recipientID; private final long senderID, recipientID;
// Properties with default values // Properties with default values
private long id; private final long id;
private Instant creationDate, receivedDate, readDate; private Instant creationDate, receivedDate, readDate;
private String text; private String text;
private Attachment attachment; private Attachment attachment;
@ -69,11 +69,11 @@ public class MessageBuilder {
*/ */
public MessageBuilder(Message msg, long recipientID, IDGenerator iDGenerator) { public MessageBuilder(Message msg, long recipientID, IDGenerator iDGenerator) {
this(msg.getRecipientID(), recipientID, iDGenerator.next()); this(msg.getRecipientID(), recipientID, iDGenerator.next());
this.attachment = msg.getAttachment(); attachment = msg.getAttachment();
this.creationDate = Instant.now(); creationDate = Instant.now();
this.forwarded = true; forwarded = true;
this.text = msg.getText(); text = msg.getText();
this.status = MessageStatus.WAITING; status = MessageStatus.WAITING;
} }
/** /**
@ -128,7 +128,7 @@ public class MessageBuilder {
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public GroupMessage buildGroupMessage(Group group) { public GroupMessage buildGroupMessage(Group group) {
var memberStatuses = new HashMap<Long, Message.MessageStatus>(); final var memberStatuses = new HashMap<Long, Message.MessageStatus>();
group.getContacts().forEach(user -> memberStatuses.put(user.getID(), MessageStatus.WAITING)); group.getContacts().forEach(user -> memberStatuses.put(user.getID(), MessageStatus.WAITING));
return buildGroupMessage(group, memberStatuses); return buildGroupMessage(group, memberStatuses);
} }

View File

@ -17,7 +17,7 @@ import java.util.function.Consumer;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public class EventBus { public final class EventBus {
/** /**
* Contains all event handler instances registered at this event bus as values * Contains all event handler instances registered at this event bus as values

View File

@ -15,7 +15,7 @@ import envoy.data.User;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class GroupCreation extends Event<String> { public final class GroupCreation extends Event<String> {
private final Set<Long> initialMemberIDs; private final Set<Long> initialMemberIDs;

View File

@ -0,0 +1,25 @@
package envoy.event;
/**
* Used to communicate with a client that his request to create a group might
* have been rejected as it might be disabled on his current server.
* <p>
* Project: <strong>common</strong><br>
* File: <strong>GroupCreationResult.java</strong><br>
* Created: <strong>22.08.2020</strong><br>
*
* @author Leon Hofmeister
* @since Envoy Common v0.2-beta
*/
public class GroupCreationResult extends Event<Boolean> {
private static final long serialVersionUID = 1L;
/**
* Creates a new {@code GroupCreationResult}.
*
* @param success whether the GroupCreation sent before was successful
* @since Envoy Common v0.2-beta
*/
public GroupCreationResult(boolean success) { super(success); }
}

View File

@ -13,7 +13,7 @@ import envoy.data.Message.MessageStatus;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class GroupMessageStatusChange extends MessageStatusChange { public final class GroupMessageStatusChange extends MessageStatusChange {
private final long memberID; private final long memberID;

View File

@ -17,7 +17,7 @@ import envoy.data.User;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class GroupResize extends Event<User> { public final class GroupResize extends Event<User> {
private final long groupID; private final long groupID;
private final ElementOperation operation; private final ElementOperation operation;

View File

@ -11,7 +11,7 @@ package envoy.event;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.3-alpha * @since Envoy Common v0.3-alpha
*/ */
public class HandshakeRejection extends Event<String> { public final class HandshakeRejection extends Event<String> {
/** /**
* Select this value if a given password hash or user name was incorrect. * Select this value if a given password hash or user name was incorrect.

View File

@ -11,7 +11,7 @@ package envoy.event;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.3-alpha * @since Envoy Common v0.3-alpha
*/ */
public class IDGeneratorRequest extends Event.Valueless { public final class IDGeneratorRequest extends Event.Valueless {
private static final long serialVersionUID = 1431107413883364583L; private static final long serialVersionUID = 1431107413883364583L;
} }

View File

@ -11,7 +11,7 @@ package envoy.event;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Client v0.2-beta * @since Envoy Client v0.2-beta
*/ */
public class IsTyping extends Event<Long> { public final class IsTyping extends Event<Long> {
private final long destinationID; private final long destinationID;

View File

@ -11,7 +11,7 @@ package envoy.event;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.2-beta * @since Envoy Common v0.2-beta
*/ */
public class IssueProposal extends Event<String> { public final class IssueProposal extends Event<String> {
private final String description; private final String description;
private final boolean bug; private final boolean bug;

View File

@ -14,7 +14,7 @@ import envoy.data.Contact;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class NameChange extends Event<String> { public final class NameChange extends Event<String> {
private final long id; private final long id;

View File

@ -0,0 +1,17 @@
package envoy.event;
/**
* This event is used so that the server can tell the client that attachments
* will be filtered out.
* <p>
* Project: <strong>common</strong><br>
* File: <strong>NoAttachments.java</strong><br>
* Created: <strong>22.08.2020</strong><br>
*
* @author Leon Hofmeister
* @since Envoy Common v0.2-beta
*/
public class NoAttachments extends Event.Valueless {
private static final long serialVersionUID = 1L;
}

View File

@ -10,7 +10,7 @@ import envoy.data.Contact;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.2-beta * @since Envoy Common v0.2-beta
*/ */
public class PasswordChangeRequest extends Event<String> { public final class PasswordChangeRequest extends Event<String> {
private final long id; private final long id;
private final String oldPassword; private final String oldPassword;

View File

@ -11,7 +11,7 @@ package envoy.event;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.2-beta * @since Envoy Common v0.2-beta
*/ */
public class PasswordChangeResult extends Event<Boolean> { public final class PasswordChangeResult extends Event<Boolean> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -8,7 +8,7 @@ package envoy.event;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.2-beta * @since Envoy Common v0.2-beta
*/ */
public class ProfilePicChange extends Event<byte[]> { public final class ProfilePicChange extends Event<byte[]> {
private final long id; private final long id;

View File

@ -11,7 +11,7 @@ import envoy.data.User.UserStatus;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class UserStatusChange extends Event<UserStatus> { public final class UserStatusChange extends Event<UserStatus> {
private final long id; private final long id;

View File

@ -14,7 +14,7 @@ import envoy.event.Event;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class ContactOperation extends Event<Contact> { public final class ContactOperation extends Event<Contact> {
private final ElementOperation operationType; private final ElementOperation operationType;

View File

@ -12,7 +12,7 @@ import envoy.event.Event;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class UserSearchRequest extends Event<String> { public final class UserSearchRequest extends Event<String> {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;

View File

@ -15,7 +15,7 @@ import envoy.event.Event;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class UserSearchResult extends Event<List<User>> { public final class UserSearchResult extends Event<List<User>> {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;

View File

@ -8,7 +8,7 @@ package envoy.exception;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public class EnvoyException extends Exception { public final class EnvoyException extends Exception {
private static final long serialVersionUID = 2096147309395387479L; private static final long serialVersionUID = 2096147309395387479L;

View File

@ -12,7 +12,7 @@ import java.util.regex.Pattern;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class Bounds { public final class Bounds {
private Bounds() {} private Bounds() {}

View File

@ -12,18 +12,15 @@ import envoy.data.Config;
* Configures the {@link java.util.logging} API to output the log into the * Configures the {@link java.util.logging} API to output the log into the
* console and a log file. * console and a log file.
* <p> * <p>
* Call the {@link EnvoyLog#attach(String)} method to configure a part of the
* logger hierarchy.
* <p>
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>EnvoyLogger.java</strong><br> * File: <strong>EnvoyLogger.java</strong><br>
* Created: <strong>14 Dec 2019</strong><br> * Created: <strong>14.12.2019</strong><br>
* *
* @author Leon Hofmeister * @author Leon Hofmeister
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public class EnvoyLog { public final class EnvoyLog {
private static FileHandler fileHandler; private static FileHandler fileHandler;
private static StreamHandler consoleHandler; private static StreamHandler consoleHandler;
@ -32,8 +29,7 @@ public class EnvoyLog {
private EnvoyLog() {} private EnvoyLog() {}
/** /**
* Initializes logging. Call this method before calling the * Initializes logging.
* {@link EnvoyLog#attach(String)} method.
* *
* @param config the config providing the console and log file barriers * @param config the config providing the console and log file barriers
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
@ -45,18 +41,19 @@ public class EnvoyLog {
LogManager.getLogManager().reset(); LogManager.getLogManager().reset();
// Configure log file // Configure log file
final File logFile = new File((File) config.get("homeDirectory").get(), final File logFile = new File(config.getHomeDirectory(),
"log/envoy_user_" + DateTimeFormatter.ofPattern("yyyy-MM-dd--hh-mm-mm").format(LocalDateTime.now()) + ".log"); "log/" + DateTimeFormatter.ofPattern("yyyy-MM-dd--hh-mm").format(LocalDateTime.now()) + ".log");
logFile.getParentFile().mkdirs(); logFile.getParentFile().mkdirs();
// Configure formatting // Configure formatting
// Sample log entry: [2020-06-13 16:50:26] [INFORMATION] [envoy.client.ui.Startup] Closing connection... // Sample log entry: [2020-06-13 16:50:26] [INFORMATION]
// [envoy.client.ui.Startup] Closing connection...
System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] [%3$s] %5$s %6$s%n"); System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] [%3$s] %5$s %6$s%n");
final SimpleFormatter formatter = new SimpleFormatter(); final SimpleFormatter formatter = new SimpleFormatter();
try { try {
fileHandler = new FileHandler(logFile.getAbsolutePath()); fileHandler = new FileHandler(logFile.getAbsolutePath());
fileHandler.setLevel((Level) config.get("fileLevelBarrier").get()); fileHandler.setLevel(config.getFileLevelBarrier());
fileHandler.setFormatter(formatter); fileHandler.setFormatter(formatter);
} catch (SecurityException | IOException e) { } catch (SecurityException | IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -69,10 +66,11 @@ public class EnvoyLog {
flush(); flush();
} }
}; };
consoleHandler.setLevel((Level) config.get("consoleLevelBarrier").get()); consoleHandler.setLevel(config.getConsoleLevelBarrier());
consoleHandler.setFormatter(formatter); consoleHandler.setFormatter(formatter);
initialized = true; initialized = true;
EnvoyLog.attach("envoy");
} }
/** /**
@ -82,7 +80,7 @@ public class EnvoyLog {
* @param path the path to the loggers to configure * @param path the path to the loggers to configure
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public static void attach(String path) { private static void attach(String path) {
if (!initialized) throw new IllegalStateException("EnvoyLog is not initialized"); if (!initialized) throw new IllegalStateException("EnvoyLog is not initialized");
// Get root logger // Get root logger
@ -105,22 +103,4 @@ public class EnvoyLog {
* @since Envoy Common v0.1-beta * @since Envoy Common v0.1-beta
*/ */
public static Logger getLogger(Class<?> logClass) { return Logger.getLogger(logClass.getCanonicalName()); } public static Logger getLogger(Class<?> logClass) { return Logger.getLogger(logClass.getCanonicalName()); }
/**
* Defines the logger level required for a record to be written to the log file.
*
* @param fileLevelBarrier the log file level
* @since Envoy Common v0.1-beta
*/
public static void setFileLevelBarrier(Level fileLevelBarrier) { if (fileHandler != null) fileHandler.setLevel(fileLevelBarrier); }
/**
* Defines the logger level required for a record to be written to the console.
*
* @param consoleLevelBarrier the console logger level
* @since Envoy Common v0.1-beta
*/
public static void setConsoleLevelBarrier(Level consoleLevelBarrier) {
if (consoleHandler != null) consoleHandler.setLevel(consoleLevelBarrier);
}
} }

View File

@ -12,7 +12,7 @@ import java.io.*;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Common v0.2-alpha * @since Envoy Common v0.2-alpha
*/ */
public class SerializationUtils { public final class SerializationUtils {
private SerializationUtils() {} private SerializationUtils() {}

View File

@ -1,16 +1,13 @@
package envoy.server; package envoy.server;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Set; import java.util.Set;
import java.util.logging.Level; import java.util.logging.Level;
import com.jenkov.nioserver.Server; import com.jenkov.nioserver.Server;
import envoy.data.Config;
import envoy.data.ConfigItem;
import envoy.server.data.PersistenceManager; import envoy.server.data.PersistenceManager;
import envoy.server.data.ServerConfig;
import envoy.server.net.ConnectionManager; import envoy.server.net.ConnectionManager;
import envoy.server.net.ObjectMessageProcessor; import envoy.server.net.ObjectMessageProcessor;
import envoy.server.net.ObjectMessageReader; import envoy.server.net.ObjectMessageReader;
@ -27,26 +24,12 @@ import envoy.util.EnvoyLog;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class Startup { public final class Startup {
/** /**
* Initializes the logger with a new config instance. * Stores the configuration used for the whole server
*
* @since Envoy Server Standalone v0.1-beta
*/ */
private static void initLogging() { public static final ServerConfig config = ServerConfig.getInstance();
final var items = new HashMap<String, ConfigItem<?>>();
items.put("homeDirectory",
new ConfigItem<>("homeDirectory", "h", File::new, new File(System.getProperty("user.home"), ".envoy-server"), true));
items.put("fileLevelBarrier", new ConfigItem<>("fileLevelBarrier", "fb", Level::parse, Level.WARNING, true));
items.put("consoleLevelBarrier", new ConfigItem<>("consoleLevelBarrier", "cb", Level::parse, Level.FINEST, true));
final var config = new Config();
config.load(items);
EnvoyLog.initialize(config);
EnvoyLog.attach("envoy");
}
/** /**
* Starts the server. * Starts the server.
@ -57,7 +40,13 @@ public class Startup {
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
initLogging(); try {
config.loadAll(Startup.class, "server.properties", args);
EnvoyLog.initialize(config);
} catch (final IllegalStateException e) {
EnvoyLog.getLogger(Startup.class).log(Level.SEVERE, "Error loading configuration values: ", e);
System.exit(1);
}
final var server = new Server(8080, ObjectMessageReader::new, final var server = new Server(8080, ObjectMessageReader::new,
new ObjectMessageProcessor(Set.of(new LoginCredentialProcessor(), new ObjectMessageProcessor(Set.of(new LoginCredentialProcessor(),
@ -84,8 +73,8 @@ public class Startup {
server.start(); server.start();
server.getSocketProcessor().registerSocketIdListener(ConnectionManager.getInstance()); server.getSocketProcessor().registerSocketIdListener(ConnectionManager.getInstance());
if (args.length == 0 || !args[0].equalsIgnoreCase("no-enter-to-stop")) { if (config.isEnterToStop()) {
System.out.println("Press the return key to stop the server..."); System.out.println("Press Enter to stop the server...");
System.in.read(); System.in.read();
System.out.println("Stopped"); System.out.println("Stopped");
System.exit(0); System.exit(0);

View File

@ -14,7 +14,7 @@ import javax.persistence.Table;
*/ */
@Entity @Entity
@Table(name = "configuration") @Table(name = "configuration")
public class ConfigItem { public final class ConfigItem {
@Id @Id
private String key; private String key;

View File

@ -28,7 +28,7 @@ import javax.persistence.NamedQuery;
query = "SELECT g FROM Group g WHERE g.creationDate > :lastSeen AND :user MEMBER OF g.contacts" query = "SELECT g FROM Group g WHERE g.creationDate > :lastSeen AND :user MEMBER OF g.contacts"
) )
}) })
public class Group extends Contact { public final class Group extends Contact {
/** /**
* Named query retrieving a group by name (parameter {@code :name}). * Named query retrieving a group by name (parameter {@code :name}).

View File

@ -24,7 +24,7 @@ import envoy.data.Group;
+ "OR m.status = envoy.data.Message$MessageStatus.READ AND m.readDate > :lastSeen " + "OR m.status = envoy.data.Message$MessageStatus.READ AND m.readDate > :lastSeen "
+ "OR m.lastStatusChangeDate > :lastSeen)" + "OR m.lastStatusChangeDate > :lastSeen)"
) )
public class GroupMessage extends Message { public final class GroupMessage extends Message {
/** /**
* Named query retrieving pending group messages sent to a group containing a * Named query retrieving pending group messages sent to a group containing a

View File

@ -1,6 +1,7 @@
package envoy.server.data; package envoy.server.data;
import static envoy.data.Message.MessageStatus.*; import static envoy.data.Message.MessageStatus.*;
import static envoy.server.Startup.config;
import java.time.Instant; import java.time.Instant;
@ -104,7 +105,7 @@ public class Message {
sender = persistenceManager.getUserByID(message.getSenderID()); sender = persistenceManager.getUserByID(message.getSenderID());
recipient = persistenceManager.getContactByID(message.getRecipientID()); recipient = persistenceManager.getContactByID(message.getRecipientID());
forwarded = message.isForwarded(); forwarded = message.isForwarded();
if (message.hasAttachment()) { if (config.isAttachmentSupportEnabled() && message.hasAttachment()) {
final var messageAttachment = message.getAttachment(); final var messageAttachment = message.getAttachment();
attachment = messageAttachment.getData(); attachment = messageAttachment.getData();
attachmentName = messageAttachment.getName(); attachmentName = messageAttachment.getName();

View File

@ -19,7 +19,7 @@ import envoy.server.net.ConnectionManager;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class PersistenceManager { public final class PersistenceManager {
private final EntityManager entityManager = Persistence.createEntityManagerFactory("envoy").createEntityManager(); private final EntityManager entityManager = Persistence.createEntityManagerFactory("envoy").createEntityManager();
private final EntityTransaction transaction = entityManager.getTransaction(); private final EntityTransaction transaction = entityManager.getTransaction();

View File

@ -0,0 +1,96 @@
package envoy.server.data;
import static java.util.function.Function.identity;
import envoy.data.Config;
/**
* Project: <strong>server</strong><br>
* File: <strong>ServerConfig.java</strong><br>
* Created: <strong>21.08.2020</strong><br>
*
* @author Leon Hofmeister
* @since Envoy Server v0.2-beta
*/
public final class ServerConfig extends Config {
private static ServerConfig config;
/**
* @return the singleton instance of the server config
* @since Envoy Client v0.1-beta
*/
public static ServerConfig getInstance() { return config == null ? config = new ServerConfig() : config; }
private ServerConfig() {
super(".envoy-server");
put("enter-to-stop", "dev-stop", Boolean::parseBoolean);
// parameters for issue reporting
put("issueCreationURL", "i-url", identity());
put("issueAuthToken", "i-token", identity());
put("userMadeLabel", "l-um", identity());
put("bugLabel", "l-b", identity());
put("featureLabel", "l-f", identity());
// enabling/ disabling several processors
put("enableIssueReporting", "e-ir", Boolean::parseBoolean);
put("enableGroups", "e-g", Boolean::parseBoolean);
put("enableAttachments", "e-a", Boolean::parseBoolean);
}
/**
* @return true if this server should be stoppable by pressing enter
* @since Envoy Server v0.2-beta
*/
public Boolean isEnterToStop() { return (Boolean) items.get("enter-to-stop").get(); }
/**
* @return {@code true} if issue reporting is enabled
* @since Envoy Client v0.3-alpha
*/
public Boolean isIssueReportingEnabled() { return (Boolean) items.get("enableIssueReporting").get(); }
/**
* @return {@code true} if attachment support has been enabled
* @since Envoy Client v0.3-alpha
*/
public Boolean isAttachmentSupportEnabled() { return (Boolean) items.get("enableAttachments").get(); }
/**
* @return {@code true} if group support has been enabled
* @since Envoy Client v0.3-alpha
*/
public Boolean isGroupSupportEnabled() { return (Boolean) items.get("enableGroups").get(); }
/**
* @return the URL where issues should be uploaded to
* @since Envoy Client v0.1-alpha
*/
public String getIssueReportingURL() { return (String) items.get("issueCreationURL").get(); }
/**
* @return the String representation for the "{@code user made}" - label
* @since Envoy Client v0.1-alpha
*/
public String getUserMadeLabel() { return (String) items.get("userMadeLabel").get(); }
/**
* @return the String representation for the "{@code user made}" - label
* @since Envoy Client v0.1-alpha
*/
public String getBugLabel() { return (String) items.get("bugLabel").get(); }
/**
* @return the String representation for the "{@code user made}" - label
* @since Envoy Client v0.1-alpha
*/
public String getFeatureLabel() { return (String) items.get("featureLabel").get(); }
/**
* @return the authorization token used to authenticate to
* {@link ServerConfig#getIssueReportingURL()}. If null,
* authorization is expected to occur via a query_param or via a basic
* user-password-combination
* @since Envoy Server v0.2-beta
*/
public String getIssueAuthToken() { return (String) items.get("issueAuthToken").get(); }
}

View File

@ -36,7 +36,7 @@ import envoy.data.User.UserStatus;
query = "SELECT u FROM User u WHERE (lower(u.name) LIKE lower(:searchPhrase) AND u <> :context AND :context NOT MEMBER OF u.contacts)" query = "SELECT u FROM User u WHERE (lower(u.name) LIKE lower(:searchPhrase) AND u <> :context AND :context NOT MEMBER OF u.contacts)"
) )
}) })
public class User extends Contact { public final class User extends Contact {
/** /**
* Named query retrieving a user by name (parameter {@code :name}). * Named query retrieving a user by name (parameter {@code :name}).

View File

@ -19,7 +19,7 @@ import envoy.server.processors.UserStatusChangeProcessor;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class ConnectionManager implements ISocketIdListener { public final class ConnectionManager implements ISocketIdListener {
/** /**
* Contains all socket IDs that have not yet performed a handshake / acquired * Contains all socket IDs that have not yet performed a handshake / acquired

View File

@ -25,7 +25,7 @@ import envoy.util.EnvoyLog;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class ObjectMessageProcessor implements IMessageProcessor { public final class ObjectMessageProcessor implements IMessageProcessor {
private final Set<ObjectProcessor<?>> processors; private final Set<ObjectProcessor<?>> processors;

View File

@ -19,7 +19,7 @@ import envoy.util.SerializationUtils;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class ObjectMessageReader implements IMessageReader { public final class ObjectMessageReader implements IMessageReader {
private List<Message> completeMessages = new ArrayList<>(); private List<Message> completeMessages = new ArrayList<>();
private Message nextMessage; private Message nextMessage;

View File

@ -22,7 +22,7 @@ import envoy.util.SerializationUtils;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class ObjectWriteProxy { public final class ObjectWriteProxy {
private final WriteProxy writeProxy; private final WriteProxy writeProxy;

View File

@ -17,7 +17,7 @@ import envoy.util.EnvoyLog;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class ContactOperationProcessor implements ObjectProcessor<ContactOperation> { public final class ContactOperationProcessor implements ObjectProcessor<ContactOperation> {
private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
private static final Logger logger = EnvoyLog.getLogger(ContactOperationProcessor.class); private static final Logger logger = EnvoyLog.getLogger(ContactOperationProcessor.class);

View File

@ -1,9 +1,12 @@
package envoy.server.processors; package envoy.server.processors;
import static envoy.server.Startup.config;
import java.util.HashSet; import java.util.HashSet;
import envoy.event.ElementOperation; import envoy.event.ElementOperation;
import envoy.event.GroupCreation; import envoy.event.GroupCreation;
import envoy.event.GroupCreationResult;
import envoy.event.contact.ContactOperation; import envoy.event.contact.ContactOperation;
import envoy.server.data.Contact; import envoy.server.data.Contact;
import envoy.server.data.PersistenceManager; import envoy.server.data.PersistenceManager;
@ -14,18 +17,21 @@ import envoy.server.net.ObjectWriteProxy;
* Project: <strong>envoy-server-standalone</strong><br> * Project: <strong>envoy-server-standalone</strong><br>
* File: <strong>GroupCreationProcessor.java</strong><br> * File: <strong>GroupCreationProcessor.java</strong><br>
* Created: <strong>26.03.2020</strong><br> * Created: <strong>26.03.2020</strong><br>
* *
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-beta * @since Envoy Server Standalone v0.1-beta
*/ */
public class GroupCreationProcessor implements ObjectProcessor<GroupCreation> { public final class GroupCreationProcessor implements ObjectProcessor<GroupCreation> {
private final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private final PersistenceManager persistenceManager = PersistenceManager.getInstance();
private final ConnectionManager connectionManager = ConnectionManager.getInstance(); private final ConnectionManager connectionManager = ConnectionManager.getInstance();
@Override @Override
public void process(GroupCreation groupCreation, long socketID, ObjectWriteProxy writeProxy) { public void process(GroupCreation groupCreation, long socketID, ObjectWriteProxy writeProxy) {
envoy.server.data.Group group = new envoy.server.data.Group(); // Don't allow the creation of groups if manually disabled
writeProxy.write(socketID, new GroupCreationResult(config.isGroupSupportEnabled()));
if (!config.isGroupSupportEnabled()) return;
final envoy.server.data.Group group = new envoy.server.data.Group();
group.setName(groupCreation.get()); group.setName(groupCreation.get());
group.setContacts(new HashSet<>()); group.setContacts(new HashSet<>());
groupCreation.getInitialMemberIDs().stream().map(persistenceManager::getUserByID).forEach(group.getContacts()::add); groupCreation.getInitialMemberIDs().stream().map(persistenceManager::getUserByID).forEach(group.getContacts()::add);

View File

@ -1,64 +1,78 @@
package envoy.server.processors; package envoy.server.processors;
import static envoy.data.Message.MessageStatus.*; import static envoy.data.Message.MessageStatus.*;
import static envoy.server.Startup.config;
import java.time.Instant;
import java.util.Collections; import java.time.Instant;
import java.util.logging.Logger; import java.util.Collections;
import java.util.logging.Logger;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityExistsException;
import envoy.data.GroupMessage;
import envoy.event.MessageStatusChange; import envoy.data.GroupMessage;
import envoy.server.data.PersistenceManager; import envoy.event.MessageStatusChange;
import envoy.server.net.ConnectionManager; import envoy.event.NoAttachments;
import envoy.server.net.ObjectWriteProxy; import envoy.server.data.PersistenceManager;
import envoy.util.EnvoyLog; import envoy.server.net.ConnectionManager;
import envoy.server.net.ObjectWriteProxy;
/** import envoy.util.EnvoyLog;
* Project: <strong>envoy-server-standalone</strong><br>
* File: <strong>GroupMessageProcessor.java</strong><br> /**
* Created: <strong>18.04.2020</strong><br> * Project: <strong>envoy-server-standalone</strong><br>
* * File: <strong>GroupMessageProcessor.java</strong><br>
* @author Maximilian K&auml;fer * Created: <strong>18.04.2020</strong><br>
* @since Envoy Server Standalone v0.1-beta *
*/ * @author Maximilian K&auml;fer
public class GroupMessageProcessor implements ObjectProcessor<GroupMessage> { * @since Envoy Server Standalone v0.1-beta
*/
private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); public final class GroupMessageProcessor implements ObjectProcessor<GroupMessage> {
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();
private static final Logger logger = EnvoyLog.getLogger(GroupCreationProcessor.class); private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();
@Override private static final Logger logger = EnvoyLog.getLogger(GroupCreationProcessor.class);
public void process(GroupMessage groupMessage, long socketID, ObjectWriteProxy writeProxy) {
groupMessage.nextStatus(); @Override
public void process(GroupMessage groupMessage, long socketID, ObjectWriteProxy writeProxy) {
// Update statuses to SENT / RECEIVED depending on online status groupMessage.nextStatus();
groupMessage.getMemberStatuses().replaceAll((memberID, status) -> connectionManager.isOnline(memberID) ? RECEIVED : SENT);
// Update statuses to SENT / RECEIVED depending on online status
// Set status for sender to READ groupMessage.getMemberStatuses().replaceAll((memberID, status) -> connectionManager.isOnline(memberID) ? RECEIVED : SENT);
groupMessage.getMemberStatuses().replace(groupMessage.getSenderID(), READ);
// Set status for sender to READ
// Increment the overall status to RECEIVED if necessary groupMessage.getMemberStatuses().replace(groupMessage.getSenderID(), READ);
if (Collections.min(groupMessage.getMemberStatuses().values()) == RECEIVED) {
groupMessage.nextStatus(); // Increment the overall status to RECEIVED if necessary
if (Collections.min(groupMessage.getMemberStatuses().values()) == RECEIVED) {
// Notify the sender of the status change groupMessage.nextStatus();
writeProxy.write(socketID, new MessageStatusChange(groupMessage));
} // Notify the sender of the status change
writeProxy.write(socketID, new MessageStatusChange(groupMessage));
// Deliver the message to the recipients that are online }
writeProxy.writeToOnlineContacts(
persistenceManager.getGroupByID(groupMessage.getRecipientID()) // message attachment will be automatically removed if disabled in config
.getContacts() final var groupMessageServer = new envoy.server.data.GroupMessage(groupMessage, Instant.now());
.stream() // Telling the server to reload the message without the attachment and telling
.filter(c -> c.getID() != groupMessage.getSenderID()), // the client not to send anymore attachments
groupMessage); if (!config.isAttachmentSupportEnabled() && groupMessage.hasAttachment()) {
groupMessage = groupMessageServer.toCommon();
try { writeProxy.write(socketID, new NoAttachments());
PersistenceManager.getInstance().addMessage(new envoy.server.data.GroupMessage(groupMessage, Instant.now())); }
} catch (EntityExistsException e) {
logger.warning("Received a groupMessage with an ID that already exists"); // This is needed unfortunately because of f***ing lambda restrictions ("must be
} // fINaL oR EFfEcTivELy FiNAl")
} final var groupMessageCopy = groupMessage;
} // Deliver the message to the recipients that are online
writeProxy.writeToOnlineContacts(
persistenceManager.getGroupByID(groupMessageCopy.getRecipientID())
.getContacts()
.stream()
.filter(c -> c.getID() != groupMessageCopy.getSenderID()),
groupMessageCopy);
try {
PersistenceManager.getInstance().addMessage(groupMessageServer);
} catch (final EntityExistsException e) {
logger.warning("Received a groupMessage with an ID that already exists");
}
}
}

View File

@ -24,7 +24,7 @@ import envoy.util.EnvoyLog;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-beta * @since Envoy Server Standalone v0.1-beta
*/ */
public class GroupMessageStatusChangeProcessor implements ObjectProcessor<GroupMessageStatusChange> { public final class GroupMessageStatusChangeProcessor implements ObjectProcessor<GroupMessageStatusChange> {
private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();

View File

@ -14,7 +14,7 @@ import envoy.server.net.ObjectWriteProxy;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-beta * @since Envoy Server Standalone v0.1-beta
*/ */
public class GroupResizeProcessor implements ObjectProcessor<GroupResize> { public final class GroupResizeProcessor implements ObjectProcessor<GroupResize> {
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();
private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); private static final ConnectionManager connectionManager = ConnectionManager.getInstance();

View File

@ -17,7 +17,7 @@ import envoy.server.net.ObjectWriteProxy;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class IDGeneratorRequestProcessor implements ObjectProcessor<IDGeneratorRequest> { public final class IDGeneratorRequestProcessor implements ObjectProcessor<IDGeneratorRequest> {
private static final long ID_RANGE = 200; private static final long ID_RANGE = 200;

View File

@ -18,7 +18,7 @@ import envoy.server.net.ObjectWriteProxy;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server v0.2-beta * @since Envoy Server v0.2-beta
*/ */
public class IsTypingProcessor implements ObjectProcessor<IsTyping> { public final class IsTypingProcessor implements ObjectProcessor<IsTyping> {
private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();

View File

@ -1,5 +1,7 @@
package envoy.server.processors; package envoy.server.processors;
import static envoy.server.Startup.config;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
@ -21,29 +23,34 @@ import envoy.util.EnvoyLog;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server v0.2-beta * @since Envoy Server v0.2-beta
*/ */
public class IssueProposalProcessor implements ObjectProcessor<IssueProposal> { public final class IssueProposalProcessor implements ObjectProcessor<IssueProposal> {
private static boolean issueReportingEnabled = true; private static final Logger logger = EnvoyLog.getLogger(IssueProposalProcessor.class);
private static final Logger logger = EnvoyLog.getLogger(IssueProposalProcessor.class);
@Override @Override
public void process(IssueProposal issueProposal, long socketID, ObjectWriteProxy writeProxy) throws IOException { public void process(IssueProposal issueProposal, long socketID, ObjectWriteProxy writeProxy) throws IOException {
// Do nothing if manually disabled // Do nothing if manually disabled
if (!issueReportingEnabled) return; if (!config.isIssueReportingEnabled()) return;
try { try {
final var url = new URL( final var url = new URL(config.getIssueReportingURL());
"https://git.kske.dev/api/v1/repos/zdm/envoy/issues?access_token=6d8ec2a72d64cbaf6319434aa2e7caf0130701b3");
final var connection = (HttpURLConnection) url.openConnection(); final var connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8"); connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept", "application/json");
// Two types of authorization are currently supported: access token as
// query param or access token as authorization header
final var authenticationToken = config.getIssueAuthToken();
if (authenticationToken != null) {
final String auth = "token " + authenticationToken;
connection.setRequestProperty("Authorization", auth);
}
connection.setDoOutput(true); connection.setDoOutput(true);
final var json = String.format("{\"title\":\"%s\",\"body\":\"%s\",\"labels\":[240, %d]}", final var json = String.format("{\"title\":\"%s\",\"body\":\"%s\",\"labels\":[%s, %s]}",
issueProposal.get(), issueProposal.get(),
issueProposal.getDescription(), issueProposal.getDescription(),
// Label 240 should be user-made, label 117 bug and label 119 feature config.getUserMadeLabel(),
issueProposal.isBug() ? 117 : 119); issueProposal.isBug() ? config.getBugLabel() : config.getFeatureLabel());
try (final var os = connection.getOutputStream()) { try (final var os = connection.getOutputStream()) {
final byte[] input = json.getBytes("utf-8"); final byte[] input = json.getBytes("utf-8");
os.write(input, 0, input.length); os.write(input, 0, input.length);
@ -51,29 +58,9 @@ public class IssueProposalProcessor implements ObjectProcessor<IssueProposal> {
final var status = connection.getResponseCode(); final var status = connection.getResponseCode();
if (status == 201) logger.log(Level.INFO, "Successfully created an issue"); if (status == 201) logger.log(Level.INFO, "Successfully created an issue");
else logger.log(Level.WARNING, else logger.log(Level.WARNING,
String.format("Tried creating an issue for %s but received status code %d - Request params:title=%s,description=%s,json=%s", String.format("Tried creating an issue for %s but received status code %d - Request params:%s", url, status, json));
url,
status,
issueProposal.get(),
issueProposal.getDescription(),
json));
} catch (final IOException e) { } catch (final IOException e) {
logger.log(Level.WARNING, "An error occurred while creating an issue: ", e); logger.log(Level.WARNING, "An error occurred while creating an issue: ", e);
} }
} }
/**
* @return whether issue reporting is enabled
* @since Envoy Server v0.2-beta
*/
public static boolean isIssueReportingEnabled() { return issueReportingEnabled; }
/**
* @param issueReportingEnabled whether issue reporting should be enabled - true
* by default
* @since Envoy Server v0.2-beta
*/
public static void setIssueReportingEnabled(boolean issueReportingEnabled) {
IssueProposalProcessor.issueReportingEnabled = issueReportingEnabled;
}
} }

View File

@ -1,5 +1,7 @@
package envoy.server.processors; package envoy.server.processors;
import static envoy.server.Startup.config;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -7,6 +9,7 @@ import javax.persistence.EntityExistsException;
import envoy.data.Message; import envoy.data.Message;
import envoy.event.MessageStatusChange; import envoy.event.MessageStatusChange;
import envoy.event.NoAttachments;
import envoy.server.data.PersistenceManager; import envoy.server.data.PersistenceManager;
import envoy.server.net.ConnectionManager; import envoy.server.net.ConnectionManager;
import envoy.server.net.ObjectWriteProxy; import envoy.server.net.ObjectWriteProxy;
@ -23,7 +26,7 @@ import envoy.util.EnvoyLog;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class MessageProcessor implements ObjectProcessor<Message> { public final class MessageProcessor implements ObjectProcessor<Message> {
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();
private static final ConnectionManager connectionManager = ConnectionManager.getInstance(); private static final ConnectionManager connectionManager = ConnectionManager.getInstance();
@ -35,6 +38,11 @@ public class MessageProcessor implements ObjectProcessor<Message> {
// Convert to server message // Convert to server message
final var serverMessage = new envoy.server.data.Message(message); final var serverMessage = new envoy.server.data.Message(message);
// Telling the server to reload the message without the attachment
if (!config.isAttachmentSupportEnabled() && message.hasAttachment()) {
message = serverMessage.toCommon();
writeProxy.write(socketID, new NoAttachments());
}
try { try {
@ -54,7 +62,7 @@ public class MessageProcessor implements ObjectProcessor<Message> {
// Note that the exact time stamp might differ slightly // Note that the exact time stamp might differ slightly
writeProxy.write(socketID, new MessageStatusChange(message)); writeProxy.write(socketID, new MessageStatusChange(message));
} }
} catch (EntityExistsException e) { } catch (final EntityExistsException e) {
logger.log(Level.WARNING, "Received " + message + " with an ID that already exists!"); logger.log(Level.WARNING, "Received " + message + " with an ID that already exists!");
} }
} }

View File

@ -19,7 +19,7 @@ import envoy.util.EnvoyLog;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class MessageStatusChangeProcessor implements ObjectProcessor<MessageStatusChange> { public final class MessageStatusChangeProcessor implements ObjectProcessor<MessageStatusChange> {
private final ConnectionManager connectionManager = ConnectionManager.getInstance(); private final ConnectionManager connectionManager = ConnectionManager.getInstance();
private final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private final PersistenceManager persistenceManager = PersistenceManager.getInstance();

View File

@ -15,7 +15,7 @@ import envoy.server.net.ObjectWriteProxy;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server Standalone v0.1-beta * @since Envoy Server Standalone v0.1-beta
*/ */
public class NameChangeProcessor implements ObjectProcessor<NameChange> { public final class NameChangeProcessor implements ObjectProcessor<NameChange> {
private static final PersistenceManager persistenceManager = PersistenceManager.getInstance(); private static final PersistenceManager persistenceManager = PersistenceManager.getInstance();

View File

@ -18,7 +18,7 @@ import envoy.util.EnvoyLog;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server v0.2-beta * @since Envoy Server v0.2-beta
*/ */
public class PasswordChangeRequestProcessor implements ObjectProcessor<PasswordChangeRequest> { public final class PasswordChangeRequestProcessor implements ObjectProcessor<PasswordChangeRequest> {
@Override @Override
public void process(PasswordChangeRequest event, long socketID, ObjectWriteProxy writeProxy) throws IOException { public void process(PasswordChangeRequest event, long socketID, ObjectWriteProxy writeProxy) throws IOException {

View File

@ -13,7 +13,7 @@ import envoy.server.net.ObjectWriteProxy;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server v0.2-beta * @since Envoy Server v0.2-beta
*/ */
public class ProfilePicChangeProcessor implements ObjectProcessor<ProfilePicChange> { public final class ProfilePicChangeProcessor implements ObjectProcessor<ProfilePicChange> {
@Override @Override
public void process(ProfilePicChange event, long socketID, ObjectWriteProxy writeProxy) throws IOException {} public void process(ProfilePicChange event, long socketID, ObjectWriteProxy writeProxy) throws IOException {}

View File

@ -20,7 +20,7 @@ import envoy.server.net.ObjectWriteProxy;
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class UserSearchProcessor implements ObjectProcessor<UserSearchRequest> { public final class UserSearchProcessor implements ObjectProcessor<UserSearchRequest> {
/** /**
* Writes a list of contacts to the client containing all {@link Contact}s * Writes a list of contacts to the client containing all {@link Contact}s

View File

@ -19,7 +19,7 @@ import envoy.util.EnvoyLog;
* @author Leon Hofmeister * @author Leon Hofmeister
* @since Envoy Server Standalone v0.1-alpha * @since Envoy Server Standalone v0.1-alpha
*/ */
public class UserStatusChangeProcessor implements ObjectProcessor<UserStatusChange> { public final class UserStatusChangeProcessor implements ObjectProcessor<UserStatusChange> {
private static ObjectWriteProxy writeProxy; private static ObjectWriteProxy writeProxy;

View File

@ -19,7 +19,7 @@ import javax.crypto.spec.PBEKeySpec;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-beta * @since Envoy Server Standalone v0.1-beta
*/ */
public class PasswordUtil { public final class PasswordUtil {
private static final int ITERATIONS = 1000; private static final int ITERATIONS = 1000;
private static final int KEY_LENGTH = 64 * 8; private static final int KEY_LENGTH = 64 * 8;

View File

@ -13,7 +13,7 @@ import java.util.regex.Pattern;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-beta * @since Envoy Server Standalone v0.1-beta
*/ */
public class VersionUtil { public final class VersionUtil {
/** /**
* The minimal client version compatible with this server. * The minimal client version compatible with this server.

View File

@ -0,0 +1,16 @@
enter-to-stop=true
enableAttachments=true
enableGroups=true
enableIssueReporting=true
# git.kske.dev config
issueCreationURL=https://git.kske.dev/api/v1/repos/zdm/envoy/issues?access_token=6d8ec2a72d64cbaf6319434aa2e7caf0130701b3
userMadeLabel=240
bugLabel=117
featureLabel=119
# api.github.com config - supply an additional auth token
#issueCreationURL=https://api.github.com/repos/informatik-ag-ngl/envoy/issues
#userMadeLabel="user made"
#bugLabel="bug"
#featureLabel="feature"
consoleLevelBarrier=FINEST
fileLevelBarrier=WARNING