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 1872 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.
README.md 0 → 100644
# Shell lab
I denne lab'en skal vi utforske *grensesnitt*, og fortsette med å benytte oss av klasser og objekter.
Samtidig skal vi benytte anledningen til å bli bedre kjent med terminalen, som er et svært viktig verktøy for alle som jobber teknisk med datamaskiner. Både utviklere, system-adminstratorer og vanlige brukere som ønsker å benytte spesialisert software andre har laget vil ha stor glede av den.
> Kjært barn har mange navn. Under lister vi opp noen synonymer til «terminal» med litt ulike opphav, og som har litt ulike konnotasjoner. I praksis bruker vi disse ordene litt om hverandre.
> * **Terminal**. Opprinnelig brukt om kombinasjonen av en fysisk skjerm og et tastatur. Disse kunne være et annet sted enn selve datamaskinen. I senere tid har begrepet blitt brukt om programmer som gir et grafisk brukergrensesnitt (et vindu) til et shell. En **konsoll** var en spesiell terminal som var en integrert del av datamaskinen, og som ikke kunne skilles fra den slik man kunne med andre terminaler.
> * **Shell**. Programmet som vanligvis vises i en terminal. Dette er et rent software-konsept. Et shell *tolker* kommandoer og kan starter andre prosesser. Opprinnelig var dette det dataprogrammet som startet først når oppstarten var ferdig og datamaskinen var klar til bruk. Det ble kalt et shell fordi det «omgav» kjernen i operativsystemet som et skall, og ble for brukerne det eneste de trengte å forholde seg til ved bruk av maskinen. Ordet kommer naturligvis fra tiden før vinduer og mus var vanlig. Det finnes mange ulike shell: for eksempel er **bash** og **zsh** i dag vanlige shell for Linux/Mac mens **cmd** og **PowerShell** er vanlige shell i Windows.
> * **CLI** (kommandolinjen). Et CLI (*command line interface*) er et program med et tekstbasert grensesnitt, for eksempel et shell. Men en kommandolinje er ikke nødvendigvis knyttet til å navigere et operativsystem og starte andre programmer. For eksempel kan vi lage et tekstbasert spill; dette spillet vil da ha en kommandolinje selv om vi ikke ville kalt det for et shell.
I denne lab'en skal vi lage et enkelt shell for å navigere filsystemet som er løst inspirert av *bash*. Kommandoene vi bruker vil også fungere omtrent på samme måte i zsh og PowerShell.
## Oversikt
* [Bli kjent med eksisterende kildekode](#bli-kjent-med-eksisterende-kildekode)
* [Kjøre SimpleShell](#kjøre-simpleshell)
* [Vis SimpleShell gjennom GUI](#vis-simpleshell-gjennom-gui)
* [Et grensesnitt for kommandoer](#et-grensesnitt-for-kommandoer)
* [Opprette grensesnittet Command](#opprette-grensesnittet-command)
* [Definere metoder i Command](#definere-metoder-i-command)
* [Vår første kommando: echo](#vår-første-kommando--echo)
* [Installere kommandoer i SimpleShell](#installere-kommandoer-i-simpleshell)
* [Frivillige forbedringer](#frivillige-forbedringer)
* [exit: en annen enkel kommando](#exit--en-annen-enkel-kommando)
* [pwd, cd og ls: kommandoer som trenger kontekst](#pwd--cd--og-ls--kommandoer-som-trenger-kontekst)
* [man: kommando for å lese manualen](#man--kommando-for-å-lese-manualen)
* [Trykk backspace for å fjerne bakerste bokstav i kommandoen](#trykk-backspace-for-å-fjerne-bakerste-bokstav-i-kommandoen)
* [Starte Java-programmer fra SimpleShell](#starte-java-programmer-fra-simpleshell)
* [Forbedret ls: ls -l, ls -a, ls path/to/folder](#forbedret-ls--ls--l--ls--a--ls-pathtofolder)
* [Flere kommandoer som trenger kontekst: touch, mkdir, cat, rm, mv, cp](#flere-kommandoer-som-trenger-kontekst--touch-mkdir-cat-rm-mv-cp)
* [grep: en bonus-utfordring](#grep--en-bonus-utfordring)
## Bli kjent med eksisterende kildekode
- [ ] Kjør *main*-metoden i `Main` ([link](./src/main/java/no/uib/inf101/terminal/Main.java)) og se at du får opp et vindu du kan skrive i. Sjekk at det virker å skrive, og at du får en ny linje når du trykker enter.
- [ ] I *main*-metoden, bytt ut *DummyShell* med *EchoShell*. Sjekk at når du nå kjører programmet, vil du få et ekko av hver linje du skriver.
Dette du nå har bevitnet kalles *polymorfisme*, og innebærer at to objekter med forskjellig *klasse* begge har samme *type*, og at det finnes kode som fungerer bra med objekter fra begge klassene selv om metodene deres er implementert ulikt. Dette gir oss en høy grad a *modularitet*, siden vi enkelt kan bytte ut objekter i én klasse med objekter i en annen klasse med en litt annen oppførsel.
- [ ] Besvar spørsmålene i `TextAnswers` ([link](./src/main/java/no/uib/inf101/terminal/TextAnswers.java)).
✅ Du er klar til å gå videre når testene i `TestTextAnswers` ([link](`./src/test/java/no/uib/inf101/terminal/TestTextAnswers.java)) passerer
## Kjøre SimpleShell
I resten av oppgaven skal vi modifisere klassen [SimpleShell](./src/main/java/no/uib/inf101/terminal/SimpleShell.java) og senere opprette noen andre klasser og grensesnitt som vi skal bruke for å forbedre SimpleShell.
- [ ] Kjør testene i `TestSimpleShellStarter` ([link](./src/test/java/no/uib/inf101/terminal/TestSimpleShellStarter.java)) og se at de allerede passerer.
### Vis SimpleShell gjennom GUI
Vi ønsker at det grafiske brukergrensesnittet vårt [Terminal](./src/main/java/no/uib/inf101/terminal/Terminal.java) skal virke sammen med SimpleShell. Konsturktøren til Terminal-klassen aksepterer alle shell og objekter som implementerer *CommandLineInterface*.
- [ ] La `SimpleShell` implementere grensesnittet `CommandLineInterface`.
- [ ] Opprett de metodene som må implementeres for å oppfylle kontrakten *CommandLineInterface* beskriver. Du kan enten
- gi nytt navn til metodene *aKeyIsPressed* og *whatTheScreenLooksLike* slik at de stemmer overens med metodenavnene som er angitt i CommandLineInterface. Når du endrer navnet, bruk din IDE sin «refactor» -funksjonalitet: høyreklikk på metodenavnet og velg *rename symbol* (VS Code) eller *refactor -> rename* (Intellij) eller tilsvarende. Hvis du glemmer dette, må du endre navnet manuelt i alle testene i TestSimpleShellStarter som bruker disse metodenavnene. Alternativt kan du:
- opprette metodene som kreves av CommandLineInterface og la dem enkelt og greit kalle på *aKeyIsPressed* og *whatTheScreenLooksLike*.
- [ ] Husk i *SimpleShell* å bruke `@Override` foran de metodene som opprinnelig er definert i et grensesnitt.
- [ ] I `Main::main`-metoden: Bytt ut *EchoShell/DummyShell* med *SimpleShell*. Kjør programmet og se at kommandoene `pwd`, `cd` og `ls` virker. Prøv også noe helt annet og se at det kommer en feilmelding uten at java-programmet krasjer.
> Våre kommandoer er forenklede versjoner av de samme kommandoene i bash.
> * `pwd` (print working directory) skriver ut hvilken mappe i filsystemet som er **cwd** (current working directory), altså den mappen man «er» i.
> * `ls` skriver ut alle filene og mappene som befinner seg i cwd.
> * `cd foo` endrer cwd til å bli mappen «foo». Mappen «foo» må ligge i cwd.
> * `cd ..` endrer cwd til å bli mappen over seg i mappehierarkiet.
> * `cd` endrer cwd til å bli «home» -mappen. Det er ikke så viktig hvilken mappe dette er, men det er den samme hver gang (hvis man ikke manipulerer hvilken mappe dette er (slik vi må gjøre i testene), vil dette være cwd for programmet som startet java-prosessen).
✅ Du er klar til å gå videre når testene i `TestSimpleShell` ([link](./src/test/java/no/uib/inf101/terminal/TestSimpleShell.java)) passerer.
## Et grensesnitt for kommandoer
- [ ] Les over kildekoden for metoden `executeCommand` i `SimpleShell`. Det er i denne metoden at vi bestemmer at ulike ting skal skje basert på hvilken kommando som blir gitt (se sekvensen med if og else if).
Vi ønsker å endre executeCommand slik at vi ikke bruker en lang sekvens med if og else if, men i stedet slår opp på `commandName` i et oppslagsverk og finner hvilken kommando som skal utføres der. Vi ønsker altså at koden skal se omtrent slik ut i stedet:
```java
Command command = this.allCommands.get(commandName);
if (command != null) {
String result = command.run(args);
return result;
} else {
return "Command not found: \"" + commandName + "\"";
}
```
Som pseudokode kan koden over tolkes slik:
* Basert på verdien av `commandName`, finn ut hvilken kommando som skal utføres
* Dersom vi fant en gyldig kommando, utfør den og returner resultatet.
Du trenger ikke å ender denne koden helt enda, men dette illustrer hvor vi er på vei. For å komme oss hit, mangler vi en del ting. For eksempel finnes det ikke en type som heter `Command`. La oss definer den nå:
### Opprette grensesnittet `Command`
- [ ] Opprett et nytt grensesnitt som heter `Command` i pakken *no.uib.inf101.terminal*.
* VS Code: høyreklikk på «terminal» der det står no/uib/inf101/terminal i filutforskeren. ![klikk her i VSCode](./img/vscode-terminalfolder.png) Velg så *new file* og skriv *Command.java*. I den nye filen kan du opprette grensesnittet, og skrive inn koden som vises under.
* Intellij: høyreklikk «no.uib.inf101.terminal» i prosjekt-navigatoren, og velg *new -> Java class*. I boksen som kommer opp, skriv *Command* og velg *Interface* i menyen under. Koden som vises under skal nå ha blitt generert automatisk for deg.
Filen skal se nå se slik ut:
```java
package no.uib.inf101.terminal;
public interface Command {
}
```
### Definere metoder i `Command`
Planen er at vi skal kunne kalle på `run`*Command* -objekter. Nærmere bestemt ønsker vi at følgende skal være mulig hvis *command* er en variabel som har typen *Command*:
```java
String[] args = new String[] { "foo", "bar" };
String result = command.run(args);
```
For at dette skal være lov, må grensesnittet *Command* definere en metodesignatur `String run(String[])`. La oss gjøre det nå.
- [ ] Legg til følgende metodesignatur i `Command`:
```java
String run(String[] args);
```
I tillegg trenger vi å vite hva navnet til kommandoen er.
- [ ] Legg til følgende metodesignatur i `Command`:
```java
String getName();
```
### Vår første kommando: echo
Echo er en enkel kommando. Hvis man skriver kommandoen `echo foo bar`, så blir resultatet `foo bar `. Denne kommandoen vil du også finne i bash og lignende shell, og det eneste den gjør er å spytte tilbake argumentene den fikk som input.
* [ ] Opprett en klasse `CmdEcho` i pakken *no.uib.inf101.terminal*
* [ ] La `CmdEcho` implementere grensesnittet `Command`
* [ ] La `CmdEcho` implementere metodene som er definert i *Command* -gresesnittet. Husk å annotere hver av dem med `@Override`.
* [ ] La `getName()` alltid returnere `"echo"`.
* [ ] La `run(String[])` returnere en streng hvor hvert av argumentene i String[] -arrayen er limt sammen med mellomrom. Gå gjennom args med en foreach-løkke, og legg til et mellomrom etter hver av strengene. For eksempel, hvis input er `new String[] {"foo", "bar"}`, skal returverdien være `"foo bar "` (legg merke til ekstra mellomrom etter *bar*).
* [ ] I filen `TestCmdEcho` ([link](./src/test/java/no/uib/inf101/terminal/TestCmdEcho.java)), fjern kommentarene slik at testene blir aktivert.
✅ Du kan gå videre når testene i `TestCmdEcho` er aktivert og passerer.
## Installere kommandoer i SimpleShell
Vi skal nå installere kommandoer i SimpleShell. Til dette trenger vi å lagre forskjellige Command-objekter. Dette gjør vi i et oppslagsverk
- [ ] Opprett en instansvariabel `allCommands` i SimpleShell:
```java
private final HashMap<String, Command> allCommands = new HashMap<>();
```
Koden over oppretter en variabel som
* heter `allCommands`, og
* har typen `HashMap<String, Command>`. Det betyr at typen er et oppslagsverk hvor nøklene er av typen `String`, og verdiene er av typen `Command`.
I tillegg opprettes det et nytt objekt i klassen `HashMap` som da er et tomt oppslagsverk uten noen nøkler eller verdier enda. Det neste vi skal gjøre er å gjøre det mulig å legge til kommandoer i oppslagsverket.
- [ ] Opprett en metode i SimpleShell med signatur `public void installCommand(Command)`. La metoden hente ut navnet fra Command -objektet og opprett et nytt nøkkel-verdi -par i *allCommands* med navnet som nøkkel og Command-objektet som verdi. For eksempel:
```java
this.allCommands.put(command.getName(), command);
```
- [ ] I `Main::main` -metoden, kall `installCommand` på SimpleShell -objektet med et nytt `CmdEcho` -objekt som argument. Merk at du må endre typen til shell-variabelen slik at den har typen SimpleShell, ellers vil du ikke ha tilgang til installCommand -metoden.
```java
SimpleShell shell = new SimpleShell();
shell.installCommand(new CmdEcho());
Terminal gui = new Terminal(shell);
gui.run();
```
Vi har nå installert kommandoen *echo* i shellet vi bruker i Main-metoden. Det eneste som gjenstår før vi kan bruke echo-kommandoen er at `executeCommand` faktisk slår opp i oppslagsverket og kjører kommandoen.
- [ ] Modifiser `executeCommand` slik at den slår opp på kommandoen og kaller run dersom den fant en kommando med det gitte kommandonavnet.
```java
Command command = this.allCommands.get(commandName);
if (command != null) {
return command.run(args);
} else if (/* ... */) {
// ...
} else {
return "Command not found: \"" + commandName + "\"";
}
```
- [ ] Kjør `Main` og sjekk at echo-kommandoen virker i praksis.
- [ ] Fjern kommenteringen fra `TestSimpleShellEcho` ([link](./src/test/java/no/uib/inf101/terminal/TestSimpleShellEcho.java)) slik at testen blir aktiv.
✅ Du er ferdig med den obligatoriske delen av laben når testen i `TestSimpleShellEcho` er aktivert og passerer (i tillegg til at testene i `TestCmdEcho`, `TestSimpleShell` og `TestTextAnswers` fremdeles passerer).
## Frivillige forbedringer
### `exit`: en annen enkel kommando
- [ ] Opprett en ny klasse `CmdExit` etter samme mønster som `CmdEcho`, som også implementerer *Command* -grensesnittet.
- [ ] I run-metoden, gjør et kall til `System.exit(0);`
- [ ] Installer kommandoen i `Main::main` på samme måte som tidligere.
- [ ] Sjekk at det fungerer å lukke programmet ved å gi kommandoen `exit`.
### `pwd`, `cd`, og `ls`: kommandoer som trenger kontekst
Vi skal opprette egne klasser for hver av metodene `pwd`, `cd` og `ls`. Dette er kommandoer som har behov for å vite konteksten shellet kjører i. Vi gjør dette ved at SimpleShell gir disse kommandoene en kontekst når de blir installert.
- [ ] I `Command`: legg til en metode-signatur for å sette kontekst.
```java
default void setContext(Context context) { /* do nothing */ };
```
Denne linjen oppretter en metode i grensesnittet med en *standard* (default) implementasjon (som altså her er å ikke gjøre noen ting som helst dersom metoden blir kalt). Dette innebærer imidlertid at vi nå kan kalle på `setContext` dersom vi har å gjøre med et `Command`-objekt.
- [ ] I `SimpleShell::installCommand`, gjør et kall til *setContext*:
```java
command.setContext(this.context);
```
Vi er nå klare til å opprette klassene `CmdLs`, `CmdPwd` og `CmdCd` som alle implementerer *Command* -grensesnittet.
- [ ] La disse klassene ha en instansvariabel for kontekst, og la dem overskrive `setContext` -metoden slik at denne instansvariabelen bli initiert med en verdi når metoden kalles.
- [ ] Kopier funksjonaliteten fra de tilsvarende metodene i SimpleShell inn i run-metodene i de nye klassene.
- [ ] Fjern metodene fra SimpleShell (inkludert sekvensen med else-if i executeCommand), og installer dem i stedet i `Main::main` på samme måte som vi gjorde for echo -kommandoen
- [ ] Sjekk at testene fremdeles passerer og at de fremdeles virker i terminal-gui'en
### `man`: kommando for å lese manualen
* `man command` gir oss manualen til kommandoen `command`.
- [ ] La `Command` -grensesnittet ha en metode `String getManual()` som returnerer instruksjoner for hvordan kommandoen brukes
- [ ] La `Command` -grensesnittet ha en default-metode `void setCommandContext(Map<String, Command>)` med en standard-implementasjon som ikke gjør noen ting.
- [ ] I `SimpleShell::installCommand`, gjør et kall til setCommandContext med this.allCommands som argument.
- [ ] I `CmdMan`, la det være en instansvariabel av typen `Map<String, Command>`, og initer denne i `setCommandContext`.
- [ ] I `run` -metoden til `CmdMan`, hent ut riktig Command-objekt fra nevnte instansvariabel og skriv ut resultatet av getManual() kalt på dette objektet.
### Trykk backspace for å fjerne bakerste bokstav i kommandoen
Undersøk metoden `SimpleShell::keyPressed` og se hvordan ulike taster håndteres. Legg til funskjonalitet slik at når backspace trykkes fjernes bakerste bokstav i kommandoen.
> Hint: sjekk hvilken verdi som kommer når du trykker på backspace ved å legge til
`System.out.println("Keycode pressed: '" + ((int) key) + "'");` i begynnelsen av keyPressed-metoden. Start programmet, trykk backspace og se hva som skrives ut. Dette vil være et tall, siden vi *castet* key-variabelen til en `int`.
>
> Når du senere ønsker å legge til en betingelse i programflyten, kan du også sammenligne castet verdi, slik: `((int) key) == /* tallet her */`
### Starte java-programmer fra SimpleShell
Det neste steget for å få et fullt funksjonelt shell er muligheten til å starte og avslutte andre programmer, kontrollere hva disse programmene får som input, og la dem gi oss output i sanntid. Hva som skal til for å klare alle disse oppgavene går utenfor pensum i INF101, og er ikke støttet av Terminal-klassen vår.
Likevel kan vi gi en liten smakebit, nemlig hvordan vi kan kjøre andre *java* -programmer med den begrensning at de ikke er basert på interaktiv input i konsollen.
#### Hello World
- [ ] Opprett en klasse `HelloWorld` som skriver ut `"Hello World!"` til skjermen. Denne skal du kjenne igjen fra tidligere:
```java
package no.uib.inf101.terminal;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
```
- [ ] Opprett en klasse `CmdJavaProgram` og kopier inn koden under (avhengig av hvor mange metoder du har i `Command` -grensesnittet kan det være du må legge til en metode). Du trenger ikke å forstå alle deler av hva koden gjøre.
```java
package no.uib.inf101.terminal;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
public class CmdJavaProgram implements Command {
private final Class<?> mainClass;
private final String commandName;
/**
* Create a command from a Java program. Programs that read from
* standard input are not supported, but printing to standard
* output (i.e. using System.out to print) is ok.
*
* @param commandName The name of the command
* @param mainClass The class containing a main(String[]) method
*/
public JavaProgram(String commandName, Class<?> mainClass) {
this.mainClass = mainClass;
this.commandName = commandName;
}
@Override
public String getName() {
return this.commandName;
}
@Override
public String run(String[] args) {
// Remember original System.out and System.err
final PrintStream orgOut = System.out;
final PrintStream orgErr = System.err;
try {
// Prepare for capturing the output of the program
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream newOut = new PrintStream(out, true, StandardCharsets.UTF_8);
System.setOut(newOut);
System.setErr(newOut);
// Invoke main method of the class for which this command was created
Method main = this.mainClass.getMethod("main", String[].class);
main.invoke(null, new Object[] {args});
// Convert the captured output to a string and return it
return out.toString(StandardCharsets.UTF_8);
} catch (NoSuchMethodException e) {
return "No main method found in class " + this.mainClass.getName();
} catch (Exception e) {
return e.toString();
} finally {
// Restore the original System.out and System.err
System.setOut(orgOut);
System.setErr(orgErr);
}
}
}
```
Så gjenstår det å installere HelloWorld som en kommando `"hello"`.
- [ ] I `Main::main`, installer HelloWorld som en kommando:
```java
shell.installCommand(new CmdJavaProgram("hello", HelloWorld.class));
```
✅ Sjekk at du kan kjøre programmet, og at kommandoen `"hello"` skriver ut `Hello World!` i GUI'en.
PS: Prøv også:
```java
shell.installCommand(new CmdJavaProgram("new", Main.class));
```
Hva er det som skjer?
### Forbedret `ls`: `ls -l`, `ls -a`, `ls path/to/folder`
I bash har kommandoen `ls` flere muligheter enn det vi så langt har laget. For eksempel:
* elementene vises i sortert rekkefølge
* `ls -l` vil vise elementene med linjeskift `'\n'` mellom seg i stedet for mellomrom `' '`
* `ls -a` vil vise skjulte filer, mens vanlig `ls` kun viser filer som ikke er skjulte.
* `ls -la` er en kombinasjon av de to over
* `ls path/to/folder` vil vise filene i mappen `cwd/path/to/folder`.
Det kan være en fin øvelse å gjenskape dette for vår `ls` -kommando.
### Flere kommandoer som trenger kontekst: touch, mkdir, cat, rm, mv, cp
* `touch filename` oppretter en ny tom fil med det gitte navnet (hvis den ikke finnes fra før)
* `mkdir dirname` oppretter en ny mappe med det gitte navnet (hvis den ikke finnes fra før)
* `cat filename` returnerer tekst-innholdet i den gitte filen som en streng
* `rm filname` sletter en fil eller en tom mappe (forsiktig når du tester med denne!)
* `rm -r foldername` sletter en mappe og alt innholdet i den (veldig forsiktig når du tester med denne!)
* `mv source target` endrer navn på filen eller mappen *source* til filnavnet/mappenavnet *target*. Dette kan innebære flytting hvis target er en sti til en annen mappe. Dersom *target* er en mappe som finnes fra før, flyttes *source* -filen/mappen til *target* -mappen og beholder sitt opprinnelige navn.
* `cp source target` det samme som mv, men lager en kopi i stedet for å flytte.
### `grep`: en bonus-utfordring
Grep er på mange måter *cat* med inkludert filter. Den skriver kun ut de linjene som har innhold som matcher søkeordet. Standard bruk:
`grep searchword filename`
Vi anbefaler alle å bli kjent med hvordan grep virker i shell som bash. De ambisiøse kan også implementere det de klarer av den til bruk i vårt eget SimpleShell.
* `grep -i searchword filename` ignorerer case, dvs søkeordet `abc` vil få treff på `aBC`
* `grep -v searchword filename` skriver ut alle linjene som *ikke* matcher søkeordet
* `grep searchword foldername` kjører grep på alle filer i mappen. I utskriften skrives navnet på filen ut først, og så linjene i den filen.
* `grep -l searchword foldername` skriver kun ut navnet på filene med innhold som matcher, uten å skrive ut selve treffene
* `grep -L searchword foldername` skriver kun ut navnet på filene *uten* innhold som matcher
* `grep -r searchword foldername` kjører grep på alle filer i mappen *og* på alle filer i alle undermapper i uendelig dypde.
Prøv deg frem og sammenlign med hva som skjer i bash. Les mer om grep [her](https://www.opensourceforu.com/2012/06/beginners-guide-gnu-grep-basics/) eller en annen introduksjon [her](https://danielmiessler.com/study/grep/).
#!/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