programmieren-projekt/src/SocketPackage.java

109 lines
2.5 KiB
Java

import java.util.Arrays;
import java.util.List;
/**
* @author Luca Conte
*/
public class SocketPackage {
private String name = "";
private String data = "";
/**
* initialises a socket package by prividing a package name and data
* @param name the name of the package
* @param data the data of the package
* @author Luca Conte
*/
public SocketPackage(String name, String data) {
this.setName(name);
this.setData(data);
}
/**
* initialises an empty socket package
* @author Luca Conte
*/
public SocketPackage() {
this("","");
}
/**
* initialises a socket package from a message
* the message is parsed according to https://github.com/lgc-4/ProgProjekt-Netzwerkstandard
* @param message the message to be parsed
* @author Luca Conte
*/
public SocketPackage(String message) {
if (message.length() <= 0) {
throw new IllegalArgumentException("Socket message cannot be empty.");
}
String[] components = message.split(" ");
this.setName(components[0]);
if (components.length > 1) {
this.setData(message.substring(components[0].length() + 1));
} else {
this.setData("");
}
}
/**
* sets the package name
* the name is always stored in upper case
* @param name the new name of the package
* @author Luca Conte
*/
public void setName(String name) {
if (name == null) name = "";
this.name = name.toUpperCase();
}
/**
* sets the package data
* @param name the new data of the package
* @author Luca Conte
*/
public void setData(String data) {
if (data == null) data = "";
this.data = data;
}
/**
* returns the name of the package
* @return the name of the package
* @author Luca Conte
*/
public String getName() {
return this.name;
}
/**
* returns the data of the package
* @return the data of the package
* @author Luca Conte
*/
public String getData() {
return this.data;
}
/**
* parses the package into a string according to https://github.com/lgc-4/ProgProjekt-Netzwerkstandard
* the package name and data are joined using a space " " `0x20`
* @return the package in string format
*/
public String toString() {
if (this.data == null || this.data.length() == 0) {
return this.name;
} else {
return this.name + " " + this.data;
}
}
/**
* returns the data string as a list, split at every space " " `0x20`
* @return the data string as a list, split at every space " " `0x20`
* @author Luca Conte
*/
public List<String> splitData() {
return Arrays.asList(this.data.split(" "));
}
}