Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • Njal.Nordal/lab-3
  • elias.m.johansen/lab-3
  • David.Mo/lab-3
  • Henrik.Tennebekk/lab-3
  • Kjetil.Hole/lab-3
  • theodor.andreasen/lab-3
  • Julie.Hallan/lab-3
  • Leon.Dammann/lab-3-inf-101
  • K.Inci/lab-3
  • Oscar.Stromsli/inf-101-lab-3
  • ii/inf101/23v/students/lab-3
  • Jan.Brunner/lab-3-2023
  • Benjamin.Fossbakken/lab-3
  • eivind.hjertholm/lab-3
  • Jacob.Grahm-Haga/lab-3
  • Eric.Bogevik/lab-3-new
  • Eskil.Yttri/lab-3-v-23
  • markus.trohjell/lab-3
  • Henrik.Dalsto/lab-3
  • Dag.Himle/lab-3
  • Olav.Eikanger/lab-3
  • Qingle.Xu/lab-3
  • Axel.Lundeby/lab-3
  • Theodor.Nissen-Meyer/lab-3
  • Jonathan.Christensen/lab-3
  • Yisahak.Sahilu/lab-3-2023
  • Kai.Waloen/lab-3
  • Viktor.Yordanov/lab-3
  • Magne.Qvarme/lab-3
  • Fernando.Aguilar/lab-3
  • R.Bortne/lab-3
  • Elias.Aronsen/lab-3-23-v
  • Halfdan.Hesthammer/lab-3-inf-101-v-23
  • ingmar.forsberg/lab-3
  • Julie.Mikkelsen/lab-3-jm
  • Natanem.Hailu/lab-3
  • Emma.Wergedahl/lab-3
  • Oscar.Larssen/lab-3
  • Martin.Fausa/lab-3
  • Mathias.Handeland/lab-3
  • Lauritz.Angeltveit/lab-3
  • V.Larsen/lab-3
  • Thomas.T.Jensen/lab-3
  • Stian.Bekkeheien/lab-3-inf-101
  • Kristian.Roynestad/lab-3
  • Cecilie.Efford/lab-3023
  • Olav.Skogen/lab-3
  • Havard.Kolve/lab-3
  • Per.Lande/lab-3
  • Idiris.Elmi/lab-3
  • Espen.Svasand/lab-3
  • ole-andreas.jensen/lab-3
  • Cecilie.Tveter/lab-3-inf-101-v-23
  • Marius.Jorgensen/lab-3
  • Stine.Fanebust/lab-3
  • Henrik.Skjeret/lab-3-v-23
