Skip to content
Snippets Groups Projects
Commit c8835647 authored by Torstein Strømme's avatar Torstein Strømme
Browse files

version 0.1 starter code

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 1481 additions and 0 deletions
mvnw
mvnw.cmd
# Created by https://www.toptal.com/developers/gitignore/api/eclipse,maven,java,intellij,visualstudiocode,macos,windows
# Edit at https://www.toptal.com/developers/gitignore?templates=eclipse,maven,java,intellij,visualstudiocode,macos,windows
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
.apt_generated_test/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
# Uncomment this line if you wish to ignore the project description file.
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project
### Eclipse Patch ###
# Spring Boot Tooling
.sts4-cache/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
### Java ###
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
# Eclipse m2e generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/eclipse,maven,java,intellij,visualstudiocode,macos,windows
target/
.mvn/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
LICENSE 0 → 100644
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This diff is collapsed.
#!/bin/bash
# Script for packaging a Java application as a Mac installer.
# Designed to be used with Maven (see example pom.xml at
# https://github.com/torsteins/JavaInstallerForSwing)
#
# Inspired by a template made by dlemmermann at
# https://github.com/dlemmermann/JPackageScriptFX
#
# Simplified by Torstein Strømme to fit INF101 at the University of Bergen.
# ------ ENVIRONMENT ----------------------------------------------
# The script depends on environment variables to exist in order to
# run properly (think of them as input parameters to the script).
# We print them all here:
echo "required input environment variables..."
echo " ABOUT_NAME: $ABOUT_NAME" # name of terminal in menu
echo " APP_PACKAGE: $APP_PACKAGE" # e.g. "no.uib.inf101.terminal"
echo " APP_VENDOR: $APP_VENDOR" # info shown in ~about~ dialog
echo " APP_VERSION: $APP_VERSION" # version shown in ~about~ dialog
echo " ICON_PATH: $ICON_PATH" # path to .icns -file
echo " INSTALLER_TYPE: $INSTALLER_TYPE" # e.g. "dmg" or "pkg"
echo " JAVA_HOME: $JAVA_HOME" # path to java installation
echo " JAVA_VERSION: $JAVA_VERSION" # e.g. "17"
echo " MAIN_CLASS: $MAIN_CLASS" # e.g. "no.uib.inf101.terminal.Main"
echo " MAIN_JAR: $MAIN_JAR" # filename produced in package phase
echo " PROJECT_NAME: $PROJECT_NAME" # human-friendly name of application
echo " PROJECT_VERSION: $PROJECT_VERSION" # version in pom, e.g. "1.0-SNAPSHOT"
echo "computed variables..."
CURRENT_YEAR=$(date +'%Y')
echo " CURRENT_YEAR: $CURRENT_YEAR"
PATH_TO_MAIN_CLASS="target/classes/${MAIN_CLASS//'.'//}.class"
echo " PATH_TO_MAIN_CLASS: $PATH_TO_MAIN_CLASS"
# ------ SETUP DIRECTORIES AND FILES ----------------------------------------
# Remove previously generated java runtime and installers. Copy all required
# jar files into the input/libs folder.
echo "setting up directories and files..."
rm -rfd ./target/java-runtime/
rm -rfd target/installer/
mkdir -p target/installer/input/libs/
if [[ -d target/libs ]]; then
cp target/libs/* target/installer/input/libs
fi
cp "target/${MAIN_JAR}" target/installer/input/libs/
## ------ REQUIRED MODULES ---------------------------------------------------
## Use jlink to detect all modules that are required to run the application.
## Starting point for the jdep analysis is the set of jars being used by the
## application.
echo "detecting required modules.."
detected_modules=$("$JAVA_HOME/bin/jdeps" \
-q \
--multi-release "${JAVA_VERSION}" \
--ignore-missing-deps \
--print-module-deps \
--class-path "target/installer/input/libs/*" \
"$PATH_TO_MAIN_CLASS")
echo " detected modules: ${detected_modules}"
# Note: in the original version of this script by dlemmermann (reference
# above), there is a separate section on manual required modules. Please
# adapt from that script if you find that this is required. Only applies
# to certain modules, such as jdk.crypto.ec or jdk.localedata.
# ------ RUNTIME IMAGE ------------------------------------------------------
# Use the jlink tool to create a runtime image for our application. We are
# doing this in a separate step instead of letting jlink do the work as part
# of the jpackage tool. This approach allows for finer configuration and also
# works with dependencies that are not fully modularized, yet.
echo "creating java runtime image..."
"$JAVA_HOME/bin/jlink" \
--strip-native-commands \
--no-header-files \
--no-man-pages \
--compress=2 \
--strip-debug \
--add-modules "${detected_modules}" \
--output target/java-runtime
# ------ PACKAGING ----------------------------------------------------------
# In the end we will find the package inside the target/installer directory.
echo "creating installer of type $INSTALLER_TYPE..."
"$JAVA_HOME/bin/jpackage" \
--type "$INSTALLER_TYPE" \
--dest target/installer \
--input target/installer/input/libs \
--name "${PROJECT_NAME}" \
--main-class "${MAIN_CLASS}" \
--main-jar "${MAIN_JAR}" \
--runtime-image target/java-runtime \
--icon "${ICON_PATH}" \
--app-version "${APP_VERSION}" \
--vendor "${APP_VENDOR}" \
--copyright "Copyright © ${CURRENT_YEAR} ${APP_VENDOR}." \
--mac-package-identifier "${APP_PACKAGE}"
# --java-options -Xmx2048m \
@ECHO OFF
REM Script for packaging a Java application as a Windows installer.
REM Designed to be used with Maven (see example pom.xml at
REM https://github.com/torsteins/JavaInstallerForSwing)
REM
REM Inspired by a template made by dlemmermann at
REM https://github.com/dlemmermann/JPackageScriptFX
REM
REM Simplified by Torstein Strømme to fit INF101 at the University of Bergen.
REM ------ ENVIRONMENT --------------------------------------------------------
REM The script depends on various environment variables to exist in order to
REM run properly. The location of the java binaries (java home), and the
REM project version as defined inside the pom.xml file, e.g. 1.0-SNAPSHOT.
ECHO "required input environment variables..."
ECHO " APP_PACKAGE: %APP_PACKAGE%"
ECHO " APP_VENDOR: %APP_VENDOR%"
REM APP_VERSION: the application version, e.g. 1.0.0, shown in "about" dialog
ECHO " APP_VERSION: %APP_VERSION%"
ECHO " ICON_PATH: %ICON_PATH%"
REM Set desired installer type: "msi" "exe" (or "app-image").
ECHO " INSTALLER_TYPE: %INSTALLER_TYPE%"
ECHO " JAVA_HOME: %JAVA_HOME%"
ECHO " JAVA_VERSION: %JAVA_VERSION%"
ECHO " MAIN_JAR: %MAIN_JAR%"
ECHO " MAIN_CLASS: %MAIN_CLASS%"
ECHO " PROJECT_NAME: %PROJECT_NAME%"
ECHO " PROJECT_VERSION: %PROJECT_VERSION%"
ECHO "computed variables..."
SET PATH_TO_MAIN="target\classes\%MAIN_CLASS:.=\%.class"
ECHO " PATH_TO_MAIN: %PATH_TO_MAIN%"
SET YEAR=%DATE:~6,4%
ECHO " YEAR: %YEAR%"
REM ------ SETUP DIRECTORIES AND FILES ----------------------------------------
REM Remove previously generated java runtime and installers. Copy all required
REM jar files into the input/libs folder.
ECHO "setting up directories and files..."
IF EXIST target\java-runtime RMDIR /S /Q .\target\java-runtime
IF EXIST target\installer RMDIR /S /Q target\installer
MKDIR target\installer\input\libs
XCOPY /S /Q target\libs\* target\installer\input\libs\
COPY target\%MAIN_JAR% target\installer\input\libs\
REM ------ REQUIRED MODULES ---------------------------------------------------
REM Use jlink to detect all modules that are required to run the application.
REM Starting point for the jdep analysis is the set of jars being used by the
REM application.
ECHO "detecting required modules with jdeps..."
"%JAVA_HOME%\bin\jdeps" ^
-q ^
--multi-release %JAVA_VERSION% ^
--ignore-missing-deps ^
--class-path "target\installer\input\libs\*" ^
--print-module-deps "%PATH_TO_MAIN%" > temp.txt
SET /p detected_modules=<temp.txt
DEL temp.txt
ECHO " detected modules: %detected_modules%"
REM ------ RUNTIME IMAGE ------------------------------------------------------
REM Use the jlink tool to create a runtime image for our application. We are
REM doing this in a separate step instead of letting jlink do the work as part
REM of the jpackage tool. This approach allows for finer configuration and also
REM works with dependencies that are not fully modularized, yet.
ECHO "creating java runtime image with jlink..."
CALL "%JAVA_HOME%\bin\jlink" ^
--strip-native-commands ^
--no-header-files ^
--no-man-pages ^
--compress=2 ^
--strip-debug ^
--add-modules "%detected_modules%" ^
--output target/java-runtime
REM ------ PACKAGING ----------------------------------------------------------
REM In the end we will find the package inside the target/installer directory.
ECHO "creating install package with jpackage..."
CALL "%JAVA_HOME%\bin\jpackage" ^
--type %INSTALLER_TYPE% ^
--dest target/installer ^
--input target/installer/input/libs ^
--name "%PROJECT_NAME%" ^
--main-class "%MAIN_CLASS%" ^
--main-jar "%MAIN_JAR%" ^
--runtime-image target/java-runtime ^
--icon "%ICON_PATH%" ^
--app-version %APP_VERSION% ^
--vendor "%APP_VENDOR%" ^
--copyright "Copyright © %YEAR% %APP_VENDOR%" ^
--win-dir-chooser ^
--win-per-user-install ^
--win-shortcut ^
--win-menu
REM --java-options -Xmx2048m
img/vscode-terminalfolder.png

11.7 KiB

pom.xml 0 → 100644
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Major project properties -->
<groupId>no.uib.inf101.app</groupId>
<artifactId>SamplePackagedSwingApp</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Sample Application</name>
<packaging>jar</packaging>
<properties>
<!-- General project properties -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>17</java.version>
<!-- Properties required for packaging application as JAR and installer -->
<app.main.class>no.uib.inf101.terminal.Main</app.main.class>
<app.vendor>Torstein Strømme</app.vendor> <!-- copyright holder -->
<app.version>1.0.0</app.version> <!-- version displayed in "about" -->
<app.installer.macosx.type>dmg</app.installer.macosx.type> <!-- dmg, pkg -->
<app.installer.windows.type>msi</app.installer.windows.type> <!-- msi, exe -->
<app.macosx.icon.path>src/main/logo/macosx/logo.icns</app.macosx.icon.path>
<app.windows.icon.path>src/main/logo/windows/logo.ico</app.windows.icon.path>
<!-- Library and plugin versions -->
<junit.version>5.9.1</junit.version>
<maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
<maven.dependency.plugin.version>3.4.0</maven.dependency.plugin.version>
<maven.jar.plugin.version>3.3.0</maven.jar.plugin.version>
<exec.maven.plugin.version>1.6.0</exec.maven.plugin.version>
<!-- Computed properties -->
<maven.compiler.release>${java.version}</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<release>${java.version}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven.dependency.plugin.version}</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/libs
</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
<includeScope>compile</includeScope>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven.jar.plugin.version}</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${app.main.class}</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>build-mac</id>
<activation>
<os><family>mac</family></os>
</activation>
<build>
<plugins>
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<version>${exec.maven.plugin.version}</version>
<executions>
<execution>
<id>Build Native Mac App</id>
<phase>install</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<workingDirectory>${project.basedir}</workingDirectory>
<executable>./build_app_mac.sh</executable>
<environmentVariables>
<APP_PACKAGE>${project.groupId}</APP_PACKAGE>
<ABOUT_NAME>${project.name}</ABOUT_NAME>
<APP_VENDOR>${app.vendor}</APP_VENDOR>
<APP_VERSION>${app.version}</APP_VERSION>
<ICON_PATH>${app.macosx.icon.path}</ICON_PATH>
<INSTALLER_TYPE>${app.installer.macosx.type}</INSTALLER_TYPE>
<JAVA_HOME>${java.home}</JAVA_HOME>
<JAVA_VERSION>${java.version}</JAVA_VERSION>
<MAIN_CLASS>${app.main.class}</MAIN_CLASS>
<MAIN_JAR>${project.artifactId}-${project.version}.jar</MAIN_JAR>
<PROJECT_NAME>${project.name}</PROJECT_NAME>
<PROJECT_VERSION>${project.version}</PROJECT_VERSION>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>build-windows</id>
<activation>
<os><family>windows</family></os>
</activation>
<build>
<plugins>
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<version>${exec.maven.plugin.version}</version>
<executions>
<execution>
<id>Build Native Windows App</id>
<phase>install</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<workingDirectory>${project.basedir}</workingDirectory>
<executable>build_app_windows.bat</executable>
<environmentVariables>
<APP_PACKAGE>${project.groupId}</APP_PACKAGE>
<APP_VENDOR>${app.vendor}</APP_VENDOR>
<APP_VERSION>${app.version}</APP_VERSION>
<ICON_PATH>${app.windows.icon.path}</ICON_PATH>
<INSTALLER_TYPE>${app.installer.windows.type}</INSTALLER_TYPE>
<JAVA_HOME>${java.home}</JAVA_HOME>
<JAVA_VERSION>${java.version}</JAVA_VERSION>
<MAIN_JAR>${project.artifactId}-${project.version}.jar</MAIN_JAR>
<MAIN_CLASS>${app.main.class}</MAIN_CLASS>
<PROJECT_NAME>${project.name}</PROJECT_NAME>
<PROJECT_VERSION>${project.version}</PROJECT_VERSION>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
package no.uib.inf101.terminal;
/**
* A command line interface is a program with a text-based user interface.
* The user can enter keys as input, and the program will respond by giving
* text which can be displayed on a screen.
*/
public interface CommandLineInterface {
/**
* Called when a key is pressed.
*
* @param key The key that was pressed
*/
void keyPressed(char key);
/**
* Get the text to display on the screen.
* @return The text to display
*/
String getScreenContent();
}
package no.uib.inf101.terminal;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
public class Context {
private final File home;
private File cwd;
public Context(File home) {
try {
this.home = home.getCanonicalFile();
this.cwd = this.home;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean goToPath(String path) {
File newDir = new File(cwd, path);
if (!newDir.isDirectory()) {
return false;
}
try {
cwd = newDir.getCanonicalFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public File getCwd() {
return this.cwd;
}
public void goToHome() {
this.cwd = this.home;
}
public boolean isAtHome() {
return Objects.equals(this.cwd, this.home);
}
}
package no.uib.inf101.terminal;
public class DummyShell implements CommandLineInterface {
private String screenContent = "$ ";
@Override
public void keyPressed(char keyCode) {
if (keyCode == '\n') {
screenContent += "\n$ ";
} else {
screenContent += keyCode;
}
}
@Override
public String getScreenContent() {
return screenContent;
}
}
package no.uib.inf101.terminal;
import java.util.ArrayList;
public class EchoShell implements CommandLineInterface {
ArrayList<String> outputLines = new ArrayList<>();
String currentLine = "";
@Override
public void keyPressed(char keyCode) {
if (keyCode == '\n') {
outputLines.add("$ " + currentLine);
outputLines.add("Oh, an echo! listen: " + currentLine);
currentLine = "";
} else {
currentLine += keyCode;
}
}
@Override
public String getScreenContent() {
String result = "";
for (String line : outputLines) {
result += line + "\n";
}
return result + "$ " + currentLine;
}
}
package no.uib.inf101.terminal;
public class Main {
public static void main(String[] args) {
// Create a new shell
CommandLineInterface shell = new DummyShell();
// Run the shell in the terminal GUI
Terminal gui = new Terminal(shell);
gui.run();
}
}
\ No newline at end of file
package no.uib.inf101.terminal;
import java.io.File;
import java.util.ArrayList;
import java.util.Objects;
// TODO: Let SimpleShell implement CommandLineInterface
public class SimpleShell {
//////////////////////////////////////////////////////////////////////
/// Instance variables ///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/** The prompt to show before each command */
private final String prompt = "$ ";
/** The context variable contains cwd and home directories etc. */
private final Context context = new Context(
new File(System.getProperty("user.dir"))
);
/** A list of historic commands and their outputs */
private final ArrayList<String> history = new ArrayList<>();
/** The command currently being typed */
private String currentCommand = "";
//////////////////////////////////////////////////////////////////////
/// Public methods //////
/// (methods expected to be used by someone outside this class) //////
//////////////////////////////////////////////////////////////////////
// TODO: rename method to fit new interface, annotate with @Override
// Note: methods with @Override generally do not need javadoc comments,
// since the javadoc comment is inherited. You should hence remove the
// javadoc comment here unless there is something special about this
// implementation. You should remove to-do comments when you are done.
/**
* Called when a key is pressed.
*
* @param key The key that was pressed
*/
public void aKeyIsPressed(char key) {
if (key == '\n') {
this.processCurrentCommandLine();
} else if (key >= ' ' && key <= '~') {
this.currentCommand += key;
}
}
// TODO: rename method to fit new interface, annotate with @Override
/**
* Get the text which the terminal should display
*
* @return the text
*/
public String whatTheScreenLooksLike() {
String s = "";
for (String line : this.history) {
s += line;
}
s += this.prompt;
s += this.currentCommand;
return s;
}
//////////////////////////////////////////////////////////////////////
/// Private methods ///////////////////
/// (helper methods used internally in this class) ///////////////////
//////////////////////////////////////////////////////////////////////
/**
* Process the current command line. This entails splitting it into
* a command name and arguments; executing the command; and adding
* the result to the history.
*/
private void processCurrentCommandLine() {
String result = "";
if (this.currentCommand.length() > 0) {
String[] args = this.currentCommand.split(" ");
String commandName = args[0];
String[] commandArgs = new String[args.length - 1];
System.arraycopy(args, 1, commandArgs, 0, commandArgs.length);
result = this.executeCommand(commandName, commandArgs);
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result += '\n';
}
}
this.history.add(this.prompt + this.currentCommand + "\n" + result);
this.currentCommand = "";
}
/**
* Execute a command with the given name and arguments. The command
* name could be "ls", "cd", "pwd", etc., and the arguments are the
* arguments to the command. For example for the command "cd foo", the
* command name is "cd" and the argument comes in the array ["foo"].
*
* @param commandName The name of the command to execute
* @param args The arguments to the command
* @return The output of the command
*/
private String executeCommand(String commandName, String[] args) {
// TODO: Change sequence of if/else if below to a lookup in a map
if (Objects.equals(commandName, "pwd")) {
return this.doPwd(args);
} else if (Objects.equals(commandName, "cd")) {
return this.doCd(args);
} else if (Objects.equals(commandName, "ls")) {
return this.doLs(args);
} else {
return "Command not found: \"" + commandName + "\"";
}
}
// TODO: remove this method and replace it with Command -type object
private String doPwd(String[] args) {
return this.context.getCwd().getAbsolutePath();
}
// TODO: remove this method and replace it with Command -type object
private String doCd(String[] args) {
if (args.length == 0) {
this.context.goToHome();
return "";
} else if (args.length > 1) {
return "cd: too many arguments";
}
String path = args[0];
if (this.context.goToPath(path)) {
return "";
} else {
return "cd: no such file or directory: " + path;
}
}
// TODO: remove this method and replace it with Command -type object
private String doLs(String[] args) {
File cwd = this.context.getCwd();
String s = "";
for (File file : cwd.listFiles()) {
s += file.getName();
s += " ";
}
return s;
}
}
package no.uib.inf101.terminal;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Terminal extends JPanel {
private final CommandLineInterface terminal;
public Terminal(CommandLineInterface cli) {
this.terminal = cli;
this.setPreferredSize(new Dimension(400, 300));
this.setFocusable(true);
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Terminal.this.terminal.keyPressed(e.getKeyChar());
Terminal.this.repaint();
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
String content = this.terminal.getScreenContent();
// Calculate number of lines that can fit display
int lineHeight = g.getFontMetrics().getHeight() + 5;
int lines = this.getHeight() / lineHeight;
// Draw the text on the screen, line by line
g.setColor(Color.BLACK);
g.setFont(new Font("Monospaced", Font.PLAIN, 12));
int y = lineHeight;
// Iterate through the last 'lines' lines of the content
String[] linesOfContent = content.split("\n");
for (int i = Math.max(0, linesOfContent.length - lines); i < linesOfContent.length; i++) {
g.drawString(linesOfContent[i], 5, y);
y += lineHeight;
}
}
public void run() {
JFrame frame = new JFrame("INF101 Terminal");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setVisible(true);
}
}
package no.uib.inf101.terminal;
public class TextAnswers {
/*
* Consider the following code:
*
* CommandLineInterface cli = new DummyShell();
*/
/** What is the type of the variable cli? */
static final String q1 = "";
/** In which class is the object cli refers to? */
static final String q2 = "";
/** True or false: CommandLineInterface is both a type and interface. */
static final Boolean q3 = null;
/** True or false: DummyShell is both a class and a type. */
static final Boolean q4 = null;
}
File added
src/main/logo/windows/logo.ico

61.1 KiB

src/main/resources/no/uib/inf101/terminal/app-icon400.png

144 KiB

package no.uib.inf101.terminal;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestCmdEcho {
// @Test
// public void testGetName() {
// Command echo = new CmdEcho();
// assertEquals("echo", echo.getName());
// }
//
// @Test
// public void testRun() {
// Command echo = new CmdEcho();
//
// String[] args = new String[] {"foo", "bar"};
// assertEquals("foo bar ", echo.run(args));
//
// args = new String[] {"hello"};
// assertEquals("hello ", echo.run(args));
//
// args = new String[] {};
// assertEquals("", echo.run(args));
// }
}
package no.uib.inf101.terminal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
public class TestSimpleShell {
static final String orgCwd = System.getProperty("user.dir");
static final String DIR = "testdir";
static final String SUBDIR = "subdir";
private File subdir;
private File dir;
private SimpleShell shell; // The shell we are testing
////////////////////////////////////////////////////////////////////////
//////// The tests ////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Test
public void testImplementsCLI() {
assertInstanceOf(CommandLineInterface.class, this.shell,
"SimpleShell should implement CommandLineInterface");
}
@Test
public void testDoNothing() {
if ((Object) this.shell instanceof CommandLineInterface cli) {
assertEquals("$ ", cli.getScreenContent());
} else {
fail("SimpleShell does not implement CommandLineInterface");
}
}
@Test
public void testWriteFoo() {
if ((Object) this.shell instanceof CommandLineInterface cli) {
cli.keyPressed('f');
cli.keyPressed('o');
cli.keyPressed('o');
assertEquals("$ foo", cli.getScreenContent());
} else {
fail("SimpleShell does not implement CommandLineInterface");
}
}
@Test
public void testIllegalCommand() {
if ((Object) this.shell instanceof CommandLineInterface cli) {
cli.keyPressed('f');
cli.keyPressed('o');
cli.keyPressed('o');
cli.keyPressed('\n');
assertEquals("$ foo\nCommand not found: \"foo\"\n$ ", cli.getScreenContent());
} else {
fail("SimpleShell does not implement CommandLineInterface");
}
}
@Test
public void testPwd() throws IOException {
if ((Object) this.shell instanceof CommandLineInterface cli) {
cli.keyPressed('p');
cli.keyPressed('w');
cli.keyPressed('d');
cli.keyPressed('\n');
String expected = "$ pwd" + "\n" + this.dir.getCanonicalPath() + "\n$ ";
assertEquals(expected, cli.getScreenContent());
} else {
fail("SimpleShell does not implement CommandLineInterface");
}
}
@Test
public void testLs() throws IOException {
if ((Object) this.shell instanceof CommandLineInterface cli) {
cli.keyPressed('l');
cli.keyPressed('s');
cli.keyPressed('\n');
String expected = "$ ls\n" + SUBDIR + " \n$ ";
assertEquals(expected, cli.getScreenContent());
} else {
fail("SimpleShell does not implement CommandLineInterface");
}
}
@Test
public void testCd() throws IOException {
if ((Object) this.shell instanceof CommandLineInterface cli) {
for (char c : "pwd\n".toCharArray()) cli.keyPressed(c);
for (char c : ("cd " + SUBDIR + "\n").toCharArray()) cli.keyPressed(c);
for (char c : "pwd\n".toCharArray()) cli.keyPressed(c);
String expected = "$ pwd\n"
+ this.dir.getCanonicalPath() + "\n"
+ "$ cd subdir\n"
+ "$ pwd\n"
+ this.subdir.getCanonicalPath() + "\n"
+ "$ ";
assertEquals(expected, cli.getScreenContent());
} else {
fail("SimpleShell does not implement CommandLineInterface");
}
}
////////////////////////////////////////////////////////////////////////
//////// Preparing the tests //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@BeforeEach
public void setUp() throws IOException {
// Set up test directory
File cwd = new File(orgCwd);
this.dir = new File(cwd, DIR);
this.subdir = new File(this.dir, SUBDIR);
this.dir.mkdir();
this.subdir.mkdir();
System.setProperty("user.dir", this.dir.getCanonicalPath());
// Set up shell
this.shell = new SimpleShell();
}
@AfterEach
public void tearDown() {
// Tear down test directory
File cwd = new File(System.getProperty("user.dir"));
File testDir = new File(cwd, DIR);
deleteFolderAndItsContent(testDir);
System.setProperty("user.dir", orgCwd);
// Tear down shell
this.shell = null;
}
private void deleteFolderAndItsContent(File file) {
File[] subFiles = file.listFiles();
if (subFiles != null) {
for (File f : subFiles) {
deleteFolderAndItsContent(f);
}
}
file.delete();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment