Skip to content

Commit

Permalink
Dev v0.1.4 update (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShuraBlack authored Oct 23, 2023
2 parents 043c791 + ddabc5c commit 80831d3
Show file tree
Hide file tree
Showing 15 changed files with 107 additions and 100 deletions.
19 changes: 10 additions & 9 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Logging:
- [Log4J Simple](https://github.com/apache/logging-log4j2) - **2.0.5**
- [Junit5](https://github.com/junit-team/junit5) - **5.9.2**

## Download ![Static Badge](https://img.shields.io/badge/version-v0.1.3-%230679b6)
## Download ![Static Badge](https://img.shields.io/badge/version-v0.1.4-%230679b6)
Currently this project only supports [GitHub Release](https://github.com/ShuraBlack/JhttpFileShare/releases) with a **.jar**.

## Java Arguments
Expand All @@ -36,16 +36,17 @@ USAGE:
java -jar JhttpFileShare.jar [options/flags]
FLAGS:
-ip Shows all Network Interfaces
-v, -verbose Enables verbose mode (more informations Server-side)
-nr Disables the root folder restriction (Access entire file browser)
-h, -help Shows this help
-ip Shows all Network Interfaces
-v, -verbose Enables verbose mode (more informations Server-side)
-nr Disables the root folder restriction (Access entire file browser)
-up Enables uploading to the host mashine
-h, -help Shows this help
OPTIONS:
-ip=<network_name> Sets the IP Address to the given network name [default: 0.0.0.0]
-p, -port=<port> Sets the Port to the given port [default: 80]
-threads=<size> Sets the Thread Pool Size to the given size [default: 3]
-root=<path> Sets the root folder [default: user.dir]
-ip=<network_name> Sets the IP Address to the given network name [default: 0.0.0.0]
-p, -port=<port> Sets the Port to the given port [default: 80]
-threads=<size> Sets the Thread Pool Size to the given size [default: 3]
-root=<path> Sets the root folder [default: user.dir]
```

## Usage
Expand Down
19 changes: 9 additions & 10 deletions src/main/java/controller/Controller.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* Main component for the JhttpFileShare application.<br><br>
* This class is the entry point and will initialize the server and the command line interface.
*
* @version 0.1.0
* @version 0.1.4
* @since 19.Oct.2023
* @author ShuraBlack
*/
Expand Down Expand Up @@ -55,7 +55,7 @@ public Controller(String[] args) {

System.out.println(
"==================================================================================\n"
+ "= JhttpFileShare - Version 0.1.2 =\n"
+ "= JhttpFileShare - Version 0.1.4 =\n"
+ "= Code by ShuraBlack =\n"
+ "==================================================================================\n"
+ getProperties() + "\n"
Expand Down Expand Up @@ -97,16 +97,15 @@ public static List<UserSession> getSessions() {
* @return The properties
*/
private static String getProperties() {
String properties = String.format("= Verbose: %s, "
+ "Root Restriction: %s, "
+ "Port: %s, "
+ "Thread Pool Size: %s",
return String.format("= Verbose: %-27s IP: %-59s =%n"
+ "= Root Restriction: %-18s Port: %-57s =%n"
+ "= Upload Allowed: %-20s Thread Pool Size: %-45s =",
colorize(Config.isVerbose()),
"\033[0;36m" + Config.getIpAddress() + "\033[0m",
colorize(Config.isRootRestricted()),
Config.getPort(),
Config.getThreadPoolSize());
properties += " ".repeat(102 - properties.length()) + " =";
return properties;
"\033[0;36m" + Config.getPort() + "\033[0m",
colorize(Config.isUploadAllowed()),
"\033[0;36m" + Config.getThreadPoolSize() + "\033[0m");
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/model/data/FileData.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static void getDirectoryStructure(String path) {
* @param file The file to add.
* @param depth The depth of the file in the directory structure.
*/
public static void addFile(File file, int depth, StringBuilder builder) {
private static void addFile(File file, int depth, StringBuilder builder) {
builder.append(" ".repeat(depth)).append("> ").append(file.getName()).append("<br>");

for (File f : file.listFiles()) {
Expand Down
23 changes: 0 additions & 23 deletions src/main/java/model/data/Structure.java

This file was deleted.

70 changes: 37 additions & 33 deletions src/main/java/model/interpreter/ArgsInterpreter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,16 @@
import org.apache.logging.log4j.Logger;
import util.Config;

import java.io.File;
import java.net.*;
import java.util.*;
import java.util.regex.Pattern;

/**
* Interpreter for the command line arguments.
* <br><br>
* This class will interpret the command line arguments and set the corresponding values.
* <br><br>
* The following arguments are available:
* <ul>
* <li>-ip</li>
* <li>-p, -port</li>
* <li>-v, -verbose</li>
* <li>-h, -help</li>
* <li>-nolimit</li>
* <li>-threads</li>
* <li>-root</li>
* </ul>
*
* @version 0.1.0
* @version 0.1.4
* @since 19.Oct.2023
* @author ShuraBlack
*/
Expand Down Expand Up @@ -86,6 +75,9 @@ public static void interpret(String[] args) {
case "-root":
interpretRoot(entry.getValue());
break;
case "-up":
interpretUpload();
break;
case "-help":
case "-h":
interpretHelp();
Expand All @@ -108,10 +100,13 @@ public static void interpret(String[] args) {
private static void interpretIP(String value) {
try {
if (value == null) {
LOGGER.info("Network Interfaces:\n(Search for the the local network name you use on the devices)\n");
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
StringBuilder builder = new StringBuilder();
builder.append("\nNetwork Interfaces:\n(Search for the the local network name you use on the devices)\n");
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
displayInterfaceInformation(builder, netint);

LOGGER.info(builder.toString());
System.exit(0);
} else {
NetworkInterface netint = NetworkInterface.getByName(value);
Expand Down Expand Up @@ -196,44 +191,53 @@ private static void interpretThreads(String value) {
* @param value The path or null.
*/
private static void interpretRoot(String value) {
if (value == null || value.isEmpty() || !Pattern.matches("([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?",value)) {
if (value == null) {
LOGGER.warn("Root not found! Use default root.");
return;
}
File file = new File(value);
if (file.isFile()) {
LOGGER.warn("selected a file, not a directory! Use default root.");
}
Config.set("ROOT_DIRECTORY", value.replaceAll("\\\\", "/"));
LOGGER.info("Set Root to {}", Config.getRootDirectory());
}

private static void interpretUpload() {
Config.set("UPLOAD_ALLOWED", "true");
LOGGER.info("Upload got enabled");
}

/**
* Prints out the help.
*/
private static void interpretHelp() {
System.out.println("JhttpFileShare Server 0.1.2\n");
System.out.println("USAGE:\n\tjava -jar JhttpFileShare.jar [options/flags]\n");
System.out.println("FLAGS:");
System.out.println("\t-ip\t\t\t\t\tShows all Network Interfaces\n"
+ "\t-v, -verbose\t\t\t\tEnables verbose mode (more informations Server-side)\n"
+ "\t-nr\t\t\t\tDisables the root folder restriction (Access entire file browser)\n"
+ "\t-h, -help\t\t\t\tShows this help\n");
System.out.println("OPTIONS:\n"
+ "\t-ip=<network_name>\t\t\tSets the IP Address to the given network name [default: 0.0.0.0]\n"
+ "\t-p, -port=<port>\t\t\tSets the Port to the given port [default: 80]\n"
+ "\t-threads=<size>\t\t\t\tSets the Thread Pool Size to the given size [default: 3]\n"
+ "\t-root=<path>\t\t\t\tSets the root folder [default: user.dir]\n");
LOGGER.info("\nJhttpFileShare Server 0.1.4\n\n" +
"USAGE:\n\tjava -jar JhttpFileShare.jar [options/flags]\n\n" +
"FLAGS:\n" +
"\t-ip\t\t\t\t\t\t\tShows all Network Interfaces\n" +
"\t-v, -verbose\t\t\t\tEnables verbose mode (more informations Server-side)\n" +
"\t-nr\t\t\t\t\t\t\tDisables the root folder restriction (Access entire file browser)\n" +
"\t-up\t\t\t\t\t\t\tEnables uploading to the host mashine\n" +
"\t-h, -help\t\t\t\t\tShows this help\n\n" +
"OPTIONS:\n" +
"\t-ip=<network_name>\t\t\tSets the IP Address to the given network name [default: 0.0.0.0]\n" +
"\t-p, -port=<port>\t\t\tSets the Port to the given port [default: 80]\n" +
"\t-threads=<size>\t\t\t\tSets the Thread Pool Size to the given size [default: 3]\n" +
"\t-root=<path>\t\t\t\tSets the root folder [default: user.dir]\n");
System.exit(0);
}

/**
* Prints out the network interfaces.
* Appends the network interface information to the given string builder.
* @param builder The string builder.
* @param netint The network interface.
*/
private static void displayInterfaceInformation(NetworkInterface netint) {
StringBuilder sb = new StringBuilder();
private static void displayInterfaceInformation(StringBuilder builder, NetworkInterface netint) {
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
if (inetAddress instanceof Inet6Address) continue;
sb.append(netint.getName()).append(" - ").append(inetAddress.getHostAddress()).append("\n");
builder.append(netint.getName()).append(" - ").append(inetAddress.getHostAddress()).append("\n");
}
System.out.printf(sb.toString());
}
}
9 changes: 5 additions & 4 deletions src/main/java/model/pages/DirectoryPage.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
import java.util.Map;
import java.util.Optional;

import static util.FileSize.convertSize;
import static util.Query.queryToMap;
import static util.FileSize.convert;
import static util.Query.toMap;

/**
* This class is responsible for the directory page request.
Expand Down Expand Up @@ -48,7 +48,7 @@ public void handle(HttpExchange he) throws IOException {
userSession = session.get();
}

Map<String, String> params = queryToMap(he.getRequestURI().getQuery());
Map<String, String> params = toMap(he.getRequestURI().getQuery());
if (params.containsKey("folder")) {
userSession.setWorkDirectory(params.get("folder"));
userSession.clear();
Expand Down Expand Up @@ -90,7 +90,7 @@ public static String htmlFromUserSession(UserSession session) {

html.append("<dt>").append(name).append("</dt>\n");
if (file.getSize() > 0) {
html.append("<dd>").append(convertSize(file.getSize())).append("</dd>\n");
html.append("<dd>").append(convert(file.getSize())).append("</dd>\n");
}
}
html.append("</dl>\n");
Expand All @@ -111,6 +111,7 @@ public static String htmlFromUserSession(UserSession session) {
* @return The filled content.
*/
public static String populateContent(UserSession userSession, String content) {
content = content.replace("{{uploadDisabled}}", !Config.isUploadAllowed() ? "display: none;" : "display: inline-block;");
content = content.replace("{{returnDisabled}}",
Config.isRootRestricted() && userSession.getWorkDirectory().equals(Config.getRootDirectory())
? "display: none;" : "display: inline-block;");
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/model/pages/DownloadPage.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import java.nio.file.Files;
import java.util.Map;

import static util.Query.queryToMap;
import static util.Query.toMap;

/**
* This class is responsible for the download page request.
Expand All @@ -36,7 +36,7 @@ public class DownloadPage implements HttpHandler {

@Override
public void handle(HttpExchange he) throws IOException {
Map<String, String> params = queryToMap(he.getRequestURI().getQuery());
Map<String, String> params = toMap(he.getRequestURI().getQuery());
if (params.isEmpty() || !params.containsKey(FILENAME) || !params.get(FILENAME).contains(Config.getRootDirectory())) {
return;
}
Expand Down
9 changes: 7 additions & 2 deletions src/main/java/model/pages/UploadPage.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand All @@ -38,11 +39,15 @@ public class UploadPage implements HttpHandler {

@Override
public void handle(HttpExchange httpExchange) throws IOException {
if (!Config.isUploadAllowed()) {
return;
}

Headers headers = httpExchange.getRequestHeaders();
String contentType = headers.getFirst("Content-Type");
if(contentType.startsWith("multipart/form-data")){
String boundary = contentType.substring(contentType.indexOf("boundary=")+9);
byte[] boundaryBytes = ("\r\n--" + boundary).getBytes(Charset.forName("UTF-8"));
byte[] boundaryBytes = ("\r\n--" + boundary).getBytes(StandardCharsets.UTF_8);
byte[] payload = getInputAsBinary(httpExchange.getRequestBody());
ArrayList<MultiPart> list = new ArrayList<>();

Expand All @@ -56,7 +61,7 @@ public void handle(HttpExchange httpExchange) throws IOException {
}
byte[] part = Arrays.copyOfRange(payload,startPart,endPart);

int headerEnd = indexOf(part,"\r\n\r\n".getBytes(Charset.forName("UTF-8")),0,part.length-1);
int headerEnd = indexOf(part,"\r\n\r\n".getBytes(StandardCharsets.UTF_8),0,part.length-1);
if(headerEnd>0) {
MultiPart p = new MultiPart();
byte[] head = Arrays.copyOfRange(part, 0, headerEnd);
Expand Down
14 changes: 9 additions & 5 deletions src/main/java/model/server/Server.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package model.server;

import com.sun.net.httpserver.HttpServer;
import controller.Controller;
import model.pages.DirectoryPage;
import model.pages.DownloadPage;
import model.pages.UploadPage;
Expand All @@ -17,7 +16,7 @@
* This class represents the server component of the JhttpFileShare application.<br><br>
* It will create a HttpServer instance and register the needed contexts.
*
* @version 0.1.0
* @version 0.1.4
* @since 19.Oct.2023
* @author ShuraBlack
*/
Expand All @@ -43,13 +42,18 @@ public Server() {
httpServer.createContext("/directory", new DirectoryPage());
if (Config.isVerbose())
LOGGER.info("Created context /directory");

httpServer.createContext("/download", new DownloadPage());
if (Config.isVerbose())
LOGGER.info("Created context /download");

httpServer.createContext("/upload", new UploadPage());
if (Config.isVerbose())
LOGGER.info("Created context /upload");
httpServer.setExecutor(Executors.newFixedThreadPool(Config.getThreadPoolSize()));
if (Config.isUploadAllowed()) {
if (Config.isVerbose())
LOGGER.info("Created context /upload");
httpServer.setExecutor(Executors.newFixedThreadPool(Config.getThreadPoolSize()));
}

httpServer.start();
} catch (IOException e) {
LOGGER.error("Couldnt start Server!", e);
Expand Down
1 change: 1 addition & 0 deletions src/main/java/model/session/UserSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,5 @@ public void setWorkDirectory(String workDirectory) {
this.workDirectory = workDirectory;
this.workDirectory = this.workDirectory.replaceAll("\\\\", "/");
}

}
Loading

0 comments on commit 80831d3

Please sign in to comment.