Skip to content

Commit

Permalink
New feature: PDF transfer
Browse files Browse the repository at this point in the history
  • Loading branch information
ThePurpleJedi committed Feb 25, 2022
1 parent 2dfa180 commit 633c2b0
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 36 deletions.
18 changes: 9 additions & 9 deletions .idea/sonarlint/issuestore/index.pb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/com/mercurys/encryption/Key.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

public class Key {
private static final int FRAGMENT_LENGTH = 8;
private final int numberOfFragments;
private int numberOfFragments;
private char[] keyValue;

public Key(int keyLength) {
keyValue = new char[keyLength];
numberOfFragments = keyLength / FRAGMENT_LENGTH;
}

public Key() {
}

public void setKey(char[] key) {
if (this.isAlreadyAssigned()) {
this.keyValue = key;
Expand Down
10 changes: 7 additions & 3 deletions src/com/mercurys/handlers/ImageHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public ImageHandler(DataInputStream inputStream) {
this.inputStream = inputStream;
}

public void sendImageFileAsByteStream(final String imageFileName) throws IOException {
public void sendImageFile(final String imageFileName) throws IOException {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedImage bufferedImage = ImageIO.read(new File(imageFileName));

Expand All @@ -46,10 +46,14 @@ public BufferedImage getImageAsBufferedImage() {
}

private byte[] getImageAsBytes() throws IOException {
return readImageSize(ByteBuffer.wrap(readImageSize(4)).asIntBuffer().get());
return readByteArrayFromInputStream(getImageSize());
}

private byte[] readImageSize(int x) throws IOException {
private int getImageSize() throws IOException {
return ByteBuffer.wrap(readByteArrayFromInputStream(4)).asIntBuffer().get();
}

private byte[] readByteArrayFromInputStream(int x) throws IOException {
final byte[] imgSize = new byte[x];
this.inputStream.readFully(imgSize);
return imgSize;
Expand Down
20 changes: 14 additions & 6 deletions src/com/mercurys/handlers/MessageHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,25 @@ public void sendMessagesToOtherUser() throws IOException {
}

public void sendMessage(String outGoingLine) throws IOException {
if (outGoingLine.startsWith("/image")) {
this.handleImageUpload(outGoingLine.substring(7));
} else {
writer.println(encryption.encrypt(outGoingLine));
switch (outGoingLine.split(" +")[0]) {
case "/image" -> this.handleImageUpload(outGoingLine.substring(7));
case "/pdf" -> this.handlePDFUpload(outGoingLine.substring(5));

default -> writer.println(encryption.encrypt(outGoingLine));
}
}

private void handlePDFUpload(String pdfFileName) {
PDFHandler pdfHandler = new PDFHandler(outputStream);
writer.println("/pdf");
pdfHandler.sendPDFFile(pdfFileName);
System.out.println("[M. Console]: PDF sent!");
}

private void handleImageUpload(final String imageFileName) throws IOException {
ImageHandler imageHandler = new ImageHandler(outputStream);
writer.println(new Encryption().encrypt("/image incoming!"));
imageHandler.sendImageFileAsByteStream(imageFileName);
writer.println("/image");
imageHandler.sendImageFile(imageFileName);
System.out.println("[M. Console]: Image sent!");
}
}
95 changes: 95 additions & 0 deletions src/com/mercurys/handlers/PDFHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package com.mercurys.handlers;

import java.io.*;
import java.nio.file.*;
import java.text.*;
import java.util.Calendar;

public class PDFHandler {

private DataInputStream inputStream;
private DataOutputStream outputStream;
private String pdfDownloadPath;

public PDFHandler(DataOutputStream outputStream) {
this.outputStream = outputStream;
}

public PDFHandler(DataInputStream inputStream) {
this.inputStream = inputStream;
}

public static void main(String[] args) {
try {
PDFHandler printerOfPDFs = new PDFHandler(new DataOutputStream(new FileOutputStream(
"/home/raghav/Documents/Java/Testing.txt")));
PDFHandler downloaderOfPDFS = new PDFHandler(new DataInputStream(new FileInputStream(
"/home/raghav/Documents/Java/Testing.txt")));

printerOfPDFs.sendPDFFile(
"/home/raghav/Documents/Books/Non Fiction/Plane-Trigonometry-Part-I.pdf");
System.out.println("PDF read and printed to output");
downloaderOfPDFS.downloadPDF();
System.out.println("PDF downloaded");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}

public void sendPDFFile(final String pdfFileName) {
try {
this.outputStream.writeInt(getPDFAsByteArray(pdfFileName).length);
this.outputStream.write(getPDFAsByteArray(pdfFileName));
} catch (IOException e) {
e.printStackTrace();
}
}

private byte[] getPDFAsByteArray(String fileName) throws IOException {
Path pathToPDF = Paths.get(fileName);
return Files.readAllBytes(pathToPDF);
}

public void downloadPDF() {
try {
byte[] fileToDownload = readPDFByteArray();
pdfDownloadPath = setDownloadLocation();
writePDFToDownloadLocation(fileToDownload);
} catch (IOException e) {
e.printStackTrace();
}
}

private byte[] readPDFByteArray() throws IOException {
byte[] pdfAsBytes = new byte[inputStream.readInt()];
inputStream.readFully(pdfAsBytes);
return pdfAsBytes;
}

private void writePDFToDownloadLocation(byte[] fileAsByteArray) throws IOException {
createDirectoriesToDownloadLocation();
Path pathToFile = Paths.get(pdfDownloadPath);
Files.write(pathToFile, fileAsByteArray);
}

private void createDirectoriesToDownloadLocation() throws IOException {
String s = System.getProperty("file.separator");
Files.createDirectories(Paths.get(
pdfDownloadPath.substring(0, pdfDownloadPath.lastIndexOf(s)) + s));
}

private String setDownloadLocation() {
final String s = System.getProperty("file.separator");
return MessageFormat.format("{0}{1}Documents{1}Mercurys{1}ReceivedFile{2}.pdf",
System.getProperty("user.home"), s, getFormattedSimpleDate());
}

private String getFormattedSimpleDate() {
return new SimpleDateFormat("ddMMyyyy-HHmmss").format(Calendar.getInstance().getTime());
}

public String getPdfDownloadPath() {
return pdfDownloadPath;
}
}
60 changes: 43 additions & 17 deletions src/com/mercurys/readers/MediaReaderThread.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.mercurys.readers;

import com.mercurys.encryption.*;
import com.mercurys.handlers.ImageHandler;
import com.mercurys.handlers.*;

import java.awt.image.BufferedImage;
import java.io.*;
Expand Down Expand Up @@ -45,37 +45,63 @@ private void readAndPrintMessages() throws IOException {
String inBoundLine;
while ((inBoundLine = reader.readLine()) != null) {
if (inBoundLine.equals("-x-")) return;
if (isImage(inBoundLine)) {
downloadIncomingImage();
} else if (isValidEncryptedTextMessage(inBoundLine)) {
System.out.println(this.sentBy + ": " + decryption.decrypt(inBoundLine));
} else {
System.out.println("Invalid Message Format");
}
handleIncomingMessage(inBoundLine);
}
}

private void handleIncomingMessage(String inBoundLine) {
if (isValidEncryptedTextMessage(inBoundLine)) {
printMessage(inBoundLine);
} else if (inBoundLine.startsWith("/")) {
handleFileTransferCommand(inBoundLine);
}
}

private boolean isImage(String inBoundLine) {
return decryption.decrypt(inBoundLine).startsWith("/image");
private void printMessage(String inBoundLine) {
System.out.println(this.sentBy + ": " + decryption.decrypt(inBoundLine));
}

private boolean isValidEncryptedTextMessage(String inBoundLine) {
return new Key(88).getKeyFromMessage(inBoundLine.split(" +")).length() == 88;
}

private void handleFileTransferCommand(String inBoundLine) {
switch (getFileType(inBoundLine)) {
case "/image" -> this.downloadIncomingImage();
case "/pdf" -> this.downloadIncomingPDF();
case "Woops" -> System.out.println("woops");
default -> System.out.println("Unknown command!");
}
}

private String getFileType(String inBoundLine) {
return (!inBoundLine.isBlank())? inBoundLine.split(" +")[0] : "Woops";
}

private void downloadIncomingImage() {
notifyUserOfFileReading("image");
ImageHandler imageHandler = new ImageHandler(inputStream);
notifyUserOfImageReading();
final BufferedImage image = imageHandler.getImageAsBufferedImage();
imageHandler.downloadBufferedImage(image);
BufferedImage bufferedImage = imageHandler.getImageAsBufferedImage();
imageHandler.downloadBufferedImage(bufferedImage);
notifyUserOfDownloadLocation(imageHandler.getImageDownloadPath());
}

private void notifyUserOfDownloadLocation(String downloadPath) {
System.out.println("[M. Console]: The image file has been downloaded as "
+ imageHandler.getImageDownloadPath());
+ downloadPath);
}

private void notifyUserOfImageReading() {
private void notifyUserOfFileReading(String fileType) {
System.out.println("[M. Console]: Attention! " +
"The user at the other end is attempting to send you an image file.");
System.out.println("[M. Console]: Reading image file...");
"The other user is uploading a file of type " + fileType);
System.out.println("[M. Console]: Reading file...");
}

private void downloadIncomingPDF() {
PDFHandler pdfHandler = new PDFHandler(inputStream);
notifyUserOfFileReading("PDF");
pdfHandler.downloadPDF();
notifyUserOfDownloadLocation(pdfHandler.getPdfDownloadPath());
}

public void exitThread() {
Expand Down

0 comments on commit 633c2b0

Please sign in to comment.