Skip to content

Commit

Permalink
Added separate ImageHandler class
Browse files Browse the repository at this point in the history
  • Loading branch information
ThePurpleJedi committed Feb 13, 2022
1 parent 6209a9d commit 5d3c7c4
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 78 deletions.
4 changes: 0 additions & 4 deletions .idea/sonarlint/issuestore/index.pb

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

3 changes: 0 additions & 3 deletions out/.gitignore

This file was deleted.

8 changes: 8 additions & 0 deletions project-mercurys.iml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/2" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/4" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/5" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/6" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/9" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/c" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/d" />
<excludeFolder url="file://$MODULE_DIR$/.idea/sonarlint/issuestore/e" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
Expand Down
48 changes: 8 additions & 40 deletions src/com/mercurys/threads/ReadMediaThread.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
package com.mercurys.threads;

import com.mercurys.encryption.Decryption;
import com.mercurys.unfinished.MImageHandler;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.file.*;
import java.text.*;
import java.util.Calendar;

public class ReadMediaThread extends Thread {

Expand All @@ -35,7 +31,6 @@ public void run() {
if (this.exit) {
this.interrupt();
}

this.readAndPrintMessages(reader);
this.exitThread();

Expand All @@ -54,49 +49,22 @@ private void readAndPrintMessages(final BufferedReader reader) throws IOExceptio
if (inBoundLine == null) {
break;
} else if (decryption.decrypt(inBoundLine).startsWith("/image")) {
final BufferedImage image = this.getImageAsBufferedImage();
this.downloadBufferedImage(image);
downloadIncomingImage();
} else if (decryption.getKeyFromMessage(inBoundLine.split(" +")).length() == 88) {
System.out.println(this.sentBy + ": " + this.decryption.decrypt(inBoundLine));
}
}
}

private void downloadBufferedImage(final BufferedImage image) {
if (image == null) {
return;
}
final String s = System.getProperty("file.separator");
final String downloadPath =
MessageFormat.format("{0}{1}Pictures{1}Mercurys{1}{3}{1}ReceivedImage{2}.png",
System.getProperty("user.home"), s, new SimpleDateFormat("HHmmss")
.format(Calendar.getInstance().getTime()), new SimpleDateFormat("dd.MM.yyyy")
.format(Calendar.getInstance().getTime()));
try {
Files.createDirectories(Paths.get(downloadPath.substring(0, downloadPath.lastIndexOf(s)) + s));
ImageIO.write(image, "png", new File(downloadPath));
} catch (final IOException e) {
e.printStackTrace();
}
System.out.println("[M. Console]: The image file has been downloaded as " + downloadPath);
}

