Here is a simple app that i am trying to implement in java. my goal is to write a program that can convert ASCII to Binary and back.
Questions:
- Am i violating any OOP Rule.
- Is my code readable ?
- How can i make it more efficient ?
- Anything that want to suggest.
Code:
public class FXMLDocumentController implements Initializable {
@FXML
TextArea asciiTextArea;
@FXML
TextArea binaryTextArea;
@FXML
StackPane animationPane;
private static final int AMOUNT_OF_BITS = 8;
@FXML
private void handleBinaryToText(ActionEvent event) {
Callable<String> task = () -> binaryToAscii(binaryTextArea.getText());
try {
runTask(task, asciiTextArea);
} catch (InterruptedException | ExecutionException ex) {
asciiTextArea.setText(ex.toString());
}
}
@FXML
private void handleTextToBinary(ActionEvent event) {
Callable<String> task = () -> asciiToBinary(asciiTextArea.getText());
try {
runTask(task, binaryTextArea);
} catch (InterruptedException | ExecutionException ex) {
binaryTextArea.setText(ex.toString());
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
//Validate the Binary TextArea
final Pattern binaryRegex = Pattern.compile("\\A[01\\n]*\\Z");
Predicate<String> tester = binaryRegex.asPredicate();
binaryTextArea.setTextFormatter(new TextFormatter<>(change -> {
if (!tester.test(change.getControlNewText())) {
return null;
}
return change;
}));
//binaryTextArea.setTextFormatter();
}
// Create the Binary To Text Task task
private String binaryToAscii(final String input) {
if (input.length() % AMOUNT_OF_BITS != 0) {
String msg = "Input must be a multiple of " + AMOUNT_OF_BITS;
binaryTextArea.setText(msg);
throw new IllegalArgumentException(msg);
}
final int INPUT_LEN = input.length();
final int BUILDER_SIZE = INPUT_LEN / 8;
StringBuilder result = new StringBuilder(BUILDER_SIZE);
for (int i = 0; i < INPUT_LEN; i += AMOUNT_OF_BITS) {
char charCode = (char) Integer.parseInt(input.substring(i, i + AMOUNT_OF_BITS), 2);
result.append(charCode);
}
return result.toString();
}
// Create the Binary To Text Task
private String asciiToBinary(String text) {
final byte[] bytes = text.getBytes();
StringBuilder result = new StringBuilder(bytes.length * 8);
for (byte b : bytes) {
int val = b;
for (int i = 0; i < AMOUNT_OF_BITS; i++) {
result.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
}
return result.toString();
}
private void runTask(Callable<String> task, TextArea textArea) throws InterruptedException, ExecutionException {
ExecutorService thread = Executors.newFixedThreadPool(1);
final String result = thread.submit(task).get();
Platform.runLater(() -> {
textArea.setText(result);
});
thread.shutdown();
}
}