From b28425af4daadec592b25fe3d92b9510870be6cb Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Wed, 13 Mar 2019 12:31:51 +0200 Subject: [PATCH 01/26] printAveragePriceOfPayableLocations called inside Main --- 3/src/main/java/Main.java | 1 + 1 file changed, 1 insertion(+) diff --git a/3/src/main/java/Main.java b/3/src/main/java/Main.java index 63a047c..2ef09a0 100644 --- a/3/src/main/java/Main.java +++ b/3/src/main/java/Main.java @@ -31,6 +31,7 @@ public static void main(String[] args) { TravelMapService travelMapService = new TravelMapService(map); travelMapService.printVisitableButNotPlayableLocations(); + travelMapService.printAveragePriceOfPayableLocations(); } From 35fff0f5063099220a168b0367defa810f5cac98 Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 18:24:41 +0200 Subject: [PATCH 02/26] bonus lab3 --- 3/src/main/java/Main.java | 6 ++ 3/src/main/java/graph/Edge.java | 31 +++++++++ .../java/service/FloydWarshallService.java | 63 +++++++++++++++++++ 3/src/main/java/service/GreedyService.java | 5 -- 4 files changed, 100 insertions(+), 5 deletions(-) create mode 100644 3/src/main/java/service/FloydWarshallService.java delete mode 100644 3/src/main/java/service/GreedyService.java diff --git a/3/src/main/java/Main.java b/3/src/main/java/Main.java index 2ef09a0..9b97e69 100644 --- a/3/src/main/java/Main.java +++ b/3/src/main/java/Main.java @@ -1,4 +1,5 @@ import model.*; +import service.FloydWarshallService; import service.TravelMapService; import java.time.DayOfWeek; @@ -33,6 +34,11 @@ public static void main(String[] args) { travelMapService.printVisitableButNotPlayableLocations(); travelMapService.printAveragePriceOfPayableLocations(); + + System.out.println("Distances:"); + FloydWarshallService floydWarshallService = new FloydWarshallService(); + floydWarshallService.floydWarshall(map.getNodes(),map.getEdges()); + floydWarshallService.printDistances(); } private static void setupMap(Hotel v1, Museum v2, Museum v3, Church v4, Church v5, Restaurant v6, TravelMap map) { diff --git a/3/src/main/java/graph/Edge.java b/3/src/main/java/graph/Edge.java index e6138d8..63ab20a 100644 --- a/3/src/main/java/graph/Edge.java +++ b/3/src/main/java/graph/Edge.java @@ -24,4 +24,35 @@ public Edge(Node startingNode, Node endingNode, int cost, boolean isTwoWay) { this.cost = cost; } + public Node getStartingNode() { + return startingNode; + } + + public void setStartingNode(Node startingNode) { + this.startingNode = startingNode; + } + + public Node getEndingNode() { + return endingNode; + } + + public void setEndingNode(Node endingNode) { + this.endingNode = endingNode; + } + + public boolean isTwoWay() { + return isTwoWay; + } + + public void setTwoWay(boolean twoWay) { + isTwoWay = twoWay; + } + + public int getCost() { + return cost; + } + + public void setCost(int cost) { + this.cost = cost; + } } diff --git a/3/src/main/java/service/FloydWarshallService.java b/3/src/main/java/service/FloydWarshallService.java new file mode 100644 index 0000000..049471d --- /dev/null +++ b/3/src/main/java/service/FloydWarshallService.java @@ -0,0 +1,63 @@ +package service; + +import graph.Edge; +import graph.Node; +import javafx.util.Pair; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FloydWarshallService { + + private Map, Integer> distances = new HashMap<>(); + + + public void floydWarshall(List nodes, List edges) { + + edges.forEach(edge -> { + Node source = edge.getStartingNode(); + Node destination = edge.getEndingNode(); + distances.putIfAbsent(new Pair<>(source, destination), edge.getCost()); + if (edge.isTwoWay()) { + distances.putIfAbsent(new Pair<>(destination, source), edge.getCost()); + } + }); + + nodes.forEach(intermediate -> { + nodes.forEach(source -> { + nodes.forEach(destination -> { + if (thereAreEdgesBetween(intermediate, source, destination)) { + Integer distanceThroughIntermediate = getDistance(intermediate, source) + getDistance(destination, intermediate); + Integer directDistance = getDistance(destination, source); + if (distanceThroughIntermediate < directDistance) { + updateDistance(source, destination, distanceThroughIntermediate); + } + } + }); + }); + }); + } + + private void updateDistance(Node source, Node destination, Integer distanceThroughIntermediate) { + distances.replace(new Pair<>(source, destination), distanceThroughIntermediate); + } + + private Integer getDistance(Node intermediate, Node source) { + return distances.get(new Pair<>(source, intermediate)); + } + + private boolean thereAreEdgesBetween(Node intermediate, Node source, Node destination) { + return distances.containsKey(new Pair<>(source, destination)) && + distances.containsKey(new Pair<>(source, intermediate)) && + distances.containsKey(new Pair<>(intermediate, destination)); + } + + public void printDistances(){ +// distances.forEach((n1, n2) -> System.out.println( "From "+ n1.getKey() + " to " n2.g" distance " + elem.getValue())); + distances.forEach((key,val)->{ + System.out.println("From " + key.getKey().getName() + " to " + + key.getValue().getName() + " the distance is " + val); + }); + } +} diff --git a/3/src/main/java/service/GreedyService.java b/3/src/main/java/service/GreedyService.java deleted file mode 100644 index c535de1..0000000 --- a/3/src/main/java/service/GreedyService.java +++ /dev/null @@ -1,5 +0,0 @@ -package service; - -public class GreedyService { - -} From 0c121e45e55064508744e8712a4cb9fed2072580 Mon Sep 17 00:00:00 2001 From: OnateK Date: Fri, 15 Mar 2019 18:29:14 +0200 Subject: [PATCH 03/26] graph --- _4/src/main/java/Graph.java | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 _4/src/main/java/Graph.java diff --git a/_4/src/main/java/Graph.java b/_4/src/main/java/Graph.java new file mode 100644 index 0000000..5e2b807 --- /dev/null +++ b/_4/src/main/java/Graph.java @@ -0,0 +1,2 @@ +public class Graph { +} From 94cc7dce1fe1e39a163dde4268836b735f66983a Mon Sep 17 00:00:00 2001 From: OnateK Date: Fri, 15 Mar 2019 18:31:47 +0200 Subject: [PATCH 04/26] basic clasess --- _4/src/main/java/Catalog.java | 2 ++ _4/src/main/java/CatalogIO.java | 2 ++ _4/src/main/java/Main.java | 5 +++++ 3 files changed, 9 insertions(+) create mode 100644 _4/src/main/java/Catalog.java create mode 100644 _4/src/main/java/CatalogIO.java create mode 100644 _4/src/main/java/Main.java diff --git a/_4/src/main/java/Catalog.java b/_4/src/main/java/Catalog.java new file mode 100644 index 0000000..d0253b1 --- /dev/null +++ b/_4/src/main/java/Catalog.java @@ -0,0 +1,2 @@ +public class Catalog { +} diff --git a/_4/src/main/java/CatalogIO.java b/_4/src/main/java/CatalogIO.java new file mode 100644 index 0000000..2e076e2 --- /dev/null +++ b/_4/src/main/java/CatalogIO.java @@ -0,0 +1,2 @@ +public class CatalogIO { +} diff --git a/_4/src/main/java/Main.java b/_4/src/main/java/Main.java new file mode 100644 index 0000000..6054a64 --- /dev/null +++ b/_4/src/main/java/Main.java @@ -0,0 +1,5 @@ +public class Main { + public static void main(String[] args) { + + } +} From 88ca40fe1ca353a61d8939826a119097144d5f7e Mon Sep 17 00:00:00 2001 From: OnateK Date: Fri, 15 Mar 2019 18:32:10 +0200 Subject: [PATCH 05/26] basic clasess --- _4/src/main/resources/k3.tgf | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 _4/src/main/resources/k3.tgf diff --git a/_4/src/main/resources/k3.tgf b/_4/src/main/resources/k3.tgf new file mode 100644 index 0000000..e69de29 From 2fbf0c5be29bc241c886f30c5eb34c6019c7d8e3 Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 18:33:27 +0200 Subject: [PATCH 06/26] k3.tgf --- _4/src/main/resources/k3.tgf | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/_4/src/main/resources/k3.tgf b/_4/src/main/resources/k3.tgf index e69de29..ce561ca 100644 --- a/_4/src/main/resources/k3.tgf +++ b/_4/src/main/resources/k3.tgf @@ -0,0 +1,8 @@ +# Nodes +1 +2 +3 +# Edges +1 2 +1 3 +2 3 \ No newline at end of file From 338f35d11e60e2aea916ce1f95de1bf153285d6f Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 18:42:03 +0200 Subject: [PATCH 07/26] method signatures for catalog --- _4/src/main/java/Catalog.java | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/_4/src/main/java/Catalog.java b/_4/src/main/java/Catalog.java index d0253b1..1ca9f13 100644 --- a/_4/src/main/java/Catalog.java +++ b/_4/src/main/java/Catalog.java @@ -1,2 +1,22 @@ -public class Catalog { +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +public class Catalog implements Serializable { + + List graphList = new LinkedList(); + String path; + + public Catalog(String path) { + this.path = path; + } + + public void add (Graph graph){ + + } + + public void open(String graphName){ + + } + } From f5a783d95b5a20e1221cd553508ed74f1aaec93e Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 18:43:36 +0200 Subject: [PATCH 08/26] method signatures for catalog --- _4/src/main/java/Catalog.java | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/_4/src/main/java/Catalog.java b/_4/src/main/java/Catalog.java index 1ca9f13..c426ec2 100644 --- a/_4/src/main/java/Catalog.java +++ b/_4/src/main/java/Catalog.java @@ -4,13 +4,29 @@ public class Catalog implements Serializable { - List graphList = new LinkedList(); - String path; + private List graphList = new LinkedList(); + private String path; public Catalog(String path) { this.path = path; } + public List getGraphList() { + return graphList; + } + + public void setGraphList(List graphList) { + this.graphList = graphList; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + public void add (Graph graph){ } @@ -19,4 +35,12 @@ public void open(String graphName){ } + public void save(String fileName){ + + } + + public void load(String fileName){ + + } + } From d912ac4c58c272f3aee20aef68c836b6228816ac Mon Sep 17 00:00:00 2001 From: OnateK Date: Fri, 15 Mar 2019 18:45:24 +0200 Subject: [PATCH 09/26] Graph class --- _4/src/main/java/Graph.java | 38 +++++++++++++++++++++ _4/src/main/resources/{ => Complete}/k3.tgf | 0 _4/src/main/resources/Complete/k4.tgf | 0 _4/src/main/resources/Special/patterson.tgf | 0 4 files changed, 38 insertions(+) rename _4/src/main/resources/{ => Complete}/k3.tgf (100%) create mode 100644 _4/src/main/resources/Complete/k4.tgf create mode 100644 _4/src/main/resources/Special/patterson.tgf diff --git a/_4/src/main/java/Graph.java b/_4/src/main/java/Graph.java index 5e2b807..62b97d4 100644 --- a/_4/src/main/java/Graph.java +++ b/_4/src/main/java/Graph.java @@ -1,2 +1,40 @@ public class Graph { + + private String name; + private String imagePath; + private String tgfPath; + + public Graph(){ + + } + + public Graph(String name, String imagePath, String tgfPath) { + this.name = name; + this.imagePath = imagePath; + this.tgfPath = tgfPath; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getImagePath() { + return imagePath; + } + + public void setImagePath(String imagePath) { + this.imagePath = imagePath; + } + + public String getTgfPath() { + return tgfPath; + } + + public void setTgfPath(String tgfPath) { + this.tgfPath = tgfPath; + } } diff --git a/_4/src/main/resources/k3.tgf b/_4/src/main/resources/Complete/k3.tgf similarity index 100% rename from _4/src/main/resources/k3.tgf rename to _4/src/main/resources/Complete/k3.tgf diff --git a/_4/src/main/resources/Complete/k4.tgf b/_4/src/main/resources/Complete/k4.tgf new file mode 100644 index 0000000..e69de29 diff --git a/_4/src/main/resources/Special/patterson.tgf b/_4/src/main/resources/Special/patterson.tgf new file mode 100644 index 0000000..e69de29 From 177239995725cd694c09e87ad00ef1e41524d692 Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 18:51:45 +0200 Subject: [PATCH 10/26] pathUtils added --- _4/src/main/java/Utils/PathUtils.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 _4/src/main/java/Utils/PathUtils.java diff --git a/_4/src/main/java/Utils/PathUtils.java b/_4/src/main/java/Utils/PathUtils.java new file mode 100644 index 0000000..e66b13e --- /dev/null +++ b/_4/src/main/java/Utils/PathUtils.java @@ -0,0 +1,14 @@ +package Utils; + +public class PathUtils { + + static boolean isAbsolute(String path){ + if (path.contains(":")) + return true; + return false; + } + + static boolean isRelative(String path){ + return !PathUtils.isAbsolute(path); + } +} From 38b0242938756457255aec81e213ea318084ccac Mon Sep 17 00:00:00 2001 From: OnateK Date: Fri, 15 Mar 2019 18:52:23 +0200 Subject: [PATCH 11/26] k3 and k4 added --- _4/src/main/java/Graph.java | 9 +++++++++ _4/src/main/resources/Complete/k3.tgf | 8 ++++++++ _4/src/main/resources/Complete/k4.tgf | 12 ++++++++++++ 3 files changed, 29 insertions(+) diff --git a/_4/src/main/java/Graph.java b/_4/src/main/java/Graph.java index 62b97d4..28319b6 100644 --- a/_4/src/main/java/Graph.java +++ b/_4/src/main/java/Graph.java @@ -1,6 +1,7 @@ public class Graph { private String name; + private String description; private String imagePath; private String tgfPath; @@ -14,6 +15,14 @@ public Graph(String name, String imagePath, String tgfPath) { this.tgfPath = tgfPath; } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + public String getName() { return name; } diff --git a/_4/src/main/resources/Complete/k3.tgf b/_4/src/main/resources/Complete/k3.tgf index e69de29..ce561ca 100644 --- a/_4/src/main/resources/Complete/k3.tgf +++ b/_4/src/main/resources/Complete/k3.tgf @@ -0,0 +1,8 @@ +# Nodes +1 +2 +3 +# Edges +1 2 +1 3 +2 3 \ No newline at end of file diff --git a/_4/src/main/resources/Complete/k4.tgf b/_4/src/main/resources/Complete/k4.tgf index e69de29..91f8c60 100644 --- a/_4/src/main/resources/Complete/k4.tgf +++ b/_4/src/main/resources/Complete/k4.tgf @@ -0,0 +1,12 @@ +# Nodes +1 +2 +3 +4 +# Edges +1 2 +1 3 +1 4 +2 3 +2 4 +3 4 \ No newline at end of file From b53effc487a29d278cc4be5e64a92e603f19cf5e Mon Sep 17 00:00:00 2001 From: OnateK Date: Fri, 15 Mar 2019 19:09:00 +0200 Subject: [PATCH 12/26] added javaDocs for Graph Class and My exception Class --- _4/src/main/java/Exceptions/MyException.java | 19 +++++++++ _4/src/main/java/Graph.java | 41 ++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 _4/src/main/java/Exceptions/MyException.java diff --git a/_4/src/main/java/Exceptions/MyException.java b/_4/src/main/java/Exceptions/MyException.java new file mode 100644 index 0000000..d6fda33 --- /dev/null +++ b/_4/src/main/java/Exceptions/MyException.java @@ -0,0 +1,19 @@ +package Exceptions; + +public class MyException extends Exception{ + + private String myException; + + /** + * Constructor for a new exception + * @param myException exception text + */ + public MyException(String myException){ + this.myException = myException; + } + + @Override + public String toString() { + return "Custom Exception: "+ myException; + } +} diff --git a/_4/src/main/java/Graph.java b/_4/src/main/java/Graph.java index 28319b6..930b44c 100644 --- a/_4/src/main/java/Graph.java +++ b/_4/src/main/java/Graph.java @@ -5,44 +5,85 @@ public class Graph { private String imagePath; private String tgfPath; + /** + * Default constructor + */ public Graph(){ } + /** + * Constructor for a new graph + * @param name graph name + * @param imagePath graph image path + * @param tgfPath graph tgf path ( details ) + */ public Graph(String name, String imagePath, String tgfPath) { this.name = name; this.imagePath = imagePath; this.tgfPath = tgfPath; } + /** + * Getter for description + * @return graph description + */ public String getDescription() { return description; } + /** + * Set the graph description + * @param description graph description + */ public void setDescription(String description) { this.description = description; } + /** + * Get graph name + * @return graph name + */ public String getName() { return name; } + /** + * Set graph name + * @param name graph name + */ public void setName(String name) { this.name = name; } + /** + * Get graph image path + * @return image path + */ public String getImagePath() { return imagePath; } + /** + * Set graph image path + * @param imagePath image path + */ public void setImagePath(String imagePath) { this.imagePath = imagePath; } + /** + * Get the tgf (details) of the graph + * @return the path to the tgf for the graph + */ public String getTgfPath() { return tgfPath; } + /** + * Set the path for the tgf (details) of the graph + * @param tgfPath the path for the tgf of the graph + */ public void setTgfPath(String tgfPath) { this.tgfPath = tgfPath; } From f9bea13bebef71453812ec65438ddafd68291abd Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 19:19:54 +0200 Subject: [PATCH 13/26] catalog save and load --- _4/pom.xml | 12 +++++++++ _4/src/main/java/Catalog.java | 24 ++++++++++-------- _4/src/main/java/CatalogIO.java | 45 +++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 11 deletions(-) diff --git a/_4/pom.xml b/_4/pom.xml index d776e6b..0e1d747 100644 --- a/_4/pom.xml +++ b/_4/pom.xml @@ -7,6 +7,18 @@ ketaval 4 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + + + \ No newline at end of file diff --git a/_4/src/main/java/Catalog.java b/_4/src/main/java/Catalog.java index c426ec2..0d67662 100644 --- a/_4/src/main/java/Catalog.java +++ b/_4/src/main/java/Catalog.java @@ -1,6 +1,9 @@ -import java.io.Serializable; +import java.awt.*; +import java.io.*; import java.util.LinkedList; import java.util.List; +import java.awt.Desktop; +import java.util.Objects; public class Catalog implements Serializable { @@ -28,19 +31,18 @@ public void setPath(String path) { } public void add (Graph graph){ - + graphList.add(graph); } public void open(String graphName){ - - } - - public void save(String fileName){ - - } - - public void load(String fileName){ - + Desktop desktop = Desktop.getDesktop(); + desktop.enableSuddenTermination(); + try { + desktop.open(new File(graphName)); + } catch (IOException e) { + System.out.println("No file found having this name. Please retry."); + e.printStackTrace(); + } } } diff --git a/_4/src/main/java/CatalogIO.java b/_4/src/main/java/CatalogIO.java index 2e076e2..ba0b33a 100644 --- a/_4/src/main/java/CatalogIO.java +++ b/_4/src/main/java/CatalogIO.java @@ -1,2 +1,47 @@ +import java.io.*; +import java.util.Objects; + public class CatalogIO { + + private Catalog catalog; + + public Catalog getCatalog() { + return catalog; + } + + public void setCatalog(Catalog catalog) { + this.catalog = catalog; + } + + public void save(String fileName){ + FileOutputStream fout; + ObjectOutputStream oos = null; + try { + fout = new FileOutputStream(fileName); + oos = new ObjectOutputStream(fout); + Objects.requireNonNull(oos).writeObject(this); + } catch (FileNotFoundException e) { + System.out.println("Failed to create file named " + fileName); + e.printStackTrace(); + } catch (IOException e) { + System.out.println("Failed to serialize the catalog."); + e.printStackTrace(); + } + } + + public void load(String fileName){ + FileInputStream fin; + ObjectInputStream ois = null; + try { + fin= new FileInputStream(fileName); + ois = new ObjectInputStream(fin); + this.catalog= (Catalog) ois.readObject(); + } catch (IOException | ClassNotFoundException e) { + System.out.println("File not found."); + e.printStackTrace(); + } + } + + + } From db13a1ef21ec6bbe3a99c9710f997fe6ba5d9dd7 Mon Sep 17 00:00:00 2001 From: Valeriu Moise Date: Fri, 15 Mar 2019 19:25:20 +0200 Subject: [PATCH 14/26] catalog.list() done --- _4/src/main/java/Catalog.java | 5 ++++- _4/src/main/java/Graph.java | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/_4/src/main/java/Catalog.java b/_4/src/main/java/Catalog.java index 0d67662..b466137 100644 --- a/_4/src/main/java/Catalog.java +++ b/_4/src/main/java/Catalog.java @@ -36,7 +36,6 @@ public void add (Graph graph){ public void open(String graphName){ Desktop desktop = Desktop.getDesktop(); - desktop.enableSuddenTermination(); try { desktop.open(new File(graphName)); } catch (IOException e) { @@ -45,4 +44,8 @@ public void open(String graphName){ } } + public void list(){ + graphList.forEach(graph -> System.out.println(graph.toString())); + } + } diff --git a/_4/src/main/java/Graph.java b/_4/src/main/java/Graph.java index 930b44c..7d82459 100644 --- a/_4/src/main/java/Graph.java +++ b/_4/src/main/java/Graph.java @@ -87,4 +87,15 @@ public String getTgfPath() { public void setTgfPath(String tgfPath) { this.tgfPath = tgfPath; } + + + @Override + public String toString() { + return "Graph{" + + "name='" + name + '\'' + + ", description='" + description + '\'' + + ", imagePath='" + imagePath + '\'' + + ", tgfPath='" + tgfPath + '\'' + + '}'; + } } From 23f3d3011e05b64c51eed724acab662aeb8ad58e Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 18:19:39 +0300 Subject: [PATCH 15/26] lab8 --- 5/pom.xml | 24 ++++ 5/src/main/java/Main.java | 7 ++ 5/src/main/java/model/Catalog.java | 52 +++++++++ 5/src/main/java/model/Graph.java | 103 ++++++++++++++++++ 5/src/main/java/service/CatalogIOService.java | 55 ++++++++++ 5/src/main/java/ui/CatalogFrame.java | 37 +++++++ 5/src/main/java/ui/CatalogList.java | 21 ++++ 5/src/main/java/ui/ControlPanel.java | 17 +++ 5/src/main/java/ui/GraphForm.java | 49 +++++++++ 5/src/main/java/ui/SwingControl.java | 84 ++++++++++++++ _4/pom.xml | 13 +++ _4/target/classes/Complete/k3.tgf | 8 ++ _4/target/classes/Complete/k4.tgf | 12 ++ _4/target/classes/Special/patterson.tgf | 0 _4/target/maven-archiver/pom.properties | 5 + _7/lab6_node.png | Bin 0 -> 9960 bytes _7/pom.xml | 24 ++++ _7/src/main/java/main/Main.java | 10 ++ _7/src/main/java/swingGUI/Canvas.form | 13 +++ _7/src/main/java/swingGUI/Canvas.java | 82 ++++++++++++++ _7/src/main/java/swingGUI/ControlPanel.form | 13 +++ _7/src/main/java/swingGUI/ControlPanel.java | 21 ++++ _7/src/main/java/swingGUI/DrawingFrame.form | 13 +++ _7/src/main/java/swingGUI/DrawingFrame.java | 79 ++++++++++++++ _7/src/main/java/swingGUI/Toolbar.form | 13 +++ _7/src/main/java/swingGUI/Toolbar.java | 36 ++++++ _8/pom.xml | 12 ++ 27 files changed, 803 insertions(+) create mode 100644 5/pom.xml create mode 100644 5/src/main/java/Main.java create mode 100644 5/src/main/java/model/Catalog.java create mode 100644 5/src/main/java/model/Graph.java create mode 100644 5/src/main/java/service/CatalogIOService.java create mode 100644 5/src/main/java/ui/CatalogFrame.java create mode 100644 5/src/main/java/ui/CatalogList.java create mode 100644 5/src/main/java/ui/ControlPanel.java create mode 100644 5/src/main/java/ui/GraphForm.java create mode 100644 5/src/main/java/ui/SwingControl.java create mode 100644 _4/target/classes/Complete/k3.tgf create mode 100644 _4/target/classes/Complete/k4.tgf create mode 100644 _4/target/classes/Special/patterson.tgf create mode 100644 _4/target/maven-archiver/pom.properties create mode 100644 _7/lab6_node.png create mode 100644 _7/pom.xml create mode 100644 _7/src/main/java/main/Main.java create mode 100644 _7/src/main/java/swingGUI/Canvas.form create mode 100644 _7/src/main/java/swingGUI/Canvas.java create mode 100644 _7/src/main/java/swingGUI/ControlPanel.form create mode 100644 _7/src/main/java/swingGUI/ControlPanel.java create mode 100644 _7/src/main/java/swingGUI/DrawingFrame.form create mode 100644 _7/src/main/java/swingGUI/DrawingFrame.java create mode 100644 _7/src/main/java/swingGUI/Toolbar.form create mode 100644 _7/src/main/java/swingGUI/Toolbar.java create mode 100644 _8/pom.xml diff --git a/5/pom.xml b/5/pom.xml new file mode 100644 index 0000000..7cd4774 --- /dev/null +++ b/5/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + ketval + 5 + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + + + \ No newline at end of file diff --git a/5/src/main/java/Main.java b/5/src/main/java/Main.java new file mode 100644 index 0000000..0605190 --- /dev/null +++ b/5/src/main/java/Main.java @@ -0,0 +1,7 @@ +import ui.CatalogFrame; + +public class Main { + public static void main(String[] args) { + new CatalogFrame().setVisible(true); + } +} diff --git a/5/src/main/java/model/Catalog.java b/5/src/main/java/model/Catalog.java new file mode 100644 index 0000000..17a76c3 --- /dev/null +++ b/5/src/main/java/model/Catalog.java @@ -0,0 +1,52 @@ +package model; + +import java.awt.*; +import java.io.*; +import java.util.LinkedList; +import java.util.List; +import java.awt.Desktop; + +public class Catalog implements Serializable { + + private List graphList = new LinkedList(); + private String path; + + public Catalog(String path) { + this.path = path; + } + + public List getGraphList() { + return graphList; + } + + public void setGraphList(List graphList) { + this.graphList = graphList; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public void add (Graph graph){ + graphList.add(graph); + } + + public void open(String graphName){ + Desktop desktop = Desktop.getDesktop(); + try { + desktop.open(new File(graphName)); + } catch (IOException e) { + System.out.println("No file found having this name. Please retry."); + e.printStackTrace(); + } + } + + public void list(){ + graphList.forEach(graph -> System.out.println(graph.toString())); + } + +} diff --git a/5/src/main/java/model/Graph.java b/5/src/main/java/model/Graph.java new file mode 100644 index 0000000..2fbeb1d --- /dev/null +++ b/5/src/main/java/model/Graph.java @@ -0,0 +1,103 @@ +package model; + +public class Graph { + + private String name; + private String description; + private String imagePath; + private String tgfPath; + + /** + * Default constructor + */ + public Graph(){ + + } + + /** + * Constructor for a new graph + * @param name graph name + * @param imagePath graph image path + * @param tgfPath graph tgf path ( details ) + */ + public Graph(String name, String imagePath, String tgfPath) { + this.name = name; + this.imagePath = imagePath; + this.tgfPath = tgfPath; + } + + /** + * Getter for description + * @return graph description + */ + public String getDescription() { + return description; + } + + /** + * Set the graph description + * @param description graph description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Get graph name + * @return graph name + */ + public String getName() { + return name; + } + + /** + * Set graph name + * @param name graph name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Get graph image path + * @return image path + */ + public String getImagePath() { + return imagePath; + } + + /** + * Set graph image path + * @param imagePath image path + */ + public void setImagePath(String imagePath) { + this.imagePath = imagePath; + } + + /** + * Get the tgf (details) of the graph + * @return the path to the tgf for the graph + */ + public String getTgfPath() { + return tgfPath; + } + + /** + * Set the path for the tgf (details) of the graph + * @param tgfPath the path for the tgf of the graph + */ + public void setTgfPath(String tgfPath) { + this.tgfPath = tgfPath; + } + + + @Override + public String toString() { + return "Graph{" + + "name='" + name + '\'' + + ", description='" + description + '\'' + + ", imagePath='" + imagePath + '\'' + + ", tgfPath='" + tgfPath + '\'' + + '}'; + } +} diff --git a/5/src/main/java/service/CatalogIOService.java b/5/src/main/java/service/CatalogIOService.java new file mode 100644 index 0000000..c7509ea --- /dev/null +++ b/5/src/main/java/service/CatalogIOService.java @@ -0,0 +1,55 @@ +package service; + +import model.Catalog; + +import java.io.*; +import java.util.Objects; + +public class CatalogIOService { + + private Catalog catalog; + + public CatalogIOService(Catalog catalog) { + this.catalog = catalog; + } + + public Catalog getCatalog() { + return catalog; + } + + public void setCatalog(Catalog catalog) { + this.catalog = catalog; + } + + public void save(String fileName){ + FileOutputStream fout; + ObjectOutputStream oos = null; + try { + fout = new FileOutputStream(fileName); + oos = new ObjectOutputStream(fout); + Objects.requireNonNull(oos).writeObject(this); + } catch (FileNotFoundException e) { + System.out.println("Failed to create file named " + fileName); + e.printStackTrace(); + } catch (IOException e) { + System.out.println("Failed to serialize the catalog."); + e.printStackTrace(); + } + } + + public void load(String fileName){ + FileInputStream fin; + ObjectInputStream ois = null; + try { + fin= new FileInputStream(fileName); + ois = new ObjectInputStream(fin); + this.catalog= (Catalog) ois.readObject(); + } catch (IOException | ClassNotFoundException e) { + System.out.println("File not found."); + e.printStackTrace(); + } + } + + + +} diff --git a/5/src/main/java/ui/CatalogFrame.java b/5/src/main/java/ui/CatalogFrame.java new file mode 100644 index 0000000..caf6dd0 --- /dev/null +++ b/5/src/main/java/ui/CatalogFrame.java @@ -0,0 +1,37 @@ +package ui; + +import javax.swing.*; +import java.awt.*; + +public class CatalogFrame extends JFrame { + private GraphForm form; + private CatalogList list; + private ui.ControlPanel control; + + public CatalogFrame() { + super("Visual Graph Manager"); + init(); + } + + private void init() { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + this.setSize(600, 600); + + this.getContentPane().setLayout(new BorderLayout()); + + this.form = new GraphForm(this); + this.getContentPane().add(BorderLayout.NORTH, form); + + this.list = new CatalogList(); + this.getContentPane().add(BorderLayout.CENTER, list); + + this.control = new ControlPanel(this); + this.getContentPane().add(BorderLayout.SOUTH, control); + + form.setOpaque(true); + +// this.pack(); + this.setVisible(true); + + } +} \ No newline at end of file diff --git a/5/src/main/java/ui/CatalogList.java b/5/src/main/java/ui/CatalogList.java new file mode 100644 index 0000000..a20c39c --- /dev/null +++ b/5/src/main/java/ui/CatalogList.java @@ -0,0 +1,21 @@ +package ui; + +import model.Catalog; + +import javax.swing.*; + +public class CatalogList extends JList { + private DefaultListModel model = new DefaultListModel<>(); + + public CatalogList() { + String title = "" + + "Catalog Graphs" + ""; + this.setBorder(BorderFactory.createTitledBorder(title)); + this.setModel(model); + } + + public void addGraph(String item) { + model.addElement(item); + } +} + diff --git a/5/src/main/java/ui/ControlPanel.java b/5/src/main/java/ui/ControlPanel.java new file mode 100644 index 0000000..a72ac57 --- /dev/null +++ b/5/src/main/java/ui/ControlPanel.java @@ -0,0 +1,17 @@ +package ui; + +import javax.swing.*; + +public class ControlPanel extends JPanel { + private final CatalogFrame frame; + private JButton loadBtn = new JButton("Load"); +// ... + public ControlPanel(CatalogFrame frame) { + this.frame = frame; + init(); + } + private void init() { + add(loadBtn); + this.setVisible(true); + } +} \ No newline at end of file diff --git a/5/src/main/java/ui/GraphForm.java b/5/src/main/java/ui/GraphForm.java new file mode 100644 index 0000000..7f79321 --- /dev/null +++ b/5/src/main/java/ui/GraphForm.java @@ -0,0 +1,49 @@ +package ui; + + +import javax.swing.*; +import javax.swing.border.Border; +import java.awt.*; + +public class GraphForm extends JPanel { + private final CatalogFrame frame; + private JLabel titleLabel; + private JTextField titleField; + private JLabel verticesLabel; + private JSpinner verticesField; + private JLabel typeLabel; + private JRadioButton directedRadioButton; + private JRadioButton undiretedRadioButton; + private JLabel pathToDefinitionFileLabel; + private JFileChooser pathToDefinitionFileChooser; + private JLabel pathToImageFile; + private JFileChooser pathToImageFileChooser; + + + + public GraphForm(CatalogFrame frame) { + this.frame = frame; + titleLabel = new JLabel("Name of the graph"); + titleField = new JTextField(); + verticesLabel = new JLabel("Number of vertices"); + verticesField = new JSpinner(new SpinnerNumberModel(500, 0,1000,1)); + typeLabel = new JLabel("Graph type"); + directedRadioButton = new JRadioButton("Directed"); + undiretedRadioButton = new JRadioButton("Undirected"); + pathToDefinitionFileLabel = new JLabel("Choose the definition file"); + pathToDefinitionFileChooser = new JFileChooser(); + pathToImageFile = new JLabel("Choose de image file"); + pathToImageFileChooser = new JFileChooser(); + } + + // ... + private void init() { + frame.getContentPane().add(BorderLayout.LINE_START,titleLabel); + frame.getContentPane().add(BorderLayout.LINE_END,titleField); + setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); +// addButton.addActionListener(...); + } + private void addGraph() { +// frame.list.addGraph(...); + } +} \ No newline at end of file diff --git a/5/src/main/java/ui/SwingControl.java b/5/src/main/java/ui/SwingControl.java new file mode 100644 index 0000000..b649063 --- /dev/null +++ b/5/src/main/java/ui/SwingControl.java @@ -0,0 +1,84 @@ +package ui; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +public class SwingControl { + private JFrame mainFrame; + private JLabel headerLabel; + private JLabel statusLabel; + private JPanel controlPanel; + + public SwingControl() { + prepareGUI(); + } + +// public static void main(String[] args) { +// SwingControl swingControlDemo = new SwingControl(); +// swingControlDemo.showEventDemo(); +// } + + private void prepareGUI() { + mainFrame = new JFrame("Java SWING Examples"); + mainFrame.setSize(400, 400); + mainFrame.setLayout(new GridLayout(3, 1)); + + headerLabel = new JLabel("", JLabel.CENTER); + statusLabel = new JLabel("", JLabel.CENTER); + statusLabel.setSize(350, 100); + + mainFrame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent windowEvent) { + System.exit(0); + } + }); + controlPanel = new JPanel(); + controlPanel.setLayout(new FlowLayout()); + + mainFrame.add(headerLabel); + mainFrame.add(controlPanel); + mainFrame.add(statusLabel); + mainFrame.setVisible(true); + } + + private void showEventDemo() { + headerLabel.setText("Control in action: Button"); + + JButton okButton = new JButton("OK"); + JButton submitButton = new JButton("Submit"); + JButton cancelButton = new JButton("Cancel"); + + okButton.setActionCommand("OK"); + submitButton.setActionCommand("Submit"); + cancelButton.setActionCommand("Cancel"); + + okButton.addActionListener(new ButtonClickListener()); + submitButton.addActionListener(new ButtonClickListener()); + cancelButton.addActionListener(new ButtonClickListener()); + + controlPanel.add(okButton); + controlPanel.add(submitButton); + controlPanel.add(cancelButton); + + mainFrame.setVisible(true); + } + + private class ButtonClickListener implements ActionListener { + public void actionPerformed(ActionEvent e) { + String command = e.getActionCommand(); + + if (command.equals("OK")) { + statusLabel.setText("Ok Button clicked."); + } else if (command.equals("Submit")) { + statusLabel.setText("Submit Button clicked."); + } else { + statusLabel.setText("Cancel Button clicked."); + } + } + } +} + diff --git a/_4/pom.xml b/_4/pom.xml index 0e1d747..21c8bbc 100644 --- a/_4/pom.xml +++ b/_4/pom.xml @@ -7,6 +7,7 @@ ketaval 4 1.0-SNAPSHOT + jar @@ -17,7 +18,19 @@ 9 + + org.apache.maven.plugins + maven-jar-plugin + + + + Main + + + + + diff --git a/_4/target/classes/Complete/k3.tgf b/_4/target/classes/Complete/k3.tgf new file mode 100644 index 0000000..ce561ca --- /dev/null +++ b/_4/target/classes/Complete/k3.tgf @@ -0,0 +1,8 @@ +# Nodes +1 +2 +3 +# Edges +1 2 +1 3 +2 3 \ No newline at end of file diff --git a/_4/target/classes/Complete/k4.tgf b/_4/target/classes/Complete/k4.tgf new file mode 100644 index 0000000..91f8c60 --- /dev/null +++ b/_4/target/classes/Complete/k4.tgf @@ -0,0 +1,12 @@ +# Nodes +1 +2 +3 +4 +# Edges +1 2 +1 3 +1 4 +2 3 +2 4 +3 4 \ No newline at end of file diff --git a/_4/target/classes/Special/patterson.tgf b/_4/target/classes/Special/patterson.tgf new file mode 100644 index 0000000..e69de29 diff --git a/_4/target/maven-archiver/pom.properties b/_4/target/maven-archiver/pom.properties new file mode 100644 index 0000000..6b88f37 --- /dev/null +++ b/_4/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Fri Mar 15 19:31:57 EET 2019 +groupId=ketaval +artifactId=4 +version=1.0-SNAPSHOT diff --git a/_7/lab6_node.png b/_7/lab6_node.png new file mode 100644 index 0000000000000000000000000000000000000000..fcb487242acbbc17fe9c76dbf33a19bf53b59716 GIT binary patch literal 9960 zcmcI~c|6o#+y7@!k;+o3EHfjeL|Kb4OcKi4VoOqXvPAY7OeI8&N(f0`A=w&RYC>f% zyX?EMjcpqH5`O1Hb>H3h_j&zZ&-2{RUvoa^b3W%>=Q`K>x~}(i=Dv=W>h`VNTOkPA zepXHS0t7LlA&9|%c{AvVcDr*Ef&??qDxbRK(LT|I3wvhe-AdPpQH<6|vWV7-;X0ge zqjXv>N9H#6oLZ8{cS1~f-eI?kn%%?&T7yXE5M6XqI zk?HUlm@CYoJq^-^Hx;%gcwex^{4-k_d6iI)+D`}+&psE9{1#Ix2#be!k>UDoN!B@1f8jpn;KA=)Q%%MGZdIUa-Vj1a#CvLT0t9M{!EA zVVfX`j|;v0RxcWfTD&RC1wk%4gpzH_l5^e<+>~i`@oX%hOPNq|@NRk#5np0)4=8X8 zlUnD^?osGIPa^^%oJFEBs;_N^st*|<(c+<~EFL~!Zmxv!E0|U;I)~ZvR-RK3bnU{H ziZ6!A?SfdnDw)B@U~7+0Vohmh$V`FWK(%6(jOKGWkL`D&={JB~2s#mR)bRt1@K)jT zU{a%qd;;Gf8l+CVU<3zY!(INJVf}Xx$NFz{oIsP*^w1o07$v|T4-g3ggc5qMKfX4{6eF7~PK~IVF5>f&k9=nEl-Se|^js_a3UI6!pnp9gAa&*X81+Y8Sn;*4CsyBZwwD!g;YdkolFvX#st;~!y>tx)Ig=AGk$lSE5 z@-|B)k#Yv>2QhVUwd-=wAF?HzA*7C3DwWCZ7G9;5 zBgtLGoM>pLI&ZF#IiZB30FpWe^iwt?!zWC9C}S(FMGi7#!znN^fArfmkKeTq?WD~N zJC>RwMdoi_aU3#50I$%S7W9CKhy6ouS``7{dF1dRclTs(NtBix?SruWkIu-3XyMGW zsmI6?>F<7wj+e_#F1WQX_nxMf%soSLg?~h{1BdsxyYAyP*_>WdPTx|k73us~>&(5F zh8Jhl8+3e&0+=^BZRLU({LW6aE``{vxIX98_jtfNmQlbzYv);3?8lJ5g$Y7@ez_|f zY3%N;n7+E8yS=phJ88PZ-HOI4Ri-%tIDdoV|xD!%Xul0KDeh113BWMf7?Dl8h{bCM8Ts`j9u8T=FYhz<54QwR!2X^Nl zI#84*7IC>0gL3+o(U<|&N#^4nITz_(a4a}9JA_EX+s_>j7oA+Rw!{xmJ_-=M79c1b zg%+O{zl`5TWS8V0PzcMlA*o8iWrIOio4sz-rm`P-B3D zdxw~6A+Np}g6?DZ!>xL%0*tuPI267@`UTVJC!ca|eTtQuk0vIPMe*LzKC8kF`nAhX zT$X)(Y~GLEnQk1{zVax}b7b`r)qOuFREI!JSsD4}g2_&Kx^;W%t1}*$-1MULyNB&k z&P;lbuPYa?S%}=#wXwFA@-g7*0wJNUvRdzyL_`+dpT~RW)~WI4>NY#oqkZDeC1X1r zuhRG#pvRI}kx#a$8^?;?Cn7i%6+=3*@zkdldb6Phak)20k1K(j+KWE%;w@3HOjW^J zqY5v@jVcx>(O`zes0=0IA12JIpR`0Fo_;i?sT6$8P%#R%0ER7=!f+rz@D0Xp>9gh> zLE{?f_J;}(V5T}8=58VgmAldWmP)24^~PB$rIS>{t7MjrOQJOUcctAIwiKGgQ&P{t zzUeDK(Z`pp?3W$a#!pTnp2p|Z#u%T&4+u=MAi%lp`l30qvn4ilE$bU}|LfM<{oD0~ zsePxllZrZ=t=?NNhR>k(6ezAd4(NI0<1~k|q&%7Kd3NlIo9=tJ=^2;#xRWW4BjEv? z(OALAYLnRZM+*kNT~-%ett+JCwaz#ypicIexx~vXFA-nz#4YN1HGQ6cc0c5D*;nLB zqf6WS6r15nZ{&V7R{l<9-}gu5Mx5v^NT*?Cfgo8g_Z$Jw+hwH>%GbK)3T7UibmV~% zCa%tzz28z9K+8{BN-U~cMM_ek*%)`4dz3c+oks_l8>4kqbNA#-hq}Ty9q<9&XUr=P zmv2#Gn)qla%}c`AZ8@@mhM!`j4z4W|8$^qitEna?Q*$#W84J@hw{4_fE+d~mU)rpU zW@hJZ&K`W4vqaH9eiYk3oFHzAjW57Bxp?Q{UxR~CtxBqr&;NG%n3#MLX5sFPQDng( z)=*NJCu;Ta_!z~N0KGr}>=y~qVbtSVH@(@y)GnvMZS1W3^^piiLwi<3PZWe7N@SurQjgUcIoM~HAW;ISVg)WW<2}9b_(YA$|pQbfC(kLvi!H$;N z#edLPE2=cW8+Ff#jXCEzfc#7x@$#HsYm|bI_;kJX2IkOMYcbeh9^#ZtElaCZNu7Q> zCJt$lZGqOzz9eenx3_i_@ROiW9`;jlY?*UFhTnCkzX7`k3!8wC1)>%;*qhcD#K8UXtgl=+%3R zRSSL0QV^VxyBQdmWRkJ57VExyq(RR zOj@f>!O}@6_s50hr-@lgPYoK9s*X6w5Y;zJD=x6v#LxQ$oH1(4^E5lrab6up!29a4 zmb`(MuF)0LqQ~G5_ht5w7gY-tThLf23W^Z*9k7y)5DD(C9niw9P?|No|{o z)n+D;_M1zhLdwd&GuzB*sF6zopnWkIH284jCdoaa+d@C#Xu0iB9J?fXXTZfbSOQen z_tO+Ql6^=vYukX|;+;ew5DeHY;GCsb0(_0m5lW~A)v|xJ2pQ}Qh^adTKKg`whRF^G zkm}sounjmV0~k;j7zUD-X>&K>0X0cimOfozJaA0d&VS3C;*j7B%K^(%LER6Kv^_Ld zkO8zC)W_7ShUSYG2>HgR>t(I%Nq<0$#4IJJBs(_*yjF=Jlefw}k`C=QF1kSu*vh~} zaMS-*Pfp;g>=3zlqN}+9dS};l3H8e9au%KHFL0orQlG5v5e2J=`3p!Vq`nre3Q!N; z>TZ6t5NJktJLk5HZ36yx)Hrl^rsOmNOvqv`QBCmEvsWRu?HS#JlQuQ;iZ#_8v(YE@ zb;hv)%Az6m*n&+h!*S%&(!@cOtu4N!c8{WHsh?WsPGECo<0^&n!V!k0+lQShdx?8$ zH8I|E?I4S}rW7rbd~N&N3@cn?glTE*PDK>xC2(s*;IJyuIFB<_4$fr-OXQW&(@a1U zubRx?u@tm%aMFYo02Mnf>uIa)W%@Os@wBi>OoW4v@0?lutuA^~3p>G zVEE}i5yoI2W&A`UUfBtzjvnFE6NQwHEkAfSM$2U}9%3jFh(}st3E75)GbC8UW|cqQ z*{{@|G)R95jx?e==t>U$92_AE4$E{;4eX}2S2s3x;f7wuox|}h%H~gBlJ)4D%UOz83C)?faET4BB@+RFE`F@H&0E6MQypc zG%WI&*E@6@x;2Fxvv3ZYY?=iUUGBvPsaq~~Kb% z8^Io+2*M8CNA+B=B>>_Gv+;^u1&jEBK%Pc;!Z4xHk*@mCfiv*9B-lN`lS)`(VXiF| zf&t+WR4>Ye3^sm$J!_7vKig71?@MH=_$|!U!@rFu7#3vDNw+uTHv*oNk*?u6SI<}Q z+%*%up&{E<)k?}&kKT~iKrld%S@6>^uSm1fu_`<~?cT^%G6zp1WmoEDZF11|;kor* z>%)I{5@bD5t-Hxf@*)U^U4tdp^rPRd6(ys_@n@s6X?MoU;Yz~cGaI%6(jKgkf4Qmx zT-VUqDhW2oz!Y5uvi{$t3*gEAKNX8>e~r=FpEs}3o2Yb?0VPyC71^8^34}q_1s@yeS2hk0i|BbWwlCbW(pUFqEi}u zi)05=E)~2LP83)vq(FcWl_kr%JHEb}bzu85cN**61po5|9_L>xd^nW&=`{^#g*ohe zn&+IABp>BLXm)7uP~zy16$KzKD2?n*OBxNiF&0hVdrM{Dy{^!#KAsa83?Vje-rOl0 zIn2GMs?rD9US6kjt|L#cVf^__vYeyh(?YL{j!XSkS}!y4Dbig|W0g{r?$sQd;%nTz zGih)|;d~xa`*h}WT?fDyW@;b1%`YkEobr%==YsB<%YDA7+<-z$p0fmKVuZH-aCgp) zKEda6tSkGvYV=Y`yG!xsCpKR?EvQSIv=c=YS6!C6+taC3#@eJ)Yn+x1OllzE7FJMJ zGm^nuAC8%Lbr7!JbbVs=>rO<`ae;mfF0@+%3Zk8?^m5-1xIO@9&I4y&g zMmw^*ZjDIxYxk0=G`^0BVFba8Prg2~+U*-BQb6^Cg9-8Aghm}yc_Q}heg%I=jbxjD z;1{~~!;N?1WOmi-ZjP_ndAuiwu1kDkI1t)?v@a*sNi|TwD`tO0NHcldHfPWvB7p%r z@sDq#bPx?$iTYOW4gt%oY0|*4tM83C=0ejSU?zP_7Rk!2q<LaD0T#=bnM$R z_60T&uEMOSuKcm2Zu>F1F zgyKl% z?toHiMjglt6_%$aC#Hmi&i)L@e2~mrRA$fBb+=Pjh;Z(DJ-01PNP96n{N<|zcU8GZ zd%%dlq@NRcf!sOvgq&)szCbzEWY6GXN#LxZSflf*v{1JLqB)L)SjB7%k|W^Icp0OVn0?k2#1B@b7SwEvDy-d zLGzUZ_FZ>*67eFNu|&v#k6M|?2%Hxsc#HfMXzy69iGxz|W5yCNaEYf!haOW;S^43k z%KyCfi%vUfh$=N4vnJ|299^XO)_937HCros)?}^1g4%I$Rj~T~U|!B(<)Ff?9c$kj?4B~ z#r^|{maPS;4LALi@#C#m>0&k&4>7pxw$Q#l@d@w9muHGxb=#MNrOo@C@<;>Hiccn2 z2YQl<$z+W3wa+I#{>t2N(B7EP&sO`HDr}n6BXU~C%S(gtO3{aZr#hz+-b*_IYqnho zT#x~j>_M18TvM(?K>&;WwVU5BU8a9~+mL2RJ4=+G8p^S*=V_c8EQ;Y0^*J3aH?L{a ze43_4RHQe3Yw4j}f0jqF)-LAYq>~0K#MvIR>_Xp~&(kN!e<(lnvJy~XI}PH+G+WHX zkrS~U)29+lhbVS*4nU7%7Wba?S%^^2W)|PckiMO$I&}5PQ0-a)T>N6)Qz*W? zc7#hPxjJMvYI=Uz1sf2!eZVT1xOdTi`m(B>My&~X{M0=2DamvrciOKKfo+pJrs{dX z-{pa$E2<4bYovSkk!V9d{3NxxtlTvfFA;xnbrWvMB(_n}Y49YYxjf)7KXQ8(S_eZ% z?g`$1N>rhMQc)Dk?H#Ouo_)(oG}u#hmg*;*^WvhN(YvKsdi}^YwFiI_9bP1ECk-dm ztS9nWhnQrAu%Ejh+lES(&9qnR#M9fcPKdf(u7L`z_ zQLg9|mcKIc3Svn%i?`v}uMjWr?8fxs_ls}JcA^!R93u;RX91>l;-V4_-t^A@sz=n> zAUI70UyctNkjBs9v8u8i_2iIFMv19hrvsuoaf4rzBSC>Q5T``YVhtNtbi8zNb}j9g zWAQr-s*Y3^M5K56t>&&Re#$OH9Vi~!dDMR$WLurh}Y^YN%P?IUMdTxzSTSd=u`%lk)!z3W{_`N;af zb*o-Nv5W#Z%lAT#XqL*1%8eI21MP|tBN*0 zM-ai?ObTE&3?Gk(`fSU^)Q|qo*fl06X+kmZ_y@DIH6P9yy3bKE>S&U}a#6zaqZ#0?j$i%yo_LS7q89ONYD z{*9|xKLcj|Go`ohU|`z~Qkm(~2PRoSg~-fJz$9+>*R+2B>3s8>jTG&dw+nsPSld6o zcbz}M%g=#I)$?vCW&+uqSY8xMiu*~u4>eU=KsG09ka$^BI203^G|~Q0;k}dnQg*Iz zV~5^Rb(+^w%FM$M?PSr(&S<3ElAY{v^F^N8uXBD?1xMscUpF^qn8Jq-WF6`KouVSEm;>ryo0r?RODToq^|;p;Vfws^16qG#GxkNL`^Z(Y_G{*PnhR z-!N7Am3(gkdFMv*4PShLwIDd)ox4FB9Ajg|F6j zZm=OZ35VIxk25j#J<}{~`@r5l*8Zd10--O$l|?vl-zSL%!mTIr@S`SWm&nF165ceV zDZ(!O0_Jtrf88cqg>#}Ad*0O+Z-U{Vlz3sma>k>`!vu&1eW<9bnfx3&5R%{?kmu(4 z3ZAqkJF8^k0`# zUQ$xIUQTwb%Gxgu7&ZE{6`sJXWauZ&qC7O)@ryN5Tr^FVu-E0FB%y6bUo%IW*65#|c4hFVb63h`a^|CKC*fdt9W%qabz*)%vE ztmXXC=SPlX`?Hkb127Nj#w$3Ngiv9{Rs1xuJ3!IxS50QGU2a@^moqZ3-0*sJEE{$4 z0~|lVKtf(55OcrM;W&`o0@Ji92K~Egk?;dng0VqF>l3W512}AS>Ax`Z(Ygmzkb{0& zcAUM*0oMPZQ*~!o!9Gm4X!jm?2ciu<1-ToEUtvZy@(8?xTXG~PPuLFYvn@#h_knQN z?0$ohEog51<7U{PpO$uqv_>J54Vu6Ok)6!j;k$p$UUEwYnd}j;H`#-KN7ISNe8jfT z&UzW_T3b|qGE-82qfsEB`w$pUaGn^Ad0ZL*+uXUgGi|AxfOI;A35+o{pzH{D=H||$ zV3F&1wUH}1a96Y$JzF0(v-p!kNUtKe3mza=X>ex~T(tmsK7?(Q@!tbM*4*&jG^CmP zbLKi;^3u@8r>|2U#mRW3uTPkeoF#WuX6iiHA0$0zDS$<7PwCbG&D>WX{#>fEoQ9Wh*#<4KH_rsJ=j$^T4Y%--fobyoFpaY z(%_B)B33NS?%=JllquUv?4tzmbjNsY-mw4xN`O*~tMCt`H+(1z*yF(#`m-hF-v?C%xzf2W_{ ku=vCF|Cjm^EL>yTosg8CApDpFwhNs-qotgobnVXn19l=CE&u=k literal 0 HcmV?d00001 diff --git a/_7/pom.xml b/_7/pom.xml new file mode 100644 index 0000000..c9f85bc --- /dev/null +++ b/_7/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + ketaval + 7 + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 6 + 6 + + + + + + + \ No newline at end of file diff --git a/_7/src/main/java/main/Main.java b/_7/src/main/java/main/Main.java new file mode 100644 index 0000000..3235f7a --- /dev/null +++ b/_7/src/main/java/main/Main.java @@ -0,0 +1,10 @@ +package main; + +import swingGUI.DrawingFrame; + +public class Main { + + public static void main(String[] args) { + new DrawingFrame().setVisible(true); + } +} \ No newline at end of file diff --git a/_7/src/main/java/swingGUI/Canvas.form b/_7/src/main/java/swingGUI/Canvas.form new file mode 100644 index 0000000..d4cdb93 --- /dev/null +++ b/_7/src/main/java/swingGUI/Canvas.form @@ -0,0 +1,13 @@ + +
+ + + + + + + + + + +
diff --git a/_7/src/main/java/swingGUI/Canvas.java b/_7/src/main/java/swingGUI/Canvas.java new file mode 100644 index 0000000..5fbcea4 --- /dev/null +++ b/_7/src/main/java/swingGUI/Canvas.java @@ -0,0 +1,82 @@ +package swingGUI; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.util.Random; + +public class Canvas extends JPanel { + + private BufferedImage image; + private Graphics2D graphics; + private int currentMouseX, currentMouseY; + + public Canvas() { + this.setBorder(BorderFactory.createTitledBorder("Drawing paper:")); + setDoubleBuffered(false); + addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + currentMouseX = e.getX(); + currentMouseY = e.getY(); + if (graphics != null) { + int radius = Integer.parseInt(DrawingFrame.form.shapesRadius.getText()); + + drawShapeAt(currentMouseX, currentMouseY, radius); + repaint(); + } + } + }); + } + + protected void paintComponent(Graphics g) { + if (image == null) { + image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB); + graphics = image.createGraphics(); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + clear(); + } + g.drawImage(image, 0, 0, null); + } + + public void clear() { + graphics.setPaint(Color.white); + graphics.fillRect(0, 0, 800, 600); + graphics.setPaint(Color.black); + repaint(); + } + + public void drawShapeAt(int x, int y, int radius) { + Random rand = new Random(); + graphics.setColor(new Color(rand.nextInt(0xFFFFFF))); + + graphics.fillOval(x - (radius / 2), y - (radius / 2), radius, radius); + } + + public void drawShapeRandom(int repeatNo) { + while (repeatNo > 0) { + Random rand = new Random(); + graphics.setColor(new Color(rand.nextInt(0xFFFFFF))); + int random_x = rand.nextInt(getWidth() - 5); + int random_y = rand.nextInt(getHeight() - 20); + int random_radius = rand.nextInt(18 - 5) + 6; + int random_circle_radius = rand.nextInt(50 - 5) + 6; + + graphics.fillOval(random_x, random_y, random_circle_radius, random_circle_radius); + repeatNo--; + } + } + + public BufferedImage getImage() { + return image; + } + + public void setImage(BufferedImage image) { + this.image = image; + graphics = image.createGraphics(); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + } + +} diff --git a/_7/src/main/java/swingGUI/ControlPanel.form b/_7/src/main/java/swingGUI/ControlPanel.form new file mode 100644 index 0000000..919fa0a --- /dev/null +++ b/_7/src/main/java/swingGUI/ControlPanel.form @@ -0,0 +1,13 @@ + +
+ + + + + + + + + + +
diff --git a/_7/src/main/java/swingGUI/ControlPanel.java b/_7/src/main/java/swingGUI/ControlPanel.java new file mode 100644 index 0000000..b2a9121 --- /dev/null +++ b/_7/src/main/java/swingGUI/ControlPanel.java @@ -0,0 +1,21 @@ +package swingGUI; + +import javax.swing.*; + +public class ControlPanel extends JPanel { + private final DrawingFrame frame; + JButton loadButton = new JButton("Load"); + JButton saveButton = new JButton("Save"); + JButton resetButton = new JButton("Reset"); + + public ControlPanel(DrawingFrame frame) { + this.frame = frame; + init(); + } + + private void init() { + add(loadButton); + add(saveButton); + add(resetButton); + } +} \ No newline at end of file diff --git a/_7/src/main/java/swingGUI/DrawingFrame.form b/_7/src/main/java/swingGUI/DrawingFrame.form new file mode 100644 index 0000000..6661430 --- /dev/null +++ b/_7/src/main/java/swingGUI/DrawingFrame.form @@ -0,0 +1,13 @@ + +
+ + + + + + + + + + +
diff --git a/_7/src/main/java/swingGUI/DrawingFrame.java b/_7/src/main/java/swingGUI/DrawingFrame.java new file mode 100644 index 0000000..d9a4b2e --- /dev/null +++ b/_7/src/main/java/swingGUI/DrawingFrame.java @@ -0,0 +1,79 @@ +package swingGUI; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; + +public class DrawingFrame extends JFrame { + private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + private int height = screenSize.height / 2; + private int width = screenSize.width / 2; + static Toolbar form; + private Canvas drawArea; + private ControlPanel control; + + private ActionListener actionListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if(e.getSource() == control.resetButton) { + drawArea.clear(); + } else if (e.getSource() == control.loadButton) { + try { + load(); + } catch (IOException e1) { + System.out.println("Fisierul nu exista sau formatul nu este bun."); + } + } else if (e.getSource() == control.saveButton) { + try { + save(); + } catch (IOException e1) { + System.out.println("Destinatia nu exista sau nu ai drept de salvare."); + } + } else if (e.getSource() == form.drawButton) { + int repeat = Integer.parseInt(form.shapesNo.getText()); + + drawArea.drawShapeRandom(repeat); + repaint(); + } + } + }; + + public DrawingFrame() { + super("JAVA Paint"); + rootPane.setBorder(BorderFactory.createTitledBorder("Drawing panel")); + rootPane.setPreferredSize(new Dimension(width, height)); + init(); + addComponents(); + this.pack(); + } + + private void init() { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + form = new Toolbar(this); + drawArea = new Canvas(); + control = new ControlPanel(this); + form.drawButton.addActionListener(actionListener); + control.resetButton.addActionListener(actionListener); + control.saveButton.addActionListener(actionListener); + control.loadButton.addActionListener(actionListener); + } + + private void addComponents(){ + add(form, BorderLayout.NORTH); + add(drawArea, BorderLayout.CENTER); + add(control, BorderLayout.SOUTH); + } + + private void save() throws IOException { + ImageIO.write(drawArea.getImage(), "PNG", new File("lab6_node.png")); + } + + private void load() throws IOException { + drawArea.setImage(ImageIO.read(new File("lab6_node.png"))); + repaint(); + } +} \ No newline at end of file diff --git a/_7/src/main/java/swingGUI/Toolbar.form b/_7/src/main/java/swingGUI/Toolbar.form new file mode 100644 index 0000000..8957f94 --- /dev/null +++ b/_7/src/main/java/swingGUI/Toolbar.form @@ -0,0 +1,13 @@ + +
+ + + + + + + + + + +
diff --git a/_7/src/main/java/swingGUI/Toolbar.java b/_7/src/main/java/swingGUI/Toolbar.java new file mode 100644 index 0000000..7331ab8 --- /dev/null +++ b/_7/src/main/java/swingGUI/Toolbar.java @@ -0,0 +1,36 @@ +package swingGUI; + +import javax.swing.*; +import java.awt.*; + +public class Toolbar extends JPanel { + private Integer[] sidesNo = { 0, 3, 4, 5, 6, 7, 8 }; + + private JLabel shapeNoLabel = new JLabel("Shapes number: "); + private JLabel radiusLabel = new JLabel("Radius: "); + + JTextField shapesNo = new JFormattedTextField(); + JTextField shapesRadius = new JFormattedTextField(); + + JButton drawButton = new JButton("Draw"); + + public Toolbar(DrawingFrame frame) { + this.setBorder(BorderFactory.createTitledBorder("Toolbar")); + init(); + this.setLayout(new GridLayout(2,4, 20, 0)); + } + + private void init() { + + shapesRadius.setText("5"); + shapesNo.setText("1"); + + add(shapeNoLabel); + add(radiusLabel); + add(drawButton); + + add(shapesNo); + add(shapesRadius); + } + +} \ No newline at end of file diff --git a/_8/pom.xml b/_8/pom.xml new file mode 100644 index 0000000..f678417 --- /dev/null +++ b/_8/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + ketaval + 8 + 1.0-SNAPSHOT + + + \ No newline at end of file From 96b4cecbaaf2999647e2b14bfbe055af1dc95663 Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 18:21:50 +0300 Subject: [PATCH 16/26] lab8 --- _8/src/main/java/model/Board.java | 4 ++++ _8/src/main/java/model/Game.java | 4 ++++ _8/src/main/java/model/Player.java | 4 ++++ _8/src/main/java/service/GameService.java | 4 ++++ 4 files changed, 16 insertions(+) create mode 100644 _8/src/main/java/model/Board.java create mode 100644 _8/src/main/java/model/Game.java create mode 100644 _8/src/main/java/model/Player.java create mode 100644 _8/src/main/java/service/GameService.java diff --git a/_8/src/main/java/model/Board.java b/_8/src/main/java/model/Board.java new file mode 100644 index 0000000..58d0dc6 --- /dev/null +++ b/_8/src/main/java/model/Board.java @@ -0,0 +1,4 @@ +package model; + +public class Board { +} diff --git a/_8/src/main/java/model/Game.java b/_8/src/main/java/model/Game.java new file mode 100644 index 0000000..4fe5b9e --- /dev/null +++ b/_8/src/main/java/model/Game.java @@ -0,0 +1,4 @@ +package model; + +public class Game { +} diff --git a/_8/src/main/java/model/Player.java b/_8/src/main/java/model/Player.java new file mode 100644 index 0000000..d9a4f4e --- /dev/null +++ b/_8/src/main/java/model/Player.java @@ -0,0 +1,4 @@ +package model; + +public class Player { +} diff --git a/_8/src/main/java/service/GameService.java b/_8/src/main/java/service/GameService.java new file mode 100644 index 0000000..0cfb3f9 --- /dev/null +++ b/_8/src/main/java/service/GameService.java @@ -0,0 +1,4 @@ +package service; + +public class GameService { +} From 0ba2e1774cf2a05849e85721e609be9130b504a9 Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 18:24:19 +0300 Subject: [PATCH 17/26] lab8 --- _8/src/main/java/model/Edge.java | 4 ++++ _8/src/main/java/model/Graph.java | 4 ++++ 2 files changed, 8 insertions(+) create mode 100644 _8/src/main/java/model/Edge.java create mode 100644 _8/src/main/java/model/Graph.java diff --git a/_8/src/main/java/model/Edge.java b/_8/src/main/java/model/Edge.java new file mode 100644 index 0000000..07dc3ed --- /dev/null +++ b/_8/src/main/java/model/Edge.java @@ -0,0 +1,4 @@ +package model; + +public class Edge { +} diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java new file mode 100644 index 0000000..b2c0218 --- /dev/null +++ b/_8/src/main/java/model/Graph.java @@ -0,0 +1,4 @@ +package model; + +public class Graph { +} From a80c2a7285a2f3a76d180e769a10d2e32bf670e1 Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 18:26:38 +0300 Subject: [PATCH 18/26] construuctors getters and setters --- _8/src/main/java/model/Edge.java | 23 +++++++++++++++++++++++ _8/src/main/java/model/Graph.java | 15 +++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/_8/src/main/java/model/Edge.java b/_8/src/main/java/model/Edge.java index 07dc3ed..2f3840c 100644 --- a/_8/src/main/java/model/Edge.java +++ b/_8/src/main/java/model/Edge.java @@ -1,4 +1,27 @@ package model; public class Edge { + private int source; + private int destination; + + public Edge(int source, int destination) { + this.source = source; + this.destination = destination; + } + + public int getSource() { + return source; + } + + public void setSource(int source) { + this.source = source; + } + + public int getDestination() { + return destination; + } + + public void setDestination(int destination) { + this.destination = destination; + } } diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index b2c0218..d98d729 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -1,4 +1,19 @@ package model; +import java.util.List; + public class Graph { + List edges; + + public Graph(List edges) { + this.edges = edges; + } + + public List getEdges() { + return edges; + } + + public void setEdges(List edges) { + this.edges = edges; + } } From 7e30c136137644c42dff59fbaa9f4e45ef2b4f0e Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 18:55:41 +0300 Subject: [PATCH 19/26] Player and Game code --- Lab6/out/production/Lab6/resources/canvas.png | Bin 0 -> 5668 bytes .../out/production/Lab6/resources/default.png | Bin 0 -> 1941 bytes Lab6/src/com/company/Main.java | 10 + Lab6/src/gui/Canvas.java | 207 ++++++++++++++++++ Lab6/src/gui/ControlPanel.java | 58 +++++ Lab6/src/gui/Display.java | 7 + Lab6/src/gui/DrawingFrame.java | 35 +++ Lab6/src/gui/EdgeDisplay.java | 66 ++++++ Lab6/src/gui/Graph.java | 52 +++++ Lab6/src/gui/NodeDisplay.java | 46 ++++ Lab6/src/gui/NodeShape.java | 9 + Lab6/src/gui/Toolbar.java | 36 +++ Lab6/src/resources/canvas.png | Bin 0 -> 4348 bytes Lab6/src/resources/default.png | Bin 0 -> 1941 bytes _8/pom.xml | 12 + _8/src/main/java/Main.java | 14 ++ _8/src/main/java/model/Game.java | 38 ++++ _8/src/main/java/model/Graph.java | 4 + _8/src/main/java/model/Player.java | 70 +++++- 19 files changed, 663 insertions(+), 1 deletion(-) create mode 100644 Lab6/out/production/Lab6/resources/canvas.png create mode 100644 Lab6/out/production/Lab6/resources/default.png create mode 100644 Lab6/src/com/company/Main.java create mode 100644 Lab6/src/gui/Canvas.java create mode 100644 Lab6/src/gui/ControlPanel.java create mode 100644 Lab6/src/gui/Display.java create mode 100644 Lab6/src/gui/DrawingFrame.java create mode 100644 Lab6/src/gui/EdgeDisplay.java create mode 100644 Lab6/src/gui/Graph.java create mode 100644 Lab6/src/gui/NodeDisplay.java create mode 100644 Lab6/src/gui/NodeShape.java create mode 100644 Lab6/src/gui/Toolbar.java create mode 100644 Lab6/src/resources/canvas.png create mode 100644 Lab6/src/resources/default.png create mode 100644 _8/src/main/java/Main.java diff --git a/Lab6/out/production/Lab6/resources/canvas.png b/Lab6/out/production/Lab6/resources/canvas.png new file mode 100644 index 0000000000000000000000000000000000000000..8d0c34c3ede7ab6a0a61d64fb293b9cfed09f7db GIT binary patch literal 5668 zcmeHKYgAKL7QQ;ZCIw;@op7Fac(tdl@6{d6$s3-( zG<5JnU9j3#Qt2H$;oz{{<(|>|{g(@56YK52{K|JVnuwlIEr$x>oZ3gr!2b~gFH$$i zgV==v-lpK#ymjp-T_Ra=je?IN<|b8Bfwqyy-mYt(2=UPYCn5!2&XkYT7G}L=9PGlB zn2N5ZZ$|99-N)t?u-VVQG{v>9Bb#f!3bg;w=sSIKzj@QZ>!ZcD!cxu_m3>(=AEgM zsI68cnSzIx2=fBj>YeTHvrd5gX-$tqm~jy|!oDXAfJI}nEhJU39-Ivh0jGgB;mY2bKj?Lavv8(QfinGMdSKP0 zc_ek*Go&n}SnBf`Y)k9?K5_G*bT!dBl12a6kh}PzvAgCK;+^k1y0G&dMOibXoUqt@ z|JgZs`GEd<7-W{6@_J{2VI@xvuk0EmEB0eKGqGGyn~gzmBjNd-uf0f|nN*>w5F11R z9Vam2wlhpH$cbWd{AAlX6lMHfIP#VaF6JIH>SX$0v;6g*08C5EK0y*MkU3n!!D%|I^^|eMv^Bx8XEbE_ z5_>9#%PffZC&bVKt|4IDXR zOo6*M-(T=`pItr(zsp^E`CNKD%_))<Hw!zR^EV7ap9GgNo(v}8QKC>we8 zQv8cgnHFU3rJv~>Snf$(TJZzE+DFR(VBiW#iMx^%`eXu+es@<)sW1^8b50o2X<;@- zsQOxeQAwn!dVh?9A`fNpO?rUsNRmuH{@R;!wBj&CB8YxUv+5(ZBQ=K&IH8B)?hjjI zKy0%qA6A&6cy46;lT3NQbP1J?j1KQIe>T~6#4aL$^Nk4OkiZH?g6K!_b2(CKh0hj% z^}arp!)Z*s0OTYoLdVX+|cy+^Wgo5c<@g2{-nrmWsGV95T7$aT(A!R z*9c`^#zGJxf)J13`Y-1GkTS#RT^|g#BYho4Tmc^utF&H@A+7o&OJeOcAW#s6OMW7O z_0R+nIp`-_jdK2WeJiqOXuHJ?WP^||JL$?^Mm?#$#~kQ8)YLssN%;y^J+oyZBF%2G z;)CuS@)PA3+lccMsekQ8v>a+8SKV~ESV?ld<_usP>9TS$bqy=}DIbyOD_g`F12e)4 z;*P|MYhbQH`ol1xu_?{++?umMUelVaveK)f9TIkr;o$1jsuxFJurw>4N!tRXT@eB{ z2d^p9!xcr5zv@}2Fh|f?IQzA17`;U_YK0P~I1kS@tQpfk+p05rkUd`~%l~JH>Lk{( zx>2AzYL_=OH~l(LQICCYvV{M2l^)pd`l9ss`)A;C#vsk3F!G9?oeHdK>+5VQ1_{tOR+i`Q+n7@t&R8-M}Y51n_?@rlW( zd-r@fv^2#rzF$*K3d2X-fEsT5B%6cYv?Q__)-dGlIEY_73J++2bh~r$Dc(dx%M*Z) z1IYZ*@rLV3gUCqVyj1?7Z=5XgdZVG7Z`!A>HX$sK=mW&^_jhcFZU50aCd?{wqD>-* zWyW7eAMPx@AU+W0rda? literal 0 HcmV?d00001 diff --git a/Lab6/out/production/Lab6/resources/default.png b/Lab6/out/production/Lab6/resources/default.png new file mode 100644 index 0000000000000000000000000000000000000000..8099bf7a9fb2d9b1307caeda3d13ae7245353fe6 GIT binary patch literal 1941 zcmeAS@N?(olHy`uVBq!ia0y~yU{+vYV2a>i1B%QlYbs!1V2|;1aSW-r_4c44BT(?r zg0KF$Z1oF(%uz5J0;3@?8UmvsFd71*AwW(D*f9riGcd*!a+HE}d%F6$taD0e0ssUP B6Egq+ literal 0 HcmV?d00001 diff --git a/Lab6/src/com/company/Main.java b/Lab6/src/com/company/Main.java new file mode 100644 index 0000000..35b028f --- /dev/null +++ b/Lab6/src/com/company/Main.java @@ -0,0 +1,10 @@ +package com.company; + +import gui.DrawingFrame; + +public class Main { + + public static void main(String[] args) { + new DrawingFrame().setVisible(true); + } +} diff --git a/Lab6/src/gui/Canvas.java b/Lab6/src/gui/Canvas.java new file mode 100644 index 0000000..2d73861 --- /dev/null +++ b/Lab6/src/gui/Canvas.java @@ -0,0 +1,207 @@ +package gui; + +import javax.imageio.ImageIO; +import javax.swing.*; +//import java.awt.*; +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.List; + +import static java.lang.Thread.sleep; + +public class Canvas extends JPanel { + private final DrawingFrame frame; + //Graphics graphics; + Graph graph=new Graph(); + Graphics2D graphics = graph.getImage().createGraphics(); + int startX, startY; + Point endPoint=null; + Point startPoint=null; +// Boolean move=false; + + +// private List displayNodesList = new ArrayList<>(); +// private List displayEdgesList= new ArrayList<>(); + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); +// graphics=(Graphics2D) g; +// String radiusStr=frame.getToolbar().getRadius(); +// int radius=Integer.parseInt(radiusStr); +// drawNode(x, y, radius); + frame.repaint(); + g.drawImage(graph.getImage(),0,0,null); + if(startPoint!=null && endPoint!=null && frame.getToolbar().getForm()=="Edge" && frame.getControlPanel().getAction()=="Draw") + drawEdge(startPoint.x,startPoint.y,endPoint.x,endPoint.y); + } + + public Canvas(DrawingFrame frame) { + super(); +// endPoint.x=0; +// endPoint.y=0; + this.frame=frame; + init(); + } + public void init() + { + this.setBackground(Color.white); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //for "smooth" drawing + this.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + //drawNode(e.getX(), e.getY()); + startX=e.getX(); + startY=e.getY(); + //repaint(); + String radiusStr=frame.getToolbar().getRadius(); + int radius=Integer.parseInt(radiusStr); + if(frame.getToolbar().getForm()=="Node" && frame.getControlPanel().getAction()=="Draw") + drawNode(startX,startY,radius); + else if(frame.getControlPanel().getAction()=="Erase") + delete(startX, startY); + } + public void mousePressed(MouseEvent e) { + startPoint = e.getPoint(); + } + + public void mouseReleased(MouseEvent e) { + startPoint = null; + } + }); + + this.addMouseMotionListener(new MouseMotionAdapter() { + + public void mouseMoved(MouseEvent e) { + endPoint = e.getPoint(); + } + + public void mouseDragged(MouseEvent e) { + endPoint = e.getPoint(); +// repaint(); + } + }); + } + + + + public void drawNode(int x, int y, int radius) { + //Random rand = new Random(); + String colorStr=frame.getToolbar().getColor(); +// if(colorStr=="Blue") + //graphics.setColor(new Color(rand.nextInt(0xFFFFFF))); //you may use a random color or the one specified in the toolbar + graphics.setColor(transformColor(colorStr)); + graphics.fill(new NodeShape(x, y, radius)); + NodeDisplay d = new NodeDisplay(x,y,radius,transformColor(colorStr)); + graph.addNode(d); + + } + + public void drawEdge(int stX, int stY, int finX, int finY) + { + String colorStr1=frame.getToolbar().getColor(); + graphics.setColor(transformColor(colorStr1)); + graphics.setStroke(new BasicStroke(Integer.parseInt(frame.getToolbar().getRadius()))); + graphics.drawLine(stX, stY, finX, finY); + EdgeDisplay e = new EdgeDisplay(stX, stY, finX, finY,transformColor(colorStr1),Integer.parseInt(frame.getToolbar().getRadius())); + graph.addEdge(e); +// g.drawLine(stX, stY, finX, finY); + } + + public Color transformColor(String color) + { + Map colorMap = new HashMap<>(); + colorMap.put("Blue",Color.blue); + colorMap.put("Red",Color.red); + colorMap.put("Green",Color.green); + colorMap.put("Yellow",Color.yellow); + colorMap.put("Black",Color.black); + colorMap.put("Gray",Color.gray); + colorMap.put("Cyan",Color.cyan); + for(String it:colorMap.keySet()) + { + if(it==color) + return colorMap.get(it); + } + Random defaultColor=new Random(); + return new Color(defaultColor.nextInt(0xFFFFFF)); + + } + + public void resetAll() + { + graph.setImage(new BufferedImage(1366, 720, BufferedImage.TYPE_INT_ARGB)) ; + graphics = graph.getImage().createGraphics(); + new Canvas(frame); + } + + public void loadDefault() + { + try { + graph.setImage( ImageIO.read(new File("src/resources/canvas.png"))); + } catch (IOException e) { + e.printStackTrace(); + } + graphics = graph.getImage().createGraphics(); + new Canvas(frame); + + } + + private void delete(int x, int y) + { + deleteNode(x,y); + deleteEdge(x,y); + resetAll(); + redrawNodes(); + redrawEdges(); + } + + private void deleteNode(int x, int y){ + for(NodeDisplay n : graph.getDisplayNodeList()) + { + int r=n.getRadius(); + int minX=n.getCoordX()-r; + int maxX=n.getCoordX()+r; + int minY=n.getCoordY()-r; + int maxY=n.getCoordY()+r; + + if(x>=minX && x<=maxX && y>=minY && y<=maxY) + { + graph.deleteNode(n); + break; + } + } + } + + private void redrawNodes() + { + for(NodeDisplay n:graph.getDisplayNodeList()) + { + drawNode(n.getCoordX(),n.getCoordY(),n.getRadius()); + try { + sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + private void deleteEdge(int x, int y){ + + } + private void redrawEdges() + { + for(EdgeDisplay e:graph.getDisplayEdgeList()) + { + drawEdge(e.getStartX(),e.getStartY(),e.getEndX(),e.getEndY()); + } + } + + public Graph getGraph() + { + return this.graph; + } +} diff --git a/Lab6/src/gui/ControlPanel.java b/Lab6/src/gui/ControlPanel.java new file mode 100644 index 0000000..0c0c51a --- /dev/null +++ b/Lab6/src/gui/ControlPanel.java @@ -0,0 +1,58 @@ +package gui; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.awt.event.ActionEvent; + +public class ControlPanel extends JPanel { + private final DrawingFrame frame; + private JComboBox action; + + public ControlPanel(DrawingFrame frame) { + this.frame=frame; + this.setLayout(new FlowLayout()); + + this.setBorder(BorderFactory.createLineBorder(Color.blue)); + init(); + } + public void init() { + JButton loadButton = new JButton("Load"); + JButton saveButton = new JButton("Save"); + JButton resetButton = new JButton("Reset"); + String actionFields[]={"Draw", "Erase"}; + action=new JComboBox<>(actionFields); + loadButton.addActionListener(this::loadFunction); + saveButton.addActionListener(this::saveFunction); + resetButton.addActionListener(this::resetFunction); + this.add(action); + this.add(loadButton); + this.add(saveButton); + this.add(resetButton); + } + + private void saveFunction(ActionEvent e) { + try { + ImageIO.write(frame.getCanvas().getGraph().getImage(), "png", new File("src/resources/canvas.png")); + } catch (IOException e1) { + e1.printStackTrace(); + } + + } + + private void resetFunction(ActionEvent e) + { + frame.getCanvas().resetAll(); + } + + private void loadFunction(ActionEvent e) + { + frame.getCanvas().loadDefault(); + } + public String getAction() + { + return action.getSelectedItem().toString(); + } +} diff --git a/Lab6/src/gui/Display.java b/Lab6/src/gui/Display.java new file mode 100644 index 0000000..a4f8ec4 --- /dev/null +++ b/Lab6/src/gui/Display.java @@ -0,0 +1,7 @@ +package gui; + +import java.awt.*; + +public interface Display { + public Color getColor(); +} diff --git a/Lab6/src/gui/DrawingFrame.java b/Lab6/src/gui/DrawingFrame.java new file mode 100644 index 0000000..c1fa35e --- /dev/null +++ b/Lab6/src/gui/DrawingFrame.java @@ -0,0 +1,35 @@ +package gui; + +import javax.swing.*; +import java.awt.*; + +public class DrawingFrame extends JFrame { + private Toolbar toolbar; + private Canvas canvas; + private ControlPanel controlPanel; + + public DrawingFrame() { + super("Graph drawing manager"); + toolbar=new Toolbar(this); + canvas =new Canvas(this); + controlPanel=new ControlPanel(this); + init(); + } + + private void init(){ + setDefaultCloseOperation(EXIT_ON_CLOSE); + this.setSize(600, 600); + this.add(toolbar, BorderLayout.NORTH); + this.add(canvas,BorderLayout.CENTER); + this.add(controlPanel, BorderLayout.SOUTH); +// this.pack(); + this.setVisible(true); + } + + public Toolbar getToolbar() + { + return toolbar; + } + public Canvas getCanvas() { return canvas; } + public ControlPanel getControlPanel() { return controlPanel; } +} diff --git a/Lab6/src/gui/EdgeDisplay.java b/Lab6/src/gui/EdgeDisplay.java new file mode 100644 index 0000000..b3c753e --- /dev/null +++ b/Lab6/src/gui/EdgeDisplay.java @@ -0,0 +1,66 @@ +package gui; + +import java.awt.*; + +public class EdgeDisplay implements Display{ + private int startX, startY, endX, endY; + private Color color; + private int stroke; + + public EdgeDisplay(int startX, int startY, int endX, int endY, Color color, int stroke) { + this.startX = startX; + this.startY = startY; + this.endX = endX; + this.endY = endY; + this.color = color; + this.stroke = stroke; + } + + public int getStartX() { + return startX; + } + + public int getStartY() { + return startY; + } + + public int getEndX() { + return endX; + } + + public int getEndY() { + return endY; + } + + public Color getColor() { + return color; + } + + public int getStroke() { + return stroke; + } + + public void setStartX(int startX) { + this.startX = startX; + } + + public void setStartY(int startY) { + this.startY = startY; + } + + public void setEndX(int endX) { + this.endX = endX; + } + + public void setEndY(int endY) { + this.endY = endY; + } + + public void setColor(Color color) { + this.color = color; + } + + public void setStroke(int stroke) { + this.stroke = stroke; + } +} diff --git a/Lab6/src/gui/Graph.java b/Lab6/src/gui/Graph.java new file mode 100644 index 0000000..d44e6de --- /dev/null +++ b/Lab6/src/gui/Graph.java @@ -0,0 +1,52 @@ +package gui; + +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; + +public class Graph { + private List displayNodeList ; + private List displayEdgeList ; + private BufferedImage image; + public Graph() { + this.displayNodeList = new ArrayList(); + this.displayEdgeList = new ArrayList(); + image=new BufferedImage(1366, 720, BufferedImage.TYPE_INT_ARGB); + } + + public void addEdge(EdgeDisplay e) + { + displayEdgeList.add(e); + } + + public void addNode(NodeDisplay n) + { + displayNodeList.add(n); + } + + public void deleteEdge(EdgeDisplay e) + { + displayEdgeList.remove(e); + } + + public void deleteNode(NodeDisplay n) + { + displayNodeList.remove(n); + } + + public List getDisplayNodeList() { + return displayNodeList; + } + + public List getDisplayEdgeList() { + return displayEdgeList; + } + + public BufferedImage getImage() { + return image; + } + + public void setImage(BufferedImage image) { + this.image = image; + } +} diff --git a/Lab6/src/gui/NodeDisplay.java b/Lab6/src/gui/NodeDisplay.java new file mode 100644 index 0000000..b22b400 --- /dev/null +++ b/Lab6/src/gui/NodeDisplay.java @@ -0,0 +1,46 @@ +package gui; + +import java.awt.*; + +public class NodeDisplay implements Display { + private int coordX, coordY, radius; + private Color color; + public NodeDisplay(int coordX, int coordY, int radius, Color color) { + this.coordX = coordX; + this.coordY = coordY; + this.radius = radius; + this.color = color; + } + + public int getCoordX() { + return coordX; + } + + public int getCoordY() { + return coordY; + } + + public int getRadius() { + return radius; + } + + public Color getColor() { + return color; + } + + public void setCoordX(int coordX) { + this.coordX = coordX; + } + + public void setCoordY(int coordY) { + this.coordY = coordY; + } + + public void setRadius(int radius) { + this.radius = radius; + } + + public void setColor(Color color) { + this.color = color; + } +} diff --git a/Lab6/src/gui/NodeShape.java b/Lab6/src/gui/NodeShape.java new file mode 100644 index 0000000..c79f97a --- /dev/null +++ b/Lab6/src/gui/NodeShape.java @@ -0,0 +1,9 @@ +package gui; + +import java.awt.geom.Ellipse2D; + +public class NodeShape extends Ellipse2D.Double { + public NodeShape(double x0, double y0, double radius) { + super(x0 - radius / 2, y0 - radius / 2, radius, radius); + } +} diff --git a/Lab6/src/gui/Toolbar.java b/Lab6/src/gui/Toolbar.java new file mode 100644 index 0000000..ec44d9a --- /dev/null +++ b/Lab6/src/gui/Toolbar.java @@ -0,0 +1,36 @@ +package gui; + +import javax.swing.*; +import java.awt.*; + +public class Toolbar extends JPanel { + private final DrawingFrame frame; + private JComboBox form; + private JComboBox color; + private TextField radiusField; + public Toolbar(DrawingFrame frame) { + this.frame=frame; + init(); + } + public void init(){ + String Fields[]={"Node", "Edge"}; + String Colors[]={"Random", "Blue", "Red", "Black", "Gray", "Yellow", "Green", "Cyan"}; + form=new JComboBox<>(Fields); + color=new JComboBox<>(Colors); + radiusField=new TextField("30"); + JLabel radiusLabel=new JLabel("Radius/Thickness"); + this.setLayout(new FlowLayout()); + this.add(radiusLabel); + this.add(radiusField); + this.add(form); + this.add(color); + + + } + public String getRadius() + { + return radiusField.getText(); + } + public String getColor() {return color.getSelectedItem().toString();} + public String getForm() {return form.getSelectedItem().toString();} +} diff --git a/Lab6/src/resources/canvas.png b/Lab6/src/resources/canvas.png new file mode 100644 index 0000000000000000000000000000000000000000..567e6a259cc91de5ec57c72eaa08b1807bec96a2 GIT binary patch literal 4348 zcmeAS@N?(olHy`uVBq!ia0y~yU=3qnV7kD;1{A3-*N$Xh5IF4V;uunK>+M}bKWRr1 zwg*#hMCLj=PGtVc;BsiQLSVof!=MX+PZ&h>G%Q$B`yMI>?C?m`oLHt4=yT(Q2&b>i z2esY*>|UOncK7eo^~=p&8G$B`f+ zBrUM?^J%4c8EzhsgDqlqu04IFhHLhYciva*=Y%Y+Se(ELlHfacF|96Y>5f|q1OAqp z72eI?=_LdbpRvzI+qtW}K6b^vdDXX9gM<#0JdKPjJ$u-C+A96et~)^~kHP1Xb^fY- z_hP_i&6xCW*(*8ktMeZ}(*j8v$nIQw|4YDCKK>}t*PDeKnL&b!!Z{ zD0}h|?8FAyR=s;bW6WTthL(P;`4P-;b}Gc!kEe2F%?fQ3HqPq$db9HZ*s4J7;5~95 z9 zpO02ce$=)HnTBTm+Zi!`E{6a}F(`h2zr8$Rma9i$f|i77uKRU=+yAXcxA)7l zfXakXFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OgE<8D|7JY2Yxb-nd4Y`}XL`E& KxvXi1B%QlYbs!1V2|;1aSW-r_4c44BT(?r zg0KF$Z1oF(%uz5J0;3@?8UmvsFd71*AwW(D*f9riGcd*!a+HE}d%F6$taD0e0ssUP B6Egq+ literal 0 HcmV?d00001 diff --git a/_8/pom.xml b/_8/pom.xml index f678417..7eea098 100644 --- a/_8/pom.xml +++ b/_8/pom.xml @@ -7,6 +7,18 @@ ketaval 8 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 7 + 7 + + + + \ No newline at end of file diff --git a/_8/src/main/java/Main.java b/_8/src/main/java/Main.java new file mode 100644 index 0000000..cb191ed --- /dev/null +++ b/_8/src/main/java/Main.java @@ -0,0 +1,14 @@ +import model.Board; +import model.Game; +import model.Player; + +public class Main { + public static void main(String args[]) { + Game game = new Game(); + game.setBoard(new Board(10)); + game.addPlayer(new Player("Player 1")); + game.addPlayer(new Player("Player 2")); + game.addPlayer(new Player("Player 3")); + game.start(); + } +} diff --git a/_8/src/main/java/model/Game.java b/_8/src/main/java/model/Game.java index 4fe5b9e..4c09176 100644 --- a/_8/src/main/java/model/Game.java +++ b/_8/src/main/java/model/Game.java @@ -1,4 +1,42 @@ package model; +import java.util.ArrayList; +import java.util.List; + public class Game { + private Board board; + private final List players = new ArrayList<>(); + private Player winner; + + public void addPlayer(Player player) { + players.add(player); + player.setGame(this); + } + //Create getters and setters + + public Board getBoard() { + return board; + } + + public void setBoard(Board board) { + this.board = board; + } + + public List getPlayers() { + return players; + } + + + //Create the method that will start the game: start one thread for each player + public void startGame() { + // TODO: code this + } + + public void setWinner(Player player) { + this.winner = player; + } + + public void start() { + + } } diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index d98d729..fb453e6 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -16,4 +16,8 @@ public List getEdges() { public void setEdges(List edges) { this.edges = edges; } + + public void addEdge(Edge edge){ + edges.add(edge); + } } diff --git a/_8/src/main/java/model/Player.java b/_8/src/main/java/model/Player.java index d9a4f4e..7d00c66 100644 --- a/_8/src/main/java/model/Player.java +++ b/_8/src/main/java/model/Player.java @@ -1,4 +1,72 @@ package model; -public class Player { +public class Player implements Runnable{ + private String name; + private Game game; + private Graph graph; + + public Player(String name) { + this.name = name; + } + + public Player(String name, Game game, Graph graph) { + this.name = name; + this.game = game; + this.graph = graph; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public Graph getGraph() { + return graph; + } + + public void setGraph(Graph graph) { + this.graph = graph; + } + + private boolean play() throws InterruptedException { + Board board = game.getBoard(); + if (board.isEmpty()) { return false; } + graph.addEdge( board.extract() ); + Thread.sleep(THINKING_TIME); //declare this constant + if (graph.isSpanningTree()) { + game.setWinner(this); + } + return true; + } + + public void run() { + + } + // implement the run() method, that will repeatedly extract edges + // implement the toString() method + + + @Override + public String toString() { + return "Player{" + + "name='" + name + '\'' + + ", game=" + game + + ", graph=" + graph + + '}'; + } + + private final static int THINKING_TIME = 2000; + + } From 628f35b1cd59de5efebcecb2303067e1c3bb6ad4 Mon Sep 17 00:00:00 2001 From: Onatek Date: Fri, 5 Apr 2019 19:01:11 +0300 Subject: [PATCH 20/26] added board --- _8/src/main/java/model/Board.java | 28 ++++++++++++++++++++++++++++ _8/src/main/java/model/Graph.java | 7 +++++++ 2 files changed, 35 insertions(+) diff --git a/_8/src/main/java/model/Board.java b/_8/src/main/java/model/Board.java index 58d0dc6..5412cab 100644 --- a/_8/src/main/java/model/Board.java +++ b/_8/src/main/java/model/Board.java @@ -1,4 +1,32 @@ package model; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + public class Board { + + private final Graph complete; + + public Board(int n){ + + List edges = null; + int edgeCount = 0; + for (int i = 0; i < n-1 ; i++) { + for (int j = i+1; j < n ; j++) { + edges.set(edgeCount, new Edge(i, j)); + } + } + + Collections.shuffle(edges); + complete = new Graph(edges); + + } + + public synchronized Edge extract(){ + + Edge edge = complete.pullFirst(); + return edge; + } + } diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index d98d729..3276e84 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -13,6 +13,13 @@ public List getEdges() { return edges; } + public Edge pullFirst(){ + + Edge edge = edges.get(0); + + return edge; + } + public void setEdges(List edges) { this.edges = edges; } From 337c502dabd54b3481b667150681af5d7cc3349a Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 19:02:26 +0300 Subject: [PATCH 21/26] Extract edge --- _8/src/main/java/model/Graph.java | 6 ++++++ _8/src/main/java/model/Player.java | 7 ++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index fb453e6..50cb79c 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -1,6 +1,7 @@ package model; import java.util.List; +import java.util.Random; public class Graph { List edges; @@ -20,4 +21,9 @@ public void setEdges(List edges) { public void addEdge(Edge edge){ edges.add(edge); } + + public void extractEdge() { + Random rand = new Random(); + edges.remove(rand.nextInt(edges.size()-1)+1); + } } diff --git a/_8/src/main/java/model/Player.java b/_8/src/main/java/model/Player.java index 7d00c66..418acdb 100644 --- a/_8/src/main/java/model/Player.java +++ b/_8/src/main/java/model/Player.java @@ -51,18 +51,15 @@ private boolean play() throws InterruptedException { } public void run() { - + System.out.println(this.toString() + " is playing..."); + this.graph.extractEdge(); } - // implement the run() method, that will repeatedly extract edges - // implement the toString() method @Override public String toString() { return "Player{" + "name='" + name + '\'' + - ", game=" + game + - ", graph=" + graph + '}'; } From 7c1fd70950344af3b061af1971c127c71e538f33 Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 19:03:23 +0300 Subject: [PATCH 22/26] . --- _8/src/main/java/model/Player.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_8/src/main/java/model/Player.java b/_8/src/main/java/model/Player.java index 418acdb..e8a55c7 100644 --- a/_8/src/main/java/model/Player.java +++ b/_8/src/main/java/model/Player.java @@ -51,8 +51,8 @@ private boolean play() throws InterruptedException { } public void run() { - System.out.println(this.toString() + " is playing..."); this.graph.extractEdge(); + System.out.println(this.toString() + " extracted an edge..."); } From fd084286db88ac53f767264e0d6fd3afaff81523 Mon Sep 17 00:00:00 2001 From: Onatek Date: Fri, 5 Apr 2019 19:05:29 +0300 Subject: [PATCH 23/26] finished board --- _8/src/main/java/model/Board.java | 6 ++++++ _8/src/main/java/model/Graph.java | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/_8/src/main/java/model/Board.java b/_8/src/main/java/model/Board.java index 5412cab..bd35521 100644 --- a/_8/src/main/java/model/Board.java +++ b/_8/src/main/java/model/Board.java @@ -29,4 +29,10 @@ public synchronized Edge extract(){ return edge; } + public boolean isEmpty(){ + + return complete.isEmpty(); + + } + } diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index dca2cc6..d058548 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -27,4 +27,8 @@ public void setEdges(List edges) { public void addEdge(Edge edge){ edges.add(edge); } + + public boolean isEmpty(){ + return edges.isEmpty(); + } } From afebea335611842b7c3986d643dcb59df8ac3fd9 Mon Sep 17 00:00:00 2001 From: Valeriu Date: Fri, 5 Apr 2019 19:21:30 +0300 Subject: [PATCH 24/26] isSpanningTree metod done --- _8/pom.xml | 4 ++-- _8/src/main/java/model/Graph.java | 37 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/_8/pom.xml b/_8/pom.xml index 7eea098..b1d0a22 100644 --- a/_8/pom.xml +++ b/_8/pom.xml @@ -13,8 +13,8 @@ org.apache.maven.plugins maven-compiler-plugin - 7 - 7 + 8 + 8 diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index 8920b67..b75048f 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -2,6 +2,7 @@ import java.util.List; import java.util.Random; +import java.util.stream.Collectors; public class Graph { List edges; @@ -33,4 +34,40 @@ public void extractEdge() { Random rand = new Random(); edges.remove(rand.nextInt(edges.size()-1)+1); } + + public boolean isSpanningTree(){ + int n = edges.size(); + int visited[] = new int[n]; + boolean isSpanningTree; + + for(int i=0; i currentNodeEdges = getCurrentNodeEdges(v); + + currentNodeEdges.forEach(edge -> { + int dest = edge.getDestination(); + if (visited[dest]!=0) + DFSUtil(dest,visited); + }); + + } + + private List getCurrentNodeEdges(int v) { + return edges.stream() + .filter(edges -> edges.getSource() == v) + .collect(Collectors.toList()); + } + + public void DFS(int v,int visited[]){ + int n = edges.size(); + DFSUtil(n,visited); + } } From be0506854c87e2e26691a4c9b8b851252787235c Mon Sep 17 00:00:00 2001 From: Onatek Date: Fri, 5 Apr 2019 19:22:02 +0300 Subject: [PATCH 25/26] done extract --- _8/src/main/java/model/Graph.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_8/src/main/java/model/Graph.java b/_8/src/main/java/model/Graph.java index 5e9be18..8b76ccd 100644 --- a/_8/src/main/java/model/Graph.java +++ b/_8/src/main/java/model/Graph.java @@ -17,7 +17,7 @@ public List getEdges() { public Edge pullFirst() { Edge edge = edges.get(0); - + edges.remove(0); return edge; } From 0968514c512ba3a2fc1c2876e59cfcdea07039f8 Mon Sep 17 00:00:00 2001 From: Valeriu Date: Tue, 28 May 2019 12:17:31 +0300 Subject: [PATCH 26/26] lab 89 --- _8/src/main/java/Main.java | 21 +- _8/src/main/java/model/Board.java | 19 +- _8/src/main/java/model/Game.java | 11 +- _8/src/main/java/model/Player.java | 17 +- lab8/ClientApplicatin/ClientApplicatin.iml | 12 + .../src/com/company/SocialNetworkClient.java | 63 + lab8/ServerApplication/ServerApplication.iml | 12 + .../src/com/company/ClientThread.java | 59 + .../src/com/company/Command.java | 9 + .../src/com/company/CommandBuilder.java | 46 + .../src/com/company/FriendCommand.java | 25 + .../src/com/company/LoginCommand.java | 33 + .../src/com/company/Person.java | 29 + .../src/com/company/RegisterCommand.java | 23 + .../src/com/company/SFTPsender.java | 63 + .../src/com/company/SendCommand.java | 26 + .../src/com/company/SocialNetwork.java | 78 ++ .../src/com/company/SocialNetworkServer.java | 67 ++ .../src/com/company/StopCommand.java | 19 + .../src/com/company/readCommand.java | 31 + lab8/jsch-0.1.55/ChangeLog | 1061 +++++++++++++++++ lab8/jsch-0.1.55/LICENSE.txt | 30 + lab8/jsch-0.1.55/README | 229 ++++ lab8/jsch-0.1.55/build.bat | 17 + lab8/jsch-0.1.55/build.sh | 25 + lab8/jsch-0.1.55/build.xml | 97 ++ lab8/jsch-0.1.55/examples/AES.java | 149 +++ .../examples/ChangePassphrase.java | 73 ++ lab8/jsch-0.1.55/examples/Compression.java | 149 +++ lab8/jsch-0.1.55/examples/Daemon.java | 175 +++ lab8/jsch-0.1.55/examples/Exec.java | 187 +++ lab8/jsch-0.1.55/examples/KeyGen.java | 82 ++ lab8/jsch-0.1.55/examples/KnownHosts.java | 182 +++ lab8/jsch-0.1.55/examples/Logger.java | 160 +++ lab8/jsch-0.1.55/examples/OpenSSHConfig.java | 137 +++ .../jsch-0.1.55/examples/PortForwardingL.java | 155 +++ .../jsch-0.1.55/examples/PortForwardingR.java | 156 +++ lab8/jsch-0.1.55/examples/README | 182 +++ lab8/jsch-0.1.55/examples/ScpFrom.java | 249 ++++ lab8/jsch-0.1.55/examples/ScpTo.java | 232 ++++ .../jsch-0.1.55/examples/ScpToNoneCipher.java | 218 ++++ lab8/jsch-0.1.55/examples/Sftp.java | 547 +++++++++ lab8/jsch-0.1.55/examples/Shell.java | 123 ++ .../examples/StreamForwarding.java | 155 +++ lab8/jsch-0.1.55/examples/Subsystem.java | 164 +++ lab8/jsch-0.1.55/examples/Sudo.java | 184 +++ lab8/jsch-0.1.55/examples/UserAuthKI.java | 152 +++ lab8/jsch-0.1.55/examples/UserAuthPubKey.java | 154 +++ lab8/jsch-0.1.55/examples/ViaHTTP.java | 155 +++ lab8/jsch-0.1.55/examples/ViaSOCKS5.java | 154 +++ lab8/jsch-0.1.55/examples/X11Forwarding.java | 158 +++ lab8/jsch-0.1.55/jsch.iml | 14 + lab8/jsch-0.1.55/pom.xml | 113 ++ lab8/jsch-0.1.55/tools/bin/ant | 134 +++ lab8/jsch-0.1.55/tools/bin/ant.bat | 110 ++ lab8/jsch-0.1.55/tools/bin/antRun | 9 + lab8/jsch-0.1.55/tools/bin/antRun.bat | 20 + lab8/jsch-0.1.55/tools/bin/lcp.bat | 9 + lab8/jsch-0.1.55/tools/bin/runant.pl | 131 ++ lab8/jsch-0.1.55/tools/bin/runant.py | 96 ++ lab9/Movies.sql | 38 + lab9/populate.sql | 11 + lab9/src/lab9/DAO/MovieController.java | 53 + lab9/src/lab9/DAO/PersonController.java | 44 + lab9/src/lab9/Database.java | 74 ++ lab9/src/lab9/Main.java | 48 + lab9/src/model/Actor.java | 33 + lab9/src/model/Director.java | 40 + lab9/src/model/Movie.java | 49 + lab9/src/model/MovieList.java | 33 + lab9/src/model/Person.java | 13 + 71 files changed, 7604 insertions(+), 22 deletions(-) create mode 100644 lab8/ClientApplicatin/ClientApplicatin.iml create mode 100644 lab8/ClientApplicatin/src/com/company/SocialNetworkClient.java create mode 100644 lab8/ServerApplication/ServerApplication.iml create mode 100644 lab8/ServerApplication/src/com/company/ClientThread.java create mode 100644 lab8/ServerApplication/src/com/company/Command.java create mode 100644 lab8/ServerApplication/src/com/company/CommandBuilder.java create mode 100644 lab8/ServerApplication/src/com/company/FriendCommand.java create mode 100644 lab8/ServerApplication/src/com/company/LoginCommand.java create mode 100644 lab8/ServerApplication/src/com/company/Person.java create mode 100644 lab8/ServerApplication/src/com/company/RegisterCommand.java create mode 100644 lab8/ServerApplication/src/com/company/SFTPsender.java create mode 100644 lab8/ServerApplication/src/com/company/SendCommand.java create mode 100644 lab8/ServerApplication/src/com/company/SocialNetwork.java create mode 100644 lab8/ServerApplication/src/com/company/SocialNetworkServer.java create mode 100644 lab8/ServerApplication/src/com/company/StopCommand.java create mode 100644 lab8/ServerApplication/src/com/company/readCommand.java create mode 100644 lab8/jsch-0.1.55/ChangeLog create mode 100644 lab8/jsch-0.1.55/LICENSE.txt create mode 100644 lab8/jsch-0.1.55/README create mode 100644 lab8/jsch-0.1.55/build.bat create mode 100644 lab8/jsch-0.1.55/build.sh create mode 100644 lab8/jsch-0.1.55/build.xml create mode 100644 lab8/jsch-0.1.55/examples/AES.java create mode 100644 lab8/jsch-0.1.55/examples/ChangePassphrase.java create mode 100644 lab8/jsch-0.1.55/examples/Compression.java create mode 100644 lab8/jsch-0.1.55/examples/Daemon.java create mode 100644 lab8/jsch-0.1.55/examples/Exec.java create mode 100644 lab8/jsch-0.1.55/examples/KeyGen.java create mode 100644 lab8/jsch-0.1.55/examples/KnownHosts.java create mode 100644 lab8/jsch-0.1.55/examples/Logger.java create mode 100644 lab8/jsch-0.1.55/examples/OpenSSHConfig.java create mode 100644 lab8/jsch-0.1.55/examples/PortForwardingL.java create mode 100644 lab8/jsch-0.1.55/examples/PortForwardingR.java create mode 100644 lab8/jsch-0.1.55/examples/README create mode 100644 lab8/jsch-0.1.55/examples/ScpFrom.java create mode 100644 lab8/jsch-0.1.55/examples/ScpTo.java create mode 100644 lab8/jsch-0.1.55/examples/ScpToNoneCipher.java create mode 100644 lab8/jsch-0.1.55/examples/Sftp.java create mode 100644 lab8/jsch-0.1.55/examples/Shell.java create mode 100644 lab8/jsch-0.1.55/examples/StreamForwarding.java create mode 100644 lab8/jsch-0.1.55/examples/Subsystem.java create mode 100644 lab8/jsch-0.1.55/examples/Sudo.java create mode 100644 lab8/jsch-0.1.55/examples/UserAuthKI.java create mode 100644 lab8/jsch-0.1.55/examples/UserAuthPubKey.java create mode 100644 lab8/jsch-0.1.55/examples/ViaHTTP.java create mode 100644 lab8/jsch-0.1.55/examples/ViaSOCKS5.java create mode 100644 lab8/jsch-0.1.55/examples/X11Forwarding.java create mode 100644 lab8/jsch-0.1.55/jsch.iml create mode 100644 lab8/jsch-0.1.55/pom.xml create mode 100644 lab8/jsch-0.1.55/tools/bin/ant create mode 100644 lab8/jsch-0.1.55/tools/bin/ant.bat create mode 100644 lab8/jsch-0.1.55/tools/bin/antRun create mode 100644 lab8/jsch-0.1.55/tools/bin/antRun.bat create mode 100644 lab8/jsch-0.1.55/tools/bin/lcp.bat create mode 100644 lab8/jsch-0.1.55/tools/bin/runant.pl create mode 100644 lab8/jsch-0.1.55/tools/bin/runant.py create mode 100644 lab9/Movies.sql create mode 100644 lab9/populate.sql create mode 100644 lab9/src/lab9/DAO/MovieController.java create mode 100644 lab9/src/lab9/DAO/PersonController.java create mode 100644 lab9/src/lab9/Database.java create mode 100644 lab9/src/lab9/Main.java create mode 100644 lab9/src/model/Actor.java create mode 100644 lab9/src/model/Director.java create mode 100644 lab9/src/model/Movie.java create mode 100644 lab9/src/model/MovieList.java create mode 100644 lab9/src/model/Person.java diff --git a/_8/src/main/java/Main.java b/_8/src/main/java/Main.java index cb191ed..2cec14d 100644 --- a/_8/src/main/java/Main.java +++ b/_8/src/main/java/Main.java @@ -5,10 +5,23 @@ public class Main { public static void main(String args[]) { Game game = new Game(); - game.setBoard(new Board(10)); - game.addPlayer(new Player("Player 1")); - game.addPlayer(new Player("Player 2")); - game.addPlayer(new Player("Player 3")); + game.setBoard(new Board(3)); + game.addPlayer(new Player("Player 1",game)); + //game.addPlayer(new Player("Player 2",game)); +// game.addPlayer(new Player("Player 3",game)); +// game.addPlayer(new Player("Player 4",game)); +// game.addPlayer(new Player("Player 5",game)); +// game.addPlayer(new Player("Player 6",game)); +// +// for(int i=10;i<100000;i++) +// game.addPlayer(new Player("Player "+i,game)); + game.start(); + + Player winner = game.getWinner(); + if (winner == null) + System.out.println("No one won"); + else + System.out.println(game.getWinner().toString() + " is the winner"); } } diff --git a/_8/src/main/java/model/Board.java b/_8/src/main/java/model/Board.java index bd35521..1364396 100644 --- a/_8/src/main/java/model/Board.java +++ b/_8/src/main/java/model/Board.java @@ -1,35 +1,34 @@ package model; -import java.util.Collection; import java.util.Collections; +import java.util.LinkedList; import java.util.List; public class Board { private final Graph complete; - public Board(int n){ + public Board(int n) { - List edges = null; - int edgeCount = 0; - for (int i = 0; i < n-1 ; i++) { - for (int j = i+1; j < n ; j++) { - edges.set(edgeCount, new Edge(i, j)); + List edges = new LinkedList<>(); + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + edges.add(new Edge(i, j)); } } Collections.shuffle(edges); - complete = new Graph(edges); + complete = new Graph(edges); } - public synchronized Edge extract(){ + public synchronized Edge extract() { Edge edge = complete.pullFirst(); return edge; } - public boolean isEmpty(){ + public boolean isEmpty() { return complete.isEmpty(); diff --git a/_8/src/main/java/model/Game.java b/_8/src/main/java/model/Game.java index 4c09176..362bbdc 100644 --- a/_8/src/main/java/model/Game.java +++ b/_8/src/main/java/model/Game.java @@ -27,16 +27,19 @@ public List getPlayers() { } - //Create the method that will start the game: start one thread for each player - public void startGame() { - // TODO: code this - } public void setWinner(Player player) { this.winner = player; } public void start() { + players.forEach(player -> { + Thread newThread = new Thread(player); + newThread.start(); + }); + } + public Player getWinner() { + return winner; } } diff --git a/_8/src/main/java/model/Player.java b/_8/src/main/java/model/Player.java index e8a55c7..f279e52 100644 --- a/_8/src/main/java/model/Player.java +++ b/_8/src/main/java/model/Player.java @@ -1,12 +1,16 @@ package model; +import java.util.LinkedList; +import java.util.List; + public class Player implements Runnable{ private String name; private Game game; private Graph graph; - public Player(String name) { + public Player(String name, Game game) { this.name = name; + this.graph = new Graph(new LinkedList()); } public Player(String name, Game game, Graph graph) { @@ -45,14 +49,19 @@ private boolean play() throws InterruptedException { graph.addEdge( board.extract() ); Thread.sleep(THINKING_TIME); //declare this constant if (graph.isSpanningTree()) { - game.setWinner(this); + if (game.getWinner() != null) + game.setWinner(this); + else return true; } return true; } public void run() { - this.graph.extractEdge(); - System.out.println(this.toString() + " extracted an edge..."); + try { + play(); + } catch (InterruptedException e) { + e.printStackTrace(); + } } diff --git a/lab8/ClientApplicatin/ClientApplicatin.iml b/lab8/ClientApplicatin/ClientApplicatin.iml new file mode 100644 index 0000000..d5c0743 --- /dev/null +++ b/lab8/ClientApplicatin/ClientApplicatin.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/lab8/ClientApplicatin/src/com/company/SocialNetworkClient.java b/lab8/ClientApplicatin/src/com/company/SocialNetworkClient.java new file mode 100644 index 0000000..06eca4f --- /dev/null +++ b/lab8/ClientApplicatin/src/com/company/SocialNetworkClient.java @@ -0,0 +1,63 @@ +package com.company; +// alow pararel running + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Scanner; + +public class SocialNetworkClient { + private final static String SERVER_ADDRESS = "127.0.0.1"; + private final static int PORT = 8100; + private Socket socket; + + public static void main(String[] args) throws IOException { + SocialNetworkClient client = new SocialNetworkClient(); + while (true) { + String request = client.readFromKeyboard(); + if (request.equalsIgnoreCase("exit")) { + break; + } else { + try { + client.sendRequestToServer(request); + } + catch (SocketException se){ + System.out.println("Server shut down successfully!"); + System.exit(0); + } + } + } + } + + //Implement the sendRequestToServer method + private String sendRequestToServer(String request) throws IOException { + socket = new Socket(SERVER_ADDRESS, PORT); + String resp = ""; + // timeout after 10000 milliseconds + int timeOut = 10000; + this.socket.setSoTimeout(timeOut); + try { + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + // send the request to the server: + out.println(request); + // read the response from the server: + String response = in.readLine(); + System.out.println(response); + } catch (UnknownHostException e) { + System.err.println(e); + } + return resp; + } + + private String readFromKeyboard() { + Scanner scanner = new Scanner(System.in); + // citesc toata linia de la tastatura: + return scanner.nextLine(); + } +} \ No newline at end of file diff --git a/lab8/ServerApplication/ServerApplication.iml b/lab8/ServerApplication/ServerApplication.iml new file mode 100644 index 0000000..d5c0743 --- /dev/null +++ b/lab8/ServerApplication/ServerApplication.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/lab8/ServerApplication/src/com/company/ClientThread.java b/lab8/ServerApplication/src/com/company/ClientThread.java new file mode 100644 index 0000000..be9f674 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/ClientThread.java @@ -0,0 +1,59 @@ +package com.company; +import java.net.*; +import java.io.*; + +public class ClientThread extends Thread { + private Socket socket = null; + private SocialNetworkServer server; + SocialNetwork net = new SocialNetwork(socket); + + ClientThread(Socket socket) throws FileNotFoundException, UnsupportedEncodingException { + this.socket = socket; + // this.server = server; + } + + @Override + public void run() { + try { + while (true) { + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //client -> server stream + String request = in.readLine(); + System.out.println("\r\nMessage from " + Thread.currentThread().getName() + ": " + request); + String response = execute(request); + if (request.equalsIgnoreCase("stop")) { + System.exit(0); + } + PrintWriter out = new PrintWriter(socket.getOutputStream()); //server -> client stream + out.println(response); + // gracefully stop!!! + + out.flush(); + } + } catch (IOException e) { + System.err.println("Communication error... " + e); + } finally { + try { + socket.close(); // or use try-with-resources + } catch (IOException e) { + System.err.println(e); + } + } + } + + // display the message: "Server received the request ... " + private String execute(String request) throws IOException { + String response; + response = null; + CommandBuilder commandBuilder = new CommandBuilder(); + Command command; + if (request.equalsIgnoreCase("stop")) { + response = "Goodbye!"; + } else { + System.out.println("Server received the request " + request); + command = commandBuilder.CommandBuilder(request); + response = command.execute(net, socket); + } + return response; + } +} + diff --git a/lab8/ServerApplication/src/com/company/Command.java b/lab8/ServerApplication/src/com/company/Command.java new file mode 100644 index 0000000..361f4b7 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/Command.java @@ -0,0 +1,9 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; + +public interface Command +{ + String execute(SocialNetwork network, Socket socket) throws IOException; +} \ No newline at end of file diff --git a/lab8/ServerApplication/src/com/company/CommandBuilder.java b/lab8/ServerApplication/src/com/company/CommandBuilder.java new file mode 100644 index 0000000..6552561 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/CommandBuilder.java @@ -0,0 +1,46 @@ +package com.company; + +import java.util.Arrays; + +public class CommandBuilder { + public Command CommandBuilder(String request) + { + String command; + String[] args; + String[] parts = request.split(" "); + command = parts[0]; + args = Arrays.copyOfRange(parts,1,parts.length); + + if(command.equals("register")) + { + return new RegisterCommand(args); + } + + if(command.equals("login")) + { + return new LoginCommand(args); + } + + if(command.equals("friend")) + { + return new FriendCommand(args); + } + + if(command.equals("send")) + { + return new SendCommand(args); + } + // stop app + if(command.equals("stop")) + { + return new StopCommand(args); + } + + if(command.equals("read")) + { + return new readCommand(args); + } + return null; + + } +} diff --git a/lab8/ServerApplication/src/com/company/FriendCommand.java b/lab8/ServerApplication/src/com/company/FriendCommand.java new file mode 100644 index 0000000..e6c8504 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/FriendCommand.java @@ -0,0 +1,25 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; +import java.util.ArrayList; + +public class FriendCommand implements Command { + String[] args; + + public FriendCommand(String[] args) + { + this.args = args; + } + + @Override + public String execute(SocialNetwork network, Socket socket) throws IOException { + ArrayList names = new ArrayList<>(); + for (String arg: args){ + Person p = new Person(arg); + network.addFriends(p); + } + + return "Friends added"; + } +} diff --git a/lab8/ServerApplication/src/com/company/LoginCommand.java b/lab8/ServerApplication/src/com/company/LoginCommand.java new file mode 100644 index 0000000..aafb615 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/LoginCommand.java @@ -0,0 +1,33 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; + +public class LoginCommand implements Command { + String[] args; + + public LoginCommand(String[] args) + { + this.args = args; + } + + @Override + public String execute(SocialNetwork network, Socket socket) throws IOException { + String name; + name = args[0]; + for(int i=0; i messagesToRecieve = new LinkedList<>(); + + Person(String name){ + this.name = name; + } + + String getName(){ + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Queue getMessagesToRecieve() { + return messagesToRecieve; + } + + public void setMessagesToRecieve(Queue messagesToRecieve) { + this.messagesToRecieve = messagesToRecieve; + } +} diff --git a/lab8/ServerApplication/src/com/company/RegisterCommand.java b/lab8/ServerApplication/src/com/company/RegisterCommand.java new file mode 100644 index 0000000..0608809 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/RegisterCommand.java @@ -0,0 +1,23 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; + +public class RegisterCommand implements Command { + String[] args; + + + public RegisterCommand(String[] args) + { + this.args = args; + } + + @Override + public String execute(SocialNetwork network, Socket socket) throws IOException { + String name; + name = args[0]; + network.addRegistration(new Person(name)); + return "Person registered"; + } + +} diff --git a/lab8/ServerApplication/src/com/company/SFTPsender.java b/lab8/ServerApplication/src/com/company/SFTPsender.java new file mode 100644 index 0000000..d846840 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/SFTPsender.java @@ -0,0 +1,63 @@ +package com.company; +/* +import com.jcraft.jsch.*; + +import java.io.*; + +public class SFTPsender { + + public void send(String fileName) throws IOException { + String SFTPHOST = "fenrir.info.uaic.ro"; + int SFTPPORT = 22; + String SFTPUSER = "teodora.grosu"; + String SFTPPASS = readPassword(); + String SFTPWORKINGDIR = "/fenrir/studs/teodora.grosu/html/"; + + Session session = null; + Channel channel = null; + ChannelSftp channelSftp = null; + + try { + JSch jsch = new JSch(); + session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT); + session.setPassword(SFTPPASS); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + session.setConfig(config); + session.connect(); + System.out.println("Host connected."); + channel = session.openChannel("sftp"); + channel.connect(); + System.out.println("sftp channel opened and connected."); + channelSftp = (ChannelSftp) channel; + channelSftp.cd(SFTPWORKINGDIR); + File f = new File(fileName); + channelSftp.put(new FileInputStream(f), f.getName()); + + } catch (Exception ex) { + ex.printStackTrace(); + } + finally{ + + channelSftp.exit(); + System.out.println("sftp Channel exited."); + channel.disconnect(); + System.out.println("Channel disconnected."); + session.disconnect(); + System.out.println("Host Session disconnected."); + } + } + + public String readPassword () throws IOException { + File file = new File("D:\\Anul 2\\Java\\HTML\\pass.txt"); + + BufferedReader br = new BufferedReader(new FileReader(file)); + + String st; + st = br.readLine(); + + return st; + } + +}*/ + diff --git a/lab8/ServerApplication/src/com/company/SendCommand.java b/lab8/ServerApplication/src/com/company/SendCommand.java new file mode 100644 index 0000000..0f5e408 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/SendCommand.java @@ -0,0 +1,26 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; + +public class SendCommand implements Command { + String[] args; + + public SendCommand(String[] args) + { + this.args = args; + } + SocialNetworkServer server; + + @Override + public String execute(SocialNetwork network, Socket socket) throws IOException { + String message = args[0]; +// for(int i=0; i client stream +// out.println(message); +// } + network.getFriends().forEach(friend -> friend.messagesToRecieve.add(message)); + return "Message sent"; + } +} + diff --git a/lab8/ServerApplication/src/com/company/SocialNetwork.java b/lab8/ServerApplication/src/com/company/SocialNetwork.java new file mode 100644 index 0000000..9fdc5c6 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/SocialNetwork.java @@ -0,0 +1,78 @@ +package com.company; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Scanner; + + +public class SocialNetwork { + private Socket socket = null; + private ArrayList registered = new ArrayList<>(); + private ArrayList login = new ArrayList<>(); + private ArrayList myFriends = new ArrayList<>(); + + //PrintWriter writer = new PrintWriter("D:\\FACULTATE TOT\\ANUL2\\JAVA\\file.html", "UTF-8"); + //SFTPsender senderSFTP = new SFTPsender(); + //String htmlCode = htmlHeader(); + + SocialNetwork(Socket socket) throws FileNotFoundException, UnsupportedEncodingException { + this.socket = socket; + } + + ArrayList getNetwork() throws IOException { + // htmlCode = htmlCode.concat("Registred users: " + registered + ".\n"); + // writer.print(htmlCode); + //SFTPsender.send("D:\\FACULTATE TOT\\ANUL2\\JAVA\\file.html"); + + return registered; + } + + void addRegistration(Person p) throws IOException { + //htmlCode = htmlCode.concat( p.getName() + " was registred " + ".\n"); + //writer.print(htmlCode); + //SFTPsender.send("D:\\FACULTATE TOT\\ANUL2\\JAVA\\file.html"); + + registered.add(p); + } + + void addLogin(Person p) throws IOException { + //htmlCode = htmlCode.concat(p.getName() + " logged in.\n"); + //writer.print(htmlCode); + //senderSFTP.send("D:\\FACULTATE TOT\\ANUL2\\JAVA\\file.html"); + + login.add(p); + } + + void addFriends(Person p) throws IOException { + //htmlCode = htmlCode.concat(p.getName() + " added to friends.\n"); + //writer.print(htmlCode); + //senderSFTP.send("D:\\FACULTATE TOT\\ANUL2\\JAVA\\file.html"); + + myFriends.add(p); + } + + ArrayList getFriends(){ + return myFriends; + } + + + public String readFromKeyboard() { + Scanner scanner = new Scanner(System.in); + // citesc toata linia de la tastatura: + return scanner.nextLine(); + } + + + private String htmlHeader() { + + return "\n" + + "\t\n" + + "\t\t Social Network \n" + + "\t\n" + + "\t\n" + + "\t\t

"; + } +} diff --git a/lab8/ServerApplication/src/com/company/SocialNetworkServer.java b/lab8/ServerApplication/src/com/company/SocialNetworkServer.java new file mode 100644 index 0000000..67befe3 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/SocialNetworkServer.java @@ -0,0 +1,67 @@ +package com.company; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.HashMap; +import java.util.Map; + +public class SocialNetworkServer { + private static final int PORT = 8100; + private ServerSocket serverSocket; + private boolean running = false; + + Map sockets = new HashMap(); + static String username; + + + public SocialNetworkServer(String username) throws IOException { + ServerSocket serverSocket = null; + this.username = username; + } + + public static void main(String[] args) throws IOException { + SocialNetworkServer server = new SocialNetworkServer(username); + server.init(); + server.waitForClients(); //... handle the exceptions! + } + + public void init() throws IOException { + try { + running = true; + serverSocket = new ServerSocket(PORT); + } catch (IOException e) { + System.err.println("Eroare IO: " + e); + } + } + + public void waitForClients() throws IOException{ + try { + while (running) { + Socket socket = serverSocket.accept(); + // Executam solicitarea clientului intr - un fir de executie + ClientThread t = new ClientThread(socket); + String username = getUserName(socket); + sockets.put(username, socket); + t.start(); + } + } catch (IOException e) { + System.err.println("Eroare : " + e); + } + } + + private String getUserName(Socket socket) { + return username; + } + + public ServerSocket getServerSocket() + { + return serverSocket; + } + + public Map getSockets() {return sockets;} + + public void stop() throws IOException { + this.running = false; + serverSocket.close(); + } +} \ No newline at end of file diff --git a/lab8/ServerApplication/src/com/company/StopCommand.java b/lab8/ServerApplication/src/com/company/StopCommand.java new file mode 100644 index 0000000..ab36a11 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/StopCommand.java @@ -0,0 +1,19 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; + +public class StopCommand implements Command +{ + String[] args; + + public StopCommand(String[] args) + { + this.args = args; + } + @Override + public String execute(SocialNetwork network, Socket socket) throws IOException { + socket.close(); + return "Server stopped"; + } +} diff --git a/lab8/ServerApplication/src/com/company/readCommand.java b/lab8/ServerApplication/src/com/company/readCommand.java new file mode 100644 index 0000000..80a9388 --- /dev/null +++ b/lab8/ServerApplication/src/com/company/readCommand.java @@ -0,0 +1,31 @@ +package com.company; + +import java.io.IOException; +import java.net.Socket; + +public class readCommand implements Command { + String[] args; + + public readCommand(String[] args) + { + this.args = args; + } + + @Override + public String execute(SocialNetwork network, Socket socket) throws IOException { +// String message = network.readFromKeyboard(); +// while(!message.equals("")){ +// PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //server -> client stream +// out.println("mesaj: " + message); +// message = network.readFromKeyboard(); +// } + StringBuilder messages = new StringBuilder(); + network.getFriends().forEach(friend -> { + messages.append(friend.messagesToRecieve.peek()); + messages.append("\n"); + friend.messagesToRecieve.remove(); + }); + return messages.toString(); + } + +} diff --git a/lab8/jsch-0.1.55/ChangeLog b/lab8/jsch-0.1.55/ChangeLog new file mode 100644 index 0000000..1d0baa8 --- /dev/null +++ b/lab8/jsch-0.1.55/ChangeLog @@ -0,0 +1,1061 @@ +ChangeLog of JSch +==================================================================== +Last modified: Thu Nov 22 01:06:27 UTC 2018 + + +Changes since version 0.1.54: +- bugfix: fixed vulnerabilities in examples; + ScpTo.java, ScpFrom.java and ScpNoneCipher.java, + https://gist.github.com/ymnk/2318108/revisions#diff-a5ec82fe8ccb2efa64aa42a5592bb137 + https://gist.github.com/ymnk/2318108/revisions#diff-c1b069ab3a670f4fd3270d0f57550007 + https://gist.github.com/ymnk/2318108/revisions#diff-a20032aa3cc9119fa627ec948b9ada46 + thanks to Dylan Katz(http://dylankatz.com). +- bugfix: OpenSSHConfig#getUser() should not overwrite the given user-name. +- bugfix: fixed 'Invalid encoding for signature' errors in ssh-dss. +- bugfix: fixed bugs in the key-exchange for ecdsa-sha2-nistp384, + ecdsa-sha2-nistp521. +- bugfix: failed to generate the key pair from private keys, + ecdsa 384 and 521. +- bugfix: failed to load the ecdsa 521 key identity from ssh-add command. +- change: updating copyright messages; 2016 -> 2018 +- feature: supporting key files on EBCDIC environment. + + +Changes since version 0.1.53: +- bugfix: fixed CVS-2016-5725 + Refer to following links, + http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=2016-5725 + https://github.com/tintinweb/pub/tree/master/pocs/cve-2016-5725 + Thanks a lot for tintinweb's contributions. +- bugfix: sftp-put may send the garbage data in some rare case. +- bugfix: fixed a deadlock bug in KnownHosts#getHostKey(). +- bugfix: SftpProgressMonitor#init() was not invoked in sftp-put + by using the output-stream. +- change: KnownHosts#setKnownHosts() should accept the non-existing file. +- change: excluding the user interaction time from the timeout value. +- change: addressing SFTP slow file transfer speed with Titan FTP. +- change: updating copyright messages; 2015 -> 2016 + + +Changes since version 0.1.52: +- bugfix: the rekey initiated by the remote may crash the session. +- change: Logjam: use ecdh-sha2-nistp* if available, + ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, + diffie-hellman-group14-sha1, + diffie-hellman-group-exchange-sha256, + diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1 +- change: Logjam: diffie-hellman-group-exchange-sha256 and + diffie-hellman-group-exchange-sha1 will use 2048-bit key on + Java8's SunJCE, thanks to JDK-6521495 and JDK-7044060. +- change: key words for OpenSSH's config file should be case-insensitive. +- change: there should be the host name in "WARNING: REMOTE HOST + IDENTIFICATION HAS CHANGED" message. + + +Changes since version 0.1.51: +- bugfix: resource leak: duplicate keys in LocalIdentityRepository. +- feature: added the support for SSH ECC defined in RFC5656, + ecdsa-sha2-nistp256, + ecdsa-sha2-nistp384, + ecdsa-sha2-nistp521, + ecdh-sha2-nistp256, + ecdh-sha2-nistp384, + ecdh-sha2-nistp521 + This functionality requires Java7 or later. +- feature: added the support for server host keys in + ecdsa-sha2-nistp256, + ecdsa-sha2-nistp384, + ecdsa-sha2-nistp521 +- feature: generating key-pairs in + ecdh-sha2-nistp256, + ecdh-sha2-nistp384, + ecdh-sha2-nistp521 +- change: aes192-ctr, aes256-ctr and + diffie-hellman-group-exchange-sha256 have been enabled + by the default. +- change: key exchange methods, ecdh-sha2-nistp256, + ecdh-sha2-nistp384 and ecdh-sha2-nistp521 have been enabled + by the default. +- change: the support for host keys in ecdsa-sha2-nistp256, + ecdsa-sha2-nistp384 and ecdsa-sha2-nistp521 have been enabled + by the default. +- change: 'examples/KeyGen.java' demonstrates how to generate + ecdsa-sha2-* key-pairs. +- change: updating copyright messages; 2014 -> 2015 +- TODO: The ECC support is not functional on Java6 with BouncyCastle. + + +Changes since version 0.1.50: +- bugfix: reproducibility of "verify: false". FIXED. + Hundreds of thousands of connections had caused that exception. +- bugfix: resource leaks at the failure of making local port forwarding. FIXED. +- bugfix: NPE in connecting to the non-standard TCP port. FIXED. + This problem had appeared if a host-key does not exist in + "known_host" file. +- bugfix: TCP connection may not be dropped if error messages from + the remote are too long. FIXED. +- bugfix: SftpATTRS#getAtimeString() returns the wrong string. FIXED. +- bugfix: bytes to be added by SSH_MSG_CHANNEL_WINDOW_ADJUST must be in + unsigned integer. FIXED. +- bugfix: Util#checkTilde() should not convert a tilde in + "C:\PROGRA~1\". FIXED. +- bugfix: A long long command for ChannelExec will cause + an ArrayIndexOutOfBoundsException. FIXED. +- bugfix: ChannelSftp should not send bulk request greedily even if the remote + window has the enough space. FIXED. +- bugfix: Util.createSocket() should throw an exception with 'cause'. FIXED. +- bugfix: failed to parse .ssh/config in the EBCDIC environment. FIXED. +- bugfix: com.jcraft.jsch.jcraft.HMACSHA1(used only for MacOSX) is not + reusable. FIXED. +- bugfix: NPE caused by the delayed response for channel opening + requests. FIXED. +- bugfix: hung-up in uploading huge data to ProFTPd without the config + 'SFTPClientMatch "JSCH.*" channelWindowSize 1GB' FIXED. +- bugfix: Cipher#init() may cause an infinite loop with 100% cpu use due to + https://bugs.openjdk.java.net/browse/JDK-8028627 FIXED. +- bugfix: in some case, JSche#setKnowHosts(InputStream stream) may fail + to close the given stream. FIXED +- change: com.jcraft.jsch.jcraft.HMAC* will not be used. + It seems Java6 on Mac OS X has fixed some memory leak bug in JCE, + so there is no reason to use c.j.j.j.HMAC* introduced at 0.1.30. +- change: updating copyright messages; 2013 -> 2014 +- change: allowed to create the symbolic/hard link to the relative path by + ChannelSftp#symlink(String oldpath, String newpath) + ChannelSftp#hardlink(String oldpath, String newpath) +- change: the availability of ciphers listed in "CheckCiphers" config will + not be checked if they are not used. +- change: Util#fromBase64() will throw JSchException in stead of + RuntimeException, if the given string is not in base64 format. +- feature: added the support for private keys in PKCS#8 format. +- feature: introduced the interface com.jcraft.jsch.PBKDF to abstract + the implementation of Password-Based Key Derivation Function, + and added its implementation com.jcraft.jsch.jce.PBKDF by using JCE. + + +Changes since version 0.1.49: +- bugfix: "verify: false" error on Java7u6(and later). FIXED. + http://stackoverflow.com/questions/12279836/ssh-using-jschexception-verify-false-sometimes-fails + https://issues.apache.org/jira/browse/IVY-1374 +- bugfix: Session#setPortForwardingL(String bind_address, + int lport, String host, int rport) + will not work for the long host name. FIXED. +- change: changed JSch#getIdentityRepository() to be public. +- feature: added the following method to choose a canceled remote + port-forwarding with the specified bind address, + Session#delPortForwardingR(String bind_address, int rport) +- feature: added support for following OpenSSH's sftp extensions, + posix-rename@openssh.com, + statvfs@openssh.com, + hardlink@openssh.com, + and some methods and a class to use those functionalities, + ChannelSftp#hardlink(String oldpath, String newpath), + ChannelSftp#statVFS(String path) + SftpStatVFS +- feature: added support for OpenSSH's configuration file, + JSch#setConfigRepository(ConfigRepository configRepository) + JSch#getConfigRepository() + OpenSSHConfig class + Session#getSession(String host) + and added an example to demonstrate how to use it, + examples/OpenSSHConfig.java + OpenSSHConfig class will recognize the following keywords, + Host + User + Hostname + Port + PreferredAuthentications + IdentityFile + NumberOfPasswordPrompts + ConnectTimeout + HostKeyAlias + UserKnownHostsFile + KexAlgorithms + HostKeyAlgorithms + Ciphers + Macs + Compression + CompressionLevel + ForwardAgent + RequestTTY + ServerAliveInterval + LocalForward + RemoteForward + ClearAllForwardings +- feature: added support for "diffie-hellman-group-exchange-sha256" +- feature: allowed to use tilde(~) in the file name, + JSch#setIdentity(String prvkey, String pubkey) + JSch#setKnownHosts(String prvkey, String pubkey) +- feature: added support for known_hosts file, which may include + markers(@revoke) and comments. + HostKey(String host, int type, byte[] key, String comment) + HostKey(String marker, String host, int type, + byte[] key, String comment) + HostKey#getComment() + HostKey#getMarker() +- feature: added following methods to KeyPar class, + writePrivateKey(java.io.OutputStream out, byte[] passphrase) + writePrivateKey(String name, byte[] passphrase) +- feature: allowed to set the connection timeout for the local port-forwarding, + and added following methods, + Session#setPortForwardingL(String bind_address, + int lport, String host, int rport, + ServerSocketFactory ssf, + int connectTimeout) + ChannelDirectTCPIP#connect(int connectTimeout) +- feature: added the following method to Session class + getStreamForwarder(String host, int port) + and updated example/StreamForwarding.java to use that method. +- feature: added following methods to Session class, + setPortForwardingL(String conf) + setPortForwardingR(String conf) +- feature: allowed to have the session local HostkeyRepository, + Session#setHostKeyRepository(HostKeyRepository hostkeyRepository) + Session#getHostKeyRepository() +- feature: added support for OpenSSH's local extension, + "no-more-sessions@openssh.com" and the method, + Session#noMoreSessionChannels() + + +Changes since version 0.1.48: +- bugfix: Some sftp servers will sometimes fail to handle bulk requests, + and whenever detecting such failures, we should re-send + requests again and again. FIXED +- bugfix: KeyPair#getFingerPrint() should return a fingerprint instead + of keysize + " " + fingerprint. FIXED +- bugfix: KeyPair#getKeySize() should return its key size. FIXED +- bugfix: SftpATTRS#isDir() should return false for unix domain + socket files. FIXED +- change: improved the heuristics for the password prompt in + the keyboard-interactive authentication. It may not be + started with "password:". +- change: ChannelSftp#put(InputStream src, String dst) will not check + if dst is directory or not, and if an exception is thrown, + the check will be done. +- change: if the compression is enabled without jzlib.jar, + an exception will be thrown. +- feature: JSch#addIdentity() and KeyPair#load() methods will accept + Putty's private key files. + Note that Putty encrypts its private key with "aes256-cbc". + So, to handle such key files, "Java Cryptography + Extension (JCE) Unlimited Strength Jurisdiction Policy Files" + must be installed. +- feature: hmac-sha2-256 defined in RFC6668 is supported. +- feature: added following methods to KeyPair class, + byte[] getSignature(byte[] data) + Signature getVerifier() + byte[] forSSHAgent() + void setPublicKeyComment(String comment) +- feature: added following methods to SftpATTR class, + boolean isChr() + boolean isBlk() + boolean isFifo() + boolean isSock() + + +Changes since version 0.1.47: +- change: the file transfer speed with ChannelSftp#get(String src) has been + improved; sending multiple requests at any one time. +- change: by the default, at most, 16 requests will be sent at any one time + in ChannelSftp. +- feature: added Session#{setIdentityRepository(),getIdentityRepository()} + + +Changes since version 0.1.46: +- bugfix: failed to initialize channels for the stream forwarding. FIXED +- change: Session#getHostKey() will return the given hostkey + even if session is not established. +- change: Logger will record additional messages about algorithm negotiations. +- feature: added ChannelSftp#ls(String path, LsEntrySelector selector) method. +- feature: added IdentityRepository#{getName(),getStatus()} methods. + + +Changes since version 0.1.45: +- bugfix: in the agent forwarding mode, "ssh-add -l" on the remote + will freeze. FIXED +- bugfix: requests should not be sent to the closed channel. FIXED +- bugfix: ChannelShell#setAgentForwarding(true) will cause + resource leaks. FIXED +- change: for the efficiency, channel opening will be delayed + in local port forwarding. +- change: added examples/Sudo.java to demonstrate sudo on exec channel. +- change: authentication trials will be failed at 6 failures by the default. +- change: updating copyright messages; 2011 -> 2012 +- feature: added JSch#setIdentityRepository(IdentityRepository irepo) to + integrate with jsch-agent-proxy. + + +Changes since version 0.1.44: +- bugfix: fields referred by multiple threads simultaneously should be + volatile. FIXED +- bugfix: use local window size offered by the remote in sftp put. + FIXED +- bugfix: SftpProgressMonitor#init was not invoked in sftp-put + for input-stream. FIXED +- bugfix: sftp protocol version 3, 4 and 5 should allow only + UTF-8 encoding. FIXED +- bugfix: Channel Subsystem had failed to set X forwarding flag. + FIXED +- bugfix: Channel X11 had leaked some resources. + FIXED +- bugfix: packet compression may break sessions + in some case(transferring deflated data). FIXED +- bugfix: failed to set dev-null for logger + FIXED +- bugfix: even in sftp protocol version 3 session, some sftpd sends data + packets defined in sftp protocol 6 ;-( working around it. FIXED +- bugfix: ChannelSftp file globbing logic had missed + the string "foo\\\*bar" as a pattern. FIXED +- bugfix: sequential accesses to ChannelSftp by multiple threads may + break its I/O channel. + https://bugs.eclipse.org/bugs/show_bug.cgi?id=359184 FIXED +- bugfix: KeyPair.load can not handle private keys cyphered with AES. FIXED +- change: to improve sftp-put performance, send multiple packet at one time. +- change: wait/notify will be used instead of sleep loop + in establishing channel connections. +- change: increasing local window size for sftp get. +- change: updating copyright messages; 2010 -> 2011 +- change: src/com -> src/main/java/com +- feature: key-exchange method "diffie-hellman-group14-sha1" + (RFC4253#section-8.2) +- feature: KeyPair#getPlulicKeyCommment() is added. + + +Changes since version 0.1.43: +- bugfix: hmac-md5-96 and hmac-sha1-96 are broken. FIXED. +- bugfix: working around OOME in parsing broken data from the remote. FIXED. +- bugfix: failed to send very long command for exec channels. FIXED. +- bugfix: in some case, failed to get the response + for remote port-forwarding request. FIXED. +- feature: support for private keys ciphered with aes192-cbc and aes128-cbc. + + +Changes since version 0.1.42: +- bugfix: the remote window size must be in unsigned int. FIXED. +- bugfix: support for EBCDIC environment. FIXED. +- bugfix: data may be written to the closed channel. FIXED. +- bugfix: NPE in closing channels. FIXED. +- bugfix: the private key file may include garbage data before its header. FIXED. +- bugfix: the session down may not be detected during the re-keying process. FIXED. +- change: try keyboard-interactive auth with the given password if UserInfo is not given. +- change: working around the wrong auth method list sent by some SSHD + in the partial auth success. +- change: working around the CPNI-957037 Plain-text Recovery Attack. +- change: in searching for [host]:non-default port in known_hosts, + host:22 should be also checked. +- change: updating copyright messages; 2009 -> 2010 + + +Changes since version 0.1.41: +- bugfix: making exec request during re-keying process will cause + the dead lock for the session. FIXED. + Many thanks for PanLi at Prominic dot NET and www.prominic.net, + US based hosting company. Without their testing JSch with + hundreds of hosts and their bug reports, this problem + was not fixed. +- change: updating copyright messages; 2008 -> 2009 + + +Changes since version 0.1.40: +- bugfix: canceling the remote port-forwarding with the incorrect + bind-address. FIXED. +- bugfix: sftp had missed to close the file in some case. FIXED. +- bugfix: ls(sftp) will throw an exception for the empty directory + in connecting to some sftpd server. FIXED. +- change: dropping the session gently in accepting incorrect packets. +- change: by the default, aes128-ctr will be chosen if it is available + on the local and the remote. +- feature: adding the support for the private key ciphered in AES256. +- feature: new ciphers: aes128-ctr,aes192-ctr,aes256-ctr, + 3des-ctr,arcfour,arcfour128 ,arcfour256 + + +Changes since version 0.1.39: +- bugfix: ProxySOCKS4 had not been functional. FIXED. +- bugfix: NPE at closing the session when it is not opened. FIXED. +- change: JSch#getConfing has become public. + + +Changes since version 0.1.38: +- bugfix: session will be dropped at rekeying. FIXED. +- bugfix: NPE should not be thrown at unexpected session drop. FIXED. +- change: Channel#getSession() may throw JSchExecption. + + +Changes since version 0.1.37: +- bugfix: NPE should not be thrown at unexpected session drop. FIXED. +- bugfix: AIOOBE at Session#connect(). FIXED. +- bugfix: Even if 'true' is given for + Channel#setOutputStream(OutputStream out, boolean dontclose) + as the second paramter, 'out' will be closed. FIXED. +- change: 'examples/Sftp.java' has been modified to demonstrate + ChannelSftp#reaplpath(String path) +- change: setEnv(Hashtable env) for exec and shell channels have been + marked as @deprecated +- feature: setEnv(String name, String value) has been added to exec + and shell channels. +- feature: setEnv(byte[] name, byte[] value) has been added to exec + and shell channels. +- feature: ChannelSftp#realpath(String path) has been added. +- feature: ChannelExec#setCommand(byte[] command) has been added. +- feature: com.jcraft.jsch.ChannelSftp.LsEntry has implemented + java.lang.Comparable +- feature: Session#getServerAliveInterval(), Session#getServerAliveCountMaX() + have been added. + + +Changes since version 0.1.36: +- bugfix: some sftpd will send invalid data in sftp protocol + point of view, and we need to work around such data. FIXED. +- bugfix: the stream forwarding had been broken since 0.1.30. FIXED. +- bugfix: failed to detect 'SSH_MSG_CHANNEL_OPEN_FAILURE'. FIXED. +- bugfix: ChannelSftp will generate the unfavorable absolute pathname + in some case. FIXED. +- bugfix: failed to ignore the invalid public-key file. FIXED. +- change: ignoring empty data sent by 'SSH_MSG_CHANNEL_DATA' and + 'SSH_MSG_CHANNEL_EXTENDED_DATA'. +- change: updating copyright messages; 2007 -> 2008 +- change: build.xml will enable 'javac.debug' option by the default. +- change: added logging messages to IndentityFile and Session class. +- change: followings are deprecated methods, + InputStream ChannelSftp#get(String src, + int mode) + InputStream ChannelSftp#get(String src, + SftpProgressMonitor, + int mode) +- feature: following method is added, + InputStream ChannelSftp#get(String src, + SftpProgressMonitor monitor, + long skip) + + +Changes since version 0.1.35: +- bugfix: ChannelSftp can not handle the local filenames correctly on Windows. FIXED. +- bugfix: '/' must be handled as the file separator on JVM for Windows. FIXED. +- change: the system property + "javax.security.auth.useSubjectCredsOnly" + will be set to "false" for "gssapi-with-mic" + if that property is not given explicitly. +- change: added changes about ChannelSftp#{pwd(), home()} to + ChangeLog; 'Changes since version 0.1.34:' section. + + +Changes since version 0.1.34: +- bugfix: the OutputStream from the channel may make the JVM + lockup in some case. FIXED. + There was a possibility that Channel#connect() may be failed + to initialize its internal without throwing the JSchException. + On such case, the write operation for OutputStream from + that channel will cause the system(JVM) to lock up. +- bugfix: ChannelSftp had problems filename globbing. FIXED. +- bugfix: the message included in SSH_FXP_STATUS must be UTF-8. FIXED. +- change: ChannelSftp supports the filename globbing for + the filename in multi-byte characters. +- change: ChannelSftp will internally handle filenames in UTF-8 encoding. +- change: ChannelSftp#pwd() may throw an SftpException. +- change: ChannelSftp#home() may throw an SftpException. +- feature: following methods have been added in ChannelSftp + String getServerVersion() + String getClientVersion() + void setFilenameEncoding(String encoding) + String getExtension(String key) + +Changes since version 0.1.33: +- bugfix: there had a possibility that the session may be broken + if ciphers for upward/downward streams are different. FIXED. +- bugfix: the authentication method "keyboard-interactive" had + not been tried without UserInfo. FIXED. +- bugfix: ChannelShell#setTerminalMode(byte[] terminal_mode) had + not been functional. FIXED. +- bugfix: the remote port-forwarding to the daemon had been broken + since 0.1.30. FIXED. +- change: the cipher "aes128-cbc" will be used if AES is available. +- change: the interface 'com.jcraft.jsch.ForwardedTCPIPDaemon' has been changed. +- change: the data transfer rate will be improved on some environment. +- feature: ChannelExec can control the size of pty; + ChannelExec#setPtySize(int col, int row, int wp, int hp) is + added. +- feature: the property "CheckCiphers" has been added. + Refer to 'examples/AES.java'. +- feature: Session#setConfig(String key, String value), + JSch#setConfig(String key, String value) have been added. + + +Changes since version 0.1.32: +- bugfix: freeze in 'diffie-hellman-group-exchange-sha1'. FIXED. + By the default, 'diffie-hellman-group1-sha1' will be used + and if you have not chosen 'diffie-hellman-group-exchange-sha1' + explicitly, you don't have to worry about it. +- bugfix: there should be timeout mechanism in opening a socket + for remote port forwarding. FIXED. + At the failure or timeout, 'SSH_MSG_CHANNEL_OPEN_FAILURE' + will be sent to sshd. +- bugfix: there should be timeout mechanism in opening a socket + for X11 forwarding. FIXED. + At the failure or timeout, 'SSH_MSG_CHANNEL_OPEN_FAILURE' + will be sent to sshd. + + +Changes since version 0.1.31: +- bugfix: remote port forwarding will be hanged at its closing. FIXED. +- bugfix: X forwarding channels will be hanged and some resources + will be leaked whenever they are closed. FIXED. +- bugfix: failed to detect "Connection refused". FIXED. +- bugfix: at the failure for keyboard-interactive auth method, + a session will be terminated. FIXED. +- bugfix: due to the cancel for keyboard-interactive auth method, + a session will be terminated. FIXED. +- change: com.jcraft.jsch.jcraft.Compression#uncompress will respect + the argument "start". +- change: "gssapi-with-mic" will choose the default credential. +- feature: Session#setPortForwardingL will return the assigned local + TCP port number; TCP port will be assigned dynamically if lport==0. +- feature: support for SSH_MSG_UNIMPLEMENTED. +- feature: support for PASSWD_CHANGEREQ. + + +Changes since version 0.1.30: +- bugfix: a problem in padding for ciphered private key. + PKCS#5 padding should be used. FIXED. +- bugfix: crash in parsing invalid public key file. FIXED. +- bugfix: a public key may not have a comment. FIXED. +- bugfix: output stream from ChannelSftp#put will hang if it is closed + twice. FIXED. +- feature: agent forwarding. To enable this functionality, + Channel{Exec,Shell,Sftp}#setAgentForwarding(boolean enable) are added. +- feature: ChannelShell#setTerminalMode(byte[] terminal_mode) is added. +- feature: Session#setDaemonThread(boolean true) to run internal threads as + daemon threads. +- feature: an option "PreferredAuthentications" is added. + The default value is "gssapi-with-mic,publickey,keyboard-interactive,password". +- change: if alias-name is given, non-standard TCP port number will not be + saved in 'known_hosts' file. + + +Changes since version 0.1.29: +- bugfix: ChannelSftp#cd() will not throw an exception even if + a file is given. FIXED. +- bugfix: ChannelSftp#put() has a bug which will appear in using + on the slow network. FIXED. +- bugfix: ChannelSftp#ls() has a bug which will appear in using + on the slow network. FIXED. +- bugfix: a bug had sneaked in the remote port forwarding. FIXED. +- bugfix: some APIs from JCE have the memory leak on Mac OS X, + so we have re-written the code(com.jcraft.jsch.jcraft.HMAC* + classes) without them. On Mac OS X, such new classes will + be used automatically. FIXED. +- bugfix: the session will be crashed by the long banner message. FIXED. +- change: '/dev/random' will not be referred on Gnu/Linux. +- change: if non-standard TCP port number is used, that number will + be saved in known_hosts file as recent OpenSSH's ssh client does. +- change: Channel#getOutputStream will not use Piped{Output,Input}Stream. +- change: com.jcraft.jsch.HostKeyRepository interface has been + slightly modified. +- feature: Session#setPortForwardingR(String bind_address, ...) has been added. +- feature: the packet compression method 'zlib@openssh.com' has been supported. +- feature: the hashed known_hosts file has been supported. + Refer to 'examples/KnownHosts.java'. +- feature: the authentication method 'gssapi-with-mic' has been + experimentally supported. +- feature: com.jcraft.jsch.Logger interface and + JSch#setLogger(Logger logger) have been added. + Refer to 'examples/Logger.java' for the usage. + + +Changes since version 0.1.28: +- bugfix: ChannelSftp#put will stack in some situations FIXED. +- bugfix: ChannelSftp invoked 'glob_remote' redundantly. FIXED. +- bugfix: ChannelSftp failed to make globbing for some file names. FIXED. +- bugfix: ChannelSftp did not carefully read its input-stream. FIXED. +- bugfix: ChannelSftp#lstat did not try globbing for given path. FIXED. +- bugfix: at closing channel, eof_lcoal and eof_remote did not + become true. FIXED. +- bugfix: IdentityFile did not carefully read file input-streams. FIXED. +- bugfix: KeyPair did not carefully read file input-streams. FIXED. +- bugfix: ProxySOCKS4 did not carefully read file input-streams. FIXED. +- bugfix: ProxySOCKS5 did not carefully read file input-streams. FIXED. +- bugfix: ForwardedTCPIPDaemom may fail in some situation. FIXED. +- bugfix: X forwarding failed to handle the magic-cookie + in some case FIXED. + Thanks to Walter Pfannenmller. +- bugfix: setKnownHosts in KnownHosts.java doesn't read the last + line if linefeed is missing FIXED. + Thanks to Henrik Langos. +- bugfix: With StrictHostKeyChecking set to yes connect() + shouldn't ask. FIXED. + Thanks to Henrik Langos. +- change: Identity#setPassphrase(String passphrase) is replaced with + Identity#setPassphrase(byte[] passphrase). +- change: IdentityFile will clear its internal secrets at finalizing. +- change: KeyPair will clear its internal secrets at finalizing. +- change: KeyPair will clear its internal secrets at finalizing. +- change: MAC#doFinal() is replaced with + MAC#doFile(byte[] buf, int offset) +- change: at TCP socket reading timeout, keep-alive message will be sent + to the remote sshd. To disable this functionality, invoke + explicitly Session.setServerAliveCountMax(0) +- change: PortWatcher stops to use InetAddress.getByAddress(). +- change: in the user authentication, username, password and passphrase + will be encoded in UTF-8. +- change: JSch#addIdentity will check duplicate keys. +- change: SftpException#message has been deleted. +- change: SftpException#getMessage() will return the detailed message. +- feature: IdentityFile#setPassphrase(byte[] passphrase) is added. +- feature: IdentityFile#clear() is added to clear its internal secrets. +- feature: KeyPair#decrypt(byte[] passphrase) is added. +- feature: JSch#addIdentity(String path, byte[] passphrase) is added. +- feature: JSch#getIdentityNames() is added. +- feature: JSch#removeIdentity(String name) is added. +- feature: JSch#removeAllIdentity() is added. +- feature: ChannelSftp#readlink(String path) is added. +- feature: ChannelSftp#getHome() is added. +- feature: Channel#connect(int connectTimeout) is added. +- feature: ChannelShell#setPtyType(String ttype) is added. +- feature: Session#setPassword(byte[] password) is added. +- feature: Session#setHostKeyAlias(String alias) is added. +- feature: KeepAlive is implemented and + Session#setServerAliveInterval(int interval) and + Session#setServerAliveCountMax(int count) are added. +- feature: Session#sendKeepAliveMsg() is added. +- feature: JSchException#getCause() may return a reason. +- feature: SftpException#getCause() may return a reason. +- feature: ChannelExec#setErrStream(OutputStream out, boolean dontclose) + is added. + + +Changes since version 0.1.27: +- bugfix: ChannelSftp#localAbsolutePath did not work correctly. FIXED. +- bugfix: ChannelSftp#chmod did not work for directory. FIXED. +- bugfix: ProxyHTTP had a bug in processing HTTP headers. FIXED. +- bugfix: messages before server's version string should be ignored. FIXED. +- feature: Environment Variable Passing. + + +Changes since version 0.1.26: +- bugfix: there was a session crash bug. That occurrence is rare, but + depends on the thread scheduling. FIXED. +- bugfix: problems in generating remote/local absolute paths on sftp. FIXED. +- bugfix: problems in handling cancel operations for sftp. FIXED. +- bugfix: ChannelX11s were not terminated for a wrong cookie. FIXED. +- bugfix: NoSuchAlgorithmException should be thrown if JCE is not + accessible. FIXED. +- bugfix: ProxyHTTP should check the return code from proxy. FIXED. +- bugfix: server's version string should be checked carefully. FIXED. +- feature: some more improvements on sftp uploading. +- feature: 'getUserName' method is added to Session class. + + +Changes since version 0.1.25: +- bugfix: infinite loop/hang on connection at unexpected error during + key-exchanging operation. FIXED +- bugfix: delays on sftp uploading. FIXED +- bugfix: failed to purge a host-key from its repository in some case. FIXED. +- feature: SOCKS4 proxy + + +Changes since version 0.1.24: +- bugfix: remote port forwarding is not established. FIXED. +- bugfix: failed to parse known_hosts file if it has a long public key blob. + FIXED. +- bugfix: sftp put/get operations keep failing. FIXED. +- bugfix: ChannelShell.setXForwarding always set xforwarding to be true. FIXED. +- change: ChannelShell.setPty is added. +- change: Proxy interface is free from session object. +- change: added examples/ScpToNoneCipher.java to demonstrate NONE Cipher switching. +- feature: added NONE Cipher switching support. +- feature: timeout check will be enabled for proxy connections. + + +Changes since version 0.1.23: +- bugfix: there was resource leak problems in closing local port forwardings. + FIXED. +- bugfix: there was a session crash problems in using aes-cbc cipher. FIXED. +- change: ChannelSession.setPtySize was redefined. +- feature: added SocketFactory for remote port forwarding. + Session.setPortForwardingR(int rport, String host, int lport, + SocketFactory sf) +- feature: added ServerSocketFactory for local port forwarding. + Session.setPortForwardingL(String boundaddress, + int lport, String host, int rport, + ServerSocketFactory ssf) + +Changes since version 0.1.22: +- bugfix: there was a freeze problem at fails on key-exchanging. FIXED. +- bugfix: race-condition forcefully disconnects session in closing channels. + FIXED. + + +Changes since version 0.1.21: +- bugfix: there is a bug in read() method implementation for the + input-stream returned from ChannelSftp.get(). FIXED. +- bugfix: at fail on requesting for the remote port forwarding, + an exception should be thrown. FIXED. +- bugfix: SSH_MSG_CHANNEL_OPEN request for the X11 forwarding should not + be accepted if clients don not expect it. FIXED. +- bugfix: there is a problem in transferring large data(mote than 1GB) + to sshd from recent OpenSSH(3.6.1 or later). FIXED. + For security concerns, those sshd will re-key periodically and + jsch had failed to handle it. +- bugfix: 'exec', 'shell' and 'sftp' channels will fail if the acceptable + packet size by remote sshd is not so large. FIXED. +- bugfix: there are problems in 'InputStream ChannelSftp.get(String)' + and 'OutputStream put(String)'. FIXED. +- feature: added boolean flag 'dontclose' to + * setInputStream(), + * setOutputStream() and + * setExtOutputStream() + methods of Channel class. +- feature: added 'com.jcraft.jsch.ChannelSubsystem' +- feature: allowed to control the compression level in the packet compression. + Refer to 'examples/Compression.java'. +- change: modified 'com/jcraft/jsch/jce/KeyPairGenRSA.java' to be complied + on JDK 1.2. +- change: 'examples/ScpTo.java' and 'examples/ScpFrom.java' will use + 'long' type for the file size instead of 'int'. +- change: 'Identity.getSignature' method will not expect 'session'. +- change: while waiting for socket connection establishment, Thread.join + will be used instead of Thread.sleep. + + +Changes since version 0.1.20: +- known issue: there are problems in 'InputStream ChannelSftp.get(String)' + and 'OutputStream put(String)'. They will be re-implemented + in the next release. +- bugfix: EOF packets should not be sent twice. This bug had crashed + the session on every channel close. FIXED. +- bugfix: at the fail on opening connection to remote sshd, + a misleading exception "invalid server's version string" + had been thrown. FIXED. +- bugfix: fixed a bug in hadling the size of remote channel window. +- bugfix: channels should not be closed even if EOF is received. FIXED. +- bugfix: fixed bugs in file name globbing on sftp. +- change: to transfer packets efficiently, the size of internal buffer + for each channel has been increased. +- change: ChannelSftp.ls will return a vector of + com.jcraft.jsch.ChannelSftp.LsEntry. Sorry for inconveniences. +- feature: added ForwardedTCPIPDaemon. Refer to 'examples/Daemon.java', + which demonstrates to provide network services like inetd. +- feature: ChannelExec.setPty() method to request for assigning pseudo tty. +- feature: added ciphers "aes128-cbc", "aes192-cbc" and "aes256-cbc". + Refer to 'examples/AES.java'. +- feature: local port-forwarding settings can be dynamically deleted + by the bound address. +- feature: added 'Channel.isClosed()'. Channel.getExitStatus() should be + invoked after Channel.isClosed()==true. + + +Changes since version 0.1.19: +- ClassCastException while calling ChannelExec.finalize() method. FIXED. + Thanks to wswiatek at ais dot pl. + + +Changes since version 0.1.18: +- fixed problems related to thread-safety. + Thanks to Eric Meek at cs dot utk dot edu. +- At the lost of the network connectivity to the remote SSHD, clients + connected to the local port were never made aware of the + disconnection. FIXED. +- fixed confusions in handling EOFs from local input stream and + the input stream for remote process. +- 'com.jcraft.jsch.jce.AES128CBC' is added, but it is not be functional in + this release. It will work in the next release. +- Some sshd(Foxit-WAC-Serve) waits for SSH_MSG_NEWKEYS request before + sending it. FIXED. +- fixed a problem in connecting to Cisco Devices. + Thanks to Jason Jeffords at comcast dot net. +- changed the method 'add' of 'HostKeyRepository' interface. +- 'UIKeyborarInteracetive' will ignore empty prompt by sshd. +- added 'sendIgnore()' method to 'Session' class. +- added '-p' for scp command in 'examples/ScpTo.java' to preserve + modification times, access times, and modes from the original file. + + +Changes since version 0.1.17: +- added 'com.jcraft.jsch.HostKeyRepository' interface. + It will allow you to handle host keys in your own repository + (for example, RDB) instead of using 'known_hosts' file. +- added methods to get the finger-print of host keys. + refer to 'examples/KnownHosts.java'. +- improved 'known_hosts' file handling. + - comment lines will be kept. + - SSH1 host keys will be kept. + - each hostname can have multiple host keys. +- fixed a crash bug in processing private keys which have too long key-bits. + + +Changes since version 0.1.16: +- 'com.jcraft.jsch.jce.DHG1' and 'com.jcraft.jsch.jce.DHGEX' are moved to + 'com.jcraft.jsch' package. +- added APIs to handle hostkeys included in 'known_hosts', + JSch.getHostKeys(), + JSch.removeHostKey() +- allowing to set timeout value in opening sockets, + Session.connect(int timeout) + + +Changes since version 0.1.15: +- adding support of setting mtime for remote files on sftp channel. +- setKnownHosts method of JSch class will accept InputStream. +- implementation of Basic password authentication for HTTP proxy. +- fixed a bug in checking which ssh protocol version remote sshd supports +- SSH_MSG_CHANNEL_OPEN_FAILURE will be handled correctly. +- methods in SftpATTRS class has been public. +- working around SIGBLOB bug hidden in older sshd. + + +Changes since version 0.1.14: +- fixed a crash bug in accepting keep-alive messages. +- the parent directory of 'known_hosts' file will be created + if it does not exist. +- the Subsystem channel support was removed. + + +Changes since version 0.1.13: +- added 'setClientVersion' method to Session class. +- fixed hung-up problem on SftpChannel in connecting to + the sshd, which does not support sftp. +- fixed OutOfMemory exception problem in decrypting a private key + with bad passphrase. +- fixed hung-up problem in communicating with the sshd, + whose window size is small. +- RuntimeExceptions will be thrown from jsch APIs. +- SSH_MSG_CHANNEL_SUCCESS and SSH_MSG_CHANNEL_FAILURE requests + have been supported. + + +Changes since version 0.1.12: +- added the partial authentication support. +- allowing to change the passphrase of a private key file + instead of creating a new private key. +- added 'examples/ChangePassphrase.java' +- the interface 'UIKeyboardInteractive' has been modified. + + +Changes since version 0.1.11: +- RSA keypair generation. +- added the method 'getFingerPrint' to KeyPair class, + which will return the finger print of the public key. +- fixed a bug in generating non-ciphered private key. + + +Changes since version 0.1.10: +- fixed a bug in the password authentication, sneaked in + 0.1.9. By this bug, the password authentication had failed every time. + + +Changes since version 0.1.9: +- username and password can be in UTF-8 encoding. +- DSA keypair generation. +- added 'examples/KeyGen.java', which demonstrates + the DSA keypair generation. + + +Changes since version 0.1.8: +- fixed crash problems on the local port forwarding. +- fixed crash problems on the remote port forwarding. +- added setErrStream() and getErrStream() to ChannelExec. +- added keyboard-interactive authentication support. +- modified TripleDESCBC to support IBM's JDK 1.4.1. +- added 'examples/UserAuthKI.java', which demonstrates keyboard-interactive + authentication. + + +Changes since version 0.1.7: +- added APIs for sftp resume downloads and uploads. + The author greatly appreciates + elpernotador(webmaster at unlix dot com dot ar), + who motivated him to hack this functionality. +- 'examples/Sftp.java' demonstrates sftp resume functionality. + Please refer to "put-resume", "put-append", "get-resume" and + "get-append" command. +- added the support of 'window-change' request. +- fixed a freeze bug in 'Inputstream get(String src)' method of 'ChannelSftp' + class. + + +Changes since version 0.1.6: +- added 'int getExitStatus()' method to 'Channel' class. +- fixed crash bugs in closing channels for port forwarding. +- fixed glitches in managing forwarded ports. + + +Changes since version 0.1.5: +- fixed crash bugs in port forwarding. +- modified to use "ssh-rsa" for key-exchanging by the default. +- the port forwarding setting can be canceled dynamically. +- fixed a freeze bug in getting an empty file on sftp channel. + + +Changes since version 0.1.4: +- fixed a bug in managing local window size. + The local window should be consumed by CHANNEL_EXTENDED_DATA packet. +- checking the availability of the ssh session in opening channels. + In some case, ssh session had been freezed. +- java.io.File.separator will be refereed in generating local pathname + on sftp channel. +- absolute local pathname will be handled correctly on sftp channel. + + +Changes since version 0.1.3: +- fixed a serious bug, which had leaked resources related to + ChannelExec. +- added the older SFTP protocol(version 0, 1, 2) support. +- fixed a problem in the authentication step for FSecure's sshd. +- fixed a bug, which had broken Diffie-Hellman key exchange in some case. +- implemented the file name globbing for local files on sftp session. +- fixed a bug in the file name globbing. +- added an interface 'SftpProgressMonitor'. +- modified 'examples/Sftp.java' to demonstrate displaying progress-bar + in transferring files. + + +Changes since version 0.1.2: +- modified 'build.xml' to allow Ant users to compile jsch with debug + support (i.e. line-number tables) by overriding the property + javac.debug on the command line. +- added a property 'StrictHostKeyChecking'. +- added 'UserAuthNone' class to request a list of authentication methods on + remote sshd. +- channels will be managed in each sessions. +- added 'ChannelSubsystem', which allows users to use their own + implementations for subsystems. +- added 'isEOF()' method to 'Channel' class. +- supported key pair files in DOS file format. + + +Changes since version 0.1.1: +- added the file name globbing support on sftp session. +- fixed a bug in the public key authentication. + When there was not a public key in ~/.ssh/, that problem occurred. +- improved the 'setTimeout' method. +- fixed a typo in 'LICENSE.txt' + + +Changes since version 0.1.0: +- added 'rekey' method to 'Session' class for key re-exchanging. +- added 'rekey' and 'compression' command to 'examples/Sftp.java'. +- added new 'get' and 'put' methods to 'ChannelSftp'. + Those methods will operate I/O streams. +- methods in 'ChannelSftp' will throw 'SftpException' +- 'ChannelSftp.Ssh_exp_name' is added for the output of 'ls'. + Thanks to Graeme Vetterlein. +- added 'setTimeout' and 'getTimeout' methods to 'Session' class. +- guess will be done in the algorithm negotiation step. +- FSecure's DSA private key has been supported partially. +- hostkeys will be saved into 'known_hosts' file. +- fixed a bug in 'Util.toBase64' method. +- 'Identity' will reject unrecognized keys. +- 'build.xml' will check if jzlib is available or not. + Thanks to Stefan Bodewig. +- added javadoc target in 'build.xml'. + Thanks to Robert Anderson. + + +Changes since version 0.0.13: +- fixed a bug in connecting to Fsecure's sshd on Windows. +- the license is changed to BSD style. + + +Changes since version 0.0.12: +- fixed a bug in verifying DAS signatures. +- added 'SftpATTR' class, which allow you to get attributes of remote files on + sftp channel, and 'stat', 'lstat' method are added to 'ChannelSftp' class. +- added 'getInputStream' and 'getOutputStream' methods Channel class, which + return passive I/O streams. +- 'setIdentity' method is deleted from 'Session' class and + 'addIdentity' method is added to 'JSch' class +- 'setUserName' method is deleted from 'Session' class and + 'getSession' method of 'JSch' class is changed. +- 'isConnected' method is added to 'Session' class. +- 'UserInfo' interface is changed. + + +Changes since version 0.0.11: +- taking care of remote window size. +- adding 'disconnect' method to 'Channel' and 'Session' classes. +- signal sending support. +- 'mkdir' command for sftp. +- 'fromBase64' method has been moved to Util class and 'toBase64' method has + also been added to that class. +- 'KnownHosts' class for checking host-key in 'known_host' file. +- 'examples/KnownHosts.java' has been added. +- 'setUserName' and 'setPassword' methods have been added to Session class. +- 'UserInfo' interface has been changed. +- The implementation of compression has moved to 'com.jcraft.jsch.jcraft' + package. +- fixed a bug in handling 'SSH_MSG_CHANNEL_REQUET' request. +- fixed a bug in sending multiple requests on a single session. + + +Changes since version 0.0.10: +- Diffie-Hellman key exchange 'diffie-hellman-group1-sha1' is supported. + Refer to 'src/com/jcraft/jsch/jce/DHG1.java'. + Thanks to Mitsugu Kitano, whose feedback was very helpful. +- By the default, 'diffie-hellman-group1-sha1' will be used in the + key exchange step. +- The file attribute on 'SSH File Transfer Protocol' is supported. + Now, we can say JSch supports 'SSH File Transfer Protocol'. +- 'examples/Sftp.java' is updated. + 'chgrp','chown','chmod' commands are supported. + + +Changes since version 0.0.9: +- SSH File Transfer Protocol is supported partially. +- 'examples/Sftp.java' is added. + This example is a tiny sftp command and supports 'cd','put','get','rm',etc. +- 'close' method is added to Channel interface. +- build.xml for examples is added. + Thanks to Ronald Broberg. + + +Changes since version 0.0.8: +- the tunneling through a SOCKS5 proxy is supported. +- 'examples/ScpFrom.java' is added. +- 'com.jcraft.jsch.UserInfo' interface is modified. + + +Changes since version 0.0.7: +- Packet comression is supported. +- 'examples/Compression.java' is added. +- JZlib is included. + + +Changes since version 0.0.6: +- RSA host key is supported. +- RSA public key authentication is supported. + + +Changes since version 0.0.5: +- DSA public key authentication is supported. +- examples/UserAuthPubKey.java is added. +- examples/ScpTo.java is added. + + +Changes since version 0.0.4: +- 3des-cbc is supported. +- hmac-sha1 is supported. +- hmac-md5-96 is supported. +- hmac-sha1-96 is supported. + + +Changes since version 0.0.3: +- port forwarding, similar to the -L option of SSH. +- examples/PortForwardingL.java is added. +- examples/StreamForwarding.java is added. +- examples/Exec.java is renamed as examples/Shell.java +- stream forwarding is added. +- ChannelSftp class is added for implementing filexfer. +- interfaces for jsch users are changed. + + +Changes since version 0.0.2: +- remote exec is supported. +- examples/Exec.java is added. +- build.xml and some scripts for Ant are added. (lbruand) +- Const class is added. (lbruand) + + +Changes since version 0.0.1: +- the tunneling via HTTP proxy is supported. +- port forwarding like option -R of ssh command. + the given port on the remote host will be forwarded to the given host + and port on the local side. diff --git a/lab8/jsch-0.1.55/LICENSE.txt b/lab8/jsch-0.1.55/LICENSE.txt new file mode 100644 index 0000000..303096b --- /dev/null +++ b/lab8/jsch-0.1.55/LICENSE.txt @@ -0,0 +1,30 @@ +JSch 0.0.* was released under the GNU LGPL license. Later, we have switched +over to a BSD-style license. + +------------------------------------------------------------------------------ +Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lab8/jsch-0.1.55/README b/lab8/jsch-0.1.55/README new file mode 100644 index 0000000..d00a219 --- /dev/null +++ b/lab8/jsch-0.1.55/README @@ -0,0 +1,229 @@ + + JSch + + Java Secure Channel + by ymnk@jcraft.com, JCraft,Inc. + + http://www.jcraft.com/jsch/ + +Last modified: Thu Mar 18 13:58:16 UTC 2015 + + +Description +=========== +JSch is a pure Java implementation of SSH2. JSch allows you to +connect to an sshd server and use port forwarding, X11 forwarding, +file transfer, etc., and you can integrate its functionality +into your own Java programs. JSch is licensed under BSD style license. + + +Documentation +============= +* README files all over the source tree have info related to the stuff + in the directories. +* ChangeLog: what changed from the previous version? + + +Directories & Files in the Source Tree +====================================== +* src/com/ has source trees of JSch +* example/ has some samples, which demonstrate the usages. +* tools/ has scripts for Ant. + + +Why JSch? +========== +Our intension in developing this stuff is to enable users of our pure +java X servers, WiredX(http://wiredx.net/) and WeirdX, to enjoy secure X +sessions. Our efforts have mostly targeted the SSH2 protocol in relation +to X Window System and X11 forwarding. Of course, we are also interested in +adding other functionality - port forward, file transfer, terminal emulation, etc. + + +Features +======== +* JSch is in pure Java, but it depends on JavaTM Cryptography + Extension (JCE). JSch is know to work with: + o J2SE 1.4.0 or later (no additional libraries required). + o J2SE 1.3 and Sun's JCE reference implementation that can be + obtained at http://java.sun.com/products/jce/ + o J2SE 1.2.2 and later and Bouncycastle's JCE implementation that + can be obtained at http://www.bouncycastle.org/ +* SSH2 protocol support. +* Key exchange: diffie-hellman-group-exchange-sha1, + diffie-hellman-group1-sha1, + diffie-hellman-group14-sha1, + diffie-hellman-group-exchange-sha256, + ecdh-sha2-nistp256, + ecdh-sha2-nistp384, + ecdh-sha2-nistp521 +* Cipher: blowfish-cbc,3des-cbc,aes128-cbc,aes192-cbc,aes256-cbc + 3des-ctr,aes128-ctr,aes192-ctr,aes256-ctc, + arcfour,arcfour128,arcfour256 +* MAC: hmac-md5,hmac-md5-96,hmac-sha1,hmac-sha1-96 +* Host key type: ssh-dss,ssh-rsa, + ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521 +* Userauth: password +* Userauth: publickey(DSA,RSA,ECDSA) +* Userauth: keyboard-interactive +* Userauth: gssapi-with-mic +* X11 forwarding. +* xauth spoofing. +* connection through HTTP proxy. +* connection through SOCKS5, SOCKS4 proxy. +* port forwarding. +* stream forwarding. +* signal sending. + The unofficial patch for sshd of openssh will be find in the thread + http://marc.theaimsgroup.com/?l=openssh-unix-dev&m=104295745607575&w=2 +* envrironment variable passing. +* remote exec. +* generating DSA and RSA key pairs. +* supporting private keys in OpenSSL(traditional SSLeay) and PKCS#8 format. +* SSH File Transfer Protocol(version 0, 1, 2, 3) +* partial authentication +* packet compression: zlib, zlib@openssh.com + JZlib(http://www.jcraft.com/jzlib/) has been used. +* hashed known_hosts file. +* NONE Cipher switching. + http://www.psc.edu/networking/projects/hpn-ssh/none.php +* JSch is licensed under BSD style license(refer to LICENSE.txt). + + +How To Try +========== +This archive does not include java byte code, so please compile +the source code by your self. + $ cd jsch-?.?.?/src + $ javac com/jcraft/jsch/*java com/jcraft/jsch/jce/*java com/jcraft/jzlib/*.java +'/examples/' directory has included some samples to demonstrate what +JSch can do. Please refer to '/examples/README' file. + + +AES cipher +========== +JSch supports aes128-cbc,aes192-cbc,aes256-cbc,aes128-ctr,aes192-ctr, +aes256-ctr but you require AES support in your J2SE to choose some of them. +If you are using Sun's J2SE, J2SE 1.4.2 or later is required. +And then, J2SE 1.4.2(or later) does not support aes256 by the default, +because of 'import control restrictions of some countries'. +We have confirmed that by applying + "Java Cryptography Extension (JCE) + Unlimited Strength Jurisdiction Policy Files 1.4.2" +on + http://java.sun.com/j2se/1.4.2/download.html#docs +we can enjoy 'aes256-cbc,aes256-ctr'. + + +Stream Forwarding +================= +JSch has a unique functionality, Stream Forwarding. +Stream Forwarding allows you to plug Java I/O streams directly into a remote TCP +port without assigning and opening a local TCP port. +In port forwarding, as with the -L option of ssh command, you have to assign +and open a local TCP port and that port is also accessible by crackers +on localhost. In some case, that local TCP port may be plugged to a +secret port via SSH session. +A sample program, /example/StreamForwarding.java , demonstrates +this functionality. + + +Generating Authentication Keys +============================== +JSch allows you to generate DSA and RSA key pairs, which are in OpenSSH format. +Please refer to 'examples/KeyGen.java'. + + +Packet Compression +================== +According to the draft from IETF sesch working group, the packet +compression can be applied to each data stream directions; from sshd +server to ssh client and from ssh client to sshd server. So, jsch +allows you to choose which data stream direction will be compressed or not. +For example, in X11 forwarding session, the packet compression for data +stream from sshd to ssh client will save the network traffic, but +usually the traffic from ssh client to sshd is light, so by omitting +the compression for this direction, you may be able to save some CPU time. +Please refer to a sample program 'examples/Compression.java'. + + +Property +======== +By setting properties, you can control the behavior of jsch. +Here is an example of enabling the packet compression, + + Session session=jsch.getSession(user, host, 22); + java.util.Properties config=new java.util.Properties(); + config.put("compression.s2c", "zlib,none"); + config.put("compression.c2s", "zlib,none"); + session.setConfig(config); + session.connect(); + +Current release has supported following properties, +* compression.s2c: zlib, none + default: none + Specifies whether to use compression for the data stream + from sshd to jsch. If "zlib,none" is given and the remote sshd does + not allow the packet compression, compression will not be done. +* compression.c2s: zlib, none + default: none + Specifies whether to use compression for the data stream + from jsch to sshd. +* StrictHostKeyChecking: ask | yes | no + default: ask + If this property is set to ``yes'', jsch will never automatically add + host keys to the $HOME/.ssh/known_hosts file, and refuses to connect + to hosts whose host key has changed. This property forces the user + to manually add all new hosts. If this property is set to ``no'', + jsch will automatically add new host keys to the user known hosts + files. If this property is set to ``ask'', new host keys will be + added to the user known host files only after the user has confirmed + that is what they really want to do, and jsch will refuse to connect + to hosts whose host key has changed. + + +TODO +==== +* re-implementation with java.nio. +* replacing cipher, hash by JCE with pure Java code. +* SSH File Transfer Protocol version 4. +* error handling. + + +Copyrights & Disclaimers +======================== +JSch is copyrighted by ymnk, JCraft,Inc. and is licensed through BSD style license. +Read the LICENSE.txt file for the complete license. + + +Credits and Acknowledgments +============================ +JSch has been developed by ymnk@jcraft.com and it can not be hacked +without several help. +* First of all, we want to thank JCE team at Sun Microsystems. + For long time, we had planed to implement SSH2 in pure Java, + but we had hesitated to do because tons of work must be done for + implementing ciphers, hashes, etc., from the scratch. + Thanks to newly added functionalities to J2SE 1.4.0, we could + start this project. +* We appreciate the OpenSSH project. + The options '-ddd' of sshd, '---vvv' of ssh and the compile options + '-DPACKET_DEBUG', '-DDEBUG_KEXDH' and '-DDEBUG_KEX' were very + useful in debugging JSch. +* We appreciate IETF sesch working group and SSH Communications Security Corp. + Without the standardization of the protocol, we could not get the + chance to implement JSch. +* We appreciate Seigo Haruyama(http://www.unixuser.org/~haruyama/), + who are interpreting drafts of SSH2 protocol in Japanese. + His works were very useful for us to understand the technical terms + in our native language. +* We also appreciate SourceForge.net's awesome service to the + Open Source Community. + + +If you have any comments, suggestions and questions, write us +at jsch@jcraft.com + + +``SSH is a registered trademark and Secure Shell is a trademark of +SSH Communications Security Corp (www.ssh.com)''. diff --git a/lab8/jsch-0.1.55/build.bat b/lab8/jsch-0.1.55/build.bat new file mode 100644 index 0000000..91d56dc --- /dev/null +++ b/lab8/jsch-0.1.55/build.bat @@ -0,0 +1,17 @@ +@echo off + +echo. +echo JSch Build System +echo ----------------- + +set OLD_ANT_HOME=%ANT_HOME% +set ANT_HOME=tools + +set OLD_CLASSPATH=%CLASSPATH% + +%ANT_HOME%\bin\ant.bat -emacs %1 %2 %3 %4 %5 %6 %7 %8 +goto cleanup + +:cleanup +set ANT_HOME=%OLD_ANT_HOME% +set CLASSPATH=%OLD_CLASSPATH% diff --git a/lab8/jsch-0.1.55/build.sh b/lab8/jsch-0.1.55/build.sh new file mode 100644 index 0000000..9435a67 --- /dev/null +++ b/lab8/jsch-0.1.55/build.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +echo +echo "JSch Build System" +echo "-----------------" + +export OLD_ANT_HOME=$ANT_HOME +ANT_HOME=./tools + +export OLD_CLASSPATH=$CLASSPATH + + + +export CLASSPATH + +chmod u+x ${ANT_HOME}/bin/antRun +chmod u+x ${ANT_HOME}/bin/ant + +export PROPOSAL="" + + +${ANT_HOME}/bin/ant -emacs $@ + +export CLASSPATH=$OLD_CLASSPATH +export ANT_HOME=$OLD_ANT_HOME diff --git a/lab8/jsch-0.1.55/build.xml b/lab8/jsch-0.1.55/build.xml new file mode 100644 index 0000000..ae9e76e --- /dev/null +++ b/lab8/jsch-0.1.55/build.xml @@ -0,0 +1,97 @@ + + +JSch is a pure Java implementation of SSH2. JSch allows you to connect to an +sshd server and use port forwarding, X11 forwarding, file transfer, etc., and +you can integrate its functionality into your own Java programs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lab8/jsch-0.1.55/examples/AES.java b/lab8/jsch-0.1.55/examples/AES.java new file mode 100644 index 0000000..0b3e80e --- /dev/null +++ b/lab8/jsch-0.1.55/examples/AES.java @@ -0,0 +1,149 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/** + * This program will demonstrate how to use "aes128-cbc". + * + */ +import com.jcraft.jsch.*; +import java.awt.*; +import javax.swing.*; + +public class AES{ + public static void main(String[] arg){ + + try{ + JSch jsch=new JSch(); + + //jsch.setKnownHosts("/home/foo/.ssh/known_hosts"); + + String host=null; + if(arg.length>0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + //session.setPassword("your password"); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.setConfig("cipher.s2c", "aes128-cbc,3des-cbc,blowfish-cbc"); + session.setConfig("cipher.c2s", "aes128-cbc,3des-cbc,blowfish-cbc"); + session.setConfig("CheckCiphers", "aes128-cbc"); + + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ + return false; + } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none"); + session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none"); + session.setConfig("compression_level", "9"); + + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String foo=JOptionPane.showInputDialog("Enter remote port number", + "8888"); + rport=Integer.parseInt(foo); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + //session.setPortForwardingR(rport, Parrot.class.getName()); + session.setPortForwardingR(rport, "Daemon$Parrot"); + System.out.println(host+":"+rport+" <--> "+"Parrot"); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class Parrot implements ForwardedTCPIPDaemon{ + ChannelForwardedTCPIP channel; + Object[] arg; + InputStream in; + OutputStream out; + + public void setChannel(ChannelForwardedTCPIP c, InputStream in, OutputStream out){ + this.channel=c; + this.in=in; + this.out=out; + } + public void setArg(Object[] arg){this.arg=arg;} + public void run(){ + try{ + byte[] buf=new byte[1024]; + System.out.println("remote port: "+channel.getRemotePort()); + System.out.println("remote host: "+channel.getSession().getHost()); + while(true){ + int i=in.read(buf, 0, buf.length); + if(i<=0)break; + out.write(buf, 0, i); + out.flush(); + if(buf[0]=='.')break; + } + } + catch(JSchException e){ + System.out.println("session is down."); + } + catch(IOException e){ + } + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result=JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + /* + String xhost="127.0.0.1"; + int xport=0; + String display=JOptionPane.showInputDialog("Enter display name", + xhost+":"+xport); + xhost=display.substring(0, display.indexOf(':')); + xport=Integer.parseInt(display.substring(display.indexOf(':')+1)); + session.setX11Host(xhost); + session.setX11Port(xport+6000); + */ + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + String command=JOptionPane.showInputDialog("Enter command", + "set|grep SSH"); + + Channel channel=session.openChannel("exec"); + ((ChannelExec)channel).setCommand(command); + + // X Forwarding + // channel.setXForwarding(true); + + //channel.setInputStream(System.in); + channel.setInputStream(null); + + //channel.setOutputStream(System.out); + + //FileOutputStream fos=new FileOutputStream("/tmp/stderr"); + //((ChannelExec)channel).setErrStream(fos); + ((ChannelExec)channel).setErrStream(System.err); + + InputStream in=channel.getInputStream(); + + channel.connect(); + + byte[] tmp=new byte[1024]; + while(true){ + while(in.available()>0){ + int i=in.read(tmp, 0, 1024); + if(i<0)break; + System.out.print(new String(tmp, 0, i)); + } + if(channel.isClosed()){ + if(in.available()>0) continue; + System.out.println("exit-status: "+channel.getExitStatus()); + break; + } + try{Thread.sleep(1000);}catch(Exception ee){} + } + channel.disconnect(); + session.disconnect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ + return false; + } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + /* + // In adding to known_hosts file, host names will be hashed. + session.setConfig("HashKnownHosts", "yes"); + */ + + session.connect(); + + { + HostKey hk=session.getHostKey(); + System.out.println("HostKey: "+ + hk.getHost()+" "+ + hk.getType()+" "+ + hk.getFingerPrint(jsch)); + } + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyLogger implements com.jcraft.jsch.Logger { + static java.util.Hashtable name=new java.util.Hashtable(); + static{ + name.put(new Integer(DEBUG), "DEBUG: "); + name.put(new Integer(INFO), "INFO: "); + name.put(new Integer(WARN), "WARN: "); + name.put(new Integer(ERROR), "ERROR: "); + name.put(new Integer(FATAL), "FATAL: "); + } + public boolean isEnabled(int level){ + return true; + } + public void log(int level, String message){ + System.err.print(name.get(new Integer(level))); + System.err.println(message); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result=JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ + return false; + } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + String config = + "Port 22\n"+ + "\n"+ + "Host foo\n"+ + " User "+user+"\n"+ + " Hostname "+host+"\n"+ + "Host *\n"+ + " ConnectTime 30000\n"+ + " PreferredAuthentications keyboard-interactive,password,publickey\n"+ + " #ForwardAgent yes\n"+ + " #StrictHostKeyChecking no\n"+ + " #IdentityFile ~/.ssh/id_rsa\n"+ + " #UserKnownHostsFile ~/.ssh/known_hosts"; + + System.out.println("Generated configurations:"); + System.out.println(config); + + ConfigRepository configRepository = + com.jcraft.jsch.OpenSSHConfig.parse(config); + //com.jcraft.jsch.OpenSSHConfig.parseFile("~/.ssh/config"); + + jsch.setConfigRepository(configRepository); + + // "foo" is from "Host foo" in the above config. + Session session=jsch.getSession("foo"); + + String passwd = JOptionPane.showInputDialog("Enter password"); + session.setPassword(passwd); + + UserInfo ui = new MyUserInfo(){ + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + public boolean promptYesNo(String message){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + message, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + // If password is not given before the invocation of Session#connect(), + // implement also following methods, + // * UserInfo#getPassword(), + // * UserInfo#promptPassword(String message) and + // * UIKeyboardInteractive#promptKeyboardInteractive() + + }; + + session.setUserInfo(ui); + + session.connect(); // making a connection with timeout as defined above. + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + /* + // a hack for MS-DOS prompt on Windows. + channel.setInputStream(new FilterInputStream(System.in){ + public int read(byte[] b, int off, int len)throws IOException{ + return in.read(b, off, (len>1024?1024:len)); + } + }); + */ + + channel.setOutputStream(System.out); + + /* + // Choose the pty-type "vt102". + ((ChannelShell)channel).setPtyType("vt102"); + */ + + /* + // Set environment variable "LANG" as "ja_JP.eucJP". + ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP"); + */ + + //channel.connect(); + channel.connect(3*1000); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static abstract class MyUserInfo + implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return null; } + public boolean promptYesNo(String str){ return false; } + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return false; } + public boolean promptPassword(String message){ return false; } + public void showMessage(String message){ } + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + return null; + } + } +} diff --git a/lab8/jsch-0.1.55/examples/PortForwardingL.java b/lab8/jsch-0.1.55/examples/PortForwardingL.java new file mode 100644 index 0000000..a34f238 --- /dev/null +++ b/lab8/jsch-0.1.55/examples/PortForwardingL.java @@ -0,0 +1,155 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/** + * This program will demonstrate the port forwarding like option -L of + * ssh command; the given port on the local host will be forwarded to + * the given remote host and port on the remote side. + * $ CLASSPATH=.:../build javac PortForwardingL.java + * $ CLASSPATH=.:../build java PortForwardingL + * You will be asked username, hostname, port:host:hostport and passwd. + * If everything works fine, you will get the shell prompt. + * Try the port on localhost. + * + */ +import com.jcraft.jsch.*; +import java.awt.*; +import javax.swing.*; + +public class PortForwardingL{ + public static void main(String[] arg){ + + int lport; + String rhost; + int rport; + + try{ + JSch jsch=new JSch(); + + String host=null; + if(arg.length>0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String foo=JOptionPane.showInputDialog("Enter -L port:host:hostport", + "port:host:hostport"); + lport=Integer.parseInt(foo.substring(0, foo.indexOf(':'))); + foo=foo.substring(foo.indexOf(':')+1); + rhost=foo.substring(0, foo.indexOf(':')); + rport=Integer.parseInt(foo.substring(foo.indexOf(':')+1)); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + //Channel channel=session.openChannel("shell"); + //channel.connect(); + + int assinged_port=session.setPortForwardingL(lport, rhost, rport); + System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String foo=JOptionPane.showInputDialog("Enter -R port:host:hostport", + "port:host:hostport"); + rport=Integer.parseInt(foo.substring(0, foo.indexOf(':'))); + foo=foo.substring(foo.indexOf(':')+1); + lhost=foo.substring(0, foo.indexOf(':')); + lport=Integer.parseInt(foo.substring(foo.indexOf(':')+1)); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + // Channel channel=session.openChannel("shell"); + // channel.connect(); + + session.setPortForwardingR(rport, lhost, lport); + + System.out.println(host+":"+rport+" -> "+lhost+":"+lport); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i'. + 'help' command will show available command. + In current implementation, the destination path for 'get' and 'put' + commands must be a file, not a directory. + +- KnownHosts.java + This program will demonstrate the 'known_hosts' file handling. + $ CLASSPATH=.:../build javac KnownHosts.java + $ CLASSPATH=.:../build java KnownHosts + You will be asked username, hostname, a path for 'known_hosts' and passwd. + If everything works fine, you will get the shell prompt. + In current implementation, jsch only reads 'known_hosts' for checking + and does not modify it. + +- UserAuthKI.java + This program will demonstrate the keyboard-interactive authentication. + $ CLASSPATH=.:../build javac UserAuthKI.java + $ CLASSPATH=.:../build java UserAuthKI + If the remote sshd supports keyboard-interactive authentication, + you will be prompted. + +- KeyGen.java + This progam will demonstrate the DSA keypair generation. + $ CLASSPATH=.:../build javac KeyGen.java + $ CLASSPATH=.:../build java KeyGen rsa output_keyfile comment +or + $ CLASSPATH=.:../build java KeyGen dsa output_keyfile comment + You will be asked a passphrase for output_keyfile. + If everything works fine, you will get the DSA or RSA keypair, + output_keyfile and output_keyfile+".pub". + The private key and public key are in the OpenSSH format. + +- ChangePassphrase.java + This program will demonstrate to change the passphrase for a + private key file instead of creating a new private key. + $ CLASSPATH=.:../build javac ChangePassphrase.java + $ CLASSPATH=.:../build java ChangePassphrase private-key + A passphrase will be prompted if the given private-key has been + encrypted. After successfully loading the content of the + private-key, the new passphrase will be prompted and the given + private-key will be re-encrypted with that new passphrase. + +- AES.java + This program will demonstrate how to use "aes128-cbc". + +- Daemon.java + This program will demonstrate how to provide a network service like + inetd by using remote port-forwarding functionality. + +- Logger.java + This program will demonstrate how to enable logging mechanism and + get logging messages. + +- Subsystem.java + This program will demonstrate how to use the Subsystem channel. + +- Sudo.java + This program will demonstrate how to exec 'sudo' on the remote. + +- ScpToNoneCipher.java + This program will demonstrate how to enable none cipher. + +- JumpHosts.java + This program will demonstrate SSH through jump hosts. + +- OpenSSHConfig.java + This program will demonstrate how OpenSSH's config is supported. diff --git a/lab8/jsch-0.1.55/examples/ScpFrom.java b/lab8/jsch-0.1.55/examples/ScpFrom.java new file mode 100644 index 0000000..0d633ae --- /dev/null +++ b/lab8/jsch-0.1.55/examples/ScpFrom.java @@ -0,0 +1,249 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/** + * This program will demonstrate the file transfer from remote to local + * $ CLASSPATH=.:../build javac ScpFrom.java + * $ CLASSPATH=.:../build java ScpFrom user@remotehost:file1 file2 + * You will be asked passwd. + * If everything works fine, a file 'file1' on 'remotehost' will copied to + * local 'file1'. + * + */ +import com.jcraft.jsch.*; +import java.awt.*; +import javax.swing.*; +import java.io.*; + +public class ScpFrom{ + public static void main(String[] arg){ + if(arg.length!=2){ + System.err.println("usage: java ScpFrom user@remotehost:file1 file2"); + System.exit(-1); + } + + FileOutputStream fos=null; + try{ + + String user=arg[0].substring(0, arg[0].indexOf('@')); + arg[0]=arg[0].substring(arg[0].indexOf('@')+1); + String host=arg[0].substring(0, arg[0].indexOf(':')); + String rfile=arg[0].substring(arg[0].indexOf(':')+1); + String lfile=arg[1]; + + String prefix=null; + if(new File(lfile).isDirectory()){ + prefix=lfile+File.separator; + } + + JSch jsch=new JSch(); + Session session=jsch.getSession(user, host, 22); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + // exec 'scp -f rfile' remotely + rfile=rfile.replace("'", "'\"'\"'"); + rfile="'"+rfile+"'"; + String command="scp -f "+rfile; + Channel channel=session.openChannel("exec"); + ((ChannelExec)channel).setCommand(command); + + // get I/O streams for remote scp + OutputStream out=channel.getOutputStream(); + InputStream in=channel.getInputStream(); + + channel.connect(); + + byte[] buf=new byte[1024]; + + // send '\0' + buf[0]=0; out.write(buf, 0, 1); out.flush(); + + while(true){ + int c=checkAck(in); + if(c!='C'){ + break; + } + + // read '0644 ' + in.read(buf, 0, 5); + + long filesize=0L; + while(true){ + if(in.read(buf, 0, 1)<0){ + // error + break; + } + if(buf[0]==' ')break; + filesize=filesize*10L+(long)(buf[0]-'0'); + } + + String file=null; + for(int i=0;;i++){ + in.read(buf, i, 1); + if(buf[i]==(byte)0x0a){ + file=new String(buf, 0, i); + break; + } + } + + //System.out.println("filesize="+filesize+", file="+file); + + // send '\0' + buf[0]=0; out.write(buf, 0, 1); out.flush(); + + // read a content of lfile + fos=new FileOutputStream(prefix==null ? lfile : prefix+file); + int foo; + while(true){ + if(buf.length0){ + command+=lfile.substring(lfile.lastIndexOf('/')+1); + } + else{ + command+=lfile; + } + command+="\n"; + out.write(command.getBytes()); out.flush(); + if(checkAck(in)!=0){ + System.exit(0); + } + + // send a content of lfile + fis=new FileInputStream(lfile); + byte[] buf=new byte[1024]; + while(true){ + int len=fis.read(buf, 0, buf.length); + if(len<=0) break; + out.write(buf, 0, len); //out.flush(); + } + fis.close(); + fis=null; + // send '\0' + buf[0]=0; out.write(buf, 0, 1); out.flush(); + if(checkAck(in)!=0){ + System.exit(0); + } + out.close(); + + channel.disconnect(); + session.disconnect(); + + System.exit(0); + } + catch(Exception e){ + System.out.println(e); + try{if(fis!=null)fis.close();}catch(Exception ee){} + } + } + + static int checkAck(InputStream in) throws IOException{ + int b=in.read(); + // b may be 0 for success, + // 1 for error, + // 2 for fatal error, + // -1 + if(b==0) return b; + if(b==-1) return b; + + if(b==1 || b==2){ + StringBuffer sb=new StringBuffer(); + int c; + do { + c=in.read(); + sb.append((char)c); + } + while(c!='\n'); + if(b==1){ // error + System.out.print(sb.toString()); + } + if(b==2){ // fatal error + System.out.print(sb.toString()); + } + } + return b; + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + command+=lfile.substring(lfile.lastIndexOf('/')+1); + } + else{ + command+=lfile; + } + command+="\n"; + out.write(command.getBytes()); out.flush(); + + if(checkAck(in)!=0){ + System.exit(0); + } + + // send a content of lfile + fis=new FileInputStream(lfile); + byte[] buf=new byte[1024]; + while(true){ + int len=fis.read(buf, 0, buf.length); + if(len<=0) break; + out.write(buf, 0, len); out.flush(); + } + fis.close(); + fis=null; + + // send '\0' + buf[0]=0; out.write(buf, 0, 1); out.flush(); + + if(checkAck(in)!=0){ + System.exit(0); + } + + session.disconnect(); + + System.exit(0); + } + catch(Exception e){ + System.out.println(e); + try{if(fis!=null)fis.close();}catch(Exception ee){} + } + } + + static int checkAck(InputStream in) throws IOException{ + int b=in.read(); + // b may be 0 for success, + // 1 for error, + // 2 for fatal error, + // -1 + if(b==0) return b; + if(b==-1) return b; + + if(b==1 || b==2){ + StringBuffer sb=new StringBuffer(); + int c; + do { + c=in.read(); + sb.append((char)c); + } + while(c!='\n'); + if(b==1){ // error + System.out.print(sb.toString()); + } + if(b==2){ // fatal error + System.out.print(sb.toString()); + } + } + return b; + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i'. + * 'help' command will show available command. + * In current implementation, the destination path for 'get' and 'put' + * commands must be a file, not a directory. + * + */ +import com.jcraft.jsch.*; +import java.awt.*; +import javax.swing.*; + +public class Sftp{ + public static void main(String[] arg){ + + try{ + JSch jsch=new JSch(); + + String host=null; + if(arg.length>0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + int port=22; + + Session session=jsch.getSession(user, host, port); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + Channel channel=session.openChannel("sftp"); + channel.connect(); + ChannelSftp c=(ChannelSftp)channel; + + java.io.InputStream in=System.in; + java.io.PrintStream out=System.out; + + java.util.Vector cmds=new java.util.Vector(); + byte[] buf=new byte[1024]; + int i; + String str; + int level=0; + + while(true){ + out.print("sftp> "); + cmds.removeAllElements(); + i=in.read(buf, 0, 1024); + if(i<=0)break; + + i--; + if(i>0 && buf[i-1]==0x0d)i--; + //str=new String(buf, 0, i); + //System.out.println("|"+str+"|"); + int s=0; + for(int ii=0; ii0){ cmds.addElement(new String(buf, s, ii-s)); } + while(ii'7'){foo=-1; break;} + foo<<=3; + foo|=(k-'0'); + } + if(foo==-1)continue; + } + else{ + try{foo=Integer.parseInt((String)cmds.elementAt(1));} + catch(Exception e){continue;} + } + try{ + if(cmd.equals("chgrp")){ c.chgrp(foo, path); } + else if(cmd.equals("chown")){ c.chown(foo, path); } + else if(cmd.equals("chmod")){ c.chmod(foo, path); } + } + catch(SftpException e){ + System.out.println(e.toString()); + } + continue; + } + if(cmd.equals("pwd") || cmd.equals("lpwd")){ + str=(cmd.equals("pwd")?"Remote":"Local"); + str+=" working directory: "; + if(cmd.equals("pwd")) str+=c.pwd(); + else str+=c.lpwd(); + out.println(str); + continue; + } + if(cmd.equals("ls") || cmd.equals("dir")){ + String path="."; + if(cmds.size()==2) path=(String)cmds.elementAt(1); + try{ + java.util.Vector vv=c.ls(path); + if(vv!=null){ + for(int ii=0; ii2) continue; + String p1 = cmds.size()==1 ? ".": (String)cmds.elementAt(1); + SftpStatVFS stat = c.statVFS(p1); + + long size = stat.getSize(); + long used = stat.getUsed(); + long avail = stat.getAvailForNonRoot(); + long root_avail = stat.getAvail(); + long capacity = stat.getCapacity(); + + System.out.println("Size: "+size); + System.out.println("Used: "+used); + System.out.println("Avail: "+avail); + System.out.println("(root): "+root_avail); + System.out.println("%Capacity: "+capacity); + + continue; + } + if(cmd.equals("stat") || cmd.equals("lstat")){ + if(cmds.size()!=2) continue; + String p1=(String)cmds.elementAt(1); + SftpATTRS attrs=null; + try{ + if(cmd.equals("stat")) attrs=c.stat(p1); + else attrs=c.lstat(p1); + } + catch(SftpException e){ + System.out.println(e.toString()); + } + if(attrs!=null){ + out.println(attrs); + } + else{ + } + continue; + } + if(cmd.equals("readlink")){ + if(cmds.size()!=2) continue; + String p1=(String)cmds.elementAt(1); + String filename=null; + try{ + filename=c.readlink(p1); + out.println(filename); + } + catch(SftpException e){ + System.out.println(e.toString()); + } + continue; + } + if(cmd.equals("realpath")){ + if(cmds.size()!=2) continue; + String p1=(String)cmds.elementAt(1); + String filename=null; + try{ + filename=c.realpath(p1); + out.println(filename); + } + catch(SftpException e){ + System.out.println(e.toString()); + } + continue; + } + if(cmd.equals("version")){ + out.println("SFTP protocol version "+c.version()); + continue; + } + if(cmd.equals("help") || cmd.equals("?")){ + out.println(help); + continue; + } + out.println("unimplemented command: "+cmd); + } + session.disconnect(); + } + catch(Exception e){ + System.out.println(e); + } + System.exit(0); + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i=this.count*100/max){ return true; } + percent=this.count*100/max; + + monitor.setNote("Completed "+this.count+"("+percent+"%) out of "+max+"."); + monitor.setProgress((int)this.count); + + return !(monitor.isCanceled()); + } + public void end(){ + monitor.close(); + } + } + + private static String help = +" Available commands:\n"+ +" * means unimplemented command.\n"+ +"cd path Change remote directory to 'path'\n"+ +"lcd path Change local directory to 'path'\n"+ +"chgrp grp path Change group of file 'path' to 'grp'\n"+ +"chmod mode path Change permissions of file 'path' to 'mode'\n"+ +"chown own path Change owner of file 'path' to 'own'\n"+ +"df [path] Display statistics for current directory or\n"+ +" filesystem containing 'path'\n"+ +"help Display this help text\n"+ +"get remote-path [local-path] Download file\n"+ +"get-resume remote-path [local-path] Resume to download file.\n"+ +"get-append remote-path [local-path] Append remote file to local file\n"+ +"hardlink oldpath newpath Hardlink remote file\n"+ +"*lls [ls-options [path]] Display local directory listing\n"+ +"ln oldpath newpath Symlink remote file\n"+ +"*lmkdir path Create local directory\n"+ +"lpwd Print local working directory\n"+ +"ls [path] Display remote directory listing\n"+ +"*lumask umask Set local umask to 'umask'\n"+ +"mkdir path Create remote directory\n"+ +"put local-path [remote-path] Upload file\n"+ +"put-resume local-path [remote-path] Resume to upload file\n"+ +"put-append local-path [remote-path] Append local file to remote file.\n"+ +"pwd Display remote working directory\n"+ +"stat path Display info about path\n"+ +"exit Quit sftp\n"+ +"quit Quit sftp\n"+ +"rename oldpath newpath Rename remote file\n"+ +"rmdir path Remove remote directory\n"+ +"rm path Delete remote file\n"+ +"symlink oldpath newpath Symlink remote file\n"+ +"readlink path Check the target of a symbolic link\n"+ +"realpath path Canonicalize the path\n"+ +"rekey Key re-exchanging\n"+ +"compression level Packet compression will be enabled\n"+ +"version Show SFTP version\n"+ +"? Synonym for help"; +} diff --git a/lab8/jsch-0.1.55/examples/Shell.java b/lab8/jsch-0.1.55/examples/Shell.java new file mode 100644 index 0000000..425cd59 --- /dev/null +++ b/lab8/jsch-0.1.55/examples/Shell.java @@ -0,0 +1,123 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/** + * This program enables you to connect to sshd server and get the shell prompt. + * $ CLASSPATH=.:../build javac Shell.java + * $ CLASSPATH=.:../build java Shell + * You will be asked username, hostname and passwd. + * If everything works fine, you will get the shell prompt. Output may + * be ugly because of lacks of terminal-emulation, but you can issue commands. + * + */ +import com.jcraft.jsch.*; +import java.awt.*; +import javax.swing.*; + +public class Shell{ + public static void main(String[] arg){ + + try{ + JSch jsch=new JSch(); + + //jsch.setKnownHosts("/home/foo/.ssh/known_hosts"); + + String host=null; + if(arg.length>0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String passwd = JOptionPane.showInputDialog("Enter password"); + session.setPassword(passwd); + + UserInfo ui = new MyUserInfo(){ + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + public boolean promptYesNo(String message){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + message, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + // If password is not given before the invocation of Session#connect(), + // implement also following methods, + // * UserInfo#getPassword(), + // * UserInfo#promptPassword(String message) and + // * UIKeyboardInteractive#promptKeyboardInteractive() + + }; + + session.setUserInfo(ui); + + // It must not be recommended, but if you want to skip host-key check, + // invoke following, + // session.setConfig("StrictHostKeyChecking", "no"); + + //session.connect(); + session.connect(30000); // making a connection with timeout. + + Channel channel=session.openChannel("shell"); + + // Enable agent-forwarding. + //((ChannelShell)channel).setAgentForwarding(true); + + channel.setInputStream(System.in); + /* + // a hack for MS-DOS prompt on Windows. + channel.setInputStream(new FilterInputStream(System.in){ + public int read(byte[] b, int off, int len)throws IOException{ + return in.read(b, off, (len>1024?1024:len)); + } + }); + */ + + channel.setOutputStream(System.out); + + /* + // Choose the pty-type "vt102". + ((ChannelShell)channel).setPtyType("vt102"); + */ + + /* + // Set environment variable "LANG" as "ja_JP.eucJP". + ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP"); + */ + + //channel.connect(); + channel.connect(3*1000); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static abstract class MyUserInfo + implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return null; } + public boolean promptYesNo(String str){ return false; } + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return false; } + public boolean promptPassword(String message){ return false; } + public void showMessage(String message){ } + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + return null; + } + } +} diff --git a/lab8/jsch-0.1.55/examples/StreamForwarding.java b/lab8/jsch-0.1.55/examples/StreamForwarding.java new file mode 100644 index 0000000..4a13939 --- /dev/null +++ b/lab8/jsch-0.1.55/examples/StreamForwarding.java @@ -0,0 +1,155 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/** + * This program will demonstrate the stream forwarding. The given Java + * I/O streams will be forwared to the given remote host and port on + * the remote side. It is simmilar to the -L option of ssh command, + * but you don't have to assign and open a local tcp port. + * $ CLASSPATH=.:../build javac StreamForwarding.java + * $ CLASSPATH=.:../build java StreamForwarding + * You will be asked username, hostname, host:hostport and passwd. + * If everything works fine, System.in and System.out streams will be + * forwared to remote port and you can send messages from command line. + * + */ +import com.jcraft.jsch.*; +import java.awt.*; +import javax.swing.*; + +public class StreamForwarding{ + public static void main(String[] arg){ + int port; + + try{ + JSch jsch=new JSch(); + + String host=null; + if(arg.length>0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + String foo=JOptionPane.showInputDialog("Enter host and port", + "host:port"); + host=foo.substring(0, foo.indexOf(':')); + port=Integer.parseInt(foo.substring(foo.indexOf(':')+1)); + + System.out.println("System.{in,out} will be forwarded to "+ + host+":"+port+"."); + Channel channel = session.getStreamForwarder(host, port); + // InputStream in = channel.getInputStream(); + // OutpuStream out = channel.getOutputStream(); + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + channel.connect(1000); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + String subsystem=JOptionPane.showInputDialog("Enter subsystem name", ""); + + Channel channel=session.openChannel("subsystem"); + ((ChannelSubsystem)channel).setSubsystem(subsystem); + ((ChannelSubsystem)channel).setPty(true); + + channel.setInputStream(System.in); + ((ChannelSubsystem)channel).setErrStream(System.err); + channel.setOutputStream(System.out); + channel.connect(); + + /* + channel.setInputStream(System.in); + ((ChannelSubsystem)channel).setErrStream(System.err); + InputStream in = channel.getInputStream(); + channel.connect(); + + byte[] tmp=new byte[1024]; + while(true){ + while(in.available()>0){ + int i=in.read(tmp, 0, 1024); + if(i<0)break; + System.out.print(new String(tmp, 0, i)); + } + if(channel.isClosed()){ + System.out.println("exit-status: "+channel.getExitStatus()); + break; + } + try{Thread.sleep(1000);}catch(Exception ee){} + } + channel.disconnect(); + session.disconnect(); + */ + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ + return false; + } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + String command=JOptionPane.showInputDialog("Enter command, execed with sudo", + "printenv SUDO_USER"); + + String sudo_pass=null; + { + JTextField passwordField=(JTextField)new JPasswordField(8); + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, + ob, + "Enter password for sudo", + JOptionPane.OK_CANCEL_OPTION); + if(result!=JOptionPane.OK_OPTION){ + System.exit(-1); + } + sudo_pass=passwordField.getText(); + } + + Channel channel=session.openChannel("exec"); + + // man sudo + // -S The -S (stdin) option causes sudo to read the password from the + // standard input instead of the terminal device. + // -p The -p (prompt) option allows you to override the default + // password prompt and use a custom one. + ((ChannelExec)channel).setCommand("sudo -S -p '' "+command); + + + InputStream in=channel.getInputStream(); + OutputStream out=channel.getOutputStream(); + ((ChannelExec)channel).setErrStream(System.err); + + channel.connect(); + + out.write((sudo_pass+"\n").getBytes()); + out.flush(); + + byte[] tmp=new byte[1024]; + while(true){ + while(in.available()>0){ + int i=in.read(tmp, 0, 1024); + if(i<0)break; + System.out.print(new String(tmp, 0, i)); + } + if(channel.isClosed()){ + System.out.println("exit-status: "+channel.getExitStatus()); + break; + } + try{Thread.sleep(1000);}catch(Exception ee){} + } + channel.disconnect(); + session.disconnect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ + return false; + } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + // username and passphrase will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return false; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ + return false; + } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ +/* +//System.out.println("promptKeyboardInteractive"); +System.out.println("destination: "+destination); +System.out.println("name: "+name); +System.out.println("instruction: "+instruction); +System.out.println("prompt.length: "+prompt.length); +System.out.println("prompt: "+prompt[0]); +*/ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + // username and passphrase will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return null; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passphrase; + JTextField passphraseField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return passphrase; } + public boolean promptPassphrase(String message){ + Object[] ob={passphraseField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passphrase=passphraseField.getText(); + return true; + } + else{ return false; } + } + public boolean promptPassword(String message){ return true; } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String proxy=JOptionPane.showInputDialog("Enter proxy server", + "hostname:port"); + proxy_host=proxy.substring(0, proxy.indexOf(':')); + proxy_port=Integer.parseInt(proxy.substring(proxy.indexOf(':')+1)); + + session.setProxy(new ProxyHTTP(proxy_host, proxy_port)); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String proxy=JOptionPane.showInputDialog("Enter proxy server", + "hostname:port"); + proxy_host=proxy.substring(0, proxy.indexOf(':')); + proxy_port=Integer.parseInt(proxy.substring(proxy.indexOf(':')+1)); + + session.setProxy(new ProxySOCKS5(proxy_host, proxy_port)); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i0){ + host=arg[0]; + } + else{ + host=JOptionPane.showInputDialog("Enter username@hostname", + System.getProperty("user.name")+ + "@localhost"); + } + String user=host.substring(0, host.indexOf('@')); + host=host.substring(host.indexOf('@')+1); + + Session session=jsch.getSession(user, host, 22); + + String display=JOptionPane.showInputDialog("Please enter display name", + xhost+":"+xport); + xhost=display.substring(0, display.indexOf(':')); + xport=Integer.parseInt(display.substring(display.indexOf(':')+1)); + + session.setX11Host(xhost); + session.setX11Port(xport+6000); + + // username and password will be given via UserInfo interface. + UserInfo ui=new MyUserInfo(); + session.setUserInfo(ui); + session.connect(); + + Channel channel=session.openChannel("shell"); + + channel.setXForwarding(true); + + channel.setInputStream(System.in); + channel.setOutputStream(System.out); + + channel.connect(); + } + catch(Exception e){ + System.out.println(e); + } + } + + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{ + public String getPassword(){ return passwd; } + public boolean promptYesNo(String str){ + Object[] options={ "yes", "no" }; + int foo=JOptionPane.showOptionDialog(null, + str, + "Warning", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + null, options, options[0]); + return foo==0; + } + + String passwd; + JTextField passwordField=(JTextField)new JPasswordField(20); + + public String getPassphrase(){ return null; } + public boolean promptPassphrase(String message){ return true; } + public boolean promptPassword(String message){ + Object[] ob={passwordField}; + int result= + JOptionPane.showConfirmDialog(null, ob, message, + JOptionPane.OK_CANCEL_OPTION); + if(result==JOptionPane.OK_OPTION){ + passwd=passwordField.getText(); + return true; + } + else{ return false; } + } + public void showMessage(String message){ + JOptionPane.showMessageDialog(null, message); + } + final GridBagConstraints gbc = + new GridBagConstraints(0,0,1,1,1,1, + GridBagConstraints.NORTHWEST, + GridBagConstraints.NONE, + new Insets(0,0,0,0),0,0); + private Container panel; + public String[] promptKeyboardInteractive(String destination, + String name, + String instruction, + String[] prompt, + boolean[] echo){ + panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + + gbc.weightx = 1.0; + gbc.gridwidth = GridBagConstraints.REMAINDER; + gbc.gridx = 0; + panel.add(new JLabel(instruction), gbc); + gbc.gridy++; + + gbc.gridwidth = GridBagConstraints.RELATIVE; + + JTextField[] texts=new JTextField[prompt.length]; + for(int i=0; i + + + + + + + + + + + + + \ No newline at end of file diff --git a/lab8/jsch-0.1.55/pom.xml b/lab8/jsch-0.1.55/pom.xml new file mode 100644 index 0000000..ef8743d --- /dev/null +++ b/lab8/jsch-0.1.55/pom.xml @@ -0,0 +1,113 @@ + + 4.0.0 + com.jcraft + jsch + jar + 0.1.55 + JSch + http://www.jcraft.com/jsch/ + JSch is a pure Java implementation of SSH2 + + JCraft,Inc. + http://www.jcraft.com/ + + + scm:git:http://git.jcraft.com/jsch.git + scm:git:http://git.jcraft.com/jsch.git + http://git.jcraft.com/jsch.git + + + + ymnk + Atsuhiko Yamanaka + ymnk at jcraft D0t com + http://github.com/ymnk + JCraft,Inc. + http://www.jcraft.com/ + + architect + developer + + +9 + + + + + Revised BSD + http://www.jcraft.com/jsch/LICENSE.txt + + + + + com.jcraft + jzlib + 1.0.7 + true + + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-javadocs + + jar + + + + + + + + + org.apache.maven.wagon + wagon-ssh-external + 1.0-alpha-5 + + + + + + org.sonatype.oss + oss-parent + 6 + + diff --git a/lab8/jsch-0.1.55/tools/bin/ant b/lab8/jsch-0.1.55/tools/bin/ant new file mode 100644 index 0000000..365f900 --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/ant @@ -0,0 +1,134 @@ +#! /bin/sh + +if [ -f $HOME/.antrc ] ; then + . $HOME/.antrc +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +case "`uname`" in + CYGWIN*) cygwin=true ;; + Darwin*) darwin=true ;; +esac + +if [ -z "$ANT_HOME" ] ; then + # try to find ANT + if [ -d /opt/ant ] ; then + ANT_HOME=/opt/ant + fi + + if [ -d ${HOME}/opt/ant ] ; then + ANT_HOME=${HOME}/opt/ant + fi + + ## resolve links - $0 may be a link to ant's home + PRG=$0 + progname=`basename $0` + + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '.*/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname $PRG`/$link" + fi + done + + ANT_HOME=`dirname "$PRG"`/.. + +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$ANT_HOME" ] && + ANT_HOME=`cygpath --unix "$ANT_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + else + JAVACMD=java + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." + echo " We cannot execute $JAVACMD" + exit +fi + +if [ -n "$CLASSPATH" ] ; then + LOCALCLASSPATH=$CLASSPATH +fi + +# add in the dependency .jar files +DIRLIBS=${ANT_HOME}/lib/*.jar +for i in ${DIRLIBS} +do + # if the directory is empty, then it will return the input string + # this is stupid, so case for it + if [ "$i" != "${DIRLIBS}" ] ; then + if [ -z "$LOCALCLASSPATH" ] ; then + LOCALCLASSPATH=$i + else + LOCALCLASSPATH="$i":$LOCALCLASSPATH + fi + fi +done + +if [ -n "$JAVA_HOME" ] ; then + if [ -f "$JAVA_HOME/lib/tools.jar" ] ; then + LOCALCLASSPATH=$LOCALCLASSPATH:$JAVA_HOME/lib/tools.jar + fi + + if [ -f "$JAVA_HOME/lib/classes.zip" ] ; then + LOCALCLASSPATH=$LOCALCLASSPATH:$JAVA_HOME/lib/classes.zip + fi + + # OSX hack to make Ant work with jikes + if $darwin ; then + OSXHACK="/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Classes" + if [ -d ${OSXHACK} ] ; then + for i in ${OSXHACK}/*.jar + do + JIKESPATH=$JIKESPATH:$i + done + fi + fi + +else + echo "Warning: JAVA_HOME environment variable is not set." + echo " If build fails because sun.* classes could not be found" + echo " you will need to set the JAVA_HOME environment variable" + echo " to the installation directory of java." +fi + +# supply JIKESPATH to Ant as jikes.class.path +if [ -n "$JIKESPATH" ] ; then + if [ -n "$ANT_OPTS" ] ; then + ANT_OPTS="$ANT_OPTS -Djikes.class.path=$JIKESPATH" + else + ANT_OPTS=-Djikes.class.path=$JIKESPATH + fi +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + ANT_HOME=`cygpath --path --windows "$ANT_HOME"` + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + LOCALCLASSPATH=`cygpath --path --windows "$LOCALCLASSPATH"` +fi + +$JAVACMD -classpath "$LOCALCLASSPATH" -Dant.home="${ANT_HOME}" $ANT_OPTS org.apache.tools.ant.Main "$@" diff --git a/lab8/jsch-0.1.55/tools/bin/ant.bat b/lab8/jsch-0.1.55/tools/bin/ant.bat new file mode 100644 index 0000000..81a2835 --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/ant.bat @@ -0,0 +1,110 @@ +@echo off + +if exist "%HOME%\antrc_pre.bat" call "%HOME%\antrc_pre.bat" + +if not "%OS%"=="Windows_NT" goto win9xStart +:winNTStart +@setlocal + +rem %~dp0 is name of current script under NT +set DEFAULT_ANT_HOME=%~dp0 + +rem : operator works similar to make : operator +set DEFAULT_ANT_HOME=%DEFAULT_ANT_HOME%\.. + +if "%ANT_HOME%"=="" set ANT_HOME=%DEFAULT_ANT_HOME% +set DEFAULT_ANT_HOME= + +rem Need to check if we are using the 4NT shell... +if "%eval[2+2]" == "4" goto setup4NT + +rem On NT/2K grab all arguments at once +set ANT_CMD_LINE_ARGS=%* +goto doneStart + +:setup4NT +set ANT_CMD_LINE_ARGS=%$ +goto doneStart + +:win9xStart +rem Slurp the command line arguments. This loop allows for an unlimited number of +rem agruments (up to the command line limit, anyway). + +set ANT_CMD_LINE_ARGS= + +:setupArgs +if %1a==a goto doneStart +set ANT_CMD_LINE_ARGS=%ANT_CMD_LINE_ARGS% %1 +shift +goto setupArgs + +:doneStart +rem This label provides a place for the argument list loop to break out +rem and for NT handling to skip to. + +rem find ANT_HOME +if not "%ANT_HOME%"=="" goto checkJava + +rem check for ant in Program Files on system drive +if not exist "%SystemDrive%\Program Files\ant" goto checkSystemDrive +set ANT_HOME=%SystemDrive%\Program Files\ant +goto checkJava + +:checkSystemDrive +rem check for ant in root directory of system drive +if not exist %SystemDrive%\ant\nul goto checkCDrive +set ANT_HOME=%SystemDrive%\ant +goto checkJava + +:checkCDrive +rem check for ant in C:\ant for Win9X users +if not exist C:\ant\nul goto noAntHome +set ANT_HOME=C:\ant +goto checkJava + +:noAntHome +echo ANT_HOME is not set and ant could not be located. Please set ANT_HOME. +goto end + +:checkJava +set _JAVACMD=%JAVACMD% +set LOCALCLASSPATH=%CLASSPATH% +for %%i in ("%ANT_HOME%\lib\*.jar") do call "%ANT_HOME%\bin\lcp.bat" %%i + +if "%JAVA_HOME%" == "" goto noJavaHome +if "%_JAVACMD%" == "" set _JAVACMD=%JAVA_HOME%\bin\java +if exist "%JAVA_HOME%\lib\tools.jar" call "%ANT_HOME%\bin\lcp.bat" %JAVA_HOME%\lib\tools.jar +if exist "%JAVA_HOME%\lib\classes.zip" call "%ANT_HOME%\bin\lcp.bat" %JAVA_HOME%\lib\classes.zip +goto checkJikes + +:noJavaHome +if "%_JAVACMD%" == "" set _JAVACMD=java +echo. +echo Warning: JAVA_HOME environment variable is not set. +echo If build fails because sun.* classes could not be found +echo you will need to set the JAVA_HOME environment variable +echo to the installation directory of java. +echo. + +:checkJikes +if not "%JIKESPATH%" == "" goto runAntWithJikes + +:runAnt +"%_JAVACMD%" -classpath "%LOCALCLASSPATH%" -Dant.home="%ANT_HOME%" %ANT_OPTS% org.apache.tools.ant.Main %ANT_CMD_LINE_ARGS% +goto end + +:runAntWithJikes +"%_JAVACMD%" -classpath "%LOCALCLASSPATH%" -Dant.home="%ANT_HOME%" -Djikes.class.path="%JIKESPATH%" %ANT_OPTS% org.apache.tools.ant.Main %ANT_CMD_LINE_ARGS% + +:end +set LOCALCLASSPATH= +set _JAVACMD= +set ANT_CMD_LINE_ARGS= + +if not "%OS%"=="Windows_NT" goto mainEnd +:winNTend +@endlocal + +:mainEnd +if exist "%HOME%\antrc_post.bat" call "%HOME%\antrc_post.bat" + diff --git a/lab8/jsch-0.1.55/tools/bin/antRun b/lab8/jsch-0.1.55/tools/bin/antRun new file mode 100644 index 0000000..f0a18f1 --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/antRun @@ -0,0 +1,9 @@ +#! /bin/sh + +# Args: DIR command +cd "$1" +CMD="$2" +shift +shift + +exec $CMD "$@" diff --git a/lab8/jsch-0.1.55/tools/bin/antRun.bat b/lab8/jsch-0.1.55/tools/bin/antRun.bat new file mode 100644 index 0000000..9168932 --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/antRun.bat @@ -0,0 +1,20 @@ +@echo off + +rem Change drive and directory to %1 (Win9X only for NT/2K use "cd /d") +cd %1 +%1\ +set ANT_RUN_CMD=%2 +shift +shift + +set PARAMS= +:loop +if ""%1 == "" goto runCommand +set PARAMS=%PARAMS% %1 +shift +goto loop + +:runCommand +rem echo %ANT_RUN_CMD% %PARAMS% +%ANT_RUN_CMD% %PARAMS% + diff --git a/lab8/jsch-0.1.55/tools/bin/lcp.bat b/lab8/jsch-0.1.55/tools/bin/lcp.bat new file mode 100644 index 0000000..2c7e276 --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/lcp.bat @@ -0,0 +1,9 @@ +set _CLASSPATHCOMPONENT=%1 +:argCheck +if %2a==a goto gotAllArgs +shift +set _CLASSPATHCOMPONENT=%_CLASSPATHCOMPONENT% %1 +goto argCheck +:gotAllArgs +set LOCALCLASSPATH=%_CLASSPATHCOMPONENT%;%LOCALCLASSPATH% + diff --git a/lab8/jsch-0.1.55/tools/bin/runant.pl b/lab8/jsch-0.1.55/tools/bin/runant.pl new file mode 100644 index 0000000..a2cc523 --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/runant.pl @@ -0,0 +1,131 @@ +#!/usr/bin/perl +####################################################################### +# +# runant.pl +# +# wrapper script for invoking ant in a platform with Perl installed +# this may include cgi-bin invocation, which is considered somewhat daft. +# (slo: that should be a separate file which can be derived from this +# and returns the XML formatted output) +# +# the code is not totally portable due to classpath and directory splitting +# issues. oops. (NB, use File::Spec::Functions will help and the code is +# structured for the catfile() call, but because of perl version funnies +# the code is not included. +# +# created: 2000-8-24 +# last modified: 2000-8-24 +# author: Steve Loughran steve_l@sourceforge.net +####################################################################### +# +# Assumptions: +# +# - the "java" executable/script is on the command path +# - ANT_HOME has been set +# - target platform uses ":" as classpath separator or perl indicates it is dos/win32 +# - target platform uses "/" as directory separator. + +#be fussy about variables +use strict; + +#platform specifics (disabled) +#use File::Spec::Functions; + +#turn warnings on during dev; generates a few spurious uninitialised var access warnings +#use warnings; + +#and set $debug to 1 to turn on trace info +my $debug=0; + +####################################################################### +# +# check to make sure environment is setup +# + +my $HOME = $ENV{ANT_HOME}; +if ($HOME eq "") + { + die "\n\nANT_HOME *MUST* be set!\n\n"; + } + +my $JAVACMD = $ENV{JAVACMD}; +$JAVACMD = "java" if $JAVACMD eq ""; + +#ISSUE: what java wants to split up classpath varies from platform to platform +#and perl is not too hot at hinting which box it is on. +#here I assume ":" 'cept on win32 and dos. Add extra tests here as needed. +my $s=":"; +if(($^O eq "MSWin32") || ($^O eq "dos")) + { + $s=";"; + } + +#build up standard classpath +my $localpath=$ENV{CLASSPATH}; +if ($localpath eq "") + { + print "warning: no initial classpath\n" if ($debug); + $localpath=""; + } + +#add jar files. I am sure there is a perl one liner to do this. +my $jarpattern="$HOME/lib/*.jar"; +my @jarfiles =glob($jarpattern); +print "jarfiles=@jarfiles\n" if ($debug); +my $jar; +foreach $jar (@jarfiles ) + { + $localpath.="$s$jar"; + } + +#if Java home is defined, look for tools.jar & classes.zip and add to classpath +my $JAVA_HOME = $ENV{JAVA_HOME}; +if ($JAVA_HOME ne "") + { + my $tools="$JAVA_HOME/lib/tools.jar"; + if (-e "$tools") + { + $localpath .= "$s$tools"; + } + my $classes="$JAVA_HOME/lib/classes.zip"; + if (-e $classes) + { + $localpath .= "$s$classes"; + } + } +else + { + print "\n\nWarning: JAVA_HOME environment variable is not set.\n". + "If the build fails because sun.* classes could not be found\n". + "you will need to set the JAVA_HOME environment variable\n". + "to the installation directory of java\n"; + } + +#jikes +my @ANT_OPTS=split $ENV{ANT_OPTS}; +if($ENV{JIKESPATH} ne "") + { + push @ANT_OPTS, "-Djikes.class.path=$ENV{JIKESPATH}"; + } + +#construct arguments to java + +my @ARGS; +push @ARGS, "-classpath", "$localpath", "-Dant.home=$HOME"; +push @ARGS, @ANT_OPTS; +push @ARGS, "org.apache.tools.ant.Main"; +push @ARGS, @ARGV; + +print "\n $JAVACMD @ARGS\n\n" if ($debug); + +my $returnValue = system $JAVACMD, @ARGS; +if ($returnValue eq 0) + { + exit 0; + } +else + { + # only 0 and 1 are widely recognized as exit values + # so change the exit value to 1 + exit 1; + } diff --git a/lab8/jsch-0.1.55/tools/bin/runant.py b/lab8/jsch-0.1.55/tools/bin/runant.py new file mode 100644 index 0000000..d5e200c --- /dev/null +++ b/lab8/jsch-0.1.55/tools/bin/runant.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +""" + + runant.py + + This script is a translation of the runant.pl written by Steve Loughran. + It runs ant with/out arguments, it should be quite portable (thanks to + the python os library) + This script has been tested with Python2.0/Win2K + + created: 2001-04-11 + author: Pierre Dittgen pierre.dittgen@criltelecom.com + + Assumptions: + + - the "java" executable/script is on the command path + - ANT_HOME has been set +""" +import os, os.path, string, sys + +# Change it to 1 to get extra debug information +debug = 0 + +####################################################################### +# +# check to make sure environment is setup +# +if not os.environ.has_key('ANT_HOME'): + print '\n\nANT_HOME *MUST* be set!\n\n' + sys.exit(1) +else: + ANT_HOME = os.environ['ANT_HOME'] + +if not os.environ.has_key('JAVACMD'): + JAVACMD = 'java' +else: + JAVACMD = os.environ['JAVACMD'] + +# Sets the separator char for CLASSPATH +SEPARATOR = ':' +if os.name == 'dos' or os.name == 'nt': + SEPARATOR = ';' + +# Build up standard classpath +localpath = '' +if os.environ.has_key('CLASSPATH'): + localpath = os.environ['CLASSPATH'] +else: + if debug: + print 'Warning: no initial classpath\n' + +# Add jar files +LIBDIR = os.path.join(ANT_HOME, 'lib') +jarfiles = [] +for file in os.listdir(LIBDIR): + if file[-4:] == '.jar': + jarfiles.append(os.path.join(LIBDIR,file)) +if debug: + print 'Jar files:' + for jar in jarfiles: + print jar +localpath = localpath + SEPARATOR + string.join(jarfiles, SEPARATOR) + +# If JAVA_HOME is defined, look for tools.jar & classes.zip +# and add to classpath +if os.environ.has_key('JAVA_HOME') and os.environ['JAVA_HOME'] != '': + JAVA_HOME = os.environ['JAVA_HOME'] + TOOLS = os.path.join(JAVA_HOME, os.path.join('lib', 'tools.jar')) + if os.path.exists(TOOLS): + localpath = localpath + SEPARATOR + TOOLS + CLASSES = os.path.join(JAVA_HOME, os.path.join('lib', 'classes.zip')) + if os.path.exists(CLASSES): + localpath = localpath + SEPARATOR + CLASSES +else: + print '\n\nWarning: JAVA_HOME environment variable is not set.\n', \ + 'If the build fails because sun.* classes could not be found\n', \ + 'you will need to set the JAVA_HOME environment variable\n', \ + 'to the installation directory of java\n' + +# Jikes +ANT_OPTS = [] +if os.environ.has_key('ANT_OPTS'): + ANT_OPTS = string.split(os.environ['ANT_OPTS']) +if os.environ.has_key('JIKESPATH'): + ANT_OPTS.append('-Djikes.class.path=' + os.environ['JIKESPATH']) + +# Builds the commandline +cmdline = '%s -classpath %s -Dant.home=%s %s org.apache.tools.ant.Main %s' \ + % (JAVACMD, localpath, ANT_HOME, string.join(ANT_OPTS,' '), \ + string.join(sys.argv[1:], ' ')) + +if debug: + print '\n%s\n\n' % (cmdline) + +# Run the biniou! +os.system(cmdline) diff --git a/lab9/Movies.sql b/lab9/Movies.sql new file mode 100644 index 0000000..8c69bf6 --- /dev/null +++ b/lab9/Movies.sql @@ -0,0 +1,38 @@ +drop table persons; +/ +drop table movies; +/ +drop table movie_actos; +/ + +create table persons( + id integer generated always as identity (start with 1 increment by 1) not null, + name varchar2(100) not null, + constraint "pk1" primary key (id) +) +/ + +create table movies( + id integer generated always as identity (start with 1 increment by 1) not null, + name varchar2(100) not null, + director_id integer not null, + constraint "fk1" foreign key (director_id) references persons on delete cascade, + constraint "pk2" primary key (id) + ) +/ + +create table movie_actors( + movie_id integer not null, + actor_id integer not null, + constraint "fk2" foreign key (movie_id) references movies(id) on delete cascade, + constraint "fk3" foreign key (actor_id) references persons(id) on delete cascade, + constraint "pk3" primary key (movie_id, actor_id) +) +/ +commit; + + +select * from persons; + + + diff --git a/lab9/populate.sql b/lab9/populate.sql new file mode 100644 index 0000000..20dbec1 --- /dev/null +++ b/lab9/populate.sql @@ -0,0 +1,11 @@ +insert into persons (name) values ('Al Pacino'); +insert into persons (name) values ('Marlon Brando'); + +insert into movies(name, director_id) values ('The godfather', 1); + +insert into movie_actors(movie_id, actor_id) values (1, 2); +insert into movie_actors(movie_id, actor_id) values (1, 3); + +select * from movie_actors; +select * from persons; +select * from movies; \ No newline at end of file diff --git a/lab9/src/lab9/DAO/MovieController.java b/lab9/src/lab9/DAO/MovieController.java new file mode 100644 index 0000000..d86d612 --- /dev/null +++ b/lab9/src/lab9/DAO/MovieController.java @@ -0,0 +1,53 @@ +package lab9.DAO; + +import lab9.Database; +import model.Actor; + +import java.sql.*; +import java.util.ArrayList; + +public class MovieController { + public void create(String name, int directorId) throws SQLException { + Connection con = Database.getConnection(); + try (PreparedStatement pstmt = con.prepareStatement("insert into movies (name, director_id) values (?, ?)")) { + pstmt.setString(1, name); + pstmt.setInt(2, directorId); + pstmt.executeUpdate(); + pstmt.close(); + Database.commit(); + } + } + public Integer findByName(String name) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select id from movies where name like '" + name + "'")) { + stmt.close(); + return rs.next() ? rs.getInt(1) : null; + } + } + public String findById(int id) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select name from movies where id like '" + id + "'")) { + return rs.next() ? rs.getString(1) : null; + } + } + + public String findByDirector(int directorId) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select name from movies where director_id like '" + directorId + "'")) { + return rs.next() ? rs.getString(1) : null; + } + } + + public ResultSet findAll() throws SQLException{ + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from movies")){ + return rs; + } + } + + +} diff --git a/lab9/src/lab9/DAO/PersonController.java b/lab9/src/lab9/DAO/PersonController.java new file mode 100644 index 0000000..20ab97a --- /dev/null +++ b/lab9/src/lab9/DAO/PersonController.java @@ -0,0 +1,44 @@ +package lab9.DAO; + +import lab9.Database; +import java.sql.*; + +public class PersonController { + + public void create(String name) throws SQLException { + try (Connection con = Database.getConnection()) { + try (PreparedStatement pstmt = con.prepareStatement("insert into persons (name) values (?)")) { + pstmt.setString(1, name); + pstmt.executeUpdate(); + pstmt.close(); + Database.commit(); + } + } + } + public Integer findByName(String name) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select id from persons where name like '" + name + "'")) { + stmt.close(); + return rs.next() ? rs.getInt(1) : null; + + } + } + public String findById(int id) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select name from persons where id like '" + id + "'")) { + return rs.next() ? rs.getString(1) : null; + } + } + public void findAll() throws SQLException{ + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from persons")){ + while (rs.next()){ + System.out.println(rs.getInt(1)+" "+rs.getString(2)); + } + } + } + +} diff --git a/lab9/src/lab9/Database.java b/lab9/src/lab9/Database.java new file mode 100644 index 0000000..f90bb97 --- /dev/null +++ b/lab9/src/lab9/Database.java @@ -0,0 +1,74 @@ +package lab9; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class Database { + private static Database db = new Database(); + private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe"; + private static final String USER = "c##dba"; + private static final String PASSWORD = "sql"; + private static Connection connection = null; + + public Database() { } + + public static Database getInstance() { + return db; + } + + public static Connection getConnection() { + if (connection == null) { + createConnection(); + } + return connection; + } + + private static void createConnection() { + + try { + DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); + Class.forName("oracle.jdbc.driver.OracleDriver"); + connection = DriverManager.getConnection(URL, USER, PASSWORD); + } catch (SQLException ex) { + for (Throwable e : ex) + if (e instanceof SQLException) { + SQLException sqlException = (SQLException) e; + System.out.println("sqlState : " + sqlException.getSQLState()); + System.out.println("error code : " + sqlException.getErrorCode()); + System.out.println("message : " + sqlException.getMessage()); + Throwable t = ex.getCause(); + while (t != null) { + System.out.println("Cause : " + t); + t = t.getCause(); + } + } + } catch (ClassNotFoundException e) { + System.out.println(e.getMessage()); + } + } + + public static void closeConnection() { + try { + connection.close(); + } catch (SQLException e) { + System.out.println(e.getMessage()); + } + } + + public static void rollback() { + try { + connection.rollback(); + } catch (SQLException e) { + System.out.println(e.getMessage()); + } + } + + public static void commit() { + try { + connection.commit(); + } catch (SQLException e) { + System.out.println(e.getMessage()); + } + } +} \ No newline at end of file diff --git a/lab9/src/lab9/Main.java b/lab9/src/lab9/Main.java new file mode 100644 index 0000000..f110d8f --- /dev/null +++ b/lab9/src/lab9/Main.java @@ -0,0 +1,48 @@ +package lab9; + +import lab9.DAO.MovieController; +import lab9.DAO.PersonController; +import model.Actor; +import model.Director; +import model.Movie; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; + +public class Main { + public static void main(String[] args) { + try { + PersonController persons = new PersonController(); + MovieController movies = new MovieController(); + + Director director1 = new Director("Francis Ford Coppola", 1); + Actor actor1 = new Actor("Al Pacino"); + Actor actor2 = new Actor("Marlon Brando"); + Movie movie1 = new Movie("The godfather"); + movie1.setDirector(director1); + movie1.addActor(actor1); + movie1.addActor(actor2); + + //persons.create("Francis Ford Coppola"); + persons.create(director1.getName()); + persons.create(actor2.getName()); + persons.create(actor1.getName()); + //Database.commit(); + + movies.create(movie1.getName(), persons.findByName("Coppola")); + //Database.commit(); + + director1.getMovies(director1.getName()); + + + + //Database.closeConnection(); + } catch (SQLException e) { + System.err.println(e); + //Database.rollback(); + } + + + } +} diff --git a/lab9/src/model/Actor.java b/lab9/src/model/Actor.java new file mode 100644 index 0000000..d8442cf --- /dev/null +++ b/lab9/src/model/Actor.java @@ -0,0 +1,33 @@ +package model; + +import lab9.Database; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; + +public class Actor extends Person { + ArrayList moviesStarred = new ArrayList<>(); + public Actor(String name){ + this.name = name; + } + + public void addMovie(Movie m){ + moviesStarred.add(m); + } + + public String getMovieStarred(String movieStarred) { + return movieStarred; + } + + public ResultSet getMovies(String name) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select m.name from persons p, movie_actors a, movies m" + + " where a.actor_id = p.id and m.id = a.movie_id and p.name like '" + name + "'")){ + return rs; + } + } +} diff --git a/lab9/src/model/Director.java b/lab9/src/model/Director.java new file mode 100644 index 0000000..dcdb7d7 --- /dev/null +++ b/lab9/src/model/Director.java @@ -0,0 +1,40 @@ +package model; + +import lab9.Database; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; + +public class Director extends Person { + int directorId; + ArrayList moviesDirected = new ArrayList<>(); + public Director(String name, int directorId){ + this.name = name; + this.directorId = directorId; + } + + public ArrayList getMovie(){ + return moviesDirected; + } + + public void addMovie(Movie m){ + moviesDirected.add(m); + } + + public int getId(){ + return directorId; + } + + public ResultSet getMovies(String name) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select m.name from persons p, movies m" + + " where m.director_id = p.id and p.name like '" + name + "'")){ + return rs; + } + } + +} diff --git a/lab9/src/model/Movie.java b/lab9/src/model/Movie.java new file mode 100644 index 0000000..7eb3592 --- /dev/null +++ b/lab9/src/model/Movie.java @@ -0,0 +1,49 @@ +package model; + +import lab9.Database; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; + +public class Movie { + String name; + Director director; + ArrayList actors = new ArrayList<>(); + + public Movie(String name){ + this.name = name; + } + + public void setDirector(Director director) { + this.director = director; + } + + public void setActors(ArrayList actors){ + this.actors = actors; + } + + public void addActor(Actor a){ + actors.add(a); + } + + public ArrayList getActors(){ + return actors; + } + + public String getName(){ + return name; + } + + public ResultSet getActors(String name) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select p.name from persons p, movie_actors a, movies m" + + " where a.actor_id = p.id and m.id = a.movie_id and m.name like '" + name + "'")){ + return rs; + } + } + +} diff --git a/lab9/src/model/MovieList.java b/lab9/src/model/MovieList.java new file mode 100644 index 0000000..226ca98 --- /dev/null +++ b/lab9/src/model/MovieList.java @@ -0,0 +1,33 @@ +package model; + +import lab9.Database; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; + +public class MovieList { + String title; + ArrayList movieList = new ArrayList<>(); + + public MovieList(String title){ + this.title = title; + } + + public void addMovie(Movie m){ + movieList.add(m); + } + + public ArrayList getList(){ + return movieList; + } + public String orderedMovies(int id) throws SQLException { + Connection con = Database.getConnection(); + try (Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select name from movies where id like '" + id + "' order by id")) { + return rs.next() ? rs.getString(1) : null; + } + } +} diff --git a/lab9/src/model/Person.java b/lab9/src/model/Person.java new file mode 100644 index 0000000..f2e084b --- /dev/null +++ b/lab9/src/model/Person.java @@ -0,0 +1,13 @@ +package model; + +public abstract class Person{ + String name; + public String getName(){ + return name; + } + + public void setName(String name){ + this.name = name; + } + +}