56 results
Show changes
Commits on Source (23)
Showing
with 299 additions and 293 deletions
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.
...@@ -5,16 +5,10 @@ I denne lab'en skal vi utforske *grensesnitt*, og fortsette med å benytte oss a ...@@ -5,16 +5,10 @@ I denne lab'en skal vi utforske *grensesnitt*, og fortsette med å benytte oss a
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. 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. I denne lab'en skal vi modifisere 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.
> * **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
* [Anbefalte forberedelser](#anbefalte-forberedelser)
* [Ordbok: shell og terminal](#ordbok--shell-og-terminal)
* [Bli kjent med eksisterende kildekode](#bli-kjent-med-eksisterende-kildekode) * [Bli kjent med eksisterende kildekode](#bli-kjent-med-eksisterende-kildekode)
* [Kjøre SimpleShell](#kjøre-simpleshell) * [Kjøre SimpleShell](#kjøre-simpleshell)
* [Vis SimpleShell gjennom GUI](#vis-simpleshell-gjennom-gui) * [Vis SimpleShell gjennom GUI](#vis-simpleshell-gjennom-gui)
...@@ -23,28 +17,45 @@ I denne lab'en skal vi lage et enkelt shell for å navigere filsystemet som er l ...@@ -23,28 +17,45 @@ I denne lab'en skal vi lage et enkelt shell for å navigere filsystemet som er l
* [Definere metoder i Command](#definere-metoder-i-command) * [Definere metoder i Command](#definere-metoder-i-command)
* [Vår første kommando: echo](#vår-første-kommando--echo) * [Vår første kommando: echo](#vår-første-kommando--echo)
* [Installere kommandoer i SimpleShell](#installere-kommandoer-i-simpleshell) * [Installere kommandoer i SimpleShell](#installere-kommandoer-i-simpleshell)
* [Frivillige forbedringer](#frivillige-forbedringer) * [Anbefalte forbedringer](#anbefalte-forbedringer)
* [exit: en annen enkel kommando](#exit--en-annen-enkel-kommando) * [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) * [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) * [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) * [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) * [Starte Java-programmer fra SimpleShell](#starte-java-programmer-fra-simpleshell)
* [Flere frivillige forbedringer](#flere-frivillige-forbedringer)
* [Forbedret ls: ls -l, ls -a, ls path/to/folder](#forbedret-ls--ls--l--ls--a--ls-pathtofolder) * [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) * [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) * [grep: søking i filer](#fgrep--søking-i-filer)
## Anbefalte forberedelser
Les og forstå kursnotater som er spesielt relevante for denne lab'en:
* Kursnotater om [klasser og objekter](https://inf101.ii.uib.no/notat/objekter/) utgjør grunnlaget vi bygger videre på.
* Kursnotatene om [grensesnitt](https://inf101.ii.uib.no/notat/grensesnitt/) frem til og med avsnittet om polymorfisme er særlig relevante for denne lab'en.
* En skumlesning av avsnittet om [innfødte array'er](https://inf101.ii.uib.no/notat/array/#innf%C3%B8dt-array) i notatene om array og lister kan være greit også.
For de frivillige oppgavene på slutten er også følgende relevant:
* Avsnittet om [Filer](https://inf101.ii.uib.no/notat/inputoutput/#filer) i notatene om input og output.
## Ordbok: shell og terminal
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 starte 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.
## Bli kjent med eksisterende kildekode ## 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. - [ ] 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. - [ ] 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. 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 av *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)). - [ ] 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 ✅ 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 ## Kjøre SimpleShell
...@@ -52,13 +63,18 @@ I resten av oppgaven skal vi modifisere klassen [SimpleShell](./src/main/java/no ...@@ -52,13 +63,18 @@ I resten av oppgaven skal vi modifisere klassen [SimpleShell](./src/main/java/no
- [ ] Kjør testene i `TestSimpleShellStarter` ([link](./src/test/java/no/uib/inf101/terminal/TestSimpleShellStarter.java)) og se at de allerede passerer. - [ ] Kjør testene i `TestSimpleShellStarter` ([link](./src/test/java/no/uib/inf101/terminal/TestSimpleShellStarter.java)) og se at de allerede passerer.
> **Målet med laben.** Før vi gjør noen endringer i det hele tatt, støtter SimpleShell tre kommandoer: pwd, ls og cd. I løpet av laben skal vi oppdatere SimpleShell slik at
> * det virker sammen med GUI'en vår «Terminal», og
> * shellet virker med ubegrenset mange kommandoer.
>
> Når laben er gjennomført skal vi kunne installere så mange kommandoer vi vil i SimpleShell uten at vi trenger å endre ytterligere på kildekoden i SimpleShell-klassen utover det vi gjorde i løpet av denne lab'en.
### Vis SimpleShell gjennom GUI ### 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*. 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`. - [ ] La `SimpleShell` implementere grensesnittet `CommandLineInterface`.
- [ ] Opprett de metodene som må implementeres for å oppfylle kontrakten *CommandLineInterface* beskriver. Du kan enten - [ ] 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: - 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* (Eclipse/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*. - 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. - [ ] 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. - [ ] 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.
...@@ -91,12 +107,13 @@ Som pseudokode kan koden over tolkes slik: ...@@ -91,12 +107,13 @@ Som pseudokode kan koden over tolkes slik:
* Basert på verdien av `commandName`, finn ut hvilken kommando som skal utføres * 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. * 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å: 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 definere den nå:
### Opprette grensesnittet `Command` ### Opprette grensesnittet `Command`
- [ ] Opprett et nytt grensesnitt som heter `Command` i pakken *no.uib.inf101.terminal*. - [ ] 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. * 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.
* Eclipse: høyreklikk «no.uib.inf101.terminal» i prosjekt-navigatoren, og velg *new -> Interface*. I boksen som kommer opp, skriv *Command*. Koden som vises under skal nå ha blitt generert automatisk for deg.
* 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. * 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: Filen skal se nå se slik ut:
...@@ -156,9 +173,9 @@ Koden over oppretter en variabel som ...@@ -156,9 +173,9 @@ Koden over oppretter en variabel som
* heter `allCommands`, og * 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`. * 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. I tillegg opprettes det et nytt objekt i klassen `HashMap` som ved opprettelse 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: - [ ] Opprett en metode i SimpleShell med signatur `public void installCommand(Command 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 ```java
this.allCommands.put(command.getName(), command); this.allCommands.put(command.getName(), command);
...@@ -177,7 +194,7 @@ gui.run(); ...@@ -177,7 +194,7 @@ 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. 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. - [ ] Modifiser `executeCommand` slik at den slår opp på kommandoen og kaller run dersom den fant en kommando med det gitte kommandonavnet. Siden vi ikke har laget og installert kommandoer for pwd, cd og ls enda lar vi den gamle implementasjonen stå for disse kommandoene.
```java ```java
Command command = this.allCommands.get(commandName); Command command = this.allCommands.get(commandName);
if (command != null) { if (command != null) {
...@@ -197,18 +214,22 @@ if (command != null) { ...@@ -197,18 +214,22 @@ if (command != null) {
✅ 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). ✅ 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 ## Anbefalte forbedringer
Forbedringene i dette avsnittet er frivillige med tanke på å bestå laben, men er sterkt anbefalt å prøve seg på.
### `exit`: en annen enkel kommando ### `exit`: en annen enkel kommando
- [ ] Opprett en ny klasse `CmdExit` etter samme mønster som `CmdEcho`, som også implementerer *Command* -grensesnittet. - [ ] 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);` - [ ] I run-metoden, gjør et kall til `System.exit(0);`. Denne metoden kan returnere for eksempel null.
- [ ] Installer kommandoen i `Main::main` på samme måte som tidligere. - [ ] Installer kommandoen i `Main::main` på samme måte som tidligere.
- [ ] Sjekk at det fungerer å lukke programmet ved å gi kommandoen `exit`. - [ ] Sjekk at det fungerer å lukke programmet ved å gi kommandoen `exit`.
### `pwd`, `cd`, og `ls`: kommandoer som trenger kontekst ### `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. Vi skal opprette egne klasser for hver av kommandoene `pwd`, `cd` og `ls`. Dette er SimpleShell sine tre kjerne-kommandoer som alltid må være tilgengelig, og som allerede var implementert; men vi ønsker å benytte oss av samme struktur som de andre kommandoene (jo færre ting som håndteres på en spesiell måte, jo bedre).
Det som skiller disse kommandoene fra echo og exit, er at de har behov for å vite *konteksten* shellet kjører i. Vi løser dette ved at SimpleShell skal gi kommandoene som ønsker det tilgang til Context-objektet når de blir installert.
- [ ] I `Command`: legg til en metode-signatur for å sette kontekst. - [ ] I `Command`: legg til en metode-signatur for å sette kontekst.
```java ```java
...@@ -225,7 +246,7 @@ command.setContext(this.context); ...@@ -225,7 +246,7 @@ command.setContext(this.context);
Vi er nå klare til å opprette klassene `CmdLs`, `CmdPwd` og `CmdCd` som alle implementerer *Command* -grensesnittet. 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. - [ ] 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. - [ ] 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 - [ ] Fjern metodene fra SimpleShell (inkludert sekvensen med else-if i executeCommand), og installer i stedet kommandoene i *konstruktøren til SimpleShell*. Dette gjøres på samme måte som vi gjorde for echo -kommandoen i Main, men objektet vi kaller installCommand på heter *this* i stedet for *shell*: for eksempel `this.installCommand(new CmdLs())`.
- [ ] Sjekk at testene fremdeles passerer og at de fremdeles virker i terminal-gui'en - [ ] Sjekk at testene fremdeles passerer og at de fremdeles virker i terminal-gui'en
...@@ -233,11 +254,11 @@ Vi er nå klare til å opprette klassene `CmdLs`, `CmdPwd` og `CmdCd` som alle i ...@@ -233,11 +254,11 @@ Vi er nå klare til å opprette klassene `CmdLs`, `CmdPwd` og `CmdCd` som alle i
* `man command` gir oss manualen til kommandoen `command`. * `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 metode `String getManual()` som returnerer instruksjoner for hvordan kommandoen brukes. Du må nå oppdatere alle klassene som implementerer Command slik at de implementerer metoden og returnerer en hensiktsmessig hjelpetekst.
- [ ] La `Command` -grensesnittet ha en default-metode `void setCommandContext(Map<String, Command>)` med en standard-implementasjon som ikke gjør noen ting. - [ ] La `Command` -grensesnittet ha en default-metode `default 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 `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 `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. - [ ] I `run` -metoden til `CmdMan`, hent ut riktig Command-objekt fra nevnte instansvariabel og returner resultatet av getManual() kalt på dette objektet.
### Trykk backspace for å fjerne bakerste bokstav i kommandoen ### Trykk backspace for å fjerne bakerste bokstav i kommandoen
...@@ -268,7 +289,7 @@ public class HelloWorld { ...@@ -268,7 +289,7 @@ public class HelloWorld {
} }
``` ```
- [ ] 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. - [ ] 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å alt koden gjør.
```java ```java
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
...@@ -291,7 +312,7 @@ public class CmdJavaProgram implements Command { ...@@ -291,7 +312,7 @@ public class CmdJavaProgram implements Command {
* @param commandName The name of the command * @param commandName The name of the command
* @param mainClass The class containing a main(String[]) method * @param mainClass The class containing a main(String[]) method
*/ */
public JavaProgram(String commandName, Class<?> mainClass) { public CmdJavaProgram(String commandName, Class<?> mainClass) {
this.mainClass = mainClass; this.mainClass = mainClass;
this.commandName = commandName; this.commandName = commandName;
} }
...@@ -352,6 +373,10 @@ shell.installCommand(new CmdJavaProgram("new", Main.class)); ...@@ -352,6 +373,10 @@ shell.installCommand(new CmdJavaProgram("new", Main.class));
Hva er det som skjer? Hva er det som skjer?
## Flere frivillige forbedringer
Forbedringene under krever at du setter deg inn i `File` -klassen fra Java sitt standardbibliotek, og bruker `Context` -klassen som følger med dette prosjektet aktivt. Du kan lese litt om `File` i [kursnotatene](https://inf101.ii.uib.no/notat/inputoutput/#filer) eller slå opp i den [offisielle dokumentasjonen](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/File.html).
### Forbedret `ls`: `ls -l`, `ls -a`, `ls path/to/folder` ### 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: I bash har kommandoen `ls` flere muligheter enn det vi så langt har laget. For eksempel:
...@@ -373,19 +398,23 @@ Det kan være en fin øvelse å gjenskape dette for vår `ls` -kommando. ...@@ -373,19 +398,23 @@ Det kan være en fin øvelse å gjenskape dette for vår `ls` -kommando.
* `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. * `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. * `cp source target` det samme som mv, men lager en kopi i stedet for å flytte.
### `grep`: en bonus-utfordring ### `fgrep`: søking i filer
*Grep* og lillebroren *fgrep* er på mange måter *cat* med et søkefilter inkludert. Den skriver kun ut de linjene som har innhold som matcher søkeordet. Standard bruk:
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: `fgrep searchword filename`
`grep searchword filename` Vi anbefaler alle å bli kjent med hvordan grep/fgrep virker i bash. De ambisiøse kan også implementere det de klarer av fgrep til bruk i vårt eget SimpleShell:
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. * `fgrep searchword filename -n` viser linjenummer
* `fgrep searchword filename -i` ignorerer case, dvs søkeordet `abc` vil få treff på `aBC`
* `fgrep searchword filename -v` skriver ut alle linjene som *ikke* matcher søkeordet
* `fgrep searchword filename -c` skriver ut hvor mange linjer som matchet søkeordet
* `fgrep searchword *` kjører grep på alle filer i current working directory. Hvis kombinert med `-n` viser utskriften navnet på filen ut først, og så linjenummer i den filen.
* `fgrep searchword * -l` skriver kun ut navnet på filene med innhold som matcher, uten å skrive ut selve treffene
* `fgrep searchword * -L` skriver kun ut navnet på filene *uten* innhold som matcher
* `fgrep searchword foldername -r` kjører grep på alle filer i mappen *og* på alle filer i alle undermapper i uendelig dypde.
* `grep -i searchword filename` ignorerer case, dvs søkeordet `abc` vil få treff på `aBC` Flagg (delen av kommandoene som begynner med `-`) kan ofte kombineres, for eksempel vil `-ni` både vise linjenummer og ignorere case. Du trenger ikke håndtere søkeord som inneholder mellomrom i første omgang, det blir eventuelt en superbonusoppgave.
* `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/). Prøv deg frem og sammenlign med hva som skjer i bash. Les mer om grep i introduksjonen til [ryanstutorials](https://ryanstutorials.net/linuxtutorial/grep.php), [opensourceforu](https://www.opensourceforu.com/2012/06/beginners-guide-gnu-grep-basics/) eller [danielmiessler](https://danielmiessler.com/study/grep/).
...@@ -30,8 +30,11 @@ echo " PROJECT_VERSION: $PROJECT_VERSION" # version in pom, e.g. "1.0-SNAPSHOT" ...@@ -30,8 +30,11 @@ echo " PROJECT_VERSION: $PROJECT_VERSION" # version in pom, e.g. "1.0-SNAPSHOT"
echo "computed variables..." echo "computed variables..."
CURRENT_YEAR=$(date +'%Y') CURRENT_YEAR=$(date +'%Y')
echo " CURRENT_YEAR: $CURRENT_YEAR" echo " CURRENT_YEAR: $CURRENT_YEAR"
PATH_TO_MAIN_CLASS="target/classes/${MAIN_CLASS//'.'//}.class" #PATH_TO_MAIN_CLASS="target/classes/${MAIN_CLASS//'.'//}.class"
PATH_TO_MAIN_CLASS="target/classes/${APP_PACKAGE//'.'//}/"
echo " PATH_TO_MAIN_CLASS: $PATH_TO_MAIN_CLASS" echo " PATH_TO_MAIN_CLASS: $PATH_TO_MAIN_CLASS"
echo " pwd: "
pwd
# ------ SETUP DIRECTORIES AND FILES ---------------------------------------- # ------ SETUP DIRECTORIES AND FILES ----------------------------------------
# Remove previously generated java runtime and installers. Copy all required # Remove previously generated java runtime and installers. Copy all required
...@@ -54,6 +57,14 @@ cp "target/${MAIN_JAR}" target/installer/input/libs/ ...@@ -54,6 +57,14 @@ cp "target/${MAIN_JAR}" target/installer/input/libs/
## application. ## application.
echo "detecting required modules.." echo "detecting required modules.."
echo "$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"
detected_modules=$("$JAVA_HOME/bin/jdeps" \ detected_modules=$("$JAVA_HOME/bin/jdeps" \
-q \ -q \
--multi-release "${JAVA_VERSION}" \ --multi-release "${JAVA_VERSION}" \
...@@ -75,6 +86,14 @@ echo " detected modules: ${detected_modules}" ...@@ -75,6 +86,14 @@ echo " detected modules: ${detected_modules}"
# works with dependencies that are not fully modularized, yet. # works with dependencies that are not fully modularized, yet.
echo "creating java runtime image..." echo "creating java runtime image..."
echo "$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
"$JAVA_HOME/bin/jlink" \ "$JAVA_HOME/bin/jlink" \
--strip-native-commands \ --strip-native-commands \
--no-header-files \ --no-header-files \
...@@ -88,6 +107,21 @@ echo "creating java runtime image..." ...@@ -88,6 +107,21 @@ echo "creating java runtime image..."
# In the end we will find the package inside the target/installer directory. # In the end we will find the package inside the target/installer directory.
echo "creating installer of type $INSTALLER_TYPE..." echo "creating installer of type $INSTALLER_TYPE..."
echo "$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 \
"$JAVA_HOME/bin/jpackage" \ "$JAVA_HOME/bin/jpackage" \
--type "$INSTALLER_TYPE" \ --type "$INSTALLER_TYPE" \
--dest target/installer \ --dest target/installer \
......
...@@ -29,7 +29,8 @@ ECHO " PROJECT_NAME: %PROJECT_NAME%" ...@@ -29,7 +29,8 @@ ECHO " PROJECT_NAME: %PROJECT_NAME%"
ECHO " PROJECT_VERSION: %PROJECT_VERSION%" ECHO " PROJECT_VERSION: %PROJECT_VERSION%"
ECHO "computed variables..." ECHO "computed variables..."
SET PATH_TO_MAIN="target\classes\%MAIN_CLASS:.=\%.class" @REM SET PATH_TO_MAIN="target\classes\%MAIN_CLASS:.=\%.class"
SET PATH_TO_MAIN="target\classes\%APP_PACKAGE:.=\%"
ECHO " PATH_TO_MAIN: %PATH_TO_MAIN%" ECHO " PATH_TO_MAIN: %PATH_TO_MAIN%"
SET YEAR=%DATE:~6,4% SET YEAR=%DATE:~6,4%
ECHO " YEAR: %YEAR%" ECHO " YEAR: %YEAR%"
......
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<!-- Major project properties --> <!-- Major project properties -->
<groupId>no.uib.inf101.app</groupId> <groupId>no.uib.inf101.terminal</groupId> <!-- must match package of Main class -->
<artifactId>SamplePackagedSwingApp</artifactId> <artifactId>INF101ShellLab</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>Sample Application</name> <name>INF101 Shell Lab</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<properties> <properties>
...@@ -17,8 +17,8 @@ ...@@ -17,8 +17,8 @@
<java.version>17</java.version> <java.version>17</java.version>
<!-- Properties required for packaging application as JAR and installer --> <!-- Properties required for packaging application as JAR and installer -->
<app.main.class>no.uib.inf101.terminal.Main</app.main.class> <app.main.class>${groupId}.Main</app.main.class> <!-- name of main class -->
<app.vendor>Torstein Strømme</app.vendor> <!-- copyright holder --> <app.vendor>Torstein Strømme</app.vendor> <!-- replace with your name -->
<app.version>1.0.0</app.version> <!-- version displayed in "about" --> <app.version>1.0.0</app.version> <!-- version displayed in "about" -->
<app.installer.macosx.type>dmg</app.installer.macosx.type> <!-- dmg, pkg --> <app.installer.macosx.type>dmg</app.installer.macosx.type> <!-- dmg, pkg -->
<app.installer.windows.type>msi</app.installer.windows.type> <!-- msi, exe --> <app.installer.windows.type>msi</app.installer.windows.type> <!-- msi, exe -->
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
<maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version> <maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
<maven.dependency.plugin.version>3.4.0</maven.dependency.plugin.version> <maven.dependency.plugin.version>3.4.0</maven.dependency.plugin.version>
<maven.jar.plugin.version>3.3.0</maven.jar.plugin.version> <maven.jar.plugin.version>3.3.0</maven.jar.plugin.version>
<maven.surefire.plugin.version>3.0.0-M5</maven.surefire.plugin.version>
<exec.maven.plugin.version>1.6.0</exec.maven.plugin.version> <exec.maven.plugin.version>1.6.0</exec.maven.plugin.version>
<!-- Computed properties --> <!-- Computed properties -->
...@@ -99,6 +100,17 @@ ...@@ -99,6 +100,17 @@
</archive> </archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven.surefire.plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins> </plugins>
</build> </build>
...@@ -125,7 +137,7 @@ ...@@ -125,7 +137,7 @@
</executions> </executions>
<configuration> <configuration>
<workingDirectory>${project.basedir}</workingDirectory> <workingDirectory>${project.basedir}</workingDirectory>
<executable>./build_app_mac.sh</executable> <executable>./make/build_app_mac.sh</executable>
<environmentVariables> <environmentVariables>
<APP_PACKAGE>${project.groupId}</APP_PACKAGE> <APP_PACKAGE>${project.groupId}</APP_PACKAGE>
<ABOUT_NAME>${project.name}</ABOUT_NAME> <ABOUT_NAME>${project.name}</ABOUT_NAME>
...@@ -168,7 +180,7 @@ ...@@ -168,7 +180,7 @@
</executions> </executions>
<configuration> <configuration>
<workingDirectory>${project.basedir}</workingDirectory> <workingDirectory>${project.basedir}</workingDirectory>
<executable>build_app_windows.bat</executable> <executable>./make/build_app_windows.bat</executable>
<environmentVariables> <environmentVariables>
<APP_PACKAGE>${project.groupId}</APP_PACKAGE> <APP_PACKAGE>${project.groupId}</APP_PACKAGE>
<APP_VENDOR>${app.vendor}</APP_VENDOR> <APP_VENDOR>${app.vendor}</APP_VENDOR>
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - CommandLineInterface.java
//
// Grensesnittet CommanLineInterface beskriver metoder for input og
// output til et program som virker med et tekstbasert grensesnitt.
// Du trenger ikke gjøre noen endringer i denne filen for denne lab'en.
/** /**
* A command line interface is a program with a text-based user interface. * 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 * The user can enter keys as input, and the program will respond by giving
...@@ -10,13 +16,14 @@ public interface CommandLineInterface { ...@@ -10,13 +16,14 @@ public interface CommandLineInterface {
/** /**
* Called when a key is pressed. * Called when a key is pressed.
* *
* @param key The key that was pressed * @param key the key that was pressed
*/ */
void keyPressed(char key); void keyPressed(char key);
/** /**
* Get the text to display on the screen. * Get the text to display on the screen.
* @return The text to display *
* @return the text to display
*/ */
String getScreenContent(); String getScreenContent();
} }
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - Context.java
//
// Denne filen inneholder kode som navigerer et filsystem. Du trenger
// ikke gjøre noen endringer i denne filen for denne lab'en (med mindre
// du selv ønsker).
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
public class Context { public class Context {
////////////////////////
// Instance variables
////////////////////////
private final File home; private final File home;
private File cwd; private File cwd;
////////////////////////
// Constructors
////////////////////////
/**
* Create a new context with the java current working directory as
* home.
*/
public Context() {
this(new File(System.getProperty("user.dir")));
}
/**
* Create a new context with the given directory as home.
*
* @param home the home directory.
*/
public Context(File home) { public Context(File home) {
try { try {
this.home = home.getCanonicalFile(); this.home = home.getCanonicalFile();
...@@ -18,27 +44,50 @@ public class Context { ...@@ -18,27 +44,50 @@ public class Context {
} }
} }
////////////////////////
// Instance methods
////////////////////////
/**
* Go to the given path, if it exists. The path can be relative to
* the current working directory, or absolute.
*
* @param path the path to go to.
* @return true if the path exists, false otherwise
*/
public boolean goToPath(String path) { public boolean goToPath(String path) {
File newDir = new File(cwd, path); File newDir = new File(this.cwd, path);
if (!newDir.isDirectory()) { if (!newDir.isDirectory()) {
return false; return false;
} }
try { try {
cwd = newDir.getCanonicalFile(); this.cwd = newDir.getCanonicalFile();
return true;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return true;
} }
/**
* Get the current working directory.
*
* @return the current working directory.
*/
public File getCwd() { public File getCwd() {
return this.cwd; return this.cwd;
} }
/** Set the current working directory to the home directory.*/
public void goToHome() { public void goToHome() {
this.cwd = this.home; this.cwd = this.home;
} }
/**
* Check if the current working directory is the home directory.
*
* @return true if the current working directory is the home
* directory, false otherwise.
*/
public boolean isAtHome() { public boolean isAtHome() {
return Objects.equals(this.cwd, this.home); return Objects.equals(this.cwd, this.home);
} }
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - DynamicShell.java
//
// Denne koden er gitt som et eksempel på en klasse som implementerer
// CommandLineInterface. Du trenger ikke gjøre noen endringer i denne
// filen for denne lab'en (med mindre du selv ønsker).
public class DummyShell implements CommandLineInterface { public class DummyShell implements CommandLineInterface {
private String screenContent = "$ "; private String screenContent = "$ ";
@Override @Override
public void keyPressed(char keyCode) { public void keyPressed(char key) {
if (keyCode == '\n') { if (key == '\n') {
screenContent += "\n$ "; screenContent += "\n$ ";
} else { } else {
screenContent += keyCode; screenContent += key;
} }
} }
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - EchoShell.java
//
// Denne koden er gitt som et eksempel på en klasse som implementerer
// CommanLineInterface. Du trenger ikke gjøre noen endringer i denne
// filen for denne lab'en (med mindre du selv ønsker).
import java.util.ArrayList; import java.util.ArrayList;
public class EchoShell implements CommandLineInterface { public class EchoShell implements CommandLineInterface {
...@@ -7,13 +13,13 @@ public class EchoShell implements CommandLineInterface { ...@@ -7,13 +13,13 @@ public class EchoShell implements CommandLineInterface {
String currentLine = ""; String currentLine = "";
@Override @Override
public void keyPressed(char keyCode) { public void keyPressed(char key) {
if (keyCode == '\n') { if (key == '\n') {
outputLines.add("$ " + currentLine); outputLines.add("$ " + currentLine);
outputLines.add("Oh, an echo! listen: " + currentLine); outputLines.add("Oh, an echo! listen: " + currentLine);
currentLine = ""; currentLine = "";
} else { } else {
currentLine += keyCode; currentLine += key;
} }
} }
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - Main.java
// Dette er filen som inneholder main-metoden.
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - SimpleShell.java
//
// Dette er klassen vi skal forbedre i denne lab'en. Slik koden er
// allerede før du begynner på laben, støtter den tre kommandoer:
//
// - cd: Bytt til en annen mappe
// - ls: List opp filer i mappen
// - pwd: Vis sti til nåværende mappe
//
// Vi skal endre denne klassen slik at den
// - kan vises av Terminal.java
// - kan støtte ubegrenset mange kommandoer
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.Objects; import java.util.Objects;
// TODO: Let SimpleShell implement CommandLineInterface // TODO 1: Let SimpleShell implement CommandLineInterface
public class SimpleShell { public class SimpleShell {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
...@@ -14,20 +28,24 @@ public class SimpleShell { ...@@ -14,20 +28,24 @@ public class SimpleShell {
/** The prompt to show before each command */ /** The prompt to show before each command */
private final String prompt = "$ "; private final String prompt = "$ ";
/** The context variable contains cwd and home directories etc. */ /** The context variable contains cwd and home directories etc. */
private final Context context = new Context( private final Context context = new Context();
new File(System.getProperty("user.dir"))
);
/** A list of historic commands and their outputs */ /** A list of historic commands and their outputs */
private final ArrayList<String> history = new ArrayList<>(); private final List<String> history = new ArrayList<>();
/** The command currently being typed */ /** The command currently being typed */
private String currentCommand = ""; private String currentCommand = "";
// TODO 4: Create instance variable storing Command objects
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/// Public methods ////// /// Public instance methods //////
/// (methods expected to be used by someone outside this class) ////// /// (methods expected to be used by someone outside this class) //////
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// TODO: rename method to fit new interface, annotate with @Override /** Constructor for SimpleShell */
public SimpleShell() {
// TODO 7-8-9: Install core commands SimpleShell supports (pwd, ls, cd)
}
// TODO 2: rename method to fit new interface, annotate with @Override
// Note: methods with @Override generally do not need javadoc comments, // Note: methods with @Override generally do not need javadoc comments,
// since the javadoc comment is inherited. You should hence remove the // since the javadoc comment is inherited. You should hence remove the
// javadoc comment here unless there is something special about this // javadoc comment here unless there is something special about this
...@@ -42,10 +60,12 @@ public class SimpleShell { ...@@ -42,10 +60,12 @@ public class SimpleShell {
this.processCurrentCommandLine(); this.processCurrentCommandLine();
} else if (key >= ' ' && key <= '~') { } else if (key >= ' ' && key <= '~') {
this.currentCommand += key; this.currentCommand += key;
} else {
// Some special key was pressed (e.g. shift, ctrl), we ignore it
} }
} }
// TODO: rename method to fit new interface, annotate with @Override // TODO 3: rename method to fit new interface, annotate with @Override
/** /**
* Get the text which the terminal should display * Get the text which the terminal should display
* *
...@@ -61,6 +81,8 @@ public class SimpleShell { ...@@ -61,6 +81,8 @@ public class SimpleShell {
return s; return s;
} }
// TODO 5: Add method to install a command
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/// Private methods /////////////////// /// Private methods ///////////////////
/// (helper methods used internally in this class) /////////////////// /// (helper methods used internally in this class) ///////////////////
...@@ -98,7 +120,8 @@ public class SimpleShell { ...@@ -98,7 +120,8 @@ public class SimpleShell {
* @return The output of the command * @return The output of the command
*/ */
private String executeCommand(String commandName, String[] args) { private String executeCommand(String commandName, String[] args) {
// TODO: Change sequence of if/else if below to a lookup in a map // TODO 6: Call run on Command object for given commandName if present
// TODO 7-8-9: Remove if's for cd, ls, pwd once installed as commands
if (Objects.equals(commandName, "pwd")) { if (Objects.equals(commandName, "pwd")) {
return this.doPwd(args); return this.doPwd(args);
} else if (Objects.equals(commandName, "cd")) { } else if (Objects.equals(commandName, "cd")) {
...@@ -110,12 +133,12 @@ public class SimpleShell { ...@@ -110,12 +133,12 @@ public class SimpleShell {
} }
} }
// TODO: remove this method and replace it with Command -type object // TODO 7: remove this method and replace it with Command -type object
private String doPwd(String[] args) { private String doPwd(String[] args) {
return this.context.getCwd().getAbsolutePath(); return this.context.getCwd().getAbsolutePath();
} }
// TODO: remove this method and replace it with Command -type object // TODO 8: remove this method and replace it with Command -type object
private String doCd(String[] args) { private String doCd(String[] args) {
if (args.length == 0) { if (args.length == 0) {
this.context.goToHome(); this.context.goToHome();
...@@ -131,7 +154,7 @@ public class SimpleShell { ...@@ -131,7 +154,7 @@ public class SimpleShell {
} }
} }
// TODO: remove this method and replace it with Command -type object // TODO 9: remove this method and replace it with Command -type object
private String doLs(String[] args) { private String doLs(String[] args) {
File cwd = this.context.getCwd(); File cwd = this.context.getCwd();
String s = ""; String s = "";
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - Terminal.java
//
// Denne filen inneholder kode som tegner et vindu på skjermen, som
// viser et CommandLineInterface -program. Du er ikke forventet å
// forstå denne koden denne uken, og du trenger ikke gjøre noen
// endringer i denne filen for denne lab'en (med mindre du selv ønsker).
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.KeyAdapter; import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
/**
* A simple terminal GUI for interacting with command line interfaces.
*/
public class Terminal extends JPanel { public class Terminal extends JPanel {
private final CommandLineInterface terminal; ////////////////////////
// Instance variables
////////////////////////
/** The command line interface to interact with. */
private final CommandLineInterface cli;
////////////////////////
// Constructor
////////////////////////
/** Create a new terminal GUI for the given command line interface. */
public Terminal(CommandLineInterface cli) { public Terminal(CommandLineInterface cli) {
this.terminal = cli; this.cli = cli;
this.setPreferredSize(new Dimension(400, 300)); this.setPreferredSize(new Dimension(400, 300));
this.setFocusable(true); this.setFocusable(true);
this.addKeyListener(new KeyAdapter() { this.addKeyListener(new KeyAdapter() {
@Override @Override
public void keyPressed(KeyEvent e) { public void keyPressed(KeyEvent e) {
Terminal.this.terminal.keyPressed(e.getKeyChar()); Terminal.this.cli.keyPressed(e.getKeyChar());
Terminal.this.repaint(); Terminal.this.repaint();
} }
}); });
} }
////////////////////////
// Instance methods
////////////////////////
@Override @Override
public void paintComponent(Graphics g) { public void paintComponent(Graphics g) {
super.paintComponent(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.setColor(Color.BLACK);
g.setFont(new Font("Monospaced", Font.PLAIN, 12)); g.setFont(new Font("Monospaced", Font.PLAIN, 12));
int y = lineHeight; int lineHeight = g.getFontMetrics().getHeight() + 2;
// Iterate through the last 'lines' lines of the content // Tegn teksten på skjermen, linje for linje. Potensiell forbedring:
String[] linesOfContent = content.split("\n"); // hvis det er for mange linjer, vis kun de siste av dem.
for (int i = Math.max(0, linesOfContent.length - lines); i < linesOfContent.length; i++) { String content = this.cli.getScreenContent();
g.drawString(linesOfContent[i], 5, y); int y = 20;
for (String line : content.split("\n")) {
g.drawString(line, 5, y);
y += lineHeight; y += lineHeight;
} }
} }
/** Run the terminal GUI in a window frame. */
public void run() { public void run() {
JFrame frame = new JFrame("INF101 Terminal"); JFrame frame = new JFrame("INF101 Terminal");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
......
package no.uib.inf101.terminal; package no.uib.inf101.terminal;
// UiB INF101 ShellLab - TextAnswers.java
//
// I denne filen skal du besvare spørsmålene under. Du kan sjekke
// svarene dine ved å kjøre testen TextAnswersTest.java.
public class TextAnswers { public class TextAnswers {
/* /**
* Consider the following code: * Consider the following code:
*
* CommandLineInterface cli = new DummyShell(); * CommandLineInterface cli = new DummyShell();
*
* What is the type of the variable cli?
*/ */
/** What is the type of the variable cli? */
static final String q1 = ""; static final String q1 = "";
/** In which class is the object cli refers to? */ /**
* Consider the following code:
* CommandLineInterface cli = new DummyShell();
*
* In which class is the object cli refers to?
*/
static final String q2 = ""; static final String q2 = "";
/** True or false: CommandLineInterface is both a type and interface. */ /**
* Consider the following code:
* CommandLineInterface cli = new DummyShell();
*
* true or false: CommandLineInterface is both a type and an interface.
*/
static final Boolean q3 = null; static final Boolean q3 = null;
/** True or false: DummyShell is both a class and a type. */ /**
* Consider the following code:
* CommandLineInterface cli = new DummyShell();
*
* true or false: DummyShell is both a class and a type.
*/
static final Boolean q4 = null; static final Boolean q4 = null;
} }
...@@ -30,7 +30,7 @@ public class TestSimpleShellEcho { ...@@ -30,7 +30,7 @@ public class TestSimpleShellEcho {
// shell.keyPressed('r'); // shell.keyPressed('r');
// shell.keyPressed('\n'); // shell.keyPressed('\n');
// //
// String expected = "$ echo foo bar \nfoo bar \n$ "; // String expected = "$ echo foo bar\nfoo bar \n$ ";
// assertEquals(expected, shell.getScreenContent()); // assertEquals(expected, shell.getScreenContent());
// } // }
} }