private BufferedImage getImageAsBufferedImage() {
private void downloadIncomingImage() {
MImageHandler imageHandler = new MImageHandler(inputStream);
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...");
try {
final byte[] imgSize = new byte[4];
this.inputStream.readFully(imgSize);
final byte[] imgArr = new byte[ByteBuffer.wrap(imgSize).asIntBuffer().get()];
this.inputStream.readFully(imgArr);
return ImageIO.read(new ByteArrayInputStream(imgArr));

} catch (final IOException e) {
System.out.println("Exception Occurred!");
e.printStackTrace();
return null;
}
final BufferedImage image = imageHandler.getImageAsBufferedImage();
imageHandler.downloadBufferedImage(image);
System.out.println("[M. Console]: The image file has been downloaded as "
+ imageHandler.getImageDownloadPath());
}

public void exitThread() {
Expand Down
73 changes: 73 additions & 0 deletions src/com/mercurys/unfinished/MImageHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.mercurys.unfinished;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.file.*;
import java.text.*;
import java.util.Calendar;

public class MImageHandler {

DataOutputStream outputStream;
DataInputStream inputStream;
String imageDownloadPath;

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

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

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

final byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();

this.outputStream.write(size);
this.outputStream.write(byteArrayOutputStream.toByteArray());
}

public BufferedImage getImageAsBufferedImage() {
try {
final byte[] imgSize = new byte[4];
this.inputStream.readFully(imgSize);
final byte[] imgArr = new byte[ByteBuffer.wrap(imgSize).asIntBuffer().get()];
this.inputStream.readFully(imgArr);
return ImageIO.read(new ByteArrayInputStream(imgArr));

} catch (final IOException e) {
System.out.println("Exception Occurred!");
e.printStackTrace();
return null;
}
}

public void downloadBufferedImage(final BufferedImage image) {
if (image == null) {
return;
}
final String s = System.getProperty("file.separator");
final String downloadPath =
MessageFormat.format("{0}{1}Pictures{1}Mercurys{1}{3}{1}ReceivedImage{2}.png",
System.getProperty("user.home"), s, new SimpleDateFormat("HHmmss")
.format(Calendar.getInstance().getTime()), new SimpleDateFormat("dd.MM.yyyy")
.format(Calendar.getInstance().getTime()));
try {
Files.createDirectories(Paths.get(downloadPath.substring(0, downloadPath.lastIndexOf(s)) + s));
ImageIO.write(image, "png", new File(downloadPath));
this.imageDownloadPath = downloadPath;
} catch (final IOException e) {
e.printStackTrace();
}
}

public String getImageDownloadPath() {
return imageDownloadPath;
}
}
15 changes: 7 additions & 8 deletions src/com/mercurys/unfinished/MediaClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,24 +37,23 @@ private static String getHostAddress() {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter server host address [IP] or press 1 for localhost:");
final String hostAddress = sc.next();
return (hostAddress.equals("1"))? "localhost" : hostAddress;
return (hostAddress.equals("1"))? "192.168.0.151" : hostAddress;
}

private void talk() {
try {
final ReadMediaThread readMediaThread = new ReadMediaThread(this.socket,
"client1" + this.socket.getLocalAddress().toString());
final ReadMediaThread incomingMessageReader = new ReadMediaThread(this.socket,
"M_Host" + this.socket.getLocalAddress().toString());
incomingMessageReader.start();
this.sendMessagesToServer();

readMediaThread.start();
this.writeToClient();

this.closeConnection(readMediaThread);
this.closeConnection(incomingMessageReader);
} catch (final IOException e) {
e.printStackTrace();
}
}

private void writeToClient() {
private void sendMessagesToServer() {
final Encryption encryption = new Encryption();
final PrintWriter writer = new PrintWriter(this.outputStream, true);
final Scanner scanner = new Scanner(System.in);
Expand Down
36 changes: 13 additions & 23 deletions src/com/mercurys/unfinished/MediaServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
import com.mercurys.encryption.Encryption;
import com.mercurys.threads.ReadMediaThread;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.Scanner;

public class MediaServer {
Expand All @@ -17,7 +14,8 @@ public class MediaServer {

private MediaServer(final int port) {
try (final ServerSocket serverSocket = new ServerSocket()) {
serverSocket.bind(new InetSocketAddress("localhost", port));
String hostAddress = "192.168.0.151"; //replace with one's own LAN IP address
serverSocket.bind(new InetSocketAddress(hostAddress, port));
System.out.println("""
Server initiated.
Waiting for client...""");
Expand All @@ -34,26 +32,26 @@ private MediaServer(final int port) {

public static void main(final String[] args) {
final MediaServer mediaServer = new MediaServer(4444);
mediaServer.talk();
mediaServer.startTalking();

System.out.println("Thank you for using Project Mercurys!");
}

private void talk() {
private void startTalking() {
try {
final ReadMediaThread readMediaThread = new ReadMediaThread(this.socket,
"client1" + this.socket.getLocalAddress().toString());
final ReadMediaThread incomingMessageReader = new ReadMediaThread(this.socket,
"M_Client");

readMediaThread.start();
this.writeToClient();
incomingMessageReader.start();
this.sendMessages();

this.closeConnection(readMediaThread);
this.closeConnection(incomingMessageReader);
} catch (final IOException e) {
e.printStackTrace();
}
}

private void writeToClient() {
private void sendMessages() {
final Encryption encryption = new Encryption();
final PrintWriter writer = new PrintWriter(this.outputStream, true);
final Scanner scanner = new Scanner(System.in);
Expand All @@ -71,26 +69,18 @@ private void writeToClient() {
}

private void handleImageUpload(final PrintWriter writer, final String outGoingLine) {
MImageHandler imageHandler = new MImageHandler(outputStream);
try {
writer.println(new Encryption().encrypt("/image incoming!"));
this.sendImageFileAsByteStream(outGoingLine);
System.out.println("[Mercurys:] Image sent!");
imageHandler.sendImageFileAsByteStream(outGoingLine);
System.out.println("[M_Console:] Image sent!");
} catch (final IOException e) {
System.out.println("Exception Occurred!");
e.printStackTrace();
}
}

private void sendImageFileAsByteStream(final String imageFileName) throws IOException {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedImage bufferedImage = ImageIO.read(new File(imageFileName));
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);

final byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();

this.outputStream.write(size);
this.outputStream.write(byteArrayOutputStream.toByteArray());
}

private void closeConnection(final ReadMediaThread readMediaThread) throws IOException {
readMediaThread.exitThread();
Expand Down

0 comments on commit 5d3c7c4

Please sign in to comment.