file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
113420_1 | package be.annelyse.year2019;
import be.annelyse.util.Color;
import be.annelyse.util.Coordinate2D;
import be.annelyse.util.Direction;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class Day11 {
private static LinkedBlockingQueue<Long> inputPaintRobot = new LinkedBlockingQueue<>();
private static LinkedBlockingQueue<Long> outputPaintRobot = new LinkedBlockingQueue<>();
private static List<Pannel> paintedPannels;
public static void main(String[] args) {
// System.out.println("********************************************************************");
// System.out.println("The testSolution is: " + solveWithoutIntComputer("Day11_test1"));
System.out.println("********************************************************************");
System.out.println("The solution with my computer is is: " + solveA("Day11"));
}
private static int solveWithoutIntComputer(String inputFileName) {
List<Long> input = getInput(inputFileName);
LinkedBlockingQueue<Long> testInput = new LinkedBlockingQueue<>(input);
PaintRobot testPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), testInput, outputPaintRobot);
Thread paintRobotThread = new Thread(testPaintRobot);
paintRobotThread.start();
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
testPaintRobot.setActive(false); //todo ... deze komt te laat!!!! deze zou moeten komen voor hij alweer wacht op een nieuwe input. Misschien hier te implementeren als de laatste input wordt genomen ofzo???
try {
paintRobotThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return testPaintRobot.getPaintedPannels().size();
}
private static int solveA(String inputFileName) {
PaintRobot ourPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), inputPaintRobot, outputPaintRobot);
IntCodeComputer2 intCodeComputer2 = new IntCodeComputer2(getInput(inputFileName), outputPaintRobot, inputPaintRobot);
Thread paintRobotThread = new Thread(ourPaintRobot);
paintRobotThread.start();
Thread intComputerThread = new Thread(intCodeComputer2);
intComputerThread.start();
try {
intComputerThread.join();
paintedPannels = ourPaintRobot.getPaintedPannels();
ourPaintRobot.setActive(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
printPaintedPannels(paintedPannels);
return paintedPannels.size();
}
static List<Long> getInput(String inputFileName) {
String input = null;
try {
input = Files.readString(Paths.get("src/main/resources/input/year2019", inputFileName));
} catch (IOException e) {
e.printStackTrace();
}
return Arrays.stream(input.split(","))
.map(Long::parseLong)
.collect(Collectors.toList());
}
static String[][] printPaintedPannels(List<Pannel> paintedPannels) {
int xMin = paintedPannels.stream().map(Coordinate2D::getX).min(Integer::compareTo).get();
int xMax = paintedPannels.stream().map(Coordinate2D::getX).max(Integer::compareTo).get();
int yMin = paintedPannels.stream().map(Coordinate2D::getY).min(Integer::compareTo).get();
int yMax = paintedPannels.stream().map(Coordinate2D::getY).max(Integer::compareTo).get();
System.out.println("xMin: " + xMin + " xMax: " + xMax + " yMin: " + yMin + " yMax: " + yMax);
int columnCount = xMax - xMin + 1;
int rowCount = yMax - yMin + 1;
String[][] print = new String[columnCount][rowCount];
for (int y = rowCount-1; y >= 0; y--){
System.out.println();
for (int x = 0; x < columnCount; x++){
int indexOfPannel = paintedPannels.indexOf(new Pannel(x+xMin,y+yMin));
if(indexOfPannel < 0){
print[x][y] = " ";
} else {
Color pannelColor = paintedPannels.get(indexOfPannel).getColor();
print[x][y] = pannelColor.toString();
}
System.out.print(print[x][y]);
}
}
return print;
}
}
| AnnelyseBe/AdventOfCode2019 | src/main/java/be/annelyse/year2019/Day11.java | 1,352 | //todo ... deze komt te laat!!!! deze zou moeten komen voor hij alweer wacht op een nieuwe input. Misschien hier te implementeren als de laatste input wordt genomen ofzo??? | line_comment | nl | package be.annelyse.year2019;
import be.annelyse.util.Color;
import be.annelyse.util.Coordinate2D;
import be.annelyse.util.Direction;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class Day11 {
private static LinkedBlockingQueue<Long> inputPaintRobot = new LinkedBlockingQueue<>();
private static LinkedBlockingQueue<Long> outputPaintRobot = new LinkedBlockingQueue<>();
private static List<Pannel> paintedPannels;
public static void main(String[] args) {
// System.out.println("********************************************************************");
// System.out.println("The testSolution is: " + solveWithoutIntComputer("Day11_test1"));
System.out.println("********************************************************************");
System.out.println("The solution with my computer is is: " + solveA("Day11"));
}
private static int solveWithoutIntComputer(String inputFileName) {
List<Long> input = getInput(inputFileName);
LinkedBlockingQueue<Long> testInput = new LinkedBlockingQueue<>(input);
PaintRobot testPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), testInput, outputPaintRobot);
Thread paintRobotThread = new Thread(testPaintRobot);
paintRobotThread.start();
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
testPaintRobot.setActive(false); //todo ...<SUF>
try {
paintRobotThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return testPaintRobot.getPaintedPannels().size();
}
private static int solveA(String inputFileName) {
PaintRobot ourPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), inputPaintRobot, outputPaintRobot);
IntCodeComputer2 intCodeComputer2 = new IntCodeComputer2(getInput(inputFileName), outputPaintRobot, inputPaintRobot);
Thread paintRobotThread = new Thread(ourPaintRobot);
paintRobotThread.start();
Thread intComputerThread = new Thread(intCodeComputer2);
intComputerThread.start();
try {
intComputerThread.join();
paintedPannels = ourPaintRobot.getPaintedPannels();
ourPaintRobot.setActive(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
printPaintedPannels(paintedPannels);
return paintedPannels.size();
}
static List<Long> getInput(String inputFileName) {
String input = null;
try {
input = Files.readString(Paths.get("src/main/resources/input/year2019", inputFileName));
} catch (IOException e) {
e.printStackTrace();
}
return Arrays.stream(input.split(","))
.map(Long::parseLong)
.collect(Collectors.toList());
}
static String[][] printPaintedPannels(List<Pannel> paintedPannels) {
int xMin = paintedPannels.stream().map(Coordinate2D::getX).min(Integer::compareTo).get();
int xMax = paintedPannels.stream().map(Coordinate2D::getX).max(Integer::compareTo).get();
int yMin = paintedPannels.stream().map(Coordinate2D::getY).min(Integer::compareTo).get();
int yMax = paintedPannels.stream().map(Coordinate2D::getY).max(Integer::compareTo).get();
System.out.println("xMin: " + xMin + " xMax: " + xMax + " yMin: " + yMin + " yMax: " + yMax);
int columnCount = xMax - xMin + 1;
int rowCount = yMax - yMin + 1;
String[][] print = new String[columnCount][rowCount];
for (int y = rowCount-1; y >= 0; y--){
System.out.println();
for (int x = 0; x < columnCount; x++){
int indexOfPannel = paintedPannels.indexOf(new Pannel(x+xMin,y+yMin));
if(indexOfPannel < 0){
print[x][y] = " ";
} else {
Color pannelColor = paintedPannels.get(indexOfPannel).getColor();
print[x][y] = pannelColor.toString();
}
System.out.print(print[x][y]);
}
}
return print;
}
}
|
84745_2 | package be.annelyse.budget;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
@SpringBootApplication
// @Configuration (beans definiëren)
// @ComponentScan (zoekt beans in pakket en subpakketten waar deze file in zit)
// @EnableAutoConfiguration geldt voor het pakket en subpakketten waar deze file in zit
public class BudgetApplication {
public static void main(String[] args) {
//configuratie van de applicatie (context)
SpringApplication.run(BudgetApplication.class, args);
}
//todo diy is een test vanuit thymeleaf voorbeeld. komt er een internationalisation message ding bij resoures???
/*
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}
}
| AnnelyseBe/MyBudget_repo3 | src/main/java/be/annelyse/budget/BudgetApplication.java | 287 | // @EnableAutoConfiguration geldt voor het pakket en subpakketten waar deze file in zit | line_comment | nl | package be.annelyse.budget;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
@SpringBootApplication
// @Configuration (beans definiëren)
// @ComponentScan (zoekt beans in pakket en subpakketten waar deze file in zit)
// @EnableAutoConfiguration geldt<SUF>
public class BudgetApplication {
public static void main(String[] args) {
//configuratie van de applicatie (context)
SpringApplication.run(BudgetApplication.class, args);
}
//todo diy is een test vanuit thymeleaf voorbeeld. komt er een internationalisation message ding bij resoures???
/*
* Message externalization/internationalization
*/
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}
}
|
169967_1 | package com.nhlstenden.amazonsimulatie.views;
import com.nhlstenden.amazonsimulatie.base.Command;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;
/*
* Deze class is de standaard websocketview. De class is een andere variant
* van een gewone view. Een "normale" view is meestal een schermpje op de PC,
* maar in dit geval is het wat de gebruiker ziet in de browser. Het behandelen
* van een webpagina als view zie je vaker wanneer je te maken hebt met
* serversystemen. In deze class wordt de WebSocketSession van de client opgeslagen,
* waarmee de view class kan communiceren met de browser.
*/
public class WebAppView implements View {
private WebSocketSession sesion;
private Command onClose;
public WebAppView(WebSocketSession sesion) {
this.sesion = sesion;
}
/*
* Deze methode wordt aangroepen vanuit de controller wanneer er een update voor
* de views is. Op elke view wordt dan de update methode aangroepen, welke een
* JSON pakketje maakt van de informatie die verstuurd moet worden. Deze JSON
* wordt naar de browser verstuurd, welke de informatie weer afhandeld.
*/
@Override
public void update(BinaryMessage bin) {
try {
if (this.sesion.isOpen()) {
this.sesion.sendMessage(bin);
} else {
this.onClose.execute();
}
} catch (Exception e) {
this.onClose.execute();
}
}
@Override
public void onViewClose(Command command) {
onClose = command;
}
}
| AnotherFoxGuy/AzwSimulatie | src/main/java/com/nhlstenden/amazonsimulatie/views/WebAppView.java | 449 | /*
* Deze methode wordt aangroepen vanuit de controller wanneer er een update voor
* de views is. Op elke view wordt dan de update methode aangroepen, welke een
* JSON pakketje maakt van de informatie die verstuurd moet worden. Deze JSON
* wordt naar de browser verstuurd, welke de informatie weer afhandeld.
*/ | block_comment | nl | package com.nhlstenden.amazonsimulatie.views;
import com.nhlstenden.amazonsimulatie.base.Command;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;
/*
* Deze class is de standaard websocketview. De class is een andere variant
* van een gewone view. Een "normale" view is meestal een schermpje op de PC,
* maar in dit geval is het wat de gebruiker ziet in de browser. Het behandelen
* van een webpagina als view zie je vaker wanneer je te maken hebt met
* serversystemen. In deze class wordt de WebSocketSession van de client opgeslagen,
* waarmee de view class kan communiceren met de browser.
*/
public class WebAppView implements View {
private WebSocketSession sesion;
private Command onClose;
public WebAppView(WebSocketSession sesion) {
this.sesion = sesion;
}
/*
* Deze methode wordt<SUF>*/
@Override
public void update(BinaryMessage bin) {
try {
if (this.sesion.isOpen()) {
this.sesion.sendMessage(bin);
} else {
this.onClose.execute();
}
} catch (Exception e) {
this.onClose.execute();
}
}
@Override
public void onViewClose(Command command) {
onClose = command;
}
}
|
13749_39 | package ownCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Math.toIntExact;
public class Game {
public String player1Name;
public String player2Name;
public String boardstring;
public ArrayList<String> boardHistory = new ArrayList<String>();
public int DIM;
public int player1ColorIndex;
public int player2ColorIndex;
public int gameID;
public int currentPlayer;
private int firstAnswer = -10;//0 is een legit optie, dus kunnen niet een 'lege' int maken. vandaar heb ik het op -10 gezet
private int secondAnswer = -10;
public boolean onePass = false;
public boolean rematch = false;
public boolean twoAnswers = false;
public ClientHandler player1CH;
public ClientHandler player2CH;
public Board board;
private HashMap<Integer, Intersection> sameColorNeightbours = new HashMap<Integer, Intersection>();
private List<Intersection> notSameColorNeightbours = new ArrayList<Intersection>();//empty zit hier ook in
public Game(String player1Name, int player1ColorIndex, String player2Name, int DIM, int gameID) {
this.player1Name = player1Name;
this.player2Name = player2Name;
this.player1ColorIndex = player1ColorIndex;
if(player1ColorIndex == 1) {
player2ColorIndex = 2;
} else if(player1ColorIndex == 2) {
player2ColorIndex = 1;
} else {
print("Something goes wrong with ginving players their color");
}
this.DIM = DIM;
this.boardstring = createEmptyBoard(DIM);
this.gameID = gameID;
this.currentPlayer = player1ColorIndex;
this.board = new Board(boardstring, DIM);
}
//boardHistory updaten
public void updateBoardHistory(String oldboardstring) {
if( !this.boardHistory.contains(oldboardstring)) {
boardHistory.add(oldboardstring);
}
}
//maak een leeg board
public String createEmptyBoard(int DIM) {
String boardstring = "";
for(int i = 0; i<DIM*DIM; i++) {
boardstring = boardstring+Integer.toString(0);
}
return boardstring;
}
//verander de currentPlayer
public void setCurrentPlayerOther() {
if(currentPlayer == 1) {
currentPlayer = 2;
}
else if(currentPlayer == 2) {
currentPlayer = 1;
}
}
//krijg de naam van de opponent
public String getPlayerNameOther(String playerName) {
if(playerName == player1Name) {
return player2Name;
}
else {
return player1Name;
}
}
//krijg de ClientHandler van de opponent
public ClientHandler getPlayerCHOther(ClientHandler ch) {
if(ch == player1CH) {
return player2CH;
}
else {
return player1CH;
}
}
// update het board van deze game
public String updateBoard(String playerName, int tileIndex, String boardstring, int DIM) {
this.board = new Board(boardstring, DIM);//board updaten met huidige boardstring
int tileColor = 0;
Intersection i = Intersection.EMPTY;
if(playerName.equals(player1Name)) {
tileColor = player1ColorIndex;
} else if (playerName.equals(player2Name)) {
tileColor = player2ColorIndex;
} else {
print("playerName is not known for this game");
}
if(tileColor == 1) {
i= Intersection.BLACK;
} else if (tileColor == 2) {
i= Intersection.WHITE;
} else {
print("this is not a valid move");
}
this.board.setIntersection(tileIndex, i);
String notYetCheckedBoardstring = this.board.toBoardstring();
String checkedBoardstring = checkForCaptures(notYetCheckedBoardstring, DIM);
return notYetCheckedBoardstring;//de vernieuwe boardstring
}
//kijk of er stenen gecaptured zijn
public String checkForCaptures(String notYetCheckedBoardstring, int DIM) {
Board board = new Board(notYetCheckedBoardstring, DIM);
Intersection[] intersectionsArray = board.intersections;
List<Intersection> intersections = new ArrayList<Intersection>(Arrays.asList(intersectionsArray));
for(int i = 0; i < intersections.size(); i++) {
if(intersections.get(i) == Intersection.EMPTY) {
continue;//empty tellen niet mee met stenen capturen, dus continue
}
else {
sameColorNeightbours.put(i, intersections.get(i));//stop de eerste steen in sameColorNeightbours
HashMap<Integer, Intersection> neightboursListhsm = board.getNeighbours(i, DIM, intersections); //buren van de eerste sten
sameColorOrNot(neightboursListhsm, i, intersections);//bekijk of de buren dezelfde kleur hebben als de steen op tileIndex i
while(!notSameColorNeightbours.contains(Intersection.EMPTY)) {//als de groep omringt wordt door de andere kleur
for(int a = 0; a < intersections.size(); a++) {//ga hashmap sameColorNeightbours af op alle mogelijke tileIndexes die opgeslagen zijn
if(sameColorNeightbours.get(a)!= null) {//als er op deze tileIndex dus WEL een intersectie in de hashmap opgeslagen is
board.setIntersection(a, Intersection.EMPTY);
}
}
String checkedBoardstring = board.toBoardstring();
return checkedBoardstring;
}
return notYetCheckedBoardstring;//niks is veranderd
}
}
return notYetCheckedBoardstring;
}
//bekijkt of de stenen in de HashMap allemaal dezelfde kleur zijn als de steen die je meegeeft via de int en intersections
public void sameColorOrNot(HashMap<Integer, Intersection> neightboursList, int a, List<Intersection> intersections) {//a tileIndex eerste steen & intersections weet of het black/white is
for(int i = 0; i < intersections.size(); i++) {
Intersection checkingThisNeightbour = neightboursList.get(i);//ga alle stenen af in de HashMap
if(checkingThisNeightbour == intersections.get(a)) {//zelfde als de steen waar we de buren van hebben gevraagd?
if(!sameColorNeightbours.containsKey(i)) {//Dus een nieuwe steen die ook in de groep hoort
sameColorNeightbours.put(i, checkingThisNeightbour);//stop nieuwe bij de groep
//wanneer je er een nieuwe steen in stopt, moet je het opnieuw testen, met de grotere groep
HashMap<Integer, Intersection> biggerNeightboursList = new HashMap<Integer, Intersection>() ;//hierin komen de neightbours van de neightbours
for(int b = 0; b < intersections.size(); b++) {
Intersection value = sameColorNeightbours.get(b);//b = key
if(value != null) {
Board board = new Board("0", 1);//niet netjes, maar functie getNeightbours hoeft niet met specifiek board
double DDIM = Math.sqrt((double)intersections.size());
int DIM = (int)DDIM;
HashMap<Integer, Intersection>thisStoneNeightbours = board.getNeighbours(b, DIM, intersections);
for(int c = 0; c < intersections.size(); c++) {//ga de neightbours af van deze steen
Intersection v = thisStoneNeightbours.get(c);
if(v != null) {
biggerNeightboursList.put(c, v);
} else { // lege key in HashMap thisStoneNeightbours
continue;
}
}
} else { //lege key in HashMap sameColorNeightbours
continue;
}
}
sameColorOrNot(biggerNeightboursList, a, intersections);//dit zijn de buren, rekening houdend met de nieuw toegevoegde steen. die wil je ook testen
}
} else { //niet zelfde als de steen die we meegeven met int a en intersections
if(checkingThisNeightbour != null) {
notSameColorNeightbours.add(checkingThisNeightbour);//dit is de rand van de groep (kan ook een lege intersectie zijn)
} else { // lege key in HashMap neighboursList
continue;
}
}
}
}
//bereken score
public Score score(String boardstring, int DIM) {
String checkedBoardstring = capturedEmptyfields(boardstring, DIM);//elk vak aan lege intersecties dat gecaptured is door 1 kleur wordt omgezet in stenen in die kleur
Board board = new Board(checkedBoardstring, DIM);
Intersection[] intersectionsArray = board.intersections;
int pointsBlack = 0;
double pointsWhite = 0.0;
for(int i = 0; i < intersectionsArray.length; i++) {
if(intersectionsArray[i] == Intersection.BLACK) {
pointsBlack = pointsBlack + 1;
}
else if(intersectionsArray[i] == Intersection.WHITE) {
pointsWhite = pointsWhite + 1.0;
}
}
pointsWhite = pointsWhite + 0.5;
String scoreString = pointsBlack + ";" + pointsWhite;
Score score = new Score(scoreString);
return score;
}
//elk vak aan lege intersecties dat gecaptured is door 1 kleur wordt omgezet in stenen in die kleur
public String capturedEmptyfields(String boardstring, int DIM) {
Board board = new Board(boardstring, DIM);
Intersection[] intersectionsArray = board.intersections;
List<Intersection> intersections = new ArrayList<Intersection>(Arrays.asList(intersectionsArray));
for(int i = 0; i < intersections.size(); i++) {
if(intersections.get(i) != Intersection.EMPTY) {
continue;
}
else {
sameColorNeightbours.put(i, intersections.get(i));//stop de lege intersectie in sameColorNeightbours
HashMap<Integer, Intersection> neightboursListhsm = board.getNeighbours(i, DIM, intersections);
sameColorOrNot(neightboursListhsm, i, intersections);//bekijk of de buren dezelfde kleur hebben als de steen op tileIndex i
if(notSameColorNeightbours.contains(Intersection.WHITE) && !notSameColorNeightbours.contains(Intersection.BLACK)) {//als de groep alleen omringt door wit
for(int a = 0; a < intersections.size(); a++) {//ga hashmap sameColorNeightbours af op alle mogelijke tileIndexes die opgeslagen zijn
if(sameColorNeightbours.get(a)!= null) {//als er op deze tileIndex dus WEL een intersectie in de hashmap opgeslagen is
board.setIntersection(a, Intersection.WHITE);
}
}
String checkedBoardstring = board.toBoardstring();
return checkedBoardstring;
} else if(!notSameColorNeightbours.contains(Intersection.WHITE) && notSameColorNeightbours.contains(Intersection.BLACK)) {//als de groep alleen omringt door zwart
for(int a = 0; a < intersections.size(); a++) {//ga hashmap sameColorNeig.. af op alle mogelijke tileIndexes die opgeslagen zijn
if(sameColorNeightbours.get(a)!= null) {//als er op deze tileIndex dus WEL een intersectie in de hashmap opgeslagen is
board.setIntersection(a, Intersection.BLACK);
}
}
String checkedBoardstring = board.toBoardstring();
return checkedBoardstring;
} else {
return boardstring;//niks verandert
}
}
}
return boardstring;//for loop doorheen en niks geturned
}
//geef de winner String
public String winner(Score score) {
int pointsBlack = score.pointsBlack;
double pointsWhite = score.pointsWhite;
int winnerColor = 0;
String winner = "";
if (pointsBlack > pointsWhite) {
winnerColor = 1;
}
else {
winnerColor = 2;
}
if(player1ColorIndex == winnerColor) {
winner = player1Name;
}
else {
winner = player2Name;
}
return winner;
}
//geef kleur van de speler
public int getPlayerColor(String playerName) {
if(playerName == player1Name) {
return player1ColorIndex;
} else {
if(player1ColorIndex == 1) {
return 2;
} else {
return 1;
}
}
}
//onthoudt beide antwoorden van de spelers
public void rematchOrNot(int answer) {
if (firstAnswer == -10) {
firstAnswer = answer;
} else if(secondAnswer == -10) {
secondAnswer = answer;
twoAnswers = true;
}
if(firstAnswer == 1 && secondAnswer == 1){
rematch = true;
}
}
public void print(String s) {
System.out.println(s);
}
}
| Anouk0308/GO-Nedap-Anouk | src/main/java/ownCode/Game.java | 3,977 | //als de groep alleen omringt door wit | line_comment | nl | package ownCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Math.toIntExact;
public class Game {
public String player1Name;
public String player2Name;
public String boardstring;
public ArrayList<String> boardHistory = new ArrayList<String>();
public int DIM;
public int player1ColorIndex;
public int player2ColorIndex;
public int gameID;
public int currentPlayer;
private int firstAnswer = -10;//0 is een legit optie, dus kunnen niet een 'lege' int maken. vandaar heb ik het op -10 gezet
private int secondAnswer = -10;
public boolean onePass = false;
public boolean rematch = false;
public boolean twoAnswers = false;
public ClientHandler player1CH;
public ClientHandler player2CH;
public Board board;
private HashMap<Integer, Intersection> sameColorNeightbours = new HashMap<Integer, Intersection>();
private List<Intersection> notSameColorNeightbours = new ArrayList<Intersection>();//empty zit hier ook in
public Game(String player1Name, int player1ColorIndex, String player2Name, int DIM, int gameID) {
this.player1Name = player1Name;
this.player2Name = player2Name;
this.player1ColorIndex = player1ColorIndex;
if(player1ColorIndex == 1) {
player2ColorIndex = 2;
} else if(player1ColorIndex == 2) {
player2ColorIndex = 1;
} else {
print("Something goes wrong with ginving players their color");
}
this.DIM = DIM;
this.boardstring = createEmptyBoard(DIM);
this.gameID = gameID;
this.currentPlayer = player1ColorIndex;
this.board = new Board(boardstring, DIM);
}
//boardHistory updaten
public void updateBoardHistory(String oldboardstring) {
if( !this.boardHistory.contains(oldboardstring)) {
boardHistory.add(oldboardstring);
}
}
//maak een leeg board
public String createEmptyBoard(int DIM) {
String boardstring = "";
for(int i = 0; i<DIM*DIM; i++) {
boardstring = boardstring+Integer.toString(0);
}
return boardstring;
}
//verander de currentPlayer
public void setCurrentPlayerOther() {
if(currentPlayer == 1) {
currentPlayer = 2;
}
else if(currentPlayer == 2) {
currentPlayer = 1;
}
}
//krijg de naam van de opponent
public String getPlayerNameOther(String playerName) {
if(playerName == player1Name) {
return player2Name;
}
else {
return player1Name;
}
}
//krijg de ClientHandler van de opponent
public ClientHandler getPlayerCHOther(ClientHandler ch) {
if(ch == player1CH) {
return player2CH;
}
else {
return player1CH;
}
}
// update het board van deze game
public String updateBoard(String playerName, int tileIndex, String boardstring, int DIM) {
this.board = new Board(boardstring, DIM);//board updaten met huidige boardstring
int tileColor = 0;
Intersection i = Intersection.EMPTY;
if(playerName.equals(player1Name)) {
tileColor = player1ColorIndex;
} else if (playerName.equals(player2Name)) {
tileColor = player2ColorIndex;
} else {
print("playerName is not known for this game");
}
if(tileColor == 1) {
i= Intersection.BLACK;
} else if (tileColor == 2) {
i= Intersection.WHITE;
} else {
print("this is not a valid move");
}
this.board.setIntersection(tileIndex, i);
String notYetCheckedBoardstring = this.board.toBoardstring();
String checkedBoardstring = checkForCaptures(notYetCheckedBoardstring, DIM);
return notYetCheckedBoardstring;//de vernieuwe boardstring
}
//kijk of er stenen gecaptured zijn
public String checkForCaptures(String notYetCheckedBoardstring, int DIM) {
Board board = new Board(notYetCheckedBoardstring, DIM);
Intersection[] intersectionsArray = board.intersections;
List<Intersection> intersections = new ArrayList<Intersection>(Arrays.asList(intersectionsArray));
for(int i = 0; i < intersections.size(); i++) {
if(intersections.get(i) == Intersection.EMPTY) {
continue;//empty tellen niet mee met stenen capturen, dus continue
}
else {
sameColorNeightbours.put(i, intersections.get(i));//stop de eerste steen in sameColorNeightbours
HashMap<Integer, Intersection> neightboursListhsm = board.getNeighbours(i, DIM, intersections); //buren van de eerste sten
sameColorOrNot(neightboursListhsm, i, intersections);//bekijk of de buren dezelfde kleur hebben als de steen op tileIndex i
while(!notSameColorNeightbours.contains(Intersection.EMPTY)) {//als de groep omringt wordt door de andere kleur
for(int a = 0; a < intersections.size(); a++) {//ga hashmap sameColorNeightbours af op alle mogelijke tileIndexes die opgeslagen zijn
if(sameColorNeightbours.get(a)!= null) {//als er op deze tileIndex dus WEL een intersectie in de hashmap opgeslagen is
board.setIntersection(a, Intersection.EMPTY);
}
}
String checkedBoardstring = board.toBoardstring();
return checkedBoardstring;
}
return notYetCheckedBoardstring;//niks is veranderd
}
}
return notYetCheckedBoardstring;
}
//bekijkt of de stenen in de HashMap allemaal dezelfde kleur zijn als de steen die je meegeeft via de int en intersections
public void sameColorOrNot(HashMap<Integer, Intersection> neightboursList, int a, List<Intersection> intersections) {//a tileIndex eerste steen & intersections weet of het black/white is
for(int i = 0; i < intersections.size(); i++) {
Intersection checkingThisNeightbour = neightboursList.get(i);//ga alle stenen af in de HashMap
if(checkingThisNeightbour == intersections.get(a)) {//zelfde als de steen waar we de buren van hebben gevraagd?
if(!sameColorNeightbours.containsKey(i)) {//Dus een nieuwe steen die ook in de groep hoort
sameColorNeightbours.put(i, checkingThisNeightbour);//stop nieuwe bij de groep
//wanneer je er een nieuwe steen in stopt, moet je het opnieuw testen, met de grotere groep
HashMap<Integer, Intersection> biggerNeightboursList = new HashMap<Integer, Intersection>() ;//hierin komen de neightbours van de neightbours
for(int b = 0; b < intersections.size(); b++) {
Intersection value = sameColorNeightbours.get(b);//b = key
if(value != null) {
Board board = new Board("0", 1);//niet netjes, maar functie getNeightbours hoeft niet met specifiek board
double DDIM = Math.sqrt((double)intersections.size());
int DIM = (int)DDIM;
HashMap<Integer, Intersection>thisStoneNeightbours = board.getNeighbours(b, DIM, intersections);
for(int c = 0; c < intersections.size(); c++) {//ga de neightbours af van deze steen
Intersection v = thisStoneNeightbours.get(c);
if(v != null) {
biggerNeightboursList.put(c, v);
} else { // lege key in HashMap thisStoneNeightbours
continue;
}
}
} else { //lege key in HashMap sameColorNeightbours
continue;
}
}
sameColorOrNot(biggerNeightboursList, a, intersections);//dit zijn de buren, rekening houdend met de nieuw toegevoegde steen. die wil je ook testen
}
} else { //niet zelfde als de steen die we meegeven met int a en intersections
if(checkingThisNeightbour != null) {
notSameColorNeightbours.add(checkingThisNeightbour);//dit is de rand van de groep (kan ook een lege intersectie zijn)
} else { // lege key in HashMap neighboursList
continue;
}
}
}
}
//bereken score
public Score score(String boardstring, int DIM) {
String checkedBoardstring = capturedEmptyfields(boardstring, DIM);//elk vak aan lege intersecties dat gecaptured is door 1 kleur wordt omgezet in stenen in die kleur
Board board = new Board(checkedBoardstring, DIM);
Intersection[] intersectionsArray = board.intersections;
int pointsBlack = 0;
double pointsWhite = 0.0;
for(int i = 0; i < intersectionsArray.length; i++) {
if(intersectionsArray[i] == Intersection.BLACK) {
pointsBlack = pointsBlack + 1;
}
else if(intersectionsArray[i] == Intersection.WHITE) {
pointsWhite = pointsWhite + 1.0;
}
}
pointsWhite = pointsWhite + 0.5;
String scoreString = pointsBlack + ";" + pointsWhite;
Score score = new Score(scoreString);
return score;
}
//elk vak aan lege intersecties dat gecaptured is door 1 kleur wordt omgezet in stenen in die kleur
public String capturedEmptyfields(String boardstring, int DIM) {
Board board = new Board(boardstring, DIM);
Intersection[] intersectionsArray = board.intersections;
List<Intersection> intersections = new ArrayList<Intersection>(Arrays.asList(intersectionsArray));
for(int i = 0; i < intersections.size(); i++) {
if(intersections.get(i) != Intersection.EMPTY) {
continue;
}
else {
sameColorNeightbours.put(i, intersections.get(i));//stop de lege intersectie in sameColorNeightbours
HashMap<Integer, Intersection> neightboursListhsm = board.getNeighbours(i, DIM, intersections);
sameColorOrNot(neightboursListhsm, i, intersections);//bekijk of de buren dezelfde kleur hebben als de steen op tileIndex i
if(notSameColorNeightbours.contains(Intersection.WHITE) && !notSameColorNeightbours.contains(Intersection.BLACK)) {//als de<SUF>
for(int a = 0; a < intersections.size(); a++) {//ga hashmap sameColorNeightbours af op alle mogelijke tileIndexes die opgeslagen zijn
if(sameColorNeightbours.get(a)!= null) {//als er op deze tileIndex dus WEL een intersectie in de hashmap opgeslagen is
board.setIntersection(a, Intersection.WHITE);
}
}
String checkedBoardstring = board.toBoardstring();
return checkedBoardstring;
} else if(!notSameColorNeightbours.contains(Intersection.WHITE) && notSameColorNeightbours.contains(Intersection.BLACK)) {//als de groep alleen omringt door zwart
for(int a = 0; a < intersections.size(); a++) {//ga hashmap sameColorNeig.. af op alle mogelijke tileIndexes die opgeslagen zijn
if(sameColorNeightbours.get(a)!= null) {//als er op deze tileIndex dus WEL een intersectie in de hashmap opgeslagen is
board.setIntersection(a, Intersection.BLACK);
}
}
String checkedBoardstring = board.toBoardstring();
return checkedBoardstring;
} else {
return boardstring;//niks verandert
}
}
}
return boardstring;//for loop doorheen en niks geturned
}
//geef de winner String
public String winner(Score score) {
int pointsBlack = score.pointsBlack;
double pointsWhite = score.pointsWhite;
int winnerColor = 0;
String winner = "";
if (pointsBlack > pointsWhite) {
winnerColor = 1;
}
else {
winnerColor = 2;
}
if(player1ColorIndex == winnerColor) {
winner = player1Name;
}
else {
winner = player2Name;
}
return winner;
}
//geef kleur van de speler
public int getPlayerColor(String playerName) {
if(playerName == player1Name) {
return player1ColorIndex;
} else {
if(player1ColorIndex == 1) {
return 2;
} else {
return 1;
}
}
}
//onthoudt beide antwoorden van de spelers
public void rematchOrNot(int answer) {
if (firstAnswer == -10) {
firstAnswer = answer;
} else if(secondAnswer == -10) {
secondAnswer = answer;
twoAnswers = true;
}
if(firstAnswer == 1 && secondAnswer == 1){
rematch = true;
}
}
public void print(String s) {
System.out.println(s);
}
}
|
32621_2 | import java.util.ArrayList;
import java.util.List;
//import org.apache.commons.lang3.tuple.MutablePair<L, R>;
//import org.apache.commons.lang3.tuple.ImmutablePair<L, R>
public class Board {
public Square[] squares = new Square[81];
public Board() {
for(int i = 0; i<81; i++) {
squares[i] = new Square();
}
}
public SquareBoardCombi[] getRow(int i) {
int compare = Math.floorDiv(i, 9);
List<SquareBoardCombi> rowtemp = new ArrayList<SquareBoardCombi>();
SquareBoardCombi[] row = new SquareBoardCombi[9];
for (int a = 0; a < squares.length; a++) {
if (Math.floorDiv(a,9) == compare) {
SquareBoardCombi s = new SquareBoardCombi(a, squares[a]);
rowtemp.add(s);
} else {
continue;
}
}
row = rowtemp.toArray(row);
return row;
}
public SquareBoardCombi[] getColumn(int i) {
int compare = i%9;
List<SquareBoardCombi> columntemp = new ArrayList<SquareBoardCombi>();
SquareBoardCombi[] column = new SquareBoardCombi[9];
for(int a = 0; a < squares.length; a++) {
if(a%9 == compare) {
SquareBoardCombi s = new SquareBoardCombi(a, squares[a]);
columntemp.add(s);
} else {
continue;
}
}
column = columntemp.toArray(column);
return column;
}
public SquareBoardCombi[] getGroup(int i) {//groot vierkantje
SquareBoardCombi[] group = new SquareBoardCombi[9];
List<SquareBoardCombi> grouptemp = new ArrayList<SquareBoardCombi>();
if(i == 0 || i == 1 || i == 2 || i == 9 || i == 10 || i == 11 || i == 18 || i == 19 || i ==20){
SquareBoardCombi s1 = new SquareBoardCombi(0, squares[0]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(1, squares[1]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(2, squares[2]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(9, squares[9]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(10, squares[10]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(11, squares[11]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(18, squares[18]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(19, squares[19]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(20, squares[20]);
grouptemp.add(s9);
} else if(i == 3 || i == 4 || i == 5 || i == 12 || i == 13 || i == 14 || i == 21 || i == 22 || i ==23){
SquareBoardCombi s1 = new SquareBoardCombi(3, squares[3]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(4, squares[4]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(5, squares[5]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(12, squares[12]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(13, squares[13]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(14, squares[14]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(21, squares[21]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(22, squares[22]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(23, squares[23]);
grouptemp.add(s9);
} else if(i == 6 || i == 7 || i == 8 || i == 15 || i == 16 || i == 17 || i == 24 || i == 25 || i ==26){
SquareBoardCombi s1 = new SquareBoardCombi(6, squares[6]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(7, squares[7]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(8, squares[8]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(15, squares[15]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(16, squares[16]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(17, squares[17]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(24, squares[24]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(25, squares[25]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(26, squares[26]);
grouptemp.add(s9);
} else if(i == 27 || i == 28 || i == 29 || i == 36 || i == 37 || i == 38 || i == 45 || i == 46 || i ==47){
SquareBoardCombi s1 = new SquareBoardCombi(27, squares[27]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(28, squares[28]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(29, squares[29]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(36, squares[36]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(37, squares[37]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(38, squares[38]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(45, squares[45]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(46, squares[46]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(47, squares[47]);
grouptemp.add(s9);
}else if(i == 30 || i == 31 || i == 32 || i == 39 || i == 40 || i == 41 || i == 48 || i == 49 || i ==50){
SquareBoardCombi s1 = new SquareBoardCombi(30, squares[30]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(31, squares[31]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(32, squares[32]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(39, squares[39]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(40, squares[40]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(41, squares[41]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(48, squares[48]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(49, squares[49]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(50, squares[50]);
grouptemp.add(s9);
} else if(i == 33 || i == 34 || i == 35 || i == 42 || i == 43 || i == 44 || i == 51 || i == 52 || i ==53){
SquareBoardCombi s1 = new SquareBoardCombi(33, squares[33]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(34, squares[34]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(35, squares[35]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(42, squares[42]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(43, squares[43]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(44, squares[44]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(51, squares[51]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(52, squares[52]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(53, squares[53]);
grouptemp.add(s9);
}else if(i == 54 || i == 55 || i == 56 || i == 63 || i == 64 || i == 65 || i == 72 || i == 73 || i ==74) {
SquareBoardCombi s1 = new SquareBoardCombi(54, squares[54]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(55, squares[55]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(56, squares[56]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(63, squares[63]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(64, squares[64]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(65, squares[65]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(72, squares[72]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(73, squares[73]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(74, squares[74]);
grouptemp.add(s9);
}else if(i == 57 || i == 58 || i == 59 || i == 66 || i == 67 || i == 68 || i == 75 || i == 76 || i ==77) {
SquareBoardCombi s1 = new SquareBoardCombi(57, squares[57]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(58, squares[58]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(59, squares[59]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(66, squares[66]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(67, squares[67]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(68, squares[68]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(75, squares[75]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(76, squares[76]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(77, squares[77]);
grouptemp.add(s9);
}else if(i == 60 || i == 61 || i == 62 || i == 69 || i == 70 || i == 71 || i == 78 || i == 79 || i ==80) {
SquareBoardCombi s1 = new SquareBoardCombi(60, squares[60]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(61, squares[61]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(62, squares[62]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(69, squares[69]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(70, squares[70]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(71, squares[71]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(78, squares[78]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(79, squares[79]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(80, squares[80]);
grouptemp.add(s9);
}
group = grouptemp.toArray(group);
return group;
}
public void remove(int i, EnumSquares e){
Square s = squares[i];
if(s.possibleNumbers.contains(e)){
s.possibleNumbers.remove(e);
}
}
public void set(int i, EnumSquares es) {
Square s = squares[i];
s.stateSquare = es;
SquareBoardCombi[] row = getRow(i);
SquareBoardCombi[] column = getColumn(i);
SquareBoardCombi[] group = getGroup(i);
for(int a = 0; a < row.length; a++){
SquareBoardCombi sbc = row[a];
int index = sbc.i;
remove(index, es);
}
for(int b = 0; b < column.length; b++){
SquareBoardCombi sbc = column[b];
int index = sbc.i;
remove(index, es);
}
for(int c = 0; c < group.length; c++) {
SquareBoardCombi sbc = group[c];
int index = sbc.i;
remove(index, es);
}
checkSquares();
}
public void checkSquares(){
checkOnePossibityInSquare();
checkOneSquarepossible();
}
public boolean onePossibility(int i) {
return(squares[i].possibleNumbers.size() == 1);
}
public void checkOnePossibityInSquare(){//kijkt of een vierkantje nog maar 1 mogelijkheid heeft
for(int i = 0; i < squares.length; i++){
Square s = squares[i];
if(s.stateSquare == EnumSquares.EMPTY) {
if (onePossibility(i)) {
set(i, s.possibleNumbers.get(0));
} else {
continue;
}
} else{
continue;
}
}
}
public void checkOneSquarepossible(){//kijkt per rij, kollom en groep of er maar 1 vierkantje is waar bv de 5 in kan
SquareBoardCombi[][] sbcArrayArray = getAllSBC(); //krijg alle rijen, alle kollomen en alle groepen
for(int a = 0; a < sbcArrayArray.length; a++){
SquareBoardCombi[] sbca = sbcArrayArray[a]; //krijg een rij, kollom of groep
for(int b = 1; b < 10; b++){ //doe dit per getal 1....9
int counter = 0;
EnumSquares es = getEnumFromInt(b);
int index = -1;
for(int c = 0; c<9; c++){ // kijk voor elke SquareBoardCombi in de rij(of kolom/groep)
SquareBoardCombi sbc = sbca[c];
Square s = sbc.s;
int i = sbc.i;
if(s.possibleNumbers.contains(es)){
counter = counter + 1;
index = i;
}
else{
continue;
}
}
if(counter == 1){
set(index,es);
} else{
continue;
}
}
}
}
public SquareBoardCombi[][] getAllSBC(){//kijkt per rij, kollom en groep of er maar 1 vierkantje is waar bv de 5 in kan
SquareBoardCombi[][] sbcArrayArray = new SquareBoardCombi[27][9]; //krijg alle rijen, alle kollomen en alle groepen
for (int i = 0; i < 9; i++){//alle rijen
sbcArrayArray[i]= getRow(i);
}
for (int i = 0; i < 9; i++){//alle kollomen
int arrayIndex = i+9;
int columnGetter = i*9;
sbcArrayArray[arrayIndex] = getColumn(columnGetter);
}
for (int i = 0; i < 9; i++){//alle groepen
int arrayIndex = i+18;
int groupGetter = 0;
if(i <= 4) {
groupGetter = i * 12;//fout//
} else if (i == 5){
groupGetter = i * 10+1;
} else if(i == 6){
groupGetter = i * 9;
} else if(i == 7){
groupGetter = i*11;
} else {
groupGetter = i*10;
}
sbcArrayArray[arrayIndex] = getGroup(groupGetter);
}
return sbcArrayArray;
}
public EnumSquares getEnumFromInt(int i){
EnumSquares es;
switch(i){
case 0: es = EnumSquares.EMPTY; break;
case 1: es = EnumSquares.ONE; break;
case 2: es = EnumSquares.TWO; break;
case 3: es = EnumSquares.THREE; break;
case 4: es = EnumSquares.FOUR; break;
case 5: es = EnumSquares.FIVE; break;
case 6: es = EnumSquares.SIX; break;
case 7: es = EnumSquares.SEVEN; break;
case 8: es = EnumSquares.EIGHT; break;
case 9: es = EnumSquares.NINE; break;
default: es = EnumSquares.EMPTY; break;
}
return es;
}
public boolean full(){
int teller = 0;
for(int i = 0; i< squares.length; i++){
Square s = squares[i];
if(s.stateSquare == EnumSquares.EMPTY){
teller = teller + 1;
} else{
continue;
}
}
return(teller == 0);
}
public String toBoardstring() {
String newboardstring = "";
int tempi = 0;
String temps;
for(int i = 0; 0 <= i && i < 81; i++) {
if(squares[i].stateSquare == EnumSquares.EMPTY) {
tempi = 0;
} else if(squares[i].stateSquare == EnumSquares.ONE) {
tempi = 1;
} else if(squares[i].stateSquare == EnumSquares.TWO) {
tempi = 2;
} else if(squares[i].stateSquare == EnumSquares.THREE) {
tempi = 3;
} else if(squares[i].stateSquare == EnumSquares.FOUR) {
tempi = 4;
} else if(squares[i].stateSquare == EnumSquares.FIVE) {
tempi = 5;
} else if(squares[i].stateSquare == EnumSquares.SIX) {
tempi = 6;
} else if(squares[i].stateSquare == EnumSquares.SEVEN) {
tempi = 7;
} else if(squares[i].stateSquare == EnumSquares.EIGHT) {
tempi = 8;
} else if(squares[i].stateSquare == EnumSquares.NINE) {
tempi = 9;
}
temps = Integer.toString(tempi);
newboardstring = newboardstring + temps;
}
return newboardstring;
}
public SquareBoardCombi[] toSquaresArray(String boardstring) {
String[] boardstringArray = boardstring.split("\\B");
List<SquareBoardCombi> sbctemp = new ArrayList<SquareBoardCombi>();
SquareBoardCombi[] sbcar = new SquareBoardCombi[81];
SquareBoardCombi sbc;
Square stemp = new Square();
for(int i = 0; 0 <= i && i < 81; i++) {
if(boardstringArray[i].equals("0")) {
stemp.stateSquare = EnumSquares.EMPTY;
} else if(boardstringArray[i].equals("1")) {
stemp.stateSquare = EnumSquares.ONE;
} else if(boardstringArray[i].equals("2")) {
stemp.stateSquare = EnumSquares.TWO;
} else if(boardstringArray[i].equals("3")) {
stemp.stateSquare = EnumSquares.THREE;
} else if(boardstringArray[i].equals("4")) {
stemp.stateSquare = EnumSquares.FOUR;
} else if(boardstringArray[i].equals("5")) {
stemp.stateSquare = EnumSquares.FIVE;
} else if(boardstringArray[i].equals("6")) {
stemp.stateSquare = EnumSquares.SIX;
} else if(boardstringArray[i].equals("7")) {
stemp.stateSquare = EnumSquares.SEVEN;
} else if(boardstringArray[i].equals("8")) {
stemp.stateSquare = EnumSquares.EIGHT;
} else if(boardstringArray[i].equals("9")) {
stemp.stateSquare = EnumSquares.NINE;
}
sbc = new SquareBoardCombi(i, stemp);
sbctemp.add(sbc);
}
sbcar = sbctemp.toArray(sbcar);
return sbcar;
}
} | Anouk0308/Sudoku | src/Board.java | 6,587 | //kijkt of een vierkantje nog maar 1 mogelijkheid heeft | line_comment | nl | import java.util.ArrayList;
import java.util.List;
//import org.apache.commons.lang3.tuple.MutablePair<L, R>;
//import org.apache.commons.lang3.tuple.ImmutablePair<L, R>
public class Board {
public Square[] squares = new Square[81];
public Board() {
for(int i = 0; i<81; i++) {
squares[i] = new Square();
}
}
public SquareBoardCombi[] getRow(int i) {
int compare = Math.floorDiv(i, 9);
List<SquareBoardCombi> rowtemp = new ArrayList<SquareBoardCombi>();
SquareBoardCombi[] row = new SquareBoardCombi[9];
for (int a = 0; a < squares.length; a++) {
if (Math.floorDiv(a,9) == compare) {
SquareBoardCombi s = new SquareBoardCombi(a, squares[a]);
rowtemp.add(s);
} else {
continue;
}
}
row = rowtemp.toArray(row);
return row;
}
public SquareBoardCombi[] getColumn(int i) {
int compare = i%9;
List<SquareBoardCombi> columntemp = new ArrayList<SquareBoardCombi>();
SquareBoardCombi[] column = new SquareBoardCombi[9];
for(int a = 0; a < squares.length; a++) {
if(a%9 == compare) {
SquareBoardCombi s = new SquareBoardCombi(a, squares[a]);
columntemp.add(s);
} else {
continue;
}
}
column = columntemp.toArray(column);
return column;
}
public SquareBoardCombi[] getGroup(int i) {//groot vierkantje
SquareBoardCombi[] group = new SquareBoardCombi[9];
List<SquareBoardCombi> grouptemp = new ArrayList<SquareBoardCombi>();
if(i == 0 || i == 1 || i == 2 || i == 9 || i == 10 || i == 11 || i == 18 || i == 19 || i ==20){
SquareBoardCombi s1 = new SquareBoardCombi(0, squares[0]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(1, squares[1]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(2, squares[2]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(9, squares[9]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(10, squares[10]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(11, squares[11]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(18, squares[18]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(19, squares[19]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(20, squares[20]);
grouptemp.add(s9);
} else if(i == 3 || i == 4 || i == 5 || i == 12 || i == 13 || i == 14 || i == 21 || i == 22 || i ==23){
SquareBoardCombi s1 = new SquareBoardCombi(3, squares[3]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(4, squares[4]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(5, squares[5]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(12, squares[12]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(13, squares[13]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(14, squares[14]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(21, squares[21]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(22, squares[22]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(23, squares[23]);
grouptemp.add(s9);
} else if(i == 6 || i == 7 || i == 8 || i == 15 || i == 16 || i == 17 || i == 24 || i == 25 || i ==26){
SquareBoardCombi s1 = new SquareBoardCombi(6, squares[6]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(7, squares[7]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(8, squares[8]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(15, squares[15]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(16, squares[16]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(17, squares[17]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(24, squares[24]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(25, squares[25]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(26, squares[26]);
grouptemp.add(s9);
} else if(i == 27 || i == 28 || i == 29 || i == 36 || i == 37 || i == 38 || i == 45 || i == 46 || i ==47){
SquareBoardCombi s1 = new SquareBoardCombi(27, squares[27]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(28, squares[28]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(29, squares[29]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(36, squares[36]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(37, squares[37]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(38, squares[38]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(45, squares[45]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(46, squares[46]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(47, squares[47]);
grouptemp.add(s9);
}else if(i == 30 || i == 31 || i == 32 || i == 39 || i == 40 || i == 41 || i == 48 || i == 49 || i ==50){
SquareBoardCombi s1 = new SquareBoardCombi(30, squares[30]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(31, squares[31]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(32, squares[32]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(39, squares[39]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(40, squares[40]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(41, squares[41]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(48, squares[48]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(49, squares[49]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(50, squares[50]);
grouptemp.add(s9);
} else if(i == 33 || i == 34 || i == 35 || i == 42 || i == 43 || i == 44 || i == 51 || i == 52 || i ==53){
SquareBoardCombi s1 = new SquareBoardCombi(33, squares[33]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(34, squares[34]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(35, squares[35]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(42, squares[42]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(43, squares[43]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(44, squares[44]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(51, squares[51]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(52, squares[52]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(53, squares[53]);
grouptemp.add(s9);
}else if(i == 54 || i == 55 || i == 56 || i == 63 || i == 64 || i == 65 || i == 72 || i == 73 || i ==74) {
SquareBoardCombi s1 = new SquareBoardCombi(54, squares[54]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(55, squares[55]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(56, squares[56]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(63, squares[63]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(64, squares[64]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(65, squares[65]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(72, squares[72]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(73, squares[73]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(74, squares[74]);
grouptemp.add(s9);
}else if(i == 57 || i == 58 || i == 59 || i == 66 || i == 67 || i == 68 || i == 75 || i == 76 || i ==77) {
SquareBoardCombi s1 = new SquareBoardCombi(57, squares[57]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(58, squares[58]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(59, squares[59]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(66, squares[66]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(67, squares[67]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(68, squares[68]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(75, squares[75]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(76, squares[76]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(77, squares[77]);
grouptemp.add(s9);
}else if(i == 60 || i == 61 || i == 62 || i == 69 || i == 70 || i == 71 || i == 78 || i == 79 || i ==80) {
SquareBoardCombi s1 = new SquareBoardCombi(60, squares[60]);
grouptemp.add(s1);
SquareBoardCombi s2 = new SquareBoardCombi(61, squares[61]);
grouptemp.add(s2);
SquareBoardCombi s3 = new SquareBoardCombi(62, squares[62]);
grouptemp.add(s3);
SquareBoardCombi s4 = new SquareBoardCombi(69, squares[69]);
grouptemp.add(s4);
SquareBoardCombi s5 = new SquareBoardCombi(70, squares[70]);
grouptemp.add(s5);
SquareBoardCombi s6 = new SquareBoardCombi(71, squares[71]);
grouptemp.add(s6);
SquareBoardCombi s7 = new SquareBoardCombi(78, squares[78]);
grouptemp.add(s7);
SquareBoardCombi s8 = new SquareBoardCombi(79, squares[79]);
grouptemp.add(s8);
SquareBoardCombi s9 = new SquareBoardCombi(80, squares[80]);
grouptemp.add(s9);
}
group = grouptemp.toArray(group);
return group;
}
public void remove(int i, EnumSquares e){
Square s = squares[i];
if(s.possibleNumbers.contains(e)){
s.possibleNumbers.remove(e);
}
}
public void set(int i, EnumSquares es) {
Square s = squares[i];
s.stateSquare = es;
SquareBoardCombi[] row = getRow(i);
SquareBoardCombi[] column = getColumn(i);
SquareBoardCombi[] group = getGroup(i);
for(int a = 0; a < row.length; a++){
SquareBoardCombi sbc = row[a];
int index = sbc.i;
remove(index, es);
}
for(int b = 0; b < column.length; b++){
SquareBoardCombi sbc = column[b];
int index = sbc.i;
remove(index, es);
}
for(int c = 0; c < group.length; c++) {
SquareBoardCombi sbc = group[c];
int index = sbc.i;
remove(index, es);
}
checkSquares();
}
public void checkSquares(){
checkOnePossibityInSquare();
checkOneSquarepossible();
}
public boolean onePossibility(int i) {
return(squares[i].possibleNumbers.size() == 1);
}
public void checkOnePossibityInSquare(){//kijkt of<SUF>
for(int i = 0; i < squares.length; i++){
Square s = squares[i];
if(s.stateSquare == EnumSquares.EMPTY) {
if (onePossibility(i)) {
set(i, s.possibleNumbers.get(0));
} else {
continue;
}
} else{
continue;
}
}
}
public void checkOneSquarepossible(){//kijkt per rij, kollom en groep of er maar 1 vierkantje is waar bv de 5 in kan
SquareBoardCombi[][] sbcArrayArray = getAllSBC(); //krijg alle rijen, alle kollomen en alle groepen
for(int a = 0; a < sbcArrayArray.length; a++){
SquareBoardCombi[] sbca = sbcArrayArray[a]; //krijg een rij, kollom of groep
for(int b = 1; b < 10; b++){ //doe dit per getal 1....9
int counter = 0;
EnumSquares es = getEnumFromInt(b);
int index = -1;
for(int c = 0; c<9; c++){ // kijk voor elke SquareBoardCombi in de rij(of kolom/groep)
SquareBoardCombi sbc = sbca[c];
Square s = sbc.s;
int i = sbc.i;
if(s.possibleNumbers.contains(es)){
counter = counter + 1;
index = i;
}
else{
continue;
}
}
if(counter == 1){
set(index,es);
} else{
continue;
}
}
}
}
public SquareBoardCombi[][] getAllSBC(){//kijkt per rij, kollom en groep of er maar 1 vierkantje is waar bv de 5 in kan
SquareBoardCombi[][] sbcArrayArray = new SquareBoardCombi[27][9]; //krijg alle rijen, alle kollomen en alle groepen
for (int i = 0; i < 9; i++){//alle rijen
sbcArrayArray[i]= getRow(i);
}
for (int i = 0; i < 9; i++){//alle kollomen
int arrayIndex = i+9;
int columnGetter = i*9;
sbcArrayArray[arrayIndex] = getColumn(columnGetter);
}
for (int i = 0; i < 9; i++){//alle groepen
int arrayIndex = i+18;
int groupGetter = 0;
if(i <= 4) {
groupGetter = i * 12;//fout//
} else if (i == 5){
groupGetter = i * 10+1;
} else if(i == 6){
groupGetter = i * 9;
} else if(i == 7){
groupGetter = i*11;
} else {
groupGetter = i*10;
}
sbcArrayArray[arrayIndex] = getGroup(groupGetter);
}
return sbcArrayArray;
}
public EnumSquares getEnumFromInt(int i){
EnumSquares es;
switch(i){
case 0: es = EnumSquares.EMPTY; break;
case 1: es = EnumSquares.ONE; break;
case 2: es = EnumSquares.TWO; break;
case 3: es = EnumSquares.THREE; break;
case 4: es = EnumSquares.FOUR; break;
case 5: es = EnumSquares.FIVE; break;
case 6: es = EnumSquares.SIX; break;
case 7: es = EnumSquares.SEVEN; break;
case 8: es = EnumSquares.EIGHT; break;
case 9: es = EnumSquares.NINE; break;
default: es = EnumSquares.EMPTY; break;
}
return es;
}
public boolean full(){
int teller = 0;
for(int i = 0; i< squares.length; i++){
Square s = squares[i];
if(s.stateSquare == EnumSquares.EMPTY){
teller = teller + 1;
} else{
continue;
}
}
return(teller == 0);
}
public String toBoardstring() {
String newboardstring = "";
int tempi = 0;
String temps;
for(int i = 0; 0 <= i && i < 81; i++) {
if(squares[i].stateSquare == EnumSquares.EMPTY) {
tempi = 0;
} else if(squares[i].stateSquare == EnumSquares.ONE) {
tempi = 1;
} else if(squares[i].stateSquare == EnumSquares.TWO) {
tempi = 2;
} else if(squares[i].stateSquare == EnumSquares.THREE) {
tempi = 3;
} else if(squares[i].stateSquare == EnumSquares.FOUR) {
tempi = 4;
} else if(squares[i].stateSquare == EnumSquares.FIVE) {
tempi = 5;
} else if(squares[i].stateSquare == EnumSquares.SIX) {
tempi = 6;
} else if(squares[i].stateSquare == EnumSquares.SEVEN) {
tempi = 7;
} else if(squares[i].stateSquare == EnumSquares.EIGHT) {
tempi = 8;
} else if(squares[i].stateSquare == EnumSquares.NINE) {
tempi = 9;
}
temps = Integer.toString(tempi);
newboardstring = newboardstring + temps;
}
return newboardstring;
}
public SquareBoardCombi[] toSquaresArray(String boardstring) {
String[] boardstringArray = boardstring.split("\\B");
List<SquareBoardCombi> sbctemp = new ArrayList<SquareBoardCombi>();
SquareBoardCombi[] sbcar = new SquareBoardCombi[81];
SquareBoardCombi sbc;
Square stemp = new Square();
for(int i = 0; 0 <= i && i < 81; i++) {
if(boardstringArray[i].equals("0")) {
stemp.stateSquare = EnumSquares.EMPTY;
} else if(boardstringArray[i].equals("1")) {
stemp.stateSquare = EnumSquares.ONE;
} else if(boardstringArray[i].equals("2")) {
stemp.stateSquare = EnumSquares.TWO;
} else if(boardstringArray[i].equals("3")) {
stemp.stateSquare = EnumSquares.THREE;
} else if(boardstringArray[i].equals("4")) {
stemp.stateSquare = EnumSquares.FOUR;
} else if(boardstringArray[i].equals("5")) {
stemp.stateSquare = EnumSquares.FIVE;
} else if(boardstringArray[i].equals("6")) {
stemp.stateSquare = EnumSquares.SIX;
} else if(boardstringArray[i].equals("7")) {
stemp.stateSquare = EnumSquares.SEVEN;
} else if(boardstringArray[i].equals("8")) {
stemp.stateSquare = EnumSquares.EIGHT;
} else if(boardstringArray[i].equals("9")) {
stemp.stateSquare = EnumSquares.NINE;
}
sbc = new SquareBoardCombi(i, stemp);
sbctemp.add(sbc);
}
sbcar = sbctemp.toArray(sbcar);
return sbcar;
}
} |
141653_8 | /***************************************************************************
* (C) Copyright 2003-2023 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
import games.stendhal.server.maps.quests.AGrandfathersWish;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
final LinkedList<Achievement> achievements = new LinkedList<Achievement>();
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend",
"Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
new QuestCompletedCondition("campfire"),
// Annie, Kalavan city gardens
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(
new QuestActiveCondition("fishsoup_for_hughie"),
new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new QuestCompletedCondition("eggs_for_marianne")
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective",
"Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
},
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Elias Breland, Deniran
new QuestCompletedCondition(AGrandfathersWish.QUEST_SLOT)
)));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan",
"Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing",
"Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
| AntumDeluge/arianne-stendhal | src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java | 1,739 | // Annie, Kalavan city gardens | line_comment | nl | /***************************************************************************
* (C) Copyright 2003-2023 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
import games.stendhal.server.maps.quests.AGrandfathersWish;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
final LinkedList<Achievement> achievements = new LinkedList<Achievement>();
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend",
"Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
new QuestCompletedCondition("campfire"),
// Annie, Kalavan<SUF>
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(
new QuestActiveCondition("fishsoup_for_hughie"),
new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new QuestCompletedCondition("eggs_for_marianne")
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective",
"Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
},
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Elias Breland, Deniran
new QuestCompletedCondition(AGrandfathersWish.QUEST_SLOT)
)));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan",
"Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing",
"Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
|
4464_48 | package mindustry.game;
import arc.graphics.*;
import arc.struct.*;
import arc.util.*;
import arc.util.serialization.*;
import arc.util.serialization.Json.*;
import mindustry.*;
import mindustry.content.*;
import mindustry.graphics.g3d.*;
import mindustry.io.*;
import mindustry.type.*;
import mindustry.type.Weather.*;
import mindustry.world.*;
import mindustry.world.blocks.*;
/**
* Defines current rules on how the game should function.
* Does not store game state, just configuration.
*/
public class Rules{
/** Sandbox mode: Enables infinite resources, build range and build speed. */
public boolean infiniteResources;
/** Team-specific rules. */
public TeamRules teams = new TeamRules();
/** Whether the waves come automatically on a timer. If not, waves come when the play button is pressed. */
public boolean waveTimer = true;
/** Whether the waves can be manually summoned with the play button. */
public boolean waveSending = true;
/** Whether waves are spawnable at all. */
public boolean waves;
/** Whether the game objective is PvP. Note that this enables automatic hosting. */
public boolean pvp;
/** Whether is waiting for players enabled in PvP. */
public boolean pvpAutoPause = true;
/** Whether to pause the wave timer until all enemies are destroyed. */
public boolean waitEnemies = false;
/** Determines if gamemode is attack mode. */
public boolean attackMode = false;
/** Whether this is the editor gamemode. */
public boolean editor = false;
/** Whether blocks can be repaired by clicking them. */
public boolean derelictRepair = true;
/** Whether a gameover can happen at all. Set this to false to implement custom gameover conditions. */
public boolean canGameOver = true;
/** Whether cores change teams when they are destroyed. */
public boolean coreCapture = false;
/** Whether reactors can explode and damage other blocks. */
public boolean reactorExplosions = true;
/** Whether to allow manual unit control. */
public boolean possessionAllowed = true;
/** Whether schematics are allowed. */
public boolean schematicsAllowed = true;
/** Whether friendly explosions can occur and set fire/damage other blocks. */
public boolean damageExplosions = true;
/** Whether fire (and neoplasm spread) is enabled. */
public boolean fire = true;
/** Whether units use and require ammo. */
public boolean unitAmmo = false;
/** EXPERIMENTAL! If true, blocks will update in units and share power. */
public boolean unitPayloadUpdate = false;
/** If true, units' payloads are destroy()ed when the unit is destroyed. */
public boolean unitPayloadsExplode = false;
/** Whether cores add to unit limit */
public boolean unitCapVariable = true;
/** If true, unit spawn points are shown. */
public boolean showSpawns = false;
/** Multiplies power output of solar panels. */
public float solarMultiplier = 1f;
/** How fast unit factories build units. */
public float unitBuildSpeedMultiplier = 1f;
/** Multiplier of resources that units take to build. */
public float unitCostMultiplier = 1f;
/** How much damage units deal. */
public float unitDamageMultiplier = 1f;
/** How much health units start with. */
public float unitHealthMultiplier = 1f;
/** How much damage unit crash damage deals. (Compounds with unitDamageMultiplier) */
public float unitCrashDamageMultiplier = 1f;
/** If true, ghost blocks will appear upon destruction, letting builder blocks/units rebuild them. */
public boolean ghostBlocks = true;
/** Whether to allow units to build with logic. */
public boolean logicUnitBuild = true;
/** If true, world processors no longer update. Used for testing. */
public boolean disableWorldProcessors = false;
/** How much health blocks start with. */
public float blockHealthMultiplier = 1f;
/** How much damage blocks (turrets) deal. */
public float blockDamageMultiplier = 1f;
/** Multiplier for buildings resource cost. */
public float buildCostMultiplier = 1f;
/** Multiplier for building speed. */
public float buildSpeedMultiplier = 1f;
/** Multiplier for percentage of materials refunded when deconstructing. */
public float deconstructRefundMultiplier = 0.5f;
/** No-build zone around enemy core radius. */
public float enemyCoreBuildRadius = 400f;
/** If true, no-build zones are calculated based on the closest core. */
public boolean polygonCoreProtection = false;
/** If true, blocks cannot be placed near blocks that are near the enemy team.*/
public boolean placeRangeCheck = false;
/** If true, dead teams in PvP automatically have their blocks & units converted to derelict upon death. */
public boolean cleanupDeadTeams = true;
/** If true, items can only be deposited in the core. */
public boolean onlyDepositCore = false;
/** If true, every enemy block in the radius of the (enemy) core is destroyed upon death. Used for campaign maps. */
public boolean coreDestroyClear = false;
/** If true, banned blocks are hidden from the build menu. */
public boolean hideBannedBlocks = false;
/** If true, most blocks (including environmental walls) can be deconstructed. This is only meant to be used internally in sandbox/test maps. */
public boolean allowEnvironmentDeconstruct = false;
/** If true, buildings will be constructed instantly, with no limit on blocks placed per second. This is highly experimental and may cause lag! */
public boolean instantBuild = false;
/** If true, bannedBlocks becomes a whitelist. */
public boolean blockWhitelist = false;
/** If true, bannedUnits becomes a whitelist. */
public boolean unitWhitelist = false;
/** Radius around enemy wave drop zones.*/
public float dropZoneRadius = 300f;
/** Time between waves in ticks. */
public float waveSpacing = 2 * Time.toMinutes;
/** Starting wave spacing; if <=0, uses waveSpacing * 2. */
public float initialWaveSpacing = 0f;
/** Wave after which the player 'wins'. Use a value <= 0 to disable. */
public int winWave = 0;
/** Base unit cap. Can still be increased by blocks. */
public int unitCap = 0;
/** Environment drag multiplier. */
public float dragMultiplier = 1f;
/** Environmental flags that dictate visuals & how blocks function. */
public int env = Vars.defaultEnv;
/** Attributes of the environment. */
public Attributes attributes = new Attributes();
/** Sector for saves that have them. */
public @Nullable Sector sector;
/** Spawn layout. */
public Seq<SpawnGroup> spawns = new Seq<>();
/** Starting items put in cores. */
public Seq<ItemStack> loadout = ItemStack.list(Items.copper, 100);
/** Weather events that occur here. */
public Seq<WeatherEntry> weather = new Seq<>(1);
/** Blocks that cannot be placed. */
public ObjectSet<Block> bannedBlocks = new ObjectSet<>();
/** Units that cannot be built. */
public ObjectSet<UnitType> bannedUnits = new ObjectSet<>();
/** Reveals blocks normally hidden by build visibility. */
public ObjectSet<Block> revealedBlocks = new ObjectSet<>();
/** Unlocked content names. Only used in multiplayer when the campaign is enabled. */
public ObjectSet<String> researched = new ObjectSet<>();
/** Block containing these items as requirements are hidden. */
public ObjectSet<Item> hiddenBuildItems = Items.erekirOnlyItems.asSet();
/** In-map objective executor. */
public MapObjectives objectives = new MapObjectives();
/** Flags set by objectives. Used in world processors. */
public ObjectSet<String> objectiveFlags = new ObjectSet<>();
/** If true, fog of war is enabled. Enemy units and buildings are hidden unless in radar view. */
public boolean fog = false;
/** If fog = true, this is whether static (black) fog is enabled. */
public boolean staticFog = true;
/** Color for static, undiscovered fog of war areas. */
public Color staticColor = new Color(0f, 0f, 0f, 1f);
/** Color for discovered but un-monitored fog of war areas. */
public Color dynamicColor = new Color(0f, 0f, 0f, 0.5f);
/** Whether ambient lighting is enabled. */
public boolean lighting = false;
/** Ambient light color, used when lighting is enabled. */
public Color ambientLight = new Color(0.01f, 0.01f, 0.04f, 0.99f);
/** team of the player by default. */
public Team defaultTeam = Team.sharded;
/** team of the enemy in waves/sectors. */
public Team waveTeam = Team.crux;
/** color of clouds that is displayed when the player is landing */
public Color cloudColor = new Color(0f, 0f, 0f, 0f);
/** name of the custom mode that this ruleset describes, or null. */
public @Nullable String modeName;
/** Mission string displayed instead of wave/core counter. Null to disable. */
public @Nullable String mission;
/** Whether cores incinerate items when full, just like in the campaign. */
public boolean coreIncinerates = false;
/** If false, borders fade out into darkness. Only use with custom backgrounds!*/
public boolean borderDarkness = true;
/** If true, the map play area is cropped based on the rectangle below. */
public boolean limitMapArea = false;
/** Map area limit rectangle. */
public int limitX, limitY, limitWidth = 1, limitHeight = 1;
/** If true, blocks outside the map area are disabled. */
public boolean disableOutsideArea = true;
/** special tags for additional info. */
public StringMap tags = new StringMap();
/** Name of callback to call for background rendering in mods; see Renderer#addCustomBackground. Runs last. */
public @Nullable String customBackgroundCallback;
/** path to background texture with extension (e.g. "sprites/space.png")*/
public @Nullable String backgroundTexture;
/** background texture move speed scaling - bigger numbers mean slower movement. 0 to disable. */
public float backgroundSpeed = 27000f;
/** background texture scaling factor */
public float backgroundScl = 1f;
/** background UV offsets */
public float backgroundOffsetX = 0.1f, backgroundOffsetY = 0.1f;
/** Parameters for planet rendered in the background. Cannot be changed once a map is loaded. */
public @Nullable PlanetParams planetBackground;
/** Rules from this planet are applied. If it's {@code sun}, mixed tech is enabled. */
public Planet planet = Planets.serpulo;
/** Copies this ruleset exactly. Not efficient at all, do not use often. */
public Rules copy(){
return JsonIO.copy(this);
}
/** Returns the gamemode that best fits these rules. */
public Gamemode mode(){
if(pvp){
return Gamemode.pvp;
}else if(editor){
return Gamemode.editor;
}else if(attackMode){
return Gamemode.attack;
}else if(infiniteResources){
return Gamemode.sandbox;
}else{
return Gamemode.survival;
}
}
public boolean hasEnv(int env){
return (this.env & env) != 0;
}
public float unitBuildSpeed(Team team){
return unitBuildSpeedMultiplier * teams.get(team).unitBuildSpeedMultiplier;
}
public float unitCost(Team team){
return unitCostMultiplier * teams.get(team).unitCostMultiplier;
}
public float unitDamage(Team team){
return unitDamageMultiplier * teams.get(team).unitDamageMultiplier;
}
public float unitHealth(Team team){
//a 0 here would be a very bad idea.
return Math.max(unitHealthMultiplier * teams.get(team).unitHealthMultiplier, 0.000001f);
}
public float unitCrashDamage(Team team){
return unitDamage(team) * unitCrashDamageMultiplier * teams.get(team).unitCrashDamageMultiplier;
}
public float blockHealth(Team team){
return blockHealthMultiplier * teams.get(team).blockHealthMultiplier;
}
public float blockDamage(Team team){
return blockDamageMultiplier * teams.get(team).blockDamageMultiplier;
}
public float buildSpeed(Team team){
return buildSpeedMultiplier * teams.get(team).buildSpeedMultiplier;
}
public boolean isBanned(Block block){
return blockWhitelist != bannedBlocks.contains(block);
}
public boolean isBanned(UnitType unit){
return unitWhitelist != bannedUnits.contains(unit);
}
/** A team-specific ruleset. */
public static class TeamRule{
/** Whether, when AI is enabled, ships should be spawned from the core. TODO remove / unnecessary? */
public boolean aiCoreSpawn = true;
/** If true, blocks don't require power or resources. */
public boolean cheat;
/** If true, resources are not consumed when building. */
public boolean infiniteResources;
/** If true, this team has infinite unit ammo. */
public boolean infiniteAmmo;
/** AI that builds random schematics. */
public boolean buildAi;
/** Tier of builder AI. [0, 1] */
public float buildAiTier = 1f;
/** Enables "RTS" unit AI. */
public boolean rtsAi;
/** Minimum size of attack squads. */
public int rtsMinSquad = 4;
/** Maximum size of attack squads. */
public int rtsMaxSquad = 1000;
/** Minimum "advantage" needed for a squad to attack. Higher -> more cautious. */
public float rtsMinWeight = 1.2f;
/** How fast unit factories build units. */
public float unitBuildSpeedMultiplier = 1f;
/** How much damage units deal. */
public float unitDamageMultiplier = 1f;
/** How much damage unit crash damage deals. (Compounds with unitDamageMultiplier) */
public float unitCrashDamageMultiplier = 1f;
/** Multiplier of resources that units take to build. */
public float unitCostMultiplier = 1f;
/** How much health units start with. */
public float unitHealthMultiplier = 1f;
/** How much health blocks start with. */
public float blockHealthMultiplier = 1f;
/** How much damage blocks (turrets) deal. */
public float blockDamageMultiplier = 1f;
/** Multiplier for building speed. */
public float buildSpeedMultiplier = 1f;
//build cost disabled due to technical complexity
}
/** A simple map for storing TeamRules in an efficient way without hashing. */
public static class TeamRules implements JsonSerializable{
final TeamRule[] values = new TeamRule[Team.all.length];
public TeamRule get(Team team){
TeamRule out = values[team.id];
return out == null ? (values[team.id] = new TeamRule()) : out;
}
@Override
public void write(Json json){
for(Team team : Team.all){
if(values[team.id] != null){
json.writeValue(team.id + "", values[team.id], TeamRule.class);
}
}
}
@Override
public void read(Json json, JsonValue jsonData){
for(JsonValue value : jsonData){
values[Integer.parseInt(value.name)] = json.readValue(TeamRule.class, value);
}
}
}
}
| Anuken/Mindustry | core/src/mindustry/game/Rules.java | 4,161 | /** Radius around enemy wave drop zones.*/ | block_comment | nl | package mindustry.game;
import arc.graphics.*;
import arc.struct.*;
import arc.util.*;
import arc.util.serialization.*;
import arc.util.serialization.Json.*;
import mindustry.*;
import mindustry.content.*;
import mindustry.graphics.g3d.*;
import mindustry.io.*;
import mindustry.type.*;
import mindustry.type.Weather.*;
import mindustry.world.*;
import mindustry.world.blocks.*;
/**
* Defines current rules on how the game should function.
* Does not store game state, just configuration.
*/
public class Rules{
/** Sandbox mode: Enables infinite resources, build range and build speed. */
public boolean infiniteResources;
/** Team-specific rules. */
public TeamRules teams = new TeamRules();
/** Whether the waves come automatically on a timer. If not, waves come when the play button is pressed. */
public boolean waveTimer = true;
/** Whether the waves can be manually summoned with the play button. */
public boolean waveSending = true;
/** Whether waves are spawnable at all. */
public boolean waves;
/** Whether the game objective is PvP. Note that this enables automatic hosting. */
public boolean pvp;
/** Whether is waiting for players enabled in PvP. */
public boolean pvpAutoPause = true;
/** Whether to pause the wave timer until all enemies are destroyed. */
public boolean waitEnemies = false;
/** Determines if gamemode is attack mode. */
public boolean attackMode = false;
/** Whether this is the editor gamemode. */
public boolean editor = false;
/** Whether blocks can be repaired by clicking them. */
public boolean derelictRepair = true;
/** Whether a gameover can happen at all. Set this to false to implement custom gameover conditions. */
public boolean canGameOver = true;
/** Whether cores change teams when they are destroyed. */
public boolean coreCapture = false;
/** Whether reactors can explode and damage other blocks. */
public boolean reactorExplosions = true;
/** Whether to allow manual unit control. */
public boolean possessionAllowed = true;
/** Whether schematics are allowed. */
public boolean schematicsAllowed = true;
/** Whether friendly explosions can occur and set fire/damage other blocks. */
public boolean damageExplosions = true;
/** Whether fire (and neoplasm spread) is enabled. */
public boolean fire = true;
/** Whether units use and require ammo. */
public boolean unitAmmo = false;
/** EXPERIMENTAL! If true, blocks will update in units and share power. */
public boolean unitPayloadUpdate = false;
/** If true, units' payloads are destroy()ed when the unit is destroyed. */
public boolean unitPayloadsExplode = false;
/** Whether cores add to unit limit */
public boolean unitCapVariable = true;
/** If true, unit spawn points are shown. */
public boolean showSpawns = false;
/** Multiplies power output of solar panels. */
public float solarMultiplier = 1f;
/** How fast unit factories build units. */
public float unitBuildSpeedMultiplier = 1f;
/** Multiplier of resources that units take to build. */
public float unitCostMultiplier = 1f;
/** How much damage units deal. */
public float unitDamageMultiplier = 1f;
/** How much health units start with. */
public float unitHealthMultiplier = 1f;
/** How much damage unit crash damage deals. (Compounds with unitDamageMultiplier) */
public float unitCrashDamageMultiplier = 1f;
/** If true, ghost blocks will appear upon destruction, letting builder blocks/units rebuild them. */
public boolean ghostBlocks = true;
/** Whether to allow units to build with logic. */
public boolean logicUnitBuild = true;
/** If true, world processors no longer update. Used for testing. */
public boolean disableWorldProcessors = false;
/** How much health blocks start with. */
public float blockHealthMultiplier = 1f;
/** How much damage blocks (turrets) deal. */
public float blockDamageMultiplier = 1f;
/** Multiplier for buildings resource cost. */
public float buildCostMultiplier = 1f;
/** Multiplier for building speed. */
public float buildSpeedMultiplier = 1f;
/** Multiplier for percentage of materials refunded when deconstructing. */
public float deconstructRefundMultiplier = 0.5f;
/** No-build zone around enemy core radius. */
public float enemyCoreBuildRadius = 400f;
/** If true, no-build zones are calculated based on the closest core. */
public boolean polygonCoreProtection = false;
/** If true, blocks cannot be placed near blocks that are near the enemy team.*/
public boolean placeRangeCheck = false;
/** If true, dead teams in PvP automatically have their blocks & units converted to derelict upon death. */
public boolean cleanupDeadTeams = true;
/** If true, items can only be deposited in the core. */
public boolean onlyDepositCore = false;
/** If true, every enemy block in the radius of the (enemy) core is destroyed upon death. Used for campaign maps. */
public boolean coreDestroyClear = false;
/** If true, banned blocks are hidden from the build menu. */
public boolean hideBannedBlocks = false;
/** If true, most blocks (including environmental walls) can be deconstructed. This is only meant to be used internally in sandbox/test maps. */
public boolean allowEnvironmentDeconstruct = false;
/** If true, buildings will be constructed instantly, with no limit on blocks placed per second. This is highly experimental and may cause lag! */
public boolean instantBuild = false;
/** If true, bannedBlocks becomes a whitelist. */
public boolean blockWhitelist = false;
/** If true, bannedUnits becomes a whitelist. */
public boolean unitWhitelist = false;
/** Radius around enemy<SUF>*/
public float dropZoneRadius = 300f;
/** Time between waves in ticks. */
public float waveSpacing = 2 * Time.toMinutes;
/** Starting wave spacing; if <=0, uses waveSpacing * 2. */
public float initialWaveSpacing = 0f;
/** Wave after which the player 'wins'. Use a value <= 0 to disable. */
public int winWave = 0;
/** Base unit cap. Can still be increased by blocks. */
public int unitCap = 0;
/** Environment drag multiplier. */
public float dragMultiplier = 1f;
/** Environmental flags that dictate visuals & how blocks function. */
public int env = Vars.defaultEnv;
/** Attributes of the environment. */
public Attributes attributes = new Attributes();
/** Sector for saves that have them. */
public @Nullable Sector sector;
/** Spawn layout. */
public Seq<SpawnGroup> spawns = new Seq<>();
/** Starting items put in cores. */
public Seq<ItemStack> loadout = ItemStack.list(Items.copper, 100);
/** Weather events that occur here. */
public Seq<WeatherEntry> weather = new Seq<>(1);
/** Blocks that cannot be placed. */
public ObjectSet<Block> bannedBlocks = new ObjectSet<>();
/** Units that cannot be built. */
public ObjectSet<UnitType> bannedUnits = new ObjectSet<>();
/** Reveals blocks normally hidden by build visibility. */
public ObjectSet<Block> revealedBlocks = new ObjectSet<>();
/** Unlocked content names. Only used in multiplayer when the campaign is enabled. */
public ObjectSet<String> researched = new ObjectSet<>();
/** Block containing these items as requirements are hidden. */
public ObjectSet<Item> hiddenBuildItems = Items.erekirOnlyItems.asSet();
/** In-map objective executor. */
public MapObjectives objectives = new MapObjectives();
/** Flags set by objectives. Used in world processors. */
public ObjectSet<String> objectiveFlags = new ObjectSet<>();
/** If true, fog of war is enabled. Enemy units and buildings are hidden unless in radar view. */
public boolean fog = false;
/** If fog = true, this is whether static (black) fog is enabled. */
public boolean staticFog = true;
/** Color for static, undiscovered fog of war areas. */
public Color staticColor = new Color(0f, 0f, 0f, 1f);
/** Color for discovered but un-monitored fog of war areas. */
public Color dynamicColor = new Color(0f, 0f, 0f, 0.5f);
/** Whether ambient lighting is enabled. */
public boolean lighting = false;
/** Ambient light color, used when lighting is enabled. */
public Color ambientLight = new Color(0.01f, 0.01f, 0.04f, 0.99f);
/** team of the player by default. */
public Team defaultTeam = Team.sharded;
/** team of the enemy in waves/sectors. */
public Team waveTeam = Team.crux;
/** color of clouds that is displayed when the player is landing */
public Color cloudColor = new Color(0f, 0f, 0f, 0f);
/** name of the custom mode that this ruleset describes, or null. */
public @Nullable String modeName;
/** Mission string displayed instead of wave/core counter. Null to disable. */
public @Nullable String mission;
/** Whether cores incinerate items when full, just like in the campaign. */
public boolean coreIncinerates = false;
/** If false, borders fade out into darkness. Only use with custom backgrounds!*/
public boolean borderDarkness = true;
/** If true, the map play area is cropped based on the rectangle below. */
public boolean limitMapArea = false;
/** Map area limit rectangle. */
public int limitX, limitY, limitWidth = 1, limitHeight = 1;
/** If true, blocks outside the map area are disabled. */
public boolean disableOutsideArea = true;
/** special tags for additional info. */
public StringMap tags = new StringMap();
/** Name of callback to call for background rendering in mods; see Renderer#addCustomBackground. Runs last. */
public @Nullable String customBackgroundCallback;
/** path to background texture with extension (e.g. "sprites/space.png")*/
public @Nullable String backgroundTexture;
/** background texture move speed scaling - bigger numbers mean slower movement. 0 to disable. */
public float backgroundSpeed = 27000f;
/** background texture scaling factor */
public float backgroundScl = 1f;
/** background UV offsets */
public float backgroundOffsetX = 0.1f, backgroundOffsetY = 0.1f;
/** Parameters for planet rendered in the background. Cannot be changed once a map is loaded. */
public @Nullable PlanetParams planetBackground;
/** Rules from this planet are applied. If it's {@code sun}, mixed tech is enabled. */
public Planet planet = Planets.serpulo;
/** Copies this ruleset exactly. Not efficient at all, do not use often. */
public Rules copy(){
return JsonIO.copy(this);
}
/** Returns the gamemode that best fits these rules. */
public Gamemode mode(){
if(pvp){
return Gamemode.pvp;
}else if(editor){
return Gamemode.editor;
}else if(attackMode){
return Gamemode.attack;
}else if(infiniteResources){
return Gamemode.sandbox;
}else{
return Gamemode.survival;
}
}
public boolean hasEnv(int env){
return (this.env & env) != 0;
}
public float unitBuildSpeed(Team team){
return unitBuildSpeedMultiplier * teams.get(team).unitBuildSpeedMultiplier;
}
public float unitCost(Team team){
return unitCostMultiplier * teams.get(team).unitCostMultiplier;
}
public float unitDamage(Team team){
return unitDamageMultiplier * teams.get(team).unitDamageMultiplier;
}
public float unitHealth(Team team){
//a 0 here would be a very bad idea.
return Math.max(unitHealthMultiplier * teams.get(team).unitHealthMultiplier, 0.000001f);
}
public float unitCrashDamage(Team team){
return unitDamage(team) * unitCrashDamageMultiplier * teams.get(team).unitCrashDamageMultiplier;
}
public float blockHealth(Team team){
return blockHealthMultiplier * teams.get(team).blockHealthMultiplier;
}
public float blockDamage(Team team){
return blockDamageMultiplier * teams.get(team).blockDamageMultiplier;
}
public float buildSpeed(Team team){
return buildSpeedMultiplier * teams.get(team).buildSpeedMultiplier;
}
public boolean isBanned(Block block){
return blockWhitelist != bannedBlocks.contains(block);
}
public boolean isBanned(UnitType unit){
return unitWhitelist != bannedUnits.contains(unit);
}
/** A team-specific ruleset. */
public static class TeamRule{
/** Whether, when AI is enabled, ships should be spawned from the core. TODO remove / unnecessary? */
public boolean aiCoreSpawn = true;
/** If true, blocks don't require power or resources. */
public boolean cheat;
/** If true, resources are not consumed when building. */
public boolean infiniteResources;
/** If true, this team has infinite unit ammo. */
public boolean infiniteAmmo;
/** AI that builds random schematics. */
public boolean buildAi;
/** Tier of builder AI. [0, 1] */
public float buildAiTier = 1f;
/** Enables "RTS" unit AI. */
public boolean rtsAi;
/** Minimum size of attack squads. */
public int rtsMinSquad = 4;
/** Maximum size of attack squads. */
public int rtsMaxSquad = 1000;
/** Minimum "advantage" needed for a squad to attack. Higher -> more cautious. */
public float rtsMinWeight = 1.2f;
/** How fast unit factories build units. */
public float unitBuildSpeedMultiplier = 1f;
/** How much damage units deal. */
public float unitDamageMultiplier = 1f;
/** How much damage unit crash damage deals. (Compounds with unitDamageMultiplier) */
public float unitCrashDamageMultiplier = 1f;
/** Multiplier of resources that units take to build. */
public float unitCostMultiplier = 1f;
/** How much health units start with. */
public float unitHealthMultiplier = 1f;
/** How much health blocks start with. */
public float blockHealthMultiplier = 1f;
/** How much damage blocks (turrets) deal. */
public float blockDamageMultiplier = 1f;
/** Multiplier for building speed. */
public float buildSpeedMultiplier = 1f;
//build cost disabled due to technical complexity
}
/** A simple map for storing TeamRules in an efficient way without hashing. */
public static class TeamRules implements JsonSerializable{
final TeamRule[] values = new TeamRule[Team.all.length];
public TeamRule get(Team team){
TeamRule out = values[team.id];
return out == null ? (values[team.id] = new TeamRule()) : out;
}
@Override
public void write(Json json){
for(Team team : Team.all){
if(values[team.id] != null){
json.writeValue(team.id + "", values[team.id], TeamRule.class);
}
}
}
@Override
public void read(Json json, JsonValue jsonData){
for(JsonValue value : jsonData){
values[Integer.parseInt(value.name)] = json.readValue(TeamRule.class, value);
}
}
}
}
|
169888_6 | public class E_Combining_Bonus {
public static void main(String[] args) {
// Hieronder zie je een array. We gaan arrays later behandelen, voor nu hoef je maar 3 dingen te weten.
// 1. De array is een lijstje van nummers
// 2. Je kunt de lengte van een Array opvragen met de length property (numbers.length)
// 3. Je kunt een individueel element ophalen met de index (numbers[0] == 4, numbers[1] == 3)
int[] numbers = {7, 4, 1, 67, 2, 4, 6, 2, 345, 5, 52, 1, 2415, 7, 5, 178, 14, 4};
//
// Combination 1
//
// implementeer een forloop die alle even nummers print. Je gebruikt hiervoor ook een if statement
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
System.out.println(numbers[i]);
}
}
//
// Combination 2
//
// Implementeer een whileloop de nummers in de lijst optelt tot het resultaat groter is dan 400. Bonus, zorg ook dat de index nooit groter kan worden dan de lengte van de array.
// Je hebt ook een index nodig voor de array (int index = 0;) en een accumulator voor het resultaat (int result = 0;). Deze index en accumulator kun je in de while loop muteren.
int index = 0;
int accumulator = 0;
//add while
while (index < numbers.length && accumulator <= 400) {
accumulator += numbers[index];
}
System.out.println(accumulator);
}
}
| Aphelion-im/EdHub-Programmeren-met-Java-opdrachten | H3.5 - Controlflow-constructies/backend-java-controlflow/src/main/java/E_Combining_Bonus.java | 482 | // Je hebt ook een index nodig voor de array (int index = 0;) en een accumulator voor het resultaat (int result = 0;). Deze index en accumulator kun je in de while loop muteren. | line_comment | nl | public class E_Combining_Bonus {
public static void main(String[] args) {
// Hieronder zie je een array. We gaan arrays later behandelen, voor nu hoef je maar 3 dingen te weten.
// 1. De array is een lijstje van nummers
// 2. Je kunt de lengte van een Array opvragen met de length property (numbers.length)
// 3. Je kunt een individueel element ophalen met de index (numbers[0] == 4, numbers[1] == 3)
int[] numbers = {7, 4, 1, 67, 2, 4, 6, 2, 345, 5, 52, 1, 2415, 7, 5, 178, 14, 4};
//
// Combination 1
//
// implementeer een forloop die alle even nummers print. Je gebruikt hiervoor ook een if statement
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
System.out.println(numbers[i]);
}
}
//
// Combination 2
//
// Implementeer een whileloop de nummers in de lijst optelt tot het resultaat groter is dan 400. Bonus, zorg ook dat de index nooit groter kan worden dan de lengte van de array.
// Je hebt<SUF>
int index = 0;
int accumulator = 0;
//add while
while (index < numbers.length && accumulator <= 400) {
accumulator += numbers[index];
}
System.out.println(accumulator);
}
}
|
30162_19 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// @RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class TelevisionsController {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
// Show all televisions
@GetMapping("/televisions")
public ResponseEntity<Object> getAllTelevisions() { // Of ResponseEntity<String>
// return "Televisions"; werkt ook
// return ResponseEntity.ok(televisionDatabase);
return new ResponseEntity<>(televisionDatabase, HttpStatus.OK); // 200 OK
}
// Show 1 television
@GetMapping("televisions/{id}")
public ResponseEntity<Object> getTelevision(@PathVariable("id") int id) { // Verschil met: @PathVariable int id?
// return ResponseEntity.ok("television with id: " + id);
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return new ResponseEntity<>(televisionDatabase.get(id), HttpStatus.OK);
}
// Post/create 1 television
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) { // Of ResponseEntity<Object>
// return ResponseEntity.created(null).body("television"); - Oude manier van noteren?
// Bonus bonus: check voor 20 letters:
if (television.length() > 20) {
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
// return ResponseEntity.created(null).body(television);
return new ResponseEntity<>("Television: " + television + " added.", HttpStatus.CREATED); // 201
}
}
// Update television
@PutMapping("/televisions/{id}")
public ResponseEntity<Object> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if (televisionDatabase.isEmpty() || id > televisionDatabase.size()) {
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
// return ResponseEntity.noContent().build();
return new ResponseEntity<>(television + " with id#" + id + " updated!", HttpStatus.OK);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null); // Ipv remove()? Geeft een entry met null in de ArrayList
// televisionDatabase.remove(id);
// return new ResponseEntity<>("deleted", HttpStatus.NO_CONTENT); // Met 204 No Content kun je geen bericht mee sturen
return new ResponseEntity<>("Television: " + id + " deleted.", HttpStatus.GONE); // 410 Gone
}
} | Aphelion-im/Les-10-uitwerking-opdracht-backend-spring-boot-tech-it-easy-controller | src/main/java/nl/novi/techiteasy/controllers/TelevisionsController.java | 1,170 | // Return een 204 status | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// @RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class TelevisionsController {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
// Show all televisions
@GetMapping("/televisions")
public ResponseEntity<Object> getAllTelevisions() { // Of ResponseEntity<String>
// return "Televisions"; werkt ook
// return ResponseEntity.ok(televisionDatabase);
return new ResponseEntity<>(televisionDatabase, HttpStatus.OK); // 200 OK
}
// Show 1 television
@GetMapping("televisions/{id}")
public ResponseEntity<Object> getTelevision(@PathVariable("id") int id) { // Verschil met: @PathVariable int id?
// return ResponseEntity.ok("television with id: " + id);
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return new ResponseEntity<>(televisionDatabase.get(id), HttpStatus.OK);
}
// Post/create 1 television
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) { // Of ResponseEntity<Object>
// return ResponseEntity.created(null).body("television"); - Oude manier van noteren?
// Bonus bonus: check voor 20 letters:
if (television.length() > 20) {
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
// return ResponseEntity.created(null).body(television);
return new ResponseEntity<>("Television: " + television + " added.", HttpStatus.CREATED); // 201
}
}
// Update television
@PutMapping("/televisions/{id}")
public ResponseEntity<Object> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if (televisionDatabase.isEmpty() || id > televisionDatabase.size()) {
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een<SUF>
// return ResponseEntity.noContent().build();
return new ResponseEntity<>(television + " with id#" + id + " updated!", HttpStatus.OK);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null); // Ipv remove()? Geeft een entry met null in de ArrayList
// televisionDatabase.remove(id);
// return new ResponseEntity<>("deleted", HttpStatus.NO_CONTENT); // Met 204 No Content kun je geen bericht mee sturen
return new ResponseEntity<>("Television: " + id + " deleted.", HttpStatus.GONE); // 410 Gone
}
} |
42201_14 | // RequestBody te gebruiken bij @PutMapping en @PostMapping
// Delete person by name & Search probleem: - Uitwerking met @RequestBody i.p.v. RequestParam, maar dat lukt niet in Postman
// Uitwerkingen: https://github.com/hogeschoolnovi/backend-spring-boot-lesopdracht-les10/blob/uitwerkingen/les10/src/main/java/com/example/les10/controller/PersonController.java
package nl.eliascc.les10.controller;
import nl.eliascc.les10.model.Person;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class PersonController {
private final List<Person> persons = new ArrayList<>();
public PersonController() { // Constructor. Maak een Person object aan en voeg deze toe aan de ArrayList persons
Person p = new Person();
p.name = "Pietje";
p.dob = LocalDate.of(1995, Month.AUGUST, 8);
p.gender = 'm';
this.persons.add(p);
}
// Waarschijnlijk kan deze notatie ook: @GetMapping("")
@GetMapping // Omdat de BaseURL al op /persons staat via de bovenstaande @RequestMapping, laat je deze leeg.
// Vraag de persons lijst op
public ResponseEntity<List<Person>> getPersons() { // ResponseEntity: Robert-Jan: "Een response entity is zeg maar een hulpmiddel om vanuit jouw code, jouw endpoint, iets te gaan retourneren naar de client. Het is een handige klasse/object om zowel een body terug te geven als ook een http status."
return new ResponseEntity<>(persons, HttpStatus.OK); // ResponseEntity<>(Body, HttpStatus.OK). HttpStatus.OK = 200 OK
}
@PostMapping
public ResponseEntity<Person> createPerson(@RequestBody Person p) { // @RequestBody - Wat er in Body JSON komt te staan: Person p. Wordt gebruikt voor POST-requests en PUT-requests om daadwerkelijk data mee te sturen. Deze annotatie stelt je dus in staat om complete objecten mee te sturen in een HTTP request. In Postman: Body > Raw > Json
persons.add(p);
return new ResponseEntity<>(p, HttpStatus.CREATED); // HttpStatus.CREATED. Geeft: 201 Created
}
// Update a person
@PutMapping("/{id}")
public ResponseEntity<Object> updatePerson(@RequestBody Person p, @PathVariable int id) { // @PathVariable - of long id - Om een specifiek item, met een specifiek id, ophalen uit de database. Postman: Zowel een param in de url als een Body
if (id >= 0 && id < persons.size()) {
persons.set(id, p); // ArrayList.set() --> Replaces value at given index with given value....
return new ResponseEntity<>(p, HttpStatus.OK);
} else {
return new ResponseEntity<>("Invalid ID", HttpStatus.NOT_FOUND); // HttpStatus.BAD_REQUEST. Postman geeft: 400 Bad request.
}
}
// Opdrachten Persons:
// GET method die de zoveelste persoon uit de lijst returned
@GetMapping("/{index}")
public ResponseEntity<Person> getPerson(@PathVariable int index) {
// Gebruik de ArrayList.get() methode om de Person uit de lijst te halen
if (index >= 0 && index < persons.size()) {
Person person = persons.get(index);
// return ResponseEntity.ok(person); // HTTPStatus 200 OK
return new ResponseEntity<>(person, HttpStatus.FOUND); // HTTPStatus 302 Found
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); // 404 Not found zonder Body bericht (null)
}
}
// Delete person with index#
@DeleteMapping("/{index}")
public ResponseEntity<Person> deletePerson(@PathVariable int index) {
if (index > 0 && index < persons.size()) {
persons.remove(index);
return new ResponseEntity<>(null, HttpStatus.NO_CONTENT); // 204 No content
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); // 404 Not found
}
// Delete person by name - Uitwerking met @RequestBody ipv RequestParam, maar dat lukt niet in Postman
// Kan een NullPointerException geven als een entry waarden met null heeft
@DeleteMapping()
public ResponseEntity<?> deletePerson(@RequestBody String name) { // <?> Waarschijnlijk een Optional: An Optional is a container that either has something in it or doesn't.
// Loop door de persons List heen.
for (Person p : persons) {
// Kijk of er een Person in de lijst staat met de gegeven naam
if (p.name.equals(name)) {
// Zo ja, verwijder deze persoon en return met HttpStatus 204
persons.remove(p);
return ResponseEntity.noContent().build();
// return ResponseEntity<>(null, HttpStatus.NO_CONTENT);
}
}
// Staat er geen Persoon met de gegeven naam in de List, return dan HttpStatus 404
// return ResponseEntity.notFound().build(); // Oude manier van noteren?
return new ResponseEntity<>("Person not found", HttpStatus.NOT_FOUND); // 404 Not found
}
//Extra. Hetzelfde probleem met RequestBody & RequestParam in Postman
@GetMapping("/search")
public ResponseEntity<List<Person>> getPersonsContaining(@RequestBody String name) { // @RequestBody --> @RequestParam
// Maak een Lijst waarin je de gevonden Persons kunt verzamelen
List<Person> aggregator = new ArrayList<>();
// Loop door de lijst om Persons waarvan de naam, of een gedeelte van de naam, overeenkomt met de parameter
for (Person p : persons) {
if (p.name.contains(name)) {
// Voeg de gevonden persoon toe aan de List
aggregator.add(p);
}
}
if (aggregator.isEmpty()) { // Arraylist.isEmpty(); True/False.
// return ResponseEntity.notFound().build();
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
// return ResponseEntity.ok(aggregator);
return new ResponseEntity<>(aggregator, HttpStatus.FOUND);
}
}
| Aphelion-im/Les-10-uitwerking-opdracht-persons | src/main/java/nl/eliascc/les10/controller/PersonController.java | 1,755 | // HttpStatus.BAD_REQUEST. Postman geeft: 400 Bad request. | line_comment | nl | // RequestBody te gebruiken bij @PutMapping en @PostMapping
// Delete person by name & Search probleem: - Uitwerking met @RequestBody i.p.v. RequestParam, maar dat lukt niet in Postman
// Uitwerkingen: https://github.com/hogeschoolnovi/backend-spring-boot-lesopdracht-les10/blob/uitwerkingen/les10/src/main/java/com/example/les10/controller/PersonController.java
package nl.eliascc.les10.controller;
import nl.eliascc.les10.model.Person;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class PersonController {
private final List<Person> persons = new ArrayList<>();
public PersonController() { // Constructor. Maak een Person object aan en voeg deze toe aan de ArrayList persons
Person p = new Person();
p.name = "Pietje";
p.dob = LocalDate.of(1995, Month.AUGUST, 8);
p.gender = 'm';
this.persons.add(p);
}
// Waarschijnlijk kan deze notatie ook: @GetMapping("")
@GetMapping // Omdat de BaseURL al op /persons staat via de bovenstaande @RequestMapping, laat je deze leeg.
// Vraag de persons lijst op
public ResponseEntity<List<Person>> getPersons() { // ResponseEntity: Robert-Jan: "Een response entity is zeg maar een hulpmiddel om vanuit jouw code, jouw endpoint, iets te gaan retourneren naar de client. Het is een handige klasse/object om zowel een body terug te geven als ook een http status."
return new ResponseEntity<>(persons, HttpStatus.OK); // ResponseEntity<>(Body, HttpStatus.OK). HttpStatus.OK = 200 OK
}
@PostMapping
public ResponseEntity<Person> createPerson(@RequestBody Person p) { // @RequestBody - Wat er in Body JSON komt te staan: Person p. Wordt gebruikt voor POST-requests en PUT-requests om daadwerkelijk data mee te sturen. Deze annotatie stelt je dus in staat om complete objecten mee te sturen in een HTTP request. In Postman: Body > Raw > Json
persons.add(p);
return new ResponseEntity<>(p, HttpStatus.CREATED); // HttpStatus.CREATED. Geeft: 201 Created
}
// Update a person
@PutMapping("/{id}")
public ResponseEntity<Object> updatePerson(@RequestBody Person p, @PathVariable int id) { // @PathVariable - of long id - Om een specifiek item, met een specifiek id, ophalen uit de database. Postman: Zowel een param in de url als een Body
if (id >= 0 && id < persons.size()) {
persons.set(id, p); // ArrayList.set() --> Replaces value at given index with given value....
return new ResponseEntity<>(p, HttpStatus.OK);
} else {
return new ResponseEntity<>("Invalid ID", HttpStatus.NOT_FOUND); // HttpStatus.BAD_REQUEST. Postman<SUF>
}
}
// Opdrachten Persons:
// GET method die de zoveelste persoon uit de lijst returned
@GetMapping("/{index}")
public ResponseEntity<Person> getPerson(@PathVariable int index) {
// Gebruik de ArrayList.get() methode om de Person uit de lijst te halen
if (index >= 0 && index < persons.size()) {
Person person = persons.get(index);
// return ResponseEntity.ok(person); // HTTPStatus 200 OK
return new ResponseEntity<>(person, HttpStatus.FOUND); // HTTPStatus 302 Found
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); // 404 Not found zonder Body bericht (null)
}
}
// Delete person with index#
@DeleteMapping("/{index}")
public ResponseEntity<Person> deletePerson(@PathVariable int index) {
if (index > 0 && index < persons.size()) {
persons.remove(index);
return new ResponseEntity<>(null, HttpStatus.NO_CONTENT); // 204 No content
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); // 404 Not found
}
// Delete person by name - Uitwerking met @RequestBody ipv RequestParam, maar dat lukt niet in Postman
// Kan een NullPointerException geven als een entry waarden met null heeft
@DeleteMapping()
public ResponseEntity<?> deletePerson(@RequestBody String name) { // <?> Waarschijnlijk een Optional: An Optional is a container that either has something in it or doesn't.
// Loop door de persons List heen.
for (Person p : persons) {
// Kijk of er een Person in de lijst staat met de gegeven naam
if (p.name.equals(name)) {
// Zo ja, verwijder deze persoon en return met HttpStatus 204
persons.remove(p);
return ResponseEntity.noContent().build();
// return ResponseEntity<>(null, HttpStatus.NO_CONTENT);
}
}
// Staat er geen Persoon met de gegeven naam in de List, return dan HttpStatus 404
// return ResponseEntity.notFound().build(); // Oude manier van noteren?
return new ResponseEntity<>("Person not found", HttpStatus.NOT_FOUND); // 404 Not found
}
//Extra. Hetzelfde probleem met RequestBody & RequestParam in Postman
@GetMapping("/search")
public ResponseEntity<List<Person>> getPersonsContaining(@RequestBody String name) { // @RequestBody --> @RequestParam
// Maak een Lijst waarin je de gevonden Persons kunt verzamelen
List<Person> aggregator = new ArrayList<>();
// Loop door de lijst om Persons waarvan de naam, of een gedeelte van de naam, overeenkomt met de parameter
for (Person p : persons) {
if (p.name.contains(name)) {
// Voeg de gevonden persoon toe aan de List
aggregator.add(p);
}
}
if (aggregator.isEmpty()) { // Arraylist.isEmpty(); True/False.
// return ResponseEntity.notFound().build();
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
// return ResponseEntity.ok(aggregator);
return new ResponseEntity<>(aggregator, HttpStatus.FOUND);
}
}
|
43508_11 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.models.Television;
import nl.novi.techiteasy.repositories.TelevisionRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@RestController
// @RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class TelevisionController {
// Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database.
// We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken.
private final TelevisionRepository televisionRepository;
// Constructor injection
public TelevisionController(TelevisionRepository televisionRepository) {
this.televisionRepository = televisionRepository;
}
// Show all televisions
@GetMapping("/televisions")
public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { // Of ResponseEntity<String>
List<Television> televisions;
// Als geen merk ingevuld, geen parameters, geef dan alle entries weer.
if (brand == null) {
// Vul de televisions lijst met alle televisions
televisions = televisionRepository.findAll();
// Als wel een merk ingevuld, geef dan alle televisies van dit merk weer
} else {
// Vul de televisions lijst met alle television die een bepaald merk hebben
televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand);
}
// return ResponseEntity.ok().body(televisions);
return new ResponseEntity<>(televisions, HttpStatus.OK); // 200 OK
}
// Geef 1 television met een specifieke id weer
@GetMapping("televisions/{id}")
public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Verschil met: @PathVariable int id?
// Haal de television met het gegeven id uit de database.
// Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty,
// maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit
// halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt.
// Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message.
Optional<Television> television = televisionRepository.findById(id);
// Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()"
if (television.isEmpty()) {
// Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message.
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode.
Television television1 = television.get(); // Haal het uit de optional en stop het in television1
// Return de television en een 200 status
return ResponseEntity.ok().body(television1);
}
}
// We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object.
@PostMapping("/televisions")
public ResponseEntity<Television> addTelevision(@RequestBody Television television) {
// Er vanuit gaande dat televisies direct in de applicatie worden toegevoegd als ze gekocht zijn.
television.setOriginalStock(LocalDate.now()); // Wat doet dit in de database?
// Sla de nieuwe tv in de database op met de save-methode van de repository
Television returnTelevision = televisionRepository.save(television);
// Hier moet eigen nog een URI uri response.
// Return de gemaakte television en een 201 status
return ResponseEntity.created(null).body(returnTelevision);
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) {
// Verwijder de television met het opgegeven id uit de database.
televisionRepository.deleteById(id);
// Return een 204 status
return ResponseEntity.noContent().build();
}
// Update a television
@PutMapping("/televisions/{id}")
public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
// Haal de aan te passen tv uit de database met het gegeven id
Optional<Television> television = televisionRepository.findById(id);
// Als eerste checken we of de aan te passen tv wel in de database bestaat.
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters.
// Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database.
Television television1 = television.get();
television1.setAvailableSize(newTelevision.getAvailableSize());
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setBluetooth(newTelevision.getBluetooth());
television1.setBrand(newTelevision.getBrand());
television1.setHdr(newTelevision.getHdr());
television1.setName(newTelevision.getName());
television1.setOriginalStock(newTelevision.getOriginalStock());
television1.setPrice(newTelevision.getPrice());
television1.setRefreshRate(newTelevision.getRefreshRate());
television1.setScreenQuality(newTelevision.getScreenQuality());
television1.setScreenType(newTelevision.getScreenType());
television1.setSmartTv(newTelevision.getSmartTv());
television1.setSold(newTelevision.getSold());
television1.setType(newTelevision.getType());
television1.setVoiceControl(newTelevision.getVoiceControl());
television1.setWifi(newTelevision.getWifi());
// Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten.
Television returnTelevision = televisionRepository.save(television1);
// Return de nieuwe versie van deze tv en een 200 code
return ResponseEntity.ok().body(returnTelevision);
}
}
// Televisie gedeeltelijk bijwerken
@PatchMapping("/televisions/{id}")
public ResponseEntity<Television> updatePartialTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
Optional<Television> television = televisionRepository.findById(id);
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Het verschil tussen een patch en een put methode is dat een put een compleet object update,
// waar een patch een gedeeltelijk object kan updaten.
// Zet alles in een null-check, om te voorkomen dat je perongelijk bestaande waardes overschrijft met null-waardes.
// Intellij heeft een handige postfix voor null-checks. Dit doe je door bijvoorbeeld "newTelevision.getBrand().notnull" te typen en dan op tab te drukken.
Television television1 = television.get();
if (newTelevision.getAmbiLight() != null) {
television1.setAmbiLight(newTelevision.getAmbiLight());
}
if (newTelevision.getAvailableSize() != null) {
television1.setAvailableSize(newTelevision.getAvailableSize());
}
if (newTelevision.getBluetooth()) {
television1.setBluetooth(newTelevision.getBluetooth());
}
if (newTelevision.getBrand() != null) {
television1.setBrand(newTelevision.getBrand());
}
if (newTelevision.getHdr() != null) {
television1.setHdr(newTelevision.getHdr());
}
if (newTelevision.getName() != null) {
television1.setName(newTelevision.getName());
}
if (newTelevision.getOriginalStock() != null) {
television1.setOriginalStock(newTelevision.getOriginalStock());
}
if (newTelevision.getPrice() != null) {
television1.setPrice(newTelevision.getPrice());
}
if (newTelevision.getRefreshRate() != null) {
television1.setRefreshRate(newTelevision.getRefreshRate());
}
if (newTelevision.getScreenQuality() != null) {
television1.setScreenQuality(newTelevision.getScreenQuality());
}
if (newTelevision.getScreenType() != null) {
television1.setScreenType(newTelevision.getScreenType());
}
if (newTelevision.getSmartTv() != null) {
television1.setSmartTv(newTelevision.getSmartTv());
}
if (newTelevision.getSold() != null) {
television1.setSold(newTelevision.getSold());
}
if (newTelevision.getType() != null) {
television1.setType(newTelevision.getType());
}
if (newTelevision.getVoiceControl() != null) {
television1.setVoiceControl(newTelevision.getVoiceControl());
}
if (newTelevision.getWifi() != null) {
television1.setWifi(newTelevision.getWifi());
}
Television returnTelevision = televisionRepository.save(television1);
return ResponseEntity.ok().body(returnTelevision);
}
}
} | Aphelion-im/Les-11-uitwerking-opdracht-backend-spring-boot-tech-it-easy-model | src/main/java/nl/novi/techiteasy/controllers/TelevisionController.java | 2,825 | // Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty, | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.models.Television;
import nl.novi.techiteasy.repositories.TelevisionRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@RestController
// @RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class TelevisionController {
// Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database.
// We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken.
private final TelevisionRepository televisionRepository;
// Constructor injection
public TelevisionController(TelevisionRepository televisionRepository) {
this.televisionRepository = televisionRepository;
}
// Show all televisions
@GetMapping("/televisions")
public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { // Of ResponseEntity<String>
List<Television> televisions;
// Als geen merk ingevuld, geen parameters, geef dan alle entries weer.
if (brand == null) {
// Vul de televisions lijst met alle televisions
televisions = televisionRepository.findAll();
// Als wel een merk ingevuld, geef dan alle televisies van dit merk weer
} else {
// Vul de televisions lijst met alle television die een bepaald merk hebben
televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand);
}
// return ResponseEntity.ok().body(televisions);
return new ResponseEntity<>(televisions, HttpStatus.OK); // 200 OK
}
// Geef 1 television met een specifieke id weer
@GetMapping("televisions/{id}")
public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Verschil met: @PathVariable int id?
// Haal de television met het gegeven id uit de database.
// Het Optional<SUF>
// maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit
// halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt.
// Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message.
Optional<Television> television = televisionRepository.findById(id);
// Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()"
if (television.isEmpty()) {
// Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message.
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode.
Television television1 = television.get(); // Haal het uit de optional en stop het in television1
// Return de television en een 200 status
return ResponseEntity.ok().body(television1);
}
}
// We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object.
@PostMapping("/televisions")
public ResponseEntity<Television> addTelevision(@RequestBody Television television) {
// Er vanuit gaande dat televisies direct in de applicatie worden toegevoegd als ze gekocht zijn.
television.setOriginalStock(LocalDate.now()); // Wat doet dit in de database?
// Sla de nieuwe tv in de database op met de save-methode van de repository
Television returnTelevision = televisionRepository.save(television);
// Hier moet eigen nog een URI uri response.
// Return de gemaakte television en een 201 status
return ResponseEntity.created(null).body(returnTelevision);
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) {
// Verwijder de television met het opgegeven id uit de database.
televisionRepository.deleteById(id);
// Return een 204 status
return ResponseEntity.noContent().build();
}
// Update a television
@PutMapping("/televisions/{id}")
public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
// Haal de aan te passen tv uit de database met het gegeven id
Optional<Television> television = televisionRepository.findById(id);
// Als eerste checken we of de aan te passen tv wel in de database bestaat.
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters.
// Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database.
Television television1 = television.get();
television1.setAvailableSize(newTelevision.getAvailableSize());
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setBluetooth(newTelevision.getBluetooth());
television1.setBrand(newTelevision.getBrand());
television1.setHdr(newTelevision.getHdr());
television1.setName(newTelevision.getName());
television1.setOriginalStock(newTelevision.getOriginalStock());
television1.setPrice(newTelevision.getPrice());
television1.setRefreshRate(newTelevision.getRefreshRate());
television1.setScreenQuality(newTelevision.getScreenQuality());
television1.setScreenType(newTelevision.getScreenType());
television1.setSmartTv(newTelevision.getSmartTv());
television1.setSold(newTelevision.getSold());
television1.setType(newTelevision.getType());
television1.setVoiceControl(newTelevision.getVoiceControl());
television1.setWifi(newTelevision.getWifi());
// Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten.
Television returnTelevision = televisionRepository.save(television1);
// Return de nieuwe versie van deze tv en een 200 code
return ResponseEntity.ok().body(returnTelevision);
}
}
// Televisie gedeeltelijk bijwerken
@PatchMapping("/televisions/{id}")
public ResponseEntity<Television> updatePartialTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
Optional<Television> television = televisionRepository.findById(id);
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Het verschil tussen een patch en een put methode is dat een put een compleet object update,
// waar een patch een gedeeltelijk object kan updaten.
// Zet alles in een null-check, om te voorkomen dat je perongelijk bestaande waardes overschrijft met null-waardes.
// Intellij heeft een handige postfix voor null-checks. Dit doe je door bijvoorbeeld "newTelevision.getBrand().notnull" te typen en dan op tab te drukken.
Television television1 = television.get();
if (newTelevision.getAmbiLight() != null) {
television1.setAmbiLight(newTelevision.getAmbiLight());
}
if (newTelevision.getAvailableSize() != null) {
television1.setAvailableSize(newTelevision.getAvailableSize());
}
if (newTelevision.getBluetooth()) {
television1.setBluetooth(newTelevision.getBluetooth());
}
if (newTelevision.getBrand() != null) {
television1.setBrand(newTelevision.getBrand());
}
if (newTelevision.getHdr() != null) {
television1.setHdr(newTelevision.getHdr());
}
if (newTelevision.getName() != null) {
television1.setName(newTelevision.getName());
}
if (newTelevision.getOriginalStock() != null) {
television1.setOriginalStock(newTelevision.getOriginalStock());
}
if (newTelevision.getPrice() != null) {
television1.setPrice(newTelevision.getPrice());
}
if (newTelevision.getRefreshRate() != null) {
television1.setRefreshRate(newTelevision.getRefreshRate());
}
if (newTelevision.getScreenQuality() != null) {
television1.setScreenQuality(newTelevision.getScreenQuality());
}
if (newTelevision.getScreenType() != null) {
television1.setScreenType(newTelevision.getScreenType());
}
if (newTelevision.getSmartTv() != null) {
television1.setSmartTv(newTelevision.getSmartTv());
}
if (newTelevision.getSold() != null) {
television1.setSold(newTelevision.getSold());
}
if (newTelevision.getType() != null) {
television1.setType(newTelevision.getType());
}
if (newTelevision.getVoiceControl() != null) {
television1.setVoiceControl(newTelevision.getVoiceControl());
}
if (newTelevision.getWifi() != null) {
television1.setWifi(newTelevision.getWifi());
}
Television returnTelevision = televisionRepository.save(television1);
return ResponseEntity.ok().body(returnTelevision);
}
}
} |
176589_1 | package nl.novi.les11docenten.models;
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDate;
@Entity // // Deze klasse kan vertaald worden naar een tabel in de database.
@Table(name = "teachers") // Vul je dit niet in, dan wordt de naam van de tabel hetzelfde als de naam van de klasse
@Data // Lombok: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor.
public class Teacher {
@Id // Maakt dat dit veld de primary key van de tabel wordt. Uniek. Not null
@GeneratedValue // Zorgt er voor dat Hibernate de waarde van ons id zelf bepaald én verhoogd.
private Long id; // Wordt bigint, NOT NULL, PRIMARY KEY
@Column(name = "first_name")
private String firstName; // Wordt first_name, varchar(255). In Postman: firstName
private String lastName;
private LocalDate dob;
// En alle Getters & Setters via (eventueel) Lombok
// Wel de benodigde Getters/Setters noteren ivm Postman volledige response van het JSON object.
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public LocalDate getDob() {
// return dob;
// }
//
// public void setDob(LocalDate dob) {
// this.dob = dob;
// }
}
| Aphelion-im/Les-11-uitwerking-opdracht-docenten | src/main/java/nl/novi/les11docenten/models/Teacher.java | 531 | // Vul je dit niet in, dan wordt de naam van de tabel hetzelfde als de naam van de klasse | line_comment | nl | package nl.novi.les11docenten.models;
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDate;
@Entity // // Deze klasse kan vertaald worden naar een tabel in de database.
@Table(name = "teachers") // Vul je<SUF>
@Data // Lombok: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor.
public class Teacher {
@Id // Maakt dat dit veld de primary key van de tabel wordt. Uniek. Not null
@GeneratedValue // Zorgt er voor dat Hibernate de waarde van ons id zelf bepaald én verhoogd.
private Long id; // Wordt bigint, NOT NULL, PRIMARY KEY
@Column(name = "first_name")
private String firstName; // Wordt first_name, varchar(255). In Postman: firstName
private String lastName;
private LocalDate dob;
// En alle Getters & Setters via (eventueel) Lombok
// Wel de benodigde Getters/Setters noteren ivm Postman volledige response van het JSON object.
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public LocalDate getDob() {
// return dob;
// }
//
// public void setDob(LocalDate dob) {
// this.dob = dob;
// }
}
|
24573_0 | package nl.novi.les11studenten.controllers;
import nl.novi.les11studenten.models.Student;
import nl.novi.les11studenten.repositories.StudentRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
/*
Om onze repository in onze controller te kunnen gebruiken, gebruiken we geen “new” keyword, maar laten we Spring
de juiste Bean vinden door middel van dependency injection.
Dependency injection is heel simpel. Wanneer we in onze controller gebruik willen maken van onze repository,
dan hoeven dat alleen maar aan te geven. We declareren een globale variabele en vullen die in, in de constructor.
Note: We kunnen dependencies ook injecteren zonder de constructor te gebruiken. Dit kun je doen door de @Autowired annotatie
te gebruiken boven de klasse variabele of boven de getter van die klassevariabele.
Constructor injection heeft echter de voorkeur, omdat je de klasse variabele dan "final” kunt maken.
Zo weet je zeker dat de repository (in dit geval) niet gaandeweg gewijzigd kan worden.
https://edhub.novi.nl/study/courses/319/content/12890 (Spring context en dependency injection)
*/
private final StudentRepository studentRepository;
// Lijkt er op dat dependency injection het meegeven van een object als een parameter in de constructor van een andere klasse is.
// To promote loose coupling
// Actual Constructor injection:
public StudentController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping
// findAll() hoort bij StudentRepository/JpaRepository en bijhorende methods
public ResponseEntity<List<Student>> getStudents() {
// return ResponseEntity.ok(studentRepository.findAll());
return new ResponseEntity<>(studentRepository.findAll(), HttpStatus.OK);
}
// Dit bevat nog geen validatie en NullPointerException beveiliging.
// Getters en setters vereist (Student.java) om een JSON object te posten en terug te krijgen!
// Bij elke ResponseEntity.created() een URI uri meegeven.
@PostMapping
public ResponseEntity<?> postStudent(@RequestBody Student student) { // Generic met <?> Wildcard data type. Yet unknown type.
studentRepository.save(student);
// Geeft: http://localhost:8080/students/1 in Postman: Headers > Location. Waar 1 is de id van de entry
URI uri = URI.create(ServletUriComponentsBuilder
.fromCurrentRequest().path("/" + student.getStudentNr()).toUriString());
// return ResponseEntity.ok().build(); // Stuurt niets terug qua body na posten in Postman
return ResponseEntity.created(uri).body(student);
}
// Via de Repository query methods:
// https://medium.com/@hashanlahiru6/all-about-query-methods-in-spring-data-jpa-52d74e5d2be7
@GetMapping("/fullname") // localhost:8080/students/fullname?query=b
public ResponseEntity<List<Student>> getStudentBySubstring(@RequestParam(name="query") String substring){
List<Student> studentList = studentRepository.findByFullNameContainingIgnoreCase(substring);
if(!studentList.isEmpty()){
return ResponseEntity.ok(studentList);
} else {
return ResponseEntity.notFound().build(); // Wat doet build()?
}
}
}
| Aphelion-im/Les-11-uitwerking-opdracht-studenten | src/main/java/nl/novi/les11studenten/controllers/StudentController.java | 977 | /*
Om onze repository in onze controller te kunnen gebruiken, gebruiken we geen “new” keyword, maar laten we Spring
de juiste Bean vinden door middel van dependency injection.
Dependency injection is heel simpel. Wanneer we in onze controller gebruik willen maken van onze repository,
dan hoeven dat alleen maar aan te geven. We declareren een globale variabele en vullen die in, in de constructor.
Note: We kunnen dependencies ook injecteren zonder de constructor te gebruiken. Dit kun je doen door de @Autowired annotatie
te gebruiken boven de klasse variabele of boven de getter van die klassevariabele.
Constructor injection heeft echter de voorkeur, omdat je de klasse variabele dan "final” kunt maken.
Zo weet je zeker dat de repository (in dit geval) niet gaandeweg gewijzigd kan worden.
https://edhub.novi.nl/study/courses/319/content/12890 (Spring context en dependency injection)
*/ | block_comment | nl | package nl.novi.les11studenten.controllers;
import nl.novi.les11studenten.models.Student;
import nl.novi.les11studenten.repositories.StudentRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
/*
Om onze repository<SUF>*/
private final StudentRepository studentRepository;
// Lijkt er op dat dependency injection het meegeven van een object als een parameter in de constructor van een andere klasse is.
// To promote loose coupling
// Actual Constructor injection:
public StudentController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping
// findAll() hoort bij StudentRepository/JpaRepository en bijhorende methods
public ResponseEntity<List<Student>> getStudents() {
// return ResponseEntity.ok(studentRepository.findAll());
return new ResponseEntity<>(studentRepository.findAll(), HttpStatus.OK);
}
// Dit bevat nog geen validatie en NullPointerException beveiliging.
// Getters en setters vereist (Student.java) om een JSON object te posten en terug te krijgen!
// Bij elke ResponseEntity.created() een URI uri meegeven.
@PostMapping
public ResponseEntity<?> postStudent(@RequestBody Student student) { // Generic met <?> Wildcard data type. Yet unknown type.
studentRepository.save(student);
// Geeft: http://localhost:8080/students/1 in Postman: Headers > Location. Waar 1 is de id van de entry
URI uri = URI.create(ServletUriComponentsBuilder
.fromCurrentRequest().path("/" + student.getStudentNr()).toUriString());
// return ResponseEntity.ok().build(); // Stuurt niets terug qua body na posten in Postman
return ResponseEntity.created(uri).body(student);
}
// Via de Repository query methods:
// https://medium.com/@hashanlahiru6/all-about-query-methods-in-spring-data-jpa-52d74e5d2be7
@GetMapping("/fullname") // localhost:8080/students/fullname?query=b
public ResponseEntity<List<Student>> getStudentBySubstring(@RequestParam(name="query") String substring){
List<Student> studentList = studentRepository.findByFullNameContainingIgnoreCase(substring);
if(!studentList.isEmpty()){
return ResponseEntity.ok(studentList);
} else {
return ResponseEntity.notFound().build(); // Wat doet build()?
}
}
}
|
30841_5 | package com.example.les12.service;
import com.example.les12.dto.TeacherDto;
import com.example.les12.exception.DuplicateResourceException;
import com.example.les12.exception.ResourceNotFoundException;
import com.example.les12.model.Teacher;
import com.example.les12.repository.TeacherRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TeacherService {
// Service gekoppeld aan Repository. Controller <-> Service <-> Repository
// Controller gekoppeld aan Service
// Model overgenomen door Dto
private final TeacherRepository teacherRepository;
public TeacherService(TeacherRepository teacherRepository) {
this.teacherRepository = teacherRepository;
}
// Moet eigenlijk met een Optional
public TeacherDto getTeacher(Long id) {
Teacher teacher = teacherRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Teacher not found"));
TeacherDto teacherDto = new TeacherDto();
teacherDto.id = teacher.getId();
teacherDto.firstName = teacher.getFirstName();
teacherDto.lastName = teacher.getLastName();
teacherDto.dob = teacher.getDob();
teacherDto.salary = teacher.getSalary();
return teacherDto;
}
// Repos zit nu niet meer in de Controllers, maar in de Services
// Geen validatie beschikbaar (Dubbele namen of andere validatie)
public Long createTeacher(TeacherDto teacherDto) {
if (teacherRepository.existsByFirstNameIgnoreCaseAndLastNameIgnoreCase(teacherDto.firstName, teacherDto.lastName)) {
throw new DuplicateResourceException("This resource already exists!");
}
Teacher teacher = new Teacher();
teacher.setFirstName(teacherDto.firstName);
teacher.setLastName(teacherDto.lastName);
teacher.setDob(teacherDto.dob);
teacher.setSalary(teacherDto.salary);
teacherRepository.save(teacher);
return teacher.getId();
// teacherDto.id = teacher.getId();
// return teacherDto; Geeft com.example.les12.dto.TeacherDto@2a61bf3f in Postman
}
// Uit repo: https://github.com/robertjanelias/les12opdracht/blob/main/src/main/java/com/example/les11model/service/TeacherService.java
public List<TeacherDto> getTeachers() {
List<Teacher> teachers = teacherRepository.findAll(); // Er stond, met foutmelding: List<Teacher> teachers = repos.findAll();
List<TeacherDto> teacherDtos = new ArrayList<>();
for (Teacher teacher : teachers) {
TeacherDto tdto = new TeacherDto();
tdto.id = teacher.getId();
tdto.dob = teacher.getDob();
tdto.firstName = teacher.getFirstName();
tdto.lastName = teacher.getLastName();
tdto.salary = teacher.getSalary();
teacherDtos.add(tdto);
}
return teacherDtos;
}
}
| Aphelion-im/Les-12-uitwerking-opdracht-teacher-service | src/main/java/com/example/les12/service/TeacherService.java | 865 | // Geen validatie beschikbaar (Dubbele namen of andere validatie) | line_comment | nl | package com.example.les12.service;
import com.example.les12.dto.TeacherDto;
import com.example.les12.exception.DuplicateResourceException;
import com.example.les12.exception.ResourceNotFoundException;
import com.example.les12.model.Teacher;
import com.example.les12.repository.TeacherRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TeacherService {
// Service gekoppeld aan Repository. Controller <-> Service <-> Repository
// Controller gekoppeld aan Service
// Model overgenomen door Dto
private final TeacherRepository teacherRepository;
public TeacherService(TeacherRepository teacherRepository) {
this.teacherRepository = teacherRepository;
}
// Moet eigenlijk met een Optional
public TeacherDto getTeacher(Long id) {
Teacher teacher = teacherRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Teacher not found"));
TeacherDto teacherDto = new TeacherDto();
teacherDto.id = teacher.getId();
teacherDto.firstName = teacher.getFirstName();
teacherDto.lastName = teacher.getLastName();
teacherDto.dob = teacher.getDob();
teacherDto.salary = teacher.getSalary();
return teacherDto;
}
// Repos zit nu niet meer in de Controllers, maar in de Services
// Geen validatie<SUF>
public Long createTeacher(TeacherDto teacherDto) {
if (teacherRepository.existsByFirstNameIgnoreCaseAndLastNameIgnoreCase(teacherDto.firstName, teacherDto.lastName)) {
throw new DuplicateResourceException("This resource already exists!");
}
Teacher teacher = new Teacher();
teacher.setFirstName(teacherDto.firstName);
teacher.setLastName(teacherDto.lastName);
teacher.setDob(teacherDto.dob);
teacher.setSalary(teacherDto.salary);
teacherRepository.save(teacher);
return teacher.getId();
// teacherDto.id = teacher.getId();
// return teacherDto; Geeft com.example.les12.dto.TeacherDto@2a61bf3f in Postman
}
// Uit repo: https://github.com/robertjanelias/les12opdracht/blob/main/src/main/java/com/example/les11model/service/TeacherService.java
public List<TeacherDto> getTeachers() {
List<Teacher> teachers = teacherRepository.findAll(); // Er stond, met foutmelding: List<Teacher> teachers = repos.findAll();
List<TeacherDto> teacherDtos = new ArrayList<>();
for (Teacher teacher : teachers) {
TeacherDto tdto = new TeacherDto();
tdto.id = teacher.getId();
tdto.dob = teacher.getDob();
tdto.firstName = teacher.getFirstName();
tdto.lastName = teacher.getLastName();
tdto.salary = teacher.getSalary();
teacherDtos.add(tdto);
}
return teacherDtos;
}
}
|
68664_0 | package nl.novi.techiteasy1121.services;
import nl.novi.techiteasy1121.Dtos.TelevisionDto;
import nl.novi.techiteasy1121.Dtos.TelevisionInputDto;
import nl.novi.techiteasy1121.exceptions.RecordNotFoundException;
import nl.novi.techiteasy1121.models.Television;
import nl.novi.techiteasy1121.repositories.TelevisionRepository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
// Zet de annotatie boven de klasse, zodat Spring het herkent en inleest als Service.
@Service
public class TelevisionService {
// We importeren de repository nu in de service in plaats van in de controller.
// dit mag met constructor injection of autowire.
private final TelevisionRepository televisionRepository;
public TelevisionService(TelevisionRepository televisionRepository) {
this.televisionRepository = televisionRepository;
}
// Vanuit de repository kunnen we een lijst van Televisions krijgen, maar de communicatie container tussen Service en
// Controller is de Dto. We moeten de Televisions dus vertalen naar TelevisionDtos. Dit moet een voor een, omdat
// de translateToDto() methode geen lijst accepteert als argument, dus gebruiken we een for-loop.
public List<TelevisionDto> getAllTelevisions() {
List<Television> tvList = televisionRepository.findAll();
List<TelevisionDto> tvDtoList = new ArrayList<>();
for (Television tv : tvList) {
TelevisionDto dto = transferToDto(tv);
tvDtoList.add(dto);
}
return tvDtoList;
}
// Vanuit de repository kunnen we een lijst van Televisions met een bepaalde brand krijgen, maar de communicatie
// container tussen Service en Controller is de Dto. We moeten de Televisions dus vertalen naar TelevisionDtos. Dit
// moet een voor een, omdat de translateToDto() methode geen lijst accepteert als argument, dus gebruiken we een for-loop.
public List<TelevisionDto> getAllTelevisionsByBrand(String brand) {
List<Television> tvList = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand);
List<TelevisionDto> tvDtoList = new ArrayList<>();
for (Television tv : tvList) {
TelevisionDto dto = transferToDto(tv);
tvDtoList.add(dto);
}
return tvDtoList;
}
// Deze methode is inhoudelijk hetzelfde als het was in de vorige opdracht. Wat veranderd is, is dat we nu checken
// op optional.isPresent in plaats van optional.isEmpty en we returnen een TelevisionDto in plaats van een Television.
public TelevisionDto getTelevisionById(Long id) {
Optional<Television> televisionOptional = televisionRepository.findById(id);
if (televisionOptional.isPresent()) {
Television tv = televisionOptional.get();
return transferToDto(tv);
} else {
throw new RecordNotFoundException("geen televisie gevonden");
}
}
// In deze methode moeten we twee keer een vertaalmethode toepassen.
// De eerste keer van dto naar televsion, omdat de parameter een dto is.
// De tweede keer van television naar dto, omdat de return waarde een dto is.
// !! Geeft internal server error als je bovenop een bestaande id probeert te posten. Na de error 500 telt het wel op naar de volgende id
public TelevisionDto addTelevision(TelevisionInputDto dto) {
Television tv = transferToTelevision(dto);
televisionRepository.save(tv);
return transferToDto(tv);
}
// Deze methode is inhoudelijk niet veranderd. Het is alleen verplaatst naar de Service laag.
public void deleteTelevision(@RequestBody Long id) {
televisionRepository.deleteById(id);
}
// Deze methode is inhoudelijk niet veranderd, alleen staat het nu in de Service laag en worden er Dto's en
// vertaal methodes gebruikt.
public TelevisionDto updateTelevision(Long id, TelevisionInputDto newTelevision) {
Optional<Television> televisionOptional = televisionRepository.findById(id);
if (televisionOptional.isPresent()) {
Television television1 = televisionOptional.get();
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setAvailableSize(newTelevision.getAvailableSize());
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setBluetooth(newTelevision.getBluetooth());
television1.setBrand(newTelevision.getBrand());
television1.setHdr(newTelevision.getHdr());
television1.setName(newTelevision.getName());
television1.setOriginalStock(newTelevision.getOriginalStock());
television1.setPrice(newTelevision.getPrice());
television1.setRefreshRate(newTelevision.getRefreshRate());
television1.setScreenQuality(newTelevision.getScreenQuality());
television1.setScreenType(newTelevision.getScreenType());
television1.setSmartTv(newTelevision.getSmartTv());
television1.setSold(newTelevision.getSold());
television1.setType(newTelevision.getType());
television1.setVoiceControl(newTelevision.getVoiceControl());
television1.setWifi(newTelevision.getWifi());
Television returnTelevision = televisionRepository.save(television1);
return transferToDto(returnTelevision);
} else {
throw new RecordNotFoundException("geen televisie gevonden"); // Naar Engels vertalen
}
}
// Dit is de vertaal methode van TelevisionInputDto naar Television.
public Television transferToTelevision(TelevisionInputDto dto) {
// Var keyword:
// We can declare any datatype with the var keyword. Type inference is used in var keyword in which it detects automatically
// the datatype of a variable based on the surrounding context.
var television = new Television();
television.setType(dto.getType());
television.setBrand(dto.getBrand());
television.setName(dto.getName());
television.setPrice(dto.getPrice());
television.setAvailableSize(dto.getAvailableSize());
television.setRefreshRate(dto.getRefreshRate());
television.setScreenType(dto.getScreenType());
television.setScreenQuality(dto.getScreenQuality());
television.setSmartTv(dto.getSmartTv());
television.setWifi(dto.getWifi());
television.setVoiceControl(dto.getVoiceControl());
television.setHdr(dto.getHdr());
television.setBluetooth(dto.getBluetooth());
television.setAmbiLight(dto.getAmbiLight());
television.setOriginalStock(dto.getOriginalStock());
television.setSold(dto.getSold());
return television;
}
// Dit is de vertaal methode van Television naar TelevisionDto
public TelevisionDto transferToDto(Television television) {
TelevisionDto dto = new TelevisionDto();
// Paul heeft hier nog validatie voor het geval het leeg is:
// if (car.getLicenseplate() != null) {
// autoDto.setLicenseplate(car.getLicenseplate());
// }
dto.setId(television.getId());
dto.setType(television.getType());
dto.setBrand(television.getBrand());
dto.setName(television.getName());
dto.setPrice(television.getPrice());
dto.setAvailableSize(television.getAvailableSize());
dto.setRefreshRate(television.getRefreshRate());
dto.setScreenType(television.getScreenType());
dto.setScreenQuality(television.getScreenQuality());
dto.setSmartTv(television.getWifi());
dto.setWifi(television.getWifi());
dto.setVoiceControl(television.getVoiceControl());
dto.setHdr(television.getHdr());
dto.setBluetooth(television.getBluetooth());
dto.setAmbiLight(television.getAmbiLight());
dto.setOriginalStock(television.getOriginalStock());
dto.setSold(television.getSold());
return dto;
}
}
| Aphelion-im/Les-12-uitwerking-opdracht-tech-it-easy-service-dto | src/main/java/nl/novi/techiteasy1121/services/TelevisionService.java | 2,434 | // Zet de annotatie boven de klasse, zodat Spring het herkent en inleest als Service. | line_comment | nl | package nl.novi.techiteasy1121.services;
import nl.novi.techiteasy1121.Dtos.TelevisionDto;
import nl.novi.techiteasy1121.Dtos.TelevisionInputDto;
import nl.novi.techiteasy1121.exceptions.RecordNotFoundException;
import nl.novi.techiteasy1121.models.Television;
import nl.novi.techiteasy1121.repositories.TelevisionRepository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
// Zet de<SUF>
@Service
public class TelevisionService {
// We importeren de repository nu in de service in plaats van in de controller.
// dit mag met constructor injection of autowire.
private final TelevisionRepository televisionRepository;
public TelevisionService(TelevisionRepository televisionRepository) {
this.televisionRepository = televisionRepository;
}
// Vanuit de repository kunnen we een lijst van Televisions krijgen, maar de communicatie container tussen Service en
// Controller is de Dto. We moeten de Televisions dus vertalen naar TelevisionDtos. Dit moet een voor een, omdat
// de translateToDto() methode geen lijst accepteert als argument, dus gebruiken we een for-loop.
public List<TelevisionDto> getAllTelevisions() {
List<Television> tvList = televisionRepository.findAll();
List<TelevisionDto> tvDtoList = new ArrayList<>();
for (Television tv : tvList) {
TelevisionDto dto = transferToDto(tv);
tvDtoList.add(dto);
}
return tvDtoList;
}
// Vanuit de repository kunnen we een lijst van Televisions met een bepaalde brand krijgen, maar de communicatie
// container tussen Service en Controller is de Dto. We moeten de Televisions dus vertalen naar TelevisionDtos. Dit
// moet een voor een, omdat de translateToDto() methode geen lijst accepteert als argument, dus gebruiken we een for-loop.
public List<TelevisionDto> getAllTelevisionsByBrand(String brand) {
List<Television> tvList = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand);
List<TelevisionDto> tvDtoList = new ArrayList<>();
for (Television tv : tvList) {
TelevisionDto dto = transferToDto(tv);
tvDtoList.add(dto);
}
return tvDtoList;
}
// Deze methode is inhoudelijk hetzelfde als het was in de vorige opdracht. Wat veranderd is, is dat we nu checken
// op optional.isPresent in plaats van optional.isEmpty en we returnen een TelevisionDto in plaats van een Television.
public TelevisionDto getTelevisionById(Long id) {
Optional<Television> televisionOptional = televisionRepository.findById(id);
if (televisionOptional.isPresent()) {
Television tv = televisionOptional.get();
return transferToDto(tv);
} else {
throw new RecordNotFoundException("geen televisie gevonden");
}
}
// In deze methode moeten we twee keer een vertaalmethode toepassen.
// De eerste keer van dto naar televsion, omdat de parameter een dto is.
// De tweede keer van television naar dto, omdat de return waarde een dto is.
// !! Geeft internal server error als je bovenop een bestaande id probeert te posten. Na de error 500 telt het wel op naar de volgende id
public TelevisionDto addTelevision(TelevisionInputDto dto) {
Television tv = transferToTelevision(dto);
televisionRepository.save(tv);
return transferToDto(tv);
}
// Deze methode is inhoudelijk niet veranderd. Het is alleen verplaatst naar de Service laag.
public void deleteTelevision(@RequestBody Long id) {
televisionRepository.deleteById(id);
}
// Deze methode is inhoudelijk niet veranderd, alleen staat het nu in de Service laag en worden er Dto's en
// vertaal methodes gebruikt.
public TelevisionDto updateTelevision(Long id, TelevisionInputDto newTelevision) {
Optional<Television> televisionOptional = televisionRepository.findById(id);
if (televisionOptional.isPresent()) {
Television television1 = televisionOptional.get();
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setAvailableSize(newTelevision.getAvailableSize());
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setBluetooth(newTelevision.getBluetooth());
television1.setBrand(newTelevision.getBrand());
television1.setHdr(newTelevision.getHdr());
television1.setName(newTelevision.getName());
television1.setOriginalStock(newTelevision.getOriginalStock());
television1.setPrice(newTelevision.getPrice());
television1.setRefreshRate(newTelevision.getRefreshRate());
television1.setScreenQuality(newTelevision.getScreenQuality());
television1.setScreenType(newTelevision.getScreenType());
television1.setSmartTv(newTelevision.getSmartTv());
television1.setSold(newTelevision.getSold());
television1.setType(newTelevision.getType());
television1.setVoiceControl(newTelevision.getVoiceControl());
television1.setWifi(newTelevision.getWifi());
Television returnTelevision = televisionRepository.save(television1);
return transferToDto(returnTelevision);
} else {
throw new RecordNotFoundException("geen televisie gevonden"); // Naar Engels vertalen
}
}
// Dit is de vertaal methode van TelevisionInputDto naar Television.
public Television transferToTelevision(TelevisionInputDto dto) {
// Var keyword:
// We can declare any datatype with the var keyword. Type inference is used in var keyword in which it detects automatically
// the datatype of a variable based on the surrounding context.
var television = new Television();
television.setType(dto.getType());
television.setBrand(dto.getBrand());
television.setName(dto.getName());
television.setPrice(dto.getPrice());
television.setAvailableSize(dto.getAvailableSize());
television.setRefreshRate(dto.getRefreshRate());
television.setScreenType(dto.getScreenType());
television.setScreenQuality(dto.getScreenQuality());
television.setSmartTv(dto.getSmartTv());
television.setWifi(dto.getWifi());
television.setVoiceControl(dto.getVoiceControl());
television.setHdr(dto.getHdr());
television.setBluetooth(dto.getBluetooth());
television.setAmbiLight(dto.getAmbiLight());
television.setOriginalStock(dto.getOriginalStock());
television.setSold(dto.getSold());
return television;
}
// Dit is de vertaal methode van Television naar TelevisionDto
public TelevisionDto transferToDto(Television television) {
TelevisionDto dto = new TelevisionDto();
// Paul heeft hier nog validatie voor het geval het leeg is:
// if (car.getLicenseplate() != null) {
// autoDto.setLicenseplate(car.getLicenseplate());
// }
dto.setId(television.getId());
dto.setType(television.getType());
dto.setBrand(television.getBrand());
dto.setName(television.getName());
dto.setPrice(television.getPrice());
dto.setAvailableSize(television.getAvailableSize());
dto.setRefreshRate(television.getRefreshRate());
dto.setScreenType(television.getScreenType());
dto.setScreenQuality(television.getScreenQuality());
dto.setSmartTv(television.getWifi());
dto.setWifi(television.getWifi());
dto.setVoiceControl(television.getVoiceControl());
dto.setHdr(television.getHdr());
dto.setBluetooth(television.getBluetooth());
dto.setAmbiLight(television.getAmbiLight());
dto.setOriginalStock(television.getOriginalStock());
dto.setSold(television.getSold());
return dto;
}
}
|
48629_2 | package nl.novi.les13.controller;
import nl.novi.les13.dto.CourseDto;
import nl.novi.les13.model.Course;
import nl.novi.les13.model.Lesson;
import nl.novi.les13.model.Teacher;
import nl.novi.les13.repository.CourseRepository;
import nl.novi.les13.repository.LessonRepository;
import nl.novi.les13.repository.TeacherRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
@RequestMapping("/courses")
public class CourseController {
// ALWAYS USE SERVICES INSTEAD OF REPOSITORIES IN CONTROLLERS!!!
private final CourseRepository courseRepository;
private final TeacherRepository teacherRepository;
private final LessonRepository lessonRepository;
public CourseController(CourseRepository courseRepository, TeacherRepository teacherRepository, LessonRepository lessonRepository) {
this.courseRepository = courseRepository;
this.teacherRepository = teacherRepository;
this.lessonRepository = lessonRepository;
}
@PostMapping
public ResponseEntity<CourseDto> createCourse(@RequestBody CourseDto courseDto) {
// Normaliter horen de onderstaande 3 regels (Mapper) in de Service:
Course course = new Course();
course.setTitle(courseDto.title);
course.setSp(courseDto.sp);
// Zoiets als: Als docent bestaat, koppel deze dan toe aan de cursus
// Het veld in CourseDto teacherIds:
for (Long id : courseDto.teacherIds) {
Optional<Teacher> ot = teacherRepository.findById(id);
if (ot.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false.
Teacher teacher = ot.get(); // Optional.get(); - Return the value that's inside the Optional
course.getTeachers().add(teacher);
}
}
for (Long id : courseDto.lessonIds) {
Optional<Lesson> ol = lessonRepository.findById(id);
if (ol.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false.
Lesson lesson = ol.get(); // Optional.get(); - Return the value that's inside the Optional
course.getLessons().add(lesson);
}
}
courseRepository.save(course);
courseDto.id = course.getId(); // Zonder deze regel geeft Postman null als id.
return new ResponseEntity<>(courseDto, HttpStatus.CREATED);
}
}
| Aphelion-im/Les-13-uitwerking-opdracht-lesson | src/main/java/nl/novi/les13/controller/CourseController.java | 754 | // Zoiets als: Als docent bestaat, koppel deze dan toe aan de cursus | line_comment | nl | package nl.novi.les13.controller;
import nl.novi.les13.dto.CourseDto;
import nl.novi.les13.model.Course;
import nl.novi.les13.model.Lesson;
import nl.novi.les13.model.Teacher;
import nl.novi.les13.repository.CourseRepository;
import nl.novi.les13.repository.LessonRepository;
import nl.novi.les13.repository.TeacherRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
@RequestMapping("/courses")
public class CourseController {
// ALWAYS USE SERVICES INSTEAD OF REPOSITORIES IN CONTROLLERS!!!
private final CourseRepository courseRepository;
private final TeacherRepository teacherRepository;
private final LessonRepository lessonRepository;
public CourseController(CourseRepository courseRepository, TeacherRepository teacherRepository, LessonRepository lessonRepository) {
this.courseRepository = courseRepository;
this.teacherRepository = teacherRepository;
this.lessonRepository = lessonRepository;
}
@PostMapping
public ResponseEntity<CourseDto> createCourse(@RequestBody CourseDto courseDto) {
// Normaliter horen de onderstaande 3 regels (Mapper) in de Service:
Course course = new Course();
course.setTitle(courseDto.title);
course.setSp(courseDto.sp);
// Zoiets als:<SUF>
// Het veld in CourseDto teacherIds:
for (Long id : courseDto.teacherIds) {
Optional<Teacher> ot = teacherRepository.findById(id);
if (ot.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false.
Teacher teacher = ot.get(); // Optional.get(); - Return the value that's inside the Optional
course.getTeachers().add(teacher);
}
}
for (Long id : courseDto.lessonIds) {
Optional<Lesson> ol = lessonRepository.findById(id);
if (ol.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false.
Lesson lesson = ol.get(); // Optional.get(); - Return the value that's inside the Optional
course.getLessons().add(lesson);
}
}
courseRepository.save(course);
courseDto.id = course.getId(); // Zonder deze regel geeft Postman null als id.
return new ResponseEntity<>(courseDto, HttpStatus.CREATED);
}
}
|
137238_3 | package nl.novi.techiteasy1121.services;
import lombok.AllArgsConstructor;
import nl.novi.techiteasy1121.dtos.TelevisionDto;
import nl.novi.techiteasy1121.dtos.WallBracketDto;
import nl.novi.techiteasy1121.exceptions.RecordNotFoundException;
import nl.novi.techiteasy1121.models.Television;
import nl.novi.techiteasy1121.models.TelevisionWallBracket;
import nl.novi.techiteasy1121.models.TelevisionWallBracketKey;
import nl.novi.techiteasy1121.models.WallBracket;
import nl.novi.techiteasy1121.repositories.TelevisionRepository;
import nl.novi.techiteasy1121.repositories.TelevisionWallBracketRepository;
import nl.novi.techiteasy1121.repositories.WallBracketRepository;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// Deze klasse bevat de service methodes van TelevisionWallBracketController.
// Deze klasse wijkt af van de andere service-klassen, omdat deze in 3 verschillende controllers wordt ge-autowired.
// Deze class heeft geen Dto
@Service
@AllArgsConstructor
public class TelevisionWallBracketService {
private final TelevisionRepository televisionRepository;
private final WallBracketRepository wallBracketRepository;
private final TelevisionWallBracketRepository televisionWallBracketRepository;
public Collection<TelevisionDto> getTelevisionsByWallBracketId(Long wallBracketId) {
Collection<TelevisionDto> televisionDtoCollection = new HashSet<>();
Collection<TelevisionWallBracket> televisionWallbrackets = televisionWallBracketRepository.findAllByWallBracketId(wallBracketId);
for (TelevisionWallBracket televisionWallbracket : televisionWallbrackets) {
Television television = televisionWallbracket.getTelevision();
TelevisionDto televisionDto = new TelevisionDto();
televisionDto.setId(television.getId());
televisionDto.setTestEnum(television.getTestEnum());
televisionDto.setType(television.getType());
televisionDto.setBrand(television.getBrand());
televisionDto.setName(television.getName());
televisionDto.setPrice(television.getPrice());
televisionDto.setAvailableSize(television.getAvailableSize());
televisionDto.setRefreshRate(television.getRefreshRate());
televisionDto.setScreenType(television.getScreenType());
televisionDto.setScreenQuality(television.getScreenQuality());
televisionDto.setSmartTv(television.getSmartTv());
televisionDto.setWifi(television.getWifi());
televisionDto.setVoiceControl(television.getVoiceControl());
televisionDto.setHdr(television.getHdr());
televisionDto.setBluetooth(television.getBluetooth());
televisionDto.setAmbiLight(television.getAmbiLight());
televisionDto.setOriginalStock(television.getOriginalStock());
televisionDto.setSold(television.getSold());
televisionDtoCollection.add(televisionDto);
}
return televisionDtoCollection;
}
// Collection is de super klasse van zowel List als Set.
public Collection<WallBracketDto> getWallBracketsByTelevisionId(Long televisionId) {
//We gebruiken hier Set om te voorkomen dat er dubbele entries in staan.
Set<WallBracketDto> wallBracketDtoSet = new HashSet<>();
List<TelevisionWallBracket> televisionWallbrackets = televisionWallBracketRepository.findAllByTelevisionId(televisionId);
for (TelevisionWallBracket televisionWallbracket : televisionWallbrackets) {
WallBracket wallBracket = televisionWallbracket.getWallBracket();
var dto = new WallBracketDto();
dto.setId(wallBracket.getId());
dto.setName(wallBracket.getName());
dto.setSize(wallBracket.getSize());
dto.setAdjustable(wallBracket.getAdjustable());
dto.setPrice(wallBracket.getPrice());
wallBracketDtoSet.add(dto);
}
return wallBracketDtoSet;
}
public void addTelevisionWallBracket(Long televisionId, Long wallBracketId) {
var televisionWallBracket = new TelevisionWallBracket();
if (!televisionRepository.existsById(televisionId)) {
throw new RecordNotFoundException();
}
Television television = televisionRepository.findById(televisionId).orElse(null);
if (!wallBracketRepository.existsById(wallBracketId)) {
throw new RecordNotFoundException();
}
WallBracket wallBracket = wallBracketRepository.findById(wallBracketId).orElse(null);
televisionWallBracket.setTelevision(television);
televisionWallBracket.setWallBracket(wallBracket);
TelevisionWallBracketKey id = new TelevisionWallBracketKey(televisionId, wallBracketId);
televisionWallBracket.setId(id);
televisionWallBracketRepository.save(televisionWallBracket);
}
// Of Optionals?
public void deleteTelevisionWallBracket(Long televisionId, Long wallBracketId) {
TelevisionWallBracketKey id = new TelevisionWallBracketKey(televisionId, wallBracketId);
if (!televisionWallBracketRepository.existsById(id)) {
throw new RecordNotFoundException("Combination Television #id: " + televisionId + " and " + "Wallbracket #id: " + wallBracketId + " not found.");
} else {
televisionWallBracketRepository.deleteById(id);
}
}
}
| Aphelion-im/Les-13-uitwerking-opdracht-tech-it-easy-relations | src/main/java/nl/novi/techiteasy1121/services/TelevisionWallBracketService.java | 1,634 | // Collection is de super klasse van zowel List als Set. | line_comment | nl | package nl.novi.techiteasy1121.services;
import lombok.AllArgsConstructor;
import nl.novi.techiteasy1121.dtos.TelevisionDto;
import nl.novi.techiteasy1121.dtos.WallBracketDto;
import nl.novi.techiteasy1121.exceptions.RecordNotFoundException;
import nl.novi.techiteasy1121.models.Television;
import nl.novi.techiteasy1121.models.TelevisionWallBracket;
import nl.novi.techiteasy1121.models.TelevisionWallBracketKey;
import nl.novi.techiteasy1121.models.WallBracket;
import nl.novi.techiteasy1121.repositories.TelevisionRepository;
import nl.novi.techiteasy1121.repositories.TelevisionWallBracketRepository;
import nl.novi.techiteasy1121.repositories.WallBracketRepository;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// Deze klasse bevat de service methodes van TelevisionWallBracketController.
// Deze klasse wijkt af van de andere service-klassen, omdat deze in 3 verschillende controllers wordt ge-autowired.
// Deze class heeft geen Dto
@Service
@AllArgsConstructor
public class TelevisionWallBracketService {
private final TelevisionRepository televisionRepository;
private final WallBracketRepository wallBracketRepository;
private final TelevisionWallBracketRepository televisionWallBracketRepository;
public Collection<TelevisionDto> getTelevisionsByWallBracketId(Long wallBracketId) {
Collection<TelevisionDto> televisionDtoCollection = new HashSet<>();
Collection<TelevisionWallBracket> televisionWallbrackets = televisionWallBracketRepository.findAllByWallBracketId(wallBracketId);
for (TelevisionWallBracket televisionWallbracket : televisionWallbrackets) {
Television television = televisionWallbracket.getTelevision();
TelevisionDto televisionDto = new TelevisionDto();
televisionDto.setId(television.getId());
televisionDto.setTestEnum(television.getTestEnum());
televisionDto.setType(television.getType());
televisionDto.setBrand(television.getBrand());
televisionDto.setName(television.getName());
televisionDto.setPrice(television.getPrice());
televisionDto.setAvailableSize(television.getAvailableSize());
televisionDto.setRefreshRate(television.getRefreshRate());
televisionDto.setScreenType(television.getScreenType());
televisionDto.setScreenQuality(television.getScreenQuality());
televisionDto.setSmartTv(television.getSmartTv());
televisionDto.setWifi(television.getWifi());
televisionDto.setVoiceControl(television.getVoiceControl());
televisionDto.setHdr(television.getHdr());
televisionDto.setBluetooth(television.getBluetooth());
televisionDto.setAmbiLight(television.getAmbiLight());
televisionDto.setOriginalStock(television.getOriginalStock());
televisionDto.setSold(television.getSold());
televisionDtoCollection.add(televisionDto);
}
return televisionDtoCollection;
}
// Collection is<SUF>
public Collection<WallBracketDto> getWallBracketsByTelevisionId(Long televisionId) {
//We gebruiken hier Set om te voorkomen dat er dubbele entries in staan.
Set<WallBracketDto> wallBracketDtoSet = new HashSet<>();
List<TelevisionWallBracket> televisionWallbrackets = televisionWallBracketRepository.findAllByTelevisionId(televisionId);
for (TelevisionWallBracket televisionWallbracket : televisionWallbrackets) {
WallBracket wallBracket = televisionWallbracket.getWallBracket();
var dto = new WallBracketDto();
dto.setId(wallBracket.getId());
dto.setName(wallBracket.getName());
dto.setSize(wallBracket.getSize());
dto.setAdjustable(wallBracket.getAdjustable());
dto.setPrice(wallBracket.getPrice());
wallBracketDtoSet.add(dto);
}
return wallBracketDtoSet;
}
public void addTelevisionWallBracket(Long televisionId, Long wallBracketId) {
var televisionWallBracket = new TelevisionWallBracket();
if (!televisionRepository.existsById(televisionId)) {
throw new RecordNotFoundException();
}
Television television = televisionRepository.findById(televisionId).orElse(null);
if (!wallBracketRepository.existsById(wallBracketId)) {
throw new RecordNotFoundException();
}
WallBracket wallBracket = wallBracketRepository.findById(wallBracketId).orElse(null);
televisionWallBracket.setTelevision(television);
televisionWallBracket.setWallBracket(wallBracket);
TelevisionWallBracketKey id = new TelevisionWallBracketKey(televisionId, wallBracketId);
televisionWallBracket.setId(id);
televisionWallBracketRepository.save(televisionWallBracket);
}
// Of Optionals?
public void deleteTelevisionWallBracket(Long televisionId, Long wallBracketId) {
TelevisionWallBracketKey id = new TelevisionWallBracketKey(televisionId, wallBracketId);
if (!televisionWallBracketRepository.existsById(id)) {
throw new RecordNotFoundException("Combination Television #id: " + televisionId + " and " + "Wallbracket #id: " + wallBracketId + " not found.");
} else {
televisionWallBracketRepository.deleteById(id);
}
}
}
|
21125_5 | package nl.novi.les16jwt.controller;
import nl.novi.les16jwt.dto.UserDto;
import nl.novi.les16jwt.model.Role;
import nl.novi.les16jwt.model.User;
import nl.novi.les16jwt.repository.RoleRepository;
import nl.novi.les16jwt.repository.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@RestController
public class UserController {
private final UserRepository userRepos;
private final RoleRepository roleRepos;
private final PasswordEncoder encoder;
public UserController(UserRepository userRepos, RoleRepository roleRepos, PasswordEncoder encoder) {
this.userRepos = userRepos;
this.roleRepos = roleRepos;
this.encoder = encoder;
}
// Les 16 (2023/02) video@2h34m:
// Deze method geeft in Postman een (encrypted) password terug: Dat is niet de bedoeling!
// Daarom opsplitsen in een UserInputDto en een UserOutputDto.
// In UserOutputDto laat je dan het password weg.
// RJ komt over dat voor de eindopdracht er niet heel streng naar gekeken gaat worden door de examinator, maar het is beter van wel
@GetMapping("/users")
public List getUsers() {
Iterable<User> users = userRepos.findAll();
List<User> userList = new ArrayList<>();
for(User user : users) {
userList.add(user);
}
return userList;
}
// Moet hier een URI uri?: Ja, Garage heeft dat ook
@PostMapping("/users")
public String createUser(@RequestBody UserDto userDto) {
User newUser = new User();
newUser.setUsername(userDto.username);
newUser.setPassword(encoder.encode(userDto.password));
List<Role> userRoles = new ArrayList<>();
for (String rolename : userDto.roles) {
Optional<Role> or = roleRepos.findById("ROLE_" + rolename);
userRoles.add(or.get());
}
newUser.setRoles(userRoles);
userRepos.save(newUser);
return "Done";
}
}
| Aphelion-im/Les-16-uitwerking-opdracht-jwt | src/main/java/nl/novi/les16jwt/controller/UserController.java | 697 | // Moet hier een URI uri?: Ja, Garage heeft dat ook | line_comment | nl | package nl.novi.les16jwt.controller;
import nl.novi.les16jwt.dto.UserDto;
import nl.novi.les16jwt.model.Role;
import nl.novi.les16jwt.model.User;
import nl.novi.les16jwt.repository.RoleRepository;
import nl.novi.les16jwt.repository.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@RestController
public class UserController {
private final UserRepository userRepos;
private final RoleRepository roleRepos;
private final PasswordEncoder encoder;
public UserController(UserRepository userRepos, RoleRepository roleRepos, PasswordEncoder encoder) {
this.userRepos = userRepos;
this.roleRepos = roleRepos;
this.encoder = encoder;
}
// Les 16 (2023/02) video@2h34m:
// Deze method geeft in Postman een (encrypted) password terug: Dat is niet de bedoeling!
// Daarom opsplitsen in een UserInputDto en een UserOutputDto.
// In UserOutputDto laat je dan het password weg.
// RJ komt over dat voor de eindopdracht er niet heel streng naar gekeken gaat worden door de examinator, maar het is beter van wel
@GetMapping("/users")
public List getUsers() {
Iterable<User> users = userRepos.findAll();
List<User> userList = new ArrayList<>();
for(User user : users) {
userList.add(user);
}
return userList;
}
// Moet hier<SUF>
@PostMapping("/users")
public String createUser(@RequestBody UserDto userDto) {
User newUser = new User();
newUser.setUsername(userDto.username);
newUser.setPassword(encoder.encode(userDto.password));
List<Role> userRoles = new ArrayList<>();
for (String rolename : userDto.roles) {
Optional<Role> or = roleRepos.findById("ROLE_" + rolename);
userRoles.add(or.get());
}
newUser.setRoles(userRoles);
userRepos.save(newUser);
return "Done";
}
}
|
144559_1 | package nl.novi.les9;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
@RestController
public class NameController {
private final ArrayList<String> names = new ArrayList<>(); // Private field?
private final Set<String> noDuplicates = new HashSet<>();
private String myName;
@GetMapping("/hello")
public static String printHello() {
return "Hello, world!!";
}
// Naam in een normale variabele stoppen
@PostMapping("/addName")
public void addName(@RequestParam(required = true) String name) { // name moet overeenkomen met de key name in Postman!
if (name != null) {
myName = name;
}
}
// Naam in een ArrayList stoppen
@PostMapping("/addNames")
public String addNames(@RequestParam(required = true) String name) { // name moet overeenkomen met de key name in Postman!
if (name != null && !names.contains(name.toLowerCase())) { // Het kan ook met Set, HashSet, etc.- Voegt alleen Greet toe of greet, niet beide. Case sensitive.
names.add(name);
} else {
return "Error: Name was already added!";
}
return "201 OK: Name " + "\"" + name + "\"" + " successfully added!";
}
// Naam in een HashSet stoppen (Set mag geen duplicaten! Dubbele beveiliging met contains t/f check)
@PostMapping("/addNameNoDuplicates")
public String addNames2(@RequestParam String name) {
if (name != null && !noDuplicates.contains(name)) { // Ignore case, zowel Greet als greet kun je toevoegen als aparte namen
noDuplicates.add(name);
} else {
return "Error: Name was already added!";
}
return "201 OK: Name " + "\"" + name + "\"" + " successfully added!";
}
// Laat naam in de variabele zien
@GetMapping("/showName")
public String showName() {
return "Hallo " + myName;
}
// Version 1: Vraag de namen op die in de ArrayList staan door middel van ForEach
@GetMapping("/showNames")
public ArrayList<String> showNames() {
ArrayList<String> result = new ArrayList<>();
for (String name : names) {
result.add("Hallo " + name);
}
return result;
}
// Version 2: Vraag de namen op die in de ArrayList staan door middel van StringBuilder
// Met dubbele waarden
@GetMapping("/showNames2")
public StringBuilder showNames2() {
StringBuilder greetings = new StringBuilder();
for (String name : names) {
greetings.append("Hallo ").append(name).append("\n");
}
return greetings; // Of String als return type + return greetings.toString();
}
// Normale variable reversed name met StringBuilder
@GetMapping("/reversedName")
public StringBuilder reversedName() {
StringBuilder reversedName = new StringBuilder(myName);
return reversedName.reverse();
}
// Normale variable reversed name met StringBuilder
@GetMapping("/reversedName2")
public ArrayList<String> reversedName2() {
ArrayList<String> result = new ArrayList<>();
for (String name : names) {
StringBuilder reversedName = new StringBuilder(name).reverse(); // Is dit wel de beste manier om steeds een StringBuilder object aan te maken?
result.add(String.valueOf(reversedName));
}
return result;
}
}
| Aphelion-im/Les-9-Opdracht-Namenlijst | src/main/java/nl/novi/les9/NameController.java | 1,005 | // name moet overeenkomen met de key name in Postman! | line_comment | nl | package nl.novi.les9;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
@RestController
public class NameController {
private final ArrayList<String> names = new ArrayList<>(); // Private field?
private final Set<String> noDuplicates = new HashSet<>();
private String myName;
@GetMapping("/hello")
public static String printHello() {
return "Hello, world!!";
}
// Naam in een normale variabele stoppen
@PostMapping("/addName")
public void addName(@RequestParam(required = true) String name) { // name moet<SUF>
if (name != null) {
myName = name;
}
}
// Naam in een ArrayList stoppen
@PostMapping("/addNames")
public String addNames(@RequestParam(required = true) String name) { // name moet overeenkomen met de key name in Postman!
if (name != null && !names.contains(name.toLowerCase())) { // Het kan ook met Set, HashSet, etc.- Voegt alleen Greet toe of greet, niet beide. Case sensitive.
names.add(name);
} else {
return "Error: Name was already added!";
}
return "201 OK: Name " + "\"" + name + "\"" + " successfully added!";
}
// Naam in een HashSet stoppen (Set mag geen duplicaten! Dubbele beveiliging met contains t/f check)
@PostMapping("/addNameNoDuplicates")
public String addNames2(@RequestParam String name) {
if (name != null && !noDuplicates.contains(name)) { // Ignore case, zowel Greet als greet kun je toevoegen als aparte namen
noDuplicates.add(name);
} else {
return "Error: Name was already added!";
}
return "201 OK: Name " + "\"" + name + "\"" + " successfully added!";
}
// Laat naam in de variabele zien
@GetMapping("/showName")
public String showName() {
return "Hallo " + myName;
}
// Version 1: Vraag de namen op die in de ArrayList staan door middel van ForEach
@GetMapping("/showNames")
public ArrayList<String> showNames() {
ArrayList<String> result = new ArrayList<>();
for (String name : names) {
result.add("Hallo " + name);
}
return result;
}
// Version 2: Vraag de namen op die in de ArrayList staan door middel van StringBuilder
// Met dubbele waarden
@GetMapping("/showNames2")
public StringBuilder showNames2() {
StringBuilder greetings = new StringBuilder();
for (String name : names) {
greetings.append("Hallo ").append(name).append("\n");
}
return greetings; // Of String als return type + return greetings.toString();
}
// Normale variable reversed name met StringBuilder
@GetMapping("/reversedName")
public StringBuilder reversedName() {
StringBuilder reversedName = new StringBuilder(myName);
return reversedName.reverse();
}
// Normale variable reversed name met StringBuilder
@GetMapping("/reversedName2")
public ArrayList<String> reversedName2() {
ArrayList<String> result = new ArrayList<>();
for (String name : names) {
StringBuilder reversedName = new StringBuilder(name).reverse(); // Is dit wel de beste manier om steeds een StringBuilder object aan te maken?
result.add(String.valueOf(reversedName));
}
return result;
}
}
|
125583_11 | // Pets
// Dog
// Cat
// Specific:
// Lion int numberOfChildren;
// Tiger int numberOfStripes;
// Hond nameOfOwner, favoriteFoodBrand, species
// Kat nameOfOwner, favoriteFoodBrand, species, indoorOutdoor
// Wolf. packName
// Zoo animals: // extends ZooAnimal
// String nameOfPaddock; // Lion, tiger, Wolf - Vind ik een Zoo eigenschap
// String dayLastFed; // Lion, tiger, Wolf
// String landOfOrigin; // Lion, tiger, Wolf
package nl.novi.javaprogrammeren.overerving;
public abstract class Animal {
private String name; // Lion, tiger, Dog, Cat, Wolf
private final String gender; // Lion, tiger, Dog, Cat, Wolf
// Protected: An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses. (Not in superclass!)
protected Animal(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return this.name;
}
public String getGender() {
return this.gender;
}
public void setName(String name) {
this.name = name;
}
public void move() {
System.out.println(this.name + " has moved 0.25 meters.");
}
public void sleep() {
System.out.println("The animal is going to sleep for 8 hours.");
}
public void eat(String food) {
System.out.println(this.getName() + " is eating " + food);
}
// Dog of Cat moet een specifiek eigen geluid hebben. Vandaar @Overrule in de subclass
public abstract void makeSound();
}
| Aphelion-im/SD-BE-JP-Overerving-02-opdracht | src/nl/novi/javaprogrammeren/overerving/Animal.java | 455 | // Dog of Cat moet een specifiek eigen geluid hebben. Vandaar @Overrule in de subclass | line_comment | nl | // Pets
// Dog
// Cat
// Specific:
// Lion int numberOfChildren;
// Tiger int numberOfStripes;
// Hond nameOfOwner, favoriteFoodBrand, species
// Kat nameOfOwner, favoriteFoodBrand, species, indoorOutdoor
// Wolf. packName
// Zoo animals: // extends ZooAnimal
// String nameOfPaddock; // Lion, tiger, Wolf - Vind ik een Zoo eigenschap
// String dayLastFed; // Lion, tiger, Wolf
// String landOfOrigin; // Lion, tiger, Wolf
package nl.novi.javaprogrammeren.overerving;
public abstract class Animal {
private String name; // Lion, tiger, Dog, Cat, Wolf
private final String gender; // Lion, tiger, Dog, Cat, Wolf
// Protected: An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses. (Not in superclass!)
protected Animal(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return this.name;
}
public String getGender() {
return this.gender;
}
public void setName(String name) {
this.name = name;
}
public void move() {
System.out.println(this.name + " has moved 0.25 meters.");
}
public void sleep() {
System.out.println("The animal is going to sleep for 8 hours.");
}
public void eat(String food) {
System.out.println(this.getName() + " is eating " + food);
}
// Dog of<SUF>
public abstract void makeSound();
}
|
140838_0 | package nl.novi.jp.methods.junior;
/**
* Uitdagende opdracht!
* Een stuk van de code is uitgecommentarieerd, omdat deze pas gaat werken, wanneer de methode doTransaction afgemaakt
* is.
* <p>
* Maak doTransaction af. Deze moet twee waardes accepteren (welk datatype?). Een waarde is het banksaldo voor de
* transactie, de andere waarde is de waarde van de transactie.
* <p>
* Wanneer de waarde van de transactie negatief is, gaat het om het opnemen (withdraw) van geld. Deze methode dient dan
* ook aangeroepen te worden. Wanneer deze positief is, gaat het om geld storten (deposit). Dan dient de deposit methode
* aangeroepen te worden.
*/
public class JuniorFour {
public static void main(String[] args) {
doTransaction(1000, -200);
doTransaction(123, 3445);
}
public static void doTransaction(int banksaldo, int waardeTransactie) {
if (waardeTransactie > 0) {
deposit(banksaldo, waardeTransactie);
} else {
withdraw(banksaldo, waardeTransactie);
}
}
public static void deposit(int bankAccountBalance, int amount) {
int updatedBalance = bankAccountBalance + amount;
System.out.println("The user deposits: " + amount + " euro.");
System.out.println("The new balance is: " + updatedBalance);
}
public static void withdraw(int bankAccountBalance, int amount) {
int updatedBalance = bankAccountBalance + amount;
System.out.println("The user withdraws " + amount + " euro.");
System.out.println("The new balance is: " + updatedBalance);
}
}
| Aphelion-im/SD-BE-JP-methods-opdracht | src/nl/novi/jp/methods/junior/JuniorFour.java | 476 | /**
* Uitdagende opdracht!
* Een stuk van de code is uitgecommentarieerd, omdat deze pas gaat werken, wanneer de methode doTransaction afgemaakt
* is.
* <p>
* Maak doTransaction af. Deze moet twee waardes accepteren (welk datatype?). Een waarde is het banksaldo voor de
* transactie, de andere waarde is de waarde van de transactie.
* <p>
* Wanneer de waarde van de transactie negatief is, gaat het om het opnemen (withdraw) van geld. Deze methode dient dan
* ook aangeroepen te worden. Wanneer deze positief is, gaat het om geld storten (deposit). Dan dient de deposit methode
* aangeroepen te worden.
*/ | block_comment | nl | package nl.novi.jp.methods.junior;
/**
* Uitdagende opdracht!
<SUF>*/
public class JuniorFour {
public static void main(String[] args) {
doTransaction(1000, -200);
doTransaction(123, 3445);
}
public static void doTransaction(int banksaldo, int waardeTransactie) {
if (waardeTransactie > 0) {
deposit(banksaldo, waardeTransactie);
} else {
withdraw(banksaldo, waardeTransactie);
}
}
public static void deposit(int bankAccountBalance, int amount) {
int updatedBalance = bankAccountBalance + amount;
System.out.println("The user deposits: " + amount + " euro.");
System.out.println("The new balance is: " + updatedBalance);
}
public static void withdraw(int bankAccountBalance, int amount) {
int updatedBalance = bankAccountBalance + amount;
System.out.println("The user withdraws " + amount + " euro.");
System.out.println("The new balance is: " + updatedBalance);
}
}
|
169654_0 | package nl.novi.opdrachten.whilelussen;
/**
* Bekijk onderstaande while-lus.
* Zorg ervoor dat de while-lus stopt op regel 22.
*/
public class StopTwentyTwo {
public static void main(String[] tt) {
int teller = 1;
while (teller < 100) { // Deze regel mag niet aangepast worden.
if (teller == 22) {
break;
}
System.out.println("Getal: " + teller);
teller = teller + 1;
}
}
}
| Aphelion-im/SD-BE-JP-oefenopdrachten-opdracht | src/nl/novi/opdrachten/whilelussen/StopTwentyTwo.java | 157 | /**
* Bekijk onderstaande while-lus.
* Zorg ervoor dat de while-lus stopt op regel 22.
*/ | block_comment | nl | package nl.novi.opdrachten.whilelussen;
/**
* Bekijk onderstaande while-lus.<SUF>*/
public class StopTwentyTwo {
public static void main(String[] tt) {
int teller = 1;
while (teller < 100) { // Deze regel mag niet aangepast worden.
if (teller == 22) {
break;
}
System.out.println("Getal: " + teller);
teller = teller + 1;
}
}
}
|
35800_0 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean play = true;
String ongeldig = "ongeldige invoer";
// Hier mag je je code schrijven voor de hoofd-opdracht
Integer[] numeric = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
String[] alphabetic = {"een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "nul"};
Translator translator = new Translator(alphabetic, numeric);
while (play) {
System.out.println("Type 'x' om te stoppen \nType 'v' om te vertalen");
String input = scanner.nextLine();
if (input.equals("x")) {
play = false;
scanner.close();
} else if (input.equals("v")) {
System.out.println("Type een cijfer in van 0 t/m 9");
int number = scanner.nextInt();
scanner.nextLine();
if (number < 10 && number >= 0) {
String result = translator.translate(number);
System.out.println("De vertaling van " + number + " is " + result);
} else {
System.out.println(ongeldig);
}
} else {
System.out.println(ongeldig);
}
}
}
}
| Aphelion-im/backend-java-collecties-lussen-opdracht | src/Main.java | 419 | // Hier mag je je code schrijven voor de hoofd-opdracht | line_comment | nl | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean play = true;
String ongeldig = "ongeldige invoer";
// Hier mag<SUF>
Integer[] numeric = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
String[] alphabetic = {"een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "nul"};
Translator translator = new Translator(alphabetic, numeric);
while (play) {
System.out.println("Type 'x' om te stoppen \nType 'v' om te vertalen");
String input = scanner.nextLine();
if (input.equals("x")) {
play = false;
scanner.close();
} else if (input.equals("v")) {
System.out.println("Type een cijfer in van 0 t/m 9");
int number = scanner.nextInt();
scanner.nextLine();
if (number < 10 && number >= 0) {
String result = translator.translate(number);
System.out.println("De vertaling van " + number + " is " + result);
} else {
System.out.println(ongeldig);
}
} else {
System.out.println(ongeldig);
}
}
}
}
|
22204_0 | import java.util.ArrayList;
import java.util.List;
public class Person {
private final String name; // Final niet in de NOVI-uitwerkingen. Alleen een setter.
private String middleName; // Deze kan waarschijnlijk niet op final omdat deze niet in de eerste constructor staat als parameter
private final String lastName;
private int age;
private char sex;
private Person mother;
private Person father;
private List<Person> siblings; // Niet doen: = new ArrayList<>();! Maar in de method.
private List<Person> children;
private List<Pet> pets;
// List<Pet> pets = new ArrayList<>(); Geeft een dubbele pet: waarom? getPets(): [Pet@4eec7777, Pet@4eec7777, Pet@3b07d329]
public Person(String name, String lastName, int age, char sex) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
public Person(String name, String middleName, String lastName, int age, char sex) {
this.name = name;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
// Getters & Setters
// Geen print/sout in getters/setters, maar een return!
public String getName() {
return name;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public char getSex() {
return sex;
}
public int getAge() {
return age;
}
public Person getMother() {
return mother;
}
public Person getFather() {
return father;
}
public List<Person> getSiblings() {
return siblings;
}
public List<Person> getChildren() {
return children;
}
public List<Pet> getPets() { // Geeft: [Pet@3b07d329, Pet@41629346], tenzij je toString @Override in Pet.java
return pets;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(char sex) {
this.sex = sex;
}
public void setMother(Person mother) {
this.mother = mother;
}
public void setFather(Person father) {
this.father = father;
}
public void setSiblings(List<Person> siblings) {
this.siblings = siblings;
}
// ja
public void setChildren(List<Person> children) {
this.children = children;
}
// ja
public void setPets(List<Pet> pets) {
this.pets = pets;
}
// Methods
// Met alleen een father en mother parameter, zie je niet wie het kind is.
// addChild() bestaat niet, omdat het niet aangeeft wie de vader is.
public void addParents(Person father, Person mother, Person child) {
child.setMother(mother);
child.setFather(father);
// ?
mother.addChildToChildren(mother, child);
father.addChildToChildren(father, child);
}
// Hoe deze method opvatten?!
public void addChildToChildren(Person parent, Person child) {
List<Person> kids = new ArrayList<>();
if (parent.getChildren() != null) {
kids.addAll(parent.getChildren());
}
kids.add(child);
parent.setChildren(kids);
}
// Steeds een null of niet gelijk aan null check
// https://youtu.be/lm72_HCd17s?si=KF6wkEMwfPGUCEqc (Coding with John, Null Pointer Exceptions In Java - What EXACTLY They Are and How to Fix Them)
public void addPet(Person person, Pet pet) { // Herschrijven met een Optional?
List<Pet> pets = new ArrayList<>(); // Waarom hier en niet als attribuut? Als field/attribuut geeft het dubbele pet terug. 2x Pablo.
if (person.getPets() != null) { // null = De persoon heeft geen huisdieren. Null geeft Exception error: Cannot invoke iterator
pets.addAll(person.getPets()); // Alleen als een persoon een huisdier of huisdieren heeft, voeg deze dan toe aan de lijst
}
pets.add(pet); // Voeg een huisdier toe aan de lijst pets
person.setPets(pets); // Ken de lijst toe aan een persoon als de eigenaar
}
public void addSibling(Person person, Person sibling) {
List<Person> family = new ArrayList<>();
if (person.getSiblings() != null) {
for (Person people : person.getSiblings()) {
family.add(people);
}
}
family.add(sibling);
person.setSiblings(family);
}
public List<Person> getGrandChildren(Person person) {
List<Person> grandChildren = new ArrayList<>();
if (person.getChildren() != null) {
for (Person children : person.getChildren()) {
if (children.getChildren() != null) {
for (Person grandKid : children.getChildren()) {
grandChildren.add(grandKid);
}
}
}
}
return grandChildren;
}
}
// public void printPets() {
// System.out.println(this.name + " has the following pets:");
// for (Pet pet : pets) {
// System.out.println("- " + pet.getName());
// }
// } | Aphelion-im/backend-java-family-tree-opdracht | src/main/java/Person.java | 1,513 | // Final niet in de NOVI-uitwerkingen. Alleen een setter. | line_comment | nl | import java.util.ArrayList;
import java.util.List;
public class Person {
private final String name; // Final niet<SUF>
private String middleName; // Deze kan waarschijnlijk niet op final omdat deze niet in de eerste constructor staat als parameter
private final String lastName;
private int age;
private char sex;
private Person mother;
private Person father;
private List<Person> siblings; // Niet doen: = new ArrayList<>();! Maar in de method.
private List<Person> children;
private List<Pet> pets;
// List<Pet> pets = new ArrayList<>(); Geeft een dubbele pet: waarom? getPets(): [Pet@4eec7777, Pet@4eec7777, Pet@3b07d329]
public Person(String name, String lastName, int age, char sex) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
public Person(String name, String middleName, String lastName, int age, char sex) {
this.name = name;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
// Getters & Setters
// Geen print/sout in getters/setters, maar een return!
public String getName() {
return name;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public char getSex() {
return sex;
}
public int getAge() {
return age;
}
public Person getMother() {
return mother;
}
public Person getFather() {
return father;
}
public List<Person> getSiblings() {
return siblings;
}
public List<Person> getChildren() {
return children;
}
public List<Pet> getPets() { // Geeft: [Pet@3b07d329, Pet@41629346], tenzij je toString @Override in Pet.java
return pets;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(char sex) {
this.sex = sex;
}
public void setMother(Person mother) {
this.mother = mother;
}
public void setFather(Person father) {
this.father = father;
}
public void setSiblings(List<Person> siblings) {
this.siblings = siblings;
}
// ja
public void setChildren(List<Person> children) {
this.children = children;
}
// ja
public void setPets(List<Pet> pets) {
this.pets = pets;
}
// Methods
// Met alleen een father en mother parameter, zie je niet wie het kind is.
// addChild() bestaat niet, omdat het niet aangeeft wie de vader is.
public void addParents(Person father, Person mother, Person child) {
child.setMother(mother);
child.setFather(father);
// ?
mother.addChildToChildren(mother, child);
father.addChildToChildren(father, child);
}
// Hoe deze method opvatten?!
public void addChildToChildren(Person parent, Person child) {
List<Person> kids = new ArrayList<>();
if (parent.getChildren() != null) {
kids.addAll(parent.getChildren());
}
kids.add(child);
parent.setChildren(kids);
}
// Steeds een null of niet gelijk aan null check
// https://youtu.be/lm72_HCd17s?si=KF6wkEMwfPGUCEqc (Coding with John, Null Pointer Exceptions In Java - What EXACTLY They Are and How to Fix Them)
public void addPet(Person person, Pet pet) { // Herschrijven met een Optional?
List<Pet> pets = new ArrayList<>(); // Waarom hier en niet als attribuut? Als field/attribuut geeft het dubbele pet terug. 2x Pablo.
if (person.getPets() != null) { // null = De persoon heeft geen huisdieren. Null geeft Exception error: Cannot invoke iterator
pets.addAll(person.getPets()); // Alleen als een persoon een huisdier of huisdieren heeft, voeg deze dan toe aan de lijst
}
pets.add(pet); // Voeg een huisdier toe aan de lijst pets
person.setPets(pets); // Ken de lijst toe aan een persoon als de eigenaar
}
public void addSibling(Person person, Person sibling) {
List<Person> family = new ArrayList<>();
if (person.getSiblings() != null) {
for (Person people : person.getSiblings()) {
family.add(people);
}
}
family.add(sibling);
person.setSiblings(family);
}
public List<Person> getGrandChildren(Person person) {
List<Person> grandChildren = new ArrayList<>();
if (person.getChildren() != null) {
for (Person children : person.getChildren()) {
if (children.getChildren() != null) {
for (Person grandKid : children.getChildren()) {
grandChildren.add(grandKid);
}
}
}
}
return grandChildren;
}
}
// public void printPets() {
// System.out.println(this.name + " has the following pets:");
// for (Pet pet : pets) {
// System.out.println("- " + pet.getName());
// }
// } |
44584_0 | import java.util.ArrayList;
import java.util.List;
public class Airport {
private final String nameOfAirport;
private final String location;
private int numberOfFlyingVehicles;
private final List<Flyable> flyingVehiclesList = new ArrayList<>(); // Dus mogelijk om Interfaces toe te voegen aan ArrayList!
public Airport(String nameOfAirport, String location) {
this.nameOfAirport = nameOfAirport;
this.location = location;
}
public void addFlyingVehicles(Flyable flyingVehicle) {
System.out.println("Flying vehicle has been added to " + this.nameOfAirport + "!");
this.flyingVehiclesList.add(flyingVehicle);
numberOfFlyingVehicles++;
System.out.println(this.nameOfAirport + " now has " + numberOfFlyingVehicles + " flying vehicles");
}
public String getNameOfAirport() {
return nameOfAirport;
}
public String getLocation() {
return location;
}
public int getNumberOfFlyingVehicles() {
return numberOfFlyingVehicles;
}
}
| Aphelion-im/backend-java-lesopdracht-fly-and-drive-opdracht | src/Airport.java | 304 | // Dus mogelijk om Interfaces toe te voegen aan ArrayList! | line_comment | nl | import java.util.ArrayList;
import java.util.List;
public class Airport {
private final String nameOfAirport;
private final String location;
private int numberOfFlyingVehicles;
private final List<Flyable> flyingVehiclesList = new ArrayList<>(); // Dus mogelijk<SUF>
public Airport(String nameOfAirport, String location) {
this.nameOfAirport = nameOfAirport;
this.location = location;
}
public void addFlyingVehicles(Flyable flyingVehicle) {
System.out.println("Flying vehicle has been added to " + this.nameOfAirport + "!");
this.flyingVehiclesList.add(flyingVehicle);
numberOfFlyingVehicles++;
System.out.println(this.nameOfAirport + " now has " + numberOfFlyingVehicles + " flying vehicles");
}
public String getNameOfAirport() {
return nameOfAirport;
}
public String getLocation() {
return location;
}
public int getNumberOfFlyingVehicles() {
return numberOfFlyingVehicles;
}
}
|
98465_2 | import java.util.Arrays;
import java.util.List;
public class ElectricPokemon extends Pokemon {
private static final String type = "electric"; // Moet ook static
// Moet private static final
private static final List<String> attacks = Arrays.asList("thunderPunch", "electroBall", "thunder", "voltTackle");
public ElectricPokemon(String name, int level, int hp, String food, String sound) {
super(name, level, hp, food, sound, type); // Niet alle hoeven in de parameters
}
public List<String> getAttacks() {
return attacks;
} // Moest public
// Attacks
public void thunderPunch(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " hits " + enemy.getName() + " with a TunderPunch!");
switch (enemy.getType()) {
case "grass" -> {
System.out.println(enemy.getName() + " loses 20 hp");
enemy.setHp(enemy.getHp() - 20);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 40 hp");
enemy.setHp(enemy.getHp() - 40);
}
case "fire" -> {
System.out.println(enemy.getName() + " loses 15 hp");
enemy.setHp(enemy.getHp() - 15);
}
case "electric" -> {
System.out.println(enemy.getName() + " loses 10 hp");
enemy.setHp(enemy.getHp() - 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
}
public void electroBall(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " throws a ElectroBall on " + enemy.getName());
switch (enemy.getType()) {
case "fire" -> {
System.out.println(enemy.getName() + " loses 25 hp");
enemy.setHp(enemy.getHp() - 25);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 40 hp");
enemy.setHp(enemy.getHp() - 40);
}
case "grass" -> {
System.out.println(enemy.getName() + " loses 35 hp");
enemy.setHp(enemy.getHp() - 35);
}
case "electric" -> {
System.out.println(enemy.getName() + " loses 10 hp");
enemy.setHp(enemy.getHp() - 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
}
public void thunder(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " hits " + enemy.getName() + " with Thunder");
switch (enemy.getType()) {
case "fire" -> {
System.out.println(enemy.getName() + " loses 20 hp");
enemy.setHp(enemy.getHp() - 20);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 50 hp");
enemy.setHp(enemy.getHp() - 50);
}
case "grass" -> {
System.out.println(enemy.getName() + " loses 30 hp");
enemy.setHp(enemy.getHp() - 30);
}
case "electric" -> {
System.out.println(enemy.getName() + " gaines 10 hp");
System.out.println(name.getName() + " gaines 10 hp");
enemy.setHp(enemy.getHp() + 10);
name.setHp(name.getHp() + 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
System.out.println(name.getName() + " has " + name.getHp() + " hp left");
}
public void voltTackle(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " uses a VoltTackle on " + enemy.getName());
switch (enemy.getType()) {
case "fire" -> {
System.out.println(enemy.getName() + " loses 20 hp");
enemy.setHp(enemy.getHp() - 20);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 40 hp");
enemy.setHp(enemy.getHp() - 40);
}
case "grass" -> {
System.out.println(enemy.getName() + " loses 30 hp");
enemy.setHp(enemy.getHp() - 30);
}
case "electric" -> {
System.out.println(enemy.getName() + " loses 10 hp");
enemy.setHp(enemy.getHp() - 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
}
}
| Aphelion-im/backend-java-pokemon-interface-opdracht | src/ElectricPokemon.java | 1,481 | // Niet alle hoeven in de parameters | line_comment | nl | import java.util.Arrays;
import java.util.List;
public class ElectricPokemon extends Pokemon {
private static final String type = "electric"; // Moet ook static
// Moet private static final
private static final List<String> attacks = Arrays.asList("thunderPunch", "electroBall", "thunder", "voltTackle");
public ElectricPokemon(String name, int level, int hp, String food, String sound) {
super(name, level, hp, food, sound, type); // Niet alle<SUF>
}
public List<String> getAttacks() {
return attacks;
} // Moest public
// Attacks
public void thunderPunch(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " hits " + enemy.getName() + " with a TunderPunch!");
switch (enemy.getType()) {
case "grass" -> {
System.out.println(enemy.getName() + " loses 20 hp");
enemy.setHp(enemy.getHp() - 20);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 40 hp");
enemy.setHp(enemy.getHp() - 40);
}
case "fire" -> {
System.out.println(enemy.getName() + " loses 15 hp");
enemy.setHp(enemy.getHp() - 15);
}
case "electric" -> {
System.out.println(enemy.getName() + " loses 10 hp");
enemy.setHp(enemy.getHp() - 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
}
public void electroBall(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " throws a ElectroBall on " + enemy.getName());
switch (enemy.getType()) {
case "fire" -> {
System.out.println(enemy.getName() + " loses 25 hp");
enemy.setHp(enemy.getHp() - 25);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 40 hp");
enemy.setHp(enemy.getHp() - 40);
}
case "grass" -> {
System.out.println(enemy.getName() + " loses 35 hp");
enemy.setHp(enemy.getHp() - 35);
}
case "electric" -> {
System.out.println(enemy.getName() + " loses 10 hp");
enemy.setHp(enemy.getHp() - 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
}
public void thunder(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " hits " + enemy.getName() + " with Thunder");
switch (enemy.getType()) {
case "fire" -> {
System.out.println(enemy.getName() + " loses 20 hp");
enemy.setHp(enemy.getHp() - 20);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 50 hp");
enemy.setHp(enemy.getHp() - 50);
}
case "grass" -> {
System.out.println(enemy.getName() + " loses 30 hp");
enemy.setHp(enemy.getHp() - 30);
}
case "electric" -> {
System.out.println(enemy.getName() + " gaines 10 hp");
System.out.println(name.getName() + " gaines 10 hp");
enemy.setHp(enemy.getHp() + 10);
name.setHp(name.getHp() + 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
System.out.println(name.getName() + " has " + name.getHp() + " hp left");
}
public void voltTackle(Pokemon name, Pokemon enemy){
System.out.println(name.getName() + " uses a VoltTackle on " + enemy.getName());
switch (enemy.getType()) {
case "fire" -> {
System.out.println(enemy.getName() + " loses 20 hp");
enemy.setHp(enemy.getHp() - 20);
}
case "water" -> {
System.out.println(enemy.getName() + " loses 40 hp");
enemy.setHp(enemy.getHp() - 40);
}
case "grass" -> {
System.out.println(enemy.getName() + " loses 30 hp");
enemy.setHp(enemy.getHp() - 30);
}
case "electric" -> {
System.out.println(enemy.getName() + " loses 10 hp");
enemy.setHp(enemy.getHp() - 10);
}
}
System.out.println(enemy.getName() + " has " + enemy.getHp() + " hp left");
}
}
|
76888_1 | import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Created by 11302014 on 4/05/2015.
*/
public class FServer implements Runnable {
private Key myPrivateKey = null;
private Key myPublicKey = null;
FDecryptor fDecryptor = null;
public FServer(Key myPrivateKey, Key myPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException {
this.myPrivateKey = myPrivateKey;
this.myPublicKey = myPublicKey;
this.fDecryptor = new FDecryptor();
}
public void start() {
Thread buf = new Thread(this);
buf.start();
}
@Override
public void run() {
try {
ServerSocket bigSocket = new ServerSocket(FClient.port);
while (true) {
Socket smallSocket = bigSocket.accept();
OutputStream output = smallSocket.getOutputStream();
InputStream input = smallSocket.getInputStream();
Key otherPublicKey = null;
byte[] buffer = new byte[1024*1024];
int bytesReceived = 0;
//versturen van public key
System.out.println("Server: start versturen publickey..." + myPublicKey.getEncoded().length);
output.write(myPublicKey.getEncoded());
output.flush();
//ontvangen van public key
System.out.println("Server: start ontvangen publickey...");
while((bytesReceived = input.read(buffer))>0) {
KeyFactory kf = KeyFactory.getInstance("RSA");
otherPublicKey = kf.generatePublic(new X509EncodedKeySpec(buffer));
System.out.println(bytesReceived);
break;
}
FileOutputStream out = new FileOutputStream("buf.enc");
//ontvangen van file
System.out.println("Server: start ontvangen file...");
while((bytesReceived = input.read(buffer))>0) {
out.write(buffer,0,bytesReceived);
System.out.println(bytesReceived);
break;
}
out.flush();
out.close();
input.close();
smallSocket.close();
//buf file lezen
System.out.println("Server: file lezen...");
FTotalPacket received = FTotalPacket.readEncBuf();
//file decrypteren
System.out.println("Server: file decrypteren...");
byte[] unencryptedFile = fDecryptor.decrypt(received, myPrivateKey, otherPublicKey);
//file weg schrijven
System.out.println("Server: gedecrypte file wegschrijven");
/// save file dialog waar de nieuwe file moet komen
FTotalPacket.writeFile(unencryptedFile, received.getName());
//als.zip decrypten
System.out.println("Server: Zipfile uitpakken...");
unzip(received.getName());
System.out.println("Server: Done!");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private void unzip (String zipFile) {
byte[] buffer = new byte[1024];
File folder = new File ("");
if (!folder.exists()) {
folder.mkdir();
}
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze!=null) {
String fileName = ze.getName();
System.out.println(ze.getName());
File newFile = new File(fileName);
new File (newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile.getName());
int len;
while ((len = zis.read(buffer))>0) {
fos.write(buffer,0,len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| AppDev10/BasicSecurityAppDev10 | src/main/java/FServer.java | 1,388 | //versturen van public key | line_comment | nl | import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Created by 11302014 on 4/05/2015.
*/
public class FServer implements Runnable {
private Key myPrivateKey = null;
private Key myPublicKey = null;
FDecryptor fDecryptor = null;
public FServer(Key myPrivateKey, Key myPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException {
this.myPrivateKey = myPrivateKey;
this.myPublicKey = myPublicKey;
this.fDecryptor = new FDecryptor();
}
public void start() {
Thread buf = new Thread(this);
buf.start();
}
@Override
public void run() {
try {
ServerSocket bigSocket = new ServerSocket(FClient.port);
while (true) {
Socket smallSocket = bigSocket.accept();
OutputStream output = smallSocket.getOutputStream();
InputStream input = smallSocket.getInputStream();
Key otherPublicKey = null;
byte[] buffer = new byte[1024*1024];
int bytesReceived = 0;
//versturen van<SUF>
System.out.println("Server: start versturen publickey..." + myPublicKey.getEncoded().length);
output.write(myPublicKey.getEncoded());
output.flush();
//ontvangen van public key
System.out.println("Server: start ontvangen publickey...");
while((bytesReceived = input.read(buffer))>0) {
KeyFactory kf = KeyFactory.getInstance("RSA");
otherPublicKey = kf.generatePublic(new X509EncodedKeySpec(buffer));
System.out.println(bytesReceived);
break;
}
FileOutputStream out = new FileOutputStream("buf.enc");
//ontvangen van file
System.out.println("Server: start ontvangen file...");
while((bytesReceived = input.read(buffer))>0) {
out.write(buffer,0,bytesReceived);
System.out.println(bytesReceived);
break;
}
out.flush();
out.close();
input.close();
smallSocket.close();
//buf file lezen
System.out.println("Server: file lezen...");
FTotalPacket received = FTotalPacket.readEncBuf();
//file decrypteren
System.out.println("Server: file decrypteren...");
byte[] unencryptedFile = fDecryptor.decrypt(received, myPrivateKey, otherPublicKey);
//file weg schrijven
System.out.println("Server: gedecrypte file wegschrijven");
/// save file dialog waar de nieuwe file moet komen
FTotalPacket.writeFile(unencryptedFile, received.getName());
//als.zip decrypten
System.out.println("Server: Zipfile uitpakken...");
unzip(received.getName());
System.out.println("Server: Done!");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private void unzip (String zipFile) {
byte[] buffer = new byte[1024];
File folder = new File ("");
if (!folder.exists()) {
folder.mkdir();
}
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze!=null) {
String fileName = ze.getName();
System.out.println(ze.getName());
File newFile = new File(fileName);
new File (newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile.getName());
int len;
while ((len = zis.read(buffer))>0) {
fos.write(buffer,0,len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
101760_11 | /*
* This Source is licenced under the NASA OPEN SOURCE AGREEMENT VERSION 1.3
*
* Copyright (C) 2012 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*
* Modifications by MAVinci GmbH, Germany (C) 2009-2016:
* rending of own 3d modells added
*/
package eu.mavinci.desktop.gui.wwext;
import com.intel.missioncontrol.PublishSource;
import eu.mavinci.desktop.gui.wwext.sun.SunPositionProviderSingleton;
import eu.mavinci.desktop.gui.wwext.sunlight.SunPositionProvider;
import eu.mavinci.desktop.main.debug.Debug;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Vec4;
import gov.nasa.worldwind.globes.FlatGlobe;
import gov.nasa.worldwind.render.DrawContext;
import gov.nasa.worldwind.render.Renderable;
import eu.mavinci.desktop.gui.wwext.sun.SunPositionProviderSingleton;
import eu.mavinci.desktop.gui.wwext.sunlight.SunPositionProvider;
import eu.mavinci.desktop.main.debug.Debug;
import net.java.joglutils.model.examples.DisplayListRenderer;
import net.java.joglutils.model.geometry.Model;
import com.jogamp.opengl.GL2;
import java.util.logging.Level;
/** @author RodgersGB, Shawn Gano, Marco Möller, Peter Schauss */
@PublishSource(module = "World Wind", licenses = "nasa-world-wind")
public class WWModel3D implements Renderable {
protected Position position = null;
protected Model model = null;
/** latlon where the sun is perpendicular above ground */
protected LatLon sunPos;
protected double yawDeg = 0; // in degrees
protected double pitchDeg = 0; // in degrees
protected double rollDeg = 0; // in degrees
protected boolean maitainConstantSize = true; // default true
protected double size = 1;
// test rotation
public double angle = 0;
public double xAxis = 0;
public double yAxis = 0;
public double zAxis = 0;
double angle2Rad = 0;
protected DisplayListRenderer renderer = new DisplayListRenderer();
// STK - model - Nadir Alignment with ECF velocity constraint
/** Creates a new instance of WWModel3D_new */
public WWModel3D() {
renderer.debug(false);
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public void setModel(Model model) {
this.model = model;
}
public Model getModel() {
return model;
}
public double getYawDeg() {
return yawDeg;
}
public void setYawDeg(double yawDeg) {
this.yawDeg = yawDeg;
}
public double getPitchDeg() {
return pitchDeg;
}
public void setPitchDeg(double pitchDeg) {
this.pitchDeg = pitchDeg;
}
public double getRollDeg() {
return rollDeg;
}
public void setRollDeg(double rollDeg) {
this.rollDeg = rollDeg;
}
public boolean isConstantSize() {
return maitainConstantSize;
}
/**
* in case of true, the size in METER of the modell will be constant in case of false the size in PIXEL will be
* constant
*
* @param maitainConstantSize
*/
public void setMaitainConstantSize(boolean maitainConstantSize) {
this.maitainConstantSize = maitainConstantSize;
}
public double getSize() {
return size;
}
/**
* sets the size of the airplane: in case of maitainConstantSize==true: the unit is meter in case of
* maitainConstantSize==false: its a relative factor to the internal size of the 3d modell
*
* @param size
*/
public void setSize(double size) {
this.size = size;
}
public float[] computeLightPosition(Vec4 loc) {
// set light from above
Vec4 lightPos = loc.multiply3(1.2);
return new float[] {(float)lightPos.x, (float)lightPos.y, (float)lightPos.z, (float)lightPos.w};
}
// Rendering routines so the object can render itself ------
// ===============================================================
// old doRender
public void render(DrawContext dc) {
if (position == null) {
return;
}
if (model == null) {
return;
}
Position pos = this.getPosition();
Vec4 loc = dc.getGlobe().computePointFromPosition(pos);
double localScale = this.computeSize(dc, loc);
// increase height such that model is above globe
// Bounds b = this.getModel().getBounds();
// float offset = this.getModel().getCenterPoint().z - b.min.z;
// float locLen = (float)Math.sqrt(loc.dot3(loc));
// loc = loc.multiply3((localScale*offset+locLen)/locLen);
if (sunPos == null) {
SunPositionProvider spp = SunPositionProviderSingleton.getInstance();
sunPos = spp.getPosition();
}
Vec4 sun = dc.getGlobe().computePointFromPosition(new Position(sunPos, 0)).normalize3();
float[] lightPos = new float[] {(float)sun.x, (float)sun.y, (float)sun.z, 0.f}; // computeLightPosition(loc);
// System.out.format("sun: %f,$%f,%f,%f",(float)light.x,(float)light.y,(float)light.z,(float)light.w);
try {
beginDraw(dc, lightPos);
draw(dc, loc, localScale, pos.getLongitude(), pos.getLatitude());
}
// handle any exceptions
catch (Exception e) {
Debug.getLog().log(Level.SEVERE, "error rendering plane model", e);
}
// we must end drawing so that opengl
// states do not leak through.
finally {
endDraw(dc);
}
}
/*
* Update the light source properties
*/
private void updateLightSource(GL2 gl, float[] lightPosition) {
/** Ambient light array */
float[] lightAmbient = {0.4f, 0.4f, 0.4f};
/** Diffuse light array */
float[] lightDiffuse = {0.25f, 0.25f, 0.25f, 1.f};
/** Specular light array */
float[] lightSpecular = {1.f, 1.f, 1.f, 1.f};
float[] model_ambient = {0.2f, 0.2f, 0.2f, 1.f};
// Experimental: trying everything with light0 instead of light1
gl.glLightModelfv(GL2.GL_LIGHT_MODEL_AMBIENT, model_ambient, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, lightPosition, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, lightDiffuse, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, lightAmbient, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPECULAR, lightSpecular, 0);
// gl.glDisable(GL2.GL_LIGHT0);
gl.glEnable(GL2.GL_LIGHT0);
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_NORMALIZE);
// experimental lines:
gl.glColorMaterial(GL2.GL_FRONT_AND_BACK, GL2.GL_EMISSION);
gl.glEnable(GL2.GL_COLOR_MATERIAL);
// gl.glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, constantAttenuation);
// gl.glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, linearAttenuation);
// gl.glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, quadraticAttenuation);
}
// draw this layer
protected void draw(DrawContext dc, Vec4 loc, double localScale, Angle lon, Angle lat) {
GL2 gl = dc.getGL().getGL2();
if (dc.getView().getFrustumInModelCoordinates().contains(loc)) {
// MAYBE REPLACE "PUSH REFERENCE CENTER" - with gl. move to new center... (maybe not)
// gl.glColor4f(1.0f, 1.0f, 1.0f, 0.5f); // Full Brightness. 50% Alpha (new )
// Set The Blending Function For Translucency (new )
// gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
dc.getView().pushReferenceCenter(dc, loc);
if (!(dc.getView().getGlobe() instanceof FlatGlobe)) {
gl.glRotated(lon.degrees, 0, 1, 0);
gl.glRotated(-lat.degrees, 1, 0, 0);
}
gl.glScaled(localScale, localScale, localScale); // / can change the scale of the model here!!
// MM: TODO diese rotationen sind eher empirisch!
// man sollte auch auf die reihenfolge der roation achten, stimmt die?
// PM: Reihenfolge stimmt, siehe Tait-Bryan-Winkel.
// Die 90° sind 3d-Modell-bedingt. WW verwendet offenbar nicht das TB-System (Z-Achse in den Boden hinein)
// Das neue 3d-Modell ist TB-konform.
/*
* drehungen für piper-modell gl.glRotated(90-model.getYawDeg(), 0,0,1); gl.glRotated(-model.getPitchDeg(), 0,1,0);
* gl.glRotated(180-model.getRollDeg(), 1,0,0); //stimmt der roll winkel? PM: Jetzt ja!
*/
// roll pitch yaw / x y z
gl.glRotated(-getYawDeg(), 0, 0, 1);
gl.glRotated(getPitchDeg(), 1, 0, 0);
gl.glRotated(-getRollDeg(), 0, 1, 0);
// gl.glRotated(getRollDeg(), 1,0,0);
// gl.glRotated(getPitchDeg(), 0,1,0);
// gl.glRotated(-getYawDeg(), 0,0,1);
// fix coordinate system differences between opengl and obj-file format
// coordinates system is official rollpitchyaw system in blender
// and exported with rotate fix on
// this rotation brings the plane in direction roll/pitch/yaw = 0/0/0
gl.glRotated(90, 0, 0, 1);
gl.glRotated(0, 0, 1, 0);
gl.glRotated(-90, 1, 0, 0);
/* das sind die drehungen für das alte redplane modell */
// gl.glRotated(270-getYawDeg(), 0,0,1);
// gl.glRotated(getPitchDeg(), 0,1,0);
// gl.glRotated(getRollDeg(), 1,0,0); //stimmt der roll winkel?
// miniplane.3ds
// gl.glRotated(90-model.getYawDeg(), 0,0,1);
// gl.glRotated(-model.getPitchDeg(), 0,1,0);
// gl.glRotated(90-model.getRollDeg(), 1,0,0); //stimmt der roll winkel?
gl.glEnable(GL2.GL_CULL_FACE);
gl.glShadeModel(GL2.GL_SMOOTH); // gl.glShadeModel(GL.GL_FLAT);
gl.glEnable(GL2.GL_DEPTH_TEST);
gl.glDepthFunc(GL2.GL_LEQUAL);
gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
// Get an instance of the display list renderer
// iModel3DRenderer renderer = DisplayListRenderer.getInstance();
renderer.render(gl, getModel());
dc.getView().popReferenceCenter(dc);
}
}
// puts opengl in the correct state for this layer
protected void beginDraw(DrawContext dc, float[] lightPosition) {
GL2 gl = dc.getGL().getGL2();
gl.glPushAttrib(
GL2.GL_TEXTURE_BIT
| GL2.GL_COLOR_BUFFER_BIT
| GL2.GL_DEPTH_BUFFER_BIT
| GL2.GL_HINT_BIT
| GL2.GL_POLYGON_BIT
| GL2.GL_ENABLE_BIT
| GL2.GL_CURRENT_BIT
| GL2.GL_LIGHTING_BIT
| GL2.GL_TRANSFORM_BIT);
updateLightSource(gl, lightPosition);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glPushMatrix();
}
// resets opengl state
protected void endDraw(DrawContext dc) {
GL2 gl = dc.getGL().getGL2();
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glPopMatrix();
gl.glPopAttrib();
}
private double computeSize(DrawContext dc, Vec4 loc) {
if (this.maitainConstantSize) {
return size;
}
if (loc == null) {
System.err.println("Null location when computing size of model");
return 1;
}
double d = loc.distanceTo3(dc.getView().getEyePoint());
double currentSize = 60 * dc.getView().computePixelSizeAtDistance(d);
if (currentSize < 2) {
currentSize = 2;
}
return currentSize * size;
}
}
| ArduPilot/OMC | IntelMissionControl/src/main/java/eu/mavinci/desktop/gui/wwext/WWModel3D.java | 3,954 | // float offset = this.getModel().getCenterPoint().z - b.min.z; | line_comment | nl | /*
* This Source is licenced under the NASA OPEN SOURCE AGREEMENT VERSION 1.3
*
* Copyright (C) 2012 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*
* Modifications by MAVinci GmbH, Germany (C) 2009-2016:
* rending of own 3d modells added
*/
package eu.mavinci.desktop.gui.wwext;
import com.intel.missioncontrol.PublishSource;
import eu.mavinci.desktop.gui.wwext.sun.SunPositionProviderSingleton;
import eu.mavinci.desktop.gui.wwext.sunlight.SunPositionProvider;
import eu.mavinci.desktop.main.debug.Debug;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Vec4;
import gov.nasa.worldwind.globes.FlatGlobe;
import gov.nasa.worldwind.render.DrawContext;
import gov.nasa.worldwind.render.Renderable;
import eu.mavinci.desktop.gui.wwext.sun.SunPositionProviderSingleton;
import eu.mavinci.desktop.gui.wwext.sunlight.SunPositionProvider;
import eu.mavinci.desktop.main.debug.Debug;
import net.java.joglutils.model.examples.DisplayListRenderer;
import net.java.joglutils.model.geometry.Model;
import com.jogamp.opengl.GL2;
import java.util.logging.Level;
/** @author RodgersGB, Shawn Gano, Marco Möller, Peter Schauss */
@PublishSource(module = "World Wind", licenses = "nasa-world-wind")
public class WWModel3D implements Renderable {
protected Position position = null;
protected Model model = null;
/** latlon where the sun is perpendicular above ground */
protected LatLon sunPos;
protected double yawDeg = 0; // in degrees
protected double pitchDeg = 0; // in degrees
protected double rollDeg = 0; // in degrees
protected boolean maitainConstantSize = true; // default true
protected double size = 1;
// test rotation
public double angle = 0;
public double xAxis = 0;
public double yAxis = 0;
public double zAxis = 0;
double angle2Rad = 0;
protected DisplayListRenderer renderer = new DisplayListRenderer();
// STK - model - Nadir Alignment with ECF velocity constraint
/** Creates a new instance of WWModel3D_new */
public WWModel3D() {
renderer.debug(false);
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public void setModel(Model model) {
this.model = model;
}
public Model getModel() {
return model;
}
public double getYawDeg() {
return yawDeg;
}
public void setYawDeg(double yawDeg) {
this.yawDeg = yawDeg;
}
public double getPitchDeg() {
return pitchDeg;
}
public void setPitchDeg(double pitchDeg) {
this.pitchDeg = pitchDeg;
}
public double getRollDeg() {
return rollDeg;
}
public void setRollDeg(double rollDeg) {
this.rollDeg = rollDeg;
}
public boolean isConstantSize() {
return maitainConstantSize;
}
/**
* in case of true, the size in METER of the modell will be constant in case of false the size in PIXEL will be
* constant
*
* @param maitainConstantSize
*/
public void setMaitainConstantSize(boolean maitainConstantSize) {
this.maitainConstantSize = maitainConstantSize;
}
public double getSize() {
return size;
}
/**
* sets the size of the airplane: in case of maitainConstantSize==true: the unit is meter in case of
* maitainConstantSize==false: its a relative factor to the internal size of the 3d modell
*
* @param size
*/
public void setSize(double size) {
this.size = size;
}
public float[] computeLightPosition(Vec4 loc) {
// set light from above
Vec4 lightPos = loc.multiply3(1.2);
return new float[] {(float)lightPos.x, (float)lightPos.y, (float)lightPos.z, (float)lightPos.w};
}
// Rendering routines so the object can render itself ------
// ===============================================================
// old doRender
public void render(DrawContext dc) {
if (position == null) {
return;
}
if (model == null) {
return;
}
Position pos = this.getPosition();
Vec4 loc = dc.getGlobe().computePointFromPosition(pos);
double localScale = this.computeSize(dc, loc);
// increase height such that model is above globe
// Bounds b = this.getModel().getBounds();
// float offset<SUF>
// float locLen = (float)Math.sqrt(loc.dot3(loc));
// loc = loc.multiply3((localScale*offset+locLen)/locLen);
if (sunPos == null) {
SunPositionProvider spp = SunPositionProviderSingleton.getInstance();
sunPos = spp.getPosition();
}
Vec4 sun = dc.getGlobe().computePointFromPosition(new Position(sunPos, 0)).normalize3();
float[] lightPos = new float[] {(float)sun.x, (float)sun.y, (float)sun.z, 0.f}; // computeLightPosition(loc);
// System.out.format("sun: %f,$%f,%f,%f",(float)light.x,(float)light.y,(float)light.z,(float)light.w);
try {
beginDraw(dc, lightPos);
draw(dc, loc, localScale, pos.getLongitude(), pos.getLatitude());
}
// handle any exceptions
catch (Exception e) {
Debug.getLog().log(Level.SEVERE, "error rendering plane model", e);
}
// we must end drawing so that opengl
// states do not leak through.
finally {
endDraw(dc);
}
}
/*
* Update the light source properties
*/
private void updateLightSource(GL2 gl, float[] lightPosition) {
/** Ambient light array */
float[] lightAmbient = {0.4f, 0.4f, 0.4f};
/** Diffuse light array */
float[] lightDiffuse = {0.25f, 0.25f, 0.25f, 1.f};
/** Specular light array */
float[] lightSpecular = {1.f, 1.f, 1.f, 1.f};
float[] model_ambient = {0.2f, 0.2f, 0.2f, 1.f};
// Experimental: trying everything with light0 instead of light1
gl.glLightModelfv(GL2.GL_LIGHT_MODEL_AMBIENT, model_ambient, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, lightPosition, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, lightDiffuse, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, lightAmbient, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPECULAR, lightSpecular, 0);
// gl.glDisable(GL2.GL_LIGHT0);
gl.glEnable(GL2.GL_LIGHT0);
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_NORMALIZE);
// experimental lines:
gl.glColorMaterial(GL2.GL_FRONT_AND_BACK, GL2.GL_EMISSION);
gl.glEnable(GL2.GL_COLOR_MATERIAL);
// gl.glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, constantAttenuation);
// gl.glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, linearAttenuation);
// gl.glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, quadraticAttenuation);
}
// draw this layer
protected void draw(DrawContext dc, Vec4 loc, double localScale, Angle lon, Angle lat) {
GL2 gl = dc.getGL().getGL2();
if (dc.getView().getFrustumInModelCoordinates().contains(loc)) {
// MAYBE REPLACE "PUSH REFERENCE CENTER" - with gl. move to new center... (maybe not)
// gl.glColor4f(1.0f, 1.0f, 1.0f, 0.5f); // Full Brightness. 50% Alpha (new )
// Set The Blending Function For Translucency (new )
// gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
dc.getView().pushReferenceCenter(dc, loc);
if (!(dc.getView().getGlobe() instanceof FlatGlobe)) {
gl.glRotated(lon.degrees, 0, 1, 0);
gl.glRotated(-lat.degrees, 1, 0, 0);
}
gl.glScaled(localScale, localScale, localScale); // / can change the scale of the model here!!
// MM: TODO diese rotationen sind eher empirisch!
// man sollte auch auf die reihenfolge der roation achten, stimmt die?
// PM: Reihenfolge stimmt, siehe Tait-Bryan-Winkel.
// Die 90° sind 3d-Modell-bedingt. WW verwendet offenbar nicht das TB-System (Z-Achse in den Boden hinein)
// Das neue 3d-Modell ist TB-konform.
/*
* drehungen für piper-modell gl.glRotated(90-model.getYawDeg(), 0,0,1); gl.glRotated(-model.getPitchDeg(), 0,1,0);
* gl.glRotated(180-model.getRollDeg(), 1,0,0); //stimmt der roll winkel? PM: Jetzt ja!
*/
// roll pitch yaw / x y z
gl.glRotated(-getYawDeg(), 0, 0, 1);
gl.glRotated(getPitchDeg(), 1, 0, 0);
gl.glRotated(-getRollDeg(), 0, 1, 0);
// gl.glRotated(getRollDeg(), 1,0,0);
// gl.glRotated(getPitchDeg(), 0,1,0);
// gl.glRotated(-getYawDeg(), 0,0,1);
// fix coordinate system differences between opengl and obj-file format
// coordinates system is official rollpitchyaw system in blender
// and exported with rotate fix on
// this rotation brings the plane in direction roll/pitch/yaw = 0/0/0
gl.glRotated(90, 0, 0, 1);
gl.glRotated(0, 0, 1, 0);
gl.glRotated(-90, 1, 0, 0);
/* das sind die drehungen für das alte redplane modell */
// gl.glRotated(270-getYawDeg(), 0,0,1);
// gl.glRotated(getPitchDeg(), 0,1,0);
// gl.glRotated(getRollDeg(), 1,0,0); //stimmt der roll winkel?
// miniplane.3ds
// gl.glRotated(90-model.getYawDeg(), 0,0,1);
// gl.glRotated(-model.getPitchDeg(), 0,1,0);
// gl.glRotated(90-model.getRollDeg(), 1,0,0); //stimmt der roll winkel?
gl.glEnable(GL2.GL_CULL_FACE);
gl.glShadeModel(GL2.GL_SMOOTH); // gl.glShadeModel(GL.GL_FLAT);
gl.glEnable(GL2.GL_DEPTH_TEST);
gl.glDepthFunc(GL2.GL_LEQUAL);
gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
// Get an instance of the display list renderer
// iModel3DRenderer renderer = DisplayListRenderer.getInstance();
renderer.render(gl, getModel());
dc.getView().popReferenceCenter(dc);
}
}
// puts opengl in the correct state for this layer
protected void beginDraw(DrawContext dc, float[] lightPosition) {
GL2 gl = dc.getGL().getGL2();
gl.glPushAttrib(
GL2.GL_TEXTURE_BIT
| GL2.GL_COLOR_BUFFER_BIT
| GL2.GL_DEPTH_BUFFER_BIT
| GL2.GL_HINT_BIT
| GL2.GL_POLYGON_BIT
| GL2.GL_ENABLE_BIT
| GL2.GL_CURRENT_BIT
| GL2.GL_LIGHTING_BIT
| GL2.GL_TRANSFORM_BIT);
updateLightSource(gl, lightPosition);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glPushMatrix();
}
// resets opengl state
protected void endDraw(DrawContext dc) {
GL2 gl = dc.getGL().getGL2();
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glPopMatrix();
gl.glPopAttrib();
}
private double computeSize(DrawContext dc, Vec4 loc) {
if (this.maitainConstantSize) {
return size;
}
if (loc == null) {
System.err.println("Null location when computing size of model");
return 1;
}
double d = loc.distanceTo3(dc.getView().getEyePoint());
double currentSize = 60 * dc.getView().computePixelSizeAtDistance(d);
if (currentSize < 2) {
currentSize = 2;
}
return currentSize * size;
}
}
|
138855_1 | /*
* Copyright (c) 2018 W.I.S.V. 'Christiaan Huygens'
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.wisv.areafiftylan.utils;
import ch.wisv.areafiftylan.extras.consumption.model.Consumption;
import ch.wisv.areafiftylan.extras.consumption.model.PossibleConsumptionsRepository;
import ch.wisv.areafiftylan.extras.consumption.service.ConsumptionService;
import ch.wisv.areafiftylan.extras.rfid.model.RFIDLink;
import ch.wisv.areafiftylan.extras.rfid.service.RFIDLinkRepository;
import ch.wisv.areafiftylan.products.model.Ticket;
import ch.wisv.areafiftylan.products.model.TicketOption;
import ch.wisv.areafiftylan.products.model.TicketType;
import ch.wisv.areafiftylan.products.model.order.OrderStatus;
import ch.wisv.areafiftylan.products.service.repository.OrderRepository;
import ch.wisv.areafiftylan.products.service.repository.TicketOptionRepository;
import ch.wisv.areafiftylan.products.service.repository.TicketRepository;
import ch.wisv.areafiftylan.products.service.repository.TicketTypeRepository;
import ch.wisv.areafiftylan.products.service.OrderService;
import ch.wisv.areafiftylan.products.model.order.Order;
import ch.wisv.areafiftylan.seats.model.SeatGroupDTO;
import ch.wisv.areafiftylan.seats.service.SeatService;
import ch.wisv.areafiftylan.teams.model.Team;
import ch.wisv.areafiftylan.teams.service.TeamRepository;
import ch.wisv.areafiftylan.users.model.Gender;
import ch.wisv.areafiftylan.users.model.Role;
import ch.wisv.areafiftylan.users.model.User;
import ch.wisv.areafiftylan.users.service.UserRepository;
import ch.wisv.areafiftylan.web.banner.model.Banner;
import ch.wisv.areafiftylan.web.banner.service.BannerRepository;
import ch.wisv.areafiftylan.web.committee.model.CommitteeMember;
import ch.wisv.areafiftylan.web.committee.service.CommitteeRepository;
import ch.wisv.areafiftylan.web.faq.model.FaqPair;
import ch.wisv.areafiftylan.web.faq.service.FaqRepository;
import ch.wisv.areafiftylan.web.sponsor.model.Sponsor;
import ch.wisv.areafiftylan.web.sponsor.model.SponsorType;
import ch.wisv.areafiftylan.web.sponsor.service.SponsorRepository;
import ch.wisv.areafiftylan.web.tournament.model.Tournament;
import ch.wisv.areafiftylan.web.tournament.model.TournamentType;
import ch.wisv.areafiftylan.web.tournament.service.TournamentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.EventListener;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Component
@Profile("dev")
public class TestDataRunner {
private final UserRepository accountRepository;
private final TicketRepository ticketRepository;
private final SeatService seatService;
private final TeamRepository teamRepository;
private final TicketOptionRepository ticketOptionRepository;
private final TicketTypeRepository ticketTypeRepository;
private final RFIDLinkRepository rfidLinkRepository;
private final PossibleConsumptionsRepository consumptionsRepository;
private final ConsumptionService consumptionService;
private final BannerRepository bannerRepository;
private final CommitteeRepository committeeRepository;
private final FaqRepository faqRepository;
private final SponsorRepository sponsorRepository;
private final TournamentRepository tournamentRepository;
private final OrderService orderService;
private final OrderRepository orderRepository;
@Autowired
public TestDataRunner(UserRepository accountRepository, TicketRepository ticketRepository,
TeamRepository teamRepository, SeatService seatService,
TicketOptionRepository ticketOptionRepository, TicketTypeRepository ticketTypeRepository,
RFIDLinkRepository rfidLinkRepository, PossibleConsumptionsRepository consumptionsRepository,
ConsumptionService consumptionService, BannerRepository bannerRepository, CommitteeRepository committeeRepository,
FaqRepository faqRepository, SponsorRepository sponsorRepository,
TournamentRepository tournamentRepository, OrderService orderService, OrderRepository orderRepository) {
this.accountRepository = accountRepository;
this.ticketRepository = ticketRepository;
this.seatService = seatService;
this.teamRepository = teamRepository;
this.ticketOptionRepository = ticketOptionRepository;
this.ticketTypeRepository = ticketTypeRepository;
this.rfidLinkRepository = rfidLinkRepository;
this.consumptionsRepository = consumptionsRepository;
this.consumptionService = consumptionService;
this.bannerRepository = bannerRepository;
this.committeeRepository = committeeRepository;
this.faqRepository = faqRepository;
this.sponsorRepository = sponsorRepository;
this.tournamentRepository = tournamentRepository;
this.orderService = orderService;
this.orderRepository = orderRepository;
}
@EventListener(ApplicationStartedEvent.class)
public void insertTestData() {
//region Users
LocalDate localDate = LocalDate.of(2000, 1, 2);
User userAdmin = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
userAdmin.addRole(Role.ROLE_ADMIN);
User userNormal = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
User userCaptain = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
User userInvalidTicket = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
User userNoTicket = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
userAdmin.getProfile()
.setAllFields("Jan", "de Groot", "MonsterKiller9001", LocalDate.of(1990, 2, 1), Gender.MALE, "Mekelweg 4", "2826CD",
"Delft", "0906-0666", null);
userNormal.getProfile()
.setAllFields("Bert", "Kleijn", "ILoveZombies", localDate, Gender.OTHER, "Mekelweg 20", "2826CD",
"Amsterdam", "0611", null);
userInvalidTicket.getProfile()
.setAllFields("Katrien", "Zwanenburg", "Admiral Cheesecake", localDate, Gender.FEMALE, "Ganzenlaan 5",
"2826CD", "Duckstad", "0906-0666", null);
userNoTicket.getProfile()
.setAllFields("Kees", "Jager", "l33tz0r", localDate, Gender.MALE, "Herenweg 2", "2826CD", "Delft",
"0902-30283", null);
userCaptain.getProfile()
.setAllFields("Gert", "Gertson", "Whosyourdaddy", localDate, Gender.MALE, "Jansstraat", "8826CD",
"Delft", "0238-2309736", null);
userAdmin = accountRepository.saveAndFlush(userAdmin);
userNormal = accountRepository.saveAndFlush(userNormal);
userCaptain = accountRepository.saveAndFlush(userCaptain);
userInvalidTicket = accountRepository.saveAndFlush(userInvalidTicket);
userNoTicket = accountRepository.saveAndFlush(userNoTicket);
//endregion Users
//region Tickets
TicketOption chMember = ticketOptionRepository.save(new TicketOption("chMember", -5F));
TicketOption pickupService = ticketOptionRepository.save(new TicketOption("pickupService", 2.5F));
TicketType early = new TicketType("Early", "Early Bird", 35F, 50, LocalDateTime.now().plusDays(7L), true);
early.addPossibleOption(chMember);
early.addPossibleOption(pickupService);
early = ticketTypeRepository.save(early);
TicketType normal = new TicketType("Normal", "Normal Ticket", 40F, 0, LocalDateTime.now().plusDays(7L), true);
normal.addPossibleOption(chMember);
normal.addPossibleOption(pickupService);
normal = ticketTypeRepository.save(normal);
TicketType late = new TicketType("Late", "Last Minute", 42.5F, 0, LocalDateTime.now().plusDays(14L), true);
late.addPossibleOption(chMember);
late.addPossibleOption(pickupService);
late = ticketTypeRepository.save(late);
Ticket ticketAdmin = new Ticket(userAdmin, normal);
ticketAdmin.addOption(chMember);
ticketAdmin.addOption(pickupService);
ticketAdmin.setValid(true);
ticketRepository.save(ticketAdmin);
Ticket ticketCaptain = new Ticket(userCaptain, early);
ticketCaptain.addOption(chMember);
ticketCaptain.addOption(pickupService);
ticketCaptain.setValid(true);
ticketRepository.save(ticketCaptain);
Ticket ticketNormal = new Ticket(userNormal, normal);
ticketNormal.addOption(pickupService);
ticketNormal.setValid(true);
ticketRepository.save(ticketNormal);
Ticket ticketInvalid = new Ticket(userInvalidTicket, late);
ticketInvalid.setValid(false);
ticketRepository.save(ticketInvalid);
//endregion Tickets
//region RFID
RFIDLink rfidLink1 = new RFIDLink("0000000001", ticketAdmin);
RFIDLink rfidLink2 = new RFIDLink("0000000002", ticketCaptain);
RFIDLink rfidLink3 = new RFIDLink("0000000003", ticketNormal);
rfidLinkRepository.saveAndFlush(rfidLink1);
rfidLinkRepository.saveAndFlush(rfidLink2);
rfidLinkRepository.saveAndFlush(rfidLink3);
//endregion RFID
//region Consumptions
Consumption ontbijt = new Consumption("Ontbijt");
ontbijt = consumptionsRepository.saveAndFlush(ontbijt);
Consumption lunch = new Consumption("Lunch");
lunch = consumptionsRepository.saveAndFlush(lunch);
consumptionService.consume(ticketAdmin.getId(), ontbijt.getId());
consumptionService.consume(ticketAdmin.getId(), lunch.getId());
consumptionService.consume(ticketCaptain.getId(), ontbijt.getId());
consumptionService.consume(ticketNormal.getId(), ontbijt.getId());
//endregion Consumptions
//region Team
Team team = new Team("Test Team", userCaptain);
team.addMember(userNormal);
team.addMember(userInvalidTicket);
teamRepository.save(team);
Team team2 = new Team("Admin's Team", userAdmin);
team2.addMember(userCaptain);
team2.addMember(userNoTicket);
teamRepository.save(team2);
//endregion Team
//region Seat
for (char s = 'A'; s <= 'J'; s++) {
SeatGroupDTO seatGroup = new SeatGroupDTO();
seatGroup.setNumberOfSeats(16);
seatGroup.setSeatGroupName(String.valueOf(s));
seatService.addSeats(seatGroup);
}
seatService.setAllSeatsLock(false);
seatService.reserveSeat("A", 1, ticketAdmin.getId(), false);
seatService.reserveSeat("A", 2, ticketCaptain.getId(), false);
seatService.reserveSeat("B", 1, ticketNormal.getId(), false);
//endregion Seat
//region Banner
Date winterBreakStart = Date.valueOf("2017-12-23");
Date winterBreakEnd = Date.valueOf("2018-01-07");
String winterBreak = "Enjoy the winter break! AreaFiftyLAN isn't far from happening!";
Date soonAnnouncementStart = Date.valueOf("2018-02-03");
Date soonAnnouncementEnd = Date.valueOf("2018-02-28");
String soonAnnouncement = "AreaFiftyLAN starts in less than a month! Make sure to get your tickets!";
Date soldOutStart = Date.valueOf("2018-03-01");
Date soldOutEnd = Date.valueOf("2018-03-08");
String soldOut = "Tickets are sold out!";
banner(winterBreak, winterBreakStart, winterBreakEnd);
banner(soonAnnouncement, soonAnnouncementStart, soonAnnouncementEnd);
banner(soldOut, soldOutStart, soldOutEnd);
//endregion Banner
//region Web Data
committeeMember(1L, "Chairman", "Mark Rutte", "gavel");
committeeMember(2L, "Secretary", "Lodewijk Asscher", "chrome-reader-mode");
committeeMember(3L, "Treasurer", "Jeroen Dijsselbloem", "attach-money");
committeeMember(4L, "Commissioner of Promo", "Frans Timmermans", "notifications");
committeeMember(5L, "Commissioner of Logistics", "Melanie Schultz", "local-shipping");
committeeMember(6L, "Commissioner of Systems", "Klaas Dijkhoff", "settings");
committeeMember(7L, "Qualitate Qua", "Ivo Opstelten", "announcement");
faqpair("What the fox say?", "Ring-ding-ding-ding-dingeringeding!");
faqpair("What do you get if you multiply six by nine?", "42");
faqpair("What is your favorite colour?", "Blue.");
faqpair("What is the capital of Assyria?", "Well I don't know!");
faqpair("What is your favorite colour?", "Blue! no, Yellow!");
faqpair("What is the airspeed velocity of an unladen swallow?", "What do you mean? African or European swallow?");
sponsor("Christiaan Huygens", SponsorType.PRESENTER, "https://ch.tudelft.nl", "images-optimized/lancie/logo_CH.png");
sponsor("TU Delft", SponsorType.PRESENTER, "https://www.tudelft.nl", "images-optimized/logos/logo_SC.png");
Sponsor sogeti = sponsor("Sogeti", SponsorType.PREMIUM, "https://www.sogeti.nl/", "images-optimized/logos/sogeti.png");
sponsor("Nutanix", SponsorType.PREMIUM, "https://www.nutanix.com", "images-optimized/logos/nutanix.png");
sponsor("OGD", SponsorType.PREMIUM, "https://ogd.nl/", "images-optimized/logos/ogd.png");
Sponsor coolerMaster = sponsor("CoolerMaster", SponsorType.NORMAL, "http://www.coolermaster.com/", "images-optimized/logos/Cooler_Master_Logo.png");
sponsor("Spam", SponsorType.NORMAL, "http://www.spam-energydrink.com/", "images-optimized/logos/spam-logo.jpg");
sponsor("Jigsaw", SponsorType.NORMAL, "http://www.jigsaw.nl/", "images-optimized/logos/jigsaw_cleaner_logo.png");
sponsor("TransIP", SponsorType.NORMAL, "https://www.transip.nl/", "images-optimized/logos/transip_logo.png");
tournament(TournamentType.OFFICIAL, "RL", "images-optimized/activities/rl.jpg", "3 V 3", "Rocket League",
"Rocket League is a fun game.", Arrays.asList("Huis", "Koelkast", "Broodrooster"), sogeti);
tournament(TournamentType.OFFICIAL, "HS", "images-optimized/activities/hs.jpg", "1 V 1", "Hearthstone",
"Hearthstone is not a fun game.", Arrays.asList("Keyboard", "Muis", "50 Packs"), coolerMaster);
tournament(TournamentType.UNOFFICIAL, "Achtung", "images-optimized/unofficial/achtung.jpg", "1 V 1",
"Achtung Die Kurve", "Achtung!", Arrays.asList("Kratje Hertog Jan", "Kratje Heineken", "Kratje Amstel"), null);
tournament(TournamentType.UNOFFICIAL, "JD", "images-optimized/unofficial/justdance.jpg", "2 V 2", "Just Dance",
"Just Dance is about dancing.", Collections.singletonList("Nothing."), sogeti);
//endregion Web Data
//region Orders
Order order_admin = orderService.create("Normal", null);
orderService.assignOrderToUser(order_admin.getId(), userAdmin.getId());
order_admin.setStatus(OrderStatus.PAID);
orderRepository.save(order_admin);
Order order_normal = orderService.create("Normal", null);
orderService.assignOrderToUser(order_normal.getId(), userNormal.getId());
order_normal.setStatus(OrderStatus.PAID);
orderRepository.save(order_admin);
//endregion Orders
}
private CommitteeMember committeeMember(Long position, String function, String name, String icon) {
CommitteeMember committeeMember = new CommitteeMember();
committeeMember.setPosition(position);
committeeMember.setFunction(function);
committeeMember.setName(name);
committeeMember.setIcon(icon);
return committeeRepository.save(committeeMember);
}
private FaqPair faqpair(String question, String answer) {
FaqPair faqPair = new FaqPair();
faqPair.setQuestion(question);
faqPair.setAnswer(answer);
return faqRepository.save(faqPair);
}
private Sponsor sponsor(String name, SponsorType type, String website, String imageName) {
Sponsor sponsor = new Sponsor();
sponsor.setName(name);
sponsor.setType(type);
sponsor.setWebsite(website);
sponsor.setImageName(imageName);
return sponsorRepository.save(sponsor);
}
private Tournament tournament(TournamentType type, String buttonTitle, String buttonImagePath, String format,
String headerTitle, String description, List<String> prizes, Sponsor sponsor) {
Tournament tournament = new Tournament();
tournament.setType(type);
tournament.setButtonTitle(buttonTitle);
tournament.setButtonImagePath(buttonImagePath);
tournament.setFormat(format);
tournament.setHeaderTitle(headerTitle);
tournament.setDescription(description);
tournament.setPrizes(prizes);
tournament.setSponsor(sponsor);
return tournamentRepository.save(tournament);
}
private Banner banner(String text, Date startDate, Date endDate) {
Banner banner = new Banner();
banner.setText(text);
banner.setStartDate(startDate);
banner.setEndDate(endDate);
return bannerRepository.save(banner);
}
}
| AreaFiftyLAN/lancie-api | src/main/java/ch/wisv/areafiftylan/utils/TestDataRunner.java | 5,578 | //region Web Data | line_comment | nl | /*
* Copyright (c) 2018 W.I.S.V. 'Christiaan Huygens'
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.wisv.areafiftylan.utils;
import ch.wisv.areafiftylan.extras.consumption.model.Consumption;
import ch.wisv.areafiftylan.extras.consumption.model.PossibleConsumptionsRepository;
import ch.wisv.areafiftylan.extras.consumption.service.ConsumptionService;
import ch.wisv.areafiftylan.extras.rfid.model.RFIDLink;
import ch.wisv.areafiftylan.extras.rfid.service.RFIDLinkRepository;
import ch.wisv.areafiftylan.products.model.Ticket;
import ch.wisv.areafiftylan.products.model.TicketOption;
import ch.wisv.areafiftylan.products.model.TicketType;
import ch.wisv.areafiftylan.products.model.order.OrderStatus;
import ch.wisv.areafiftylan.products.service.repository.OrderRepository;
import ch.wisv.areafiftylan.products.service.repository.TicketOptionRepository;
import ch.wisv.areafiftylan.products.service.repository.TicketRepository;
import ch.wisv.areafiftylan.products.service.repository.TicketTypeRepository;
import ch.wisv.areafiftylan.products.service.OrderService;
import ch.wisv.areafiftylan.products.model.order.Order;
import ch.wisv.areafiftylan.seats.model.SeatGroupDTO;
import ch.wisv.areafiftylan.seats.service.SeatService;
import ch.wisv.areafiftylan.teams.model.Team;
import ch.wisv.areafiftylan.teams.service.TeamRepository;
import ch.wisv.areafiftylan.users.model.Gender;
import ch.wisv.areafiftylan.users.model.Role;
import ch.wisv.areafiftylan.users.model.User;
import ch.wisv.areafiftylan.users.service.UserRepository;
import ch.wisv.areafiftylan.web.banner.model.Banner;
import ch.wisv.areafiftylan.web.banner.service.BannerRepository;
import ch.wisv.areafiftylan.web.committee.model.CommitteeMember;
import ch.wisv.areafiftylan.web.committee.service.CommitteeRepository;
import ch.wisv.areafiftylan.web.faq.model.FaqPair;
import ch.wisv.areafiftylan.web.faq.service.FaqRepository;
import ch.wisv.areafiftylan.web.sponsor.model.Sponsor;
import ch.wisv.areafiftylan.web.sponsor.model.SponsorType;
import ch.wisv.areafiftylan.web.sponsor.service.SponsorRepository;
import ch.wisv.areafiftylan.web.tournament.model.Tournament;
import ch.wisv.areafiftylan.web.tournament.model.TournamentType;
import ch.wisv.areafiftylan.web.tournament.service.TournamentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.EventListener;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Component
@Profile("dev")
public class TestDataRunner {
private final UserRepository accountRepository;
private final TicketRepository ticketRepository;
private final SeatService seatService;
private final TeamRepository teamRepository;
private final TicketOptionRepository ticketOptionRepository;
private final TicketTypeRepository ticketTypeRepository;
private final RFIDLinkRepository rfidLinkRepository;
private final PossibleConsumptionsRepository consumptionsRepository;
private final ConsumptionService consumptionService;
private final BannerRepository bannerRepository;
private final CommitteeRepository committeeRepository;
private final FaqRepository faqRepository;
private final SponsorRepository sponsorRepository;
private final TournamentRepository tournamentRepository;
private final OrderService orderService;
private final OrderRepository orderRepository;
@Autowired
public TestDataRunner(UserRepository accountRepository, TicketRepository ticketRepository,
TeamRepository teamRepository, SeatService seatService,
TicketOptionRepository ticketOptionRepository, TicketTypeRepository ticketTypeRepository,
RFIDLinkRepository rfidLinkRepository, PossibleConsumptionsRepository consumptionsRepository,
ConsumptionService consumptionService, BannerRepository bannerRepository, CommitteeRepository committeeRepository,
FaqRepository faqRepository, SponsorRepository sponsorRepository,
TournamentRepository tournamentRepository, OrderService orderService, OrderRepository orderRepository) {
this.accountRepository = accountRepository;
this.ticketRepository = ticketRepository;
this.seatService = seatService;
this.teamRepository = teamRepository;
this.ticketOptionRepository = ticketOptionRepository;
this.ticketTypeRepository = ticketTypeRepository;
this.rfidLinkRepository = rfidLinkRepository;
this.consumptionsRepository = consumptionsRepository;
this.consumptionService = consumptionService;
this.bannerRepository = bannerRepository;
this.committeeRepository = committeeRepository;
this.faqRepository = faqRepository;
this.sponsorRepository = sponsorRepository;
this.tournamentRepository = tournamentRepository;
this.orderService = orderService;
this.orderRepository = orderRepository;
}
@EventListener(ApplicationStartedEvent.class)
public void insertTestData() {
//region Users
LocalDate localDate = LocalDate.of(2000, 1, 2);
User userAdmin = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
userAdmin.addRole(Role.ROLE_ADMIN);
User userNormal = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
User userCaptain = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
User userInvalidTicket = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
User userNoTicket = new User("[email protected]", new BCryptPasswordEncoder().encode("password"));
userAdmin.getProfile()
.setAllFields("Jan", "de Groot", "MonsterKiller9001", LocalDate.of(1990, 2, 1), Gender.MALE, "Mekelweg 4", "2826CD",
"Delft", "0906-0666", null);
userNormal.getProfile()
.setAllFields("Bert", "Kleijn", "ILoveZombies", localDate, Gender.OTHER, "Mekelweg 20", "2826CD",
"Amsterdam", "0611", null);
userInvalidTicket.getProfile()
.setAllFields("Katrien", "Zwanenburg", "Admiral Cheesecake", localDate, Gender.FEMALE, "Ganzenlaan 5",
"2826CD", "Duckstad", "0906-0666", null);
userNoTicket.getProfile()
.setAllFields("Kees", "Jager", "l33tz0r", localDate, Gender.MALE, "Herenweg 2", "2826CD", "Delft",
"0902-30283", null);
userCaptain.getProfile()
.setAllFields("Gert", "Gertson", "Whosyourdaddy", localDate, Gender.MALE, "Jansstraat", "8826CD",
"Delft", "0238-2309736", null);
userAdmin = accountRepository.saveAndFlush(userAdmin);
userNormal = accountRepository.saveAndFlush(userNormal);
userCaptain = accountRepository.saveAndFlush(userCaptain);
userInvalidTicket = accountRepository.saveAndFlush(userInvalidTicket);
userNoTicket = accountRepository.saveAndFlush(userNoTicket);
//endregion Users
//region Tickets
TicketOption chMember = ticketOptionRepository.save(new TicketOption("chMember", -5F));
TicketOption pickupService = ticketOptionRepository.save(new TicketOption("pickupService", 2.5F));
TicketType early = new TicketType("Early", "Early Bird", 35F, 50, LocalDateTime.now().plusDays(7L), true);
early.addPossibleOption(chMember);
early.addPossibleOption(pickupService);
early = ticketTypeRepository.save(early);
TicketType normal = new TicketType("Normal", "Normal Ticket", 40F, 0, LocalDateTime.now().plusDays(7L), true);
normal.addPossibleOption(chMember);
normal.addPossibleOption(pickupService);
normal = ticketTypeRepository.save(normal);
TicketType late = new TicketType("Late", "Last Minute", 42.5F, 0, LocalDateTime.now().plusDays(14L), true);
late.addPossibleOption(chMember);
late.addPossibleOption(pickupService);
late = ticketTypeRepository.save(late);
Ticket ticketAdmin = new Ticket(userAdmin, normal);
ticketAdmin.addOption(chMember);
ticketAdmin.addOption(pickupService);
ticketAdmin.setValid(true);
ticketRepository.save(ticketAdmin);
Ticket ticketCaptain = new Ticket(userCaptain, early);
ticketCaptain.addOption(chMember);
ticketCaptain.addOption(pickupService);
ticketCaptain.setValid(true);
ticketRepository.save(ticketCaptain);
Ticket ticketNormal = new Ticket(userNormal, normal);
ticketNormal.addOption(pickupService);
ticketNormal.setValid(true);
ticketRepository.save(ticketNormal);
Ticket ticketInvalid = new Ticket(userInvalidTicket, late);
ticketInvalid.setValid(false);
ticketRepository.save(ticketInvalid);
//endregion Tickets
//region RFID
RFIDLink rfidLink1 = new RFIDLink("0000000001", ticketAdmin);
RFIDLink rfidLink2 = new RFIDLink("0000000002", ticketCaptain);
RFIDLink rfidLink3 = new RFIDLink("0000000003", ticketNormal);
rfidLinkRepository.saveAndFlush(rfidLink1);
rfidLinkRepository.saveAndFlush(rfidLink2);
rfidLinkRepository.saveAndFlush(rfidLink3);
//endregion RFID
//region Consumptions
Consumption ontbijt = new Consumption("Ontbijt");
ontbijt = consumptionsRepository.saveAndFlush(ontbijt);
Consumption lunch = new Consumption("Lunch");
lunch = consumptionsRepository.saveAndFlush(lunch);
consumptionService.consume(ticketAdmin.getId(), ontbijt.getId());
consumptionService.consume(ticketAdmin.getId(), lunch.getId());
consumptionService.consume(ticketCaptain.getId(), ontbijt.getId());
consumptionService.consume(ticketNormal.getId(), ontbijt.getId());
//endregion Consumptions
//region Team
Team team = new Team("Test Team", userCaptain);
team.addMember(userNormal);
team.addMember(userInvalidTicket);
teamRepository.save(team);
Team team2 = new Team("Admin's Team", userAdmin);
team2.addMember(userCaptain);
team2.addMember(userNoTicket);
teamRepository.save(team2);
//endregion Team
//region Seat
for (char s = 'A'; s <= 'J'; s++) {
SeatGroupDTO seatGroup = new SeatGroupDTO();
seatGroup.setNumberOfSeats(16);
seatGroup.setSeatGroupName(String.valueOf(s));
seatService.addSeats(seatGroup);
}
seatService.setAllSeatsLock(false);
seatService.reserveSeat("A", 1, ticketAdmin.getId(), false);
seatService.reserveSeat("A", 2, ticketCaptain.getId(), false);
seatService.reserveSeat("B", 1, ticketNormal.getId(), false);
//endregion Seat
//region Banner
Date winterBreakStart = Date.valueOf("2017-12-23");
Date winterBreakEnd = Date.valueOf("2018-01-07");
String winterBreak = "Enjoy the winter break! AreaFiftyLAN isn't far from happening!";
Date soonAnnouncementStart = Date.valueOf("2018-02-03");
Date soonAnnouncementEnd = Date.valueOf("2018-02-28");
String soonAnnouncement = "AreaFiftyLAN starts in less than a month! Make sure to get your tickets!";
Date soldOutStart = Date.valueOf("2018-03-01");
Date soldOutEnd = Date.valueOf("2018-03-08");
String soldOut = "Tickets are sold out!";
banner(winterBreak, winterBreakStart, winterBreakEnd);
banner(soonAnnouncement, soonAnnouncementStart, soonAnnouncementEnd);
banner(soldOut, soldOutStart, soldOutEnd);
//endregion Banner
//region Web<SUF>
committeeMember(1L, "Chairman", "Mark Rutte", "gavel");
committeeMember(2L, "Secretary", "Lodewijk Asscher", "chrome-reader-mode");
committeeMember(3L, "Treasurer", "Jeroen Dijsselbloem", "attach-money");
committeeMember(4L, "Commissioner of Promo", "Frans Timmermans", "notifications");
committeeMember(5L, "Commissioner of Logistics", "Melanie Schultz", "local-shipping");
committeeMember(6L, "Commissioner of Systems", "Klaas Dijkhoff", "settings");
committeeMember(7L, "Qualitate Qua", "Ivo Opstelten", "announcement");
faqpair("What the fox say?", "Ring-ding-ding-ding-dingeringeding!");
faqpair("What do you get if you multiply six by nine?", "42");
faqpair("What is your favorite colour?", "Blue.");
faqpair("What is the capital of Assyria?", "Well I don't know!");
faqpair("What is your favorite colour?", "Blue! no, Yellow!");
faqpair("What is the airspeed velocity of an unladen swallow?", "What do you mean? African or European swallow?");
sponsor("Christiaan Huygens", SponsorType.PRESENTER, "https://ch.tudelft.nl", "images-optimized/lancie/logo_CH.png");
sponsor("TU Delft", SponsorType.PRESENTER, "https://www.tudelft.nl", "images-optimized/logos/logo_SC.png");
Sponsor sogeti = sponsor("Sogeti", SponsorType.PREMIUM, "https://www.sogeti.nl/", "images-optimized/logos/sogeti.png");
sponsor("Nutanix", SponsorType.PREMIUM, "https://www.nutanix.com", "images-optimized/logos/nutanix.png");
sponsor("OGD", SponsorType.PREMIUM, "https://ogd.nl/", "images-optimized/logos/ogd.png");
Sponsor coolerMaster = sponsor("CoolerMaster", SponsorType.NORMAL, "http://www.coolermaster.com/", "images-optimized/logos/Cooler_Master_Logo.png");
sponsor("Spam", SponsorType.NORMAL, "http://www.spam-energydrink.com/", "images-optimized/logos/spam-logo.jpg");
sponsor("Jigsaw", SponsorType.NORMAL, "http://www.jigsaw.nl/", "images-optimized/logos/jigsaw_cleaner_logo.png");
sponsor("TransIP", SponsorType.NORMAL, "https://www.transip.nl/", "images-optimized/logos/transip_logo.png");
tournament(TournamentType.OFFICIAL, "RL", "images-optimized/activities/rl.jpg", "3 V 3", "Rocket League",
"Rocket League is a fun game.", Arrays.asList("Huis", "Koelkast", "Broodrooster"), sogeti);
tournament(TournamentType.OFFICIAL, "HS", "images-optimized/activities/hs.jpg", "1 V 1", "Hearthstone",
"Hearthstone is not a fun game.", Arrays.asList("Keyboard", "Muis", "50 Packs"), coolerMaster);
tournament(TournamentType.UNOFFICIAL, "Achtung", "images-optimized/unofficial/achtung.jpg", "1 V 1",
"Achtung Die Kurve", "Achtung!", Arrays.asList("Kratje Hertog Jan", "Kratje Heineken", "Kratje Amstel"), null);
tournament(TournamentType.UNOFFICIAL, "JD", "images-optimized/unofficial/justdance.jpg", "2 V 2", "Just Dance",
"Just Dance is about dancing.", Collections.singletonList("Nothing."), sogeti);
//endregion Web Data
//region Orders
Order order_admin = orderService.create("Normal", null);
orderService.assignOrderToUser(order_admin.getId(), userAdmin.getId());
order_admin.setStatus(OrderStatus.PAID);
orderRepository.save(order_admin);
Order order_normal = orderService.create("Normal", null);
orderService.assignOrderToUser(order_normal.getId(), userNormal.getId());
order_normal.setStatus(OrderStatus.PAID);
orderRepository.save(order_admin);
//endregion Orders
}
private CommitteeMember committeeMember(Long position, String function, String name, String icon) {
CommitteeMember committeeMember = new CommitteeMember();
committeeMember.setPosition(position);
committeeMember.setFunction(function);
committeeMember.setName(name);
committeeMember.setIcon(icon);
return committeeRepository.save(committeeMember);
}
private FaqPair faqpair(String question, String answer) {
FaqPair faqPair = new FaqPair();
faqPair.setQuestion(question);
faqPair.setAnswer(answer);
return faqRepository.save(faqPair);
}
private Sponsor sponsor(String name, SponsorType type, String website, String imageName) {
Sponsor sponsor = new Sponsor();
sponsor.setName(name);
sponsor.setType(type);
sponsor.setWebsite(website);
sponsor.setImageName(imageName);
return sponsorRepository.save(sponsor);
}
private Tournament tournament(TournamentType type, String buttonTitle, String buttonImagePath, String format,
String headerTitle, String description, List<String> prizes, Sponsor sponsor) {
Tournament tournament = new Tournament();
tournament.setType(type);
tournament.setButtonTitle(buttonTitle);
tournament.setButtonImagePath(buttonImagePath);
tournament.setFormat(format);
tournament.setHeaderTitle(headerTitle);
tournament.setDescription(description);
tournament.setPrizes(prizes);
tournament.setSponsor(sponsor);
return tournamentRepository.save(tournament);
}
private Banner banner(String text, Date startDate, Date endDate) {
Banner banner = new Banner();
banner.setText(text);
banner.setStartDate(startDate);
banner.setEndDate(endDate);
return bannerRepository.save(banner);
}
}
|
135485_12 | /**
* 2014 Urs Zeidler
*/
package de.urszeidler.eclipse.shr5.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import de.urszeidler.eclipse.shr5.KiKraft;
import de.urszeidler.eclipse.shr5.QiFokus;
import de.urszeidler.eclipse.shr5.Shr5Package;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Qi Fokus</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link de.urszeidler.eclipse.shr5.impl.QiFokusImpl#getPower <em>Power</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class QiFokusImpl extends AbstraktFokusImpl implements QiFokus {
/**
* The cached value of the '{@link #getPower() <em>Power</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPower()
* @generated
* @ordered
*/
protected KiKraft power;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected QiFokusImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Shr5Package.Literals.QI_FOKUS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public KiKraft getPower() {
return power;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPower(KiKraft newPower, NotificationChain msgs) {
KiKraft oldPower = power;
power = newPower;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__POWER, oldPower, newPower);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated not
*/
public void setPower(KiKraft newPower) {
if (newPower != power) {
NotificationChain msgs = null;
if (power != null)
msgs = ((InternalEObject)power).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Shr5Package.QI_FOKUS__POWER, null, msgs);
if (newPower != null)
msgs = ((InternalEObject)newPower).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Shr5Package.QI_FOKUS__POWER, null, msgs);
msgs = basicSetPower(newPower, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__POWER, newPower, newPower));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__BINDUNGSKOSTEN, 1, 0));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__STUFE, 1, 0));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__WERT, 1, 0));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
return basicSetPower(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
return getPower();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
setPower((KiKraft)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
setPower((KiKraft)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
return power != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated not
*/
public int getBindungskosten() {
return getStufe() * 2;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated not
*/
public int getStufe() {
if (getPower() != null) {
return (int)Math.ceil((4 * Math.abs(getPower().getKraftpunkte()) / 100D));
}
return stufe;
}
public void setStufe(int newStufe){
super.setStufe(newStufe);
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__BINDUNGSKOSTEN, 0, 1));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__WERT_VALUE, 0, 1));
}
} // QiFokusImpl
| Argonnite/shr5rcp | de.urszeidler.shr5.model/src/de/urszeidler/eclipse/shr5/impl/QiFokusImpl.java | 2,018 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
* 2014 Urs Zeidler
*/
package de.urszeidler.eclipse.shr5.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import de.urszeidler.eclipse.shr5.KiKraft;
import de.urszeidler.eclipse.shr5.QiFokus;
import de.urszeidler.eclipse.shr5.Shr5Package;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Qi Fokus</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link de.urszeidler.eclipse.shr5.impl.QiFokusImpl#getPower <em>Power</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class QiFokusImpl extends AbstraktFokusImpl implements QiFokus {
/**
* The cached value of the '{@link #getPower() <em>Power</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPower()
* @generated
* @ordered
*/
protected KiKraft power;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected QiFokusImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Shr5Package.Literals.QI_FOKUS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public KiKraft getPower() {
return power;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPower(KiKraft newPower, NotificationChain msgs) {
KiKraft oldPower = power;
power = newPower;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__POWER, oldPower, newPower);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated not
*/
public void setPower(KiKraft newPower) {
if (newPower != power) {
NotificationChain msgs = null;
if (power != null)
msgs = ((InternalEObject)power).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Shr5Package.QI_FOKUS__POWER, null, msgs);
if (newPower != null)
msgs = ((InternalEObject)newPower).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Shr5Package.QI_FOKUS__POWER, null, msgs);
msgs = basicSetPower(newPower, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__POWER, newPower, newPower));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__BINDUNGSKOSTEN, 1, 0));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__STUFE, 1, 0));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__WERT, 1, 0));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
return basicSetPower(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
return getPower();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
setPower((KiKraft)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
setPower((KiKraft)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --><SUF>*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Shr5Package.QI_FOKUS__POWER:
return power != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated not
*/
public int getBindungskosten() {
return getStufe() * 2;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated not
*/
public int getStufe() {
if (getPower() != null) {
return (int)Math.ceil((4 * Math.abs(getPower().getKraftpunkte()) / 100D));
}
return stufe;
}
public void setStufe(int newStufe){
super.setStufe(newStufe);
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__BINDUNGSKOSTEN, 0, 1));
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.QI_FOKUS__WERT_VALUE, 0, 1));
}
} // QiFokusImpl
|
129153_2 | package org.firstinspires.ftc.teamcode;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.disnodeteam.dogecv.CameraViewDisplay;
import com.disnodeteam.dogecv.detectors.*;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
import java.io.IOException;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
@TeleOp(name="DogeCV Glyph Detector", group="DogeCV")
public class DogeCVTest extends OpMode
{
// Declare OpMode members.
private ElapsedTime runtime = new ElapsedTime();
private GlyphDetector glyphDetector = null;
HardwareVar r = new HardwareVar();
/*
* Code to run ONCE when the driver hits INIT
*/
@Override
public void init() {
r.init(hardwareMap);
telemetry.addData("Status", "Initialized");
glyphDetector = new GlyphDetector();
glyphDetector.init(hardwareMap.appContext, CameraViewDisplay.getInstance());
glyphDetector.minScore = 1;
glyphDetector.downScaleFactor = 0.3;
glyphDetector.speed = GlyphDetector.GlyphDetectionSpeed.SLOW;
glyphDetector.enable();
}
@Override
public void init_loop() {
telemetry.addData("Status", "Initialized. Gyro Calibration");
}
@Override
public void start() {
runtime.reset();
}
@Override
public void loop() {
if (glyphDetector.getChosenGlyphOffset() < 110) {
r.RBmotor.setPower(0.2);
r.LBmotor.setPower(-0.2);
} else if (glyphDetector.getChosenGlyphOffset() > 150) {
//Naar rechts draaien
} else if (glyphDetector.getChosenGlyphOffset() > 110 & glyphDetector.getChosenGlyphOffset() < 150) {
telemetry.addData("Status", "MIDDEN");
} else {
telemetry.addData("Status", "IK WEET HET NIET MEER");
}
telemetry.addData("Status", "Run Time: " + runtime);
telemetry.addData("Glyph Pos offset", glyphDetector.getChosenGlyphOffset());
telemetry.addData("Glyph Pos X, Y", glyphDetector.getChosenGlyphPosition());
}
/*
* Code to run ONCE after the driver hits STOP
*/
@Override
public void stop() {
glyphDetector.disable();
}
}
| ArjanB2001/FTC_Robot | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/DogeCVTest.java | 842 | //Naar rechts draaien | line_comment | nl | package org.firstinspires.ftc.teamcode;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.disnodeteam.dogecv.CameraViewDisplay;
import com.disnodeteam.dogecv.detectors.*;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
import java.io.IOException;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
@TeleOp(name="DogeCV Glyph Detector", group="DogeCV")
public class DogeCVTest extends OpMode
{
// Declare OpMode members.
private ElapsedTime runtime = new ElapsedTime();
private GlyphDetector glyphDetector = null;
HardwareVar r = new HardwareVar();
/*
* Code to run ONCE when the driver hits INIT
*/
@Override
public void init() {
r.init(hardwareMap);
telemetry.addData("Status", "Initialized");
glyphDetector = new GlyphDetector();
glyphDetector.init(hardwareMap.appContext, CameraViewDisplay.getInstance());
glyphDetector.minScore = 1;
glyphDetector.downScaleFactor = 0.3;
glyphDetector.speed = GlyphDetector.GlyphDetectionSpeed.SLOW;
glyphDetector.enable();
}
@Override
public void init_loop() {
telemetry.addData("Status", "Initialized. Gyro Calibration");
}
@Override
public void start() {
runtime.reset();
}
@Override
public void loop() {
if (glyphDetector.getChosenGlyphOffset() < 110) {
r.RBmotor.setPower(0.2);
r.LBmotor.setPower(-0.2);
} else if (glyphDetector.getChosenGlyphOffset() > 150) {
//Naar rechts<SUF>
} else if (glyphDetector.getChosenGlyphOffset() > 110 & glyphDetector.getChosenGlyphOffset() < 150) {
telemetry.addData("Status", "MIDDEN");
} else {
telemetry.addData("Status", "IK WEET HET NIET MEER");
}
telemetry.addData("Status", "Run Time: " + runtime);
telemetry.addData("Glyph Pos offset", glyphDetector.getChosenGlyphOffset());
telemetry.addData("Glyph Pos X, Y", glyphDetector.getChosenGlyphPosition());
}
/*
* Code to run ONCE after the driver hits STOP
*/
@Override
public void stop() {
glyphDetector.disable();
}
}
|
179889_1 | /**
* Copyright (c) 2013 HAN University of Applied Sciences
* Arjan Oortgiese
* Boyd Hofman
* Joëll Portier
* Michiel Westerbeek
* Tim Waalewijn
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package nl.han.ica.ap.antlr.workshop.nlp.listener;
import java.util.Arrays;
import java.util.Collection;
import nl.han.ica.ap.antlr.workshop.nlp.model.Association;
import nl.han.ica.ap.antlr.workshop.nlp.model.Class;
import nl.han.ica.ap.antlr.workshop.nlp.NlpLexer;
import nl.han.ica.ap.antlr.workshop.nlp.NlpParser;
import nl.han.ica.ap.antlr.workshop.nlp.controller.ClassController;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Unit test for {@link ZelfstandignaamwoordListener}
*/
@RunWith(Parameterized.class)
public class ZelfstandignaamwoordListenerTest {
private ZelfstandignaamwoordListener listener;
private ClassController classController;
private Class class1;
private Class class2;
private String sentence;
@Parameters
public static Collection<Object[]> data() {
Object[][] result = new Object[][] {
{
"De HAN heeft een student.",
"HAN",
"student",
},
{
"Het vliegtuig heeft een piloot.",
"vliegtuig",
"piloot",
},
{
"De dierentuin heeft een olifant.",
"dierentuin",
"olifant",
},
{
"De auto heeft een stuur.",
"auto",
"stuur",
}
};
return Arrays.asList(result);
}
public ZelfstandignaamwoordListenerTest(
String sentence, String class1Name, String class2Name) {
this.sentence = sentence;
classController = EasyMock.createMock(ClassController.class);
listener = new ZelfstandignaamwoordListener(classController);
class1 = EasyMock.createMock(Class.class);
class2 = EasyMock.createMock(Class.class);
Association class1Association = new Association(class2);
EasyMock.expect(class1.addAssociation(class2))
.andReturn(class1Association).atLeastOnce();
EasyMock.expect(classController.getClassByName(class1Name))
.andReturn(class1).atLeastOnce();
EasyMock.expect(classController.getClassByName(class2Name))
.andReturn(class2).atLeastOnce();
EasyMock.replay(class1);
EasyMock.replay(class2);
EasyMock.replay(classController);
}
@After
public void after() {
EasyMock.verify(classController);
EasyMock.verify(class1);
EasyMock.verify(class2);
}
@Test
public void test() {
walk(sentence);
}
/**
* Create parse tree of sentence and calls walks listener.
*
* @param sentence Sentence.
*/
private void walk(String sentence) {
ANTLRInputStream input = new ANTLRInputStream(sentence);
NlpLexer lexer = new NlpLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
NlpParser parser = new NlpParser(tokens);
ParseTree tree = parser.tekst();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, tree);
}
}
| ArjanO/ANTLR-Workshop | nlp/src/test/java/nl/han/ica/ap/antlr/workshop/nlp/listener/ZelfstandignaamwoordListenerTest.java | 1,441 | /**
* Unit test for {@link ZelfstandignaamwoordListener}
*/ | block_comment | nl | /**
* Copyright (c) 2013 HAN University of Applied Sciences
* Arjan Oortgiese
* Boyd Hofman
* Joëll Portier
* Michiel Westerbeek
* Tim Waalewijn
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package nl.han.ica.ap.antlr.workshop.nlp.listener;
import java.util.Arrays;
import java.util.Collection;
import nl.han.ica.ap.antlr.workshop.nlp.model.Association;
import nl.han.ica.ap.antlr.workshop.nlp.model.Class;
import nl.han.ica.ap.antlr.workshop.nlp.NlpLexer;
import nl.han.ica.ap.antlr.workshop.nlp.NlpParser;
import nl.han.ica.ap.antlr.workshop.nlp.controller.ClassController;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Unit test for<SUF>*/
@RunWith(Parameterized.class)
public class ZelfstandignaamwoordListenerTest {
private ZelfstandignaamwoordListener listener;
private ClassController classController;
private Class class1;
private Class class2;
private String sentence;
@Parameters
public static Collection<Object[]> data() {
Object[][] result = new Object[][] {
{
"De HAN heeft een student.",
"HAN",
"student",
},
{
"Het vliegtuig heeft een piloot.",
"vliegtuig",
"piloot",
},
{
"De dierentuin heeft een olifant.",
"dierentuin",
"olifant",
},
{
"De auto heeft een stuur.",
"auto",
"stuur",
}
};
return Arrays.asList(result);
}
public ZelfstandignaamwoordListenerTest(
String sentence, String class1Name, String class2Name) {
this.sentence = sentence;
classController = EasyMock.createMock(ClassController.class);
listener = new ZelfstandignaamwoordListener(classController);
class1 = EasyMock.createMock(Class.class);
class2 = EasyMock.createMock(Class.class);
Association class1Association = new Association(class2);
EasyMock.expect(class1.addAssociation(class2))
.andReturn(class1Association).atLeastOnce();
EasyMock.expect(classController.getClassByName(class1Name))
.andReturn(class1).atLeastOnce();
EasyMock.expect(classController.getClassByName(class2Name))
.andReturn(class2).atLeastOnce();
EasyMock.replay(class1);
EasyMock.replay(class2);
EasyMock.replay(classController);
}
@After
public void after() {
EasyMock.verify(classController);
EasyMock.verify(class1);
EasyMock.verify(class2);
}
@Test
public void test() {
walk(sentence);
}
/**
* Create parse tree of sentence and calls walks listener.
*
* @param sentence Sentence.
*/
private void walk(String sentence) {
ANTLRInputStream input = new ANTLRInputStream(sentence);
NlpLexer lexer = new NlpLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
NlpParser parser = new NlpParser(tokens);
ParseTree tree = parser.tekst();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, tree);
}
}
|
179885_5 | package nl.han.ica.ap.nlp;
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map.Entry;
import nl.han.ica.ap.nlp.model.*;
import nl.han.ica.ap.nlp.model.Class;
import nl.han.ica.ap.nlp.controller.TreeController;
import org.junit.BeforeClass;
import org.junit.Test;
public class TreeControllerTest {
@Test
public void testClassAlreadyExistsAsAssociation() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("Vliegtuig");
Class passagier = new Class("Passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class passagier2 = new Class("Passagier");
Class paspoort = new Class("Paspoort");
passagier2.addAssociation(paspoort);
controller.addClass(passagier2);
int aantalpassagiers = 0;
for(Class _class : controller.classes) {
if(_class.getName().equals("Passagier")) {
aantalpassagiers++;
}
}
assertSame(0, aantalpassagiers);
assertSame(vliegtuig, controller.classes.get(0));
assertSame(passagier, controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(paspoort,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
}
@Test
public void testClassBecomesAssociation() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("Vliegtuig");
Class passagier = new Class("Passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class vliegtuigmaatschappij = new Class("Vliegtuigmaatschappij");
Class vliegtuig2 = new Class("vliegtuig");
vliegtuigmaatschappij.addAssociation(vliegtuig2);
controller.addClass(vliegtuigmaatschappij);
assertSame(1, controller.classes.size());
assertSame(vliegtuigmaatschappij,controller.classes.get(0));
assertSame(vliegtuig,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(passagier,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
}
@Test
public void testClassesShareAssociation() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("vliegtuig");
Class passagier1 = new Class("passagier");
vliegtuig.addAssociation(passagier1);
controller.addClass(vliegtuig);
Class bus = new Class("bus");
Class passagier2 = new Class("passagier");
bus.addAssociation(passagier2);
controller.addClass(bus);
assertSame(2, controller.classes.size());
assertSame(controller.classes.get(0).getAssociations().get(0).getChildClass(),controller.classes.get(1).getAssociations().get(0).getChildClass());
assertFalse(controller.classes.contains(passagier1));
}
@Test
public void testAlreadyExistsAsClass() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("vliegtuig");
Class passagier = new Class("passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class vliegtuig2 = new Class("vliegtuig");
Class piloot = new Class("piloot");
vliegtuig2.addAssociation(piloot);
controller.addClass(vliegtuig2);
assertSame(1, controller.classes.size());
assertSame(2, controller.classes.get(0).getAssociations().size());
assertSame(vliegtuig,controller.classes.get(0));
assertSame(passagier,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(piloot,controller.classes.get(0).getAssociations().get(1).getChildClass());
}
@Test
public void testClassAndAssociationAlreadyExist() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("vliegtuig");
Class passagier = new Class("passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class paspoort = new Class("paspoort");
Class bnnr = new Class("burgernummer");
paspoort.addAssociation(bnnr);
controller.addClass(paspoort);
Class passagier2 = new Class("passagier");
Class paspoort2 = new Class("paspoort");
passagier2.addAssociation(paspoort2);
controller.addClass(passagier2);
assertSame(vliegtuig, controller.classes.get(0));
assertSame(passagier,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(paspoort,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
assertSame(bnnr,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
assertEquals(1, controller.classes.size());
}
@Test
public void testClassAssociationLoop() {
TreeController controller = new TreeController();
Class ouder1 = new Class("ouder");
Class kind1 = new Class("kind");
ouder1.addAssociation(kind1);
controller.addClass(ouder1);
Class kind2 = new Class("kind");
Class ouder2 = new Class("ouder");
kind2.addAssociation(ouder2);
controller.addClass(kind2);
Class kind3 = new Class("kind");
Class voorouder1 = new Class("voorouder");
kind3.addAssociation(voorouder1);
controller.addClass(kind3);
assertEquals(1, controller.classes.size());
assertSame(ouder1, controller.classes.get(0));
assertSame(kind1,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(ouder1,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
assertSame(voorouder1,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(1).getChildClass());
}
@Test
public void testAttributeAlreadyExistsAsAssociation() {
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class naamAsAssociation = new Class("Naam");
passagier.addAssociation(naamAsAssociation);
controller.addClass(passagier);
Attribute naamAsAttribute = new Attribute("Naam", String.class);
controller.addAttribute(naamAsAttribute);
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(0, controller.classes.get(0).getAssociations().size());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(naamAsAttribute.getType(), controller.classes.get(0).getAttributes().get(0).getType());
}
@Test
public void testAddSimpleAttributeClassPair(){
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Attribute naamAsAttribute = new Attribute("Naam", String.class);
passagier.addAttribute(naamAsAttribute);
controller.addClass(passagier);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(passagier.getName(), controller.classes.get(0).getName());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
}
@Test
public void testAddAttributeWithExistingClass(){
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class passagier2 = new Class("Passagier");
Attribute naamAsAttribute = new Attribute("Naam", String.class);
passagier2.addAttribute(naamAsAttribute);
controller.addClass(passagier);
controller.addClass(passagier2);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(passagier.getName(), controller.classes.get(0).getName());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
}
@Test
public void testAddExistingAttributeWithExistingClass(){
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class passagier2 = new Class("Passagier");
Attribute naamAsAttribute = new Attribute("Naam", String.class);
Attribute naamAsAttribute2 = new Attribute("Naam", String.class);
passagier.addAttribute(naamAsAttribute);
passagier2.addAttribute(naamAsAttribute2);
controller.addClass(passagier);
controller.addClass(passagier2);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(passagier.getName(), controller.classes.get(0).getName());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
}
@Test
public void testClassWithAddAttributeWithDoubleAttributeInQueue(){
TreeController controller = new TreeController();
Attribute idIntegerAttribute = new Attribute("id", Integer.class);
controller.attributesToAssign.add(idIntegerAttribute);
Attribute idStringAttribute = new Attribute("id", String.class);
controller.attributesToAssign.add(idStringAttribute);
Class passagier = new Class("Passagier");
Class idAssociation = new Class("id");
passagier.addAssociation(idAssociation);
controller.addClass(passagier);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(1, controller.attributesToAssign.size());
}
@Test
public void testDoubleClassWithAddAttributeWithDoubleAttributeInQueue(){
TreeController controller = new TreeController();
Attribute idIntegerAttribute = new Attribute("id", Integer.class);
controller.attributesToAssign.add(idIntegerAttribute);
Attribute idStringAttribute = new Attribute("id", String.class);
controller.attributesToAssign.add(idStringAttribute);
Class passagier = new Class("Passagier");
Class idAssociationPassagier = new Class("id");
passagier.addAssociation(idAssociationPassagier);
controller.addClass(passagier);
Class vliegtuig = new Class("Vliegtuig");
Class idAssociationVliegtuig = new Class("id");
vliegtuig.addAssociation(idAssociationVliegtuig);
controller.addClass(vliegtuig);
assertEquals(2, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(1, controller.classes.get(1).getAttributes().size());
assertEquals(0, controller.attributesToAssign.size());
}
//Een passagier heeft een id.
//Een piloot heeft als id "AB".
@Test
public void testClassAssociationClassAttribute() {
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class idAssociationPassagier = new Class("id");
passagier.addAssociation(idAssociationPassagier);
controller.addClass(passagier);
Class piloot = new Class("Piloot");
Attribute idStringAttribute = new Attribute("id", String.class);
piloot.addAttribute(idStringAttribute);
controller.addClass(piloot);
assertEquals(2, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(idStringAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(1, controller.classes.get(1).getAttributes().size());
assertEquals(0, controller.attributesToAssign.size());
}
//Een naam is "Michiel".
//Een persoon heeft namen.
@Test
public void testAttributeAndClassWithPlural() {
TreeController controller = new TreeController();
Attribute naamStringAttribute = new Attribute("naam", String.class);
controller.addAttribute(naamStringAttribute);
Class persoon = new Class("Persoon");
Class namenAssociationPersoon = new Class("namen");
persoon.addAssociation(namenAssociationPersoon);
controller.addClass(persoon);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(naamStringAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(0, controller.attributesToAssign.size());
}
//Een persoon heeft namen.
//Een naam is "Michiel".
@Test
public void testClassWithPluralAndAttribute() {
TreeController controller = new TreeController();
Class persoon = new Class("Persoon");
Class namenAssociationPersoon = new Class("namen");
persoon.addAssociation(namenAssociationPersoon);
controller.addClass(persoon);
Attribute naamStringAttribute = new Attribute("naam", String.class);
controller.addAttribute(naamStringAttribute);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(naamStringAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(0, controller.attributesToAssign.size());
}
}
| ArjanO/AP-NLP | src/test/java/nl/han/ica/ap/nlp/TreeControllerTest.java | 3,899 | //Een naam is "Michiel". | line_comment | nl | package nl.han.ica.ap.nlp;
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map.Entry;
import nl.han.ica.ap.nlp.model.*;
import nl.han.ica.ap.nlp.model.Class;
import nl.han.ica.ap.nlp.controller.TreeController;
import org.junit.BeforeClass;
import org.junit.Test;
public class TreeControllerTest {
@Test
public void testClassAlreadyExistsAsAssociation() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("Vliegtuig");
Class passagier = new Class("Passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class passagier2 = new Class("Passagier");
Class paspoort = new Class("Paspoort");
passagier2.addAssociation(paspoort);
controller.addClass(passagier2);
int aantalpassagiers = 0;
for(Class _class : controller.classes) {
if(_class.getName().equals("Passagier")) {
aantalpassagiers++;
}
}
assertSame(0, aantalpassagiers);
assertSame(vliegtuig, controller.classes.get(0));
assertSame(passagier, controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(paspoort,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
}
@Test
public void testClassBecomesAssociation() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("Vliegtuig");
Class passagier = new Class("Passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class vliegtuigmaatschappij = new Class("Vliegtuigmaatschappij");
Class vliegtuig2 = new Class("vliegtuig");
vliegtuigmaatschappij.addAssociation(vliegtuig2);
controller.addClass(vliegtuigmaatschappij);
assertSame(1, controller.classes.size());
assertSame(vliegtuigmaatschappij,controller.classes.get(0));
assertSame(vliegtuig,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(passagier,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
}
@Test
public void testClassesShareAssociation() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("vliegtuig");
Class passagier1 = new Class("passagier");
vliegtuig.addAssociation(passagier1);
controller.addClass(vliegtuig);
Class bus = new Class("bus");
Class passagier2 = new Class("passagier");
bus.addAssociation(passagier2);
controller.addClass(bus);
assertSame(2, controller.classes.size());
assertSame(controller.classes.get(0).getAssociations().get(0).getChildClass(),controller.classes.get(1).getAssociations().get(0).getChildClass());
assertFalse(controller.classes.contains(passagier1));
}
@Test
public void testAlreadyExistsAsClass() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("vliegtuig");
Class passagier = new Class("passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class vliegtuig2 = new Class("vliegtuig");
Class piloot = new Class("piloot");
vliegtuig2.addAssociation(piloot);
controller.addClass(vliegtuig2);
assertSame(1, controller.classes.size());
assertSame(2, controller.classes.get(0).getAssociations().size());
assertSame(vliegtuig,controller.classes.get(0));
assertSame(passagier,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(piloot,controller.classes.get(0).getAssociations().get(1).getChildClass());
}
@Test
public void testClassAndAssociationAlreadyExist() {
TreeController controller = new TreeController();
Class vliegtuig = new Class("vliegtuig");
Class passagier = new Class("passagier");
vliegtuig.addAssociation(passagier);
controller.addClass(vliegtuig);
Class paspoort = new Class("paspoort");
Class bnnr = new Class("burgernummer");
paspoort.addAssociation(bnnr);
controller.addClass(paspoort);
Class passagier2 = new Class("passagier");
Class paspoort2 = new Class("paspoort");
passagier2.addAssociation(paspoort2);
controller.addClass(passagier2);
assertSame(vliegtuig, controller.classes.get(0));
assertSame(passagier,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(paspoort,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
assertSame(bnnr,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
assertEquals(1, controller.classes.size());
}
@Test
public void testClassAssociationLoop() {
TreeController controller = new TreeController();
Class ouder1 = new Class("ouder");
Class kind1 = new Class("kind");
ouder1.addAssociation(kind1);
controller.addClass(ouder1);
Class kind2 = new Class("kind");
Class ouder2 = new Class("ouder");
kind2.addAssociation(ouder2);
controller.addClass(kind2);
Class kind3 = new Class("kind");
Class voorouder1 = new Class("voorouder");
kind3.addAssociation(voorouder1);
controller.addClass(kind3);
assertEquals(1, controller.classes.size());
assertSame(ouder1, controller.classes.get(0));
assertSame(kind1,controller.classes.get(0).getAssociations().get(0).getChildClass());
assertSame(ouder1,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(0).getChildClass());
assertSame(voorouder1,controller.classes.get(0).getAssociations().get(0).getChildClass().getAssociations().get(1).getChildClass());
}
@Test
public void testAttributeAlreadyExistsAsAssociation() {
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class naamAsAssociation = new Class("Naam");
passagier.addAssociation(naamAsAssociation);
controller.addClass(passagier);
Attribute naamAsAttribute = new Attribute("Naam", String.class);
controller.addAttribute(naamAsAttribute);
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(0, controller.classes.get(0).getAssociations().size());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(naamAsAttribute.getType(), controller.classes.get(0).getAttributes().get(0).getType());
}
@Test
public void testAddSimpleAttributeClassPair(){
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Attribute naamAsAttribute = new Attribute("Naam", String.class);
passagier.addAttribute(naamAsAttribute);
controller.addClass(passagier);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(passagier.getName(), controller.classes.get(0).getName());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
}
@Test
public void testAddAttributeWithExistingClass(){
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class passagier2 = new Class("Passagier");
Attribute naamAsAttribute = new Attribute("Naam", String.class);
passagier2.addAttribute(naamAsAttribute);
controller.addClass(passagier);
controller.addClass(passagier2);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(passagier.getName(), controller.classes.get(0).getName());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
}
@Test
public void testAddExistingAttributeWithExistingClass(){
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class passagier2 = new Class("Passagier");
Attribute naamAsAttribute = new Attribute("Naam", String.class);
Attribute naamAsAttribute2 = new Attribute("Naam", String.class);
passagier.addAttribute(naamAsAttribute);
passagier2.addAttribute(naamAsAttribute2);
controller.addClass(passagier);
controller.addClass(passagier2);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(passagier.getName(), controller.classes.get(0).getName());
assertEquals(naamAsAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
}
@Test
public void testClassWithAddAttributeWithDoubleAttributeInQueue(){
TreeController controller = new TreeController();
Attribute idIntegerAttribute = new Attribute("id", Integer.class);
controller.attributesToAssign.add(idIntegerAttribute);
Attribute idStringAttribute = new Attribute("id", String.class);
controller.attributesToAssign.add(idStringAttribute);
Class passagier = new Class("Passagier");
Class idAssociation = new Class("id");
passagier.addAssociation(idAssociation);
controller.addClass(passagier);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(1, controller.attributesToAssign.size());
}
@Test
public void testDoubleClassWithAddAttributeWithDoubleAttributeInQueue(){
TreeController controller = new TreeController();
Attribute idIntegerAttribute = new Attribute("id", Integer.class);
controller.attributesToAssign.add(idIntegerAttribute);
Attribute idStringAttribute = new Attribute("id", String.class);
controller.attributesToAssign.add(idStringAttribute);
Class passagier = new Class("Passagier");
Class idAssociationPassagier = new Class("id");
passagier.addAssociation(idAssociationPassagier);
controller.addClass(passagier);
Class vliegtuig = new Class("Vliegtuig");
Class idAssociationVliegtuig = new Class("id");
vliegtuig.addAssociation(idAssociationVliegtuig);
controller.addClass(vliegtuig);
assertEquals(2, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(1, controller.classes.get(1).getAttributes().size());
assertEquals(0, controller.attributesToAssign.size());
}
//Een passagier heeft een id.
//Een piloot heeft als id "AB".
@Test
public void testClassAssociationClassAttribute() {
TreeController controller = new TreeController();
Class passagier = new Class("Passagier");
Class idAssociationPassagier = new Class("id");
passagier.addAssociation(idAssociationPassagier);
controller.addClass(passagier);
Class piloot = new Class("Piloot");
Attribute idStringAttribute = new Attribute("id", String.class);
piloot.addAttribute(idStringAttribute);
controller.addClass(piloot);
assertEquals(2, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(idStringAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(1, controller.classes.get(1).getAttributes().size());
assertEquals(0, controller.attributesToAssign.size());
}
//Een naam is "Michiel".
//Een persoon heeft namen.
@Test
public void testAttributeAndClassWithPlural() {
TreeController controller = new TreeController();
Attribute naamStringAttribute = new Attribute("naam", String.class);
controller.addAttribute(naamStringAttribute);
Class persoon = new Class("Persoon");
Class namenAssociationPersoon = new Class("namen");
persoon.addAssociation(namenAssociationPersoon);
controller.addClass(persoon);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(naamStringAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(0, controller.attributesToAssign.size());
}
//Een persoon heeft namen.
//Een naam<SUF>
@Test
public void testClassWithPluralAndAttribute() {
TreeController controller = new TreeController();
Class persoon = new Class("Persoon");
Class namenAssociationPersoon = new Class("namen");
persoon.addAssociation(namenAssociationPersoon);
controller.addClass(persoon);
Attribute naamStringAttribute = new Attribute("naam", String.class);
controller.addAttribute(naamStringAttribute);
assertEquals(1, controller.classes.size());
assertEquals(1, controller.classes.get(0).getAttributes().size());
assertEquals(naamStringAttribute.getName(), controller.classes.get(0).getAttributes().get(0).getName());
assertEquals(0, controller.attributesToAssign.size());
}
}
|
174764_4 | package jrds;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jrds.starter.ConnectionInfo;
public class HostInfo {
private String name = null;
private String dnsName = null;
private Set<String> tags = null;
private File hostdir = null;
private boolean hidden = false;
private final Map<String, ConnectionInfo> cnxList = new HashMap<String, ConnectionInfo>();
private final Set<Probe<?, ?>> probesList = new HashSet<Probe<?, ?>>();
public HostInfo(String name) {
super();
this.name = name;
}
public HostInfo(String name, String dnsName) {
super();
this.name = name;
this.dnsName = dnsName;
}
/**
* @param hostdir the hostdir to set
*/
public void setHostDir(File hostdir) {
this.hostdir = hostdir;
}
public File getHostDir() {
return hostdir;
}
public void addTag(String tag) {
if(tags == null)
tags = new HashSet<String>();
tags.add(tag);
}
public Set<String> getTags() {
Set<String> temptags = tags;
if(tags == null)
temptags = new HashSet<String>();
return temptags;
}
/**
* @return the dnsName
*/
public String getDnsName() {
if(dnsName != null)
return dnsName;
else
return name;
}
/**
* @param dnsName the dnsName to set
*/
public void setDnsName(String dnsName) {
this.dnsName = dnsName;
}
/**
* Is the host to be shown in the host list ?
*
* @return the hidden
*/
public boolean isHidden() {
return hidden;
}
/**
* @param hidden the hidden to set
*/
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public void addConnection(ConnectionInfo cnx) {
cnxList.put(cnx.getName(), cnx);
}
public Iterable<ConnectionInfo> getConnections() {
return cnxList.values();
}
public ConnectionInfo getConnection(String name) {
return cnxList.get(name);
}
public void addProbe(Probe<?, ?> p) {
probesList.add(p);
}
public Iterable<Probe<?, ?>> getProbes() {
return probesList;
}
public int getNumProbes() {
return probesList.size();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name;
}
}
| Arkanosis/jrds | src/jrds/HostInfo.java | 861 | /**
* @param hidden the hidden to set
*/ | block_comment | nl | package jrds;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jrds.starter.ConnectionInfo;
public class HostInfo {
private String name = null;
private String dnsName = null;
private Set<String> tags = null;
private File hostdir = null;
private boolean hidden = false;
private final Map<String, ConnectionInfo> cnxList = new HashMap<String, ConnectionInfo>();
private final Set<Probe<?, ?>> probesList = new HashSet<Probe<?, ?>>();
public HostInfo(String name) {
super();
this.name = name;
}
public HostInfo(String name, String dnsName) {
super();
this.name = name;
this.dnsName = dnsName;
}
/**
* @param hostdir the hostdir to set
*/
public void setHostDir(File hostdir) {
this.hostdir = hostdir;
}
public File getHostDir() {
return hostdir;
}
public void addTag(String tag) {
if(tags == null)
tags = new HashSet<String>();
tags.add(tag);
}
public Set<String> getTags() {
Set<String> temptags = tags;
if(tags == null)
temptags = new HashSet<String>();
return temptags;
}
/**
* @return the dnsName
*/
public String getDnsName() {
if(dnsName != null)
return dnsName;
else
return name;
}
/**
* @param dnsName the dnsName to set
*/
public void setDnsName(String dnsName) {
this.dnsName = dnsName;
}
/**
* Is the host to be shown in the host list ?
*
* @return the hidden
*/
public boolean isHidden() {
return hidden;
}
/**
* @param hidden the<SUF>*/
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public void addConnection(ConnectionInfo cnx) {
cnxList.put(cnx.getName(), cnx);
}
public Iterable<ConnectionInfo> getConnections() {
return cnxList.values();
}
public ConnectionInfo getConnection(String name) {
return cnxList.get(name);
}
public void addProbe(Probe<?, ?> p) {
probesList.add(p);
}
public Iterable<Probe<?, ?>> getProbes() {
return probesList;
}
public int getNumProbes() {
return probesList.size();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name;
}
}
|
20470_0 | package presentation;
import patterns.component.SlideshowComposite;
/**
* <p>Presentation houdt de slides in de presentatie bij.</p>
* <p>Er is slechts ��n instantie van deze klasse aanwezig.</p>
* @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman
* @version 1.1 2002/12/17 Gert Florijn
* @version 1.2 2003/11/19 Sylvia Stuurman
* @version 1.3 2004/08/17 Sylvia Stuurman
* @version 1.4 2007/07/16 Sylvia Stuurman
* @version 1.5 2010/03/03 Sylvia Stuurman
* @version 1.6 2014/05/16 Sylvia Stuurman
* @version 1.7 - ?? Applied design @Amriet Jainandunsing
* @version 1.? 2022/11/03 Fixed opening from files via file explorer @Armando Gerard
*/
public class Presentation {
private String showTitle; // de titel van de presentatie
private SlideshowComposite slideshowComposite;
private static Presentation presentation;
private boolean isLocked = true;
public Presentation() {
if(presentation != null)
presentation.clear(true);
presentation = this;
isLocked = false;
}
public static Presentation getPresentation() {
return presentation;
}
public void setSlideshowComposite(SlideshowComposite slideshowComposite) {
this.slideshowComposite = slideshowComposite;
}
public String getTitle() {
return showTitle;
}
public void setTitle(String nt) {
showTitle = nt;
}
public SlideshowComposite getSlideshowComposite() {
return this.slideshowComposite;
}
public void setSlideNumber(int number) {
this.slideshowComposite.setActive(true);
this.slideshowComposite.setSlideNumber(number);
}
// Verwijder de presentatie, om klaar te zijn voor de volgende
public void clear(boolean locked) {
if(slideshowComposite != null) {
isLocked = locked;
slideshowComposite.setActive(!isLocked);
slideshowComposite.removeAll();
}
}
public void exit(int n) {
System.exit(n);
}
public boolean canQuit() {
// This would have changed if saving was implemented,
// it would check if there are processes active that need to be finished first
return true;
}
}
| Armandreano/ou-jabberpoint | src/presentation/Presentation.java | 695 | /**
* <p>Presentation houdt de slides in de presentatie bij.</p>
* <p>Er is slechts ��n instantie van deze klasse aanwezig.</p>
* @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman
* @version 1.1 2002/12/17 Gert Florijn
* @version 1.2 2003/11/19 Sylvia Stuurman
* @version 1.3 2004/08/17 Sylvia Stuurman
* @version 1.4 2007/07/16 Sylvia Stuurman
* @version 1.5 2010/03/03 Sylvia Stuurman
* @version 1.6 2014/05/16 Sylvia Stuurman
* @version 1.7 - ?? Applied design @Amriet Jainandunsing
* @version 1.? 2022/11/03 Fixed opening from files via file explorer @Armando Gerard
*/ | block_comment | nl | package presentation;
import patterns.component.SlideshowComposite;
/**
* <p>Presentation houdt de<SUF>*/
public class Presentation {
private String showTitle; // de titel van de presentatie
private SlideshowComposite slideshowComposite;
private static Presentation presentation;
private boolean isLocked = true;
public Presentation() {
if(presentation != null)
presentation.clear(true);
presentation = this;
isLocked = false;
}
public static Presentation getPresentation() {
return presentation;
}
public void setSlideshowComposite(SlideshowComposite slideshowComposite) {
this.slideshowComposite = slideshowComposite;
}
public String getTitle() {
return showTitle;
}
public void setTitle(String nt) {
showTitle = nt;
}
public SlideshowComposite getSlideshowComposite() {
return this.slideshowComposite;
}
public void setSlideNumber(int number) {
this.slideshowComposite.setActive(true);
this.slideshowComposite.setSlideNumber(number);
}
// Verwijder de presentatie, om klaar te zijn voor de volgende
public void clear(boolean locked) {
if(slideshowComposite != null) {
isLocked = locked;
slideshowComposite.setActive(!isLocked);
slideshowComposite.removeAll();
}
}
public void exit(int n) {
System.exit(n);
}
public boolean canQuit() {
// This would have changed if saving was implemented,
// it would check if there are processes active that need to be finished first
return true;
}
}
|
157027_0 | package core.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import jm.JMC;
import jm.music.data.Note;
import jm.music.data.Phrase;
import util.Log;
import util.Tools;
import core.data.chords.Chord;
import core.data.patterns.Pattern;
import core.data.patterns.SNPattern;
import core.data.tonality.Tonality;
public class DataStorage {
public static LinkedList<Pattern> SIMPLE_PATTERNS;
public static LinkedList<Pattern> SIMPLE_TONAL_PATTERNS;
public static LinkedList<Pattern> SIMPLE_CHORD_PATTERNS;
public static LinkedList<Pattern> SIMPLE_CHROMATIC_PATTERNS;
public static LinkedList<Pattern> SIMPLE_SAME_PATTERNS;
public static LinkedList<Pattern> SIMPLE_PATTERNS_FOR_MOTIVE;
public static LinkedList<Pattern> BASE_ACCOMPANIMENT_PATTERNS;
public static HashMap<PInstrument, LinkedList<Pattern>> INSTRUMENTS_ACCOMPANIMENTS;
public static LinkedList<Pattern> SECOND_VOICE_PATTERNS;
public static LinkedList<Pattern> MOVEMENT_PATTERNS;
public static HashMap<Integer, LinkedList<Pattern>> MOVEMENT_PATTERNS_VALUED; //Integer - movements jump value
public static LinkedList<PInstrument> INSTRUMENTS;
public static LinkedList<Melisma> MELISMAS;
public static void init()
{
SIMPLE_PATTERNS = new LinkedList<Pattern>();
SIMPLE_TONAL_PATTERNS = new LinkedList<Pattern>();
SIMPLE_CHORD_PATTERNS = new LinkedList<Pattern>();
SIMPLE_CHROMATIC_PATTERNS = new LinkedList<Pattern>();
SIMPLE_SAME_PATTERNS = new LinkedList<Pattern>();
SIMPLE_PATTERNS_FOR_MOTIVE = new LinkedList<Pattern>();
parseFileIntoList("database/SimplePatterns.txt", SIMPLE_PATTERNS);
for(Pattern p : SIMPLE_PATTERNS)
{
if(p.getName().toLowerCase().contains("same"))
SIMPLE_SAME_PATTERNS.add(p);
if(p.getName().toLowerCase().contains("chord"))
SIMPLE_CHORD_PATTERNS.add(p);
if(p.getName().toLowerCase().contains("chromatic"))
SIMPLE_CHROMATIC_PATTERNS.add(p);
if(p.getName().toLowerCase().contains("tonal"))
SIMPLE_TONAL_PATTERNS.add(p);
}
//SIMPLE_PATTERNS_FOR_MOTIVE.addAll(SIMPLE_CHROMATIC_PATTERNS);
SIMPLE_PATTERNS_FOR_MOTIVE.addAll(SIMPLE_TONAL_PATTERNS);
SIMPLE_PATTERNS_FOR_MOTIVE.addAll(SIMPLE_SAME_PATTERNS);
MOVEMENT_PATTERNS = new LinkedList<Pattern>();
parseFileIntoList("database/MovementPatterns.txt", MOVEMENT_PATTERNS);
MOVEMENT_PATTERNS_VALUED = new HashMap<Integer, LinkedList<Pattern>>();
for(Pattern i : MOVEMENT_PATTERNS)
{
Pattern p = new Pattern(i);
int patternJump = p.getOverallPatternJumpLength();
if(MOVEMENT_PATTERNS_VALUED.containsKey(patternJump))
{
MOVEMENT_PATTERNS_VALUED.get(patternJump).add(p);
}
else
{
LinkedList<Pattern> newList = new LinkedList<Pattern>();
newList.add(p);
MOVEMENT_PATTERNS_VALUED.put(patternJump, newList);
}
}
BASE_ACCOMPANIMENT_PATTERNS = new LinkedList<Pattern>();
parseFileIntoList("database/accompaniments/BaseAccompanimentPatterns.txt", BASE_ACCOMPANIMENT_PATTERNS);
SECOND_VOICE_PATTERNS = new LinkedList<Pattern>();
parseFileIntoList("database/SecondVoicePatterns.txt", SECOND_VOICE_PATTERNS);
MELISMAS = new LinkedList<Melisma>();
MELISMAS.add(new Melisma(Melisma.GRACE, -1));
MELISMAS.add(new Melisma(Melisma.GRACE, 1));
MELISMAS.add(new Melisma(Melisma.GRACE, -2));
MELISMAS.add(new Melisma(Melisma.GRACE, 2));
MELISMAS.add(new Melisma(Melisma.TRILL, -1));
MELISMAS.add(new Melisma(Melisma.TRILL, 1));
//Filling list of available instruments
INSTRUMENTS = new LinkedList<PInstrument>();
INSTRUMENTS.add(new PInstrument("Piano", "Фортепиано", JMC.PIANO, 3));
INSTRUMENTS.add(new PInstrument("Harpsichord", "Клавесин", JMC.HARPSICHORD, 3));
INSTRUMENTS.add(new PInstrument("Organ", "Орган", JMC.CHURCH_ORGAN, 2));
INSTRUMENTS.add(new PInstrument("Vibraphone", "Вибрафон", JMC.VIBES, 4));
INSTRUMENTS.add(new PInstrument("Xylophone", "Ксилофон", JMC.XYLOPHONE, 4));
INSTRUMENTS.add(new PInstrument("Glockenspiel", "Колокольчики", JMC.GLOCKENSPIEL, 4));
INSTRUMENTS.add(new PInstrument("Chimes", "Колокола", JMC.TUBULAR_BELL, 2));
INSTRUMENTS.add(new PInstrument("Harp", "Арфа", JMC.HARP, 3));
INSTRUMENTS.add(new PInstrument("Violin", "Скрипка", JMC.VIOLIN, 4));
INSTRUMENTS.add(new PInstrument("Viola", "Альт", JMC.VIOLA, 3));
INSTRUMENTS.add(new PInstrument("Cello", "Виолончель", JMC.CELLO, 2));
INSTRUMENTS.add(new PInstrument("Contrabass", "Контрабасс", JMC.DOUBLE_BASS, 1));
INSTRUMENTS.add(new PInstrument("Strings", "Струнные", JMC.STRING_ENSEMBLE_1, 3));
INSTRUMENTS.add(new PInstrument("Guitar", "Гитара", JMC.GUITAR, 3));
INSTRUMENTS.add(new PInstrument("Flute", "Флейта", JMC.FLUTE, 4));
INSTRUMENTS.add(new PInstrument("Clarinet", "Кларнет", JMC.CLARINET, 3));
INSTRUMENTS.add(new PInstrument("Oboe", "Гобой", JMC.OBOE, 3));
INSTRUMENTS.add(new PInstrument("Bassoon", "Фагот", JMC.BASSOON, 2));
INSTRUMENTS.add(new PInstrument("Bagpipe", "Волынка", JMC.BAGPIPE, 3));
INSTRUMENTS.add(new PInstrument("Shakuhachi", "Сякухати", JMC.SHAKUHACHI, 3));
INSTRUMENTS.add(new PInstrument("Saxophone", "Саксофон", JMC.SAX, 2));
INSTRUMENTS.add(new PInstrument("Trumpet", "Труба", JMC.TRUMPET, 3));
INSTRUMENTS.add(new PInstrument("Trombone", "Тромбон", JMC.TROMBONE, 2));
INSTRUMENTS.add(new PInstrument("Tuba", "Туба", JMC.TUBA, 2));
INSTRUMENTS.add(new PInstrument("Choir", "Хор", JMC.AAH, 3));
// INSTRUMENTS.add(new PInstrument("88", "88", JMC.FANTASIA, 3));
// INSTRUMENTS.add(new PInstrument("89", "89", 89, 3));
// INSTRUMENTS.add(new PInstrument("90", "90", 90, 3));
// INSTRUMENTS.add(new PInstrument("91", "91", 91, 3));
// INSTRUMENTS.add(new PInstrument("92", "92", 92, 3));
// INSTRUMENTS.add(new PInstrument("93", "93", 93, 3));
// INSTRUMENTS.add(new PInstrument("94", "94", 94, 3));
// INSTRUMENTS.add(new PInstrument("95", "95", 95, 3));
// INSTRUMENTS.add(new PInstrument("96", "96", 96, 3));
// INSTRUMENTS.add(new PInstrument("97", "97", 97, 3));
// INSTRUMENTS.add(new PInstrument("98", "98", 98, 3));
// INSTRUMENTS.add(new PInstrument("99", "99", 99, 3));
// INSTRUMENTS.add(new PInstrument("100", "100", 100, 3));
// INSTRUMENTS.add(new PInstrument("101", "101", 101, 3));
// INSTRUMENTS.add(new PInstrument("102", "102", 102, 3));
// INSTRUMENTS.add(new PInstrument("103", "103", 103, 3));
INSTRUMENTS_ACCOMPANIMENTS = new HashMap<PInstrument, LinkedList<Pattern>>();
for (PInstrument pi : INSTRUMENTS)
{
addInstrumentAccompanimentPattern(pi);
}
}
private static void addInstrumentAccompanimentPattern(PInstrument instrument)
{
LinkedList<Pattern> list = new LinkedList<Pattern>();
parseFileIntoList("database/accompaniments/" + instrument.name + "Patterns.txt", list);
INSTRUMENTS_ACCOMPANIMENTS.put(instrument, list);
}
public static PInstrument getInstrumentByName(String name)
{
for (PInstrument pi : INSTRUMENTS)
{
if (pi.name.equals(name))
return pi;
}
return null;
}
private static void parseFileIntoList(String filename, LinkedList<Pattern> list)
{
File f = new File(filename);
if (!f.exists())
return;
BufferedReader in;
try {
in = new BufferedReader(new FileReader(f));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if(inputLine.startsWith("//")) //Skip comments
continue;
if(inputLine.startsWith("Name~")) //Start of new pattern; Parse till end
{
String name = inputLine.substring(inputLine.indexOf("~") + 1); //Get name
String data = "";
while(!(inputLine = in.readLine()).startsWith("End"))
{
data = data + inputLine + ";";
}
Pattern p = new Pattern(data);
p.setName(name);
list.add(p);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Phrase patternsToPhrase(
List<Pattern> patterns,
HashMap<Double, Chord> harmony,
Tonality currentTonality
)
{
Phrase phr = new Phrase();
//Get all the PNotes from all patterns
LinkedList<PNote> notes = new LinkedList<PNote>();
for (Pattern p : patterns)
notes.addAll(p.getNotes());
if(notes.getFirst().getTransitionType() != PConstants.STABLE_NOTE)
{
Log.severe("DataStorage > patternsToPhrase > Error converting to phrase. First note is not beginning.");
return null;
}
Note lastNote = null;
double barPosition = 0.0;
for (PNote note : notes)
{
if (note.getTransitionType() == PConstants.STABLE_NOTE)
{
if(note.hasMelismas())
{
Melisma melisma = note.getMelismas();
switch (melisma.getType())
{
case Melisma.GRACE:
//First, we add a grace note
Note melismaNote = new Note(note.getPitch() + melisma.getPitchValue(), JMC.THIRTYSECOND_NOTE, note.getVolume() - 5);
phr.add(melismaNote);
//Then we add main note
phr.add(new Note(note.getPitch(), getAbsoluteLength(note.getLength(), note.getAbsolute_length()) - JMC.THIRTYSECOND_NOTE, note.getVolume()));
break;
case Melisma.TRILL:
double trillLength = getAbsoluteLength(note.getLength(), note.getAbsolute_length());
int trillMultiplier = 0;
while (trillLength > 0)
{
phr.add(new Note(note.getPitch() + melisma.getPitchValue() * trillMultiplier, JMC.THIRTYSECOND_NOTE, note.getVolume()));
trillMultiplier = ( trillMultiplier + 1 ) % 2;
trillLength -= JMC.THIRTYSECOND_NOTE;
}
break;
}
}
else
{
phr.add(new Note(note.getPitch(), getAbsoluteLength(note.getLength(), note.getAbsolute_length()), note.getVolume()));
}
//Define last note independently. Any melismas doesn't affect this var.
lastNote = new Note(note.getPitch(), getAbsoluteLength(note.getLength(), note.getAbsolute_length()), note.getVolume());
}
else
{
//TODO: volume changes still doesn't work. Meh.
Chord cd = harmony.get(Tools.nearestKey(harmony, barPosition));
Note n = new Note(getPitchByTransition(note.getTransitionType(),
note.getTransitionValue(),
lastNote.getPitch(), cd, currentTonality),
getAbsoluteLength(note.getLength(), lastNote.getRhythmValue()),
lastNote.getDynamic()
);
phr.add(n);
lastNote = n;
}
barPosition += lastNote.getRhythmValue();
}
return phr;
}
/** Get pitch based on transition parameters and other stuff.
* @param transitionType
* @param transitionValue
* @param pitch
* @param cd
* @param currentTonality
* @return
*/
public static int getPitchByTransition(
int transitionType,
int[] transitionValue,
int pitch,
Chord cd,
Tonality currentTonality
)
{
switch (transitionType) {
case PConstants.SAME_PITCH:
return pitch;
case PConstants.CHORD_JUMP:
return Tools.getElementInArrayByStep(transitionValue[0], cd.getAllChordNotes(), pitch);
case PConstants.CHROMATIC_JUMP:
return pitch + transitionValue[0];
case PConstants.TONALITY_JUMP:
return currentTonality.getTonalityNoteByStep(transitionValue[0], pitch);
case PConstants.COMPLEX:
int chordResult = Tools.getElementInArrayByStep(transitionValue[0], cd.getAllChordNotes(), pitch);
int tonalityResult = currentTonality.getTonalityNoteByStep(transitionValue[0], chordResult);
return tonalityResult;
default:
return pitch;
}
}
/** Get pitch based on transition parameters and other stuff except a chord.
* @param transitionType
* @param transitionValue
* @param pitch
* @param currentTonality
* @return
*/
public static int getPitchByTransition(
int transitionType,
int[] transitionValue,
int pitch,
Tonality currentTonality
)
{
switch (transitionType) {
case PConstants.SAME_PITCH:
return pitch;
case PConstants.CHORD_JUMP: //This situation doesn't appear because when calling this method - we never use chords.
return pitch;
case PConstants.CHROMATIC_JUMP:
return pitch + transitionValue[0];
case PConstants.TONALITY_JUMP:
return currentTonality.getTonalityNoteByStep(transitionValue[0], pitch);
case PConstants.COMPLEX: //This situation doesn't appear either because when calling this method - we never use chords.
return pitch;
default:
return pitch;
}
}
/** Returns a random pattern from hashMap which has required jumpvalue.
* @param jumpValue
* @param patternsHashMap
* @return New instance of pattern (no needs to wrap into new Pattern());
*/
public static Pattern getRandomPatternByJumpValue(
int jumpValue,
HashMap<Integer, LinkedList<Pattern>> patternsHashMap
)
{
if(!patternsHashMap.containsKey(jumpValue))
{
Log.severe("DataStorage > getRandomPatternByJumpValue > No entries for this jump value! Value = " + jumpValue);
return new SNPattern(JMC.D4, JMC.QUARTER_NOTE); // I'm a kind person, I always can give asker a D ;)
}
LinkedList<Pattern> goodPatterns = patternsHashMap.get(jumpValue);
int randomId = (int)(Math.random()*(goodPatterns.size() - 1));
return new Pattern(goodPatterns.get(randomId));
}
public static double getAbsoluteLength(
double relativeLength,
double absoluteLength)
{
return relativeLength * absoluteLength;
}
public static Pattern getRandomPatternFromList(LinkedList<Pattern> list)
{
return list.get((new Random()).nextInt(list.size()));
}
public static Melisma getRandomMelismaFromList(LinkedList<Melisma> list)
{
return list.get((new Random()).nextInt(list.size()));
}
public static String getTonalityTypeByName(String name)
{
if(name.equals("минор"))
return "minor";
if(name.equals("мажор"))
return "major";
Log.severe("DataStorage > Unknown tonality: " + name);
return "major";
}
public static String[] getInstrumentsImagesList()
{
String[] array = new String[INSTRUMENTS.size()];
for (int i = 0; i < INSTRUMENTS.size(); i++)
{
array[i] = INSTRUMENTS.get(i).name;
}
return array;
}
public static String[] getInstrumentsRussianNamesList()
{
String[] array = new String[INSTRUMENTS.size()];
for (int i = 0; i < INSTRUMENTS.size(); i++)
{
array[i] = INSTRUMENTS.get(i).RussianName;
}
return array;
}
public static int getInstrumentIdByMidiId(int midiId)
{
for (int i = 0; i < INSTRUMENTS.size(); i++)
{
PInstrument p = INSTRUMENTS.get(i);
if (p.midiId == midiId)
return i;
}
return -1;
}
}
| Armaxis/jmg | src/main/java/core/data/DataStorage.java | 5,762 | //Integer - movements jump value | line_comment | nl | package core.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import jm.JMC;
import jm.music.data.Note;
import jm.music.data.Phrase;
import util.Log;
import util.Tools;
import core.data.chords.Chord;
import core.data.patterns.Pattern;
import core.data.patterns.SNPattern;
import core.data.tonality.Tonality;
public class DataStorage {
public static LinkedList<Pattern> SIMPLE_PATTERNS;
public static LinkedList<Pattern> SIMPLE_TONAL_PATTERNS;
public static LinkedList<Pattern> SIMPLE_CHORD_PATTERNS;
public static LinkedList<Pattern> SIMPLE_CHROMATIC_PATTERNS;
public static LinkedList<Pattern> SIMPLE_SAME_PATTERNS;
public static LinkedList<Pattern> SIMPLE_PATTERNS_FOR_MOTIVE;
public static LinkedList<Pattern> BASE_ACCOMPANIMENT_PATTERNS;
public static HashMap<PInstrument, LinkedList<Pattern>> INSTRUMENTS_ACCOMPANIMENTS;
public static LinkedList<Pattern> SECOND_VOICE_PATTERNS;
public static LinkedList<Pattern> MOVEMENT_PATTERNS;
public static HashMap<Integer, LinkedList<Pattern>> MOVEMENT_PATTERNS_VALUED; //Integer -<SUF>
public static LinkedList<PInstrument> INSTRUMENTS;
public static LinkedList<Melisma> MELISMAS;
public static void init()
{
SIMPLE_PATTERNS = new LinkedList<Pattern>();
SIMPLE_TONAL_PATTERNS = new LinkedList<Pattern>();
SIMPLE_CHORD_PATTERNS = new LinkedList<Pattern>();
SIMPLE_CHROMATIC_PATTERNS = new LinkedList<Pattern>();
SIMPLE_SAME_PATTERNS = new LinkedList<Pattern>();
SIMPLE_PATTERNS_FOR_MOTIVE = new LinkedList<Pattern>();
parseFileIntoList("database/SimplePatterns.txt", SIMPLE_PATTERNS);
for(Pattern p : SIMPLE_PATTERNS)
{
if(p.getName().toLowerCase().contains("same"))
SIMPLE_SAME_PATTERNS.add(p);
if(p.getName().toLowerCase().contains("chord"))
SIMPLE_CHORD_PATTERNS.add(p);
if(p.getName().toLowerCase().contains("chromatic"))
SIMPLE_CHROMATIC_PATTERNS.add(p);
if(p.getName().toLowerCase().contains("tonal"))
SIMPLE_TONAL_PATTERNS.add(p);
}
//SIMPLE_PATTERNS_FOR_MOTIVE.addAll(SIMPLE_CHROMATIC_PATTERNS);
SIMPLE_PATTERNS_FOR_MOTIVE.addAll(SIMPLE_TONAL_PATTERNS);
SIMPLE_PATTERNS_FOR_MOTIVE.addAll(SIMPLE_SAME_PATTERNS);
MOVEMENT_PATTERNS = new LinkedList<Pattern>();
parseFileIntoList("database/MovementPatterns.txt", MOVEMENT_PATTERNS);
MOVEMENT_PATTERNS_VALUED = new HashMap<Integer, LinkedList<Pattern>>();
for(Pattern i : MOVEMENT_PATTERNS)
{
Pattern p = new Pattern(i);
int patternJump = p.getOverallPatternJumpLength();
if(MOVEMENT_PATTERNS_VALUED.containsKey(patternJump))
{
MOVEMENT_PATTERNS_VALUED.get(patternJump).add(p);
}
else
{
LinkedList<Pattern> newList = new LinkedList<Pattern>();
newList.add(p);
MOVEMENT_PATTERNS_VALUED.put(patternJump, newList);
}
}
BASE_ACCOMPANIMENT_PATTERNS = new LinkedList<Pattern>();
parseFileIntoList("database/accompaniments/BaseAccompanimentPatterns.txt", BASE_ACCOMPANIMENT_PATTERNS);
SECOND_VOICE_PATTERNS = new LinkedList<Pattern>();
parseFileIntoList("database/SecondVoicePatterns.txt", SECOND_VOICE_PATTERNS);
MELISMAS = new LinkedList<Melisma>();
MELISMAS.add(new Melisma(Melisma.GRACE, -1));
MELISMAS.add(new Melisma(Melisma.GRACE, 1));
MELISMAS.add(new Melisma(Melisma.GRACE, -2));
MELISMAS.add(new Melisma(Melisma.GRACE, 2));
MELISMAS.add(new Melisma(Melisma.TRILL, -1));
MELISMAS.add(new Melisma(Melisma.TRILL, 1));
//Filling list of available instruments
INSTRUMENTS = new LinkedList<PInstrument>();
INSTRUMENTS.add(new PInstrument("Piano", "Фортепиано", JMC.PIANO, 3));
INSTRUMENTS.add(new PInstrument("Harpsichord", "Клавесин", JMC.HARPSICHORD, 3));
INSTRUMENTS.add(new PInstrument("Organ", "Орган", JMC.CHURCH_ORGAN, 2));
INSTRUMENTS.add(new PInstrument("Vibraphone", "Вибрафон", JMC.VIBES, 4));
INSTRUMENTS.add(new PInstrument("Xylophone", "Ксилофон", JMC.XYLOPHONE, 4));
INSTRUMENTS.add(new PInstrument("Glockenspiel", "Колокольчики", JMC.GLOCKENSPIEL, 4));
INSTRUMENTS.add(new PInstrument("Chimes", "Колокола", JMC.TUBULAR_BELL, 2));
INSTRUMENTS.add(new PInstrument("Harp", "Арфа", JMC.HARP, 3));
INSTRUMENTS.add(new PInstrument("Violin", "Скрипка", JMC.VIOLIN, 4));
INSTRUMENTS.add(new PInstrument("Viola", "Альт", JMC.VIOLA, 3));
INSTRUMENTS.add(new PInstrument("Cello", "Виолончель", JMC.CELLO, 2));
INSTRUMENTS.add(new PInstrument("Contrabass", "Контрабасс", JMC.DOUBLE_BASS, 1));
INSTRUMENTS.add(new PInstrument("Strings", "Струнные", JMC.STRING_ENSEMBLE_1, 3));
INSTRUMENTS.add(new PInstrument("Guitar", "Гитара", JMC.GUITAR, 3));
INSTRUMENTS.add(new PInstrument("Flute", "Флейта", JMC.FLUTE, 4));
INSTRUMENTS.add(new PInstrument("Clarinet", "Кларнет", JMC.CLARINET, 3));
INSTRUMENTS.add(new PInstrument("Oboe", "Гобой", JMC.OBOE, 3));
INSTRUMENTS.add(new PInstrument("Bassoon", "Фагот", JMC.BASSOON, 2));
INSTRUMENTS.add(new PInstrument("Bagpipe", "Волынка", JMC.BAGPIPE, 3));
INSTRUMENTS.add(new PInstrument("Shakuhachi", "Сякухати", JMC.SHAKUHACHI, 3));
INSTRUMENTS.add(new PInstrument("Saxophone", "Саксофон", JMC.SAX, 2));
INSTRUMENTS.add(new PInstrument("Trumpet", "Труба", JMC.TRUMPET, 3));
INSTRUMENTS.add(new PInstrument("Trombone", "Тромбон", JMC.TROMBONE, 2));
INSTRUMENTS.add(new PInstrument("Tuba", "Туба", JMC.TUBA, 2));
INSTRUMENTS.add(new PInstrument("Choir", "Хор", JMC.AAH, 3));
// INSTRUMENTS.add(new PInstrument("88", "88", JMC.FANTASIA, 3));
// INSTRUMENTS.add(new PInstrument("89", "89", 89, 3));
// INSTRUMENTS.add(new PInstrument("90", "90", 90, 3));
// INSTRUMENTS.add(new PInstrument("91", "91", 91, 3));
// INSTRUMENTS.add(new PInstrument("92", "92", 92, 3));
// INSTRUMENTS.add(new PInstrument("93", "93", 93, 3));
// INSTRUMENTS.add(new PInstrument("94", "94", 94, 3));
// INSTRUMENTS.add(new PInstrument("95", "95", 95, 3));
// INSTRUMENTS.add(new PInstrument("96", "96", 96, 3));
// INSTRUMENTS.add(new PInstrument("97", "97", 97, 3));
// INSTRUMENTS.add(new PInstrument("98", "98", 98, 3));
// INSTRUMENTS.add(new PInstrument("99", "99", 99, 3));
// INSTRUMENTS.add(new PInstrument("100", "100", 100, 3));
// INSTRUMENTS.add(new PInstrument("101", "101", 101, 3));
// INSTRUMENTS.add(new PInstrument("102", "102", 102, 3));
// INSTRUMENTS.add(new PInstrument("103", "103", 103, 3));
INSTRUMENTS_ACCOMPANIMENTS = new HashMap<PInstrument, LinkedList<Pattern>>();
for (PInstrument pi : INSTRUMENTS)
{
addInstrumentAccompanimentPattern(pi);
}
}
private static void addInstrumentAccompanimentPattern(PInstrument instrument)
{
LinkedList<Pattern> list = new LinkedList<Pattern>();
parseFileIntoList("database/accompaniments/" + instrument.name + "Patterns.txt", list);
INSTRUMENTS_ACCOMPANIMENTS.put(instrument, list);
}
public static PInstrument getInstrumentByName(String name)
{
for (PInstrument pi : INSTRUMENTS)
{
if (pi.name.equals(name))
return pi;
}
return null;
}
private static void parseFileIntoList(String filename, LinkedList<Pattern> list)
{
File f = new File(filename);
if (!f.exists())
return;
BufferedReader in;
try {
in = new BufferedReader(new FileReader(f));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if(inputLine.startsWith("//")) //Skip comments
continue;
if(inputLine.startsWith("Name~")) //Start of new pattern; Parse till end
{
String name = inputLine.substring(inputLine.indexOf("~") + 1); //Get name
String data = "";
while(!(inputLine = in.readLine()).startsWith("End"))
{
data = data + inputLine + ";";
}
Pattern p = new Pattern(data);
p.setName(name);
list.add(p);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Phrase patternsToPhrase(
List<Pattern> patterns,
HashMap<Double, Chord> harmony,
Tonality currentTonality
)
{
Phrase phr = new Phrase();
//Get all the PNotes from all patterns
LinkedList<PNote> notes = new LinkedList<PNote>();
for (Pattern p : patterns)
notes.addAll(p.getNotes());
if(notes.getFirst().getTransitionType() != PConstants.STABLE_NOTE)
{
Log.severe("DataStorage > patternsToPhrase > Error converting to phrase. First note is not beginning.");
return null;
}
Note lastNote = null;
double barPosition = 0.0;
for (PNote note : notes)
{
if (note.getTransitionType() == PConstants.STABLE_NOTE)
{
if(note.hasMelismas())
{
Melisma melisma = note.getMelismas();
switch (melisma.getType())
{
case Melisma.GRACE:
//First, we add a grace note
Note melismaNote = new Note(note.getPitch() + melisma.getPitchValue(), JMC.THIRTYSECOND_NOTE, note.getVolume() - 5);
phr.add(melismaNote);
//Then we add main note
phr.add(new Note(note.getPitch(), getAbsoluteLength(note.getLength(), note.getAbsolute_length()) - JMC.THIRTYSECOND_NOTE, note.getVolume()));
break;
case Melisma.TRILL:
double trillLength = getAbsoluteLength(note.getLength(), note.getAbsolute_length());
int trillMultiplier = 0;
while (trillLength > 0)
{
phr.add(new Note(note.getPitch() + melisma.getPitchValue() * trillMultiplier, JMC.THIRTYSECOND_NOTE, note.getVolume()));
trillMultiplier = ( trillMultiplier + 1 ) % 2;
trillLength -= JMC.THIRTYSECOND_NOTE;
}
break;
}
}
else
{
phr.add(new Note(note.getPitch(), getAbsoluteLength(note.getLength(), note.getAbsolute_length()), note.getVolume()));
}
//Define last note independently. Any melismas doesn't affect this var.
lastNote = new Note(note.getPitch(), getAbsoluteLength(note.getLength(), note.getAbsolute_length()), note.getVolume());
}
else
{
//TODO: volume changes still doesn't work. Meh.
Chord cd = harmony.get(Tools.nearestKey(harmony, barPosition));
Note n = new Note(getPitchByTransition(note.getTransitionType(),
note.getTransitionValue(),
lastNote.getPitch(), cd, currentTonality),
getAbsoluteLength(note.getLength(), lastNote.getRhythmValue()),
lastNote.getDynamic()
);
phr.add(n);
lastNote = n;
}
barPosition += lastNote.getRhythmValue();
}
return phr;
}
/** Get pitch based on transition parameters and other stuff.
* @param transitionType
* @param transitionValue
* @param pitch
* @param cd
* @param currentTonality
* @return
*/
public static int getPitchByTransition(
int transitionType,
int[] transitionValue,
int pitch,
Chord cd,
Tonality currentTonality
)
{
switch (transitionType) {
case PConstants.SAME_PITCH:
return pitch;
case PConstants.CHORD_JUMP:
return Tools.getElementInArrayByStep(transitionValue[0], cd.getAllChordNotes(), pitch);
case PConstants.CHROMATIC_JUMP:
return pitch + transitionValue[0];
case PConstants.TONALITY_JUMP:
return currentTonality.getTonalityNoteByStep(transitionValue[0], pitch);
case PConstants.COMPLEX:
int chordResult = Tools.getElementInArrayByStep(transitionValue[0], cd.getAllChordNotes(), pitch);
int tonalityResult = currentTonality.getTonalityNoteByStep(transitionValue[0], chordResult);
return tonalityResult;
default:
return pitch;
}
}
/** Get pitch based on transition parameters and other stuff except a chord.
* @param transitionType
* @param transitionValue
* @param pitch
* @param currentTonality
* @return
*/
public static int getPitchByTransition(
int transitionType,
int[] transitionValue,
int pitch,
Tonality currentTonality
)
{
switch (transitionType) {
case PConstants.SAME_PITCH:
return pitch;
case PConstants.CHORD_JUMP: //This situation doesn't appear because when calling this method - we never use chords.
return pitch;
case PConstants.CHROMATIC_JUMP:
return pitch + transitionValue[0];
case PConstants.TONALITY_JUMP:
return currentTonality.getTonalityNoteByStep(transitionValue[0], pitch);
case PConstants.COMPLEX: //This situation doesn't appear either because when calling this method - we never use chords.
return pitch;
default:
return pitch;
}
}
/** Returns a random pattern from hashMap which has required jumpvalue.
* @param jumpValue
* @param patternsHashMap
* @return New instance of pattern (no needs to wrap into new Pattern());
*/
public static Pattern getRandomPatternByJumpValue(
int jumpValue,
HashMap<Integer, LinkedList<Pattern>> patternsHashMap
)
{
if(!patternsHashMap.containsKey(jumpValue))
{
Log.severe("DataStorage > getRandomPatternByJumpValue > No entries for this jump value! Value = " + jumpValue);
return new SNPattern(JMC.D4, JMC.QUARTER_NOTE); // I'm a kind person, I always can give asker a D ;)
}
LinkedList<Pattern> goodPatterns = patternsHashMap.get(jumpValue);
int randomId = (int)(Math.random()*(goodPatterns.size() - 1));
return new Pattern(goodPatterns.get(randomId));
}
public static double getAbsoluteLength(
double relativeLength,
double absoluteLength)
{
return relativeLength * absoluteLength;
}
public static Pattern getRandomPatternFromList(LinkedList<Pattern> list)
{
return list.get((new Random()).nextInt(list.size()));
}
public static Melisma getRandomMelismaFromList(LinkedList<Melisma> list)
{
return list.get((new Random()).nextInt(list.size()));
}
public static String getTonalityTypeByName(String name)
{
if(name.equals("минор"))
return "minor";
if(name.equals("мажор"))
return "major";
Log.severe("DataStorage > Unknown tonality: " + name);
return "major";
}
public static String[] getInstrumentsImagesList()
{
String[] array = new String[INSTRUMENTS.size()];
for (int i = 0; i < INSTRUMENTS.size(); i++)
{
array[i] = INSTRUMENTS.get(i).name;
}
return array;
}
public static String[] getInstrumentsRussianNamesList()
{
String[] array = new String[INSTRUMENTS.size()];
for (int i = 0; i < INSTRUMENTS.size(); i++)
{
array[i] = INSTRUMENTS.get(i).RussianName;
}
return array;
}
public static int getInstrumentIdByMidiId(int midiId)
{
for (int i = 0; i < INSTRUMENTS.size(); i++)
{
PInstrument p = INSTRUMENTS.get(i);
if (p.midiId == midiId)
return i;
}
return -1;
}
}
|
3049_15 | package armijn.vink.numberviewanimation;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import armijn.vink.numberviewanimation.fonts.Roboto;
public class NumberView extends View {
private final Interpolator mInterpolator;
private Paint mPaint;
private final Path mPath;
// Numbers currently shown.
private int mCurrent = 0;
private int mNext = 1;
// Frame of transition between current and next frames.
private int mFrame = 0;
private float[][][] mPoints;
private float[][][] mControlPoint1;
private float[][][] mControlPoint2;
private int textColor;
private float strokeSize;
private float viewSize;
private String font;
public NumberView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
setWillNotDraw(false);
mInterpolator = new AccelerateDecelerateInterpolator();
// A new paint with the style as stroke.
mPaint = new Paint();
Roboto roboto = new Roboto(textColor, strokeSize*3);
mPoints = Roboto.getMpoints();
mControlPoint1 = Roboto.getMcontrolpoint1();
mControlPoint2 = Roboto.getMcontrolpoint2();
mPaint = roboto.getPaint();
if(font.equals("roboto_thin")){
mPaint.setStrokeWidth(strokeSize*3);
}else if(font.equals("roboto_light")){
mPaint.setStrokeWidth(strokeSize*6);
}else if(font.equals("roboto_regular")){
mPaint.setStrokeWidth(strokeSize*9);
}else if(font.equals("roboto_medium")){
mPaint.setStrokeWidth(strokeSize*12);
}else if(font.equals("roboto_bold")){
mPaint.setStrokeWidth(strokeSize*15);
}else if(font.equals("roboto_black")){
mPaint.setStrokeWidth(strokeSize*18);
}
mPath = new Path();
}
private void init(AttributeSet attrs) {
TypedArray ta=getContext().obtainStyledAttributes(attrs, R.styleable.NumberViewAttr);
//set custom attr
try {
textColor = ta.getColor(R.styleable.NumberViewAttr_android_textColor, Color.BLACK);
strokeSize = ta.getDimensionPixelSize(R.styleable.NumberViewAttr_strokeSize, 5);
viewSize = ta.getDimensionPixelSize(R.styleable.NumberViewAttr_viewSize, 250);
font = ta.getString(R.styleable.NumberViewAttr_font);
if(font == null){
font = "roboto_regular";
}
viewSize = (viewSize/250);
strokeSize = (viewSize);
} finally {
ta.recycle();
}
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Frames 0, 1 is the first pause.
// Frames 9, 10 is the last pause.
// Constrain current frame to be between 0 and 6.
final int currentFrame;
if (mFrame < 2) {
currentFrame = 0;
} else if (mFrame > 8) {
currentFrame = 6;
} else {
currentFrame = mFrame - 2;
}
// A factor of the difference between current
// and next frame based on interpolation.
// Only 6 frames are used between the transition.
final float factor = mInterpolator.getInterpolation(currentFrame / 6.0f);
// Reset the path.
mPath.reset();
final float[][] current = mPoints[mCurrent];
final float[][] next = mPoints[mNext];
final float[][] curr1 = mControlPoint1[mCurrent];
final float[][] next1 = mControlPoint1[mNext];
final float[][] curr2 = mControlPoint2[mCurrent];
final float[][] next2 = mControlPoint2[mNext];
// First point.
mPath.moveTo((current[0][0]*viewSize) + (((next[0][0]*viewSize) - (current[0][0]*viewSize)) * factor),
(current[0][1]*viewSize) + (((next[0][1]*viewSize) - (current[0][1]*viewSize)) * factor));
// Rest of the points connected as bezier curve.
for (int i = 1; i < 5; i++) {
mPath.cubicTo((curr1[i-1][0]*viewSize) + (((next1[i-1][0]*viewSize) - (curr1[i-1][0]*viewSize)) * factor),
(curr1[i-1][1]*viewSize) + (((next1[i-1][1]*viewSize) - (curr1[i-1][1]*viewSize)) * factor),
(curr2[i-1][0]*viewSize) + (((next2[i-1][0]*viewSize) - (curr2[i-1][0]*viewSize)) * factor),
(curr2[i-1][1]*viewSize) + (((next2[i-1][1]*viewSize) - (curr2[i-1][1]*viewSize)) * factor),
(current[i][0]*viewSize) + (((next[i][0]*viewSize) - (current[i][0]*viewSize)) * factor),
(current[i][1]*viewSize) + (((next[i][1]*viewSize) - (current[i][1]*viewSize)) * factor));
}
// Draw the path.
canvas.drawPath(mPath, mPaint);
// Next frame.
mFrame++;
// Each number change has 10 frames. Reset.
if (mFrame == 10) {
// Reset to zerro.
mFrame = 0;
mCurrent = mNext;
mNext++;
// Reset to zerro.
if (mNext == 10) {
mNext = 0;
}
}
// Callback for the next frame.
postInvalidateDelayed(50);
}
} | Armijn/NumberViewAnimation | src/armijn/vink/numberviewanimation/NumberView.java | 1,821 | // Reset to zerro. | line_comment | nl | package armijn.vink.numberviewanimation;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import armijn.vink.numberviewanimation.fonts.Roboto;
public class NumberView extends View {
private final Interpolator mInterpolator;
private Paint mPaint;
private final Path mPath;
// Numbers currently shown.
private int mCurrent = 0;
private int mNext = 1;
// Frame of transition between current and next frames.
private int mFrame = 0;
private float[][][] mPoints;
private float[][][] mControlPoint1;
private float[][][] mControlPoint2;
private int textColor;
private float strokeSize;
private float viewSize;
private String font;
public NumberView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
setWillNotDraw(false);
mInterpolator = new AccelerateDecelerateInterpolator();
// A new paint with the style as stroke.
mPaint = new Paint();
Roboto roboto = new Roboto(textColor, strokeSize*3);
mPoints = Roboto.getMpoints();
mControlPoint1 = Roboto.getMcontrolpoint1();
mControlPoint2 = Roboto.getMcontrolpoint2();
mPaint = roboto.getPaint();
if(font.equals("roboto_thin")){
mPaint.setStrokeWidth(strokeSize*3);
}else if(font.equals("roboto_light")){
mPaint.setStrokeWidth(strokeSize*6);
}else if(font.equals("roboto_regular")){
mPaint.setStrokeWidth(strokeSize*9);
}else if(font.equals("roboto_medium")){
mPaint.setStrokeWidth(strokeSize*12);
}else if(font.equals("roboto_bold")){
mPaint.setStrokeWidth(strokeSize*15);
}else if(font.equals("roboto_black")){
mPaint.setStrokeWidth(strokeSize*18);
}
mPath = new Path();
}
private void init(AttributeSet attrs) {
TypedArray ta=getContext().obtainStyledAttributes(attrs, R.styleable.NumberViewAttr);
//set custom attr
try {
textColor = ta.getColor(R.styleable.NumberViewAttr_android_textColor, Color.BLACK);
strokeSize = ta.getDimensionPixelSize(R.styleable.NumberViewAttr_strokeSize, 5);
viewSize = ta.getDimensionPixelSize(R.styleable.NumberViewAttr_viewSize, 250);
font = ta.getString(R.styleable.NumberViewAttr_font);
if(font == null){
font = "roboto_regular";
}
viewSize = (viewSize/250);
strokeSize = (viewSize);
} finally {
ta.recycle();
}
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Frames 0, 1 is the first pause.
// Frames 9, 10 is the last pause.
// Constrain current frame to be between 0 and 6.
final int currentFrame;
if (mFrame < 2) {
currentFrame = 0;
} else if (mFrame > 8) {
currentFrame = 6;
} else {
currentFrame = mFrame - 2;
}
// A factor of the difference between current
// and next frame based on interpolation.
// Only 6 frames are used between the transition.
final float factor = mInterpolator.getInterpolation(currentFrame / 6.0f);
// Reset the path.
mPath.reset();
final float[][] current = mPoints[mCurrent];
final float[][] next = mPoints[mNext];
final float[][] curr1 = mControlPoint1[mCurrent];
final float[][] next1 = mControlPoint1[mNext];
final float[][] curr2 = mControlPoint2[mCurrent];
final float[][] next2 = mControlPoint2[mNext];
// First point.
mPath.moveTo((current[0][0]*viewSize) + (((next[0][0]*viewSize) - (current[0][0]*viewSize)) * factor),
(current[0][1]*viewSize) + (((next[0][1]*viewSize) - (current[0][1]*viewSize)) * factor));
// Rest of the points connected as bezier curve.
for (int i = 1; i < 5; i++) {
mPath.cubicTo((curr1[i-1][0]*viewSize) + (((next1[i-1][0]*viewSize) - (curr1[i-1][0]*viewSize)) * factor),
(curr1[i-1][1]*viewSize) + (((next1[i-1][1]*viewSize) - (curr1[i-1][1]*viewSize)) * factor),
(curr2[i-1][0]*viewSize) + (((next2[i-1][0]*viewSize) - (curr2[i-1][0]*viewSize)) * factor),
(curr2[i-1][1]*viewSize) + (((next2[i-1][1]*viewSize) - (curr2[i-1][1]*viewSize)) * factor),
(current[i][0]*viewSize) + (((next[i][0]*viewSize) - (current[i][0]*viewSize)) * factor),
(current[i][1]*viewSize) + (((next[i][1]*viewSize) - (current[i][1]*viewSize)) * factor));
}
// Draw the path.
canvas.drawPath(mPath, mPaint);
// Next frame.
mFrame++;
// Each number change has 10 frames. Reset.
if (mFrame == 10) {
// Reset to zerro.
mFrame = 0;
mCurrent = mNext;
mNext++;
// Reset to<SUF>
if (mNext == 10) {
mNext = 0;
}
}
// Callback for the next frame.
postInvalidateDelayed(50);
}
} |
29706_3 | package algoritmen;
import java.util.ArrayList;
public class KoninginnenProbleem {
public static void main(String[] args){
int n = 6;
System.out.println(nQueens(n));
}
//static anders niet oproepen zonder object te maken
public static ArrayList<Integer> nQueens(int n){
return queens(n,1,1,new ArrayList<Integer>());
}
private static ArrayList<Integer> queens(int aantalKoninginnen, int huidigeKolom, int huidigeRij,ArrayList<Integer> vorigeQ){
if (aantalKoninginnen < huidigeKolom){ //als de huidige queen die je wil plaatsen groter is dan aantal dat je moet zetten weet je dat de vorige list de oplossing was
return vorigeQ;
}
else if (isVeilig(huidigeRij, vorigeQ) && (huidigeRij<=aantalKoninginnen)){
//bewaar de huidige positie voor de huidige koningin
vorigeQ.add(huidigeRij);
//probeer de volgende koninging te plaatsten
return queens(aantalKoninginnen,huidigeKolom+1,1,vorigeQ);
}
//nagaan of de huidigeKolom/koningin nog een volgende mogelijkheid/rij heeft
//alleen zinvol indien er nog plaats is
else if (huidigeRij<aantalKoninginnen){
return queens(aantalKoninginnen, huidigeKolom,huidigeRij+1, vorigeQ);
}
//backtracking
else {
//je kan niet verder backtracken => geen oplossing
if (huidigeKolom == 1) return new ArrayList<>();
else {
int vorigeKolom = huidigeKolom - 1;
int vorigeRij = vorigeQ.get(vorigeQ.size() - 1);
vorigeQ.remove(vorigeQ.size() - 1);
return queens(aantalKoninginnen, vorigeKolom, vorigeRij + 1, vorigeQ);
}
}
}
public static boolean isVeilig(int rij, ArrayList<Integer> vorige) {
for(int rij2 : vorige){
int verschil = vorige.size()-vorige.indexOf(rij2);
if (rij == rij2){
return false;
}
else if (rij2 == rij-verschil || rij2==rij+verschil) {
return false;
}
}
return true;
}
}
| ArneDuyver/EigenTesten | src/main/java/algoritmen/KoninginnenProbleem.java | 698 | //probeer de volgende koninging te plaatsten | line_comment | nl | package algoritmen;
import java.util.ArrayList;
public class KoninginnenProbleem {
public static void main(String[] args){
int n = 6;
System.out.println(nQueens(n));
}
//static anders niet oproepen zonder object te maken
public static ArrayList<Integer> nQueens(int n){
return queens(n,1,1,new ArrayList<Integer>());
}
private static ArrayList<Integer> queens(int aantalKoninginnen, int huidigeKolom, int huidigeRij,ArrayList<Integer> vorigeQ){
if (aantalKoninginnen < huidigeKolom){ //als de huidige queen die je wil plaatsen groter is dan aantal dat je moet zetten weet je dat de vorige list de oplossing was
return vorigeQ;
}
else if (isVeilig(huidigeRij, vorigeQ) && (huidigeRij<=aantalKoninginnen)){
//bewaar de huidige positie voor de huidige koningin
vorigeQ.add(huidigeRij);
//probeer de<SUF>
return queens(aantalKoninginnen,huidigeKolom+1,1,vorigeQ);
}
//nagaan of de huidigeKolom/koningin nog een volgende mogelijkheid/rij heeft
//alleen zinvol indien er nog plaats is
else if (huidigeRij<aantalKoninginnen){
return queens(aantalKoninginnen, huidigeKolom,huidigeRij+1, vorigeQ);
}
//backtracking
else {
//je kan niet verder backtracken => geen oplossing
if (huidigeKolom == 1) return new ArrayList<>();
else {
int vorigeKolom = huidigeKolom - 1;
int vorigeRij = vorigeQ.get(vorigeQ.size() - 1);
vorigeQ.remove(vorigeQ.size() - 1);
return queens(aantalKoninginnen, vorigeKolom, vorigeRij + 1, vorigeQ);
}
}
}
public static boolean isVeilig(int rij, ArrayList<Integer> vorige) {
for(int rij2 : vorige){
int verschil = vorige.size()-vorige.indexOf(rij2);
if (rij == rij2){
return false;
}
else if (rij2 == rij-verschil || rij2==rij+verschil) {
return false;
}
}
return true;
}
}
|
45760_41 | package l2f.gameserver.model.entity.achievements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.World;
/**
*
* @author Nik
*
*/
public class PlayerCounters
{
private static final Logger _log = LoggerFactory.getLogger(PlayerCounters.class);
public static PlayerCounters DUMMY_COUNTER = new PlayerCounters(null);
// Player
public int pvpKills = 0;
public int pkInARowKills = 0;
public int highestKarma = 0;
public int timesDied = 0;
public int playersRessurected = 0;
public int duelsWon = 0;
public int fameAcquired = 0;
public long expAcquired = 0;
public int recipesSucceeded = 0;
public int recipesFailed = 0;
public int manorSeedsSow = 0;
public int critsDone = 0;
public int mcritsDone = 0;
public int maxSoulCrystalLevel = 0;
public int fishCaught = 0;
public int treasureBoxesOpened = 0;
public int unrepeatableQuestsCompleted = 0;
public int repeatableQuestsCompleted = 0;
public long adenaDestroyed = 0;
public int recommendsMade = 0;
public int foundationItemsMade = 0;
public long distanceWalked = 0;
// Enchants
public int enchantNormalSucceeded = 0;
public int enchantBlessedSucceeded = 0;
public int highestEnchant = 0;
// Clan & Olympiad
public int olyHiScore = 0;
public int olyGamesWon = 0;
public int olyGamesLost = 0;
public int timesHero = 0;
public int timesMarried = 0;
public int castleSiegesWon = 0;
public int fortSiegesWon = 0;
public int dominionSiegesWon = 0;
// Epic Bosses.
public int antharasKilled = 0;
public int baiumKilled = 0;
public int valakasKilled = 0;
public int orfenKilled = 0;
public int antQueenKilled = 0;
public int coreKilled = 0;
public int belethKilled = 0;
public int sailrenKilled = 0;
public int baylorKilled = 0;
public int zakenKilled = 0;
public int tiatKilled = 0;
public int freyaKilled = 0;
public int frintezzaKilled = 0;
// Other kills
public int mobsKilled = 0;
public int raidsKilled = 0;
public int championsKilled = 0;
public int townGuardsKilled = 0;
public int siegeGuardsKilled = 0;
public int playersKilledInSiege = 0;
public int playersKilledInDominion = 0;
public int timesVoted = 0;
public int krateisCubePoints = 0;
public int krateisCubeTotalPoints = 0;
// Here comes the code...
private Player _activeChar = null;
private int _playerObjId = 0;
public PlayerCounters(Player activeChar)
{
_activeChar = activeChar;
_playerObjId = activeChar == null ? 0 : activeChar.getObjectId();
}
public PlayerCounters(int playerObjId)
{
_activeChar = World.getPlayer(playerObjId);
_playerObjId = playerObjId;
}
protected Player getChar()
{
return _activeChar;
}
public long getPoints(String fieldName)
{
if (_activeChar == null)
return 0;
try {return getClass().getField(fieldName).getLong(this);}
catch (Exception e) {e.printStackTrace();}
return 0;
}
// public void save()
// {
// if (_activeChar == null)
// return;
//
//
// // Because im SQL noob
// Connection con = null;
// Connection con2 = null;
// PreparedStatement statement2 = null;
// PreparedStatement statement3 = null;
// ResultSet rs = null;
// try
// {
// con2 = DatabaseFactory.getInstance().getConnection();
// statement2 = con2.prepareStatement("SELECT char_id FROM character_counters WHERE char_id = " + _playerObjId + ";");
// rs = statement2.executeQuery();
// if (!rs.next())
// {
// statement3 = con2.prepareStatement("INSERT INTO character_counters (char_id) values (?);");
// statement3.setInt(1, _playerObjId);
// statement3.execute();
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con2, statement2, rs);
// }
//
// PreparedStatement statement = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// StringBuilder sb = new StringBuilder();
// sb.append("UPDATE character_counters SET ");
// boolean firstPassed = false;
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we wont save.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// if (firstPassed)
// sb.append(",");
// sb.append(field.getName());
// sb.append("=");
//
// try
// {
// sb.append(field.getInt(this));
// }
// catch (IllegalArgumentException | IllegalAccessException | SecurityException e)
// {
// sb.append(field.getLong(this));
// }
//
// firstPassed = true;
// }
// sb.append(" WHERE char_id=" + _playerObjId + ";");
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement);
// }
// }
//
// public void load()
// {
// if (_activeChar == null)
// return;
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("SELECT * FROM character_counters WHERE char_id = ?");
// statement.setInt(1, getChar().getObjectId());
// rs = statement.executeQuery();
// while(rs.next())
// {
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// try
// {
// field.setInt(this, rs.getInt(field.getName()));
// }
// catch (SQLException sqle)
// {
// field.setLong(this, rs.getLong(field.getName()));
// }
// }
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// public static String generateTopHtml(String fieldName, int maxTop, boolean asc)
// {
// Map<Integer, Long> tops = loadCounter(fieldName, maxTop, asc);
// int order = 1;
//
// StringBuilder sb = new StringBuilder(tops.size() * 100);
// sb.append("<table width=300 border=0>");
// for (Entry<Integer, Long> top : tops.entrySet())
// {
// sb.append("<tr><td><table border=0 width=294 bgcolor=" + (order % 2 == 0 ? "1E1E1E" : "090909") + ">")
// .append("<tr><td fixwidth=10%><font color=LEVEL>").append(order++).append(".<font></td>")
// .append("<td fixwidth=45%>").append(CharacterDAO.getInstance().getNameByObjectId(top.getKey()))
// .append("</td><td fixwidth=45%><font color=777777>").append(top.getValue())
// .append("</font></td></tr>")
// .append("</table></td></tr>");
// }
// sb.append("</table>");
//
// return sb.toString();
// }
// public static Map<Integer, Long> loadCounter(String fieldName, int maxRetrieved, boolean asc)
// {
// Map<Integer, Long> ret = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try(Connection con = DatabaseFactory.getInstance().getConnection())
// {
// statement = con.prepareStatement("SELECT char_id, " + fieldName + " FROM character_counters ORDER BY " + fieldName + " " + (asc ? "ASC" : "DESC") + " LIMIT 0, " + maxRetrieved + ";");
// rs = statement.executeQuery();
// ret = new LinkedHashMap<Integer, Long>(rs.getFetchSize());
// while (rs.next())
// {
// int charObjId = rs.getInt(1);
// long value = rs.getLong(2);
// ret.put(charObjId, value);
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(null, statement, rs);
// }
//
// return ret == null ? Collections.emptyMap() : ret;
// }
//
// public static void checkTable()
// {
// // Generate used fields list.
// List<String> fieldNames = new ArrayList<String>();
// for (Field field : PlayerCounters.class.getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// default:
// fieldNames.add(field.getName());
// }
// }
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("DESC character_counters");
// rs = statement.executeQuery();
// while(rs.next())
// {
// //_log.info("Checking column: " + rs.getString(1));
// fieldNames.remove(rs.getString(1));
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
//
// if (!fieldNames.isEmpty())
// {
// StringBuilder sb = new StringBuilder(fieldNames.size() * 30);
//
// try
// {
// sb.append("ALTER TABLE character_counters");
// for (String str : fieldNames)
// {
// _log.info("PlayerCounters Update: Adding missing column name: " + str);
//
// Class<?> fieldType = PlayerCounters.class.getField(str).getType();
// if (fieldType == int.class || fieldType == Integer.class)
// sb.append(" ADD COLUMN " + str + " int(11) NOT NULL DEFAULT 0,");
// else if (fieldType == long.class || fieldType == Long.class)
// sb.append(" ADD COLUMN " + str + " bigint(20) NOT NULL DEFAULT 0,");
// else
// _log.warn("Unsupported data type: " + fieldType);
//
// }
// sb.setCharAt(sb.length() - 1, ';');
//
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// _log.info("PlayerCounters Update: Changes executed!");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// }
}
| Arodev76/L2Advanced | src/main/java/l2f/gameserver/model/entity/achievements/PlayerCounters.java | 3,636 | // int order = 1; | line_comment | nl | package l2f.gameserver.model.entity.achievements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.World;
/**
*
* @author Nik
*
*/
public class PlayerCounters
{
private static final Logger _log = LoggerFactory.getLogger(PlayerCounters.class);
public static PlayerCounters DUMMY_COUNTER = new PlayerCounters(null);
// Player
public int pvpKills = 0;
public int pkInARowKills = 0;
public int highestKarma = 0;
public int timesDied = 0;
public int playersRessurected = 0;
public int duelsWon = 0;
public int fameAcquired = 0;
public long expAcquired = 0;
public int recipesSucceeded = 0;
public int recipesFailed = 0;
public int manorSeedsSow = 0;
public int critsDone = 0;
public int mcritsDone = 0;
public int maxSoulCrystalLevel = 0;
public int fishCaught = 0;
public int treasureBoxesOpened = 0;
public int unrepeatableQuestsCompleted = 0;
public int repeatableQuestsCompleted = 0;
public long adenaDestroyed = 0;
public int recommendsMade = 0;
public int foundationItemsMade = 0;
public long distanceWalked = 0;
// Enchants
public int enchantNormalSucceeded = 0;
public int enchantBlessedSucceeded = 0;
public int highestEnchant = 0;
// Clan & Olympiad
public int olyHiScore = 0;
public int olyGamesWon = 0;
public int olyGamesLost = 0;
public int timesHero = 0;
public int timesMarried = 0;
public int castleSiegesWon = 0;
public int fortSiegesWon = 0;
public int dominionSiegesWon = 0;
// Epic Bosses.
public int antharasKilled = 0;
public int baiumKilled = 0;
public int valakasKilled = 0;
public int orfenKilled = 0;
public int antQueenKilled = 0;
public int coreKilled = 0;
public int belethKilled = 0;
public int sailrenKilled = 0;
public int baylorKilled = 0;
public int zakenKilled = 0;
public int tiatKilled = 0;
public int freyaKilled = 0;
public int frintezzaKilled = 0;
// Other kills
public int mobsKilled = 0;
public int raidsKilled = 0;
public int championsKilled = 0;
public int townGuardsKilled = 0;
public int siegeGuardsKilled = 0;
public int playersKilledInSiege = 0;
public int playersKilledInDominion = 0;
public int timesVoted = 0;
public int krateisCubePoints = 0;
public int krateisCubeTotalPoints = 0;
// Here comes the code...
private Player _activeChar = null;
private int _playerObjId = 0;
public PlayerCounters(Player activeChar)
{
_activeChar = activeChar;
_playerObjId = activeChar == null ? 0 : activeChar.getObjectId();
}
public PlayerCounters(int playerObjId)
{
_activeChar = World.getPlayer(playerObjId);
_playerObjId = playerObjId;
}
protected Player getChar()
{
return _activeChar;
}
public long getPoints(String fieldName)
{
if (_activeChar == null)
return 0;
try {return getClass().getField(fieldName).getLong(this);}
catch (Exception e) {e.printStackTrace();}
return 0;
}
// public void save()
// {
// if (_activeChar == null)
// return;
//
//
// // Because im SQL noob
// Connection con = null;
// Connection con2 = null;
// PreparedStatement statement2 = null;
// PreparedStatement statement3 = null;
// ResultSet rs = null;
// try
// {
// con2 = DatabaseFactory.getInstance().getConnection();
// statement2 = con2.prepareStatement("SELECT char_id FROM character_counters WHERE char_id = " + _playerObjId + ";");
// rs = statement2.executeQuery();
// if (!rs.next())
// {
// statement3 = con2.prepareStatement("INSERT INTO character_counters (char_id) values (?);");
// statement3.setInt(1, _playerObjId);
// statement3.execute();
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con2, statement2, rs);
// }
//
// PreparedStatement statement = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// StringBuilder sb = new StringBuilder();
// sb.append("UPDATE character_counters SET ");
// boolean firstPassed = false;
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we wont save.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// if (firstPassed)
// sb.append(",");
// sb.append(field.getName());
// sb.append("=");
//
// try
// {
// sb.append(field.getInt(this));
// }
// catch (IllegalArgumentException | IllegalAccessException | SecurityException e)
// {
// sb.append(field.getLong(this));
// }
//
// firstPassed = true;
// }
// sb.append(" WHERE char_id=" + _playerObjId + ";");
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement);
// }
// }
//
// public void load()
// {
// if (_activeChar == null)
// return;
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("SELECT * FROM character_counters WHERE char_id = ?");
// statement.setInt(1, getChar().getObjectId());
// rs = statement.executeQuery();
// while(rs.next())
// {
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// try
// {
// field.setInt(this, rs.getInt(field.getName()));
// }
// catch (SQLException sqle)
// {
// field.setLong(this, rs.getLong(field.getName()));
// }
// }
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// public static String generateTopHtml(String fieldName, int maxTop, boolean asc)
// {
// Map<Integer, Long> tops = loadCounter(fieldName, maxTop, asc);
// int order<SUF>
//
// StringBuilder sb = new StringBuilder(tops.size() * 100);
// sb.append("<table width=300 border=0>");
// for (Entry<Integer, Long> top : tops.entrySet())
// {
// sb.append("<tr><td><table border=0 width=294 bgcolor=" + (order % 2 == 0 ? "1E1E1E" : "090909") + ">")
// .append("<tr><td fixwidth=10%><font color=LEVEL>").append(order++).append(".<font></td>")
// .append("<td fixwidth=45%>").append(CharacterDAO.getInstance().getNameByObjectId(top.getKey()))
// .append("</td><td fixwidth=45%><font color=777777>").append(top.getValue())
// .append("</font></td></tr>")
// .append("</table></td></tr>");
// }
// sb.append("</table>");
//
// return sb.toString();
// }
// public static Map<Integer, Long> loadCounter(String fieldName, int maxRetrieved, boolean asc)
// {
// Map<Integer, Long> ret = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try(Connection con = DatabaseFactory.getInstance().getConnection())
// {
// statement = con.prepareStatement("SELECT char_id, " + fieldName + " FROM character_counters ORDER BY " + fieldName + " " + (asc ? "ASC" : "DESC") + " LIMIT 0, " + maxRetrieved + ";");
// rs = statement.executeQuery();
// ret = new LinkedHashMap<Integer, Long>(rs.getFetchSize());
// while (rs.next())
// {
// int charObjId = rs.getInt(1);
// long value = rs.getLong(2);
// ret.put(charObjId, value);
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(null, statement, rs);
// }
//
// return ret == null ? Collections.emptyMap() : ret;
// }
//
// public static void checkTable()
// {
// // Generate used fields list.
// List<String> fieldNames = new ArrayList<String>();
// for (Field field : PlayerCounters.class.getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// default:
// fieldNames.add(field.getName());
// }
// }
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("DESC character_counters");
// rs = statement.executeQuery();
// while(rs.next())
// {
// //_log.info("Checking column: " + rs.getString(1));
// fieldNames.remove(rs.getString(1));
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
//
// if (!fieldNames.isEmpty())
// {
// StringBuilder sb = new StringBuilder(fieldNames.size() * 30);
//
// try
// {
// sb.append("ALTER TABLE character_counters");
// for (String str : fieldNames)
// {
// _log.info("PlayerCounters Update: Adding missing column name: " + str);
//
// Class<?> fieldType = PlayerCounters.class.getField(str).getType();
// if (fieldType == int.class || fieldType == Integer.class)
// sb.append(" ADD COLUMN " + str + " int(11) NOT NULL DEFAULT 0,");
// else if (fieldType == long.class || fieldType == Long.class)
// sb.append(" ADD COLUMN " + str + " bigint(20) NOT NULL DEFAULT 0,");
// else
// _log.warn("Unsupported data type: " + fieldType);
//
// }
// sb.setCharAt(sb.length() - 1, ';');
//
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// _log.info("PlayerCounters Update: Changes executed!");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// }
}
|
134424_0 | package be.ehb.mesdoigtsdefeesapp.views.fragments;
import androidx.appcompat.widget.SearchView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import be.ehb.mesdoigtsdefeesapp.R;
import be.ehb.mesdoigtsdefeesapp.models.Post;
import be.ehb.mesdoigtsdefeesapp.views.adapters.PostAdapter;
import be.ehb.mesdoigtsdefeesapp.views.viewmodels.PostViewModel;
public class PostFragment extends Fragment {
private List<Post> postList;
private PostAdapter adapter;
public PostFragment() {
}
public static PostFragment newInstance() {
return new PostFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_post, container, false);
// Om de keyboard te laten verdwijnen als je op de searchView klikt
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
RecyclerView rvPosts = view.findViewById(R.id.rv_posts);
SearchView searchView = view.findViewById(R.id.searchView);
searchView.setOnFocusChangeListener((v, hasFocus) -> {
// Om de searchView te verplaatsen wanneer de keyboard verschijnt
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) rvPosts.getLayoutParams();
layoutParams.topMargin = hasFocus ? 60 : 24;
rvPosts.setLayoutParams(layoutParams);
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
postList = new ArrayList<>();
RecyclerView rvPosts = view.findViewById(R.id.rv_posts);
adapter = new PostAdapter(getContext());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
rvPosts.setAdapter(adapter);
rvPosts.setLayoutManager(layoutManager);
PostViewModel viewModel = new ViewModelProvider(getActivity()).get(PostViewModel.class);
viewModel.getAllPosts().observe(getViewLifecycleOwner(), items -> {
postList.clear();
postList.addAll(items);
adapter.addItems(items);
adapter.notifyDataSetChanged();
});
FloatingActionButton fab = view.findViewById(R.id.btn_new_post);
fab.setOnClickListener(v -> {
Navigation.findNavController(view).navigate(R.id.action_postFragment_to_newPostFragment);
});
SearchView sv = view.findViewById(R.id.searchView);
sv.clearFocus();
// Om de searchView te laten werken (filteren)
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
filterList(newText);
return true;
}
});
}
// Om de lijst te filteren
private void filterList(String text) {
ArrayList<Post> filteredList = new ArrayList<>();
for (Post item : postList) {
if (item.getTitle().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
if (filteredList.isEmpty()) {
Toast.makeText(getContext(), "No posts found", Toast.LENGTH_SHORT).show();
} else {
adapter.setFilterList(filteredList);
}
}
}
| AronMwan/MesDoigtsDeFeesApp | app/src/main/java/be/ehb/mesdoigtsdefeesapp/views/fragments/PostFragment.java | 1,223 | // Om de keyboard te laten verdwijnen als je op de searchView klikt | line_comment | nl | package be.ehb.mesdoigtsdefeesapp.views.fragments;
import androidx.appcompat.widget.SearchView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import be.ehb.mesdoigtsdefeesapp.R;
import be.ehb.mesdoigtsdefeesapp.models.Post;
import be.ehb.mesdoigtsdefeesapp.views.adapters.PostAdapter;
import be.ehb.mesdoigtsdefeesapp.views.viewmodels.PostViewModel;
public class PostFragment extends Fragment {
private List<Post> postList;
private PostAdapter adapter;
public PostFragment() {
}
public static PostFragment newInstance() {
return new PostFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_post, container, false);
// Om de<SUF>
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
RecyclerView rvPosts = view.findViewById(R.id.rv_posts);
SearchView searchView = view.findViewById(R.id.searchView);
searchView.setOnFocusChangeListener((v, hasFocus) -> {
// Om de searchView te verplaatsen wanneer de keyboard verschijnt
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) rvPosts.getLayoutParams();
layoutParams.topMargin = hasFocus ? 60 : 24;
rvPosts.setLayoutParams(layoutParams);
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
postList = new ArrayList<>();
RecyclerView rvPosts = view.findViewById(R.id.rv_posts);
adapter = new PostAdapter(getContext());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
rvPosts.setAdapter(adapter);
rvPosts.setLayoutManager(layoutManager);
PostViewModel viewModel = new ViewModelProvider(getActivity()).get(PostViewModel.class);
viewModel.getAllPosts().observe(getViewLifecycleOwner(), items -> {
postList.clear();
postList.addAll(items);
adapter.addItems(items);
adapter.notifyDataSetChanged();
});
FloatingActionButton fab = view.findViewById(R.id.btn_new_post);
fab.setOnClickListener(v -> {
Navigation.findNavController(view).navigate(R.id.action_postFragment_to_newPostFragment);
});
SearchView sv = view.findViewById(R.id.searchView);
sv.clearFocus();
// Om de searchView te laten werken (filteren)
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
filterList(newText);
return true;
}
});
}
// Om de lijst te filteren
private void filterList(String text) {
ArrayList<Post> filteredList = new ArrayList<>();
for (Post item : postList) {
if (item.getTitle().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
if (filteredList.isEmpty()) {
Toast.makeText(getContext(), "No posts found", Toast.LENGTH_SHORT).show();
} else {
adapter.setFilterList(filteredList);
}
}
}
|
134148_45 | package nl.dani;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.dani.chllg1.Elf;
import nl.dani.chllg1.InputReader;
import nl.dani.chllg5.CrateStack;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
InputReader reader = new InputReader();
// System.out.println(reader.readFile("input1.txt"));
ArrayList<Elf> content = reader.readCalories("input1.txt");
System.out.println("content is " + content.size() + " of elves\n");
int Maxcal = 0;
for (int i = 0; i < content.size(); i++) {
// System.out.println(content.get(i).getAllCalories());
if (content.get(i).getAllCalories() > Maxcal) {
Maxcal = content.get(i).getAllCalories();
}
}
System.out.println("day 1: challenge 1: " + Maxcal);
int[] topThree = { 0, 0, 0 };
for (int i = 0; i < content.size(); i++) {
int smallest = 0;
for (int n = 0; n < 3; n++) {
if (topThree[smallest] > topThree[n]) {
smallest = n;
}
}
if (content.get(i).getAllCalories() > topThree[smallest]) {
topThree[smallest] = content.get(i).getAllCalories();
}
}
System.out.println("day 1: challenge 2: " + (topThree[0] + topThree[1] + topThree[2]));
ArrayList<String> games = reader.readGames("input2.txt");
HashMap<String, Integer> lookup = new HashMap();
lookup.put("A X", 4);
lookup.put("A Y", 8);
lookup.put("A Z", 3);
lookup.put("B X", 1);
lookup.put("B Y", 5);
lookup.put("B Z", 9);
lookup.put("C X", 7);
lookup.put("C Y", 2);
lookup.put("C Z", 6);
// System.out.println(games.size());
int score = 0;
for (int i = 0; i < games.size(); i++) {
score += lookup.get(games.get(i));
}
System.out.println("day 2: challenge 1: " + score);
HashMap<String, Integer> lookupd = new HashMap();
lookupd.clear();
lookupd.put("A X", 3);
lookupd.put("A Y", 4);
lookupd.put("A Z", 8);
lookupd.put("B X", 1);
lookupd.put("B Y", 5);
lookupd.put("B Z", 9);
lookupd.put("C X", 2);
lookupd.put("C Y", 6);
lookupd.put("C Z", 7);
score = 0;
for (int i = 0; i < games.size(); i++) {
score += lookupd.get(games.get(i));
}
System.out.println("day 2: challenge 2: " + score);
ArrayList<String> rucksacks = reader.readGames("input3.txt");
// System.out.println(((int) 'z') - 96); //char - 96 l of -64 u
int total = 0;
for (int i = 0; i < rucksacks.size(); i++) {
int length = rucksacks.get(i).length();
char[] left = rucksacks.get(i).substring(0, length / 2).toCharArray();
char[] right = rucksacks.get(i).substring(length / 2).toCharArray();
Arrays.sort(left);
Arrays.sort(right);
boolean found = false;
for (int n = 0; n < left.length; n++) {
for (int t = 0; t < right.length; t++) {
if (left[n] == right[t] && !found) {
found = true;
if (((int) left[n]) >= 97) {
total += (int) left[n] - 96;
} else {
total += (int) left[n] - 38;
}
// break;
}
}
}
}
System.out.println("day 3; challenge 1: " + total);
total = 0;
// boolean found = false;
for (int i = 0; i < rucksacks.size(); i += 3) {
boolean found = false;
for (int n = 0; n < rucksacks.get(i).length(); n++) {
for (int t = 0; t < rucksacks.get(i + 1).length(); t++) {
for (int e = 0; e < rucksacks.get(i + 2).length(); e++) {
if ((rucksacks.get(i).charAt(n) == rucksacks.get(i + 1).charAt(t))
&& (rucksacks.get(i).charAt(n) == rucksacks.get(i + 2).charAt(e) && !found)) {
found = true;
if (((int) rucksacks.get(i).charAt(n)) >= 97) {
total += (int) rucksacks.get(i).charAt(n) - 96;
} else {
total += (int) rucksacks.get(i).charAt(n) - 38;
}
}
}
}
}
}
System.out.println("day3: challenge 2: " + total);
ArrayList<String> ranges = reader.readGames("input4.txt");
// System.out.println(ranges.size());
int encapsulatingRanges = 0;
int overlappingPairs = 0;
for (int i = 0; i < ranges.size(); i++) {
// System.out.println(ranges.get(i));
String[] range = { ranges.get(i).substring(0, ranges.get(i).indexOf(',')),
ranges.get(i).substring(ranges.get(i).indexOf(',') + 1) };
int[] leftRange = { Integer.valueOf(range[0].substring(0, range[0].indexOf('-'))),
Integer.valueOf(range[0].substring(range[0].indexOf('-') + 1)) };
int[] rightRange = { Integer.valueOf(range[1].substring(0, range[1].indexOf('-'))),
Integer.valueOf(range[1].substring(range[1].indexOf('-') + 1)) };
// System.out.println(range[0] + " " + range[1]);
if ((leftRange[0] <= rightRange[0] && leftRange[1] >= rightRange[1])
|| (leftRange[0] >= rightRange[0] && leftRange[1] <= rightRange[1])) {
// System.out.println(Integer.valueOf(range[0].substring(0,
// range[0].indexOf('-'))));
// System.out.println("encapsulates");
encapsulatingRanges++;
}
if ((leftRange[0] <= rightRange[0] && leftRange[1] >= rightRange[0])
|| (rightRange[0] <= leftRange[0] && rightRange[1] >= leftRange[0])) {
overlappingPairs++;
}
// if (Integer.valueOf(range[0].))
}
System.out.println("day4: challenge 1: " + encapsulatingRanges);
System.out.println("day4: challenge 2: " + overlappingPairs);
// [C] [Q] [V]
// [D] [D] [S] [M] [Z]
// [G] [P] [W] [M] [C] [G]
// [F] [Z] [C] [D] [P] [S] [W]
// [P] [L] [C] [V] [W] [W] [H] [L]
// [G] [B] [V] [R] [L] [N] [G] [P] [F]
// [R] [T] [S] [S] [S] [T] [D] [L] [P]
// [N] [J] [M] [L] [P] [C] [H] [Z] [R]
// 1 2 3 4 5 6 7 8 9
CrateStack crateStack = new CrateStack(9);
CrateStack crateStackClone = new CrateStack(9);
char[] crates = { 'N', 'R', 'G', 'P' };
crateStack.addStack(0, crates);
crateStackClone.addStack(0, crates);
char[] crates1 = { 'J', 'T', 'B', 'L', 'F', 'G', 'D', 'C' };
crateStack.addStack(1, crates1);
crateStackClone.addStack(1, crates1);
char[] crates2 = { 'M', 'S', 'V' };
crateStack.addStack(2, crates2);
crateStackClone.addStack(2, crates2);
char[] crates3 = { 'L', 'S', 'R', 'C', 'Z', 'P' };
crateStack.addStack(3, crates3);
crateStackClone.addStack(3, crates3);
char[] crates4 = { 'P', 'S', 'L', 'V', 'C', 'W', 'D', 'Q' };
crateStack.addStack(4, crates4);
crateStackClone.addStack(4, crates4);
char[] crates5 = { 'C', 'T', 'N', 'W', 'D', 'M', 'S' };
crateStack.addStack(5, crates5);
crateStackClone.addStack(5, crates5);
char[] crates6 = { 'H', 'D', 'G', 'W', 'P' };
crateStack.addStack(6, crates6);
crateStackClone.addStack(6, crates6);
char[] crates7 = { 'Z', 'L', 'P', 'H', 'S', 'C', 'M', 'V' };
crateStack.addStack(7, crates7);
crateStackClone.addStack(7, crates7);
char[] crates8 = { 'R', 'P', 'F', 'L', 'W', 'G', 'Z' };
crateStack.addStack(8, crates8);
crateStackClone.addStack(8, crates8);
ArrayList<String> moves = reader.readGames("input5.txt");
for (int i = 0; i < moves.size(); i++) {
// System.out.println(moves.get(i));
int currentIndex;
int numMoves = Integer.valueOf(moves.get(i).substring(5, moves.get(i).indexOf('f') - 1));
currentIndex = moves.get(i).indexOf('f') + 1;
int start = Integer.valueOf(
moves.get(i).substring(moves.get(i).indexOf(' ', currentIndex) + 1, moves.get(i).indexOf('t') - 1));
currentIndex = moves.get(i).indexOf('t') + 1;
int destination = Integer.valueOf(moves.get(i).substring(moves.get(i).indexOf(' ', currentIndex) + 1));
// System.out.println(numMoves + " " + start + " " + destination);
for (int n = 0; n < numMoves; n++) {
crateStack.moveCrate(start - 1, destination - 1);
}
crateStackClone.moveCrates(start - 1, destination - 1, numMoves);
// System.out.println(moves.get(i).indexOf('e'));
// int moveN =
// Integer.valueOf(moves.get(i).substring(moves.get(i).indexOf('e')))
}
System.out.println("day5: challenge 1: " + crateStack.getTopCrates());
System.out.println("day5: challenge 2: " + crateStackClone.getTopCrates());
String datastream = reader.readGames("input6.txt").get(0);
// String pattern = "(?:([a-z])(?!.*\1)){4}";
// Pattern pattern = Pattern.compile("(?:([a-z])(?!.*\1)){4}");
boolean pkg = false;
for (int i = 0; i < datastream.length(); i++) {
// Matcher match = pattern.matcher(datastream.substring(i, i + 4));
// if (match.find()){
// System.out.println("day6: challenge 1: " + (i + 4));
// i = datastream.length();
// }
String substr = datastream.substring(i, i + 4);
int uniquechars = 0;
for (int n = 3; n >= 0; n--) {
if (substr.indexOf(substr.charAt(n)) == n) {
uniquechars++;
}
}
if (uniquechars == 4 && !pkg) {
System.out.println("day6: challenge 1: " + (i + 4));
// i = datastream.length() + 4;
pkg = true;
}
String sbstr = datastream.substring(i, i + 14);
uniquechars = 0;
for (int n = 13; n >= 0; n--) {
if (sbstr.indexOf(sbstr.charAt(n)) == n) {
uniquechars++;
}
}
if (uniquechars == 14) {
System.out.println("day6: challenge 1: " + (i + 14));
i = datastream.length() + 4;
}
}
// System.out.println(datastream);`
ArrayList<String> terminal = reader.readGames("input7.txt");
// EFSNode root = new EFSNode();
ArrayList<String> scope = new ArrayList();
scope.add("/");
Map<String, Integer> folderSize = new HashMap<>();
folderSize.put("/", 0);
// folderSize.put("kut", 20);
// System.out.println(folderSize);
for (int i = 1; i < terminal.size(); i++) {
// System.out.println(terminal.get(i));
if (terminal.get(i).startsWith("$")) {
if (terminal.get(i).startsWith("$ cd")) {
if (terminal.get(i).substring(5).equals("..")) {
scope.remove(scope.size() - 1);
} else {
// String name = "";
scope.add(scope.get(scope.size() - 1) + terminal.get(i).substring(5) + "/");
String folder = scope.get(scope.size() - 1);
// System.out.println(folder);
folderSize.put(folder, 0);
// System.out.println(folderSize);
}
}
} else {
if (!terminal.get(i).startsWith("dir")) {
// System.out.println(folderSize);
for (int n = 0; n < scope.size(); n++) {
folderSize.replace(scope.get(n), folderSize.get(scope.get(n))
+ Integer.valueOf(terminal.get(i).substring(0, terminal.get(i).indexOf(" "))));
}
}
}
}
int totalSize = 0;
int deletedDit = 700000000;
int spaceNeeeded = 30000000 - (70000000 - folderSize.get("/"));
for (Integer size : folderSize.values()) {
// System.out.println(folderSize);
if (size < 100000) {
totalSize += size;
}
if (size < deletedDit && size >= spaceNeeeded) {
deletedDit = size;
}
}
// System.out.println(folderSize.get("/") + " " + deletedDit);
System.out.println("day7: challenge 1: " + totalSize);
System.out.println("day7: challenge 2: " + deletedDit);
ArrayList<String> rows = reader.readGames("input8.txt");
int[][] treeGrid = new int[rows.size()][rows.get(0).length()];
int columns = rows.get(0).length();
int row = rows.size();
// System.out.println(row);
for (int i = 0; i < row; i++) {
for (int n = 0; n < columns; n++) {
treeGrid[i][n] = Integer.valueOf(rows.get(i).substring(n, n + 1));
// System.out.print(treeGrid[i][n] + " ");
}
}
int visibleTrees = 0;
int scenicScore = 0;
for (int i = 0; i < row; i++) {
// System.out.println(" ");
for (int n = 0; n < columns; n++) {
// boolean visible = false;
boolean ttl = false;
boolean ttr = false;
boolean ttu = false;
boolean ttb = false;
int distanceL = 0;
int distanceR = 0;
int distanceU = 0;
int distanceB = 0;
// System.out.print(treeGrid[i][n] + " -> ");
for (int t = i - 1; t >= 0; t--) {
// System.out.print(treeGrid[t][n] + " | ");
if (treeGrid[i][n] > treeGrid[t][n]) {
distanceU++;
} else {
// System.out.println(n +" "+ i + " " + treeGrid[i][n] + " " + treeGrid[t][n] +
// " left");
t = 0;
distanceU++;
}
}
// System.out.print("distance = " + distanceU);
for (int t = i + 1; t < row; t++) {
// System.out.print(treeGrid[t][n] + " | ");
if (treeGrid[i][n] > treeGrid[t][n]) {
distanceB++;
} else {
t = row;
distanceB++;
}
}
// System.out.print("distance = " + distanceB + "\n");
for (int t = n - 1; t >= 0; t--) {
// System.out.print(treeGrid[i][n] + " | ");
if (treeGrid[i][n] > treeGrid[i][t]) {
distanceL++;
} else {
t = 0;
distanceL++;
}
}
// System.out.print("distance = " + distanceL + "\n");
for (int t = n + 1; t < columns; t++) {
// System.out.print(treeGrid[i][n] + " | ");
if (treeGrid[i][n] > treeGrid[i][t]) {
distanceR++;
} else {
t = columns;
distanceR++;
}
}
// System.out.print("distance = " + distanceR + "\n");
// System.out.println(treeGrid[i][n] + " -> " + (distanceU + " " + distanceB + "
// " + distanceL + " " + distanceR) + " | " + (distanceU * distanceB * distanceL
// * distanceR));
if ((distanceU * distanceB * distanceL * distanceR) > scenicScore) {
// System.out.println(scenicScore);
scenicScore = (distanceU * distanceB * distanceL * distanceR);
}
for (int t = 0; t < row; t++) {
// System.out.print(t);
if (treeGrid[i][n] <= treeGrid[t][n]) {
// System.out.print(t + " = " + treeGrid[i][n] + " " + treeGrid[t][n] + " | ");
if (t < i) {
ttu = true;
} else if (t > i) {
ttb = true;
}
}
}
// System.out.println(" ");
for (int t = 0; t < columns; t++) {
if (treeGrid[i][n] <= treeGrid[i][t]) {
// System.out.print(t + " = " + treeGrid[i][n] + " " + treeGrid[t][n] + " | ");
if (t < n) {
ttl = true;
} else if (t > n) {
ttr = true;
// System.out.print(treeGrid[i][n] + " " + i + " " + n + " " + t + " rechts |
// ");
}
}
}
if (!ttu || !ttb || !ttl || !ttr) {
visibleTrees++;
// System.out.print(treeGrid[i][n] + " " + i + " " + n);
} else if (ttr) {
// System.out.print(treeGrid[i][n] + " " + i + " " + n);
}
}
}
// System.out.println(visibleTrees);
// visibleTrees += (row + columns) + 1;
System.out.println("day8: challenge 1: " + visibleTrees);
System.out.println("day8: challenge 2: " + scenicScore);
ArrayList<String> ropeMoves = reader.readGames("input9.txt");
int[][] knots = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 } };
ArrayList<String> pos2 = new ArrayList<>();
pos2.add("0 0");
ArrayList<String> pos10 = new ArrayList<>();
pos10.add("0 0");
for (int i = 0; i < ropeMoves.size(); i++) {
String direction = ropeMoves.get(i).substring(0, 2);
int steps = Integer.valueOf(ropeMoves.get(i).substring(2));
for (int n = 0; n < steps; n++) {
switch (direction) {
case "R ":
knots[0][0]++;
break;
case "L ":
knots[0][0]--;
break;
case "U ":
knots[0][1]++;
break;
case "D ":
knots[0][1]--;
break;
default:
break;
}
for (int j = 1; j < knots.length; j++) {
// System.out.println("controle " + n + " | " + j);
if (knots[j - 1][0] - knots[j][0] == 2 && knots[j - 1][1] - knots[j][1] == 2) {
knots[j][0] = knots[j - 1][0] - 1;
knots[j][1] = knots[j - 1][1] - 1;
} else if (knots[j - 1][0] - knots[j][0] == 2 && knots[j - 1][1] - knots[j][1] == -2) {
knots[j][0] = knots[j - 1][0] - 1;
knots[j][1] = knots[j - 1][1] + 1;
} else if (knots[j - 1][0] - knots[j][0] == -2 && knots[j - 1][1] - knots[j][1] == 2) {
knots[j][0] = knots[j - 1][0] + 1;
knots[j][1] = knots[j - 1][1] - 1;
} else if (knots[j - 1][0] - knots[j][0] == -2 && knots[j - 1][1] - knots[j][1] == -2) {
knots[j][0] = knots[j - 1][0] + 1;
knots[j][1] = knots[j - 1][1] + 1;
} else if (knots[j - 1][0] - knots[j][0] == 2) {
// System.out.println("beweging naar rechts " + j);
knots[j][0] = knots[j - 1][0] - 1;
knots[j][1] = knots[j - 1][1];
} else if (knots[j][0] - knots[j - 1][0] == 2) {
knots[j][0] = knots[j - 1][0] + 1;
knots[j][1] = knots[j - 1][1];
} else if (knots[j - 1][1] - knots[j][1] == 2) {
knots[j][0] = knots[j - 1][0];
knots[j][1] = knots[j - 1][1] - 1;
} else if (knots[j][1] - knots[j - 1][1] == 2) {
knots[j][0] = knots[j - 1][0];
knots[j][1] = knots[j - 1][1] + 1;
}
}
String pos = knots[1][0] + " " + knots[1][1];
boolean newPos = false;
for (int j = 0; j < pos2.size(); j++) {
if (pos2.get(j).equals(pos)) {
newPos = true;
}
}
if (!newPos) {
pos2.add(pos);
}
pos = knots[9][0] + " " + knots[9][1];
newPos = false;
for (int j = 0; j < pos10.size(); j++) {
if (pos10.get(j).equals(pos)) {
newPos = true;
}
}
if (!newPos) {
pos10.add(pos);
}
}
}
System.out.println("day9: challenge 1: " + pos2.size());
System.out.println("day9: challenge 2: " + pos10.size());
// lets gooo
// System.out.println("day10: challenge 1: " + pos2.size());
// System.out.println("day10: challenge 2: " + pos10.size());
}
} | ArraysZero/AdventOfCode | aoc2022/src/main/java/nl/dani/App.java | 7,448 | // System.out.println("beweging naar rechts " + j); | line_comment | nl | package nl.dani;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.dani.chllg1.Elf;
import nl.dani.chllg1.InputReader;
import nl.dani.chllg5.CrateStack;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
InputReader reader = new InputReader();
// System.out.println(reader.readFile("input1.txt"));
ArrayList<Elf> content = reader.readCalories("input1.txt");
System.out.println("content is " + content.size() + " of elves\n");
int Maxcal = 0;
for (int i = 0; i < content.size(); i++) {
// System.out.println(content.get(i).getAllCalories());
if (content.get(i).getAllCalories() > Maxcal) {
Maxcal = content.get(i).getAllCalories();
}
}
System.out.println("day 1: challenge 1: " + Maxcal);
int[] topThree = { 0, 0, 0 };
for (int i = 0; i < content.size(); i++) {
int smallest = 0;
for (int n = 0; n < 3; n++) {
if (topThree[smallest] > topThree[n]) {
smallest = n;
}
}
if (content.get(i).getAllCalories() > topThree[smallest]) {
topThree[smallest] = content.get(i).getAllCalories();
}
}
System.out.println("day 1: challenge 2: " + (topThree[0] + topThree[1] + topThree[2]));
ArrayList<String> games = reader.readGames("input2.txt");
HashMap<String, Integer> lookup = new HashMap();
lookup.put("A X", 4);
lookup.put("A Y", 8);
lookup.put("A Z", 3);
lookup.put("B X", 1);
lookup.put("B Y", 5);
lookup.put("B Z", 9);
lookup.put("C X", 7);
lookup.put("C Y", 2);
lookup.put("C Z", 6);
// System.out.println(games.size());
int score = 0;
for (int i = 0; i < games.size(); i++) {
score += lookup.get(games.get(i));
}
System.out.println("day 2: challenge 1: " + score);
HashMap<String, Integer> lookupd = new HashMap();
lookupd.clear();
lookupd.put("A X", 3);
lookupd.put("A Y", 4);
lookupd.put("A Z", 8);
lookupd.put("B X", 1);
lookupd.put("B Y", 5);
lookupd.put("B Z", 9);
lookupd.put("C X", 2);
lookupd.put("C Y", 6);
lookupd.put("C Z", 7);
score = 0;
for (int i = 0; i < games.size(); i++) {
score += lookupd.get(games.get(i));
}
System.out.println("day 2: challenge 2: " + score);
ArrayList<String> rucksacks = reader.readGames("input3.txt");
// System.out.println(((int) 'z') - 96); //char - 96 l of -64 u
int total = 0;
for (int i = 0; i < rucksacks.size(); i++) {
int length = rucksacks.get(i).length();
char[] left = rucksacks.get(i).substring(0, length / 2).toCharArray();
char[] right = rucksacks.get(i).substring(length / 2).toCharArray();
Arrays.sort(left);
Arrays.sort(right);
boolean found = false;
for (int n = 0; n < left.length; n++) {
for (int t = 0; t < right.length; t++) {
if (left[n] == right[t] && !found) {
found = true;
if (((int) left[n]) >= 97) {
total += (int) left[n] - 96;
} else {
total += (int) left[n] - 38;
}
// break;
}
}
}
}
System.out.println("day 3; challenge 1: " + total);
total = 0;
// boolean found = false;
for (int i = 0; i < rucksacks.size(); i += 3) {
boolean found = false;
for (int n = 0; n < rucksacks.get(i).length(); n++) {
for (int t = 0; t < rucksacks.get(i + 1).length(); t++) {
for (int e = 0; e < rucksacks.get(i + 2).length(); e++) {
if ((rucksacks.get(i).charAt(n) == rucksacks.get(i + 1).charAt(t))
&& (rucksacks.get(i).charAt(n) == rucksacks.get(i + 2).charAt(e) && !found)) {
found = true;
if (((int) rucksacks.get(i).charAt(n)) >= 97) {
total += (int) rucksacks.get(i).charAt(n) - 96;
} else {
total += (int) rucksacks.get(i).charAt(n) - 38;
}
}
}
}
}
}
System.out.println("day3: challenge 2: " + total);
ArrayList<String> ranges = reader.readGames("input4.txt");
// System.out.println(ranges.size());
int encapsulatingRanges = 0;
int overlappingPairs = 0;
for (int i = 0; i < ranges.size(); i++) {
// System.out.println(ranges.get(i));
String[] range = { ranges.get(i).substring(0, ranges.get(i).indexOf(',')),
ranges.get(i).substring(ranges.get(i).indexOf(',') + 1) };
int[] leftRange = { Integer.valueOf(range[0].substring(0, range[0].indexOf('-'))),
Integer.valueOf(range[0].substring(range[0].indexOf('-') + 1)) };
int[] rightRange = { Integer.valueOf(range[1].substring(0, range[1].indexOf('-'))),
Integer.valueOf(range[1].substring(range[1].indexOf('-') + 1)) };
// System.out.println(range[0] + " " + range[1]);
if ((leftRange[0] <= rightRange[0] && leftRange[1] >= rightRange[1])
|| (leftRange[0] >= rightRange[0] && leftRange[1] <= rightRange[1])) {
// System.out.println(Integer.valueOf(range[0].substring(0,
// range[0].indexOf('-'))));
// System.out.println("encapsulates");
encapsulatingRanges++;
}
if ((leftRange[0] <= rightRange[0] && leftRange[1] >= rightRange[0])
|| (rightRange[0] <= leftRange[0] && rightRange[1] >= leftRange[0])) {
overlappingPairs++;
}
// if (Integer.valueOf(range[0].))
}
System.out.println("day4: challenge 1: " + encapsulatingRanges);
System.out.println("day4: challenge 2: " + overlappingPairs);
// [C] [Q] [V]
// [D] [D] [S] [M] [Z]
// [G] [P] [W] [M] [C] [G]
// [F] [Z] [C] [D] [P] [S] [W]
// [P] [L] [C] [V] [W] [W] [H] [L]
// [G] [B] [V] [R] [L] [N] [G] [P] [F]
// [R] [T] [S] [S] [S] [T] [D] [L] [P]
// [N] [J] [M] [L] [P] [C] [H] [Z] [R]
// 1 2 3 4 5 6 7 8 9
CrateStack crateStack = new CrateStack(9);
CrateStack crateStackClone = new CrateStack(9);
char[] crates = { 'N', 'R', 'G', 'P' };
crateStack.addStack(0, crates);
crateStackClone.addStack(0, crates);
char[] crates1 = { 'J', 'T', 'B', 'L', 'F', 'G', 'D', 'C' };
crateStack.addStack(1, crates1);
crateStackClone.addStack(1, crates1);
char[] crates2 = { 'M', 'S', 'V' };
crateStack.addStack(2, crates2);
crateStackClone.addStack(2, crates2);
char[] crates3 = { 'L', 'S', 'R', 'C', 'Z', 'P' };
crateStack.addStack(3, crates3);
crateStackClone.addStack(3, crates3);
char[] crates4 = { 'P', 'S', 'L', 'V', 'C', 'W', 'D', 'Q' };
crateStack.addStack(4, crates4);
crateStackClone.addStack(4, crates4);
char[] crates5 = { 'C', 'T', 'N', 'W', 'D', 'M', 'S' };
crateStack.addStack(5, crates5);
crateStackClone.addStack(5, crates5);
char[] crates6 = { 'H', 'D', 'G', 'W', 'P' };
crateStack.addStack(6, crates6);
crateStackClone.addStack(6, crates6);
char[] crates7 = { 'Z', 'L', 'P', 'H', 'S', 'C', 'M', 'V' };
crateStack.addStack(7, crates7);
crateStackClone.addStack(7, crates7);
char[] crates8 = { 'R', 'P', 'F', 'L', 'W', 'G', 'Z' };
crateStack.addStack(8, crates8);
crateStackClone.addStack(8, crates8);
ArrayList<String> moves = reader.readGames("input5.txt");
for (int i = 0; i < moves.size(); i++) {
// System.out.println(moves.get(i));
int currentIndex;
int numMoves = Integer.valueOf(moves.get(i).substring(5, moves.get(i).indexOf('f') - 1));
currentIndex = moves.get(i).indexOf('f') + 1;
int start = Integer.valueOf(
moves.get(i).substring(moves.get(i).indexOf(' ', currentIndex) + 1, moves.get(i).indexOf('t') - 1));
currentIndex = moves.get(i).indexOf('t') + 1;
int destination = Integer.valueOf(moves.get(i).substring(moves.get(i).indexOf(' ', currentIndex) + 1));
// System.out.println(numMoves + " " + start + " " + destination);
for (int n = 0; n < numMoves; n++) {
crateStack.moveCrate(start - 1, destination - 1);
}
crateStackClone.moveCrates(start - 1, destination - 1, numMoves);
// System.out.println(moves.get(i).indexOf('e'));
// int moveN =
// Integer.valueOf(moves.get(i).substring(moves.get(i).indexOf('e')))
}
System.out.println("day5: challenge 1: " + crateStack.getTopCrates());
System.out.println("day5: challenge 2: " + crateStackClone.getTopCrates());
String datastream = reader.readGames("input6.txt").get(0);
// String pattern = "(?:([a-z])(?!.*\1)){4}";
// Pattern pattern = Pattern.compile("(?:([a-z])(?!.*\1)){4}");
boolean pkg = false;
for (int i = 0; i < datastream.length(); i++) {
// Matcher match = pattern.matcher(datastream.substring(i, i + 4));
// if (match.find()){
// System.out.println("day6: challenge 1: " + (i + 4));
// i = datastream.length();
// }
String substr = datastream.substring(i, i + 4);
int uniquechars = 0;
for (int n = 3; n >= 0; n--) {
if (substr.indexOf(substr.charAt(n)) == n) {
uniquechars++;
}
}
if (uniquechars == 4 && !pkg) {
System.out.println("day6: challenge 1: " + (i + 4));
// i = datastream.length() + 4;
pkg = true;
}
String sbstr = datastream.substring(i, i + 14);
uniquechars = 0;
for (int n = 13; n >= 0; n--) {
if (sbstr.indexOf(sbstr.charAt(n)) == n) {
uniquechars++;
}
}
if (uniquechars == 14) {
System.out.println("day6: challenge 1: " + (i + 14));
i = datastream.length() + 4;
}
}
// System.out.println(datastream);`
ArrayList<String> terminal = reader.readGames("input7.txt");
// EFSNode root = new EFSNode();
ArrayList<String> scope = new ArrayList();
scope.add("/");
Map<String, Integer> folderSize = new HashMap<>();
folderSize.put("/", 0);
// folderSize.put("kut", 20);
// System.out.println(folderSize);
for (int i = 1; i < terminal.size(); i++) {
// System.out.println(terminal.get(i));
if (terminal.get(i).startsWith("$")) {
if (terminal.get(i).startsWith("$ cd")) {
if (terminal.get(i).substring(5).equals("..")) {
scope.remove(scope.size() - 1);
} else {
// String name = "";
scope.add(scope.get(scope.size() - 1) + terminal.get(i).substring(5) + "/");
String folder = scope.get(scope.size() - 1);
// System.out.println(folder);
folderSize.put(folder, 0);
// System.out.println(folderSize);
}
}
} else {
if (!terminal.get(i).startsWith("dir")) {
// System.out.println(folderSize);
for (int n = 0; n < scope.size(); n++) {
folderSize.replace(scope.get(n), folderSize.get(scope.get(n))
+ Integer.valueOf(terminal.get(i).substring(0, terminal.get(i).indexOf(" "))));
}
}
}
}
int totalSize = 0;
int deletedDit = 700000000;
int spaceNeeeded = 30000000 - (70000000 - folderSize.get("/"));
for (Integer size : folderSize.values()) {
// System.out.println(folderSize);
if (size < 100000) {
totalSize += size;
}
if (size < deletedDit && size >= spaceNeeeded) {
deletedDit = size;
}
}
// System.out.println(folderSize.get("/") + " " + deletedDit);
System.out.println("day7: challenge 1: " + totalSize);
System.out.println("day7: challenge 2: " + deletedDit);
ArrayList<String> rows = reader.readGames("input8.txt");
int[][] treeGrid = new int[rows.size()][rows.get(0).length()];
int columns = rows.get(0).length();
int row = rows.size();
// System.out.println(row);
for (int i = 0; i < row; i++) {
for (int n = 0; n < columns; n++) {
treeGrid[i][n] = Integer.valueOf(rows.get(i).substring(n, n + 1));
// System.out.print(treeGrid[i][n] + " ");
}
}
int visibleTrees = 0;
int scenicScore = 0;
for (int i = 0; i < row; i++) {
// System.out.println(" ");
for (int n = 0; n < columns; n++) {
// boolean visible = false;
boolean ttl = false;
boolean ttr = false;
boolean ttu = false;
boolean ttb = false;
int distanceL = 0;
int distanceR = 0;
int distanceU = 0;
int distanceB = 0;
// System.out.print(treeGrid[i][n] + " -> ");
for (int t = i - 1; t >= 0; t--) {
// System.out.print(treeGrid[t][n] + " | ");
if (treeGrid[i][n] > treeGrid[t][n]) {
distanceU++;
} else {
// System.out.println(n +" "+ i + " " + treeGrid[i][n] + " " + treeGrid[t][n] +
// " left");
t = 0;
distanceU++;
}
}
// System.out.print("distance = " + distanceU);
for (int t = i + 1; t < row; t++) {
// System.out.print(treeGrid[t][n] + " | ");
if (treeGrid[i][n] > treeGrid[t][n]) {
distanceB++;
} else {
t = row;
distanceB++;
}
}
// System.out.print("distance = " + distanceB + "\n");
for (int t = n - 1; t >= 0; t--) {
// System.out.print(treeGrid[i][n] + " | ");
if (treeGrid[i][n] > treeGrid[i][t]) {
distanceL++;
} else {
t = 0;
distanceL++;
}
}
// System.out.print("distance = " + distanceL + "\n");
for (int t = n + 1; t < columns; t++) {
// System.out.print(treeGrid[i][n] + " | ");
if (treeGrid[i][n] > treeGrid[i][t]) {
distanceR++;
} else {
t = columns;
distanceR++;
}
}
// System.out.print("distance = " + distanceR + "\n");
// System.out.println(treeGrid[i][n] + " -> " + (distanceU + " " + distanceB + "
// " + distanceL + " " + distanceR) + " | " + (distanceU * distanceB * distanceL
// * distanceR));
if ((distanceU * distanceB * distanceL * distanceR) > scenicScore) {
// System.out.println(scenicScore);
scenicScore = (distanceU * distanceB * distanceL * distanceR);
}
for (int t = 0; t < row; t++) {
// System.out.print(t);
if (treeGrid[i][n] <= treeGrid[t][n]) {
// System.out.print(t + " = " + treeGrid[i][n] + " " + treeGrid[t][n] + " | ");
if (t < i) {
ttu = true;
} else if (t > i) {
ttb = true;
}
}
}
// System.out.println(" ");
for (int t = 0; t < columns; t++) {
if (treeGrid[i][n] <= treeGrid[i][t]) {
// System.out.print(t + " = " + treeGrid[i][n] + " " + treeGrid[t][n] + " | ");
if (t < n) {
ttl = true;
} else if (t > n) {
ttr = true;
// System.out.print(treeGrid[i][n] + " " + i + " " + n + " " + t + " rechts |
// ");
}
}
}
if (!ttu || !ttb || !ttl || !ttr) {
visibleTrees++;
// System.out.print(treeGrid[i][n] + " " + i + " " + n);
} else if (ttr) {
// System.out.print(treeGrid[i][n] + " " + i + " " + n);
}
}
}
// System.out.println(visibleTrees);
// visibleTrees += (row + columns) + 1;
System.out.println("day8: challenge 1: " + visibleTrees);
System.out.println("day8: challenge 2: " + scenicScore);
ArrayList<String> ropeMoves = reader.readGames("input9.txt");
int[][] knots = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 } };
ArrayList<String> pos2 = new ArrayList<>();
pos2.add("0 0");
ArrayList<String> pos10 = new ArrayList<>();
pos10.add("0 0");
for (int i = 0; i < ropeMoves.size(); i++) {
String direction = ropeMoves.get(i).substring(0, 2);
int steps = Integer.valueOf(ropeMoves.get(i).substring(2));
for (int n = 0; n < steps; n++) {
switch (direction) {
case "R ":
knots[0][0]++;
break;
case "L ":
knots[0][0]--;
break;
case "U ":
knots[0][1]++;
break;
case "D ":
knots[0][1]--;
break;
default:
break;
}
for (int j = 1; j < knots.length; j++) {
// System.out.println("controle " + n + " | " + j);
if (knots[j - 1][0] - knots[j][0] == 2 && knots[j - 1][1] - knots[j][1] == 2) {
knots[j][0] = knots[j - 1][0] - 1;
knots[j][1] = knots[j - 1][1] - 1;
} else if (knots[j - 1][0] - knots[j][0] == 2 && knots[j - 1][1] - knots[j][1] == -2) {
knots[j][0] = knots[j - 1][0] - 1;
knots[j][1] = knots[j - 1][1] + 1;
} else if (knots[j - 1][0] - knots[j][0] == -2 && knots[j - 1][1] - knots[j][1] == 2) {
knots[j][0] = knots[j - 1][0] + 1;
knots[j][1] = knots[j - 1][1] - 1;
} else if (knots[j - 1][0] - knots[j][0] == -2 && knots[j - 1][1] - knots[j][1] == -2) {
knots[j][0] = knots[j - 1][0] + 1;
knots[j][1] = knots[j - 1][1] + 1;
} else if (knots[j - 1][0] - knots[j][0] == 2) {
// System.out.println("beweging naar<SUF>
knots[j][0] = knots[j - 1][0] - 1;
knots[j][1] = knots[j - 1][1];
} else if (knots[j][0] - knots[j - 1][0] == 2) {
knots[j][0] = knots[j - 1][0] + 1;
knots[j][1] = knots[j - 1][1];
} else if (knots[j - 1][1] - knots[j][1] == 2) {
knots[j][0] = knots[j - 1][0];
knots[j][1] = knots[j - 1][1] - 1;
} else if (knots[j][1] - knots[j - 1][1] == 2) {
knots[j][0] = knots[j - 1][0];
knots[j][1] = knots[j - 1][1] + 1;
}
}
String pos = knots[1][0] + " " + knots[1][1];
boolean newPos = false;
for (int j = 0; j < pos2.size(); j++) {
if (pos2.get(j).equals(pos)) {
newPos = true;
}
}
if (!newPos) {
pos2.add(pos);
}
pos = knots[9][0] + " " + knots[9][1];
newPos = false;
for (int j = 0; j < pos10.size(); j++) {
if (pos10.get(j).equals(pos)) {
newPos = true;
}
}
if (!newPos) {
pos10.add(pos);
}
}
}
System.out.println("day9: challenge 1: " + pos2.size());
System.out.println("day9: challenge 2: " + pos10.size());
// lets gooo
// System.out.println("day10: challenge 1: " + pos2.size());
// System.out.println("day10: challenge 2: " + pos10.size());
}
} |
101970_3 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.faceengine.lipsync;
import hmi.faceanimation.FaceController;
import hmi.tts.TTSTiming;
import hmi.tts.Visime;
import java.util.ArrayList;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import saiba.bml.core.Behaviour;
import asap.faceengine.faceunit.TimedFaceUnit;
import asap.faceengine.viseme.VisemeBinding;
import asap.realizer.lipsync.LipSynchProvider;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.pegboard.OffsetPeg;
import asap.realizer.pegboard.PegBoard;
import asap.realizer.pegboard.TimePeg;
import asap.realizer.planunit.PlanManager;
import asap.realizer.planunit.TimedPlanUnit;
/**
* Creates TimedFaceUnits for lipsync
* @author Herwin
*
*/
@Slf4j
public class TimedFaceUnitLipSynchProvider implements LipSynchProvider
{
private final VisemeBinding visimeBinding;
private final FaceController faceController;
private final PlanManager<TimedFaceUnit>facePlanManager;
private final PegBoard pegBoard;
public TimedFaceUnitLipSynchProvider(VisemeBinding visBinding, FaceController fc, PlanManager<TimedFaceUnit>facePlanManager, PegBoard pb)
{
visimeBinding = visBinding;
faceController = fc;
pegBoard = pb;
this.facePlanManager= facePlanManager;
}
@Override
public void addLipSyncMovement(BMLBlockPeg bbPeg, Behaviour beh, TimedPlanUnit bs, TTSTiming timing)
{
ArrayList<TimedFaceUnit> tfus = new ArrayList<TimedFaceUnit>();
double totalDuration = 0d;
double prevDuration = 0d;
// add null viseme before
TimedFaceUnit tfu = null;
HashMap<TimedFaceUnit, Double> startTimes = new HashMap<TimedFaceUnit, Double>();
HashMap<TimedFaceUnit, Double> endTimes = new HashMap<TimedFaceUnit, Double>();
for (Visime vis : timing.getVisimes())
{
// OOK: de visemen zijn nu te kort (sluiten aan op interpolatie 0/0
// ipv 50/50)
// make visemeunit, add to faceplanner...
double start = totalDuration / 1000d - prevDuration / 2000;
double peak = totalDuration / 1000d + vis.getDuration() / 2000d;
double end = totalDuration / 1000d + vis.getDuration() / 1000d;
if(tfu!=null)
{
endTimes.put(tfu, peak); // extend previous tfu to the peak of this
}
// one!
tfu = visimeBinding.getVisemeUnit(bbPeg, beh, vis.getNumber(), faceController, pegBoard);
startTimes.put(tfu, start);
endTimes.put(tfu, end);
tfus.add(tfu);
totalDuration += vis.getDuration();
prevDuration = vis.getDuration();
}
for (TimedFaceUnit vfu : tfus)
{
vfu.setSubUnit(true);
facePlanManager.addPlanUnit(vfu);
}
// and now link viseme units to the speech timepeg!
for (TimedFaceUnit plannedFU : tfus)
{
TimePeg startPeg = new OffsetPeg(bs.getTimePeg("start"), startTimes.get(plannedFU));
plannedFU.setTimePeg("start", startPeg);
TimePeg endPeg = new OffsetPeg(bs.getTimePeg("start"), endTimes.get(plannedFU));
plannedFU.setTimePeg("end", endPeg);
log.debug("adding face movement at {}-{}", plannedFU.getStartTime(), plannedFU.getEndTime());
}
}
}
| ArticulatedSocialAgentsPlatform/AsapRealizer | Engines/AsapFaceEngine/src/asap/faceengine/lipsync/TimedFaceUnitLipSynchProvider.java | 1,330 | // OOK: de visemen zijn nu te kort (sluiten aan op interpolatie 0/0 | line_comment | nl | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.faceengine.lipsync;
import hmi.faceanimation.FaceController;
import hmi.tts.TTSTiming;
import hmi.tts.Visime;
import java.util.ArrayList;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import saiba.bml.core.Behaviour;
import asap.faceengine.faceunit.TimedFaceUnit;
import asap.faceengine.viseme.VisemeBinding;
import asap.realizer.lipsync.LipSynchProvider;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.pegboard.OffsetPeg;
import asap.realizer.pegboard.PegBoard;
import asap.realizer.pegboard.TimePeg;
import asap.realizer.planunit.PlanManager;
import asap.realizer.planunit.TimedPlanUnit;
/**
* Creates TimedFaceUnits for lipsync
* @author Herwin
*
*/
@Slf4j
public class TimedFaceUnitLipSynchProvider implements LipSynchProvider
{
private final VisemeBinding visimeBinding;
private final FaceController faceController;
private final PlanManager<TimedFaceUnit>facePlanManager;
private final PegBoard pegBoard;
public TimedFaceUnitLipSynchProvider(VisemeBinding visBinding, FaceController fc, PlanManager<TimedFaceUnit>facePlanManager, PegBoard pb)
{
visimeBinding = visBinding;
faceController = fc;
pegBoard = pb;
this.facePlanManager= facePlanManager;
}
@Override
public void addLipSyncMovement(BMLBlockPeg bbPeg, Behaviour beh, TimedPlanUnit bs, TTSTiming timing)
{
ArrayList<TimedFaceUnit> tfus = new ArrayList<TimedFaceUnit>();
double totalDuration = 0d;
double prevDuration = 0d;
// add null viseme before
TimedFaceUnit tfu = null;
HashMap<TimedFaceUnit, Double> startTimes = new HashMap<TimedFaceUnit, Double>();
HashMap<TimedFaceUnit, Double> endTimes = new HashMap<TimedFaceUnit, Double>();
for (Visime vis : timing.getVisimes())
{
// OOK: de<SUF>
// ipv 50/50)
// make visemeunit, add to faceplanner...
double start = totalDuration / 1000d - prevDuration / 2000;
double peak = totalDuration / 1000d + vis.getDuration() / 2000d;
double end = totalDuration / 1000d + vis.getDuration() / 1000d;
if(tfu!=null)
{
endTimes.put(tfu, peak); // extend previous tfu to the peak of this
}
// one!
tfu = visimeBinding.getVisemeUnit(bbPeg, beh, vis.getNumber(), faceController, pegBoard);
startTimes.put(tfu, start);
endTimes.put(tfu, end);
tfus.add(tfu);
totalDuration += vis.getDuration();
prevDuration = vis.getDuration();
}
for (TimedFaceUnit vfu : tfus)
{
vfu.setSubUnit(true);
facePlanManager.addPlanUnit(vfu);
}
// and now link viseme units to the speech timepeg!
for (TimedFaceUnit plannedFU : tfus)
{
TimePeg startPeg = new OffsetPeg(bs.getTimePeg("start"), startTimes.get(plannedFU));
plannedFU.setTimePeg("start", startPeg);
TimePeg endPeg = new OffsetPeg(bs.getTimePeg("start"), endTimes.get(plannedFU));
plannedFU.setTimePeg("end", endPeg);
log.debug("adding face movement at {}-{}", plannedFU.getStartTime(), plannedFU.getEndTime());
}
}
}
|
126693_2 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.faceanimation.util;
import hmi.faceanimation.model.MPEG4Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* Provides an interface to Xface via TCP/IP. Xface accepts FAP uploads that usually contain more frames at once. In this interface, we upload one
* frame at a time. This works, but Xface stops working when these uploads come too fast after each other. We therefore create a seperate thread so
* the sleep does not get in the way of the GUI or whatever uses this interface.
* </p>
*
* <p>
* We use a small state machine to keep track of our state and stops us from connecting when connected, sending when in error, etc.
* </p>
*
* @author R.C. Paul
*/
public class XfaceInterface extends Thread
{
private MPEG4Configuration configuration;
private Integer[] values = new Integer[68];
private Logger logger = LoggerFactory.getLogger(XfaceInterface.class.getName());
private enum State
{
START, CONNECTING, STANDBY, DIRTY, SENDING_TASK, CONNECTION_CLOSED, ERROR
};
private State state;
private Socket socket;
private PrintWriter out;
private InputStream in;
private int taskId = 1;
private int ownerId;
private int port = 50011;
private int sleeptime = 500;
private boolean stopThread = false;
public XfaceInterface(int newPort)
{
setState(State.START);
port = newPort;
}
public void connect()
{
setState(State.CONNECTING);
this.start();
try
{
socket = new Socket("127.0.0.1", port);
out = new PrintWriter(socket.getOutputStream(), true);
in = socket.getInputStream();
StringBuffer inputBuffer = new StringBuffer();
while (true)
{
inputBuffer.append((char) in.read());
if (in.available() < 1)
break;
}
// Controleren of verbinding is geaccepteerd.
String inputLine = inputBuffer.toString();
Pattern pattern = Pattern.compile("<notify name=\"CONNECTION_OK\" ownerId=\"([0-9]+)\" taskId=\"[0-9]+\" status=\"[0-9]+\"/>.*");
Matcher matcher = pattern.matcher(inputLine);
if (matcher.matches())
{
ownerId = Integer.parseInt(matcher.group(1));
timedPrint("Connection made, ownerId=" + ownerId);
setState(State.STANDBY);
}
else
{
throw new Exception("Invalid reply: " + inputLine);
}
}
catch (Exception e)
{
setState(State.ERROR);
System.err.println(e.getMessage());
e.printStackTrace();
}
}
public void disconnect()
{
if (out == null)
return;
out.close();
try
{
in.close();
socket.close();
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
setState(State.CONNECTION_CLOSED);
stopThread = true;
}
public boolean isStandby()
{
return (state == State.STANDBY);
}
/**
* <p>
* Sets values via a MPEG4Configuration object. This usually contains values from 0.0-1.0 for unidirectional FAPs or -1.0-1.0 for bidirectional
* FAPs.
* </p>
*
* @param configuration
* @see setRawValues
*/
public void setConfiguration(MPEG4Configuration configuration)
{
this.configuration = configuration;
this.values = configuration.getValues();
setState(State.DIRTY);
}
/**
* <p>
* Sets raw values. These are directly used in the FAP uploads.
* <p>
*
* @param values
* @see setConfiguration
*/
public void setRawValues(Integer[] values)
{
this.values = values;
setState(State.DIRTY);
}
private void sendConfiguration()
{
// convert();
StringBuffer task = new StringBuffer();
task.append("<task name=\"UPLOAD_FAP\" ownerId=\"" + ownerId + "\" taskId=\"");
task.append(taskId);
task.append("\"><param>");
task.append("2.1 C:\\Users\\balci\\Work\\FACE\\exml2fap\\files\\TempFile 25 1\n");
for (int i = 0; i < values.length; i++)
{
if (i == 0 || i == 1 || values[i] == null)
task.append(0);
else
task.append(1);
if (i < values.length)
task.append(' ');
}
task.append("\n0 "); // Frame number
for (int i = 0; i < values.length; i++)
{
if (i == 0 || i == 1 || values[i] == null)
continue;
task.append(values[i]);
task.append(' ');
}
// System.out.println(task.toString());
task.append("</param></task>");
sendTask(taskId++, "UPLOAD_FAP", task.toString());
}
private void displayConfiguration()
{
StringBuffer task = new StringBuffer();
task.append("<task name=\"STOP_PLAYBACK\" ownerId=\"" + ownerId + "\" taskId=\"");
task.append(taskId);
task.append("\" status=\"0\"></task>");
sendTask(taskId++, "STOP_PLAYBACK", task.toString());
}
private void sendTask(int taskId, String task, String xml)
{
if (out == null)
return;
setState(State.SENDING_TASK);
out.write(xml);
out.flush();
try
{
in.skip(in.available());
}
catch (IOException e)
{
e.printStackTrace();
}
setState(State.STANDBY);
}
private void setState(State state)
{
this.state = state;
}
private void timedPrint(String message)
{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
DateFormat df = DateFormat.getTimeInstance(DateFormat.DEFAULT);
DecimalFormat mdf = new DecimalFormat("000");
String milliseconds = mdf.format(cal.get(Calendar.MILLISECOND));
String time = df.format(cal.getTime()) + "." + milliseconds;
logger.debug("[ {} ] {}", time, message);
}
public static void sleep(long time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
/*
* This method is unused but here for future reference.
*/
/*
* private void convert() { if (configuration == null) return;
*
* int[][] range = new int[68][]; range[2] = new int[2]; range[2][1] = 1000; range[3] = new int[2]; range[3][0] = -400; range[3][1] = 200;
* range[4] = new int[2]; range[4][0] = -500; range[4][1] = 300; range[7] = new int[2]; range[7][0] = -500; range[7][1] = 300; range[8] = new
* int[2]; range[8][0] = -500; range[8][1] = 300; range[9] = new int[2]; range[9][0] = -600; range[9][1] = 300; range[10] = new int[2];
* range[10][0] = -600; range[10][1] = 300; range[5] = new int[2]; range[5][0] = -200; range[5][1] = 300; range[6] = new int[2]; range[6][0] =
* -200; range[6][1] = 300; range[11] = new int[2]; range[11][0] = -300; range[11][1] = 300; range[12] = new int[2]; range[12][0] = -300;
* range[12][1] = 300; range[15] = new int[2]; range[15][0] = -1500; range[15][1] = 1500; range[16] = new int[2]; range[16][0] = -500;
* range[16][1] = 500; range[18] = new int[2]; range[18][0] = -200; range[18][1] = 1000; range[19] = new int[2]; range[19][0] = -200; range[19][1]
* = 1000; range[20] = new int[2]; range[20][0] = -10; range[20][1] = 1000; range[21] = new int[2]; range[21][0] = -10; range[21][1] = 1000;
* range[30] = new int[2]; range[30][0] = -50; range[30][1] = 150; range[31] = new int[2]; range[31][0] = -50; range[31][1] = 150; range[32] = new
* int[2]; range[32][0] = -200; range[32][1] = 500; range[33] = new int[2]; range[33][0] = -200; range[33][1] = 500; range[34] = new int[2];
* range[34][0] = -100; range[34][1] = 200; range[35] = new int[2]; range[35][0] = -100; range[35][1] = 200; range[36] = new int[2]; range[36][0]
* = -100; range[36][1] = 200; range[37] = new int[2]; range[37][0] = -100; range[37][1] = 200; range[38] = new int[2]; range[38][0] = -200;
* range[38][1] = 300; range[39] = new int[2]; range[39][0] = -200; range[39][1] = 300; range[40] = new int[2]; range[40][0] = 0; range[40][1] =
* 500; range[41] = new int[2]; range[41][0] = 0; range[41][1] = 500; range[47] = new int[2]; range[47][0] = -10000; range[47][1] = 10000;
* range[48] = new int[2]; range[48][0] = -10000; range[48][1] = 10000; range[49] = new int[2]; range[49][0] = -10000; range[49][1] = 10000;
* range[50] = new int[2]; range[50][0] = -500; range[50][1] = 200; range[51] = new int[2]; range[51][0] = -500; range[51][1] = 200; range[52] =
* new int[2]; range[52][0] = -200; range[52][1] = 500; range[54] = new int[2]; range[54][0] = -500; range[54][1] = 100; range[56] = new int[2];
* range[56][0] = -1000; range[56][1] = 500; range[58] = new int[2]; range[58][0] = -100; range[58][1] = 200;
*
* for (int i=0; i<68; i++) { if (range[i] != null) { int out_min, out_max, out_range; float in_min, in_max, in_range, in_pos;
*
* out_min = range[i][0]; out_max = range[i][1]; out_range = out_max - out_min;
*
* if (MPEG4.getFAPs().get(i).getDirectionality() == Directionality.BIDIRECTIONAL) { in_min = -1.0f; in_max = 1.0f; } else { in_min = 0.0f; in_max
* = 1.0f; }
*
* in_range = in_max - in_min; in_pos = configuration.getValue(i) * in_range + in_min; values[i] = (int) in_pos * out_range + out_min; } else {
* values[i] = 0; } } }
*/
public void run()
{
// Make sure we wait long enough after connecting.
sleep(250);
while (true)
{
sleep(sleeptime);
if (stopThread)
break;
if (communicationNeeded())
communicate();
}
}
private boolean communicationNeeded()
{
return (state == State.DIRTY);
}
private void communicate()
{
sendConfiguration();
sleep(sleeptime);
displayConfiguration();
setState(State.STANDBY);
if (configuration != null)
logger.debug(configuration.toString());
}
}
| ArticulatedSocialAgentsPlatform/HmiCore | HmiFaceAnimation/src/hmi/faceanimation/util/XfaceInterface.java | 3,898 | // Controleren of verbinding is geaccepteerd. | line_comment | nl | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.faceanimation.util;
import hmi.faceanimation.model.MPEG4Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* Provides an interface to Xface via TCP/IP. Xface accepts FAP uploads that usually contain more frames at once. In this interface, we upload one
* frame at a time. This works, but Xface stops working when these uploads come too fast after each other. We therefore create a seperate thread so
* the sleep does not get in the way of the GUI or whatever uses this interface.
* </p>
*
* <p>
* We use a small state machine to keep track of our state and stops us from connecting when connected, sending when in error, etc.
* </p>
*
* @author R.C. Paul
*/
public class XfaceInterface extends Thread
{
private MPEG4Configuration configuration;
private Integer[] values = new Integer[68];
private Logger logger = LoggerFactory.getLogger(XfaceInterface.class.getName());
private enum State
{
START, CONNECTING, STANDBY, DIRTY, SENDING_TASK, CONNECTION_CLOSED, ERROR
};
private State state;
private Socket socket;
private PrintWriter out;
private InputStream in;
private int taskId = 1;
private int ownerId;
private int port = 50011;
private int sleeptime = 500;
private boolean stopThread = false;
public XfaceInterface(int newPort)
{
setState(State.START);
port = newPort;
}
public void connect()
{
setState(State.CONNECTING);
this.start();
try
{
socket = new Socket("127.0.0.1", port);
out = new PrintWriter(socket.getOutputStream(), true);
in = socket.getInputStream();
StringBuffer inputBuffer = new StringBuffer();
while (true)
{
inputBuffer.append((char) in.read());
if (in.available() < 1)
break;
}
// Controleren of<SUF>
String inputLine = inputBuffer.toString();
Pattern pattern = Pattern.compile("<notify name=\"CONNECTION_OK\" ownerId=\"([0-9]+)\" taskId=\"[0-9]+\" status=\"[0-9]+\"/>.*");
Matcher matcher = pattern.matcher(inputLine);
if (matcher.matches())
{
ownerId = Integer.parseInt(matcher.group(1));
timedPrint("Connection made, ownerId=" + ownerId);
setState(State.STANDBY);
}
else
{
throw new Exception("Invalid reply: " + inputLine);
}
}
catch (Exception e)
{
setState(State.ERROR);
System.err.println(e.getMessage());
e.printStackTrace();
}
}
public void disconnect()
{
if (out == null)
return;
out.close();
try
{
in.close();
socket.close();
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
setState(State.CONNECTION_CLOSED);
stopThread = true;
}
public boolean isStandby()
{
return (state == State.STANDBY);
}
/**
* <p>
* Sets values via a MPEG4Configuration object. This usually contains values from 0.0-1.0 for unidirectional FAPs or -1.0-1.0 for bidirectional
* FAPs.
* </p>
*
* @param configuration
* @see setRawValues
*/
public void setConfiguration(MPEG4Configuration configuration)
{
this.configuration = configuration;
this.values = configuration.getValues();
setState(State.DIRTY);
}
/**
* <p>
* Sets raw values. These are directly used in the FAP uploads.
* <p>
*
* @param values
* @see setConfiguration
*/
public void setRawValues(Integer[] values)
{
this.values = values;
setState(State.DIRTY);
}
private void sendConfiguration()
{
// convert();
StringBuffer task = new StringBuffer();
task.append("<task name=\"UPLOAD_FAP\" ownerId=\"" + ownerId + "\" taskId=\"");
task.append(taskId);
task.append("\"><param>");
task.append("2.1 C:\\Users\\balci\\Work\\FACE\\exml2fap\\files\\TempFile 25 1\n");
for (int i = 0; i < values.length; i++)
{
if (i == 0 || i == 1 || values[i] == null)
task.append(0);
else
task.append(1);
if (i < values.length)
task.append(' ');
}
task.append("\n0 "); // Frame number
for (int i = 0; i < values.length; i++)
{
if (i == 0 || i == 1 || values[i] == null)
continue;
task.append(values[i]);
task.append(' ');
}
// System.out.println(task.toString());
task.append("</param></task>");
sendTask(taskId++, "UPLOAD_FAP", task.toString());
}
private void displayConfiguration()
{
StringBuffer task = new StringBuffer();
task.append("<task name=\"STOP_PLAYBACK\" ownerId=\"" + ownerId + "\" taskId=\"");
task.append(taskId);
task.append("\" status=\"0\"></task>");
sendTask(taskId++, "STOP_PLAYBACK", task.toString());
}
private void sendTask(int taskId, String task, String xml)
{
if (out == null)
return;
setState(State.SENDING_TASK);
out.write(xml);
out.flush();
try
{
in.skip(in.available());
}
catch (IOException e)
{
e.printStackTrace();
}
setState(State.STANDBY);
}
private void setState(State state)
{
this.state = state;
}
private void timedPrint(String message)
{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
DateFormat df = DateFormat.getTimeInstance(DateFormat.DEFAULT);
DecimalFormat mdf = new DecimalFormat("000");
String milliseconds = mdf.format(cal.get(Calendar.MILLISECOND));
String time = df.format(cal.getTime()) + "." + milliseconds;
logger.debug("[ {} ] {}", time, message);
}
public static void sleep(long time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
/*
* This method is unused but here for future reference.
*/
/*
* private void convert() { if (configuration == null) return;
*
* int[][] range = new int[68][]; range[2] = new int[2]; range[2][1] = 1000; range[3] = new int[2]; range[3][0] = -400; range[3][1] = 200;
* range[4] = new int[2]; range[4][0] = -500; range[4][1] = 300; range[7] = new int[2]; range[7][0] = -500; range[7][1] = 300; range[8] = new
* int[2]; range[8][0] = -500; range[8][1] = 300; range[9] = new int[2]; range[9][0] = -600; range[9][1] = 300; range[10] = new int[2];
* range[10][0] = -600; range[10][1] = 300; range[5] = new int[2]; range[5][0] = -200; range[5][1] = 300; range[6] = new int[2]; range[6][0] =
* -200; range[6][1] = 300; range[11] = new int[2]; range[11][0] = -300; range[11][1] = 300; range[12] = new int[2]; range[12][0] = -300;
* range[12][1] = 300; range[15] = new int[2]; range[15][0] = -1500; range[15][1] = 1500; range[16] = new int[2]; range[16][0] = -500;
* range[16][1] = 500; range[18] = new int[2]; range[18][0] = -200; range[18][1] = 1000; range[19] = new int[2]; range[19][0] = -200; range[19][1]
* = 1000; range[20] = new int[2]; range[20][0] = -10; range[20][1] = 1000; range[21] = new int[2]; range[21][0] = -10; range[21][1] = 1000;
* range[30] = new int[2]; range[30][0] = -50; range[30][1] = 150; range[31] = new int[2]; range[31][0] = -50; range[31][1] = 150; range[32] = new
* int[2]; range[32][0] = -200; range[32][1] = 500; range[33] = new int[2]; range[33][0] = -200; range[33][1] = 500; range[34] = new int[2];
* range[34][0] = -100; range[34][1] = 200; range[35] = new int[2]; range[35][0] = -100; range[35][1] = 200; range[36] = new int[2]; range[36][0]
* = -100; range[36][1] = 200; range[37] = new int[2]; range[37][0] = -100; range[37][1] = 200; range[38] = new int[2]; range[38][0] = -200;
* range[38][1] = 300; range[39] = new int[2]; range[39][0] = -200; range[39][1] = 300; range[40] = new int[2]; range[40][0] = 0; range[40][1] =
* 500; range[41] = new int[2]; range[41][0] = 0; range[41][1] = 500; range[47] = new int[2]; range[47][0] = -10000; range[47][1] = 10000;
* range[48] = new int[2]; range[48][0] = -10000; range[48][1] = 10000; range[49] = new int[2]; range[49][0] = -10000; range[49][1] = 10000;
* range[50] = new int[2]; range[50][0] = -500; range[50][1] = 200; range[51] = new int[2]; range[51][0] = -500; range[51][1] = 200; range[52] =
* new int[2]; range[52][0] = -200; range[52][1] = 500; range[54] = new int[2]; range[54][0] = -500; range[54][1] = 100; range[56] = new int[2];
* range[56][0] = -1000; range[56][1] = 500; range[58] = new int[2]; range[58][0] = -100; range[58][1] = 200;
*
* for (int i=0; i<68; i++) { if (range[i] != null) { int out_min, out_max, out_range; float in_min, in_max, in_range, in_pos;
*
* out_min = range[i][0]; out_max = range[i][1]; out_range = out_max - out_min;
*
* if (MPEG4.getFAPs().get(i).getDirectionality() == Directionality.BIDIRECTIONAL) { in_min = -1.0f; in_max = 1.0f; } else { in_min = 0.0f; in_max
* = 1.0f; }
*
* in_range = in_max - in_min; in_pos = configuration.getValue(i) * in_range + in_min; values[i] = (int) in_pos * out_range + out_min; } else {
* values[i] = 0; } } }
*/
public void run()
{
// Make sure we wait long enough after connecting.
sleep(250);
while (true)
{
sleep(sleeptime);
if (stopThread)
break;
if (communicationNeeded())
communicate();
}
}
private boolean communicationNeeded()
{
return (state == State.DIRTY);
}
private void communicate()
{
sendConfiguration();
sleep(sleeptime);
displayConfiguration();
setState(State.STANDBY);
if (configuration != null)
logger.debug(configuration.toString());
}
}
|
13779_10 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.eyepiengine;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import saiba.bml.BMLInfo;
import saiba.bml.core.Behaviour;
import saiba.bml.core.FaceLexemeBehaviour;
import saiba.bml.core.GazeBehaviour;
import saiba.bml.core.GestureBehaviour;
import saiba.bml.core.PostureBehaviour;
import saiba.bml.core.PostureShiftBehaviour;
import saiba.bml.core.ext.FaceFacsBehaviour;
import asap.realizer.AbstractPlanner;
import asap.realizer.BehaviourPlanningException;
import asap.realizer.SyncAndTimePeg;
import asap.realizer.feedback.FeedbackManager;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.pegboard.OffsetPeg;
import asap.realizer.planunit.KeyPosition;
import asap.realizer.planunit.PlanManager;
import asap.realizer.scheduler.TimePegAndConstraint;
import asap.eyepiengine.bml.DirectRosMessageBehavior;
import asap.eyepiengine.bml.EyePiGazeBehaviour;
import asap.eyepiengine.bml.EyePiGazeShiftBehaviour;
import asap.eyepiengine.planunit.TimedEyePiUnit;
import asap.eyepiengine.eyepibinding.EyePiBinding;
public class EyePiPlanner extends AbstractPlanner<TimedEyePiUnit>
{
static
{
BMLInfo.addBehaviourType(DirectRosMessageBehavior.xmlTag(), DirectRosMessageBehavior.class);
BMLInfo.addBehaviourType(EyePiGazeBehaviour.xmlTag(), EyePiGazeBehaviour.class);
BMLInfo.addBehaviourType(EyePiGazeShiftBehaviour.xmlTag(), EyePiGazeShiftBehaviour.class);
}
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(EyePiPlanner.class.getName());
private final EyePiBinding eyepiBinding;
public EyePiPlanner(FeedbackManager bfm, EyePiBinding wb, PlanManager<TimedEyePiUnit> planManager)
{
super(bfm, planManager);
eyepiBinding = wb;
}
public EyePiBinding getRosBinding()
{
return eyepiBinding;
}
@Override
public List<SyncAndTimePeg> addBehaviour(BMLBlockPeg bbPeg, Behaviour b, List<TimePegAndConstraint> sacs, TimedEyePiUnit planElement)
throws BehaviourPlanningException
{
TimedEyePiUnit twu;
if (planElement == null)
{
//TODO: why / when does this happen? does it not always go with a non-null planelement from resolveSynchs?
List<TimedEyePiUnit> twus = eyepiBinding.getEyePiUnit(fbManager, bbPeg, b);
if (twus.isEmpty())
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding (no matching constraints), behavior omitted.");
}
// for now, just add the first
twu = twus.get(0);
if (!twu.getEyePiUnit().hasValidParameters())
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding because the parameters are not valid, behavior omitted.");
}
}
else
{
twu = (TimedEyePiUnit) planElement;
}
resolveDefaultKeyPositions(b, twu);
linkSynchs(twu, sacs);
planManager.addPlanUnit(twu);
return constructSyncAndTimePegs(bbPeg,b,twu);
}
/**
* Make a timedeyepiunit from the binding, then try to resolve it's timing (as far as you can already do this) based upon the TimePegAndConstraint you get from the scheduler plus any demands from the unit itself (such as expected duration or non-malleability of certain timing)
*/
@Override
public TimedEyePiUnit resolveSynchs(BMLBlockPeg bbPeg, Behaviour b, List<TimePegAndConstraint> sacs) throws BehaviourPlanningException
{
//get proposed PlanUnit/TimedUnit from binding
List<TimedEyePiUnit> twus = eyepiBinding.getEyePiUnit(fbManager, bbPeg, b);
if (twus.isEmpty())
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding (no matching constraints), behavior omitted.");
}
TimedEyePiUnit twu = twus.get(0); //always take the first match from the binding
if (!twu.getEyePiUnit().hasValidParameters()) //TODO: figure out whether there are more "invalid parameter" responses that we might give early on (such as, unknown animation command -- which should be feedback from the ROS side!)
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding because the parameters are not valid, behavior omitted.");
}
resolveDefaultKeyPositions(b, twu);
//aanpassen: dit moet niet gedelegeerd worden maar meer hier lokaal opgelost. Want eyepibehaviors zijn niet zomaar linearly stretcheable
//resolver.resolveSynchs(bbPeg, b, sacs, twu);
//resolve door:
// - kijk of start ergens aan hangt; vraag duration op; zet end. duration niet bekend?zet op UNKNOWN
// - anders: kijk of end ergens aan hangt; vraag duration op; zet start. duration niet bekend? klaag dat de eyepi dat niet kan (zie voorbeeld bij spraak in geval van stretchen)
return twu;
}
public void resolveDefaultKeyPositions(Behaviour b, TimedEyePiUnit twu)
{
if(b instanceof GazeBehaviour || b instanceof EyePiGazeBehaviour)
{
twu.resolveGazeKeyPositions();
}
else if(b instanceof PostureShiftBehaviour)
{
twu.resolveStartAndEndKeyPositions();
}
else if(b instanceof PostureBehaviour)
{
twu.resolvePostureKeyPositions();
}
else if(b instanceof FaceLexemeBehaviour)
{
twu.resolveFaceKeyPositions();
}
else if(b instanceof FaceFacsBehaviour)
{
twu.resolveFaceKeyPositions();
}
else if(b instanceof GestureBehaviour)
{
twu.resolveGestureKeyPositions();
}
else
{
twu.resolveStartAndEndKeyPositions();
}
}
@Override
public double getRigidity(Behaviour beh)
{
return 0.5;
}
//connect all key positions in this unit, including start and end, to their correct timepegs.
//I guess this can be kept as it is for EyePi
private void linkSynchs(TimedEyePiUnit twu, List<TimePegAndConstraint> sacs)
{
for (TimePegAndConstraint s : sacs)
{
for (KeyPosition kp : twu.getEyePiUnit().getKeyPositions())
{
if (s.syncId.equals(kp.id))
{
if (s.offset == 0)
{
twu.setTimePeg(kp, s.peg);
}
else
{
twu.setTimePeg(kp, new OffsetPeg(s.peg, -s.offset));
}
}
}
}
}
/**
* beyond the directrosmessage, no special BML behaviors here -- we only take the ones we get via routing. See picture engine for how it could also go...
*/
@Override
public List<Class<? extends Behaviour>> getSupportedBehaviours()
{
List<Class<? extends Behaviour>> list = new ArrayList<Class<? extends Behaviour>>();
list.add(DirectRosMessageBehavior.class); //note: this only concerns the *BML* behaviors -- the engine may still support numerous other planunits to fulfill, e.e., other (core) BML behaviors
list.add(EyePiGazeBehaviour.class); //note: this only concerns the *BML* behaviors -- the engine may still support numerous other planunits to fulfill, e.e., other (core) BML behaviors
list.add(EyePiGazeShiftBehaviour.class); //note: this only concerns the *BML* behaviors -- the engine may still support numerous other planunits to fulfill, e.e., other (core) BML behaviors
return list;
}
@Override
public List<Class<? extends Behaviour>> getSupportedDescriptionExtensions()
{
List<Class<? extends Behaviour>> list = new ArrayList<Class<? extends Behaviour>>();
return list;
}
}
| ArticulatedSocialAgentsPlatform/UTRobotics | JavaModules/AsapEyePiEngine/src/asap/eyepiengine/EyePiPlanner.java | 2,818 | // - kijk of start ergens aan hangt; vraag duration op; zet end. duration niet bekend?zet op UNKNOWN
| line_comment | nl | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.eyepiengine;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import saiba.bml.BMLInfo;
import saiba.bml.core.Behaviour;
import saiba.bml.core.FaceLexemeBehaviour;
import saiba.bml.core.GazeBehaviour;
import saiba.bml.core.GestureBehaviour;
import saiba.bml.core.PostureBehaviour;
import saiba.bml.core.PostureShiftBehaviour;
import saiba.bml.core.ext.FaceFacsBehaviour;
import asap.realizer.AbstractPlanner;
import asap.realizer.BehaviourPlanningException;
import asap.realizer.SyncAndTimePeg;
import asap.realizer.feedback.FeedbackManager;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.pegboard.OffsetPeg;
import asap.realizer.planunit.KeyPosition;
import asap.realizer.planunit.PlanManager;
import asap.realizer.scheduler.TimePegAndConstraint;
import asap.eyepiengine.bml.DirectRosMessageBehavior;
import asap.eyepiengine.bml.EyePiGazeBehaviour;
import asap.eyepiengine.bml.EyePiGazeShiftBehaviour;
import asap.eyepiengine.planunit.TimedEyePiUnit;
import asap.eyepiengine.eyepibinding.EyePiBinding;
public class EyePiPlanner extends AbstractPlanner<TimedEyePiUnit>
{
static
{
BMLInfo.addBehaviourType(DirectRosMessageBehavior.xmlTag(), DirectRosMessageBehavior.class);
BMLInfo.addBehaviourType(EyePiGazeBehaviour.xmlTag(), EyePiGazeBehaviour.class);
BMLInfo.addBehaviourType(EyePiGazeShiftBehaviour.xmlTag(), EyePiGazeShiftBehaviour.class);
}
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(EyePiPlanner.class.getName());
private final EyePiBinding eyepiBinding;
public EyePiPlanner(FeedbackManager bfm, EyePiBinding wb, PlanManager<TimedEyePiUnit> planManager)
{
super(bfm, planManager);
eyepiBinding = wb;
}
public EyePiBinding getRosBinding()
{
return eyepiBinding;
}
@Override
public List<SyncAndTimePeg> addBehaviour(BMLBlockPeg bbPeg, Behaviour b, List<TimePegAndConstraint> sacs, TimedEyePiUnit planElement)
throws BehaviourPlanningException
{
TimedEyePiUnit twu;
if (planElement == null)
{
//TODO: why / when does this happen? does it not always go with a non-null planelement from resolveSynchs?
List<TimedEyePiUnit> twus = eyepiBinding.getEyePiUnit(fbManager, bbPeg, b);
if (twus.isEmpty())
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding (no matching constraints), behavior omitted.");
}
// for now, just add the first
twu = twus.get(0);
if (!twu.getEyePiUnit().hasValidParameters())
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding because the parameters are not valid, behavior omitted.");
}
}
else
{
twu = (TimedEyePiUnit) planElement;
}
resolveDefaultKeyPositions(b, twu);
linkSynchs(twu, sacs);
planManager.addPlanUnit(twu);
return constructSyncAndTimePegs(bbPeg,b,twu);
}
/**
* Make a timedeyepiunit from the binding, then try to resolve it's timing (as far as you can already do this) based upon the TimePegAndConstraint you get from the scheduler plus any demands from the unit itself (such as expected duration or non-malleability of certain timing)
*/
@Override
public TimedEyePiUnit resolveSynchs(BMLBlockPeg bbPeg, Behaviour b, List<TimePegAndConstraint> sacs) throws BehaviourPlanningException
{
//get proposed PlanUnit/TimedUnit from binding
List<TimedEyePiUnit> twus = eyepiBinding.getEyePiUnit(fbManager, bbPeg, b);
if (twus.isEmpty())
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding (no matching constraints), behavior omitted.");
}
TimedEyePiUnit twu = twus.get(0); //always take the first match from the binding
if (!twu.getEyePiUnit().hasValidParameters()) //TODO: figure out whether there are more "invalid parameter" responses that we might give early on (such as, unknown animation command -- which should be feedback from the ROS side!)
{
throw new BehaviourPlanningException(b, "Behavior " + b.id
+ " could not be constructed from the EyePi binding because the parameters are not valid, behavior omitted.");
}
resolveDefaultKeyPositions(b, twu);
//aanpassen: dit moet niet gedelegeerd worden maar meer hier lokaal opgelost. Want eyepibehaviors zijn niet zomaar linearly stretcheable
//resolver.resolveSynchs(bbPeg, b, sacs, twu);
//resolve door:
// - kijk<SUF>
// - anders: kijk of end ergens aan hangt; vraag duration op; zet start. duration niet bekend? klaag dat de eyepi dat niet kan (zie voorbeeld bij spraak in geval van stretchen)
return twu;
}
public void resolveDefaultKeyPositions(Behaviour b, TimedEyePiUnit twu)
{
if(b instanceof GazeBehaviour || b instanceof EyePiGazeBehaviour)
{
twu.resolveGazeKeyPositions();
}
else if(b instanceof PostureShiftBehaviour)
{
twu.resolveStartAndEndKeyPositions();
}
else if(b instanceof PostureBehaviour)
{
twu.resolvePostureKeyPositions();
}
else if(b instanceof FaceLexemeBehaviour)
{
twu.resolveFaceKeyPositions();
}
else if(b instanceof FaceFacsBehaviour)
{
twu.resolveFaceKeyPositions();
}
else if(b instanceof GestureBehaviour)
{
twu.resolveGestureKeyPositions();
}
else
{
twu.resolveStartAndEndKeyPositions();
}
}
@Override
public double getRigidity(Behaviour beh)
{
return 0.5;
}
//connect all key positions in this unit, including start and end, to their correct timepegs.
//I guess this can be kept as it is for EyePi
private void linkSynchs(TimedEyePiUnit twu, List<TimePegAndConstraint> sacs)
{
for (TimePegAndConstraint s : sacs)
{
for (KeyPosition kp : twu.getEyePiUnit().getKeyPositions())
{
if (s.syncId.equals(kp.id))
{
if (s.offset == 0)
{
twu.setTimePeg(kp, s.peg);
}
else
{
twu.setTimePeg(kp, new OffsetPeg(s.peg, -s.offset));
}
}
}
}
}
/**
* beyond the directrosmessage, no special BML behaviors here -- we only take the ones we get via routing. See picture engine for how it could also go...
*/
@Override
public List<Class<? extends Behaviour>> getSupportedBehaviours()
{
List<Class<? extends Behaviour>> list = new ArrayList<Class<? extends Behaviour>>();
list.add(DirectRosMessageBehavior.class); //note: this only concerns the *BML* behaviors -- the engine may still support numerous other planunits to fulfill, e.e., other (core) BML behaviors
list.add(EyePiGazeBehaviour.class); //note: this only concerns the *BML* behaviors -- the engine may still support numerous other planunits to fulfill, e.e., other (core) BML behaviors
list.add(EyePiGazeShiftBehaviour.class); //note: this only concerns the *BML* behaviors -- the engine may still support numerous other planunits to fulfill, e.e., other (core) BML behaviors
return list;
}
@Override
public List<Class<? extends Behaviour>> getSupportedDescriptionExtensions()
{
List<Class<? extends Behaviour>> list = new ArrayList<Class<? extends Behaviour>>();
return list;
}
}
|
29365_9 | /*
Copyright 2018, 2020 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.ibistesttool;
import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.webcontainer.WebContainerServlet;
import nl.nn.adapterframework.configuration.IbisContext;
import nl.nn.adapterframework.lifecycle.IbisApplicationServlet;
import nl.nn.testtool.echo2.Echo2Application;
/**
* @author Jaco de Groot
*/
public class Servlet extends WebContainerServlet {
// Draaien buiten Ibis:
// private WebApplicationContext webApplicationContext;
// public void init(ServletConfig servletConfig) throws ServletException {
// super.init(servletConfig);
// webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
// }
// public ApplicationInstance newApplicationInstance() {
// return (Echo2Application)webApplicationContext. getBean("echo2Application");
// }
// werkt niet, waarschijnlijk wel als deze servlet voor ibis servlet wordt geladen
// // TODO moet anders
// public static String rootRealPath;
// public void init(ServletConfig servletConfig) throws ServletException {
// super.init(servletConfig);
// rootRealPath = servletConfig.getServletContext(). getRealPath("/");
//// AppConstants appConstants = AppConstants.getInstance();
//// appConstants.put("rootRealPath", rootRealPath);
// }
/**
* @see nl.nn.testtool.echo2.Echo2Application#initBean()
*/
@Override
public ApplicationInstance newApplicationInstance() {
IbisContext ibisContext = IbisApplicationServlet.getIbisContext(getServletContext());
return (Echo2Application)ibisContext.getBean("echo2Application");
}
}
| Artimunor/iaf | ladybug/src/main/java/nl/nn/ibistesttool/Servlet.java | 598 | // // TODO moet anders | line_comment | nl | /*
Copyright 2018, 2020 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.ibistesttool;
import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.webcontainer.WebContainerServlet;
import nl.nn.adapterframework.configuration.IbisContext;
import nl.nn.adapterframework.lifecycle.IbisApplicationServlet;
import nl.nn.testtool.echo2.Echo2Application;
/**
* @author Jaco de Groot
*/
public class Servlet extends WebContainerServlet {
// Draaien buiten Ibis:
// private WebApplicationContext webApplicationContext;
// public void init(ServletConfig servletConfig) throws ServletException {
// super.init(servletConfig);
// webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
// }
// public ApplicationInstance newApplicationInstance() {
// return (Echo2Application)webApplicationContext. getBean("echo2Application");
// }
// werkt niet, waarschijnlijk wel als deze servlet voor ibis servlet wordt geladen
// // TODO moet<SUF>
// public static String rootRealPath;
// public void init(ServletConfig servletConfig) throws ServletException {
// super.init(servletConfig);
// rootRealPath = servletConfig.getServletContext(). getRealPath("/");
//// AppConstants appConstants = AppConstants.getInstance();
//// appConstants.put("rootRealPath", rootRealPath);
// }
/**
* @see nl.nn.testtool.echo2.Echo2Application#initBean()
*/
@Override
public ApplicationInstance newApplicationInstance() {
IbisContext ibisContext = IbisApplicationServlet.getIbisContext(getServletContext());
return (Echo2Application)ibisContext.getBean("echo2Application");
}
}
|
116218_4 | package engine.core;
import java.util.ArrayList;
import engine.helper.EventType;
import engine.helper.GameStatus;
import engine.helper.SpriteType;
public class MarioForwardModel {
private static final int OBS_SCENE_SHIFT = 16;
// Generic values
public static final int OBS_NONE = 0;
public static final int OBS_UNDEF = -42;
// Common between scene detail level 0 and scene detail level 1
public static final int OBS_SOLID = OBS_SCENE_SHIFT + 1;
public static final int OBS_BRICK = OBS_SCENE_SHIFT + 6;
public static final int OBS_QUESTION_BLOCK = OBS_SCENE_SHIFT + 8;
public static final int OBS_COIN = OBS_SCENE_SHIFT + 15;
// Scene detail level 0
public static final int OBS_PYRAMID_SOLID = OBS_SCENE_SHIFT + 2;
public static final int OBS_PIPE_BODY_RIGHT = OBS_SCENE_SHIFT + 21;
public static final int OBS_PIPE_BODY_LEFT = OBS_SCENE_SHIFT + 20;
public static final int OBS_PIPE_TOP_RIGHT = OBS_SCENE_SHIFT + 19;
public static final int OBS_PIPE_TOP_LEFT = OBS_SCENE_SHIFT + 18;
public static final int OBS_USED_BLOCK = OBS_SCENE_SHIFT + 14;
public static final int OBS_BULLET_BILL_BODY = OBS_SCENE_SHIFT + 5;
public static final int OBS_BULLET_BILL_NECT = OBS_SCENE_SHIFT + 4;
public static final int OBS_BULLET_BILL_HEAD = OBS_SCENE_SHIFT + 3;
public static final int OBS_BACKGROUND = OBS_SCENE_SHIFT + 47;
public static final int OBS_PLATFORM_SINGLE = OBS_SCENE_SHIFT + 43;
public static final int OBS_PLATFORM_LEFT = OBS_SCENE_SHIFT + 44;
public static final int OBS_PLATFORM_RIGHT = OBS_SCENE_SHIFT + 45;
public static final int OBS_PLATFORM_CENTER = OBS_SCENE_SHIFT + 46;
// Scene detail level 1
public static final int OBS_PLATFORM = OBS_SCENE_SHIFT + 43;
public static final int OBS_CANNON = OBS_SCENE_SHIFT + 3;
public static final int OBS_PIPE = OBS_SCENE_SHIFT + 18;
// Scene detail level 2
public static final int OBS_SCENE_OBJECT = OBS_SCENE_SHIFT + 84;
// Common between enemies detail level 0 and 1
public static final int OBS_FIREBALL = 16;
// Enemies Detail 0
public static final int OBS_GOOMBA = 2;
public static final int OBS_GOOMBA_WINGED = 3;
public static final int OBS_RED_KOOPA = 4;
public static final int OBS_RED_KOOPA_WINGED = 5;
public static final int OBS_GREEN_KOOPA = 6;
public static final int OBS_GREEN_KOOPA_WINGED = 7;
public static final int OBS_SPIKY = 8;
public static final int OBS_SPIKY_WINGED = 9;
public static final int OBS_BULLET_BILL = 10;
public static final int OBS_ENEMY_FLOWER = 11;
public static final int OBS_MUSHROOM = 12;
public static final int OBS_FIRE_FLOWER = 13;
public static final int OBS_SHELL = 14;
public static final int OBS_LIFE_MUSHROOM = 15;
// Enemies Detail 1
public static final int OBS_STOMPABLE_ENEMY = 2;
public static final int OBS_NONSTOMPABLE_ENEMY = 8;
public static final int OBS_SPECIAL_ITEM = 12;
// Enemies Detail 2
public static final int OBS_ENEMY = 1;
public static int getSpriteTypeGeneralization(SpriteType sprite, int detail) {
switch (detail) {
case (0):
switch (sprite) {
case MARIO:
return OBS_NONE;
default:
sprite.getValue();
}
case (1):
switch (sprite) {
case MARIO:
return OBS_NONE;
case FIREBALL:
return OBS_FIREBALL;
case MUSHROOM:
case LIFE_MUSHROOM:
case FIRE_FLOWER:
return OBS_SPECIAL_ITEM;
case BULLET_BILL:
case SHELL:
case GOOMBA:
case GOOMBA_WINGED:
case GREEN_KOOPA:
case GREEN_KOOPA_WINGED:
case RED_KOOPA:
case RED_KOOPA_WINGED:
return OBS_STOMPABLE_ENEMY;
case SPIKY:
case SPIKY_WINGED:
case ENEMY_FLOWER:
return OBS_NONSTOMPABLE_ENEMY;
default:
return OBS_NONE;
}
case (2):
switch (sprite) {
case FIREBALL:
case MARIO:
case MUSHROOM:
case LIFE_MUSHROOM:
case FIRE_FLOWER:
return OBS_NONE;
default:
return OBS_ENEMY;
}
}
return OBS_UNDEF;
}
public static int getBlockValueGeneralization(int tile, int detail) {
if (tile == 0) {
return OBS_NONE;
}
switch (detail) {
case (0):
switch (tile) {
// invisble blocks
case 48:
case 49:
return OBS_NONE;
// brick blocks
case 6:
case 7:
case 50:
case 51:
return OBS_BRICK;
// ? blocks
case 8:
case 11:
return OBS_QUESTION_BLOCK;
}
return tile + OBS_SCENE_SHIFT;
case (1):
switch (tile) {
// invisble blocks
case 48:
case 49:
// body for jumpthrough platform
case 47:
return OBS_NONE;
// solid blocks
case 1:
case 2:
case 14:
return OBS_SOLID;
// bullet bill blocks
case 3:
case 4:
case 5:
return OBS_CANNON;
// pipe blocks
case 18:
case 19:
case 20:
case 21:
return OBS_PIPE;
// brick blocks
case 6:
case 7:
case 50:
case 51:
return OBS_BRICK;
// ? blocks
case 8:
case 11:
return OBS_QUESTION_BLOCK;
// coin
case 15:
return OBS_COIN;
// Jump through platforms
case 43:
case 44:
case 45:
return OBS_PLATFORM;
}
return OBS_NONE;
case (2):
switch (tile) {
// invisible blocks
case 48:
case 49:
// body for jumpthrough platform
case 47:
return OBS_NONE;
}
// everything else is "something", so it is 100
return OBS_SCENE_OBJECT;
}
return OBS_UNDEF;
}
/**
* The width of the observation grid
*/
public final int obsGridWidth = MarioGame.tileWidth;
/**
* The height of the observation grid
*/
public final int obsGridHeight = MarioGame.tileHeight;
private MarioWorld world;
// stats
private int fallKill;
private int stompKill;
private int fireKill;
private int shellKill;
private int mushrooms;
private int flowers;
private int breakBlock;
/**
* Create a forward model object
*
* @param world
* the current level world that is being used. This class hides the
* world object so the agents won't cheat.
*/
public MarioForwardModel(MarioWorld world) {
this.world = world;
}
/**
* Create a clone from the current forward model state
*
* @return a clone from the current forward model state
*/
public MarioForwardModel clone() {
MarioForwardModel model = new MarioForwardModel(this.world.clone());
model.fallKill = this.fallKill;
model.stompKill = this.stompKill;
model.fireKill = this.fireKill;
model.shellKill = this.shellKill;
model.mushrooms = this.mushrooms;
model.flowers = this.flowers;
model.breakBlock = this.breakBlock;
return model;
}
/**
* Advance the forward model using the action array
*
* @param actions
* a list of all the button states
*/
public void advance(boolean[] actions) {
this.world.update(actions);
for (MarioEvent e : this.world.lastFrameEvents) {
if (e.getEventType() == EventType.FIRE_KILL.getValue()) {
this.fireKill += 1;
}
if (e.getEventType() == EventType.STOMP_KILL.getValue()) {
this.stompKill += 1;
}
if (e.getEventType() == EventType.FALL_KILL.getValue()) {
this.fallKill += 1;
}
if (e.getEventType() == EventType.SHELL_KILL.getValue()) {
this.shellKill += 1;
}
if (e.getEventType() == EventType.COLLECT.getValue()) {
if (e.getEventParam() == SpriteType.FIRE_FLOWER.getValue()) {
this.flowers += 1;
}
if (e.getEventParam() == SpriteType.MUSHROOM.getValue()) {
this.mushrooms += 1;
}
}
if (e.getEventType() == EventType.BUMP.getValue() && e.getEventParam() == OBS_BRICK
&& e.getMarioState() > 0) {
this.breakBlock += 1;
}
}
}
/**
* Get the current state of the running game
*
* @return GameStatus the current state (WIN, LOSE, TIME_OUT, RUNNING)
*/
public GameStatus getGameStatus() {
return this.world.gameStatus;
}
/**
* The percentage of distance traversed between mario and the goal
*
* @return value between 0 to 1 to indicate the percentage of distance traversed
*/
public float getCompletionPercentage() {
return this.world.mario.x / (this.world.level.exitTileX * 16);
}
/**
* Get the current level dimensions
*
* @return the first value is level width and second is level height
*/
public float[] getLevelFloatDimensions() {
return new float[] { this.world.level.width, this.world.level.height };
}
/**
* Get the remaining time before the game timesout
*
* @return the number of time ticks before timeout each frame removes 30 frames
*/
public int getRemainingTime() {
return this.world.currentTimer;
}
/**
* Get mario position
*
* @return the actual mario position in the current state
*/
public float[] getMarioFloatPos() {
return new float[] { this.world.mario.x, this.world.mario.y };
}
/**
* Get mario velocity
*
* @return the actual mario velocity in the current state
*/
public float[] getMarioFloatVelocity() {
return new float[] { this.world.mario.xa, this.world.mario.ya };
}
/**
* If mario can press the jump button while in the air to reach higher areas
*
* @return true if the agent can press the button longer and false otherwise
*/
public boolean getMarioCanJumpHigher() {
return this.world.mario.jumpTime > 0;
}
/**
* Get the current mario mode
*
* @return the current mario mode (0-small, 1-large, 2-fire)
*/
public int getMarioMode() {
int value = 0;
if (this.world.mario.isLarge) {
value = 1;
}
if (this.world.mario.isFire) {
value = 2;
}
return value;
}
/**
* Get to know if mario is touching the ground.
*
* @return true if mario is touching the ground and false otherwise
*/
public boolean isMarioOnGround() {
return this.world.mario.onGround;
}
/**
* Get to know if mario is able to jump
*
* @return true if mario can jump and false otherwise
*/
public boolean mayMarioJump() {
return this.world.mario.mayJump;
}
/**
* Get a 3x float list that contain the type of enemies, x position, y position
*
* @return an array of 3 floats that contain the enemy type, x position, y
* position for each enemy sprite
*/
public float[] getEnemiesFloatPos() {
ArrayList<MarioSprite> enemiesAlive = this.world.getEnemies();
float[] enemyPos = new float[enemiesAlive.size() * 3];
for (int i = 0; i < enemiesAlive.size(); i++) {
enemyPos[3 * i] = enemiesAlive.get(i).type.getValue();
enemyPos[3 * i + 1] = enemiesAlive.get(i).x;
enemyPos[3 * i + 2] = enemiesAlive.get(i).y;
}
return enemyPos;
}
/**
* get the number of enemies killed in the game
*
* @return number of enemies killed in the game
*/
public int getKillsTotal() {
return this.fallKill + this.fireKill + this.shellKill + this.stompKill;
}
/**
* get the number of enemies killed by fireballs
*
* @return number of enemies killed by fireballs
*/
public int getKillsByFire() {
return this.fireKill;
}
/**
* get the number of enemies killed by stomping
*
* @return number of enemies killed by stomping
*/
public int getKillsByStomp() {
return this.stompKill;
}
/**
* get the number of enemies killed by a koopa shell
*
* @return number of enemies killed by a koopa shell
*/
public int getKillsByShell() {
return this.shellKill;
}
/**
* get the number of enemies that fell from the game screen
*
* @return the number of enemies that fell from the game screen
*/
public int getKillsByFall() {
return this.fallKill;
}
/**
* get the number 100 coins collected by mario
*
* @return number of 100 coins collected by mario
*/
public int getNumLives() {
return this.world.lives;
}
/**
* get the number of mushroom collected by mario
*
* @return the number of collected mushrooms by mario
*/
public int getNumCollectedMushrooms() {
return this.mushrooms;
}
/**
* get the number of fire flowers collected by mario
*
* @return the number of collected fire flowers by mario
*/
public int getNumCollectedFireflower() {
return this.flowers;
}
/**
* get the number of coins collected by mario
*
* @return the number of collected coins by mario
*/
public int getNumCollectedCoins() {
return this.world.coins;
}
/**
* get the number of destroyed bricks by large or fire mario
*
* @return the number of destroyed bricks by large or fire mario
*/
public int getNumDestroyedBricks() {
return this.breakBlock;
}
/**
* Get the tile location of mario with respect to the screen
*
* @return the x and y location of mario on the screen as tile values
*/
public int[] getMarioScreenTilePos() {
return new int[] { (int) ((this.world.mario.x - this.world.cameraX) / 16), (int) (this.world.mario.y / 16) };
}
/**
* The current screen status as a 2D tile grid around the center of screen with
* scene detail value 1 and enemy detail value of 0
*
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getScreenCompleteObservation() {
return this.getScreenCompleteObservation(1, 0);
}
/**
* The current enemies on the screen as a 2D tile grid around the center of
* screen with a detail value of 0
*
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getScreenEnemiesObservation() {
return this.getScreenEnemiesObservation(0);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around the
* center of screen with a detail value of 1
*
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getScreenSceneObservation() {
return this.getScreenSceneObservation(1);
}
/**
* The current screen status as a 2D tile grid around mario with scene detail
* value 1 and enemy detail value of 0
*
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getMarioCompleteObservation() {
return this.getMarioCompleteObservation(1, 0);
}
/**
* The current enemies on the screen as a 2D tile grid around mario with a
* detail value of 0
*
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getMarioEnemiesObservation() {
return this.getMarioEnemiesObservation(0);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around
* mario with a detail value of 1
*
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getMarioSceneObservation() {
return this.getMarioSceneObservation(1);
}
/**
* The current screen status as a 2D tile grid around the center of screen
*
* @param sceneDetail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @param enemyDetail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getScreenCompleteObservation(int sceneDetail, int enemyDetail) {
return this.world.getMergedObservation(this.world.cameraX + MarioGame.width / 2, MarioGame.height / 2,
sceneDetail, enemyDetail);
}
/**
* The current enemies on the screen as a 2D tile grid around the center of
* screen
*
* @param detail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getScreenEnemiesObservation(int detail) {
return this.world.getEnemiesObservation(this.world.cameraX + MarioGame.width / 2, MarioGame.height / 2, detail);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around the
* center of screen
*
* @param detail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getScreenSceneObservation(int detail) {
return this.world.getSceneObservation(this.world.cameraX + MarioGame.width / 2, MarioGame.height / 2, detail);
}
/**
* The current screen status as a 2D tile grid around mario
*
* @param sceneDetail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @param enemyDetail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getMarioCompleteObservation(int sceneDetail, int enemyDetail) {
return this.world.getMergedObservation(this.world.mario.x, this.world.mario.y, sceneDetail, enemyDetail);
}
/**
* The current enemies on the screen as a 2D tile grid around mario
*
* @param detail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getMarioEnemiesObservation(int detail) {
return this.world.getEnemiesObservation(this.world.mario.x, this.world.mario.y, detail);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around
* mario
*
* @param detail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getMarioSceneObservation(int detail) {
return this.world.getSceneObservation(this.world.mario.x, this.world.mario.y, detail);
}
}
| ArturoBurela/Mario-AI-Framework | src/engine/core/MarioForwardModel.java | 6,633 | // Common between enemies detail level 0 and 1 | line_comment | nl | package engine.core;
import java.util.ArrayList;
import engine.helper.EventType;
import engine.helper.GameStatus;
import engine.helper.SpriteType;
public class MarioForwardModel {
private static final int OBS_SCENE_SHIFT = 16;
// Generic values
public static final int OBS_NONE = 0;
public static final int OBS_UNDEF = -42;
// Common between scene detail level 0 and scene detail level 1
public static final int OBS_SOLID = OBS_SCENE_SHIFT + 1;
public static final int OBS_BRICK = OBS_SCENE_SHIFT + 6;
public static final int OBS_QUESTION_BLOCK = OBS_SCENE_SHIFT + 8;
public static final int OBS_COIN = OBS_SCENE_SHIFT + 15;
// Scene detail level 0
public static final int OBS_PYRAMID_SOLID = OBS_SCENE_SHIFT + 2;
public static final int OBS_PIPE_BODY_RIGHT = OBS_SCENE_SHIFT + 21;
public static final int OBS_PIPE_BODY_LEFT = OBS_SCENE_SHIFT + 20;
public static final int OBS_PIPE_TOP_RIGHT = OBS_SCENE_SHIFT + 19;
public static final int OBS_PIPE_TOP_LEFT = OBS_SCENE_SHIFT + 18;
public static final int OBS_USED_BLOCK = OBS_SCENE_SHIFT + 14;
public static final int OBS_BULLET_BILL_BODY = OBS_SCENE_SHIFT + 5;
public static final int OBS_BULLET_BILL_NECT = OBS_SCENE_SHIFT + 4;
public static final int OBS_BULLET_BILL_HEAD = OBS_SCENE_SHIFT + 3;
public static final int OBS_BACKGROUND = OBS_SCENE_SHIFT + 47;
public static final int OBS_PLATFORM_SINGLE = OBS_SCENE_SHIFT + 43;
public static final int OBS_PLATFORM_LEFT = OBS_SCENE_SHIFT + 44;
public static final int OBS_PLATFORM_RIGHT = OBS_SCENE_SHIFT + 45;
public static final int OBS_PLATFORM_CENTER = OBS_SCENE_SHIFT + 46;
// Scene detail level 1
public static final int OBS_PLATFORM = OBS_SCENE_SHIFT + 43;
public static final int OBS_CANNON = OBS_SCENE_SHIFT + 3;
public static final int OBS_PIPE = OBS_SCENE_SHIFT + 18;
// Scene detail level 2
public static final int OBS_SCENE_OBJECT = OBS_SCENE_SHIFT + 84;
// Common between<SUF>
public static final int OBS_FIREBALL = 16;
// Enemies Detail 0
public static final int OBS_GOOMBA = 2;
public static final int OBS_GOOMBA_WINGED = 3;
public static final int OBS_RED_KOOPA = 4;
public static final int OBS_RED_KOOPA_WINGED = 5;
public static final int OBS_GREEN_KOOPA = 6;
public static final int OBS_GREEN_KOOPA_WINGED = 7;
public static final int OBS_SPIKY = 8;
public static final int OBS_SPIKY_WINGED = 9;
public static final int OBS_BULLET_BILL = 10;
public static final int OBS_ENEMY_FLOWER = 11;
public static final int OBS_MUSHROOM = 12;
public static final int OBS_FIRE_FLOWER = 13;
public static final int OBS_SHELL = 14;
public static final int OBS_LIFE_MUSHROOM = 15;
// Enemies Detail 1
public static final int OBS_STOMPABLE_ENEMY = 2;
public static final int OBS_NONSTOMPABLE_ENEMY = 8;
public static final int OBS_SPECIAL_ITEM = 12;
// Enemies Detail 2
public static final int OBS_ENEMY = 1;
public static int getSpriteTypeGeneralization(SpriteType sprite, int detail) {
switch (detail) {
case (0):
switch (sprite) {
case MARIO:
return OBS_NONE;
default:
sprite.getValue();
}
case (1):
switch (sprite) {
case MARIO:
return OBS_NONE;
case FIREBALL:
return OBS_FIREBALL;
case MUSHROOM:
case LIFE_MUSHROOM:
case FIRE_FLOWER:
return OBS_SPECIAL_ITEM;
case BULLET_BILL:
case SHELL:
case GOOMBA:
case GOOMBA_WINGED:
case GREEN_KOOPA:
case GREEN_KOOPA_WINGED:
case RED_KOOPA:
case RED_KOOPA_WINGED:
return OBS_STOMPABLE_ENEMY;
case SPIKY:
case SPIKY_WINGED:
case ENEMY_FLOWER:
return OBS_NONSTOMPABLE_ENEMY;
default:
return OBS_NONE;
}
case (2):
switch (sprite) {
case FIREBALL:
case MARIO:
case MUSHROOM:
case LIFE_MUSHROOM:
case FIRE_FLOWER:
return OBS_NONE;
default:
return OBS_ENEMY;
}
}
return OBS_UNDEF;
}
public static int getBlockValueGeneralization(int tile, int detail) {
if (tile == 0) {
return OBS_NONE;
}
switch (detail) {
case (0):
switch (tile) {
// invisble blocks
case 48:
case 49:
return OBS_NONE;
// brick blocks
case 6:
case 7:
case 50:
case 51:
return OBS_BRICK;
// ? blocks
case 8:
case 11:
return OBS_QUESTION_BLOCK;
}
return tile + OBS_SCENE_SHIFT;
case (1):
switch (tile) {
// invisble blocks
case 48:
case 49:
// body for jumpthrough platform
case 47:
return OBS_NONE;
// solid blocks
case 1:
case 2:
case 14:
return OBS_SOLID;
// bullet bill blocks
case 3:
case 4:
case 5:
return OBS_CANNON;
// pipe blocks
case 18:
case 19:
case 20:
case 21:
return OBS_PIPE;
// brick blocks
case 6:
case 7:
case 50:
case 51:
return OBS_BRICK;
// ? blocks
case 8:
case 11:
return OBS_QUESTION_BLOCK;
// coin
case 15:
return OBS_COIN;
// Jump through platforms
case 43:
case 44:
case 45:
return OBS_PLATFORM;
}
return OBS_NONE;
case (2):
switch (tile) {
// invisible blocks
case 48:
case 49:
// body for jumpthrough platform
case 47:
return OBS_NONE;
}
// everything else is "something", so it is 100
return OBS_SCENE_OBJECT;
}
return OBS_UNDEF;
}
/**
* The width of the observation grid
*/
public final int obsGridWidth = MarioGame.tileWidth;
/**
* The height of the observation grid
*/
public final int obsGridHeight = MarioGame.tileHeight;
private MarioWorld world;
// stats
private int fallKill;
private int stompKill;
private int fireKill;
private int shellKill;
private int mushrooms;
private int flowers;
private int breakBlock;
/**
* Create a forward model object
*
* @param world
* the current level world that is being used. This class hides the
* world object so the agents won't cheat.
*/
public MarioForwardModel(MarioWorld world) {
this.world = world;
}
/**
* Create a clone from the current forward model state
*
* @return a clone from the current forward model state
*/
public MarioForwardModel clone() {
MarioForwardModel model = new MarioForwardModel(this.world.clone());
model.fallKill = this.fallKill;
model.stompKill = this.stompKill;
model.fireKill = this.fireKill;
model.shellKill = this.shellKill;
model.mushrooms = this.mushrooms;
model.flowers = this.flowers;
model.breakBlock = this.breakBlock;
return model;
}
/**
* Advance the forward model using the action array
*
* @param actions
* a list of all the button states
*/
public void advance(boolean[] actions) {
this.world.update(actions);
for (MarioEvent e : this.world.lastFrameEvents) {
if (e.getEventType() == EventType.FIRE_KILL.getValue()) {
this.fireKill += 1;
}
if (e.getEventType() == EventType.STOMP_KILL.getValue()) {
this.stompKill += 1;
}
if (e.getEventType() == EventType.FALL_KILL.getValue()) {
this.fallKill += 1;
}
if (e.getEventType() == EventType.SHELL_KILL.getValue()) {
this.shellKill += 1;
}
if (e.getEventType() == EventType.COLLECT.getValue()) {
if (e.getEventParam() == SpriteType.FIRE_FLOWER.getValue()) {
this.flowers += 1;
}
if (e.getEventParam() == SpriteType.MUSHROOM.getValue()) {
this.mushrooms += 1;
}
}
if (e.getEventType() == EventType.BUMP.getValue() && e.getEventParam() == OBS_BRICK
&& e.getMarioState() > 0) {
this.breakBlock += 1;
}
}
}
/**
* Get the current state of the running game
*
* @return GameStatus the current state (WIN, LOSE, TIME_OUT, RUNNING)
*/
public GameStatus getGameStatus() {
return this.world.gameStatus;
}
/**
* The percentage of distance traversed between mario and the goal
*
* @return value between 0 to 1 to indicate the percentage of distance traversed
*/
public float getCompletionPercentage() {
return this.world.mario.x / (this.world.level.exitTileX * 16);
}
/**
* Get the current level dimensions
*
* @return the first value is level width and second is level height
*/
public float[] getLevelFloatDimensions() {
return new float[] { this.world.level.width, this.world.level.height };
}
/**
* Get the remaining time before the game timesout
*
* @return the number of time ticks before timeout each frame removes 30 frames
*/
public int getRemainingTime() {
return this.world.currentTimer;
}
/**
* Get mario position
*
* @return the actual mario position in the current state
*/
public float[] getMarioFloatPos() {
return new float[] { this.world.mario.x, this.world.mario.y };
}
/**
* Get mario velocity
*
* @return the actual mario velocity in the current state
*/
public float[] getMarioFloatVelocity() {
return new float[] { this.world.mario.xa, this.world.mario.ya };
}
/**
* If mario can press the jump button while in the air to reach higher areas
*
* @return true if the agent can press the button longer and false otherwise
*/
public boolean getMarioCanJumpHigher() {
return this.world.mario.jumpTime > 0;
}
/**
* Get the current mario mode
*
* @return the current mario mode (0-small, 1-large, 2-fire)
*/
public int getMarioMode() {
int value = 0;
if (this.world.mario.isLarge) {
value = 1;
}
if (this.world.mario.isFire) {
value = 2;
}
return value;
}
/**
* Get to know if mario is touching the ground.
*
* @return true if mario is touching the ground and false otherwise
*/
public boolean isMarioOnGround() {
return this.world.mario.onGround;
}
/**
* Get to know if mario is able to jump
*
* @return true if mario can jump and false otherwise
*/
public boolean mayMarioJump() {
return this.world.mario.mayJump;
}
/**
* Get a 3x float list that contain the type of enemies, x position, y position
*
* @return an array of 3 floats that contain the enemy type, x position, y
* position for each enemy sprite
*/
public float[] getEnemiesFloatPos() {
ArrayList<MarioSprite> enemiesAlive = this.world.getEnemies();
float[] enemyPos = new float[enemiesAlive.size() * 3];
for (int i = 0; i < enemiesAlive.size(); i++) {
enemyPos[3 * i] = enemiesAlive.get(i).type.getValue();
enemyPos[3 * i + 1] = enemiesAlive.get(i).x;
enemyPos[3 * i + 2] = enemiesAlive.get(i).y;
}
return enemyPos;
}
/**
* get the number of enemies killed in the game
*
* @return number of enemies killed in the game
*/
public int getKillsTotal() {
return this.fallKill + this.fireKill + this.shellKill + this.stompKill;
}
/**
* get the number of enemies killed by fireballs
*
* @return number of enemies killed by fireballs
*/
public int getKillsByFire() {
return this.fireKill;
}
/**
* get the number of enemies killed by stomping
*
* @return number of enemies killed by stomping
*/
public int getKillsByStomp() {
return this.stompKill;
}
/**
* get the number of enemies killed by a koopa shell
*
* @return number of enemies killed by a koopa shell
*/
public int getKillsByShell() {
return this.shellKill;
}
/**
* get the number of enemies that fell from the game screen
*
* @return the number of enemies that fell from the game screen
*/
public int getKillsByFall() {
return this.fallKill;
}
/**
* get the number 100 coins collected by mario
*
* @return number of 100 coins collected by mario
*/
public int getNumLives() {
return this.world.lives;
}
/**
* get the number of mushroom collected by mario
*
* @return the number of collected mushrooms by mario
*/
public int getNumCollectedMushrooms() {
return this.mushrooms;
}
/**
* get the number of fire flowers collected by mario
*
* @return the number of collected fire flowers by mario
*/
public int getNumCollectedFireflower() {
return this.flowers;
}
/**
* get the number of coins collected by mario
*
* @return the number of collected coins by mario
*/
public int getNumCollectedCoins() {
return this.world.coins;
}
/**
* get the number of destroyed bricks by large or fire mario
*
* @return the number of destroyed bricks by large or fire mario
*/
public int getNumDestroyedBricks() {
return this.breakBlock;
}
/**
* Get the tile location of mario with respect to the screen
*
* @return the x and y location of mario on the screen as tile values
*/
public int[] getMarioScreenTilePos() {
return new int[] { (int) ((this.world.mario.x - this.world.cameraX) / 16), (int) (this.world.mario.y / 16) };
}
/**
* The current screen status as a 2D tile grid around the center of screen with
* scene detail value 1 and enemy detail value of 0
*
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getScreenCompleteObservation() {
return this.getScreenCompleteObservation(1, 0);
}
/**
* The current enemies on the screen as a 2D tile grid around the center of
* screen with a detail value of 0
*
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getScreenEnemiesObservation() {
return this.getScreenEnemiesObservation(0);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around the
* center of screen with a detail value of 1
*
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getScreenSceneObservation() {
return this.getScreenSceneObservation(1);
}
/**
* The current screen status as a 2D tile grid around mario with scene detail
* value 1 and enemy detail value of 0
*
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getMarioCompleteObservation() {
return this.getMarioCompleteObservation(1, 0);
}
/**
* The current enemies on the screen as a 2D tile grid around mario with a
* detail value of 0
*
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getMarioEnemiesObservation() {
return this.getMarioEnemiesObservation(0);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around
* mario with a detail value of 1
*
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getMarioSceneObservation() {
return this.getMarioSceneObservation(1);
}
/**
* The current screen status as a 2D tile grid around the center of screen
*
* @param sceneDetail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @param enemyDetail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getScreenCompleteObservation(int sceneDetail, int enemyDetail) {
return this.world.getMergedObservation(this.world.cameraX + MarioGame.width / 2, MarioGame.height / 2,
sceneDetail, enemyDetail);
}
/**
* The current enemies on the screen as a 2D tile grid around the center of
* screen
*
* @param detail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getScreenEnemiesObservation(int detail) {
return this.world.getEnemiesObservation(this.world.cameraX + MarioGame.width / 2, MarioGame.height / 2, detail);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around the
* center of screen
*
* @param detail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getScreenSceneObservation(int detail) {
return this.world.getSceneObservation(this.world.cameraX + MarioGame.width / 2, MarioGame.height / 2, detail);
}
/**
* The current screen status as a 2D tile grid around mario
*
* @param sceneDetail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @param enemyDetail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid that have all the information about all objects on the screen
*/
public int[][] getMarioCompleteObservation(int sceneDetail, int enemyDetail) {
return this.world.getMergedObservation(this.world.mario.x, this.world.mario.y, sceneDetail, enemyDetail);
}
/**
* The current enemies on the screen as a 2D tile grid around mario
*
* @param detail
* the detail level of the current enemies: 0 all details, 1 less
* detailed, 2 binary detail
* @return 2D grid where each tile contain either 0 to indicate no enemy or a
* number to indicate a certain enemy. Look at SpriteTypes for enemy
* values (Detail 0).
*/
public int[][] getMarioEnemiesObservation(int detail) {
return this.world.getEnemiesObservation(this.world.mario.x, this.world.mario.y, detail);
}
/**
* The current objects (not enemies) on the screen as a 2D tile grid around
* mario
*
* @param detail
* the detail level of the scene: 0 all detail, 1 less detailed, 2
* binary detail
* @return 2D grid where each tile contain either 0 which means it is empty or a
* value that reflect the type of the tile in that area. Look at
* TileTypes for the meaning of values (Detail 1)
*/
public int[][] getMarioSceneObservation(int detail) {
return this.world.getSceneObservation(this.world.mario.x, this.world.mario.y, detail);
}
}
|
126391_2 | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Arrays;
public class Graph {
public static class Edge {
int src;
int nbr;
int wt;
Edge(int src, int nbr, int wt) {
this.src = src;
this.nbr = nbr;
this.wt = wt;
}
}
public static void addEdge(ArrayList<Edge>[] graph, int u, int v, int w) {
graph[u].add(new Edge(u, v, w));
graph[v].add(new Edge(v, u, w));
}
public static void display(ArrayList<Edge>[] graph, int N) {
for (int i = 0; i < N; i++) {
System.out.print(i + " -> ");
for (Edge e : graph[i]) {
System.out.print("(" + e.nbr + ", " + e.wt + ") ");
}
System.out.println();
}
}
public static int findEdge(ArrayList<Edge>[] graph, int u, int v) {
ArrayList<Edge> list = graph[u];
for (int i = 0; i < list.size(); i++) {
Edge e = list.get(i);
if (e.nbr == v)
return i;
}
return -1;
}
public static void removeEdge(ArrayList<Edge>[] graph, int u, int v) {
int i1 = findEdge(graph, u, v);
int i2 = findEdge(graph, v, u);
graph[u].remove(i1);
graph[v].remove(i2);
}
public static void removeVtx(ArrayList<Edge>[] graph, int u) {
ArrayList<Edge> list = graph[u];
for (int i = list.size() - 1; i >= 0; i--) {
Edge e = list.get(i);
removeEdge(graph, e.src, e.nbr);
}
}
public static boolean hasPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) {
if (src == dest)
return true;
vis[src] = true;
boolean res = false;
for (Edge e : graph[src])
if (!vis[e.nbr])
res = res || hasPath(graph, e.nbr, dest, vis);
return res;
}
public static int printAllPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis, String psf) {
if (src == dest) {
System.out.println(psf + dest);
return 1;
}
int count = 0;
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
count += printAllPath(graph, e.nbr, dest, vis, psf + src);
}
vis[src] = false;
return count;
}
public static void preOrder(ArrayList<Edge>[] graph, int src, boolean[] vis, int wsf, String psf) {
System.out.println(src + " -> " + (psf + src) + " @ " + wsf);
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
preOrder(graph, e.nbr, vis, wsf + e.wt, psf + src);
}
vis[src] = false;
}
public static void postOrder(ArrayList<Edge>[] graph, int src, boolean[] vis, int wsf, String psf) {
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
postOrder(graph, e.nbr, vis, wsf + e.wt, psf + e.nbr);
}
System.out.println(src + " -> " + psf + " @ " + wsf);
vis[src] = false;
}
public static void lightestPath(ArrayList<Edge>[] graph, int src, int dest) {
// System.out.println("Lightest Path: " + x + " of weight: " + y);
}
public static class pathPair {
String psf = "";
int wsf = -1;
}
public static pathPair heaviestPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) {
if (src == dest) {
pathPair base = new pathPair();
base.psf += src;
base.wsf = 0;
return base;
}
vis[src] = true;
pathPair myAns = new pathPair();
for (Edge e : graph[src]) {
if (!vis[e.nbr]) {
pathPair recAns = heaviestPath(graph, e.nbr, dest, vis);
if (recAns.wsf != -1 && recAns.wsf + e.wt > myAns.wsf) {
myAns.psf = src + recAns.psf;
myAns.wsf = recAns.wsf + e.wt;
}
}
}
vis[src] = false;
return myAns;
}
public static void heaviestPath(ArrayList<Edge>[] graph, int src, int dest) {
boolean[] vis = new boolean[graph.length];
pathPair ans = heaviestPath(graph, src, dest, vis);
System.out.println("Heaviest Path: " + ans.psf + " of weight: " + ans.wsf);
}
public static class ceilFloorPair {
int ceil = (int) 1e9;
int floor = -(int) 1e9;
}
public static void ceilAndFloor(ArrayList<Edge>[] graph, int src, int data, boolean[] vis, int wsf,
ceilFloorPair pair) {
if (wsf > data)
pair.ceil = Math.min(pair.ceil, wsf);
if (wsf < data)
pair.floor = Math.max(pair.floor, wsf);
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr]) {
ceilAndFloor(graph, e.nbr, data, vis, wsf + e.wt, pair);
}
}
vis[src] = false;
}
public static void ceilAndFloor(ArrayList<Edge>[] graph, int src, int data) {
ceilFloorPair pair = new ceilFloorPair();
boolean[] vis = new boolean[graph.length];
ceilAndFloor(graph, src, data, vis, 0, pair);
}
// O(E)
public static void dfs_GCC(ArrayList<Edge>[] graph, int src, boolean[] vis) {
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
dfs_GCC(graph, e.nbr, vis);
}
}
// O(E + V);
public static void GCC(ArrayList<Edge>[] graph) {
int N = graph.length, componentCount = 0;
boolean[] vis = new boolean[N];
for (int i = 0; i < N; i++) {
if (!vis[i]) {
dfs_GCC(graph, i, vis);
componentCount++;
}
}
System.out.println(componentCount);
}
public void dfs(char[][] grid, int[][] dir, int sr, int sc) {
grid[sr][sc] = '0';
for (int d = 0; d < 4; d++) {
int r = sr + dir[d][0];
int c = sc + dir[d][1];
if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == '1')
dfs(grid, dir, r, c);
}
}
public int numIslands(char[][] grid) {
int n = grid.length, m = grid[0].length, componentCount = 0;
int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1') {
dfs(grid, dir, i, j);
componentCount++;
}
}
}
return componentCount;
}
public int dfs(int[][] grid, int[][] dir, int sr, int sc) {
grid[sr][sc] = 0;
int size = 0;
for (int d = 0; d < 4; d++) {
int r = sr + dir[d][0];
int c = sc + dir[d][1];
if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == 1)
size += dfs(grid, dir, r, c);
}
return size + 1;
}
public int maxAreaOfIsland(int[][] grid) {
int n = grid.length, m = grid[0].length, maxSize = 0;
int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
int s = dfs(grid, dir, i, j);
maxSize = Math.max(maxSize, s);
}
}
}
return maxSize;
}
public static void hamintonianPathCycle(ArrayList<Edge>[] graph, int osrc, int src, int EdgeCount, boolean[] vis,
String ans) {
if (EdgeCount == graph.length - 1) {
int idx = findEdge(graph, src, osrc);
if (idx != -1) {
System.out.println(ans + src + "*");
} else {
System.out.println(ans + src + ".");
}
return;
}
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr]) {
hamintonianPathCycle(graph, osrc, e.nbr, EdgeCount + 1, vis, ans + src);
}
}
vis[src] = false;
}
public static void hamintonianPathCycle(ArrayList<Edge>[] graph, int src) {
int N = graph.length;
boolean[] vis = new boolean[N];
hamintonianPathCycle(graph, src, src, 0, vis, "");
}
public static void BFS(ArrayList<Edge>[] graph, int src, int dest) {
LinkedList<Integer> que = new LinkedList<>();
int N = graph.length;
boolean[] vis = new boolean[N];
que.addLast(src);
int level = 0;
boolean isCyclePresent = false;
int shortestPath = -1;
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
// for cycle
if (vis[rvtx]) {
isCyclePresent = true;
continue;
}
if (rvtx == dest) {
shortestPath = level;
}
vis[rvtx] = true;
for (Edge e : graph[rvtx]) {
if (!vis[e.nbr]) {
que.addLast(e.nbr);
}
}
}
}
}
public static boolean cycleDetection(ArrayList<Edge>[] graph, int src, boolean[] vis) {
LinkedList<Integer> que = new LinkedList<>();
que.addLast(src);
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
Integer rvtx = que.removeFirst();
if (vis[rvtx])
return true;
vis[rvtx] = true;
for (Edge e : graph[rvtx]) {
if (!vis[e.nbr])
que.addLast(e.nbr);
}
}
}
return false;
}
public static void cycleDetection(ArrayList<Edge>[] graph) {
int vtces = graph.length;
boolean[] vis = new boolean[vtces];
boolean res = false;
for (int i = 0; i < vtces; i++) {
if (!vis[i])
res = res || cycleDetection(graph, i, vis);
}
System.out.println(res);
}
public static class BFS_Pair {
int vtx = 0;
String psf = "";
int wsf = 0;
public BFS_Pair(int vtx, String psf, int wsf) {
this.vtx = vtx;
this.psf = psf;
this.wsf = wsf;
}
}
public static void printBFSPath(ArrayList<Edge>[] graph, int src) {
int vtces = graph.length;
boolean[] vis = new boolean[vtces];
LinkedList<BFS_Pair> que = new LinkedList<>();
que.addLast(new BFS_Pair(src, src + "", 0));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
BFS_Pair rp = que.removeFirst();
if (vis[rp.vtx])
continue;
System.out.println(rp.vtx + " -> " + rp.psf + " @ " + rp.wsf);
vis[rp.vtx] = true;
for (Edge e : graph[rp.vtx]) {
if (!vis[e.nbr])
que.addLast(new BFS_Pair(e.nbr, rp.psf + e.nbr, rp.wsf + e.wt));
}
}
}
}
public static int spreadInfection(ArrayList<Edge>[] graph, int infectedPerson, int NoOfDays) {
LinkedList<Integer> que = new LinkedList<>();
boolean[] vis = new boolean[graph.length];
que.addLast(infectedPerson);
int infectedCount = 0, day = 1;
while (que.size() != 0) {
int size = que.size();
if (day > NoOfDays)
break;
while (size-- > 0) {
int ip = que.removeFirst(); // infectedPerson
if (vis[ip])
continue;
vis[ip] = true;
infectedCount++;
for (Edge e : graph[ip]) {
if (!vis[e.nbr])
que.addLast(e.nbr);
}
}
day++;
}
return infectedCount;
}
public static boolean bipartite(ArrayList<Edge>[] graph, int src, int[] vis) {
LinkedList<Integer> que = new LinkedList<>();
que.addLast(src);
int color = 0; // 0 : red, 1 : green
boolean cycle = false, isBipartite = true;
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
if (vis[rvtx] != -1) { // cycle
cycle = true;
if (vis[rvtx] != color) { // conflict
isBipartite = false;
break;
}
continue; // not any kind oo conflict
}
vis[rvtx] = color;
for (Edge e : graph[rvtx]) {
if (vis[e.nbr] == -1) {
que.addLast(e.nbr);
}
}
}
color = (color + 1) % 2;
if (!isBipartite)
break;
}
if (cycle) {
if (isBipartite)
System.out.println("Even Length Cycle");
else
System.out.println("Odd Length Cycle");
} else if (isBipartite && !cycle) {
System.out.println("A-Cycle and Bipartite graph");
}
return isBipartite;
}
public static void bipartite(ArrayList<Edge>[] graph) {
int N = graph.length;
int[] vis = new int[N];
Arrays.fill(vis, -1);
boolean isBipartite = true;
for (int i = 0; i < N; i++) {
if (vis[i] == -1) {
isBipartite = isBipartite && bipartite(graph, i, vis);
}
}
System.out.println("Overall Graph is Bipartite: " + isBipartite);
}
public static void construction() {
int N = 7;
ArrayList<Edge>[] graph = new ArrayList[N];
for (int i = 0; i < N; i++)
graph[i] = new ArrayList<>();
addEdge(graph, 0, 1, 10);
addEdge(graph, 0, 3, 10);
addEdge(graph, 1, 2, 10);
addEdge(graph, 2, 3, 40);
addEdge(graph, 3, 4, 2);
addEdge(graph, 4, 5, 2);
addEdge(graph, 4, 6, 8);
addEdge(graph, 5, 6, 3);
display(graph, N);
// boolean[] vis = new boolean[N];
// System.out.println(printAllPath(graph, 0, 6, vis, ""));
// preOrder(graph, 0, vis, 0, "");
// heaviestPath(graph, 0, 6);
// printBFSPath(graph, 0);
}
public static void main(String[] args) {
construction();
}
} | Arvind8998/DataStructure-Algorithms-Java | PepCoding/Foundation/Graphs/Graph.java | 4,904 | // 0 : red, 1 : green | line_comment | nl | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Arrays;
public class Graph {
public static class Edge {
int src;
int nbr;
int wt;
Edge(int src, int nbr, int wt) {
this.src = src;
this.nbr = nbr;
this.wt = wt;
}
}
public static void addEdge(ArrayList<Edge>[] graph, int u, int v, int w) {
graph[u].add(new Edge(u, v, w));
graph[v].add(new Edge(v, u, w));
}
public static void display(ArrayList<Edge>[] graph, int N) {
for (int i = 0; i < N; i++) {
System.out.print(i + " -> ");
for (Edge e : graph[i]) {
System.out.print("(" + e.nbr + ", " + e.wt + ") ");
}
System.out.println();
}
}
public static int findEdge(ArrayList<Edge>[] graph, int u, int v) {
ArrayList<Edge> list = graph[u];
for (int i = 0; i < list.size(); i++) {
Edge e = list.get(i);
if (e.nbr == v)
return i;
}
return -1;
}
public static void removeEdge(ArrayList<Edge>[] graph, int u, int v) {
int i1 = findEdge(graph, u, v);
int i2 = findEdge(graph, v, u);
graph[u].remove(i1);
graph[v].remove(i2);
}
public static void removeVtx(ArrayList<Edge>[] graph, int u) {
ArrayList<Edge> list = graph[u];
for (int i = list.size() - 1; i >= 0; i--) {
Edge e = list.get(i);
removeEdge(graph, e.src, e.nbr);
}
}
public static boolean hasPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) {
if (src == dest)
return true;
vis[src] = true;
boolean res = false;
for (Edge e : graph[src])
if (!vis[e.nbr])
res = res || hasPath(graph, e.nbr, dest, vis);
return res;
}
public static int printAllPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis, String psf) {
if (src == dest) {
System.out.println(psf + dest);
return 1;
}
int count = 0;
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
count += printAllPath(graph, e.nbr, dest, vis, psf + src);
}
vis[src] = false;
return count;
}
public static void preOrder(ArrayList<Edge>[] graph, int src, boolean[] vis, int wsf, String psf) {
System.out.println(src + " -> " + (psf + src) + " @ " + wsf);
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
preOrder(graph, e.nbr, vis, wsf + e.wt, psf + src);
}
vis[src] = false;
}
public static void postOrder(ArrayList<Edge>[] graph, int src, boolean[] vis, int wsf, String psf) {
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
postOrder(graph, e.nbr, vis, wsf + e.wt, psf + e.nbr);
}
System.out.println(src + " -> " + psf + " @ " + wsf);
vis[src] = false;
}
public static void lightestPath(ArrayList<Edge>[] graph, int src, int dest) {
// System.out.println("Lightest Path: " + x + " of weight: " + y);
}
public static class pathPair {
String psf = "";
int wsf = -1;
}
public static pathPair heaviestPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) {
if (src == dest) {
pathPair base = new pathPair();
base.psf += src;
base.wsf = 0;
return base;
}
vis[src] = true;
pathPair myAns = new pathPair();
for (Edge e : graph[src]) {
if (!vis[e.nbr]) {
pathPair recAns = heaviestPath(graph, e.nbr, dest, vis);
if (recAns.wsf != -1 && recAns.wsf + e.wt > myAns.wsf) {
myAns.psf = src + recAns.psf;
myAns.wsf = recAns.wsf + e.wt;
}
}
}
vis[src] = false;
return myAns;
}
public static void heaviestPath(ArrayList<Edge>[] graph, int src, int dest) {
boolean[] vis = new boolean[graph.length];
pathPair ans = heaviestPath(graph, src, dest, vis);
System.out.println("Heaviest Path: " + ans.psf + " of weight: " + ans.wsf);
}
public static class ceilFloorPair {
int ceil = (int) 1e9;
int floor = -(int) 1e9;
}
public static void ceilAndFloor(ArrayList<Edge>[] graph, int src, int data, boolean[] vis, int wsf,
ceilFloorPair pair) {
if (wsf > data)
pair.ceil = Math.min(pair.ceil, wsf);
if (wsf < data)
pair.floor = Math.max(pair.floor, wsf);
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr]) {
ceilAndFloor(graph, e.nbr, data, vis, wsf + e.wt, pair);
}
}
vis[src] = false;
}
public static void ceilAndFloor(ArrayList<Edge>[] graph, int src, int data) {
ceilFloorPair pair = new ceilFloorPair();
boolean[] vis = new boolean[graph.length];
ceilAndFloor(graph, src, data, vis, 0, pair);
}
// O(E)
public static void dfs_GCC(ArrayList<Edge>[] graph, int src, boolean[] vis) {
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr])
dfs_GCC(graph, e.nbr, vis);
}
}
// O(E + V);
public static void GCC(ArrayList<Edge>[] graph) {
int N = graph.length, componentCount = 0;
boolean[] vis = new boolean[N];
for (int i = 0; i < N; i++) {
if (!vis[i]) {
dfs_GCC(graph, i, vis);
componentCount++;
}
}
System.out.println(componentCount);
}
public void dfs(char[][] grid, int[][] dir, int sr, int sc) {
grid[sr][sc] = '0';
for (int d = 0; d < 4; d++) {
int r = sr + dir[d][0];
int c = sc + dir[d][1];
if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == '1')
dfs(grid, dir, r, c);
}
}
public int numIslands(char[][] grid) {
int n = grid.length, m = grid[0].length, componentCount = 0;
int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1') {
dfs(grid, dir, i, j);
componentCount++;
}
}
}
return componentCount;
}
public int dfs(int[][] grid, int[][] dir, int sr, int sc) {
grid[sr][sc] = 0;
int size = 0;
for (int d = 0; d < 4; d++) {
int r = sr + dir[d][0];
int c = sc + dir[d][1];
if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == 1)
size += dfs(grid, dir, r, c);
}
return size + 1;
}
public int maxAreaOfIsland(int[][] grid) {
int n = grid.length, m = grid[0].length, maxSize = 0;
int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
int s = dfs(grid, dir, i, j);
maxSize = Math.max(maxSize, s);
}
}
}
return maxSize;
}
public static void hamintonianPathCycle(ArrayList<Edge>[] graph, int osrc, int src, int EdgeCount, boolean[] vis,
String ans) {
if (EdgeCount == graph.length - 1) {
int idx = findEdge(graph, src, osrc);
if (idx != -1) {
System.out.println(ans + src + "*");
} else {
System.out.println(ans + src + ".");
}
return;
}
vis[src] = true;
for (Edge e : graph[src]) {
if (!vis[e.nbr]) {
hamintonianPathCycle(graph, osrc, e.nbr, EdgeCount + 1, vis, ans + src);
}
}
vis[src] = false;
}
public static void hamintonianPathCycle(ArrayList<Edge>[] graph, int src) {
int N = graph.length;
boolean[] vis = new boolean[N];
hamintonianPathCycle(graph, src, src, 0, vis, "");
}
public static void BFS(ArrayList<Edge>[] graph, int src, int dest) {
LinkedList<Integer> que = new LinkedList<>();
int N = graph.length;
boolean[] vis = new boolean[N];
que.addLast(src);
int level = 0;
boolean isCyclePresent = false;
int shortestPath = -1;
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
// for cycle
if (vis[rvtx]) {
isCyclePresent = true;
continue;
}
if (rvtx == dest) {
shortestPath = level;
}
vis[rvtx] = true;
for (Edge e : graph[rvtx]) {
if (!vis[e.nbr]) {
que.addLast(e.nbr);
}
}
}
}
}
public static boolean cycleDetection(ArrayList<Edge>[] graph, int src, boolean[] vis) {
LinkedList<Integer> que = new LinkedList<>();
que.addLast(src);
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
Integer rvtx = que.removeFirst();
if (vis[rvtx])
return true;
vis[rvtx] = true;
for (Edge e : graph[rvtx]) {
if (!vis[e.nbr])
que.addLast(e.nbr);
}
}
}
return false;
}
public static void cycleDetection(ArrayList<Edge>[] graph) {
int vtces = graph.length;
boolean[] vis = new boolean[vtces];
boolean res = false;
for (int i = 0; i < vtces; i++) {
if (!vis[i])
res = res || cycleDetection(graph, i, vis);
}
System.out.println(res);
}
public static class BFS_Pair {
int vtx = 0;
String psf = "";
int wsf = 0;
public BFS_Pair(int vtx, String psf, int wsf) {
this.vtx = vtx;
this.psf = psf;
this.wsf = wsf;
}
}
public static void printBFSPath(ArrayList<Edge>[] graph, int src) {
int vtces = graph.length;
boolean[] vis = new boolean[vtces];
LinkedList<BFS_Pair> que = new LinkedList<>();
que.addLast(new BFS_Pair(src, src + "", 0));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
BFS_Pair rp = que.removeFirst();
if (vis[rp.vtx])
continue;
System.out.println(rp.vtx + " -> " + rp.psf + " @ " + rp.wsf);
vis[rp.vtx] = true;
for (Edge e : graph[rp.vtx]) {
if (!vis[e.nbr])
que.addLast(new BFS_Pair(e.nbr, rp.psf + e.nbr, rp.wsf + e.wt));
}
}
}
}
public static int spreadInfection(ArrayList<Edge>[] graph, int infectedPerson, int NoOfDays) {
LinkedList<Integer> que = new LinkedList<>();
boolean[] vis = new boolean[graph.length];
que.addLast(infectedPerson);
int infectedCount = 0, day = 1;
while (que.size() != 0) {
int size = que.size();
if (day > NoOfDays)
break;
while (size-- > 0) {
int ip = que.removeFirst(); // infectedPerson
if (vis[ip])
continue;
vis[ip] = true;
infectedCount++;
for (Edge e : graph[ip]) {
if (!vis[e.nbr])
que.addLast(e.nbr);
}
}
day++;
}
return infectedCount;
}
public static boolean bipartite(ArrayList<Edge>[] graph, int src, int[] vis) {
LinkedList<Integer> que = new LinkedList<>();
que.addLast(src);
int color = 0; // 0 :<SUF>
boolean cycle = false, isBipartite = true;
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
if (vis[rvtx] != -1) { // cycle
cycle = true;
if (vis[rvtx] != color) { // conflict
isBipartite = false;
break;
}
continue; // not any kind oo conflict
}
vis[rvtx] = color;
for (Edge e : graph[rvtx]) {
if (vis[e.nbr] == -1) {
que.addLast(e.nbr);
}
}
}
color = (color + 1) % 2;
if (!isBipartite)
break;
}
if (cycle) {
if (isBipartite)
System.out.println("Even Length Cycle");
else
System.out.println("Odd Length Cycle");
} else if (isBipartite && !cycle) {
System.out.println("A-Cycle and Bipartite graph");
}
return isBipartite;
}
public static void bipartite(ArrayList<Edge>[] graph) {
int N = graph.length;
int[] vis = new int[N];
Arrays.fill(vis, -1);
boolean isBipartite = true;
for (int i = 0; i < N; i++) {
if (vis[i] == -1) {
isBipartite = isBipartite && bipartite(graph, i, vis);
}
}
System.out.println("Overall Graph is Bipartite: " + isBipartite);
}
public static void construction() {
int N = 7;
ArrayList<Edge>[] graph = new ArrayList[N];
for (int i = 0; i < N; i++)
graph[i] = new ArrayList<>();
addEdge(graph, 0, 1, 10);
addEdge(graph, 0, 3, 10);
addEdge(graph, 1, 2, 10);
addEdge(graph, 2, 3, 40);
addEdge(graph, 3, 4, 2);
addEdge(graph, 4, 5, 2);
addEdge(graph, 4, 6, 8);
addEdge(graph, 5, 6, 3);
display(graph, N);
// boolean[] vis = new boolean[N];
// System.out.println(printAllPath(graph, 0, 6, vis, ""));
// preOrder(graph, 0, vis, 0, "");
// heaviestPath(graph, 0, 6);
// printBFSPath(graph, 0);
}
public static void main(String[] args) {
construction();
}
} |
11540_1 | package View;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import Controller.PersonController;
import Person.Person;
// ik wou eerst met twee pannels in dit frame werken, en het ene panel verwijderen om de andere erover te plakken,
// maar dan zit ik weer met hetzelfde probleem als in onze startpagina, dat de pannel pas getoont werd vanaf er
// met de size geslepen wordt dus heb gewoon terug een nieuw frame gemaakt :(
public class UserChoiceFrame extends JFrame{
private GridBagConstraints c;
private PersonController pc;
JPanel userChoicePanel;
public UserChoiceFrame(PersonController pc) {
super("Choose user to edit");
this.c = new GridBagConstraints();
this.pc = pc;
this.userChoicePanel = new JPanel();
this.userChoicePanel.setSize(new Dimension(400,200));
setSize(400, 200);
setLocation(500, 10);
setLayout(new GridBagLayout());
setVisible(true);
this.c.fill = GridBagConstraints.HORIZONTAL;
this.c.weightx = 2.0;
this.c.weighty = 2.0;
getContentPane().add(this.userChoicePanel);
this.makeUserButtons();
}
public void makeUserButtons() {
for (Person user : this.pc.getAllPerson().values()) {
JButton button = new JButton(user.getName());
button.setName(user.getName());
this.userChoicePanel.add(button,c);
button.addActionListener(l -> {
System.out.println("\nEditing: " + button.getName());
this.dispose();
new UserEditFrame(this.pc, button.getName());
});
}
}
}
| Arvocant/5-Software-Design-Project | src/main/View/UserChoiceFrame.java | 506 | // maar dan zit ik weer met hetzelfde probleem als in onze startpagina, dat de pannel pas getoont werd vanaf er | line_comment | nl | package View;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import Controller.PersonController;
import Person.Person;
// ik wou eerst met twee pannels in dit frame werken, en het ene panel verwijderen om de andere erover te plakken,
// maar dan<SUF>
// met de size geslepen wordt dus heb gewoon terug een nieuw frame gemaakt :(
public class UserChoiceFrame extends JFrame{
private GridBagConstraints c;
private PersonController pc;
JPanel userChoicePanel;
public UserChoiceFrame(PersonController pc) {
super("Choose user to edit");
this.c = new GridBagConstraints();
this.pc = pc;
this.userChoicePanel = new JPanel();
this.userChoicePanel.setSize(new Dimension(400,200));
setSize(400, 200);
setLocation(500, 10);
setLayout(new GridBagLayout());
setVisible(true);
this.c.fill = GridBagConstraints.HORIZONTAL;
this.c.weightx = 2.0;
this.c.weighty = 2.0;
getContentPane().add(this.userChoicePanel);
this.makeUserButtons();
}
public void makeUserButtons() {
for (Person user : this.pc.getAllPerson().values()) {
JButton button = new JButton(user.getName());
button.setName(user.getName());
this.userChoicePanel.add(button,c);
button.addActionListener(l -> {
System.out.println("\nEditing: " + button.getName());
this.dispose();
new UserEditFrame(this.pc, button.getName());
});
}
}
}
|
142652_3 | /*
* Engine Alpha ist eine anfängerorientierte 2D-Gaming Engine.
*
* Copyright (c) 2011 - 2014 Michael Andonie and contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ea;
import ea.internal.collision.Collider;
import ea.internal.gui.Fenster;
import ea.internal.util.Logger;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Zur Darstellung von Texten im Programmbildschirm.
* <p/>
* TODO: Review der ganzen Klasse (v.a. der Dokumentation)
*
* @author Michael Andonie
*/
public class Text extends Raum implements Leuchtend {
private static final long serialVersionUID = -2145724725115670955L;
/**
* Ein Feld aller existenten Fonts, die im Hauptprojektordner gespeichert sind.<br /> Macht das
* interne verwenden dieser Fonts moeglich, ohne das Vorhandensein der Fonts in den
* Computerressourcen selber zur Voraussetzung zu haben.
*/
private static Font[] eigene;
/**
* static-Konstruktor.<br />
* hier werden die externen Fonts geladen.
*/
static {
ArrayList<File> alleFonts = new ArrayList<>();
fontsEinbauen(alleFonts, new File(System.getProperty("user.dir")));
File[] unter = alleFonts.toArray(new File[alleFonts.size()]);
eigene = new Font[unter.length];
for (int i = 0; i < unter.length; i++) {
try {
FileInputStream s = new FileInputStream(unter[i]);
eigene[i] = Font.createFont(Font.TRUETYPE_FONT, s);
s.close();
} catch (FileNotFoundException e) {
Logger.error("Interner Lesefehler. Dies hätte unter keinen Umständen passieren dürfen.");
} catch (FontFormatException e) {
Logger.error("Das TrueType-Font-Format einer Datei (" + unter[i].getPath() + ") war nicht einlesbar!");
} catch (IOException e) {
Logger.error("Lesefehler beim Laden der eigenen Fonts! Zugriffsrechte überprüfen.");
}
}
}
/**
* Die Schriftgröße des Textes
*/
protected int groesse;
/**
* Die Schriftart (<b>fett, kursiv, oder fett & kursiv</b>).<br /> Dies wird dargestellt als
* int.Wert:<br /> 0: Normaler Text<br /> 1: Fett<br /> 2: Kursiv<br /> 3: Fett & Kursiv
*/
protected int schriftart;
/**
* Der Wert des Textes.
*/
protected String inhalt;
/**
* Der Font der Darstellung
*/
protected Font font;
/**
* Die Farbe, in der der Text dargestellt wird.
*/
protected Color farbe;
/**
* Referenz auf die Farbe, die vor dem leuchten da war (zum wiederherstellen)
*/
private Color alte;
/**
* Gibt an, ob dieser Text gerade leuchtet
*/
private boolean leuchtet = false;
/**
* Der Zaehler fuer die Leuchtanimation
*/
private int leuchtzaehler;
/**
* Textanker: links, mittig oder rechts
*/
private Anker anker = Anker.LINKS;
/**
* Ebenefalls ein vereinfachter Konstruktor. Hierbei ist die Farbe "Weiss" und der Text weder
* kursiv noch fett; weiterhin ist die Schriftgroesse automatisch 24.
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param fontName
* Der Name des zu verwendenden Fonts.<br /> Wird hierfuer ein Font verwendet, der in dem
* Projektordner vorhanden sein soll, <b>und dies ist immer und in jedem Fall zu
* empfehlen</b>, muss der Name der Schriftart hier ebenfalls einfach nur eingegeben werden,
* <b>nicht der Name der schriftart-Datei!!!!!!!!!!!!!!!!!!!!!!!!</b>
*/
public Text (String inhalt, float x, float y, String fontName) {
this(inhalt, x, y, fontName, 24);
}
/**
* Konstruktor ohne Farb- und sonderartseingabezwang. In diesem Fall ist die Farbe "Weiss" und
* der Text weder kursiv noch fett.
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param fontName
* Der Name des zu verwendenden Fonts.<br /> Wird hierfuer ein Font verwendet, der in dem
* Projektordner vorhanden sein soll, <b>und dies ist immer und in jedem Fall zu
* empfehlen</b>, muss der Name der Schriftart hier ebenfalls einfach nur eingegeben werden.
* @param schriftGroesse
* Die Groesse, in der die Schrift dargestellt werden soll
*/
public Text (String inhalt, float x, float y, String fontName, int schriftGroesse) {
this(inhalt, x, y, fontName, schriftGroesse, 0, "Weiss");
}
/**
* Konstruktor für Objekte der Klasse Text<br /> Möglich ist es auch, Fonts zu laden, die im
* Projektordner sind. Diese werden zu Anfang einmalig geladen und stehen dauerhaft zur
* Verfügung.
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param fontName
* Der Name des zu verwendenden Fonts.<br /> Wird hierfuer ein Font verwendet, der in dem
* Projektordner vorhanden sein soll, <b>und dies ist immer und in jedem Fall zu
* empfehlen</b>, muss der Name der Schriftart hier ebenfalls einfach nur eingegeben werden,
* <b>nicht der Name der schriftart-Datei!</b>
* @param schriftGroesse
* Die Groesse, in der die Schrift dargestellt werden soll
* @param schriftart
* Die Schriftart dieses Textes. Folgende Werte entsprechen folgendem:<br /> 0: Normaler
* Text<br /> 1: Fett<br /> 2: Kursiv<br /> 3: Fett & Kursiv <br /> <br /> Alles andere sorgt
* nur fuer einen normalen Text.
* @param farbe
* Die Farbe, die für den Text benutzt werden soll.
*/
public Text (String inhalt, float x, float y, String fontName, int schriftGroesse, int schriftart, String farbe) {
this.inhalt = inhalt;
this.position = new Punkt(x, y);
this.groesse = schriftGroesse;
this.farbe = zuFarbeKonvertieren(farbe);
if (schriftart >= 0 && schriftart <= 3) {
this.schriftart = schriftart;
} else {
this.schriftart = 0;
}
setzeFont(fontName);
super.leuchterAnmelden(this);
}
/**
* Setzt einen neuen Font fuer den Text
*
* @param fontName
* Der Name des neuen Fonts fuer den Text
*/
public void setzeFont (String fontName) {
Font base = null;
for (int i = 0; i < eigene.length; i++) {
if (eigene[i].getName().equals(fontName)) {
base = eigene[i];
break;
}
}
if (base != null) {
this.font = base.deriveFont(schriftart, groesse);
} else {
if (!Manager.fontExistiert(fontName)) {
fontName = "SansSerif";
Logger.error("Achtung! Die gewuenschte Schriftart existiert nicht im Font-Verzeichnis dieses PC! " + "Wurde der Name falsch geschrieben? Oder existiert der Font nicht?");
}
this.font = new Font(fontName, schriftart, groesse);
}
}
/**
* Einfacherer Konstruktor.<br /> Hierbei wird automatisch die Schriftart auf eine
* Standartmaessige gesetzt
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param schriftGroesse
* Die Groesse, in der die Schrift dargestellt werden soll
*/
public Text (String inhalt, float x, float y, int schriftGroesse) {
this(inhalt, x, y, "SansSerif", schriftGroesse, 0, "Weiss");
}
/**
* Ein vereinfachter Konstruktor.<br /> Hierbei wird eine Standartschriftart, die Farbe weiss
* und eine Groesse von 24 gewaehlt.
*
* @param inhalt
* Der Inhalt des Textes
* @param x
* X-Koordinate
* @param y
* Y-Koordinate
*/
public Text (String inhalt, float x, float y) {
this(inhalt, x, y, "SansSerif", 24, 0, "Weiss");
}
/**
* Ein vereinfachter parallerer Konstruktor.<br /> Diesen gibt es inhaltlich genauso bereits,
* jedoch sind hier die Argumente vertauscht; dies dient der Praevention undgewollter falscher
* Konstruktorenaufrufe. Hierbei wird eine Standartschriftart, die Farbe weiss und eine Groesse
* von 24 gewaehlt.
*
* @param inhalt
* Der Inhalt des Textes
* @param x
* X-Koordinate
* @param y
* Y-Koordinate
*/
public Text (float x, float y, String inhalt) {
this(inhalt, x, y, "SansSerif", 24, 0, "Weiss");
}
/**
* Ein vereinfachter parallerer Konstruktor.<br /> Diesen gibt es inhaltlich genauso bereits,
* jedoch sind hier die Argumente vertauscht; dies dient der Praevention undgewollter falscher
* Konstruktorenaufrufe. Hierbei wird eine Standartschriftart und die Farbe weiss gewaehlt.
*
* @param inhalt
* Der Inhalt des Textes
* @param x
* X-Koordinate
* @param y
* Y-Koordinate
* @param schriftGroesse
* Die Schriftgroesse, die der Text haben soll
*/
public Text (int x, int y, int schriftGroesse, String inhalt) {
this(inhalt, x, y, "SansSerif", schriftGroesse, 0, "Weiss");
} // TODO: Mehr Verwirrung als Hilfe?
private static void fontsEinbauen (final ArrayList<File> liste, File akt) {
File[] files = akt.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].equals(akt)) {
Logger.error("Das Sub-Directory war das Directory selbst. Das darf nicht passieren!");
continue;
}
if (files[i].isDirectory()) {
fontsEinbauen(liste, files[i]);
}
if (files[i].getName().toLowerCase().endsWith(".ttf")) {
liste.add(files[i]);
}
}
}
}
/**
* TODO: Dokumentation
*/
public static Font holeFont (String fontName) {
Font base = null;
for (int i = 0; i < eigene.length; i++) {
if (eigene[i].getName().equals(fontName)) {
base = eigene[i];
break;
}
}
if (base != null) {
return base;
} else {
if (!Manager.fontExistiert(fontName)) {
fontName = "SansSerif";
Logger.error("Achtung! Die gewuenschte Schriftart existiert weder als geladene Sonderdatei noch im Font-Verzeichnis dieses PC! " + "Wurde der Name falsch geschrieben? Oder existiert der Font nicht?");
}
return new Font(fontName, 0, 12);
}
}
/**
* Sehr wichtige Methode!<br /> Diese Methode liefert als Protokoll an die Konsole alle Namen,
* mit denen die aus dem Projektordner geladenen ".ttf"-Fontdateien gewaehlt werden koennen.<br
* /> Diese Namen werden als <code>String</code>-Argument erwartet, wenn die eigens eingebauten
* Fontarten verwendet werden sollen.<br /> Der Aufruf dieser Methode wird <b>UMGEHEND</b>
* empfohlen, nach dem alle zu verwendenden Arten im Projektordner liegen, denn nur unter dem an
* die Konsole projezierten Namen <b>koennen diese ueberhaupt verwendet werden</b>!!<br /> Daher
* dient diese Methode der Praevention von Verwirrung, wegen "nicht darstellbarer" Fonts.
*/
public static void geladeneSchriftartenAusgeben () {
Logger.info("Protokoll aller aus dem Projektordner geladener Fontdateien");
if (eigene.length == 0) {
Logger.info("Es wurden keine \".ttf\"-Dateien im Projektordner gefunden");
} else {
Logger.info("Es wurden " + eigene.length + " \".ttf\"-Dateien im Projektordner gefunden.");
Logger.info("Diese sind unter folgenden Namen abrufbar:");
for (Font font : eigene) {
Logger.info(font.getName());
}
}
}
/**
* Setzt den Inhalt des Textes.<br /> Parallele Methode zu <code>setzeInhalt()</code>
*
* @param inhalt
* Der neue Inhalt des Textes
*
* @see #setzeInhalt(String)
*/
public void inhaltSetzen (String inhalt) {
setzeInhalt(inhalt);
}
/**
* Setzt den Inhalt des Textes.
*
* @param inhalt
* Der neue Inhalt des Textes
*/
public void setzeInhalt (String inhalt) {
this.inhalt = inhalt;
}
/**
* Setzt die Schriftart.
*
* @param art
* Die Repraesentation der Schriftart als Zahl:<br/> 0: Normaler Text<br /> 1: Fett<br /> 2:
* Kursiv<br /> 3: Fett & Kursiv<br /> <br /> Ist die Eingabe nicht eine dieser 4 Zahlen, so
* wird nichts geaendert.<br /> Parallele Methode zu <code>setzeSchriftart()</code>
*
* @see #setzeSchriftart(int)
*/
public void schriftartSetzen (int art) {
setzeSchriftart(art);
}
/**
* Setzt die Schriftart.
*
* @param art
* Die Repraesentation der Schriftart als Zahl:<br/> 0: Normaler Text<br /> 1: Fett<br /> 2:
* Kursiv<br /> 3: Fett & Kursiv<br /> <br /> Ist die Eingabe nicht eine dieser 4 Zahlen, so
* wird nichts geaendert.
*/
public void setzeSchriftart (int art) {
if (art >= 0 && art <= 3) {
schriftart = art;
aktualisieren();
}
}
/**
* Klasseninterne Methode zum aktualisieren des Font-Objektes
*/
private void aktualisieren () {
this.font = this.font.deriveFont(schriftart, groesse);
}
/**
* Setzt die Fuellfarbe<br /> Parallele Methode zu <code>setzeFarbe()</code>
*
* @param farbe
* Der Name der neuen Fuellfarbe
*
* @see #setzeFarbe(String)
* @see #farbeSetzen(Farbe)
*/
public void farbeSetzen (String farbe) {
setzeFarbe(farbe);
}
/**
* Setzt die Fuellfarbe
*
* @param farbe
* Der Name der neuen Fuellfarbe
*/
public void setzeFarbe (String farbe) {
this.setzeFarbe(zuFarbeKonvertieren(farbe));
}
/**
* Setzt die Fuellfarbe
*
* @param c
* Die neue Fuellfarbe
*/
public void setzeFarbe (Color c) {
farbe = c;
aktualisieren();
}
/**
* Setzt die Fuellfarbe
*
* @param f
* Das Farbe-Objekt, das die neue Fuellfarbe beschreibt
*
* @see #farbeSetzen(String)
*/
public void farbeSetzen (Farbe f) {
setzeFarbe(f.wert());
}
/**
* Setzt die Schriftgroesse.<br /> Wrappt hierbei die Methode <code>setzeGroesse</code>.
*
* @param groesse
* Die neue Schriftgroesse
*
* @see #setzeGroesse(int)
*/
public void groesseSetzen (int groesse) {
setzeGroesse(groesse);
}
/**
* Setzt die Schriftgroesse
*
* @param groesse
* Die neue Schriftgroesse
*/
public void setzeGroesse (int groesse) {
this.groesse = groesse;
aktualisieren();
}
/**
* Diese Methode gibt die aktuelle Groesse des Textes aus
*
* @return Die aktuelle Schriftgroesse des Textes
*
* @see #groesseSetzen(int)
*/
public int groesse () {
return groesse;
}
/**
* Setzt einen neuen Font fuer den Text.<br /> Parallele Methode zu <code>setzeFont()</code>
*
* @param name
* Der Name des neuen Fonts fuer den Text
*
* @see #setzeFont(String)
*/
public void fontSetzen (String name) {
setzeFont(name);
}
/**
* Zeichnet das Objekt.
*
* @param g
* Das zeichnende Graphics-Objekt
* @param r
* Das BoundingRechteck, dass die Kameraperspektive Repraesentiert.<br /> Hierbei soll
* zunaechst getestet werden, ob das Objekt innerhalb der Kamera liegt, und erst dann
* gezeichnet werden.
*/
@Override
public void zeichnen (Graphics2D g, BoundingRechteck r) {
if (!r.schneidetBasic(this.dimension())) {
return;
}
super.beforeRender(g, r);
FontMetrics f = Fenster.metrik(font);
float x = position.x, y = position.y;
if (anker == Anker.MITTE) {
x = position.x - f.stringWidth(inhalt) / 2;
} else if (anker == Anker.RECHTS) {
x = position.x - f.stringWidth(inhalt);
}
g.setColor(farbe);
g.setFont(font);
g.drawString(inhalt, (int) (x - r.x), (int) (y - r.y + groesse));
super.afterRender(g, r);
}
/**
* @return Ein BoundingRechteck mit dem minimal noetigen Umfang, um das Objekt <b>voll
* einzuschliessen</b>.
*/
@Override
public BoundingRechteck dimension () {
FontMetrics f = Fenster.metrik(font);
float x = position.x, y = position.y;
if (anker == Anker.MITTE) {
x = position.x - f.stringWidth(inhalt) / 2;
} else if (anker == Anker.RECHTS) {
x = position.x - f.stringWidth(inhalt);
}
return new BoundingRechteck(x, y, f.stringWidth(inhalt), f.getHeight());
}
/**
* {@inheritDoc} Collider wird direkt aus dem das <code>Raum</code>-Objekt umfassenden
* <code>BoundingRechteck</code> erzeugt, dass über die <code>dimension()</code>-Methode
* berechnet wird.
*/
@Override
public Collider erzeugeCollider () {
return erzeugeLazyCollider();
}
/**
* Diese Methode loescht alle eventuell vorhandenen Referenzen innerhalb der Engine auf dieses
* Objekt, damit es problemlos geloescht werden kann.<br /> <b>Achtung:</b> zwar werden
* hierdurch alle Referenzen geloescht, die <b>nur innerhalb</b> der Engine liegen (dies
* betrifft vor allem Animationen etc), jedoch nicht die innerhalb eines
* <code>Knoten</code>-Objektes!!!!!!!!!<br /> Das heisst, wenn das Objekt an einem Knoten liegt
* (was <b>immer der Fall ist, wenn es auch gezeichnet wird (siehe die Wurzel des
* Fensters)</b>), muss es trotzdem selbst geloescht werden, <b>dies erledigt diese Methode
* nicht!!</b>.<br /> Diese Klasse ueberschreibt die Methode wegen des Leuchtens.
*/
@Override
public void loeschen () {
super.leuchterAbmelden(this);
super.loeschen();
}
/**
* Setzt, ob dieses Leuchtend-Objekt leuchten soll.<br /> Ist dies der Fall, so werden immer
* wieder schnell dessen Farben geaendert; so entsteht ein Leuchteffekt.
*
* @param leuchtet
* Ob dieses Objekt nun leuchten soll oder nicht (mehr).<br /> <b>Achtung:</b> Die
* Leuchtfunktion kann bei bestimmten Klassen sehr psychadelisch und aufreizend wirken! Daher
* sollte sie immer mit Bedacht und in Nuancen verwendet werden!
*/
@Override
public void leuchtetSetzen (boolean leuchtet) {
if (this.leuchtet == leuchtet) {
return;
}
this.leuchtet = leuchtet;
if (leuchtet) {
alte = farbe;
} else {
this.setzeFarbe(alte);
}
}
/**
* Fuehrt einen Leuchtschritt aus.<br /> Dies heisst, dass in dieser Methode die Farbe einfach
* gewechselt wird. Da diese Methode schnell und oft hintereinander ausgefuehrt wird, soll so
* der Leuchteffekt entstehen.<br /> <b>Diese Methode sollte nur innerhalb der Engine
* ausgefuehrt werden! Also nicht fuer den Entwickler gedacht.</b>
*/
@Override
public void leuchtSchritt () {
leuchtzaehler++;
leuchtzaehler %= farbzyklus.length;
this.setzeFarbe(farbzyklus[leuchtzaehler]);
}
/**
* Gibt wieder, ob das Leuchtet-Objekt gerade leuchtet oder nicht.
*
* @return <code>true</code>, wenn das Objekt gerade leuchtet, wenn nicht, dann ist die
* Rueckgabe <code>false</code>
*/
@Override
public boolean leuchtet () {
return this.leuchtet;
}
/**
* Gibt den aktuellen Textinhalt zurück.
*
* @return aktueller Textinhalt
*/
public String gibInhalt () {
return inhalt;
}
/**
* Gibt den aktuellen Anker zurück.
*
* @return aktueller Anker
*
* @see ea.Text.Anker
* @see #setAnker(ea.Text.Anker)
*/
public Anker getAnker () {
return anker;
}
/**
* Setzt den Textanker. Dies beschreibt, wo sich der Text relativ zur x-Koordinate befindet.
* Möglich sind: <li>{@code Text.Anker.LINKS},</li> <li>{@code Text.Anker.MITTE},</li>
* <li>{@code Text.Anker.RECHTS}.</li> <br> <b>Hinweis</b>: {@code null} wird wie {@code
* Anker.LINKS} behandelt!
*
* @param anker
* neuer Anker
*
* @see ea.Text.Anker
* @see #getAnker()
*/
public void setAnker (Anker anker) {
this.anker = anker;
}
/**
* Ein Textanker beschreibt, wo sich der Text relativ zu seiner x-Koordinate befindet. Möglich
* sind: <li>{@code Anker.LINKS},</li> <li>{@code Anker.MITTE},</li> <li>{@code
* Anker.RECHTS}.</li>
*
* @see #setAnker(ea.Text.Anker)
* @see #getAnker()
*/
public enum Anker {
LINKS, MITTE, RECHTS
}
}
| Asecave/engine-alpha | src/ea/Text.java | 7,314 | /**
* static-Konstruktor.<br />
* hier werden die externen Fonts geladen.
*/ | block_comment | nl | /*
* Engine Alpha ist eine anfängerorientierte 2D-Gaming Engine.
*
* Copyright (c) 2011 - 2014 Michael Andonie and contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ea;
import ea.internal.collision.Collider;
import ea.internal.gui.Fenster;
import ea.internal.util.Logger;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Zur Darstellung von Texten im Programmbildschirm.
* <p/>
* TODO: Review der ganzen Klasse (v.a. der Dokumentation)
*
* @author Michael Andonie
*/
public class Text extends Raum implements Leuchtend {
private static final long serialVersionUID = -2145724725115670955L;
/**
* Ein Feld aller existenten Fonts, die im Hauptprojektordner gespeichert sind.<br /> Macht das
* interne verwenden dieser Fonts moeglich, ohne das Vorhandensein der Fonts in den
* Computerressourcen selber zur Voraussetzung zu haben.
*/
private static Font[] eigene;
/**
* static-Konstruktor.<br />
<SUF>*/
static {
ArrayList<File> alleFonts = new ArrayList<>();
fontsEinbauen(alleFonts, new File(System.getProperty("user.dir")));
File[] unter = alleFonts.toArray(new File[alleFonts.size()]);
eigene = new Font[unter.length];
for (int i = 0; i < unter.length; i++) {
try {
FileInputStream s = new FileInputStream(unter[i]);
eigene[i] = Font.createFont(Font.TRUETYPE_FONT, s);
s.close();
} catch (FileNotFoundException e) {
Logger.error("Interner Lesefehler. Dies hätte unter keinen Umständen passieren dürfen.");
} catch (FontFormatException e) {
Logger.error("Das TrueType-Font-Format einer Datei (" + unter[i].getPath() + ") war nicht einlesbar!");
} catch (IOException e) {
Logger.error("Lesefehler beim Laden der eigenen Fonts! Zugriffsrechte überprüfen.");
}
}
}
/**
* Die Schriftgröße des Textes
*/
protected int groesse;
/**
* Die Schriftart (<b>fett, kursiv, oder fett & kursiv</b>).<br /> Dies wird dargestellt als
* int.Wert:<br /> 0: Normaler Text<br /> 1: Fett<br /> 2: Kursiv<br /> 3: Fett & Kursiv
*/
protected int schriftart;
/**
* Der Wert des Textes.
*/
protected String inhalt;
/**
* Der Font der Darstellung
*/
protected Font font;
/**
* Die Farbe, in der der Text dargestellt wird.
*/
protected Color farbe;
/**
* Referenz auf die Farbe, die vor dem leuchten da war (zum wiederherstellen)
*/
private Color alte;
/**
* Gibt an, ob dieser Text gerade leuchtet
*/
private boolean leuchtet = false;
/**
* Der Zaehler fuer die Leuchtanimation
*/
private int leuchtzaehler;
/**
* Textanker: links, mittig oder rechts
*/
private Anker anker = Anker.LINKS;
/**
* Ebenefalls ein vereinfachter Konstruktor. Hierbei ist die Farbe "Weiss" und der Text weder
* kursiv noch fett; weiterhin ist die Schriftgroesse automatisch 24.
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param fontName
* Der Name des zu verwendenden Fonts.<br /> Wird hierfuer ein Font verwendet, der in dem
* Projektordner vorhanden sein soll, <b>und dies ist immer und in jedem Fall zu
* empfehlen</b>, muss der Name der Schriftart hier ebenfalls einfach nur eingegeben werden,
* <b>nicht der Name der schriftart-Datei!!!!!!!!!!!!!!!!!!!!!!!!</b>
*/
public Text (String inhalt, float x, float y, String fontName) {
this(inhalt, x, y, fontName, 24);
}
/**
* Konstruktor ohne Farb- und sonderartseingabezwang. In diesem Fall ist die Farbe "Weiss" und
* der Text weder kursiv noch fett.
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param fontName
* Der Name des zu verwendenden Fonts.<br /> Wird hierfuer ein Font verwendet, der in dem
* Projektordner vorhanden sein soll, <b>und dies ist immer und in jedem Fall zu
* empfehlen</b>, muss der Name der Schriftart hier ebenfalls einfach nur eingegeben werden.
* @param schriftGroesse
* Die Groesse, in der die Schrift dargestellt werden soll
*/
public Text (String inhalt, float x, float y, String fontName, int schriftGroesse) {
this(inhalt, x, y, fontName, schriftGroesse, 0, "Weiss");
}
/**
* Konstruktor für Objekte der Klasse Text<br /> Möglich ist es auch, Fonts zu laden, die im
* Projektordner sind. Diese werden zu Anfang einmalig geladen und stehen dauerhaft zur
* Verfügung.
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param fontName
* Der Name des zu verwendenden Fonts.<br /> Wird hierfuer ein Font verwendet, der in dem
* Projektordner vorhanden sein soll, <b>und dies ist immer und in jedem Fall zu
* empfehlen</b>, muss der Name der Schriftart hier ebenfalls einfach nur eingegeben werden,
* <b>nicht der Name der schriftart-Datei!</b>
* @param schriftGroesse
* Die Groesse, in der die Schrift dargestellt werden soll
* @param schriftart
* Die Schriftart dieses Textes. Folgende Werte entsprechen folgendem:<br /> 0: Normaler
* Text<br /> 1: Fett<br /> 2: Kursiv<br /> 3: Fett & Kursiv <br /> <br /> Alles andere sorgt
* nur fuer einen normalen Text.
* @param farbe
* Die Farbe, die für den Text benutzt werden soll.
*/
public Text (String inhalt, float x, float y, String fontName, int schriftGroesse, int schriftart, String farbe) {
this.inhalt = inhalt;
this.position = new Punkt(x, y);
this.groesse = schriftGroesse;
this.farbe = zuFarbeKonvertieren(farbe);
if (schriftart >= 0 && schriftart <= 3) {
this.schriftart = schriftart;
} else {
this.schriftart = 0;
}
setzeFont(fontName);
super.leuchterAnmelden(this);
}
/**
* Setzt einen neuen Font fuer den Text
*
* @param fontName
* Der Name des neuen Fonts fuer den Text
*/
public void setzeFont (String fontName) {
Font base = null;
for (int i = 0; i < eigene.length; i++) {
if (eigene[i].getName().equals(fontName)) {
base = eigene[i];
break;
}
}
if (base != null) {
this.font = base.deriveFont(schriftart, groesse);
} else {
if (!Manager.fontExistiert(fontName)) {
fontName = "SansSerif";
Logger.error("Achtung! Die gewuenschte Schriftart existiert nicht im Font-Verzeichnis dieses PC! " + "Wurde der Name falsch geschrieben? Oder existiert der Font nicht?");
}
this.font = new Font(fontName, schriftart, groesse);
}
}
/**
* Einfacherer Konstruktor.<br /> Hierbei wird automatisch die Schriftart auf eine
* Standartmaessige gesetzt
*
* @param inhalt
* Die Zeichenkette, die dargestellt werden soll
* @param x
* Die X-Koordinate des Anfangs
* @param y
* Die Y-Koordinate des Anfangs
* @param schriftGroesse
* Die Groesse, in der die Schrift dargestellt werden soll
*/
public Text (String inhalt, float x, float y, int schriftGroesse) {
this(inhalt, x, y, "SansSerif", schriftGroesse, 0, "Weiss");
}
/**
* Ein vereinfachter Konstruktor.<br /> Hierbei wird eine Standartschriftart, die Farbe weiss
* und eine Groesse von 24 gewaehlt.
*
* @param inhalt
* Der Inhalt des Textes
* @param x
* X-Koordinate
* @param y
* Y-Koordinate
*/
public Text (String inhalt, float x, float y) {
this(inhalt, x, y, "SansSerif", 24, 0, "Weiss");
}
/**
* Ein vereinfachter parallerer Konstruktor.<br /> Diesen gibt es inhaltlich genauso bereits,
* jedoch sind hier die Argumente vertauscht; dies dient der Praevention undgewollter falscher
* Konstruktorenaufrufe. Hierbei wird eine Standartschriftart, die Farbe weiss und eine Groesse
* von 24 gewaehlt.
*
* @param inhalt
* Der Inhalt des Textes
* @param x
* X-Koordinate
* @param y
* Y-Koordinate
*/
public Text (float x, float y, String inhalt) {
this(inhalt, x, y, "SansSerif", 24, 0, "Weiss");
}
/**
* Ein vereinfachter parallerer Konstruktor.<br /> Diesen gibt es inhaltlich genauso bereits,
* jedoch sind hier die Argumente vertauscht; dies dient der Praevention undgewollter falscher
* Konstruktorenaufrufe. Hierbei wird eine Standartschriftart und die Farbe weiss gewaehlt.
*
* @param inhalt
* Der Inhalt des Textes
* @param x
* X-Koordinate
* @param y
* Y-Koordinate
* @param schriftGroesse
* Die Schriftgroesse, die der Text haben soll
*/
public Text (int x, int y, int schriftGroesse, String inhalt) {
this(inhalt, x, y, "SansSerif", schriftGroesse, 0, "Weiss");
} // TODO: Mehr Verwirrung als Hilfe?
private static void fontsEinbauen (final ArrayList<File> liste, File akt) {
File[] files = akt.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].equals(akt)) {
Logger.error("Das Sub-Directory war das Directory selbst. Das darf nicht passieren!");
continue;
}
if (files[i].isDirectory()) {
fontsEinbauen(liste, files[i]);
}
if (files[i].getName().toLowerCase().endsWith(".ttf")) {
liste.add(files[i]);
}
}
}
}
/**
* TODO: Dokumentation
*/
public static Font holeFont (String fontName) {
Font base = null;
for (int i = 0; i < eigene.length; i++) {
if (eigene[i].getName().equals(fontName)) {
base = eigene[i];
break;
}
}
if (base != null) {
return base;
} else {
if (!Manager.fontExistiert(fontName)) {
fontName = "SansSerif";
Logger.error("Achtung! Die gewuenschte Schriftart existiert weder als geladene Sonderdatei noch im Font-Verzeichnis dieses PC! " + "Wurde der Name falsch geschrieben? Oder existiert der Font nicht?");
}
return new Font(fontName, 0, 12);
}
}
/**
* Sehr wichtige Methode!<br /> Diese Methode liefert als Protokoll an die Konsole alle Namen,
* mit denen die aus dem Projektordner geladenen ".ttf"-Fontdateien gewaehlt werden koennen.<br
* /> Diese Namen werden als <code>String</code>-Argument erwartet, wenn die eigens eingebauten
* Fontarten verwendet werden sollen.<br /> Der Aufruf dieser Methode wird <b>UMGEHEND</b>
* empfohlen, nach dem alle zu verwendenden Arten im Projektordner liegen, denn nur unter dem an
* die Konsole projezierten Namen <b>koennen diese ueberhaupt verwendet werden</b>!!<br /> Daher
* dient diese Methode der Praevention von Verwirrung, wegen "nicht darstellbarer" Fonts.
*/
public static void geladeneSchriftartenAusgeben () {
Logger.info("Protokoll aller aus dem Projektordner geladener Fontdateien");
if (eigene.length == 0) {
Logger.info("Es wurden keine \".ttf\"-Dateien im Projektordner gefunden");
} else {
Logger.info("Es wurden " + eigene.length + " \".ttf\"-Dateien im Projektordner gefunden.");
Logger.info("Diese sind unter folgenden Namen abrufbar:");
for (Font font : eigene) {
Logger.info(font.getName());
}
}
}
/**
* Setzt den Inhalt des Textes.<br /> Parallele Methode zu <code>setzeInhalt()</code>
*
* @param inhalt
* Der neue Inhalt des Textes
*
* @see #setzeInhalt(String)
*/
public void inhaltSetzen (String inhalt) {
setzeInhalt(inhalt);
}
/**
* Setzt den Inhalt des Textes.
*
* @param inhalt
* Der neue Inhalt des Textes
*/
public void setzeInhalt (String inhalt) {
this.inhalt = inhalt;
}
/**
* Setzt die Schriftart.
*
* @param art
* Die Repraesentation der Schriftart als Zahl:<br/> 0: Normaler Text<br /> 1: Fett<br /> 2:
* Kursiv<br /> 3: Fett & Kursiv<br /> <br /> Ist die Eingabe nicht eine dieser 4 Zahlen, so
* wird nichts geaendert.<br /> Parallele Methode zu <code>setzeSchriftart()</code>
*
* @see #setzeSchriftart(int)
*/
public void schriftartSetzen (int art) {
setzeSchriftart(art);
}
/**
* Setzt die Schriftart.
*
* @param art
* Die Repraesentation der Schriftart als Zahl:<br/> 0: Normaler Text<br /> 1: Fett<br /> 2:
* Kursiv<br /> 3: Fett & Kursiv<br /> <br /> Ist die Eingabe nicht eine dieser 4 Zahlen, so
* wird nichts geaendert.
*/
public void setzeSchriftart (int art) {
if (art >= 0 && art <= 3) {
schriftart = art;
aktualisieren();
}
}
/**
* Klasseninterne Methode zum aktualisieren des Font-Objektes
*/
private void aktualisieren () {
this.font = this.font.deriveFont(schriftart, groesse);
}
/**
* Setzt die Fuellfarbe<br /> Parallele Methode zu <code>setzeFarbe()</code>
*
* @param farbe
* Der Name der neuen Fuellfarbe
*
* @see #setzeFarbe(String)
* @see #farbeSetzen(Farbe)
*/
public void farbeSetzen (String farbe) {
setzeFarbe(farbe);
}
/**
* Setzt die Fuellfarbe
*
* @param farbe
* Der Name der neuen Fuellfarbe
*/
public void setzeFarbe (String farbe) {
this.setzeFarbe(zuFarbeKonvertieren(farbe));
}
/**
* Setzt die Fuellfarbe
*
* @param c
* Die neue Fuellfarbe
*/
public void setzeFarbe (Color c) {
farbe = c;
aktualisieren();
}
/**
* Setzt die Fuellfarbe
*
* @param f
* Das Farbe-Objekt, das die neue Fuellfarbe beschreibt
*
* @see #farbeSetzen(String)
*/
public void farbeSetzen (Farbe f) {
setzeFarbe(f.wert());
}
/**
* Setzt die Schriftgroesse.<br /> Wrappt hierbei die Methode <code>setzeGroesse</code>.
*
* @param groesse
* Die neue Schriftgroesse
*
* @see #setzeGroesse(int)
*/
public void groesseSetzen (int groesse) {
setzeGroesse(groesse);
}
/**
* Setzt die Schriftgroesse
*
* @param groesse
* Die neue Schriftgroesse
*/
public void setzeGroesse (int groesse) {
this.groesse = groesse;
aktualisieren();
}
/**
* Diese Methode gibt die aktuelle Groesse des Textes aus
*
* @return Die aktuelle Schriftgroesse des Textes
*
* @see #groesseSetzen(int)
*/
public int groesse () {
return groesse;
}
/**
* Setzt einen neuen Font fuer den Text.<br /> Parallele Methode zu <code>setzeFont()</code>
*
* @param name
* Der Name des neuen Fonts fuer den Text
*
* @see #setzeFont(String)
*/
public void fontSetzen (String name) {
setzeFont(name);
}
/**
* Zeichnet das Objekt.
*
* @param g
* Das zeichnende Graphics-Objekt
* @param r
* Das BoundingRechteck, dass die Kameraperspektive Repraesentiert.<br /> Hierbei soll
* zunaechst getestet werden, ob das Objekt innerhalb der Kamera liegt, und erst dann
* gezeichnet werden.
*/
@Override
public void zeichnen (Graphics2D g, BoundingRechteck r) {
if (!r.schneidetBasic(this.dimension())) {
return;
}
super.beforeRender(g, r);
FontMetrics f = Fenster.metrik(font);
float x = position.x, y = position.y;
if (anker == Anker.MITTE) {
x = position.x - f.stringWidth(inhalt) / 2;
} else if (anker == Anker.RECHTS) {
x = position.x - f.stringWidth(inhalt);
}
g.setColor(farbe);
g.setFont(font);
g.drawString(inhalt, (int) (x - r.x), (int) (y - r.y + groesse));
super.afterRender(g, r);
}
/**
* @return Ein BoundingRechteck mit dem minimal noetigen Umfang, um das Objekt <b>voll
* einzuschliessen</b>.
*/
@Override
public BoundingRechteck dimension () {
FontMetrics f = Fenster.metrik(font);
float x = position.x, y = position.y;
if (anker == Anker.MITTE) {
x = position.x - f.stringWidth(inhalt) / 2;
} else if (anker == Anker.RECHTS) {
x = position.x - f.stringWidth(inhalt);
}
return new BoundingRechteck(x, y, f.stringWidth(inhalt), f.getHeight());
}
/**
* {@inheritDoc} Collider wird direkt aus dem das <code>Raum</code>-Objekt umfassenden
* <code>BoundingRechteck</code> erzeugt, dass über die <code>dimension()</code>-Methode
* berechnet wird.
*/
@Override
public Collider erzeugeCollider () {
return erzeugeLazyCollider();
}
/**
* Diese Methode loescht alle eventuell vorhandenen Referenzen innerhalb der Engine auf dieses
* Objekt, damit es problemlos geloescht werden kann.<br /> <b>Achtung:</b> zwar werden
* hierdurch alle Referenzen geloescht, die <b>nur innerhalb</b> der Engine liegen (dies
* betrifft vor allem Animationen etc), jedoch nicht die innerhalb eines
* <code>Knoten</code>-Objektes!!!!!!!!!<br /> Das heisst, wenn das Objekt an einem Knoten liegt
* (was <b>immer der Fall ist, wenn es auch gezeichnet wird (siehe die Wurzel des
* Fensters)</b>), muss es trotzdem selbst geloescht werden, <b>dies erledigt diese Methode
* nicht!!</b>.<br /> Diese Klasse ueberschreibt die Methode wegen des Leuchtens.
*/
@Override
public void loeschen () {
super.leuchterAbmelden(this);
super.loeschen();
}
/**
* Setzt, ob dieses Leuchtend-Objekt leuchten soll.<br /> Ist dies der Fall, so werden immer
* wieder schnell dessen Farben geaendert; so entsteht ein Leuchteffekt.
*
* @param leuchtet
* Ob dieses Objekt nun leuchten soll oder nicht (mehr).<br /> <b>Achtung:</b> Die
* Leuchtfunktion kann bei bestimmten Klassen sehr psychadelisch und aufreizend wirken! Daher
* sollte sie immer mit Bedacht und in Nuancen verwendet werden!
*/
@Override
public void leuchtetSetzen (boolean leuchtet) {
if (this.leuchtet == leuchtet) {
return;
}
this.leuchtet = leuchtet;
if (leuchtet) {
alte = farbe;
} else {
this.setzeFarbe(alte);
}
}
/**
* Fuehrt einen Leuchtschritt aus.<br /> Dies heisst, dass in dieser Methode die Farbe einfach
* gewechselt wird. Da diese Methode schnell und oft hintereinander ausgefuehrt wird, soll so
* der Leuchteffekt entstehen.<br /> <b>Diese Methode sollte nur innerhalb der Engine
* ausgefuehrt werden! Also nicht fuer den Entwickler gedacht.</b>
*/
@Override
public void leuchtSchritt () {
leuchtzaehler++;
leuchtzaehler %= farbzyklus.length;
this.setzeFarbe(farbzyklus[leuchtzaehler]);
}
/**
* Gibt wieder, ob das Leuchtet-Objekt gerade leuchtet oder nicht.
*
* @return <code>true</code>, wenn das Objekt gerade leuchtet, wenn nicht, dann ist die
* Rueckgabe <code>false</code>
*/
@Override
public boolean leuchtet () {
return this.leuchtet;
}
/**
* Gibt den aktuellen Textinhalt zurück.
*
* @return aktueller Textinhalt
*/
public String gibInhalt () {
return inhalt;
}
/**
* Gibt den aktuellen Anker zurück.
*
* @return aktueller Anker
*
* @see ea.Text.Anker
* @see #setAnker(ea.Text.Anker)
*/
public Anker getAnker () {
return anker;
}
/**
* Setzt den Textanker. Dies beschreibt, wo sich der Text relativ zur x-Koordinate befindet.
* Möglich sind: <li>{@code Text.Anker.LINKS},</li> <li>{@code Text.Anker.MITTE},</li>
* <li>{@code Text.Anker.RECHTS}.</li> <br> <b>Hinweis</b>: {@code null} wird wie {@code
* Anker.LINKS} behandelt!
*
* @param anker
* neuer Anker
*
* @see ea.Text.Anker
* @see #getAnker()
*/
public void setAnker (Anker anker) {
this.anker = anker;
}
/**
* Ein Textanker beschreibt, wo sich der Text relativ zu seiner x-Koordinate befindet. Möglich
* sind: <li>{@code Anker.LINKS},</li> <li>{@code Anker.MITTE},</li> <li>{@code
* Anker.RECHTS}.</li>
*
* @see #setAnker(ea.Text.Anker)
* @see #getAnker()
*/
public enum Anker {
LINKS, MITTE, RECHTS
}
}
|
187109_3 | /*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.util;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.util.AsciiString;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.Param;
import org.asynchttpclient.Request;
import org.asynchttpclient.uri.Uri;
import org.jetbrains.annotations.Nullable;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* {@link AsyncHttpClient} common utilities.
*/
public final class HttpUtils {
public static final AsciiString ACCEPT_ALL_HEADER_VALUE = new AsciiString("*/*");
public static final AsciiString GZIP_DEFLATE = new AsciiString(HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
private static final String CONTENT_TYPE_CHARSET_ATTRIBUTE = "charset=";
private static final String CONTENT_TYPE_BOUNDARY_ATTRIBUTE = "boundary=";
private static final String BROTLY_ACCEPT_ENCODING_SUFFIX = ", br";
private HttpUtils() {
// Prevent outside initialization
}
public static String hostHeader(Uri uri) {
String host = uri.getHost();
int port = uri.getPort();
return port == -1 || port == uri.getSchemeDefaultPort() ? host : host + ':' + port;
}
public static String originHeader(Uri uri) {
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder();
sb.append(uri.isSecured() ? "https://" : "http://").append(uri.getHost());
if (uri.getExplicitPort() != uri.getSchemeDefaultPort()) {
sb.append(':').append(uri.getPort());
}
return sb.toString();
}
public static @Nullable Charset extractContentTypeCharsetAttribute(String contentType) {
String charsetName = extractContentTypeAttribute(contentType, CONTENT_TYPE_CHARSET_ATTRIBUTE);
return charsetName != null ? Charset.forName(charsetName) : null;
}
public static @Nullable String extractContentTypeBoundaryAttribute(String contentType) {
return extractContentTypeAttribute(contentType, CONTENT_TYPE_BOUNDARY_ATTRIBUTE);
}
private static @Nullable String extractContentTypeAttribute(@Nullable String contentType, String attribute) {
if (contentType == null) {
return null;
}
for (int i = 0; i < contentType.length(); i++) {
if (contentType.regionMatches(true, i, attribute, 0,
attribute.length())) {
int start = i + attribute.length();
// trim left
while (start < contentType.length()) {
char c = contentType.charAt(start);
if (c == ' ' || c == '\'' || c == '"') {
start++;
} else {
break;
}
}
if (start == contentType.length()) {
break;
}
// trim right
int end = start + 1;
while (end < contentType.length()) {
char c = contentType.charAt(end);
if (c == ' ' || c == '\'' || c == '"' || c == ';') {
break;
} else {
end++;
}
}
return contentType.substring(start, end);
}
}
return null;
}
// The pool of ASCII chars to be used for generating a multipart boundary.
private static final byte[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(US_ASCII);
// a random size from 30 to 40
public static byte[] computeMultipartBoundary() {
ThreadLocalRandom random = ThreadLocalRandom.current();
byte[] bytes = new byte[random.nextInt(11) + 30];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = MULTIPART_CHARS[random.nextInt(MULTIPART_CHARS.length)];
}
return bytes;
}
public static String patchContentTypeWithBoundaryAttribute(String base, byte[] boundary) {
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder().append(base);
if (!base.isEmpty() && base.charAt(base.length() - 1) != ';') {
sb.append(';');
}
return sb.append(' ').append(CONTENT_TYPE_BOUNDARY_ATTRIBUTE).append(new String(boundary, US_ASCII)).toString();
}
public static boolean followRedirect(AsyncHttpClientConfig config, Request request) {
return request.getFollowRedirect() != null ? request.getFollowRedirect() : config.isFollowRedirect();
}
public static ByteBuffer urlEncodeFormParams(List<Param> params, Charset charset) {
return StringUtils.charSequence2ByteBuffer(urlEncodeFormParams0(params, charset), US_ASCII);
}
private static StringBuilder urlEncodeFormParams0(List<Param> params, Charset charset) {
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder();
for (Param param : params) {
encodeAndAppendFormParam(sb, param.getName(), param.getValue(), charset);
}
sb.setLength(sb.length() - 1);
return sb;
}
private static void encodeAndAppendFormParam(StringBuilder sb, String name, @Nullable String value, Charset charset) {
encodeAndAppendFormField(sb, name, charset);
if (value != null) {
sb.append('=');
encodeAndAppendFormField(sb, value, charset);
}
sb.append('&');
}
private static void encodeAndAppendFormField(StringBuilder sb, String field, Charset charset) {
if (charset.equals(UTF_8)) {
Utf8UrlEncoder.encodeAndAppendFormElement(sb, field);
} else {
// TODO there's probably room for perf improvements
sb.append(URLEncoder.encode(field, charset));
}
}
public static CharSequence filterOutBrotliFromAcceptEncoding(String acceptEncoding) {
// we don't support Brotly ATM
if (acceptEncoding.endsWith(BROTLY_ACCEPT_ENCODING_SUFFIX)) {
return acceptEncoding.subSequence(0, acceptEncoding.length() - BROTLY_ACCEPT_ENCODING_SUFFIX.length());
}
return acceptEncoding;
}
}
| AsyncHttpClient/async-http-client | client/src/main/java/org/asynchttpclient/util/HttpUtils.java | 2,015 | //" : "http://").append(uri.getHost()); | line_comment | nl | /*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.util;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.util.AsciiString;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.Param;
import org.asynchttpclient.Request;
import org.asynchttpclient.uri.Uri;
import org.jetbrains.annotations.Nullable;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* {@link AsyncHttpClient} common utilities.
*/
public final class HttpUtils {
public static final AsciiString ACCEPT_ALL_HEADER_VALUE = new AsciiString("*/*");
public static final AsciiString GZIP_DEFLATE = new AsciiString(HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
private static final String CONTENT_TYPE_CHARSET_ATTRIBUTE = "charset=";
private static final String CONTENT_TYPE_BOUNDARY_ATTRIBUTE = "boundary=";
private static final String BROTLY_ACCEPT_ENCODING_SUFFIX = ", br";
private HttpUtils() {
// Prevent outside initialization
}
public static String hostHeader(Uri uri) {
String host = uri.getHost();
int port = uri.getPort();
return port == -1 || port == uri.getSchemeDefaultPort() ? host : host + ':' + port;
}
public static String originHeader(Uri uri) {
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder();
sb.append(uri.isSecured() ? "https://" :<SUF>
if (uri.getExplicitPort() != uri.getSchemeDefaultPort()) {
sb.append(':').append(uri.getPort());
}
return sb.toString();
}
public static @Nullable Charset extractContentTypeCharsetAttribute(String contentType) {
String charsetName = extractContentTypeAttribute(contentType, CONTENT_TYPE_CHARSET_ATTRIBUTE);
return charsetName != null ? Charset.forName(charsetName) : null;
}
public static @Nullable String extractContentTypeBoundaryAttribute(String contentType) {
return extractContentTypeAttribute(contentType, CONTENT_TYPE_BOUNDARY_ATTRIBUTE);
}
private static @Nullable String extractContentTypeAttribute(@Nullable String contentType, String attribute) {
if (contentType == null) {
return null;
}
for (int i = 0; i < contentType.length(); i++) {
if (contentType.regionMatches(true, i, attribute, 0,
attribute.length())) {
int start = i + attribute.length();
// trim left
while (start < contentType.length()) {
char c = contentType.charAt(start);
if (c == ' ' || c == '\'' || c == '"') {
start++;
} else {
break;
}
}
if (start == contentType.length()) {
break;
}
// trim right
int end = start + 1;
while (end < contentType.length()) {
char c = contentType.charAt(end);
if (c == ' ' || c == '\'' || c == '"' || c == ';') {
break;
} else {
end++;
}
}
return contentType.substring(start, end);
}
}
return null;
}
// The pool of ASCII chars to be used for generating a multipart boundary.
private static final byte[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(US_ASCII);
// a random size from 30 to 40
public static byte[] computeMultipartBoundary() {
ThreadLocalRandom random = ThreadLocalRandom.current();
byte[] bytes = new byte[random.nextInt(11) + 30];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = MULTIPART_CHARS[random.nextInt(MULTIPART_CHARS.length)];
}
return bytes;
}
public static String patchContentTypeWithBoundaryAttribute(String base, byte[] boundary) {
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder().append(base);
if (!base.isEmpty() && base.charAt(base.length() - 1) != ';') {
sb.append(';');
}
return sb.append(' ').append(CONTENT_TYPE_BOUNDARY_ATTRIBUTE).append(new String(boundary, US_ASCII)).toString();
}
public static boolean followRedirect(AsyncHttpClientConfig config, Request request) {
return request.getFollowRedirect() != null ? request.getFollowRedirect() : config.isFollowRedirect();
}
public static ByteBuffer urlEncodeFormParams(List<Param> params, Charset charset) {
return StringUtils.charSequence2ByteBuffer(urlEncodeFormParams0(params, charset), US_ASCII);
}
private static StringBuilder urlEncodeFormParams0(List<Param> params, Charset charset) {
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder();
for (Param param : params) {
encodeAndAppendFormParam(sb, param.getName(), param.getValue(), charset);
}
sb.setLength(sb.length() - 1);
return sb;
}
private static void encodeAndAppendFormParam(StringBuilder sb, String name, @Nullable String value, Charset charset) {
encodeAndAppendFormField(sb, name, charset);
if (value != null) {
sb.append('=');
encodeAndAppendFormField(sb, value, charset);
}
sb.append('&');
}
private static void encodeAndAppendFormField(StringBuilder sb, String field, Charset charset) {
if (charset.equals(UTF_8)) {
Utf8UrlEncoder.encodeAndAppendFormElement(sb, field);
} else {
// TODO there's probably room for perf improvements
sb.append(URLEncoder.encode(field, charset));
}
}
public static CharSequence filterOutBrotliFromAcceptEncoding(String acceptEncoding) {
// we don't support Brotly ATM
if (acceptEncoding.endsWith(BROTLY_ACCEPT_ENCODING_SUFFIX)) {
return acceptEncoding.subSequence(0, acceptEncoding.length() - BROTLY_ACCEPT_ENCODING_SUFFIX.length());
}
return acceptEncoding;
}
}
|
52362_53 | //------------------------------------------------------------------------------------------------//
// //
// A u g m e n t a t i o n D o t I n t e r //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2023. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omr.sig.inter;
import org.audiveris.omr.glyph.Glyph;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.math.GeoOrder;
import org.audiveris.omr.math.GeoUtil;
import org.audiveris.omr.sheet.Part;
import org.audiveris.omr.sheet.ProcessingSwitch;
import org.audiveris.omr.sheet.Scale;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sheet.rhythm.MeasureStack;
import org.audiveris.omr.sheet.rhythm.Voice;
import org.audiveris.omr.sig.relation.AugmentationRelation;
import org.audiveris.omr.sig.relation.DoubleDotRelation;
import org.audiveris.omr.sig.relation.HeadStemRelation;
import org.audiveris.omr.sig.relation.Link;
import org.audiveris.omr.sig.relation.Relation;
import static org.audiveris.omr.util.HorizontalSide.RIGHT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Class <code>AugmentationDotInter</code> represents an augmentation dot for
* a note (head or rest) or another dot.
*
* @author Hervé Bitteur
*/
@XmlRootElement(name = "augmentation-dot")
public class AugmentationDotInter
extends AbstractInter
{
//~ Static fields/initializers -----------------------------------------------------------------
private static final Logger logger = LoggerFactory.getLogger(AugmentationDotInter.class);
//~ Constructors -------------------------------------------------------------------------------
/**
* No-arg constructor meant for JAXB.
*/
private AugmentationDotInter ()
{
}
/**
* Creates a new <code>AugmentationDotInter</code> object.
*
* @param glyph underlying glyph
* @param grade evaluation value
*/
public AugmentationDotInter (Glyph glyph,
Double grade)
{
super(glyph, null, Shape.AUGMENTATION_DOT, grade);
}
//~ Methods ------------------------------------------------------------------------------------
//--------//
// accept //
//--------//
@Override
public void accept (InterVisitor visitor)
{
visitor.visit(this);
}
//-------//
// added //
//-------//
/**
* Add the dot to its containing stack.
*
* @see #remove(boolean)
*/
@Override
public void added ()
{
super.added();
// Add it to containing measure stack
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.addInter(this);
}
setAbnormal(true); // No note or other dot linked yet
}
//---------------//
// checkAbnormal //
//---------------//
@Override
public boolean checkAbnormal ()
{
// Check if dot is connected to a note or to another (first) dot
boolean ab = true;
if (sig.hasRelation(this, AugmentationRelation.class)) {
ab = false;
} else {
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
if (sig.getEdgeSource(dd) == this) {
ab = false;
}
}
}
setAbnormal(ab);
return isAbnormal();
}
//-------------------//
// getAugmentedNotes //
//-------------------//
/**
* Report the notes (head/rest) that are currently linked to this augmentation dot.
*
* @return the linked notes
*/
public List<AbstractNoteInter> getAugmentedNotes ()
{
List<AbstractNoteInter> notes = null;
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
if (notes == null) {
notes = new ArrayList<>();
}
notes.add((AbstractNoteInter) sig.getEdgeTarget(rel));
}
if (notes == null) {
return Collections.emptyList();
}
return notes;
}
//--------------//
// getDotsLuBox //
//--------------//
/**
* Report dots lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getDotsLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(DoubleDotRelation.getXOutGapMaximum(getProfile()));
final int maxDy = scale.toPixels(DoubleDotRelation.getYGapMaximum(getProfile()));
return getLuBox(dotCenter, maxDx, maxDy);
}
//---------------//
// getNotesLuBox //
//---------------//
/**
* Report notes lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getNotesLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(AugmentationRelation.getXOutGapMaximum(getProfile()));
final int maxDy = scale.toPixels(AugmentationRelation.getYGapMaximum(getProfile()));
return getLuBox(dotCenter, maxDx, maxDy);
}
//---------//
// getPart //
//---------//
@Override
public Part getPart ()
{
if (part == null) {
// Beware, we may have two dots that refer to one another
// First dot
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
return part = opposite.getPart();
}
final int dotCenterX = getCenter().x;
// Perhaps a second dot, let's look for a first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
if (opposite.getCenter().x < dotCenterX) {
return part = opposite.getPart();
}
}
}
return super.getPart();
}
//--------------------------//
// getSecondAugmentationDot //
//--------------------------//
/**
* Report the second augmentation dot, if any, that is linked to this (first)
* augmentation dot.
*
* @return the second dot, if any, or null
*/
public AugmentationDotInter getSecondAugmentationDot ()
{
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
Inter dot = sig.getEdgeSource(dd);
if (dot != this) {
return (AugmentationDotInter) dot;
}
}
return null;
}
//----------//
// getVoice //
//----------//
@Override
public Voice getVoice ()
{
// Use augmented note, if any
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
return sig.getOppositeInter(this, rel).getVoice();
}
// If second dot, use first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter firstDot = sig.getEdgeTarget(rel);
if (firstDot != this) {
return firstDot.getVoice();
}
}
return null;
}
//----------------//
// lookupDotLinks //
//----------------//
/**
* Look up for all possible links with (first) dots.
*
* @param systemDots collection of augmentation dots in system, ordered bottom up
* @param system containing system
* @param profile desired profile level
* @return list of possible links, perhaps empty
*/
public List<Link> lookupDotLinks (List<Inter> systemDots,
SystemInfo system,
int profile)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for augmentation dots reachable from this dot
final Rectangle luBox = getDotsLuBox(dotCenter, system);
// Relevant dots?
final List<Inter> firsts = dotStack.filter(
Inters.intersectedInters(systemDots, GeoOrder.NONE, luBox));
// Remove the augmentation dot, if any, that corresponds to the glyph at hand
for (Inter first : firsts) {
if (first.getCenter().equals(dotCenter)) {
firsts.remove(first);
break;
}
}
final int minDx = scale.toPixels(DoubleDotRelation.getXOutGapMinimum(profile));
for (Inter first : firsts) {
Point refPt = first.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
DoubleDotRelation rel = new DoubleDotRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), profile);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(first, rel, true));
}
}
}
return links;
}
//----------------//
// lookupHeadLink //
//----------------//
/**
* Look up for a possible link with a head.
* <p>
* Even in the case of a shared head, at most one head link is returned.
* <p>
* Assumption: System dots are already in place or they are processed top down.
*
* @param systemHeadChords system head chords, sorted by abscissa
* @param system containing system
* @param profile desired profile level
* @return a link or null
*/
public Link lookupHeadLink (List<Inter> systemHeadChords,
SystemInfo system,
int profile)
{
// Need sig and getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return null;
}
// Look for heads reachable from this dot. Heads are processed via their chord.
final Rectangle luBox = getNotesLuBox(dotCenter, system);
final List<Inter> chords = dotStack.filter(
Inters.intersectedInters(systemHeadChords, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(profile));
for (Inter ic : chords) {
HeadChordInter chord = (HeadChordInter) ic;
// Heads are reported bottom up within their chord
// So, we need to sort the list top down
List<? extends Inter> chordHeads = chord.getNotes();
Collections.sort(chordHeads, Inters.byCenterOrdinate);
for (Inter ih : chordHeads) {
HeadInter head = (HeadInter) ih;
// Check head is within reach
if (!GeoUtil.yEmbraces(luBox, head.getCenter().y)) {
continue;
}
// Check head is already linked to this dot, or not yet augmented
AugmentationDotInter headDot = head.getFirstAugmentationDot();
if ((headDot == null) || (headDot == this)) {
Point refPt = head.getCenterRight();
double xGap = dotCenter.x - refPt.x;
// Make sure dot is not too close to head
if (xGap < minDx) {
continue;
}
// When this method is called, there is at most one stem per head
// (including the case of shared heads)
for (Relation rel : system.getSig().getRelations(
head,
HeadStemRelation.class)) {
HeadStemRelation hsRel = (HeadStemRelation) rel;
if (hsRel.getHeadSide() == RIGHT) {
// If containing chord has heads on right side, reduce xGap accordingly
Rectangle rightBox = chord.getHeadsBounds(RIGHT);
if (rightBox != null) {
if (xGap > 0) {
xGap = Math.max(1, xGap - rightBox.width);
}
break;
}
}
}
if (xGap > 0) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), profile);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(head, rel, true));
}
}
}
}
}
// Now choose best among links
// First priority is given to head between lines (thus facing the dot)
// Second priority is given to head on lower line
// Third priority is given to head on upper line
for (Link link : links) {
HeadInter head = (HeadInter) link.partner;
if ((head.getIntegerPitch() % 2) != 0) {
return link;
}
}
return (!links.isEmpty()) ? links.get(0) : null;
}
//------------//
// lookupLink //
//------------//
/**
* Try to detect a link between this augmentation dot and either a note
* (head or rest) or another dot on left side.
*
* @param systemRests ordered collection of rests in system
* @param systemHeadChords ordered collection of head chords in system
* @param systemDots ordered collection of augmentation dots in system
* @param system containing system
* @param profile desired profile level
* @return the best link found or null
*/
private Link lookupLink (List<Inter> systemRests,
List<Inter> systemHeadChords,
List<Inter> systemDots,
SystemInfo system,
int profile)
{
List<Link> links = new ArrayList<>();
Link headLink = lookupHeadLink(systemHeadChords, system, profile);
if (headLink != null) {
links.add(headLink);
}
links.addAll(lookupRestLinks(systemRests, system, profile));
links.addAll(lookupDotLinks(systemDots, system, profile));
return Link.bestOf(links);
}
//-----------------//
// lookupRestLinks //
//-----------------//
/**
* Look up for all possible links with rests
*
* @param systemRests system rests, sorted by abscissa
* @param system containing system
* @param profile desired profile level
* @return list of possible links, perhaps empty
*/
public List<Link> lookupRestLinks (List<Inter> systemRests,
SystemInfo system,
int profile)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for rests reachable from this dot
final Rectangle luBox = getNotesLuBox(dotCenter, system);
// Relevant rests?
final List<Inter> rests = dotStack.filter(
Inters.intersectedInters(systemRests, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(profile));
for (Inter inter : rests) {
RestInter rest = (RestInter) inter;
Point refPt = rest.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), profile);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(rest, rel, true));
}
}
}
return links;
}
//--------//
// remove //
//--------//
/**
* Remove the dot from its containing stack.
*
* @param extensive true for non-manual removals only
* @see #added()
*/
@Override
public void remove (boolean extensive)
{
if (isRemoved()) {
return;
}
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.removeInter(this);
}
super.remove(extensive);
}
//-------------//
// searchLinks //
//-------------//
/**
* Try to find a link with a note or another dot on the left.
* <p>
* In case of a shared head, a pair of links can be returned.
*
* @param system containing system
* @return a collection of 0, 1 or 2 best link(s) found
*/
@Override
public Collection<Link> searchLinks (SystemInfo system)
{
List<Inter> systemRests = system.getSig().inters(RestInter.class);
Collections.sort(systemRests, Inters.byAbscissa);
List<Inter> systemHeadChords = system.getSig().inters(HeadChordInter.class);
Collections.sort(systemHeadChords, Inters.byAbscissa);
List<Inter> systemDots = system.getSig().inters(AugmentationDotInter.class);
Collections.sort(systemDots, Inters.byAbscissa);
final int profile = Math.max(getProfile(), system.getProfile());
final Link link = lookupLink(systemRests, systemHeadChords, systemDots, system, profile);
if (link == null) {
return Collections.emptyList();
}
if (link.partner instanceof HeadInter) {
return sharedHeadLinks(link, system);
} else {
return Collections.singleton(link);
}
}
//---------------//
// searchUnlinks //
//---------------//
@Override
public Collection<Link> searchUnlinks (SystemInfo system,
Collection<Link> links)
{
return searchObsoletelinks(links, AugmentationRelation.class, DoubleDotRelation.class);
}
//-----------------//
// sharedHeadLinks //
//-----------------//
/**
* Modify the provided head link when the target head is a shared head.
* <p>
* There is a very specific case for shared heads.
* See some cases in Dichterliebe01 example.
* <ul>
* <li>If head is located <b>on</b> staff line or ledger, use dot relative location.
* <li>If head is located <b>between</b> staff lines or ledgers:
* <ul>
* <li>If {@link ProcessingSwitch#bothSharedHeadDots} is set, assign dot to <b>both</b> heads.
* <li>If switch is not set, check chords durations:
* <ul>
* <li>If they are different, assign the dot <b>only</b> to the <b>longer</b>
* (which means lower number of beams or flags).
* <li>If they are identical, assign the dot to <b>both</b>.
* </ul>
* </ul>
* </ul>
*
* @param link the provided (head) link, perhaps null
* @param system the containing system
* @return a collection of (head) links, the provided link for a non-shared head, but one or two
* links for shared heads
*/
public Collection<Link> sharedHeadLinks (Link link,
SystemInfo system)
{
if (link == null) {
return Collections.emptyList();
}
final Collection<Link> links = new ArrayList<>();
final HeadInter h1 = (HeadInter) link.partner;
final HeadInter h2 = (HeadInter) h1.getMirror();
if (h2 == null) {
links.add(link);
} else {
// Head on or between line(s)?
final int p = h1.getIntegerPitch();
if ((p % 2) == 0) {
// On line
final int yHead = h1.getCenter().y;
final int yAug = getCenter().y;
final int yCh1 = h1.getChord().getCenter().y;
final HeadInter head;
if (yAug < yHead) {
// Link to upper
head = (yCh1 < yHead) ? h1 : h2;
} else {
// Link to lower
head = (yCh1 > yHead) ? h1 : h2;
}
links.add(new Link(head, new AugmentationRelation(), true));
} else {
// Between lines
final int bf1 = h1.getChord().getBeamsOrFlagsNumber();
final int bf2 = h2.getChord().getBeamsOrFlagsNumber();
if ((bf1 == bf2) || system.getSheet().getStub().getProcessingSwitches().getValue(
ProcessingSwitch.bothSharedHeadDots)) {
// Link to both
links.add(new Link(h1, new AugmentationRelation(), true));
links.add(new Link(h2, new AugmentationRelation(), true));
} else {
// Link to longer
HeadInter head = (bf1 < bf2) ? h1 : h2;
links.add(new Link(head, new AugmentationRelation(), true));
}
}
}
return links;
}
//~ Static Methods -----------------------------------------------------------------------------
//----------//
// getLuBox //
//----------//
/**
* Report proper lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param maxDx maximum dx between entity left side and dot center
* @param maxDy maximum dy between entity center and dot center
* @return proper lookup box
*/
private static Rectangle getLuBox (Point dotCenter,
int maxDx,
int maxDy)
{
return new Rectangle(dotCenter.x - maxDx, dotCenter.y - maxDy, maxDx, 2 * maxDy);
}
}
| Audiveris/audiveris | src/main/org/audiveris/omr/sig/inter/AugmentationDotInter.java | 7,113 | // Head on or between line(s)?
| line_comment | nl | //------------------------------------------------------------------------------------------------//
// //
// A u g m e n t a t i o n D o t I n t e r //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2023. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omr.sig.inter;
import org.audiveris.omr.glyph.Glyph;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.math.GeoOrder;
import org.audiveris.omr.math.GeoUtil;
import org.audiveris.omr.sheet.Part;
import org.audiveris.omr.sheet.ProcessingSwitch;
import org.audiveris.omr.sheet.Scale;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sheet.rhythm.MeasureStack;
import org.audiveris.omr.sheet.rhythm.Voice;
import org.audiveris.omr.sig.relation.AugmentationRelation;
import org.audiveris.omr.sig.relation.DoubleDotRelation;
import org.audiveris.omr.sig.relation.HeadStemRelation;
import org.audiveris.omr.sig.relation.Link;
import org.audiveris.omr.sig.relation.Relation;
import static org.audiveris.omr.util.HorizontalSide.RIGHT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Class <code>AugmentationDotInter</code> represents an augmentation dot for
* a note (head or rest) or another dot.
*
* @author Hervé Bitteur
*/
@XmlRootElement(name = "augmentation-dot")
public class AugmentationDotInter
extends AbstractInter
{
//~ Static fields/initializers -----------------------------------------------------------------
private static final Logger logger = LoggerFactory.getLogger(AugmentationDotInter.class);
//~ Constructors -------------------------------------------------------------------------------
/**
* No-arg constructor meant for JAXB.
*/
private AugmentationDotInter ()
{
}
/**
* Creates a new <code>AugmentationDotInter</code> object.
*
* @param glyph underlying glyph
* @param grade evaluation value
*/
public AugmentationDotInter (Glyph glyph,
Double grade)
{
super(glyph, null, Shape.AUGMENTATION_DOT, grade);
}
//~ Methods ------------------------------------------------------------------------------------
//--------//
// accept //
//--------//
@Override
public void accept (InterVisitor visitor)
{
visitor.visit(this);
}
//-------//
// added //
//-------//
/**
* Add the dot to its containing stack.
*
* @see #remove(boolean)
*/
@Override
public void added ()
{
super.added();
// Add it to containing measure stack
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.addInter(this);
}
setAbnormal(true); // No note or other dot linked yet
}
//---------------//
// checkAbnormal //
//---------------//
@Override
public boolean checkAbnormal ()
{
// Check if dot is connected to a note or to another (first) dot
boolean ab = true;
if (sig.hasRelation(this, AugmentationRelation.class)) {
ab = false;
} else {
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
if (sig.getEdgeSource(dd) == this) {
ab = false;
}
}
}
setAbnormal(ab);
return isAbnormal();
}
//-------------------//
// getAugmentedNotes //
//-------------------//
/**
* Report the notes (head/rest) that are currently linked to this augmentation dot.
*
* @return the linked notes
*/
public List<AbstractNoteInter> getAugmentedNotes ()
{
List<AbstractNoteInter> notes = null;
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
if (notes == null) {
notes = new ArrayList<>();
}
notes.add((AbstractNoteInter) sig.getEdgeTarget(rel));
}
if (notes == null) {
return Collections.emptyList();
}
return notes;
}
//--------------//
// getDotsLuBox //
//--------------//
/**
* Report dots lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getDotsLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(DoubleDotRelation.getXOutGapMaximum(getProfile()));
final int maxDy = scale.toPixels(DoubleDotRelation.getYGapMaximum(getProfile()));
return getLuBox(dotCenter, maxDx, maxDy);
}
//---------------//
// getNotesLuBox //
//---------------//
/**
* Report notes lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getNotesLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(AugmentationRelation.getXOutGapMaximum(getProfile()));
final int maxDy = scale.toPixels(AugmentationRelation.getYGapMaximum(getProfile()));
return getLuBox(dotCenter, maxDx, maxDy);
}
//---------//
// getPart //
//---------//
@Override
public Part getPart ()
{
if (part == null) {
// Beware, we may have two dots that refer to one another
// First dot
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
return part = opposite.getPart();
}
final int dotCenterX = getCenter().x;
// Perhaps a second dot, let's look for a first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
if (opposite.getCenter().x < dotCenterX) {
return part = opposite.getPart();
}
}
}
return super.getPart();
}
//--------------------------//
// getSecondAugmentationDot //
//--------------------------//
/**
* Report the second augmentation dot, if any, that is linked to this (first)
* augmentation dot.
*
* @return the second dot, if any, or null
*/
public AugmentationDotInter getSecondAugmentationDot ()
{
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
Inter dot = sig.getEdgeSource(dd);
if (dot != this) {
return (AugmentationDotInter) dot;
}
}
return null;
}
//----------//
// getVoice //
//----------//
@Override
public Voice getVoice ()
{
// Use augmented note, if any
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
return sig.getOppositeInter(this, rel).getVoice();
}
// If second dot, use first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter firstDot = sig.getEdgeTarget(rel);
if (firstDot != this) {
return firstDot.getVoice();
}
}
return null;
}
//----------------//
// lookupDotLinks //
//----------------//
/**
* Look up for all possible links with (first) dots.
*
* @param systemDots collection of augmentation dots in system, ordered bottom up
* @param system containing system
* @param profile desired profile level
* @return list of possible links, perhaps empty
*/
public List<Link> lookupDotLinks (List<Inter> systemDots,
SystemInfo system,
int profile)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for augmentation dots reachable from this dot
final Rectangle luBox = getDotsLuBox(dotCenter, system);
// Relevant dots?
final List<Inter> firsts = dotStack.filter(
Inters.intersectedInters(systemDots, GeoOrder.NONE, luBox));
// Remove the augmentation dot, if any, that corresponds to the glyph at hand
for (Inter first : firsts) {
if (first.getCenter().equals(dotCenter)) {
firsts.remove(first);
break;
}
}
final int minDx = scale.toPixels(DoubleDotRelation.getXOutGapMinimum(profile));
for (Inter first : firsts) {
Point refPt = first.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
DoubleDotRelation rel = new DoubleDotRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), profile);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(first, rel, true));
}
}
}
return links;
}
//----------------//
// lookupHeadLink //
//----------------//
/**
* Look up for a possible link with a head.
* <p>
* Even in the case of a shared head, at most one head link is returned.
* <p>
* Assumption: System dots are already in place or they are processed top down.
*
* @param systemHeadChords system head chords, sorted by abscissa
* @param system containing system
* @param profile desired profile level
* @return a link or null
*/
public Link lookupHeadLink (List<Inter> systemHeadChords,
SystemInfo system,
int profile)
{
// Need sig and getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return null;
}
// Look for heads reachable from this dot. Heads are processed via their chord.
final Rectangle luBox = getNotesLuBox(dotCenter, system);
final List<Inter> chords = dotStack.filter(
Inters.intersectedInters(systemHeadChords, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(profile));
for (Inter ic : chords) {
HeadChordInter chord = (HeadChordInter) ic;
// Heads are reported bottom up within their chord
// So, we need to sort the list top down
List<? extends Inter> chordHeads = chord.getNotes();
Collections.sort(chordHeads, Inters.byCenterOrdinate);
for (Inter ih : chordHeads) {
HeadInter head = (HeadInter) ih;
// Check head is within reach
if (!GeoUtil.yEmbraces(luBox, head.getCenter().y)) {
continue;
}
// Check head is already linked to this dot, or not yet augmented
AugmentationDotInter headDot = head.getFirstAugmentationDot();
if ((headDot == null) || (headDot == this)) {
Point refPt = head.getCenterRight();
double xGap = dotCenter.x - refPt.x;
// Make sure dot is not too close to head
if (xGap < minDx) {
continue;
}
// When this method is called, there is at most one stem per head
// (including the case of shared heads)
for (Relation rel : system.getSig().getRelations(
head,
HeadStemRelation.class)) {
HeadStemRelation hsRel = (HeadStemRelation) rel;
if (hsRel.getHeadSide() == RIGHT) {
// If containing chord has heads on right side, reduce xGap accordingly
Rectangle rightBox = chord.getHeadsBounds(RIGHT);
if (rightBox != null) {
if (xGap > 0) {
xGap = Math.max(1, xGap - rightBox.width);
}
break;
}
}
}
if (xGap > 0) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), profile);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(head, rel, true));
}
}
}
}
}
// Now choose best among links
// First priority is given to head between lines (thus facing the dot)
// Second priority is given to head on lower line
// Third priority is given to head on upper line
for (Link link : links) {
HeadInter head = (HeadInter) link.partner;
if ((head.getIntegerPitch() % 2) != 0) {
return link;
}
}
return (!links.isEmpty()) ? links.get(0) : null;
}
//------------//
// lookupLink //
//------------//
/**
* Try to detect a link between this augmentation dot and either a note
* (head or rest) or another dot on left side.
*
* @param systemRests ordered collection of rests in system
* @param systemHeadChords ordered collection of head chords in system
* @param systemDots ordered collection of augmentation dots in system
* @param system containing system
* @param profile desired profile level
* @return the best link found or null
*/
private Link lookupLink (List<Inter> systemRests,
List<Inter> systemHeadChords,
List<Inter> systemDots,
SystemInfo system,
int profile)
{
List<Link> links = new ArrayList<>();
Link headLink = lookupHeadLink(systemHeadChords, system, profile);
if (headLink != null) {
links.add(headLink);
}
links.addAll(lookupRestLinks(systemRests, system, profile));
links.addAll(lookupDotLinks(systemDots, system, profile));
return Link.bestOf(links);
}
//-----------------//
// lookupRestLinks //
//-----------------//
/**
* Look up for all possible links with rests
*
* @param systemRests system rests, sorted by abscissa
* @param system containing system
* @param profile desired profile level
* @return list of possible links, perhaps empty
*/
public List<Link> lookupRestLinks (List<Inter> systemRests,
SystemInfo system,
int profile)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for rests reachable from this dot
final Rectangle luBox = getNotesLuBox(dotCenter, system);
// Relevant rests?
final List<Inter> rests = dotStack.filter(
Inters.intersectedInters(systemRests, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(profile));
for (Inter inter : rests) {
RestInter rest = (RestInter) inter;
Point refPt = rest.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), profile);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(rest, rel, true));
}
}
}
return links;
}
//--------//
// remove //
//--------//
/**
* Remove the dot from its containing stack.
*
* @param extensive true for non-manual removals only
* @see #added()
*/
@Override
public void remove (boolean extensive)
{
if (isRemoved()) {
return;
}
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.removeInter(this);
}
super.remove(extensive);
}
//-------------//
// searchLinks //
//-------------//
/**
* Try to find a link with a note or another dot on the left.
* <p>
* In case of a shared head, a pair of links can be returned.
*
* @param system containing system
* @return a collection of 0, 1 or 2 best link(s) found
*/
@Override
public Collection<Link> searchLinks (SystemInfo system)
{
List<Inter> systemRests = system.getSig().inters(RestInter.class);
Collections.sort(systemRests, Inters.byAbscissa);
List<Inter> systemHeadChords = system.getSig().inters(HeadChordInter.class);
Collections.sort(systemHeadChords, Inters.byAbscissa);
List<Inter> systemDots = system.getSig().inters(AugmentationDotInter.class);
Collections.sort(systemDots, Inters.byAbscissa);
final int profile = Math.max(getProfile(), system.getProfile());
final Link link = lookupLink(systemRests, systemHeadChords, systemDots, system, profile);
if (link == null) {
return Collections.emptyList();
}
if (link.partner instanceof HeadInter) {
return sharedHeadLinks(link, system);
} else {
return Collections.singleton(link);
}
}
//---------------//
// searchUnlinks //
//---------------//
@Override
public Collection<Link> searchUnlinks (SystemInfo system,
Collection<Link> links)
{
return searchObsoletelinks(links, AugmentationRelation.class, DoubleDotRelation.class);
}
//-----------------//
// sharedHeadLinks //
//-----------------//
/**
* Modify the provided head link when the target head is a shared head.
* <p>
* There is a very specific case for shared heads.
* See some cases in Dichterliebe01 example.
* <ul>
* <li>If head is located <b>on</b> staff line or ledger, use dot relative location.
* <li>If head is located <b>between</b> staff lines or ledgers:
* <ul>
* <li>If {@link ProcessingSwitch#bothSharedHeadDots} is set, assign dot to <b>both</b> heads.
* <li>If switch is not set, check chords durations:
* <ul>
* <li>If they are different, assign the dot <b>only</b> to the <b>longer</b>
* (which means lower number of beams or flags).
* <li>If they are identical, assign the dot to <b>both</b>.
* </ul>
* </ul>
* </ul>
*
* @param link the provided (head) link, perhaps null
* @param system the containing system
* @return a collection of (head) links, the provided link for a non-shared head, but one or two
* links for shared heads
*/
public Collection<Link> sharedHeadLinks (Link link,
SystemInfo system)
{
if (link == null) {
return Collections.emptyList();
}
final Collection<Link> links = new ArrayList<>();
final HeadInter h1 = (HeadInter) link.partner;
final HeadInter h2 = (HeadInter) h1.getMirror();
if (h2 == null) {
links.add(link);
} else {
// Head on<SUF>
final int p = h1.getIntegerPitch();
if ((p % 2) == 0) {
// On line
final int yHead = h1.getCenter().y;
final int yAug = getCenter().y;
final int yCh1 = h1.getChord().getCenter().y;
final HeadInter head;
if (yAug < yHead) {
// Link to upper
head = (yCh1 < yHead) ? h1 : h2;
} else {
// Link to lower
head = (yCh1 > yHead) ? h1 : h2;
}
links.add(new Link(head, new AugmentationRelation(), true));
} else {
// Between lines
final int bf1 = h1.getChord().getBeamsOrFlagsNumber();
final int bf2 = h2.getChord().getBeamsOrFlagsNumber();
if ((bf1 == bf2) || system.getSheet().getStub().getProcessingSwitches().getValue(
ProcessingSwitch.bothSharedHeadDots)) {
// Link to both
links.add(new Link(h1, new AugmentationRelation(), true));
links.add(new Link(h2, new AugmentationRelation(), true));
} else {
// Link to longer
HeadInter head = (bf1 < bf2) ? h1 : h2;
links.add(new Link(head, new AugmentationRelation(), true));
}
}
}
return links;
}
//~ Static Methods -----------------------------------------------------------------------------
//----------//
// getLuBox //
//----------//
/**
* Report proper lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param maxDx maximum dx between entity left side and dot center
* @param maxDy maximum dy between entity center and dot center
* @return proper lookup box
*/
private static Rectangle getLuBox (Point dotCenter,
int maxDx,
int maxDy)
{
return new Rectangle(dotCenter.x - maxDx, dotCenter.y - maxDy, maxDx, 2 * maxDy);
}
}
|
203908_5 | package FlowFree.Model;
import FlowFree.View.Gamescherm.GameschermView;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Jonathan Auteveld
* @version 1.0 12/02/2021 22:43
*/
public class FlowFreeModel {
private boolean won = false;
private List<Player> playerList;
private Player gamePlayer;
private Board board = new Board();
private LocalDate date = LocalDate.now();
private int currentx;
private int currenty;
private int pipex;
private int pipey;
private int pipeWidth;
private final int rectOffset = 15;
private int boardSize;
public FlowFreeModel() {
}
public void setBoard(int row, int column) {
this.boardSize = row;
this.board.setRij(row);
this.board.setKolom(column);
this.board.readFile();
}
public void createBoard(GameschermView view) {
//canvas eerst leegmaken met clearrect
//canvas size aanpassen zodat deze mooi in het midden van het veld komt
GraphicsContext gc = view.getCanvas().getGraphicsContext2D();
gc.clearRect(0, 0, view.getCanvas().getWidth(), view.getCanvas().getHeight());
view.getCanvas().setWidth(board.getGRIDWIDTH() * board.getRij() + 10);
view.getCanvas().setHeight(board.getGRIDWIDTH() * board.getKolom() + 10);
//bord aanmaken door vierkanten te tekenen op het canvas
//5X5 = 5 kleuren, 6x6, 7X7, 8X8 = 6 kleuren ,9X9 = 9 kleuren
//board tekenen
gc.setStroke(Color.WHITE);
for (int i = 0; i < board.getBoard().length; i++) { //rij
for (int j = 0; j < board.getBoard()[i].length; j++) { //kolom
int x = i * board.getGRIDWIDTH();
int y = j * board.getGRIDWIDTH();
int diameter = board.getGRIDWIDTH() - 10;
int circOffset = 5;
gc.strokeRect(x, y, board.getGRIDWIDTH(), board.getGRIDWIDTH());
int val = board.getBoard()[j][i];
if (val < 1 || val > 9) continue; //waarden hierbuiten uitsluiten
Color color = Color.WHITE;
switch (val) {
case 1:
color = Color.RED;
break;
case 2:
color = Color.BLUE;
break;
case 3:
color = Color.GREEN;
break;
case 4:
color = Color.ORANGE;
break;
case 5:
color = Color.YELLOW;
break;
case 6:
color = Color.TURQUOISE;
break;
case 7:
color = Color.PURPLE;
break;
case 8:
color = Color.HOTPINK;
break;
case 9:
color = Color.BROWN;
break;
}
gc.setFill(color);
gc.fillOval(x + circOffset, y + circOffset, diameter, diameter);
}
}
}
/* als de positie op het spelbord waar je klikt een bol is ( > 0 uit de array)
* dan ga je deze positie selecteren om een pipe te starten */
public boolean dotSelection(int x, int y) {
if (board.getBoard()[y][x] > 0) {
return true;
} else
return false;
}
/* positie bepalen waar je muis naar beweegt
* deze plaats wordt een negatieve waarde van de overeenkomende bol dat geselecteerd is
* hierover zal een pipe getekend worden.
* Dit wordt voorgesteld als een negatieve waarde van de Board array */
public void drag(int currentx, int currenty, int dragx, int dragy, int startx, int starty) {
if (dragx >= 0 && dragy >= 0 &&
dragy < board.getBoard().length && dragx < board.getBoard()[0].length && board.getBoard()[dragy][dragx] == 0) {
if ((dragx == currentx + 1 && dragy == currenty) || //rechts
(dragx == currentx - 1 && dragy == currenty) || //links
(dragx == currentx && dragy == currenty + 1) || //boven
(dragx == currentx && dragy == currenty - 1)) { //onder
board.getBoard()[dragy][dragx] = -board.getBoard()[starty][startx]; //negatieve waarde zal een pipe worden
this.currentx = dragx;
this.currenty = dragy;
}
}
}
public int getCurrentx() {
return currentx;
}
public int getCurrenty() {
return currenty;
}
public void drawPipe(GameschermView view) {
GraphicsContext gc = view.getCanvas().getGraphicsContext2D();
for (int i = 0; i < board.getBoard().length; i++) { //rij
for (int j = 0; j < board.getBoard()[i].length; j++) { //kolom
pipex = i * board.getGRIDWIDTH();
pipey = j * board.getGRIDWIDTH();
/* Richting bepalen waar je naar gaat */
boolean left = false;
boolean right = false;
boolean above = false;
boolean below = false;
if (i > 0 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j][i - 1])) {
left = true;
}
if (j > 0 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j - 1][i])) {
above = true;
}
if (i < board.getBoard().length - 1 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j][i + 1])) {
right = true;
}
if (j < board.getBoard().length - 1 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j + 1][i])) {
below = true;
}
int val = board.getBoard()[j][i];
if (val < -9 || val > -1) continue; //waarden hierbuiten uitsluiten
Color color = Color.WHITE;
switch (val) {
case -1:
color = Color.RED;
break;
case -2:
color = Color.BLUE;
break;
case -3:
color = Color.GREEN;
break;
case -4:
color = Color.ORANGE;
break;
case -5:
color = Color.YELLOW;
break;
case -6:
color = Color.TURQUOISE;
break;
case -7:
color = Color.PURPLE;
break;
case -8:
color = Color.HOTPINK;
break;
case -9:
color = Color.BROWN;
break;
}
gc.setFill(color);
gc.fillRect(pipex + getRectOffset(), pipey + getRectOffset(), getPipeWidth(), getPipeWidth());
if (above && below) {
gc.fillRect(pipex + getRectOffset(), pipey, getPipeWidth(), board.getGRIDWIDTH());
}
if (left && right) {
gc.fillRect(pipex, pipey + getRectOffset(), board.getGRIDWIDTH(), getPipeWidth());
}
if (above && left) { //LINKS ONDER
gc.fillRect(pipex, pipey + getRectOffset(), getPipeWidth(), getPipeWidth());
gc.fillRect(pipex + getRectOffset(), pipey, getPipeWidth(), getPipeWidth());
}
if (above && right) { //RECHTS ONDER
gc.fillRect(pipex + (board.getGRIDWIDTH() / 2), pipey + getRectOffset(), getPipeWidth(), getPipeWidth());
gc.fillRect(pipex + getRectOffset(), pipey, getPipeWidth(), getPipeWidth());
}
if (below && left) { //LINKS BOVEN
gc.fillRect(pipex + getRectOffset(), pipey + (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth(), (board.getGRIDWIDTH() - getRectOffset()));
gc.fillRect(pipex, pipey + getRectOffset(), (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth());
}
if (below && right) { //RECHTS BOVEN
gc.fillRect(pipex + getRectOffset(), pipey + (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth(), (board.getGRIDWIDTH() - getRectOffset()));
gc.fillRect(pipex + getRectOffset(), pipey + getRectOffset(), (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth());
}
}
}
}
public void saveGame(int boardSize) {
this.boardSize = boardSize;
String highScore = "highscore.bin";
Path highscorePath = Paths.get(highScore);
if (Files.exists(highscorePath)) {
List<String> logList = new ArrayList<>();
List<String> playerList = new ArrayList<>();
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(highScore)))) {
while (dis.available() > 0) {
String log = dis.readUTF();
logList.add(log);
playerList.add(log.split("-")[3]);
}
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
throw new FreeFlowException(e);
}
try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(highScore)))) {
for (String log : logList) {
dos.writeUTF(log);
}
dos.writeUTF((boardSize + "x" + boardSize + " - " + date.toString() + " - " + gamePlayer.getName() + " - " + gamePlayer.getMoves() + "\n"));
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
throw new FreeFlowException(e);
}
} else {
try {
Files.createFile(highscorePath);
} catch (IOException io) {
throw new FreeFlowException(io);
}
try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(highScore)))) {
dos.writeUTF("Boardsize - Date - Playername - Moves\n");
dos.writeUTF((boardSize + "x" + boardSize + " - " + date.toString() + " - " + gamePlayer.getName() + " - " + gamePlayer.getMoves() + "\n"));
} catch (Exception e) {
throw new FreeFlowException(e);
}
}
}
public void createPlayerlist(String name) {
playerList = new ArrayList<>();
Player player = new Player(name);
playerList.add(player);
gamePlayer = playerList.get(0);
}
public boolean isWon() {
return won;
}
public void setWon(boolean won) {
this.won = won;
}
public int getPipeWidth() {
pipeWidth = board.getGRIDWIDTH() - 30;
return pipeWidth;
}
public int getRectOffset() {
return rectOffset;
}
public Player getGamePlayer() {
return gamePlayer;
}
public int getBoardSize() {
return boardSize;
}
}
| AuteveldJ/FlowSImple | src/FlowFree/Model/FlowFreeModel.java | 3,603 | //waarden hierbuiten uitsluiten
| line_comment | nl | package FlowFree.Model;
import FlowFree.View.Gamescherm.GameschermView;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Jonathan Auteveld
* @version 1.0 12/02/2021 22:43
*/
public class FlowFreeModel {
private boolean won = false;
private List<Player> playerList;
private Player gamePlayer;
private Board board = new Board();
private LocalDate date = LocalDate.now();
private int currentx;
private int currenty;
private int pipex;
private int pipey;
private int pipeWidth;
private final int rectOffset = 15;
private int boardSize;
public FlowFreeModel() {
}
public void setBoard(int row, int column) {
this.boardSize = row;
this.board.setRij(row);
this.board.setKolom(column);
this.board.readFile();
}
public void createBoard(GameschermView view) {
//canvas eerst leegmaken met clearrect
//canvas size aanpassen zodat deze mooi in het midden van het veld komt
GraphicsContext gc = view.getCanvas().getGraphicsContext2D();
gc.clearRect(0, 0, view.getCanvas().getWidth(), view.getCanvas().getHeight());
view.getCanvas().setWidth(board.getGRIDWIDTH() * board.getRij() + 10);
view.getCanvas().setHeight(board.getGRIDWIDTH() * board.getKolom() + 10);
//bord aanmaken door vierkanten te tekenen op het canvas
//5X5 = 5 kleuren, 6x6, 7X7, 8X8 = 6 kleuren ,9X9 = 9 kleuren
//board tekenen
gc.setStroke(Color.WHITE);
for (int i = 0; i < board.getBoard().length; i++) { //rij
for (int j = 0; j < board.getBoard()[i].length; j++) { //kolom
int x = i * board.getGRIDWIDTH();
int y = j * board.getGRIDWIDTH();
int diameter = board.getGRIDWIDTH() - 10;
int circOffset = 5;
gc.strokeRect(x, y, board.getGRIDWIDTH(), board.getGRIDWIDTH());
int val = board.getBoard()[j][i];
if (val < 1 || val > 9) continue; //waarden hierbuiten<SUF>
Color color = Color.WHITE;
switch (val) {
case 1:
color = Color.RED;
break;
case 2:
color = Color.BLUE;
break;
case 3:
color = Color.GREEN;
break;
case 4:
color = Color.ORANGE;
break;
case 5:
color = Color.YELLOW;
break;
case 6:
color = Color.TURQUOISE;
break;
case 7:
color = Color.PURPLE;
break;
case 8:
color = Color.HOTPINK;
break;
case 9:
color = Color.BROWN;
break;
}
gc.setFill(color);
gc.fillOval(x + circOffset, y + circOffset, diameter, diameter);
}
}
}
/* als de positie op het spelbord waar je klikt een bol is ( > 0 uit de array)
* dan ga je deze positie selecteren om een pipe te starten */
public boolean dotSelection(int x, int y) {
if (board.getBoard()[y][x] > 0) {
return true;
} else
return false;
}
/* positie bepalen waar je muis naar beweegt
* deze plaats wordt een negatieve waarde van de overeenkomende bol dat geselecteerd is
* hierover zal een pipe getekend worden.
* Dit wordt voorgesteld als een negatieve waarde van de Board array */
public void drag(int currentx, int currenty, int dragx, int dragy, int startx, int starty) {
if (dragx >= 0 && dragy >= 0 &&
dragy < board.getBoard().length && dragx < board.getBoard()[0].length && board.getBoard()[dragy][dragx] == 0) {
if ((dragx == currentx + 1 && dragy == currenty) || //rechts
(dragx == currentx - 1 && dragy == currenty) || //links
(dragx == currentx && dragy == currenty + 1) || //boven
(dragx == currentx && dragy == currenty - 1)) { //onder
board.getBoard()[dragy][dragx] = -board.getBoard()[starty][startx]; //negatieve waarde zal een pipe worden
this.currentx = dragx;
this.currenty = dragy;
}
}
}
public int getCurrentx() {
return currentx;
}
public int getCurrenty() {
return currenty;
}
public void drawPipe(GameschermView view) {
GraphicsContext gc = view.getCanvas().getGraphicsContext2D();
for (int i = 0; i < board.getBoard().length; i++) { //rij
for (int j = 0; j < board.getBoard()[i].length; j++) { //kolom
pipex = i * board.getGRIDWIDTH();
pipey = j * board.getGRIDWIDTH();
/* Richting bepalen waar je naar gaat */
boolean left = false;
boolean right = false;
boolean above = false;
boolean below = false;
if (i > 0 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j][i - 1])) {
left = true;
}
if (j > 0 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j - 1][i])) {
above = true;
}
if (i < board.getBoard().length - 1 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j][i + 1])) {
right = true;
}
if (j < board.getBoard().length - 1 && Math.abs(board.getBoard()[j][i]) == Math.abs(board.getBoard()[j + 1][i])) {
below = true;
}
int val = board.getBoard()[j][i];
if (val < -9 || val > -1) continue; //waarden hierbuiten uitsluiten
Color color = Color.WHITE;
switch (val) {
case -1:
color = Color.RED;
break;
case -2:
color = Color.BLUE;
break;
case -3:
color = Color.GREEN;
break;
case -4:
color = Color.ORANGE;
break;
case -5:
color = Color.YELLOW;
break;
case -6:
color = Color.TURQUOISE;
break;
case -7:
color = Color.PURPLE;
break;
case -8:
color = Color.HOTPINK;
break;
case -9:
color = Color.BROWN;
break;
}
gc.setFill(color);
gc.fillRect(pipex + getRectOffset(), pipey + getRectOffset(), getPipeWidth(), getPipeWidth());
if (above && below) {
gc.fillRect(pipex + getRectOffset(), pipey, getPipeWidth(), board.getGRIDWIDTH());
}
if (left && right) {
gc.fillRect(pipex, pipey + getRectOffset(), board.getGRIDWIDTH(), getPipeWidth());
}
if (above && left) { //LINKS ONDER
gc.fillRect(pipex, pipey + getRectOffset(), getPipeWidth(), getPipeWidth());
gc.fillRect(pipex + getRectOffset(), pipey, getPipeWidth(), getPipeWidth());
}
if (above && right) { //RECHTS ONDER
gc.fillRect(pipex + (board.getGRIDWIDTH() / 2), pipey + getRectOffset(), getPipeWidth(), getPipeWidth());
gc.fillRect(pipex + getRectOffset(), pipey, getPipeWidth(), getPipeWidth());
}
if (below && left) { //LINKS BOVEN
gc.fillRect(pipex + getRectOffset(), pipey + (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth(), (board.getGRIDWIDTH() - getRectOffset()));
gc.fillRect(pipex, pipey + getRectOffset(), (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth());
}
if (below && right) { //RECHTS BOVEN
gc.fillRect(pipex + getRectOffset(), pipey + (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth(), (board.getGRIDWIDTH() - getRectOffset()));
gc.fillRect(pipex + getRectOffset(), pipey + getRectOffset(), (board.getGRIDWIDTH() - getRectOffset()), getPipeWidth());
}
}
}
}
public void saveGame(int boardSize) {
this.boardSize = boardSize;
String highScore = "highscore.bin";
Path highscorePath = Paths.get(highScore);
if (Files.exists(highscorePath)) {
List<String> logList = new ArrayList<>();
List<String> playerList = new ArrayList<>();
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(highScore)))) {
while (dis.available() > 0) {
String log = dis.readUTF();
logList.add(log);
playerList.add(log.split("-")[3]);
}
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
throw new FreeFlowException(e);
}
try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(highScore)))) {
for (String log : logList) {
dos.writeUTF(log);
}
dos.writeUTF((boardSize + "x" + boardSize + " - " + date.toString() + " - " + gamePlayer.getName() + " - " + gamePlayer.getMoves() + "\n"));
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
throw new FreeFlowException(e);
}
} else {
try {
Files.createFile(highscorePath);
} catch (IOException io) {
throw new FreeFlowException(io);
}
try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(highScore)))) {
dos.writeUTF("Boardsize - Date - Playername - Moves\n");
dos.writeUTF((boardSize + "x" + boardSize + " - " + date.toString() + " - " + gamePlayer.getName() + " - " + gamePlayer.getMoves() + "\n"));
} catch (Exception e) {
throw new FreeFlowException(e);
}
}
}
public void createPlayerlist(String name) {
playerList = new ArrayList<>();
Player player = new Player(name);
playerList.add(player);
gamePlayer = playerList.get(0);
}
public boolean isWon() {
return won;
}
public void setWon(boolean won) {
this.won = won;
}
public int getPipeWidth() {
pipeWidth = board.getGRIDWIDTH() - 30;
return pipeWidth;
}
public int getRectOffset() {
return rectOffset;
}
public Player getGamePlayer() {
return gamePlayer;
}
public int getBoardSize() {
return boardSize;
}
}
|
63169_6 | package nl.glassaanhuis.facebooktrial.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.NonCachingTokenCachingStrategy;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class ProfileActivity extends Activity {
private String url;
void draw(Session session) {
final TextView name = (TextView) findViewById(R.id.userName);
final ProfilePictureView pic = (ProfilePictureView) findViewById(R.id.photo);
final String str = session.getAccessToken();
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
name.setText(user.getName());
pic.setProfileId(user.getId());
ConnectionTask task = new ConnectionTask();
String[] params = new String[2];
params[0] = "http://glas.mycel.nl/facebook?accesstoken=" + str;
task.execute(params);
}
}).executeAsync();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
draw(session);
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectionTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String aString = "";
try {
URL aURL = new URL(urls[0]);
final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = aHttpURLConnection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(
aInputStream);
ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
int current = 0;
while ((current = aBufferedInputStream.read()) != -1) {
aByteArrayBuffer.append((byte) current);
}
aString = new String(aByteArrayBuffer.toByteArray());
} catch (IOException e) {
e.printStackTrace();
// HAHAA, HOEZO ERROR HANDLING??
}
return aString;
}
@Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
JSONArray plaatjes;
JSONArray probeer = jObject.getJSONArray("photos");
plaatjes = jObject.getJSONArray("plaatjes");
// doe iets met data
url = probeer.getJSONObject(0).get("source").toString();
GridView gridview = (GridView) findViewById(R.id.gridLayout);
gridview.setAdapter(new ImageAdapter(plaatjes, ProfileActivity.this));
RelativeLayout viewtje = (RelativeLayout) findViewById(R.id.background);
String[] params = new String[2];
params[0] = url;
DownloadImageTask task = new DownloadImageTask(viewtje);
task.execute(params);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
RelativeLayout viewtje;
public DownloadImageTask(RelativeLayout bmImage) {
this.viewtje = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
Drawable d = new BitmapDrawable(getResources(),result);
viewtje.setBackground(d);
viewtje.getBackground().setAlpha(55);
}
}
public void likePage(View v) {
//final String urlFb = "fb://page/glasvezelpaleiskwartier";
final String urlFb = "fb://page/1450066045229608";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlFb));
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() == 0) {
//final String urlBrowser = "https://www.facebook.com/glasvezelpaleiskwartier";
final String urlBrowser = "https://www.facebook.com/pages/1450066045229608";
intent.setData(Uri.parse(urlBrowser));
}
startActivity(intent);
}
}
| Avans-Everyware-42IN11EWe/FacebookTrial | app/src/main/java/nl/glassaanhuis/facebooktrial/app/ProfileActivity.java | 2,063 | // doe iets met data | line_comment | nl | package nl.glassaanhuis.facebooktrial.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.NonCachingTokenCachingStrategy;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class ProfileActivity extends Activity {
private String url;
void draw(Session session) {
final TextView name = (TextView) findViewById(R.id.userName);
final ProfilePictureView pic = (ProfilePictureView) findViewById(R.id.photo);
final String str = session.getAccessToken();
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
name.setText(user.getName());
pic.setProfileId(user.getId());
ConnectionTask task = new ConnectionTask();
String[] params = new String[2];
params[0] = "http://glas.mycel.nl/facebook?accesstoken=" + str;
task.execute(params);
}
}).executeAsync();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
draw(session);
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectionTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String aString = "";
try {
URL aURL = new URL(urls[0]);
final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = aHttpURLConnection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(
aInputStream);
ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
int current = 0;
while ((current = aBufferedInputStream.read()) != -1) {
aByteArrayBuffer.append((byte) current);
}
aString = new String(aByteArrayBuffer.toByteArray());
} catch (IOException e) {
e.printStackTrace();
// HAHAA, HOEZO ERROR HANDLING??
}
return aString;
}
@Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
JSONArray plaatjes;
JSONArray probeer = jObject.getJSONArray("photos");
plaatjes = jObject.getJSONArray("plaatjes");
// doe iets<SUF>
url = probeer.getJSONObject(0).get("source").toString();
GridView gridview = (GridView) findViewById(R.id.gridLayout);
gridview.setAdapter(new ImageAdapter(plaatjes, ProfileActivity.this));
RelativeLayout viewtje = (RelativeLayout) findViewById(R.id.background);
String[] params = new String[2];
params[0] = url;
DownloadImageTask task = new DownloadImageTask(viewtje);
task.execute(params);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
RelativeLayout viewtje;
public DownloadImageTask(RelativeLayout bmImage) {
this.viewtje = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
Drawable d = new BitmapDrawable(getResources(),result);
viewtje.setBackground(d);
viewtje.getBackground().setAlpha(55);
}
}
public void likePage(View v) {
//final String urlFb = "fb://page/glasvezelpaleiskwartier";
final String urlFb = "fb://page/1450066045229608";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlFb));
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() == 0) {
//final String urlBrowser = "https://www.facebook.com/glasvezelpaleiskwartier";
final String urlBrowser = "https://www.facebook.com/pages/1450066045229608";
intent.setData(Uri.parse(urlBrowser));
}
startActivity(intent);
}
}
|
129448_0 | import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import static javafx.application.Application.launch;
import javafx.application.Application;
import javafx.scene.image.Image;
public class JavaFXApplication extends Application {
//Main methode, zorgt voor de start van de applicatie
public static void main(String[] args) throws SQLException {
launch(args);
}
@Override //Start methode zorgt voor de weergave van het eerste scherm: Login
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
// Pad relatief aan de project directory
Path path = Paths.get("src/FXML_Bestanden/login.fxml");
URL url = path.toUri().toURL();
loader.setLocation(url);
VBox vbox = loader.<VBox>load();
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.getIcons().add(new Image(this.getClass().getResource("/FXML_Bestanden/Logo.png").toString()));
primaryStage.show();
}
}
| Avans2023-JGKJ/CodeAcademy-JGKJ | JavaFX/JavaFX/src/JavaFXApplication.java | 387 | //Main methode, zorgt voor de start van de applicatie | line_comment | nl | import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import static javafx.application.Application.launch;
import javafx.application.Application;
import javafx.scene.image.Image;
public class JavaFXApplication extends Application {
//Main methode,<SUF>
public static void main(String[] args) throws SQLException {
launch(args);
}
@Override //Start methode zorgt voor de weergave van het eerste scherm: Login
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
// Pad relatief aan de project directory
Path path = Paths.get("src/FXML_Bestanden/login.fxml");
URL url = path.toUri().toURL();
loader.setLocation(url);
VBox vbox = loader.<VBox>load();
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.getIcons().add(new Image(this.getClass().getResource("/FXML_Bestanden/Logo.png").toString()));
primaryStage.show();
}
}
|
174732_3 | package com.practice.miscellaneous;
import java.util.*;
/**Problem statement:
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Example 2:
Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j] is a digit 1-9 or '.'.
Leetcode link: https://leetcode.com/problems/valid-sudoku/description/
**/
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
Coordinates coord = new Coordinates(0, 0);
//check rows
boolean rowsAreValid = allRowsAreValid(board, coord );
//check columns
boolean colsAreValid = allColumnsAreValid(board, coord );
//check boxes
List<List<Character>> cubesList = createCubesList(board, coord);
boolean cubesAreValid = allCubesAreValid(cubesList, coord);
return rowsAreValid && colsAreValid && cubesAreValid;
}
public static boolean allCubesAreValid(List < List < Character >> cubesList, Coordinates coord ) {
for (List < Character > singleCubeList: cubesList) {
Set < Character > set = new HashSet < > ();
for (Character c: singleCubeList) {
if (!set.add(c)) {
return false;
}
}
}
return true;
}
public static List < List < Character >> createCubesList(char[][] board, Coordinates coord ) {
List < List < Character >> result = new ArrayList < > ();
int width = board[0].length;
int height = board.length;
//get the top
while (coord.wall <= width) {
List < Character > singleCubeList = addElementsForCube(board, coord);
result.add(singleCubeList);
coord.goRight();
}
//get the middle
coord.resetCoordinatesToZero();
coord.goDown();
while (coord.wall <= width) {
List < Character > singleCubeList = addElementsForCube(board, coord);
result.add(singleCubeList);
coord.goRight();
}
//get the end
coord.resetCoordinatesToZero();
coord.goDown();
coord.goDown();
while (coord.wall <= width) {
List < Character > singleCubeList = addElementsForCube(board, coord);
result.add(singleCubeList);
coord.goRight();
}
return result;
}
public static List < Character > addElementsForCube(char[][] board, Coordinates coord) {
List < Character > result = new ArrayList < > ();
for (int row = coord.floor - 3; row < coord.floor; row++) {
for (int col = coord.wall - 3; col < coord.wall; col++) {
char current = board[row][col];
if (Character.isDigit(current)) {
result.add(current);
}
}
}
return result;
}
public static boolean allColumnsAreValid(char[][] board, Coordinates coord ) {
int height = board.length;
int width = board[0].length;
for (int col = 0; col < width; col++) {
Set < Character > set = new HashSet < > ();
for (int row = 0; row < height; row++) {
char number = board[row][col];
if (Character.isDigit(number)) {
if (!set.add(number)) {
return false;
}
}
}
}
return true;
}
public static boolean allRowsAreValid(char[][] board, Coordinates coord ) {
for (char[] singleRow: board) {
Set < Character > set = new HashSet < > ();
for (char number: singleRow) {
if (Character.isDigit(number)) {
if (!set.add(number)) {
return false;
}
}
}
}
return true;
}
}
class Coordinates {
int row;
int col;
int wall;
int floor;
Coordinates(int row, int col) {
this.row = row;
this.col = col;
this.wall = col + 3;
this.floor = row + 3;
}
public void goRight() {
col += 3;
wall += 3;
}
public void resetCoordinatesToZero() {
row = 0;
col = 0;
wall = col + 3;
floor = row + 3;
}
public void goDown() {
row += 3;
floor += 3;
}
}
| AveryCS/data-structures-and-algorithms | src/com/practice/miscellaneous/ValidSudoku.java | 1,847 | //get the end | line_comment | nl | package com.practice.miscellaneous;
import java.util.*;
/**Problem statement:
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Example 2:
Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j] is a digit 1-9 or '.'.
Leetcode link: https://leetcode.com/problems/valid-sudoku/description/
**/
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
Coordinates coord = new Coordinates(0, 0);
//check rows
boolean rowsAreValid = allRowsAreValid(board, coord );
//check columns
boolean colsAreValid = allColumnsAreValid(board, coord );
//check boxes
List<List<Character>> cubesList = createCubesList(board, coord);
boolean cubesAreValid = allCubesAreValid(cubesList, coord);
return rowsAreValid && colsAreValid && cubesAreValid;
}
public static boolean allCubesAreValid(List < List < Character >> cubesList, Coordinates coord ) {
for (List < Character > singleCubeList: cubesList) {
Set < Character > set = new HashSet < > ();
for (Character c: singleCubeList) {
if (!set.add(c)) {
return false;
}
}
}
return true;
}
public static List < List < Character >> createCubesList(char[][] board, Coordinates coord ) {
List < List < Character >> result = new ArrayList < > ();
int width = board[0].length;
int height = board.length;
//get the top
while (coord.wall <= width) {
List < Character > singleCubeList = addElementsForCube(board, coord);
result.add(singleCubeList);
coord.goRight();
}
//get the middle
coord.resetCoordinatesToZero();
coord.goDown();
while (coord.wall <= width) {
List < Character > singleCubeList = addElementsForCube(board, coord);
result.add(singleCubeList);
coord.goRight();
}
//get the<SUF>
coord.resetCoordinatesToZero();
coord.goDown();
coord.goDown();
while (coord.wall <= width) {
List < Character > singleCubeList = addElementsForCube(board, coord);
result.add(singleCubeList);
coord.goRight();
}
return result;
}
public static List < Character > addElementsForCube(char[][] board, Coordinates coord) {
List < Character > result = new ArrayList < > ();
for (int row = coord.floor - 3; row < coord.floor; row++) {
for (int col = coord.wall - 3; col < coord.wall; col++) {
char current = board[row][col];
if (Character.isDigit(current)) {
result.add(current);
}
}
}
return result;
}
public static boolean allColumnsAreValid(char[][] board, Coordinates coord ) {
int height = board.length;
int width = board[0].length;
for (int col = 0; col < width; col++) {
Set < Character > set = new HashSet < > ();
for (int row = 0; row < height; row++) {
char number = board[row][col];
if (Character.isDigit(number)) {
if (!set.add(number)) {
return false;
}
}
}
}
return true;
}
public static boolean allRowsAreValid(char[][] board, Coordinates coord ) {
for (char[] singleRow: board) {
Set < Character > set = new HashSet < > ();
for (char number: singleRow) {
if (Character.isDigit(number)) {
if (!set.add(number)) {
return false;
}
}
}
}
return true;
}
}
class Coordinates {
int row;
int col;
int wall;
int floor;
Coordinates(int row, int col) {
this.row = row;
this.col = col;
this.wall = col + 3;
this.floor = row + 3;
}
public void goRight() {
col += 3;
wall += 3;
}
public void resetCoordinatesToZero() {
row = 0;
col = 0;
wall = col + 3;
floor = row + 3;
}
public void goDown() {
row += 3;
floor += 3;
}
}
|
63441_34 | package be.msec;
import be.msec.client.CAService;
import be.msec.client.CallableMiddelwareMethodes;
import be.msec.client.Challenge;
import be.msec.client.MessageToAuthCard;
import be.msec.client.SignedCertificate;
import be.msec.client.TimeInfoStruct;
import be.msec.controllers.MainServiceController;
import be.msec.controllers.RootMenuController;
import be.msec.helpers.Controller;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.awt.List;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.rmi.CORBA.Util;
public class ServiceProviderMain extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private Controller currentViewController;
private MainServiceController mainController;
private Socket serviceProviderSocket = null;
private String lastActionSPName = null;
private ArrayList<ServiceProvider> serviceProviders;
private SecretKeySpec symKey;
private IvParameterSpec ivSpec;
static final int portSP = 8003;
private byte[] challengeToAuthCard;
private ServiceProvider lastUsedSP;
/**
* Constructor
*/
public ServiceProviderMain() throws RemoteException {
}
public static void main(String[] args) {
launch(args);
}
public ArrayList<ServiceProvider> getServiceProviders() {
return serviceProviders;
}
public void setServiceProviders(ArrayList<ServiceProvider> serviceProviders) {
this.serviceProviders = serviceProviders;
}
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Service Provider overview");
initRootLayout();
showMainView();
connectToMiddleWare();
}
@Override
public void stop() {
System.out.println("Stage is Normaly closed");
}
public void sendCommandToMiddleware(ServiceProviderAction action, boolean waitForResponse) {
ObjectOutputStream objectoutputstream = null;
this.lastActionSPName = action.getServiceProvider();
try {
System.out.println("Send action to the middleware: " + action.getAction().getName());
objectoutputstream = new ObjectOutputStream(serviceProviderSocket.getOutputStream());
objectoutputstream.writeObject(action);
//wait for response)
if(waitForResponse){
//System.out.println("Commando needs response from MW! ...");
ListenForMiddelware();
}
}catch (Exception e) {
System.out.println(e);
}
}
public void authenticateServiceProvider(ServiceProvider selectedServiceProvider) {
// STEP 2
// 2. authenticate SP
System.out.println("2. auth service provider, SP");
ServiceProviderAction action = new ServiceProviderAction(new ServiceAction("Authenticate SP", CallableMiddelwareMethodes.AUTH_SP),selectedServiceProvider.getCertificate());
action.setServiceProvider(selectedServiceProvider.getName());
sendCommandToMiddleware(action,true);
}
public void recreateSessionKey(Challenge challenge) {
// STEP 3, after challenge response from MW.
System.out.println("3. recreateSessionKey, SP");
byte[] nameBytes = challenge.getNameBytes();
byte[] rndBytes = challenge.getRndBytes();
byte [] challengeBytes = challenge.getChallengeBytes();
//System.out.println("encr chlng bytes "+bytesToDec(challengeBytes));
//System.out.println("encr name bytes "+bytesToDec(nameBytes));
byte[] decryptedNameBytes;
byte[] decryptedChallengeBytes;
for(ServiceProvider sp : serviceProviders) {
if(sp.name.equals(lastActionSPName)) {
System.out.println("recreate session key "+sp.getName());
try {
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.DECRYPT_MODE, (RSAPrivateKey)sp.getPrivateKey());
System.out.println();
byte [] rnd = rsaCipher.doFinal(rndBytes);
//byte[] rnd = new String(decrypted);
//System.out.println("decrypted rndbytes "+bytesToDec(rnd));
//create session key
byte[] ivdata = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
this.ivSpec = new IvParameterSpec(ivdata);
this.symKey = new SecretKeySpec(rnd, "AES");
System.out.println("SETTING SESSION KEY!!!! " + symKey);
Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.DECRYPT_MODE, symKey, ivSpec);
decryptedChallengeBytes = aesCipher.doFinal(challengeBytes);
decryptedNameBytes = aesCipher.doFinal(nameBytes);
//System.out.println("decrypted chlng bytes "+bytesToDec(decryptedChallengeBytes));
//System.out.println("decrypted name bytes "+bytesToDec(decryptedNameBytes));
String name = new String(decryptedNameBytes);
byte [] respChallengeBytes = addOne_Bad(decryptedChallengeBytes);
//TODO beno encrypt challenge response
aesCipher.init(Cipher.ENCRYPT_MODE, this.symKey, this.ivSpec);
byte[] encryptedRespChallenge = aesCipher.doFinal(respChallengeBytes);
//send challenge response back to MW
ServiceProviderAction action = new ServiceProviderAction(new ServiceAction("verify challenge, session key", CallableMiddelwareMethodes.VERIFY_CHALLENGE), null);
action.setChallengeBytes(encryptedRespChallenge);
sendCommandToMiddleware(action,false); // verwacht niks terug
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void authenticateCard() {
// STEP 4
System.out.println("4. auth card, SP");
mainController.addToDataLog("Start authentication of card" );
//generate random bytes for challenge
byte[] b = new byte[16];
new Random().nextBytes(b);
challengeToAuthCard = b;
byte[] encryptedChallengeBytes = null;
//encrypt challengeBytes
try {
Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec);
encryptedChallengeBytes = aesCipher.doFinal(b);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
System.out.println("ERROR IN auth card, SP :");
System.out.println(symKey.getEncoded() +" "+ ivSpec.getIV());
e.printStackTrace();
}
//generate an action to send to the card
ServiceProviderAction action = new ServiceProviderAction(new ServiceAction("verify challenge to authenticate card", CallableMiddelwareMethodes.AUTH_CARD));
action.setChallengeBytes(encryptedChallengeBytes);
sendCommandToMiddleware(action,true);
}
public void authenticateCard(MessageToAuthCard cardMessage) {
// STEP 5, after second response from MW
System.out.println("5. AUTH CARD WITH MESSAGE");
//System.out.println("DONE " + bytesToHex(cardMessage.getMessage()));
Cipher aesCipher;
try {
//decrypte message
aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.DECRYPT_MODE, symKey, ivSpec);
byte[] message = aesCipher.doFinal(padding(cardMessage.getMessage()));
//System.out.println(bytesToDec(message));
//check signature
byte[] signedBytes = Arrays.copyOfRange(message, 0, 72);
byte[] signature = Arrays.copyOfRange(message, 72, 136);
Signature signer = Signature.getInstance("SHA1WithRSA");
signer.initVerify(CAService.loadPublicKey("RSA"));
signer.update(signedBytes);
if(!signer.verify(signature)) {
System.out.println("Card has a valid common certificate. (authenticate card)");
} else {
System.out.println("Card doesn't have a valid common certificate.");
return;
}
//check if sign with CommonCert key is ok
//first regenerate public key from commoncertificate
BigInteger exponent = new BigInteger(1,Arrays.copyOfRange(message, 0, 3));
BigInteger modulus = new BigInteger(1,Arrays.copyOfRange(message, 4, 68));
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
signer.initVerify(KeyFactory.getInstance("RSA").generatePublic(spec));
//generate byte array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(challengeToAuthCard);
outputStream.write("AUTH".getBytes());
byte[] bytesToSign = outputStream.toByteArray();
//System.out.println("bytes to sign : " + bytesToDec(Arrays.copyOfRange(message, 156, 220)));
//System.out.println("bytes to sign : " + KeyFactory.getInstance("RSA").generatePublic(spec));
//check sign
if(signer.verify(Arrays.copyOfRange(message, 156, 220))) {
System.out.println("Card is valid, challenge is ok. (authenticate card)");
} else {
System.out.println("Card is not valid, challenge is nok. HIER ZIT ER NOG EEN FOUT, DIE public key wordt verkeerd opgebouwd door die BigIntegers, de bytes zijn sws juist.");
return;
}
} catch (NoSuchAlgorithmException | SignatureException | IOException | InvalidKeySpecException | InvalidKeyException | URISyntaxException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void submitDataQuery(ServiceProvider selectedServiceProvider, int query) {
System.out.println("1, Start query, SP");
// STEP 1
// Do Authentication
if(lastUsedSP != selectedServiceProvider) {
System.out.println("First time with this SP --> athenticate");
authenticateServiceProvider(selectedServiceProvider);
// STEP 4
//start the authentication of the card (step 3)
authenticateCard();
//STEP 7
// Get data
System.out.println("7. Get Data, SP");
ServiceProviderAction request = new ServiceProviderAction(new ServiceAction("Get Data",CallableMiddelwareMethodes.GET_DATA), selectedServiceProvider.getCertificate());
request.setServiceProvider(selectedServiceProvider.getName());
request.setDataQuery((short) query);
sendCommandToMiddleware(request,true);
lastUsedSP = selectedServiceProvider;
}else {
System.out.println("Skipping authentication phase because already logged in to this service provider!");
ServiceProviderAction request = new ServiceProviderAction(new ServiceAction("Get Data",CallableMiddelwareMethodes.GET_DATA), selectedServiceProvider.getCertificate());
request.setServiceProvider(selectedServiceProvider.getName());
request.setDataQuery((short) query);
sendCommandToMiddleware(request,true);
}
}
public void connectToMiddleWare() {
try {
serviceProviderSocket = new Socket("localhost", portSP);
} catch (IOException ex) {
//System.out.println("CANNOT CONNECT TO MIDDLEWARE " + ex);
}
//System.out.println("Serviceprovider connected to middleware: " + serviceProviderSocket);
}
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ServiceProviderMain.class.getResource("RootMenu.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
//scene.getStylesheets().add("be.msec.stylesheet.css");
// Give the controller access to the main app.
RootMenuController controller = loader.getController();
controller.setMain(this);
currentViewController = controller;
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public Controller getCurrentViewController() {
return currentViewController;
}
// --------------------- LOGIN VIEW ------------------------
public void showMainView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ServiceProviderMain.class.getResource("mainServiceView.fxml"));
System.out.println("Loading Main Page");
AnchorPane loginView = (AnchorPane) loader.load();
//controller initialiseren + koppelen aan mainClient
MainServiceController controller = loader.getController();
controller.setMainController(this);
currentViewController = controller;
mainController = controller;
rootLayout.setCenter(loginView);
} catch (Exception e) {
e.printStackTrace();
}
}
private void ListenForMiddelware() {
System.out.println("Listening for MW...");
Object obj = null;
try {
ObjectInputStream objectinputstream = new ObjectInputStream(serviceProviderSocket.getInputStream());
obj = objectinputstream.readObject();
System.out.println("OBJECT RECEIVED");
if(obj instanceof Challenge) {
Challenge challengeFromSC = (Challenge)obj;
mainController.addToDataLog("Succesfully received challenge" );
System.out.println("CHALLENGE RECEIVED");
//recreate session key, respond to challenge
recreateSessionKey(challengeFromSC);
notify();
}
else if( obj instanceof String) {
// STEP 8
String answer = (String)obj;
System.out.println("STRING RECEIVEC, "+answer);
mainController.addToDataLog("Succesfully received: " +answer);
}
else if(obj instanceof MessageToAuthCard) {
System.out.println("MESSTOAUTHCARD RECEIVED");
authenticateCard((MessageToAuthCard) obj);
}
else if(obj instanceof byte[]) {
decryptAndShowData((byte[]) obj);
}
else {
System.out.println("UNKNOW OBJECT received "+ obj);
}
System.out.println("succesfully received an answer!");
}catch (Exception e) {
System.out.println(e);
}
}
private void decryptAndShowData(byte[] encryptedData) {
//decrypt and show in log
try {
System.out.println("Start decrypting from received data");
Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.DECRYPT_MODE, symKey, ivSpec);
byte [] cropped = new byte[encryptedData.length - 2];
cropped = Arrays.copyOfRange(encryptedData, 2, cropped.length);
cropped = padding(cropped);
System.out.println("the length is: "+ cropped.length);
byte[] data = aesCipher.doFinal(cropped);
String str = new String(data, StandardCharsets.UTF_8);
mainController.addToDataLog("Received data from card: "+ str );
System.out.println("data is: " + str);
System.out.println("Succesfully decrypted");
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ------------------------------------
// ------- UTILITY FUNCTIONS ----------
// ------------------------------------
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
String str = "";
for (int j = 0; j < hexChars.length; j += 2) {
str += "0x" + hexChars[j] + hexChars[j + 1] + ", ";
}
return str;
}
private byte [] padding(byte[] data) {
if(data.length %16 != 0) {
short length = (short) (data.length + 16 - data.length %16);
byte [] paddedData = new byte[length];
paddedData = Arrays.copyOfRange(data, 0, data.length-1);
return paddedData;
}
return data;
}
public String bytesToDec(byte[] barray) {
String str = "";
for (byte b : barray)
str += (int) b + ", ";
return str;
}
public static byte[] addOne_Bad(byte[] A) {
short lastPosition = (short)(A.length - 1);
// Looping from right to left
A[lastPosition] += 1;
return A;
}
}
| Axxeption/smartcard | workspace/ServiceProvider/src/be/msec/ServiceProviderMain.java | 5,619 | //controller initialiseren + koppelen aan mainClient | line_comment | nl | package be.msec;
import be.msec.client.CAService;
import be.msec.client.CallableMiddelwareMethodes;
import be.msec.client.Challenge;
import be.msec.client.MessageToAuthCard;
import be.msec.client.SignedCertificate;
import be.msec.client.TimeInfoStruct;
import be.msec.controllers.MainServiceController;
import be.msec.controllers.RootMenuController;
import be.msec.helpers.Controller;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.awt.List;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.rmi.CORBA.Util;
public class ServiceProviderMain extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private Controller currentViewController;
private MainServiceController mainController;
private Socket serviceProviderSocket = null;
private String lastActionSPName = null;
private ArrayList<ServiceProvider> serviceProviders;
private SecretKeySpec symKey;
private IvParameterSpec ivSpec;
static final int portSP = 8003;
private byte[] challengeToAuthCard;
private ServiceProvider lastUsedSP;
/**
* Constructor
*/
public ServiceProviderMain() throws RemoteException {
}
public static void main(String[] args) {
launch(args);
}
public ArrayList<ServiceProvider> getServiceProviders() {
return serviceProviders;
}
public void setServiceProviders(ArrayList<ServiceProvider> serviceProviders) {
this.serviceProviders = serviceProviders;
}
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Service Provider overview");
initRootLayout();
showMainView();
connectToMiddleWare();
}
@Override
public void stop() {
System.out.println("Stage is Normaly closed");
}
public void sendCommandToMiddleware(ServiceProviderAction action, boolean waitForResponse) {
ObjectOutputStream objectoutputstream = null;
this.lastActionSPName = action.getServiceProvider();
try {
System.out.println("Send action to the middleware: " + action.getAction().getName());
objectoutputstream = new ObjectOutputStream(serviceProviderSocket.getOutputStream());
objectoutputstream.writeObject(action);
//wait for response)
if(waitForResponse){
//System.out.println("Commando needs response from MW! ...");
ListenForMiddelware();
}
}catch (Exception e) {
System.out.println(e);
}
}
public void authenticateServiceProvider(ServiceProvider selectedServiceProvider) {
// STEP 2
// 2. authenticate SP
System.out.println("2. auth service provider, SP");
ServiceProviderAction action = new ServiceProviderAction(new ServiceAction("Authenticate SP", CallableMiddelwareMethodes.AUTH_SP),selectedServiceProvider.getCertificate());
action.setServiceProvider(selectedServiceProvider.getName());
sendCommandToMiddleware(action,true);
}
public void recreateSessionKey(Challenge challenge) {
// STEP 3, after challenge response from MW.
System.out.println("3. recreateSessionKey, SP");
byte[] nameBytes = challenge.getNameBytes();
byte[] rndBytes = challenge.getRndBytes();
byte [] challengeBytes = challenge.getChallengeBytes();
//System.out.println("encr chlng bytes "+bytesToDec(challengeBytes));
//System.out.println("encr name bytes "+bytesToDec(nameBytes));
byte[] decryptedNameBytes;
byte[] decryptedChallengeBytes;
for(ServiceProvider sp : serviceProviders) {
if(sp.name.equals(lastActionSPName)) {
System.out.println("recreate session key "+sp.getName());
try {
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.DECRYPT_MODE, (RSAPrivateKey)sp.getPrivateKey());
System.out.println();
byte [] rnd = rsaCipher.doFinal(rndBytes);
//byte[] rnd = new String(decrypted);
//System.out.println("decrypted rndbytes "+bytesToDec(rnd));
//create session key
byte[] ivdata = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
this.ivSpec = new IvParameterSpec(ivdata);
this.symKey = new SecretKeySpec(rnd, "AES");
System.out.println("SETTING SESSION KEY!!!! " + symKey);
Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.DECRYPT_MODE, symKey, ivSpec);
decryptedChallengeBytes = aesCipher.doFinal(challengeBytes);
decryptedNameBytes = aesCipher.doFinal(nameBytes);
//System.out.println("decrypted chlng bytes "+bytesToDec(decryptedChallengeBytes));
//System.out.println("decrypted name bytes "+bytesToDec(decryptedNameBytes));
String name = new String(decryptedNameBytes);
byte [] respChallengeBytes = addOne_Bad(decryptedChallengeBytes);
//TODO beno encrypt challenge response
aesCipher.init(Cipher.ENCRYPT_MODE, this.symKey, this.ivSpec);
byte[] encryptedRespChallenge = aesCipher.doFinal(respChallengeBytes);
//send challenge response back to MW
ServiceProviderAction action = new ServiceProviderAction(new ServiceAction("verify challenge, session key", CallableMiddelwareMethodes.VERIFY_CHALLENGE), null);
action.setChallengeBytes(encryptedRespChallenge);
sendCommandToMiddleware(action,false); // verwacht niks terug
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void authenticateCard() {
// STEP 4
System.out.println("4. auth card, SP");
mainController.addToDataLog("Start authentication of card" );
//generate random bytes for challenge
byte[] b = new byte[16];
new Random().nextBytes(b);
challengeToAuthCard = b;
byte[] encryptedChallengeBytes = null;
//encrypt challengeBytes
try {
Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec);
encryptedChallengeBytes = aesCipher.doFinal(b);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
System.out.println("ERROR IN auth card, SP :");
System.out.println(symKey.getEncoded() +" "+ ivSpec.getIV());
e.printStackTrace();
}
//generate an action to send to the card
ServiceProviderAction action = new ServiceProviderAction(new ServiceAction("verify challenge to authenticate card", CallableMiddelwareMethodes.AUTH_CARD));
action.setChallengeBytes(encryptedChallengeBytes);
sendCommandToMiddleware(action,true);
}
public void authenticateCard(MessageToAuthCard cardMessage) {
// STEP 5, after second response from MW
System.out.println("5. AUTH CARD WITH MESSAGE");
//System.out.println("DONE " + bytesToHex(cardMessage.getMessage()));
Cipher aesCipher;
try {
//decrypte message
aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.DECRYPT_MODE, symKey, ivSpec);
byte[] message = aesCipher.doFinal(padding(cardMessage.getMessage()));
//System.out.println(bytesToDec(message));
//check signature
byte[] signedBytes = Arrays.copyOfRange(message, 0, 72);
byte[] signature = Arrays.copyOfRange(message, 72, 136);
Signature signer = Signature.getInstance("SHA1WithRSA");
signer.initVerify(CAService.loadPublicKey("RSA"));
signer.update(signedBytes);
if(!signer.verify(signature)) {
System.out.println("Card has a valid common certificate. (authenticate card)");
} else {
System.out.println("Card doesn't have a valid common certificate.");
return;
}
//check if sign with CommonCert key is ok
//first regenerate public key from commoncertificate
BigInteger exponent = new BigInteger(1,Arrays.copyOfRange(message, 0, 3));
BigInteger modulus = new BigInteger(1,Arrays.copyOfRange(message, 4, 68));
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
signer.initVerify(KeyFactory.getInstance("RSA").generatePublic(spec));
//generate byte array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(challengeToAuthCard);
outputStream.write("AUTH".getBytes());
byte[] bytesToSign = outputStream.toByteArray();
//System.out.println("bytes to sign : " + bytesToDec(Arrays.copyOfRange(message, 156, 220)));
//System.out.println("bytes to sign : " + KeyFactory.getInstance("RSA").generatePublic(spec));
//check sign
if(signer.verify(Arrays.copyOfRange(message, 156, 220))) {
System.out.println("Card is valid, challenge is ok. (authenticate card)");
} else {
System.out.println("Card is not valid, challenge is nok. HIER ZIT ER NOG EEN FOUT, DIE public key wordt verkeerd opgebouwd door die BigIntegers, de bytes zijn sws juist.");
return;
}
} catch (NoSuchAlgorithmException | SignatureException | IOException | InvalidKeySpecException | InvalidKeyException | URISyntaxException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void submitDataQuery(ServiceProvider selectedServiceProvider, int query) {
System.out.println("1, Start query, SP");
// STEP 1
// Do Authentication
if(lastUsedSP != selectedServiceProvider) {
System.out.println("First time with this SP --> athenticate");
authenticateServiceProvider(selectedServiceProvider);
// STEP 4
//start the authentication of the card (step 3)
authenticateCard();
//STEP 7
// Get data
System.out.println("7. Get Data, SP");
ServiceProviderAction request = new ServiceProviderAction(new ServiceAction("Get Data",CallableMiddelwareMethodes.GET_DATA), selectedServiceProvider.getCertificate());
request.setServiceProvider(selectedServiceProvider.getName());
request.setDataQuery((short) query);
sendCommandToMiddleware(request,true);
lastUsedSP = selectedServiceProvider;
}else {
System.out.println("Skipping authentication phase because already logged in to this service provider!");
ServiceProviderAction request = new ServiceProviderAction(new ServiceAction("Get Data",CallableMiddelwareMethodes.GET_DATA), selectedServiceProvider.getCertificate());
request.setServiceProvider(selectedServiceProvider.getName());
request.setDataQuery((short) query);
sendCommandToMiddleware(request,true);
}
}
public void connectToMiddleWare() {
try {
serviceProviderSocket = new Socket("localhost", portSP);
} catch (IOException ex) {
//System.out.println("CANNOT CONNECT TO MIDDLEWARE " + ex);
}
//System.out.println("Serviceprovider connected to middleware: " + serviceProviderSocket);
}
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ServiceProviderMain.class.getResource("RootMenu.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
//scene.getStylesheets().add("be.msec.stylesheet.css");
// Give the controller access to the main app.
RootMenuController controller = loader.getController();
controller.setMain(this);
currentViewController = controller;
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public Controller getCurrentViewController() {
return currentViewController;
}
// --------------------- LOGIN VIEW ------------------------
public void showMainView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(ServiceProviderMain.class.getResource("mainServiceView.fxml"));
System.out.println("Loading Main Page");
AnchorPane loginView = (AnchorPane) loader.load();
//controller initialiseren<SUF>
MainServiceController controller = loader.getController();
controller.setMainController(this);
currentViewController = controller;
mainController = controller;
rootLayout.setCenter(loginView);
} catch (Exception e) {
e.printStackTrace();
}
}
private void ListenForMiddelware() {
System.out.println("Listening for MW...");
Object obj = null;
try {
ObjectInputStream objectinputstream = new ObjectInputStream(serviceProviderSocket.getInputStream());
obj = objectinputstream.readObject();
System.out.println("OBJECT RECEIVED");
if(obj instanceof Challenge) {
Challenge challengeFromSC = (Challenge)obj;
mainController.addToDataLog("Succesfully received challenge" );
System.out.println("CHALLENGE RECEIVED");
//recreate session key, respond to challenge
recreateSessionKey(challengeFromSC);
notify();
}
else if( obj instanceof String) {
// STEP 8
String answer = (String)obj;
System.out.println("STRING RECEIVEC, "+answer);
mainController.addToDataLog("Succesfully received: " +answer);
}
else if(obj instanceof MessageToAuthCard) {
System.out.println("MESSTOAUTHCARD RECEIVED");
authenticateCard((MessageToAuthCard) obj);
}
else if(obj instanceof byte[]) {
decryptAndShowData((byte[]) obj);
}
else {
System.out.println("UNKNOW OBJECT received "+ obj);
}
System.out.println("succesfully received an answer!");
}catch (Exception e) {
System.out.println(e);
}
}
private void decryptAndShowData(byte[] encryptedData) {
//decrypt and show in log
try {
System.out.println("Start decrypting from received data");
Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
aesCipher.init(Cipher.DECRYPT_MODE, symKey, ivSpec);
byte [] cropped = new byte[encryptedData.length - 2];
cropped = Arrays.copyOfRange(encryptedData, 2, cropped.length);
cropped = padding(cropped);
System.out.println("the length is: "+ cropped.length);
byte[] data = aesCipher.doFinal(cropped);
String str = new String(data, StandardCharsets.UTF_8);
mainController.addToDataLog("Received data from card: "+ str );
System.out.println("data is: " + str);
System.out.println("Succesfully decrypted");
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ------------------------------------
// ------- UTILITY FUNCTIONS ----------
// ------------------------------------
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
String str = "";
for (int j = 0; j < hexChars.length; j += 2) {
str += "0x" + hexChars[j] + hexChars[j + 1] + ", ";
}
return str;
}
private byte [] padding(byte[] data) {
if(data.length %16 != 0) {
short length = (short) (data.length + 16 - data.length %16);
byte [] paddedData = new byte[length];
paddedData = Arrays.copyOfRange(data, 0, data.length-1);
return paddedData;
}
return data;
}
public String bytesToDec(byte[] barray) {
String str = "";
for (byte b : barray)
str += (int) b + ", ";
return str;
}
public static byte[] addOne_Bad(byte[] A) {
short lastPosition = (short)(A.length - 1);
// Looping from right to left
A[lastPosition] += 1;
return A;
}
}
|
177632_5 | package com.example.subsidieradar.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Match implements iMatch {
@Override
public List<Subsidie> findMatches(List<Subsidie> subsidies,
String sector,
String thema,
String typeActiviteit,
String budget,
String typeAanvrager,
String projectlocatie,
boolean bijdrage,
String samenwerking) {
List<Subsidie> filteredSubsidies = new ArrayList<>();
for (Subsidie subsidie : subsidies) {
//eerst checken we of er knockoutcriteria zijn
subsidie.setKnockout(false);
System.out.println(subsidie.getAfkortingen());
if (!subsidie.getNiveau().toLowerCase().contains(projectlocatie.substring(1, projectlocatie.length() -1).toLowerCase())){
subsidie.setKnockout(true);
}
if (!subsidie.getSoort_organisatie().toLowerCase().contains(typeAanvrager.substring(1, typeAanvrager.length() -1).toLowerCase())){
subsidie.setKnockout(true);
}
if (!subsidie.getSector().equals("Geen vereiste")){
if (!subsidie.getSector().toLowerCase().contains(sector.substring(1, sector.length() -1).toLowerCase())){
subsidie.setKnockout(true);
}
}
// dan checken we groep 1; 65 punten; thema, activiteiten
int percentageGroep1 = 65;
if (!subsidie.getThemas().toLowerCase().contains(thema.substring(1, thema.length() -1).toLowerCase())) { // als subsidie ander thema heeft -35%
percentageGroep1 = percentageGroep1 - 35;
System.out.println(subsidie.getThemas().toLowerCase());
System.out.println(thema.toLowerCase());
System.out.println("-35");
}
if (!subsidie.getSubsidiabele_activiteiten().toLowerCase().contains(typeActiviteit.substring(1, typeActiviteit.length() -1).toLowerCase())) {
percentageGroep1 = percentageGroep1 - 30;
System.out.println("-30");
}
// dan groep 2; 35 punten; Verplicht; Minimaal benodigd subsidiebedrag, beoogde startdatum
// niet verplicht;, cofinanciering mogelijkheid
int percentageGroep2 = 35;
//budget
double gegevenBudget = Double.parseDouble(budget.substring( 1, budget.length() - 1 ));
boolean cat1 = false;
boolean cat2 = false;
boolean cat3 = false;
boolean cat4 = false;
if (subsidie.getSubsidiebedrag() < 50000){
cat1 = true;
} else if (subsidie.getSubsidiebedrag() >= 50000 && subsidie.getSubsidiebedrag() < 200000) {
cat2 = true;
} else if (subsidie.getSubsidiebedrag() >= 200000 && subsidie.getSubsidiebedrag() < 1000000) {
cat3 = true;
} else if (subsidie.getSubsidiebedrag() > 1000000) {
cat4 = true;
}
if (gegevenBudget < 50000){// als gegeven budget cat1
if (cat2){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat1){
percentageGroep2 = percentageGroep2 - 15;
}
} else if (gegevenBudget >= 50000 && gegevenBudget < 200000) { // als gegeven budget cat2
if (cat1 || cat3){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat2){
percentageGroep2 = percentageGroep2 - 15;
}
} else if (gegevenBudget >= 200000 && gegevenBudget < 1000000) {// als gegeven budget cat3
if (cat2 || cat4){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat3){
percentageGroep2 = percentageGroep2 - 15;
}
} else if (gegevenBudget > 1000000) { // als gegeven budget cat4
if (cat3){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat4){
percentageGroep2 = percentageGroep2 - 15;
}
}
//cofinanciering
if (!subsidie.getSubsidiepercentage().equals("n.v.t.")){
if (!bijdrage){
percentageGroep2 = percentageGroep2 - 20;
System.out.println("-20");
}
}
System.out.println("groep1: " + percentageGroep1);
System.out.println("groep2: " + percentageGroep2);
subsidie.setMatchingPercentage(percentageGroep1 + percentageGroep2);
filteredSubsidies.add(subsidie);
}
return filteredSubsidies;
}
}
| Ayoub2K/SnelSubsidies | src/main/java/com/example/subsidieradar/domain/Match.java | 1,536 | // als gegeven budget cat1 | line_comment | nl | package com.example.subsidieradar.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Match implements iMatch {
@Override
public List<Subsidie> findMatches(List<Subsidie> subsidies,
String sector,
String thema,
String typeActiviteit,
String budget,
String typeAanvrager,
String projectlocatie,
boolean bijdrage,
String samenwerking) {
List<Subsidie> filteredSubsidies = new ArrayList<>();
for (Subsidie subsidie : subsidies) {
//eerst checken we of er knockoutcriteria zijn
subsidie.setKnockout(false);
System.out.println(subsidie.getAfkortingen());
if (!subsidie.getNiveau().toLowerCase().contains(projectlocatie.substring(1, projectlocatie.length() -1).toLowerCase())){
subsidie.setKnockout(true);
}
if (!subsidie.getSoort_organisatie().toLowerCase().contains(typeAanvrager.substring(1, typeAanvrager.length() -1).toLowerCase())){
subsidie.setKnockout(true);
}
if (!subsidie.getSector().equals("Geen vereiste")){
if (!subsidie.getSector().toLowerCase().contains(sector.substring(1, sector.length() -1).toLowerCase())){
subsidie.setKnockout(true);
}
}
// dan checken we groep 1; 65 punten; thema, activiteiten
int percentageGroep1 = 65;
if (!subsidie.getThemas().toLowerCase().contains(thema.substring(1, thema.length() -1).toLowerCase())) { // als subsidie ander thema heeft -35%
percentageGroep1 = percentageGroep1 - 35;
System.out.println(subsidie.getThemas().toLowerCase());
System.out.println(thema.toLowerCase());
System.out.println("-35");
}
if (!subsidie.getSubsidiabele_activiteiten().toLowerCase().contains(typeActiviteit.substring(1, typeActiviteit.length() -1).toLowerCase())) {
percentageGroep1 = percentageGroep1 - 30;
System.out.println("-30");
}
// dan groep 2; 35 punten; Verplicht; Minimaal benodigd subsidiebedrag, beoogde startdatum
// niet verplicht;, cofinanciering mogelijkheid
int percentageGroep2 = 35;
//budget
double gegevenBudget = Double.parseDouble(budget.substring( 1, budget.length() - 1 ));
boolean cat1 = false;
boolean cat2 = false;
boolean cat3 = false;
boolean cat4 = false;
if (subsidie.getSubsidiebedrag() < 50000){
cat1 = true;
} else if (subsidie.getSubsidiebedrag() >= 50000 && subsidie.getSubsidiebedrag() < 200000) {
cat2 = true;
} else if (subsidie.getSubsidiebedrag() >= 200000 && subsidie.getSubsidiebedrag() < 1000000) {
cat3 = true;
} else if (subsidie.getSubsidiebedrag() > 1000000) {
cat4 = true;
}
if (gegevenBudget < 50000){// als gegeven<SUF>
if (cat2){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat1){
percentageGroep2 = percentageGroep2 - 15;
}
} else if (gegevenBudget >= 50000 && gegevenBudget < 200000) { // als gegeven budget cat2
if (cat1 || cat3){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat2){
percentageGroep2 = percentageGroep2 - 15;
}
} else if (gegevenBudget >= 200000 && gegevenBudget < 1000000) {// als gegeven budget cat3
if (cat2 || cat4){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat3){
percentageGroep2 = percentageGroep2 - 15;
}
} else if (gegevenBudget > 1000000) { // als gegeven budget cat4
if (cat3){
percentageGroep2 = percentageGroep2 - 10;
}else if(!cat4){
percentageGroep2 = percentageGroep2 - 15;
}
}
//cofinanciering
if (!subsidie.getSubsidiepercentage().equals("n.v.t.")){
if (!bijdrage){
percentageGroep2 = percentageGroep2 - 20;
System.out.println("-20");
}
}
System.out.println("groep1: " + percentageGroep1);
System.out.println("groep2: " + percentageGroep2);
subsidie.setMatchingPercentage(percentageGroep1 + percentageGroep2);
filteredSubsidies.add(subsidie);
}
return filteredSubsidies;
}
}
|
33031_38 | //Fix layout
//aankomsttijd bus nog verwerken
//vertrektijd/aankomsttijd in grote tabel weergeven ipv geselecteerde tijd
//wisselknop fixen
//vertalingen fixen
//logos bus trein
//plan route knop overbodig?
//
package com.example.eerstejavafx;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.util.Duration;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Locale;
import java.util.ResourceBundle;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.layout.VBox;
import static com.example.eerstejavafx.HelloController.DepartureTimeCalc.calculateDepartureTime;
import javafx.scene.input.MouseEvent;
public class HelloController implements Initializable {
@FXML
private Button smallFontSize;
@FXML
private Button middleFontSize;
@FXML
private Button bigFontSize;
@FXML
private Label WijzigLettergrootte;
@FXML
private Button refreshPage;
@FXML
Button wisselHaltes;
@FXML
private Button TaalButton;
@FXML
private Label lblVoertuig;
@FXML
private Label VertrekLabel;
@FXML
private Label huidigeTijd;
@FXML
private ChoiceBox<String> VertrekChoiceBox;
@FXML
private Label AankomstLabel;
@FXML
private ChoiceBox<String> AankomstChoiceBox;
@FXML
private TextArea selectedItemTextArea;
@FXML
private Label currentTimeLabel;
@FXML
private VBox mainContainer;
@FXML
private DatePicker datePicker;
@FXML
private ComboBox<String> timeComboBox;
private LoginController loginController;
@FXML
private Button getRoutesAndTimesButton;
@FXML
private ToggleGroup SelectTransportMode;
@FXML
private ToggleButton TreinSelector;
@FXML
private Button Traject_1;
@FXML
private Button Traject_2;
@FXML
private Button Traject_3;
public static int currentPage = 1;
public void bigFontSize(ActionEvent event) {
bigFontSizeForLabels(2);
}
public void middleFontSize(ActionEvent event) {
middleFontSizeForLabels(2);
}
public void smallFontSize(ActionEvent event) {
smallFontSizeForLabels(2);
}
private void bigFontSizeForLabels(int delta) {
changeFontSize(4);
}
private void middleFontSizeForLabels(int delta) {
changeFontSize(2);
}
private void smallFontSizeForLabels(int delta) {
changeFontSize(0);
}
private final String[] steden = {"Amersfoort", "Amsterdam", "Den Haag", "Eindhoven", "Maastricht", "Utrecht"};
@FXML
private ListView<FavoriteRoute> favoritesListView;
private ObservableList<FavoriteRoute> favoriteRoutes;
private final Map<String, Map<String, String>> routeTimes = new HashMap<>();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
datePicker.setValue(LocalDate.now());
timeComboBox.setValue(updateCurrentTime());
VertrekChoiceBox.getItems().addAll(steden);
VertrekChoiceBox.setOnAction(this::getVertrek);
AankomstChoiceBox.getItems().addAll(steden);
AankomstChoiceBox.setOnAction(this::getAankomst);
timeComboBox.getItems().addAll("05:00", "05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45",
"09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45",
"11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45",
"13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45",
"15:00", "15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45",
"17:00", "17:15", "17:30", "17:45", "18:00", "18:15", "18:30", "18:45",
"19:00", "19:15", "19:30", "19:45", "20:00", "20:15", "20:30", "20:45",
"21:00", "21:15", "21:30", "21:45", "22:00", "22:15", "22:30", "22:45",
"23:00", "23:15", "23:30", "23:45");
updateCurrentTime();
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(1), event -> updateCurrentTime()));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
routeTimes.put("Amersfoort", Map.of("Eindhoven", "51min", "Utrecht", "12min", "Maastricht", "93min", "Amsterdam", "60min", "Den Haag", "40min"));
routeTimes.put("Eindhoven", Map.of("Amersfoort", "51min", "Utrecht", "41min", "Maastricht", "42min", "Amsterdam", "50min", "Den Haag", "67min"));
routeTimes.put("Utrecht", Map.of("Amersfoort", "12min", "Eindhoven", "41min", "Maastricht", "85min", "Amsterdam", "20min", "Den Haag", "29min"));
routeTimes.put("Maastricht", Map.of("Amersfoort", "90min", "Eindhoven", "42min", "Utrecht", "85min", "Amsterdam", "101min", "Den Haag", "109min"));
routeTimes.put("Amsterdam", Map.of("Amersfoort", "60min", "Eindhoven", "51min", "Utrecht", "21min", "Maastricht", "101min", "Den Haag", "31min"));
routeTimes.put("Den Haag", Map.of("Amersfoort", "40min", "Eindhoven", "67min", "Utrecht", "30min", "Maastricht", "109min", "Amsterdam", "31min"));
getRoutesAndTimesButton.setOnAction(this::getRoutesAndTimes);
Button bigButton = new Button("groot");
bigButton.setOnAction(this::bigFontSize);
Button middleButton = new Button("klein");
middleButton.setOnAction(this::middleFontSize);
Button smallButton = new Button("middel");
smallButton.setOnAction(this::smallFontSize);
GridPane gridPane = new GridPane();
gridPane.add(middleButton, 0, 0);
gridPane.add(smallButton, 1, 0);
gridPane.add(bigButton, 2, 0);
favoriteRoutes = FXCollections.observableArrayList();
favoritesListView.setItems(favoriteRoutes);
}
// LETTERGROOTTE WIJZIGEN
private void changeFontSize(int delta) {
double defaultSize = 14;
double currentSize = defaultSize + delta;
VertrekLabel.setFont(new Font(currentSize));
AankomstLabel.setFont(new Font(currentSize));
currentTimeLabel.setFont(new Font(currentSize));
selectedItemTextArea.setStyle("-fx-font-size: " + currentSize);
}
// HUIDIGE TIJD
private String updateCurrentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
String currentTime = dateFormat.format(new Date());
currentTimeLabel.setText("\uD83D\uDD54 " + currentTime);
return currentTime;
}
// VERTREK VELD
public void getVertrek(ActionEvent event) {
String myVertrek = VertrekChoiceBox.getValue();
updateTextArea(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue());
}
// AANKOMST VELD
public void getAankomst(ActionEvent event) {
String myAankomst = AankomstChoiceBox.getValue();
updateTextArea(VertrekChoiceBox.getValue(), myAankomst);
}
// REFRESH KNOP
public void refreshPage(ActionEvent event) {
VertrekChoiceBox.getSelectionModel().clearSelection();
AankomstChoiceBox.getSelectionModel().clearSelection();
selectedItemTextArea.setText("");
Traject_1.setText("");
Traject_2.setText("");
Traject_3.setText("");
currentPage=1;
}
// HALTES WISSELEN
public void wisselHaltes(ActionEvent event) {
String vertrek = VertrekChoiceBox.getValue();
String aankomst = AankomstChoiceBox.getValue();
if (vertrek != null && aankomst != null) {
VertrekChoiceBox.setValue(aankomst);
AankomstChoiceBox.setValue(vertrek);
updateTextArea(aankomst, vertrek);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
}
// OV SELECTEREN
@FXML
private void handleTransportTypeChange() {
Toggle selectedToggleButton = SelectTransportMode.getSelectedToggle();
String voertuig;
String buttonId = ((ToggleButton) selectedToggleButton).getId();
// Now you can use the buttonId in your conditional statements
if ("BusSelector".equals(buttonId)) {
voertuig = "Bus";
lblVoertuig.setText(voertuig);
RouteManager.setTransportationBus();
} else {
voertuig = "Trein";
lblVoertuig.setText(voertuig);
TreinSelector.setSelected(true);
RouteManager.setTransportationTrain();
}
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
// ROUTEBESCHRIJVING
public void getRoutesAndTimes(ActionEvent event) {
String vertrek = VertrekChoiceBox.getValue() != null ? VertrekChoiceBox.getValue() : "Geen halte geselecteerd";
String aankomst = AankomstChoiceBox.getValue() != null ? AankomstChoiceBox.getValue() : "Geen halte geselecteerd";
LocalDate selectedDate = datePicker.getValue()!= null ? datePicker.getValue() : LocalDate.parse("Geen datum geselecteerd");
String selectedTime = timeComboBox.getValue() != null ? timeComboBox.getValue() : "Geen tijd geselecteerd";
// Calculate route time
String routeTime = RouteManager.getRouteTime(calculateDepartureTime(1), aankomst);
String currentDate = getCurrentDate(selectedDate);
// Use routeTime for departure and arrival times
String arrivalTime = calculateDestinationTime(selectedTime, Integer.parseInt(RouteManager.getRouteTime(vertrek,aankomst)));
// Update traject buttons based on the selected stops and the current page
updateTrajectButtons(vertrek, aankomst, 1);
updateTrajectButtons(vertrek, aankomst, 2);
updateTrajectButtons(vertrek, aankomst, 3);
String result = "Vertrek: " + vertrek + "\nAankomst: " + aankomst + "\nDatum: " + currentDate + "\nTijd: " + selectedTime
+ "\nVertrektijd: " + selectedTime + "\nAankomsttijd: " + arrivalTime
+ "\nReistijd: " + routeTime;
// Display selected time and destination time in the selectedItemTextArea
selectedItemTextArea.setText(result);
}
public String getRouteTime(String vertrek, String aankomst) {
if (routeTimes.containsKey(vertrek) && routeTimes.get(vertrek).containsKey(aankomst)) {
String distanceTime = routeTimes.get(vertrek).get(aankomst);
int timeInMinutes = convertTimeToMinutes(distanceTime);
return String.valueOf(timeInMinutes);
} else {
return "Zelfde halte geselecteerd";
}
}
private int convertTimeToMinutes(String time) {
String[] parts = time.split("[^\\d]+");
int hours = 0;
int minutes = 0;
if (parts.length > 0) {
hours = Integer.parseInt(parts[0]);
}
if (time.contains("u") && parts.length > 1) {
minutes = Integer.parseInt(parts[1]);
}
return hours + minutes;
}
private String getCurrentDate(LocalDate selectedDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
return selectedDate != null ? selectedDate.format(formatter) : "Geen datum geselecteerd";
}
private String getCurrentDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
return dateFormat.format(new Date());
}
private void updateTextArea(String myVertrek, String myAankomst) {
String result = "Vertrek: " + myVertrek + "\nAankomst: " + myAankomst;
// Update buttons with selected stops
updateTrajectButtons(myVertrek, myAankomst,1);
updateTrajectButtons(myVertrek, myAankomst,2);
updateTrajectButtons(myVertrek, myAankomst,3);
}
// EERDERE TIJDEN WEERGEVEN
@FXML
private void handleBtnVroeger(ActionEvent event) {
currentPage--;
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
// LATERE TIJDEN WEERGEVEN
@FXML
private void handleBtnLater(ActionEvent event) {
currentPage++;
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
// AANKOMSTTIJDEN BEREKENEN
private String calculateDestinationTime(String selectedTime, int routeTime) {
// Parse the selected time to extract hours and minutes
String[] timeParts = selectedTime.split(":");
int selectedHours = Integer.parseInt(timeParts[0]);
int selectedMinutes = Integer.parseInt(timeParts[1]);
// Calculate destination time by adding route time to selected time
int destinationHours = (selectedHours + (selectedMinutes + routeTime) / 60) % 24;
int destinationMinutes = (selectedMinutes + routeTime) % 60;
// Format the destination time
return String.format("%02d:%02d", destinationHours, destinationMinutes);
}
// VERTREKTIJDEN BEREKENEN
public class DepartureTimeCalc {
public DepartureTimeCalc(int trajectoryIndex) {
}
public static String calculateDepartureTime(int trajectoryIndex) {
DecimalFormat df = new DecimalFormat("00");
// 5:04
int startTime = 5 * 60 + 4;
// 23:35
int endTime = 23 * 60 + 35;
// Interval in minutes
int interval = 25;
final int Traject_PER_TABLE = 3;
int startTraject = (trajectoryIndex - 1) + 1;
int endTraject = startTraject + Traject_PER_TABLE - 1;
// Set var current time to display selected time
int currentTime;
// Calculate the specific timestamp for the given trajectory index
currentTime = startTime + ((startTraject - 1) + ((currentPage - 1) * 3)) * interval;
int hours = currentTime / 60;
int minutes = currentTime % 60;
return df.format(hours) + ":" + df.format(minutes);
}
}
// TRAJECTEN
@FXML
private void handleTrajectButton(ActionEvent event) {
String buttonText = null;
Button clickedButton = (Button) event.getSource();
buttonText = clickedButton.getText();
int trajectoryIndex;
// Determine the trajectory index based on the clicked button
if (buttonText.contains("1")) {
trajectoryIndex = 1;
} else if (buttonText.contains("2")) {
trajectoryIndex = 2;
} else if (buttonText.contains("3")) {
trajectoryIndex = 3;
} else {
// Default to Traject_1 if the button text doesn't contain 1, 2, or 3
trajectoryIndex = 1;
}
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), trajectoryIndex);
}
private void updateTextAreaFromButton(String buttonText,int trajectoryIndex) {
String vertrek = VertrekChoiceBox.getValue() != null ? VertrekChoiceBox.getValue() : "Geen halte geselecteerd";
String aankomst = AankomstChoiceBox.getValue() != null ? AankomstChoiceBox.getValue() : "Geen halte geselecteerd";
LocalDate selectedDate = datePicker.getValue()!= null ? datePicker.getValue() : LocalDate.parse("Geen datum geselecteerd");
String selectedTime = timeComboBox.getValue() != null ? timeComboBox.getValue() : "Geen tijd geselecteerd";
// Set destination time
String departureTime = String.valueOf(new DepartureTimeCalc(trajectoryIndex));
// Calculate route time
int routeTime = Integer.parseInt((RouteManager.getRouteTime(vertrek, aankomst)));
String currentDate = getCurrentDate(selectedDate);
// Use routeTime for departure and arrival times
String arrivalTime = calculateDestinationTime(selectedTime, routeTime);
String result = "Vertrek: " + vertrek + "\nAankomst : " + aankomst +"\n\n\nTijd: " + departureTime + " --> "
+ arrivalTime + "\n" + "\n\nDatum: " + currentDate + "\nReistijd: "+ routeTime + " minuten";
// Update buttons with selected stops
updateTrajectButtons(vertrek, aankomst,1);
updateTrajectButtons(vertrek, aankomst,2);
updateTrajectButtons(vertrek, aankomst,3);
// Display selected time and destination time in the selectedItemTextArea
selectedItemTextArea.setText(result);
}
public void updateTrajectButtons(String vertrek, String aankomst, int trajectoryIndex) {
if (vertrek != null && aankomst != null && timeComboBox != null && datePicker != null) {
String selectedTime = timeComboBox.getValue();
try {
// Get route time in minutes
int routeTime = Integer.parseInt(getRouteTime(vertrek, aankomst));
// Calculate destination time
String destinationTime1 = calculateDestinationTime(calculateDepartureTime(1), routeTime);
String destinationTime2 = calculateDestinationTime(calculateDepartureTime(2), routeTime);
String destinationTime3 = calculateDestinationTime(calculateDepartureTime(3), routeTime);
// Calculate departure time for the specified trajectory index
String departureTime = String.valueOf(new DepartureTimeCalc(trajectoryIndex));
Traject_1.setText(vertrek + "\nVertrektijd: "+ calculateDepartureTime(1) + "\n" + aankomst +
"\n" +"Aankomsttijd: " + destinationTime1 + "\nReistijd: " + RouteManager.getRouteTime(vertrek,aankomst));
Traject_2.setText(vertrek + "\nVertrektijd: "+ calculateDepartureTime(2) + "\n" + aankomst +
"\n" +"Aankomsttijd: " + destinationTime2 + "\nReistijd: " + RouteManager.getRouteTime(vertrek, aankomst));
Traject_3.setText(vertrek + "\nVertrektijd: "+ calculateDepartureTime(3) + "\n" + aankomst +
"\n" +"Aankomsttijd: " + destinationTime3 + "\nReistijd: " + RouteManager.getRouteTime(vertrek, aankomst));
} catch (NumberFormatException e) {
// Handle the case when parsing fails (invalid number format)
System.err.println("Error: Ongeldige waarde voor routeTime");
// You can display an error message or take appropriate action
}
} else {
// Handle the case when either vertrek or aankomst is null
// You can display an error message or take appropriate action
System.out.println("Error: Vertrek of aankomst is leeg");
}
}
public void updateTrajectButtons(String vertrek, String aankomst) {
if (vertrek != null && aankomst != null) {
String reistijd = getRouteTime(vertrek, aankomst) + " " + ResourceBundleManager.getString("minutes");
Traject_1.setText(ResourceBundleManager.getString("traject.button.1")
.replace("{vertrek}", vertrek)
.replace("{aankomst}", aankomst)
.replace("{reistijd}", reistijd));
Traject_2.setText(ResourceBundleManager.getString("traject.button.2")
.replace("{vertrek}", vertrek)
.replace("{aankomst}", aankomst)
.replace("{reistijd}", reistijd));
Traject_3.setText(ResourceBundleManager.getString("traject.button.3")
.replace("{vertrek}", vertrek)
.replace("{aankomst}", aankomst)
.replace("{reistijd}", reistijd));
} else {
// Behandel het geval waarin vertrek of aankomst null is
// Je kunt een foutmelding weergeven of een passende actie ondernemen
System.out.println(ResourceBundleManager.getString("error.departure.arrival.null"));
}
}
// FAVORIETE HALTES
// favoriete haltes toevoegen
@FXML
private void addToFavorites(ActionEvent event) {
String vertrek = VertrekChoiceBox.getValue();
String aankomst = AankomstChoiceBox.getValue();
if (vertrek != null && aankomst != null) {
if (!isRouteAlreadyAdded(vertrek, aankomst)) {
FavoriteRoute favoriteRoute = new FavoriteRoute();
favoriteRoute.setVertrek(vertrek);
favoriteRoute.setAankomst(aankomst);
favoriteRoutes.add(favoriteRoute);
favoritesListView.setItems(FXCollections.observableArrayList(favoriteRoutes));
} else {
System.out.println("Error: Route is al toegevoegd aan favorieten");
// Toon een melding aan de gebruiker dat de route al is toegevoegd
}
} else {
System.out.println("Error: Vertrek of Aankomst is leeg");
}
}
// favoriete haltes in vertrek- en aankomstveld weergeven
@FXML
private void handleFavoriteRouteSelection(MouseEvent event) {
FavoriteRoute selectedFavoriteRoute = favoritesListView.getSelectionModel().getSelectedItem();
if (selectedFavoriteRoute != null) {
setSelectedFavoriteRoute(selectedFavoriteRoute);
}
}
public void setSelectedFavoriteRoute(FavoriteRoute favoriteRoute) {
VertrekChoiceBox.setValue(favoriteRoute.getVertrek());
AankomstChoiceBox.setValue(favoriteRoute.getAankomst());
}
// favoriete halte maximaal 1 keer toevoegen
private boolean isRouteAlreadyAdded(String vertrek, String aankomst) {
for (FavoriteRoute route : favoriteRoutes) {
if (route.getVertrek().equals(vertrek) && route.getAankomst().equals(aankomst)) {
return true; // Route is al toegevoegd
}
}
return false; // Route is nog niet toegevoegd
}
// favoriete halte verwijderen
private void removeFavoriteRoute(String vertrek, String aankomst) {
FavoriteRoute routeToRemove = null;
for (FavoriteRoute route : favoriteRoutes) {
if (route.getVertrek().equals(vertrek) && route.getAankomst().equals(aankomst)) {
routeToRemove = route;
break;
}
}
if (routeToRemove != null) {
favoriteRoutes.remove(routeToRemove);
favoritesListView.setItems(FXCollections.observableArrayList(favoriteRoutes));
}
}
@FXML
private void removeFromFavorites(ActionEvent event) {
FavoriteRoute selectedRoute = favoritesListView.getSelectionModel().getSelectedItem();
if (selectedRoute != null) {
removeFavoriteRoute(selectedRoute.getVertrek(), selectedRoute.getAankomst());
} else {
// Toon een melding aan de gebruiker dat er geen route is geselecteerd
System.out.println("Error: Geen favoriete route geselecteerd om te verwijderen");
}
}
// INLOGGEN
public void showLoginScreen(ActionEvent event) {
try {
if (mainContainer != null) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("login.fxml"));
Parent loginScreen = loader.load();
// Get the controller associated with the login-view.fxml
LoginController loginController = loader.getController();
// Set the reference to the main container and hello controller in the login controller
loginController.setMainContainer(mainContainer);
loginController.setMainController(this);
mainContainer.getChildren().setAll(loginScreen);
} else {
System.out.println("Error: mainContainer is null");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void showMainScreen() {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("hello-view.fxml")); // Replace with your main screen FXML file
VBox mainScreenPane = loader.load();
// Set up the controller for the main screen if needed
mainContainer.getChildren().setAll(mainScreenPane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void setLoginController(LoginController loginController) {
this.loginController = loginController;
}
public void setMainContainer(VBox mainContainer) {
this.mainContainer = mainContainer;
}
// VERTALEN
public void changeTaalButton() {
if (TaalButton.getText().equals("EN")) {
TaalButton.setText("NL");
ResourceBundleManager.setLocale(new Locale("en"));
} else {
TaalButton.setText("EN");
ResourceBundleManager.setLocale(new Locale("nl"));
}
VertrekLabel.setText(ResourceBundleManager.getString("departure"));
AankomstLabel.setText(ResourceBundleManager.getString("arrival"));
datePicker.setPromptText(ResourceBundleManager.getString("select_date"));
timeComboBox.setPromptText(ResourceBundleManager.getString("select_time"));
refreshPage.setText(ResourceBundleManager.getString("refresh_page"));
wisselHaltes.setText(ResourceBundleManager.getString("Swap"));
WijzigLettergrootte.setText(ResourceBundleManager.getString("change_fontsize"));
smallFontSize.setText(ResourceBundleManager.getString("small"));
middleFontSize.setText(ResourceBundleManager.getString("middle"));
bigFontSize.setText(ResourceBundleManager.getString("big"));
}
} | AyoubElkaoui/Ov-app | src/main/java/com/example/eerstejavafx/HelloController.java | 8,121 | // Route is al toegevoegd | line_comment | nl | //Fix layout
//aankomsttijd bus nog verwerken
//vertrektijd/aankomsttijd in grote tabel weergeven ipv geselecteerde tijd
//wisselknop fixen
//vertalingen fixen
//logos bus trein
//plan route knop overbodig?
//
package com.example.eerstejavafx;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.util.Duration;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Locale;
import java.util.ResourceBundle;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.layout.VBox;
import static com.example.eerstejavafx.HelloController.DepartureTimeCalc.calculateDepartureTime;
import javafx.scene.input.MouseEvent;
public class HelloController implements Initializable {
@FXML
private Button smallFontSize;
@FXML
private Button middleFontSize;
@FXML
private Button bigFontSize;
@FXML
private Label WijzigLettergrootte;
@FXML
private Button refreshPage;
@FXML
Button wisselHaltes;
@FXML
private Button TaalButton;
@FXML
private Label lblVoertuig;
@FXML
private Label VertrekLabel;
@FXML
private Label huidigeTijd;
@FXML
private ChoiceBox<String> VertrekChoiceBox;
@FXML
private Label AankomstLabel;
@FXML
private ChoiceBox<String> AankomstChoiceBox;
@FXML
private TextArea selectedItemTextArea;
@FXML
private Label currentTimeLabel;
@FXML
private VBox mainContainer;
@FXML
private DatePicker datePicker;
@FXML
private ComboBox<String> timeComboBox;
private LoginController loginController;
@FXML
private Button getRoutesAndTimesButton;
@FXML
private ToggleGroup SelectTransportMode;
@FXML
private ToggleButton TreinSelector;
@FXML
private Button Traject_1;
@FXML
private Button Traject_2;
@FXML
private Button Traject_3;
public static int currentPage = 1;
public void bigFontSize(ActionEvent event) {
bigFontSizeForLabels(2);
}
public void middleFontSize(ActionEvent event) {
middleFontSizeForLabels(2);
}
public void smallFontSize(ActionEvent event) {
smallFontSizeForLabels(2);
}
private void bigFontSizeForLabels(int delta) {
changeFontSize(4);
}
private void middleFontSizeForLabels(int delta) {
changeFontSize(2);
}
private void smallFontSizeForLabels(int delta) {
changeFontSize(0);
}
private final String[] steden = {"Amersfoort", "Amsterdam", "Den Haag", "Eindhoven", "Maastricht", "Utrecht"};
@FXML
private ListView<FavoriteRoute> favoritesListView;
private ObservableList<FavoriteRoute> favoriteRoutes;
private final Map<String, Map<String, String>> routeTimes = new HashMap<>();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
datePicker.setValue(LocalDate.now());
timeComboBox.setValue(updateCurrentTime());
VertrekChoiceBox.getItems().addAll(steden);
VertrekChoiceBox.setOnAction(this::getVertrek);
AankomstChoiceBox.getItems().addAll(steden);
AankomstChoiceBox.setOnAction(this::getAankomst);
timeComboBox.getItems().addAll("05:00", "05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "08:45",
"09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45",
"11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45",
"13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45",
"15:00", "15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45",
"17:00", "17:15", "17:30", "17:45", "18:00", "18:15", "18:30", "18:45",
"19:00", "19:15", "19:30", "19:45", "20:00", "20:15", "20:30", "20:45",
"21:00", "21:15", "21:30", "21:45", "22:00", "22:15", "22:30", "22:45",
"23:00", "23:15", "23:30", "23:45");
updateCurrentTime();
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(1), event -> updateCurrentTime()));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
routeTimes.put("Amersfoort", Map.of("Eindhoven", "51min", "Utrecht", "12min", "Maastricht", "93min", "Amsterdam", "60min", "Den Haag", "40min"));
routeTimes.put("Eindhoven", Map.of("Amersfoort", "51min", "Utrecht", "41min", "Maastricht", "42min", "Amsterdam", "50min", "Den Haag", "67min"));
routeTimes.put("Utrecht", Map.of("Amersfoort", "12min", "Eindhoven", "41min", "Maastricht", "85min", "Amsterdam", "20min", "Den Haag", "29min"));
routeTimes.put("Maastricht", Map.of("Amersfoort", "90min", "Eindhoven", "42min", "Utrecht", "85min", "Amsterdam", "101min", "Den Haag", "109min"));
routeTimes.put("Amsterdam", Map.of("Amersfoort", "60min", "Eindhoven", "51min", "Utrecht", "21min", "Maastricht", "101min", "Den Haag", "31min"));
routeTimes.put("Den Haag", Map.of("Amersfoort", "40min", "Eindhoven", "67min", "Utrecht", "30min", "Maastricht", "109min", "Amsterdam", "31min"));
getRoutesAndTimesButton.setOnAction(this::getRoutesAndTimes);
Button bigButton = new Button("groot");
bigButton.setOnAction(this::bigFontSize);
Button middleButton = new Button("klein");
middleButton.setOnAction(this::middleFontSize);
Button smallButton = new Button("middel");
smallButton.setOnAction(this::smallFontSize);
GridPane gridPane = new GridPane();
gridPane.add(middleButton, 0, 0);
gridPane.add(smallButton, 1, 0);
gridPane.add(bigButton, 2, 0);
favoriteRoutes = FXCollections.observableArrayList();
favoritesListView.setItems(favoriteRoutes);
}
// LETTERGROOTTE WIJZIGEN
private void changeFontSize(int delta) {
double defaultSize = 14;
double currentSize = defaultSize + delta;
VertrekLabel.setFont(new Font(currentSize));
AankomstLabel.setFont(new Font(currentSize));
currentTimeLabel.setFont(new Font(currentSize));
selectedItemTextArea.setStyle("-fx-font-size: " + currentSize);
}
// HUIDIGE TIJD
private String updateCurrentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
String currentTime = dateFormat.format(new Date());
currentTimeLabel.setText("\uD83D\uDD54 " + currentTime);
return currentTime;
}
// VERTREK VELD
public void getVertrek(ActionEvent event) {
String myVertrek = VertrekChoiceBox.getValue();
updateTextArea(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue());
}
// AANKOMST VELD
public void getAankomst(ActionEvent event) {
String myAankomst = AankomstChoiceBox.getValue();
updateTextArea(VertrekChoiceBox.getValue(), myAankomst);
}
// REFRESH KNOP
public void refreshPage(ActionEvent event) {
VertrekChoiceBox.getSelectionModel().clearSelection();
AankomstChoiceBox.getSelectionModel().clearSelection();
selectedItemTextArea.setText("");
Traject_1.setText("");
Traject_2.setText("");
Traject_3.setText("");
currentPage=1;
}
// HALTES WISSELEN
public void wisselHaltes(ActionEvent event) {
String vertrek = VertrekChoiceBox.getValue();
String aankomst = AankomstChoiceBox.getValue();
if (vertrek != null && aankomst != null) {
VertrekChoiceBox.setValue(aankomst);
AankomstChoiceBox.setValue(vertrek);
updateTextArea(aankomst, vertrek);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
}
// OV SELECTEREN
@FXML
private void handleTransportTypeChange() {
Toggle selectedToggleButton = SelectTransportMode.getSelectedToggle();
String voertuig;
String buttonId = ((ToggleButton) selectedToggleButton).getId();
// Now you can use the buttonId in your conditional statements
if ("BusSelector".equals(buttonId)) {
voertuig = "Bus";
lblVoertuig.setText(voertuig);
RouteManager.setTransportationBus();
} else {
voertuig = "Trein";
lblVoertuig.setText(voertuig);
TreinSelector.setSelected(true);
RouteManager.setTransportationTrain();
}
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
// ROUTEBESCHRIJVING
public void getRoutesAndTimes(ActionEvent event) {
String vertrek = VertrekChoiceBox.getValue() != null ? VertrekChoiceBox.getValue() : "Geen halte geselecteerd";
String aankomst = AankomstChoiceBox.getValue() != null ? AankomstChoiceBox.getValue() : "Geen halte geselecteerd";
LocalDate selectedDate = datePicker.getValue()!= null ? datePicker.getValue() : LocalDate.parse("Geen datum geselecteerd");
String selectedTime = timeComboBox.getValue() != null ? timeComboBox.getValue() : "Geen tijd geselecteerd";
// Calculate route time
String routeTime = RouteManager.getRouteTime(calculateDepartureTime(1), aankomst);
String currentDate = getCurrentDate(selectedDate);
// Use routeTime for departure and arrival times
String arrivalTime = calculateDestinationTime(selectedTime, Integer.parseInt(RouteManager.getRouteTime(vertrek,aankomst)));
// Update traject buttons based on the selected stops and the current page
updateTrajectButtons(vertrek, aankomst, 1);
updateTrajectButtons(vertrek, aankomst, 2);
updateTrajectButtons(vertrek, aankomst, 3);
String result = "Vertrek: " + vertrek + "\nAankomst: " + aankomst + "\nDatum: " + currentDate + "\nTijd: " + selectedTime
+ "\nVertrektijd: " + selectedTime + "\nAankomsttijd: " + arrivalTime
+ "\nReistijd: " + routeTime;
// Display selected time and destination time in the selectedItemTextArea
selectedItemTextArea.setText(result);
}
public String getRouteTime(String vertrek, String aankomst) {
if (routeTimes.containsKey(vertrek) && routeTimes.get(vertrek).containsKey(aankomst)) {
String distanceTime = routeTimes.get(vertrek).get(aankomst);
int timeInMinutes = convertTimeToMinutes(distanceTime);
return String.valueOf(timeInMinutes);
} else {
return "Zelfde halte geselecteerd";
}
}
private int convertTimeToMinutes(String time) {
String[] parts = time.split("[^\\d]+");
int hours = 0;
int minutes = 0;
if (parts.length > 0) {
hours = Integer.parseInt(parts[0]);
}
if (time.contains("u") && parts.length > 1) {
minutes = Integer.parseInt(parts[1]);
}
return hours + minutes;
}
private String getCurrentDate(LocalDate selectedDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
return selectedDate != null ? selectedDate.format(formatter) : "Geen datum geselecteerd";
}
private String getCurrentDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
return dateFormat.format(new Date());
}
private void updateTextArea(String myVertrek, String myAankomst) {
String result = "Vertrek: " + myVertrek + "\nAankomst: " + myAankomst;
// Update buttons with selected stops
updateTrajectButtons(myVertrek, myAankomst,1);
updateTrajectButtons(myVertrek, myAankomst,2);
updateTrajectButtons(myVertrek, myAankomst,3);
}
// EERDERE TIJDEN WEERGEVEN
@FXML
private void handleBtnVroeger(ActionEvent event) {
currentPage--;
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
// LATERE TIJDEN WEERGEVEN
@FXML
private void handleBtnLater(ActionEvent event) {
currentPage++;
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 1);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 2);
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), 3);
}
// AANKOMSTTIJDEN BEREKENEN
private String calculateDestinationTime(String selectedTime, int routeTime) {
// Parse the selected time to extract hours and minutes
String[] timeParts = selectedTime.split(":");
int selectedHours = Integer.parseInt(timeParts[0]);
int selectedMinutes = Integer.parseInt(timeParts[1]);
// Calculate destination time by adding route time to selected time
int destinationHours = (selectedHours + (selectedMinutes + routeTime) / 60) % 24;
int destinationMinutes = (selectedMinutes + routeTime) % 60;
// Format the destination time
return String.format("%02d:%02d", destinationHours, destinationMinutes);
}
// VERTREKTIJDEN BEREKENEN
public class DepartureTimeCalc {
public DepartureTimeCalc(int trajectoryIndex) {
}
public static String calculateDepartureTime(int trajectoryIndex) {
DecimalFormat df = new DecimalFormat("00");
// 5:04
int startTime = 5 * 60 + 4;
// 23:35
int endTime = 23 * 60 + 35;
// Interval in minutes
int interval = 25;
final int Traject_PER_TABLE = 3;
int startTraject = (trajectoryIndex - 1) + 1;
int endTraject = startTraject + Traject_PER_TABLE - 1;
// Set var current time to display selected time
int currentTime;
// Calculate the specific timestamp for the given trajectory index
currentTime = startTime + ((startTraject - 1) + ((currentPage - 1) * 3)) * interval;
int hours = currentTime / 60;
int minutes = currentTime % 60;
return df.format(hours) + ":" + df.format(minutes);
}
}
// TRAJECTEN
@FXML
private void handleTrajectButton(ActionEvent event) {
String buttonText = null;
Button clickedButton = (Button) event.getSource();
buttonText = clickedButton.getText();
int trajectoryIndex;
// Determine the trajectory index based on the clicked button
if (buttonText.contains("1")) {
trajectoryIndex = 1;
} else if (buttonText.contains("2")) {
trajectoryIndex = 2;
} else if (buttonText.contains("3")) {
trajectoryIndex = 3;
} else {
// Default to Traject_1 if the button text doesn't contain 1, 2, or 3
trajectoryIndex = 1;
}
updateTrajectButtons(VertrekChoiceBox.getValue(), AankomstChoiceBox.getValue(), trajectoryIndex);
}
private void updateTextAreaFromButton(String buttonText,int trajectoryIndex) {
String vertrek = VertrekChoiceBox.getValue() != null ? VertrekChoiceBox.getValue() : "Geen halte geselecteerd";
String aankomst = AankomstChoiceBox.getValue() != null ? AankomstChoiceBox.getValue() : "Geen halte geselecteerd";
LocalDate selectedDate = datePicker.getValue()!= null ? datePicker.getValue() : LocalDate.parse("Geen datum geselecteerd");
String selectedTime = timeComboBox.getValue() != null ? timeComboBox.getValue() : "Geen tijd geselecteerd";
// Set destination time
String departureTime = String.valueOf(new DepartureTimeCalc(trajectoryIndex));
// Calculate route time
int routeTime = Integer.parseInt((RouteManager.getRouteTime(vertrek, aankomst)));
String currentDate = getCurrentDate(selectedDate);
// Use routeTime for departure and arrival times
String arrivalTime = calculateDestinationTime(selectedTime, routeTime);
String result = "Vertrek: " + vertrek + "\nAankomst : " + aankomst +"\n\n\nTijd: " + departureTime + " --> "
+ arrivalTime + "\n" + "\n\nDatum: " + currentDate + "\nReistijd: "+ routeTime + " minuten";
// Update buttons with selected stops
updateTrajectButtons(vertrek, aankomst,1);
updateTrajectButtons(vertrek, aankomst,2);
updateTrajectButtons(vertrek, aankomst,3);
// Display selected time and destination time in the selectedItemTextArea
selectedItemTextArea.setText(result);
}
public void updateTrajectButtons(String vertrek, String aankomst, int trajectoryIndex) {
if (vertrek != null && aankomst != null && timeComboBox != null && datePicker != null) {
String selectedTime = timeComboBox.getValue();
try {
// Get route time in minutes
int routeTime = Integer.parseInt(getRouteTime(vertrek, aankomst));
// Calculate destination time
String destinationTime1 = calculateDestinationTime(calculateDepartureTime(1), routeTime);
String destinationTime2 = calculateDestinationTime(calculateDepartureTime(2), routeTime);
String destinationTime3 = calculateDestinationTime(calculateDepartureTime(3), routeTime);
// Calculate departure time for the specified trajectory index
String departureTime = String.valueOf(new DepartureTimeCalc(trajectoryIndex));
Traject_1.setText(vertrek + "\nVertrektijd: "+ calculateDepartureTime(1) + "\n" + aankomst +
"\n" +"Aankomsttijd: " + destinationTime1 + "\nReistijd: " + RouteManager.getRouteTime(vertrek,aankomst));
Traject_2.setText(vertrek + "\nVertrektijd: "+ calculateDepartureTime(2) + "\n" + aankomst +
"\n" +"Aankomsttijd: " + destinationTime2 + "\nReistijd: " + RouteManager.getRouteTime(vertrek, aankomst));
Traject_3.setText(vertrek + "\nVertrektijd: "+ calculateDepartureTime(3) + "\n" + aankomst +
"\n" +"Aankomsttijd: " + destinationTime3 + "\nReistijd: " + RouteManager.getRouteTime(vertrek, aankomst));
} catch (NumberFormatException e) {
// Handle the case when parsing fails (invalid number format)
System.err.println("Error: Ongeldige waarde voor routeTime");
// You can display an error message or take appropriate action
}
} else {
// Handle the case when either vertrek or aankomst is null
// You can display an error message or take appropriate action
System.out.println("Error: Vertrek of aankomst is leeg");
}
}
public void updateTrajectButtons(String vertrek, String aankomst) {
if (vertrek != null && aankomst != null) {
String reistijd = getRouteTime(vertrek, aankomst) + " " + ResourceBundleManager.getString("minutes");
Traject_1.setText(ResourceBundleManager.getString("traject.button.1")
.replace("{vertrek}", vertrek)
.replace("{aankomst}", aankomst)
.replace("{reistijd}", reistijd));
Traject_2.setText(ResourceBundleManager.getString("traject.button.2")
.replace("{vertrek}", vertrek)
.replace("{aankomst}", aankomst)
.replace("{reistijd}", reistijd));
Traject_3.setText(ResourceBundleManager.getString("traject.button.3")
.replace("{vertrek}", vertrek)
.replace("{aankomst}", aankomst)
.replace("{reistijd}", reistijd));
} else {
// Behandel het geval waarin vertrek of aankomst null is
// Je kunt een foutmelding weergeven of een passende actie ondernemen
System.out.println(ResourceBundleManager.getString("error.departure.arrival.null"));
}
}
// FAVORIETE HALTES
// favoriete haltes toevoegen
@FXML
private void addToFavorites(ActionEvent event) {
String vertrek = VertrekChoiceBox.getValue();
String aankomst = AankomstChoiceBox.getValue();
if (vertrek != null && aankomst != null) {
if (!isRouteAlreadyAdded(vertrek, aankomst)) {
FavoriteRoute favoriteRoute = new FavoriteRoute();
favoriteRoute.setVertrek(vertrek);
favoriteRoute.setAankomst(aankomst);
favoriteRoutes.add(favoriteRoute);
favoritesListView.setItems(FXCollections.observableArrayList(favoriteRoutes));
} else {
System.out.println("Error: Route is al toegevoegd aan favorieten");
// Toon een melding aan de gebruiker dat de route al is toegevoegd
}
} else {
System.out.println("Error: Vertrek of Aankomst is leeg");
}
}
// favoriete haltes in vertrek- en aankomstveld weergeven
@FXML
private void handleFavoriteRouteSelection(MouseEvent event) {
FavoriteRoute selectedFavoriteRoute = favoritesListView.getSelectionModel().getSelectedItem();
if (selectedFavoriteRoute != null) {
setSelectedFavoriteRoute(selectedFavoriteRoute);
}
}
public void setSelectedFavoriteRoute(FavoriteRoute favoriteRoute) {
VertrekChoiceBox.setValue(favoriteRoute.getVertrek());
AankomstChoiceBox.setValue(favoriteRoute.getAankomst());
}
// favoriete halte maximaal 1 keer toevoegen
private boolean isRouteAlreadyAdded(String vertrek, String aankomst) {
for (FavoriteRoute route : favoriteRoutes) {
if (route.getVertrek().equals(vertrek) && route.getAankomst().equals(aankomst)) {
return true; // Route is<SUF>
}
}
return false; // Route is nog niet toegevoegd
}
// favoriete halte verwijderen
private void removeFavoriteRoute(String vertrek, String aankomst) {
FavoriteRoute routeToRemove = null;
for (FavoriteRoute route : favoriteRoutes) {
if (route.getVertrek().equals(vertrek) && route.getAankomst().equals(aankomst)) {
routeToRemove = route;
break;
}
}
if (routeToRemove != null) {
favoriteRoutes.remove(routeToRemove);
favoritesListView.setItems(FXCollections.observableArrayList(favoriteRoutes));
}
}
@FXML
private void removeFromFavorites(ActionEvent event) {
FavoriteRoute selectedRoute = favoritesListView.getSelectionModel().getSelectedItem();
if (selectedRoute != null) {
removeFavoriteRoute(selectedRoute.getVertrek(), selectedRoute.getAankomst());
} else {
// Toon een melding aan de gebruiker dat er geen route is geselecteerd
System.out.println("Error: Geen favoriete route geselecteerd om te verwijderen");
}
}
// INLOGGEN
public void showLoginScreen(ActionEvent event) {
try {
if (mainContainer != null) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("login.fxml"));
Parent loginScreen = loader.load();
// Get the controller associated with the login-view.fxml
LoginController loginController = loader.getController();
// Set the reference to the main container and hello controller in the login controller
loginController.setMainContainer(mainContainer);
loginController.setMainController(this);
mainContainer.getChildren().setAll(loginScreen);
} else {
System.out.println("Error: mainContainer is null");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void showMainScreen() {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("hello-view.fxml")); // Replace with your main screen FXML file
VBox mainScreenPane = loader.load();
// Set up the controller for the main screen if needed
mainContainer.getChildren().setAll(mainScreenPane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void setLoginController(LoginController loginController) {
this.loginController = loginController;
}
public void setMainContainer(VBox mainContainer) {
this.mainContainer = mainContainer;
}
// VERTALEN
public void changeTaalButton() {
if (TaalButton.getText().equals("EN")) {
TaalButton.setText("NL");
ResourceBundleManager.setLocale(new Locale("en"));
} else {
TaalButton.setText("EN");
ResourceBundleManager.setLocale(new Locale("nl"));
}
VertrekLabel.setText(ResourceBundleManager.getString("departure"));
AankomstLabel.setText(ResourceBundleManager.getString("arrival"));
datePicker.setPromptText(ResourceBundleManager.getString("select_date"));
timeComboBox.setPromptText(ResourceBundleManager.getString("select_time"));
refreshPage.setText(ResourceBundleManager.getString("refresh_page"));
wisselHaltes.setText(ResourceBundleManager.getString("Swap"));
WijzigLettergrootte.setText(ResourceBundleManager.getString("change_fontsize"));
smallFontSize.setText(ResourceBundleManager.getString("small"));
middleFontSize.setText(ResourceBundleManager.getString("middle"));
bigFontSize.setText(ResourceBundleManager.getString("big"));
}
} |
10445_13 | import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Scanner;
class Medication {
static final int RETURN = 0;
static final int ADD_MEDICATION = 1;
static final int EDIT_MEDICATION = 2;
static final int REMOVE_MEDICATION = 3;
String name;
String type;
String dosage;
LocalDate medicationDate;
public Medication(String name, String type, String dosage) {
this.name = name;
this.type = type;
this.dosage = dosage;
}
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setDosage(String dosage) {
this.dosage = dosage;
}
public String getDosage() {
return dosage;
}
public void setMedicationDate(LocalDate medicationDate) {
this.medicationDate = medicationDate;
}
public LocalDate getMedicationDate() {
return this.medicationDate;
}
// Add a method to set medication date to today
public void setMedicationDateToToday() {
this.medicationDate = LocalDate.now();
}
public void viewMedicationData(LocalDate medicationDate) {
System.out.format("%-17s %5s %10s %22s\n", name, type, dosage, (medicationDate != null) ?
medicationDate.format(formatter) : "");
}
// public static void MedicationMenu(Patient patient) {
// var scanner = new Scanner(System.in);
// boolean nextCycle = true;
// while (nextCycle) {
//// final int ADD_MEDICATION = patient.medicationList.size() + 1;
//// final int REMOVE_MEDICATION = patient.medicationList.size() + 2;
//// final int RETURN = patient.medicationList.size() + 3;
// System.out.format("\033[33m%d: Terug\033[0m\n", RETURN);
// System.out.format("\033[32m%d: Nieuwe medicatie toevoegen\033[0m\n", ADD_MEDICATION);
// System.out.format("\033[31m%d: Medicatie verwijderen\033[0m\n", REMOVE_MEDICATION);
//// for (Medication medication : patient.medicationList) {
//// System.out.format("%d: Bewerk %s\n", patient.medicationList.indexOf(medication) + 3,
// medication.getName());
//// }
// System.out.print("Voer uw keuze in: ");
// int choice = scanner.nextInt();
//// if (choice > 2 && choice <= patient.medicationList.size() + 3) {
//// patient.medicationList.get(choice - 3).editMedicationData();
//// choice = RETURN;
//// }
// switch (choice) {
// case RETURN ->
// // Interrupt the loop
// nextCycle = false;
// case ADD_MEDICATION -> addNewMedication(patient);
// case REMOVE_MEDICATION -> removeMedication(patient);
//// case EDIT_MEDICATION -> editMedicationData(patient);
// default -> System.out.format("\033[31mOngeldige medicatie ID: %d\033[0m \n", choice);
// }
// }
// }
public static void addNewMedication(Patient patient) {
var scanner = new Scanner(System.in);
boolean nextCycle = true;
while (nextCycle) {
System.out.format("%s\n", "-".repeat(50));
System.out.format("%s", "Voeg nieuwe medicatie toe\n");
System.out.format("\033[33m%d: Terug\033[0m\n", RETURN);
for (Medication medication : MedicationList.getMedications()) {
if (!patient.medicationList.contains(medication)) {
System.out.format("%d: %s | %s | %s\n", MedicationList.getMedications().indexOf(medication) + 1,
medication.getName(), medication.getType(), medication.getDosage());
}
}
System.out.print("Voer uw keuze in: ");
int choice = scanner.nextInt();
if (choice > 0 && choice <= MedicationList.getMedications().size()) {
if (!patient.medicationList.contains(MedicationList.getMedications().get(choice - 1))) {
MedicationList.addMedicationsToPatient(patient,
new String[]{MedicationList.getMedications().get(choice - 1).getName()});
// Set the date of medication for the added medication
Medication addedMedication = MedicationList.getMedications().get(choice - 1);
addedMedication.setMedicationDateToToday(); // Set to today's date
System.out.format("\033[32mMedicatie %s toegevoegd aan patient %s\033[0m\n",
addedMedication.getName(), patient.getFirstName());
} else {
System.out.format("\033[31mMedicatie %s zit al in de medicatielijst van patient\033[0m\n",
new String[]{MedicationList.getMedications().get(choice - 1).getName()},
patient.getFirstName());
}
choice = RETURN;
}
switch (choice) {
case RETURN ->
nextCycle = false;
default ->
System.out.format("\033[31mOngeldige medicatie ID: %d\033[0m \n", choice);
}
}
}
public static void removeMedication(Patient patient) {
var scanner = new Scanner(System.in);
boolean nextCycle = true;
while (nextCycle) {
System.out.format("%s\n", "-".repeat(50));
System.out.format("%s", "Verwijder medicatie\n");
System.out.format("\033[33m%d: Terug\033[0m\n", RETURN);
for (Medication medication : patient.medicationList) {
System.out.format("%d: %s\n", patient.medicationList.indexOf(medication) + 1, medication.getName());
}
System.out.print("Voer uw keuze in: ");
int choice = scanner.nextInt();
if (choice > 0 && choice <= patient.medicationList.size()) {
// Add the medication to the patient's medication list
System.out.format("\033[31mMedicatie %s verwijderd van patient %s\033[0m\n",
patient.medicationList.get(choice - 1).getName(), patient.getFirstName());
MedicationList.removeMedicationFromPatient(patient,
(MedicationList.getMedications().get(choice - 1).getName()));
choice = RETURN;
}
switch (choice) {
case RETURN ->
// Interrupt the loop
nextCycle = false;
default -> System.out.format("\033[31mOngeldige medicatie ID: %d\033[0m \n", choice);
}
}
}
public void editMedication(String newDosage) {
this.dosage = newDosage;
}
}
| AyoubElkaoui/Zorg-app | src/Medication.java | 2,059 | // System.out.print("Voer uw keuze in: "); | line_comment | nl | import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Scanner;
class Medication {
static final int RETURN = 0;
static final int ADD_MEDICATION = 1;
static final int EDIT_MEDICATION = 2;
static final int REMOVE_MEDICATION = 3;
String name;
String type;
String dosage;
LocalDate medicationDate;
public Medication(String name, String type, String dosage) {
this.name = name;
this.type = type;
this.dosage = dosage;
}
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setDosage(String dosage) {
this.dosage = dosage;
}
public String getDosage() {
return dosage;
}
public void setMedicationDate(LocalDate medicationDate) {
this.medicationDate = medicationDate;
}
public LocalDate getMedicationDate() {
return this.medicationDate;
}
// Add a method to set medication date to today
public void setMedicationDateToToday() {
this.medicationDate = LocalDate.now();
}
public void viewMedicationData(LocalDate medicationDate) {
System.out.format("%-17s %5s %10s %22s\n", name, type, dosage, (medicationDate != null) ?
medicationDate.format(formatter) : "");
}
// public static void MedicationMenu(Patient patient) {
// var scanner = new Scanner(System.in);
// boolean nextCycle = true;
// while (nextCycle) {
//// final int ADD_MEDICATION = patient.medicationList.size() + 1;
//// final int REMOVE_MEDICATION = patient.medicationList.size() + 2;
//// final int RETURN = patient.medicationList.size() + 3;
// System.out.format("\033[33m%d: Terug\033[0m\n", RETURN);
// System.out.format("\033[32m%d: Nieuwe medicatie toevoegen\033[0m\n", ADD_MEDICATION);
// System.out.format("\033[31m%d: Medicatie verwijderen\033[0m\n", REMOVE_MEDICATION);
//// for (Medication medication : patient.medicationList) {
//// System.out.format("%d: Bewerk %s\n", patient.medicationList.indexOf(medication) + 3,
// medication.getName());
//// }
// System.out.print("Voer uw<SUF>
// int choice = scanner.nextInt();
//// if (choice > 2 && choice <= patient.medicationList.size() + 3) {
//// patient.medicationList.get(choice - 3).editMedicationData();
//// choice = RETURN;
//// }
// switch (choice) {
// case RETURN ->
// // Interrupt the loop
// nextCycle = false;
// case ADD_MEDICATION -> addNewMedication(patient);
// case REMOVE_MEDICATION -> removeMedication(patient);
//// case EDIT_MEDICATION -> editMedicationData(patient);
// default -> System.out.format("\033[31mOngeldige medicatie ID: %d\033[0m \n", choice);
// }
// }
// }
public static void addNewMedication(Patient patient) {
var scanner = new Scanner(System.in);
boolean nextCycle = true;
while (nextCycle) {
System.out.format("%s\n", "-".repeat(50));
System.out.format("%s", "Voeg nieuwe medicatie toe\n");
System.out.format("\033[33m%d: Terug\033[0m\n", RETURN);
for (Medication medication : MedicationList.getMedications()) {
if (!patient.medicationList.contains(medication)) {
System.out.format("%d: %s | %s | %s\n", MedicationList.getMedications().indexOf(medication) + 1,
medication.getName(), medication.getType(), medication.getDosage());
}
}
System.out.print("Voer uw keuze in: ");
int choice = scanner.nextInt();
if (choice > 0 && choice <= MedicationList.getMedications().size()) {
if (!patient.medicationList.contains(MedicationList.getMedications().get(choice - 1))) {
MedicationList.addMedicationsToPatient(patient,
new String[]{MedicationList.getMedications().get(choice - 1).getName()});
// Set the date of medication for the added medication
Medication addedMedication = MedicationList.getMedications().get(choice - 1);
addedMedication.setMedicationDateToToday(); // Set to today's date
System.out.format("\033[32mMedicatie %s toegevoegd aan patient %s\033[0m\n",
addedMedication.getName(), patient.getFirstName());
} else {
System.out.format("\033[31mMedicatie %s zit al in de medicatielijst van patient\033[0m\n",
new String[]{MedicationList.getMedications().get(choice - 1).getName()},
patient.getFirstName());
}
choice = RETURN;
}
switch (choice) {
case RETURN ->
nextCycle = false;
default ->
System.out.format("\033[31mOngeldige medicatie ID: %d\033[0m \n", choice);
}
}
}
public static void removeMedication(Patient patient) {
var scanner = new Scanner(System.in);
boolean nextCycle = true;
while (nextCycle) {
System.out.format("%s\n", "-".repeat(50));
System.out.format("%s", "Verwijder medicatie\n");
System.out.format("\033[33m%d: Terug\033[0m\n", RETURN);
for (Medication medication : patient.medicationList) {
System.out.format("%d: %s\n", patient.medicationList.indexOf(medication) + 1, medication.getName());
}
System.out.print("Voer uw keuze in: ");
int choice = scanner.nextInt();
if (choice > 0 && choice <= patient.medicationList.size()) {
// Add the medication to the patient's medication list
System.out.format("\033[31mMedicatie %s verwijderd van patient %s\033[0m\n",
patient.medicationList.get(choice - 1).getName(), patient.getFirstName());
MedicationList.removeMedicationFromPatient(patient,
(MedicationList.getMedications().get(choice - 1).getName()));
choice = RETURN;
}
switch (choice) {
case RETURN ->
// Interrupt the loop
nextCycle = false;
default -> System.out.format("\033[31mOngeldige medicatie ID: %d\033[0m \n", choice);
}
}
}
public void editMedication(String newDosage) {
this.dosage = newDosage;
}
}
|
34603_2 | import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class RouteCalc {
private int EPOCHS;
private int KANDIDATEN;
final int TOTALDEST = 250;
private int[] destinations;
private int[] packages;
private int[][] distances;
private int epochTeller = 0;
private ArrayList<KandidaatRoute> huidigeKandidaten = new ArrayList<>();
public RouteCalc(int epochs, int kandidaten) {
this.EPOCHS = epochs;
this.KANDIDATEN = kandidaten;
}
public void readSituation(String file) {
File situationfile = new File(file);
Scanner scan = null;
try {
scan = new Scanner(situationfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int size = scan.nextInt();
destinations = new int[size];
packages = new int[size];
distances = new int[TOTALDEST][TOTALDEST];
for (int i = 0; i < size; i++) {
destinations[i] = scan.nextInt();
}
for (int i = 0; i < size; i++) {
packages[i] = scan.nextInt();
}
for (int i = 0; i < TOTALDEST; i++) {
for (int j = 0; j < TOTALDEST; j++) {
distances[i][j] = scan.nextInt();
}
}
}
public void bepaalRoute() {
if (epochTeller < 1) {
startSituatie();
}
for (int i = 0; i < this.EPOCHS; i++) {
evalueerEpoch();
volgendeEpoch();
}
evalueerEpoch();
Collections.sort(this.huidigeKandidaten);
System.out.println(Arrays.toString(this.huidigeKandidaten.get(0).getRoute()));
System.out.println(this.huidigeKandidaten.get(0).getScore());
}
public void evalueerKandidaat(KandidaatRoute kandidaatRoute) {
int totalDistance = 0;
int totalPackages = 0;
int totalDistanceScore;
int totalPackagesScore;
int totalStartScore = 0;
int[] currentRoute = kandidaatRoute.getRoute();
//calculating the total distance
for (int i = 0; i < currentRoute.length; i++) {
try {
totalDistance += distances[currentRoute[i]][currentRoute[i + 1]];
} catch (ArrayIndexOutOfBoundsException a) {
}
}
//set the total distance score
totalDistanceScore = totalDistance;
//get total packages
for (int i = 0; i < this.packages.length; i++) {
totalPackages += this.packages[i];
}
//calculate totalpackages score
ArrayList<Integer> copyPackages = new ArrayList<>();
//fill arraylist with packages
for (int aPackage : this.packages) {
copyPackages.add(aPackage);
}
//packages hold after every destination
for (int i = 0; i < this.packages.length; i++) {
for (int x = 0; x < copyPackages.size(); x++) {
try {
totalPackages += copyPackages.get(x + i);
} catch (IndexOutOfBoundsException e) {
}
}
}
totalPackagesScore = totalPackages / 10;
//calculate startRoute
if (kandidaatRoute.getRoute()[0] != 1) {
totalStartScore += 100000;
}
kandidaatRoute.setScore(totalDistanceScore + totalPackagesScore + totalStartScore);
}
public void evalueerEpoch() {
for (KandidaatRoute i : huidigeKandidaten) {
if (i.getScore() == 0) {
evalueerKandidaat(i);
}
}
}
public KandidaatRoute randomKandidaat() {
int[] randomRoute = new int[this.destinations.length];
KandidaatRoute kandidaatRoute = new KandidaatRoute();
ArrayList<Integer> copyDestinations = new ArrayList();
Random random = new Random();
//fill arraylist copyDestinations;
for (int i : this.destinations) {
copyDestinations.add(i);
}
//get random destination by getting at the index from destinationCopy and removing it after.
for (int i = 0; i < randomRoute.length; i++) {
int randomGetal = random.nextInt(copyDestinations.size());
randomRoute[i] = copyDestinations.get(randomGetal);
copyDestinations.remove(randomGetal);
}
kandidaatRoute.setRoute(randomRoute);
return kandidaatRoute;
}
public void startSituatie() {
for (int i = 0; i < this.KANDIDATEN; i++) {
this.huidigeKandidaten.add(randomKandidaat());
}
}
public KandidaatRoute muteer(KandidaatRoute kandidaatRoute) {
KandidaatRoute mutation = new KandidaatRoute();
int[] routeArray = new int[kandidaatRoute.getRoute().length];
//fill the array
for (int x = 0; x < kandidaatRoute.getRoute().length; x++) {
int y = kandidaatRoute.getRoute()[x];
routeArray[x] = y;
}
Random random = new Random();
for (int i = routeArray.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
//Swap
int x = routeArray[index];
routeArray[index] = routeArray[i];
routeArray[i] = x;
}
mutation.setRoute(routeArray);
return mutation;
}
public int getPercentKandidaten(int percentage) {
float p = (float) percentage / 100;
float x = (int) Math.ceil(this.KANDIDATEN * p);
return (int) x;
}
public void volgendeEpoch() {
Collections.sort(this.huidigeKandidaten);
ArrayList<KandidaatRoute> besteOplossingen = new ArrayList<>();
ArrayList<KandidaatRoute> besteOplossingenMutated = new ArrayList<>();
ArrayList<KandidaatRoute> oplossingenRandom = new ArrayList<>();
//45% best solutions to list
for (int i = 0; i < getPercentKandidaten(45); i++) {
besteOplossingen.add(huidigeKandidaten.get(i));
besteOplossingenMutated.add(muteer(huidigeKandidaten.get(i)));
}
//new 10%
for (int i = 0; i < getPercentKandidaten(10); i++) {
oplossingenRandom.add(randomKandidaat());
}
this.huidigeKandidaten.clear();
//add to epoch list
for (KandidaatRoute i : besteOplossingen) {
this.huidigeKandidaten.add(i);
}
for (KandidaatRoute i : besteOplossingenMutated) {
this.huidigeKandidaten.add(i);
}
for (KandidaatRoute i : oplossingenRandom) {
this.huidigeKandidaten.add(i);
}
besteOplossingen.clear();
besteOplossingenMutated.clear();
oplossingenRandom.clear();
for (KandidaatRoute i : huidigeKandidaten) {
System.out.println("test: " + i.getScore());
}
System.out.println("-------einde van volgende epoch --------");
epochTeller++;
}
}
| Ayrtonko/Jaar2_Sem4_DSAL_Opdr5_Bestellingen | Bestellingen/RouteCalc.java | 2,144 | //get total packages | line_comment | nl | import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class RouteCalc {
private int EPOCHS;
private int KANDIDATEN;
final int TOTALDEST = 250;
private int[] destinations;
private int[] packages;
private int[][] distances;
private int epochTeller = 0;
private ArrayList<KandidaatRoute> huidigeKandidaten = new ArrayList<>();
public RouteCalc(int epochs, int kandidaten) {
this.EPOCHS = epochs;
this.KANDIDATEN = kandidaten;
}
public void readSituation(String file) {
File situationfile = new File(file);
Scanner scan = null;
try {
scan = new Scanner(situationfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int size = scan.nextInt();
destinations = new int[size];
packages = new int[size];
distances = new int[TOTALDEST][TOTALDEST];
for (int i = 0; i < size; i++) {
destinations[i] = scan.nextInt();
}
for (int i = 0; i < size; i++) {
packages[i] = scan.nextInt();
}
for (int i = 0; i < TOTALDEST; i++) {
for (int j = 0; j < TOTALDEST; j++) {
distances[i][j] = scan.nextInt();
}
}
}
public void bepaalRoute() {
if (epochTeller < 1) {
startSituatie();
}
for (int i = 0; i < this.EPOCHS; i++) {
evalueerEpoch();
volgendeEpoch();
}
evalueerEpoch();
Collections.sort(this.huidigeKandidaten);
System.out.println(Arrays.toString(this.huidigeKandidaten.get(0).getRoute()));
System.out.println(this.huidigeKandidaten.get(0).getScore());
}
public void evalueerKandidaat(KandidaatRoute kandidaatRoute) {
int totalDistance = 0;
int totalPackages = 0;
int totalDistanceScore;
int totalPackagesScore;
int totalStartScore = 0;
int[] currentRoute = kandidaatRoute.getRoute();
//calculating the total distance
for (int i = 0; i < currentRoute.length; i++) {
try {
totalDistance += distances[currentRoute[i]][currentRoute[i + 1]];
} catch (ArrayIndexOutOfBoundsException a) {
}
}
//set the total distance score
totalDistanceScore = totalDistance;
//get total<SUF>
for (int i = 0; i < this.packages.length; i++) {
totalPackages += this.packages[i];
}
//calculate totalpackages score
ArrayList<Integer> copyPackages = new ArrayList<>();
//fill arraylist with packages
for (int aPackage : this.packages) {
copyPackages.add(aPackage);
}
//packages hold after every destination
for (int i = 0; i < this.packages.length; i++) {
for (int x = 0; x < copyPackages.size(); x++) {
try {
totalPackages += copyPackages.get(x + i);
} catch (IndexOutOfBoundsException e) {
}
}
}
totalPackagesScore = totalPackages / 10;
//calculate startRoute
if (kandidaatRoute.getRoute()[0] != 1) {
totalStartScore += 100000;
}
kandidaatRoute.setScore(totalDistanceScore + totalPackagesScore + totalStartScore);
}
public void evalueerEpoch() {
for (KandidaatRoute i : huidigeKandidaten) {
if (i.getScore() == 0) {
evalueerKandidaat(i);
}
}
}
public KandidaatRoute randomKandidaat() {
int[] randomRoute = new int[this.destinations.length];
KandidaatRoute kandidaatRoute = new KandidaatRoute();
ArrayList<Integer> copyDestinations = new ArrayList();
Random random = new Random();
//fill arraylist copyDestinations;
for (int i : this.destinations) {
copyDestinations.add(i);
}
//get random destination by getting at the index from destinationCopy and removing it after.
for (int i = 0; i < randomRoute.length; i++) {
int randomGetal = random.nextInt(copyDestinations.size());
randomRoute[i] = copyDestinations.get(randomGetal);
copyDestinations.remove(randomGetal);
}
kandidaatRoute.setRoute(randomRoute);
return kandidaatRoute;
}
public void startSituatie() {
for (int i = 0; i < this.KANDIDATEN; i++) {
this.huidigeKandidaten.add(randomKandidaat());
}
}
public KandidaatRoute muteer(KandidaatRoute kandidaatRoute) {
KandidaatRoute mutation = new KandidaatRoute();
int[] routeArray = new int[kandidaatRoute.getRoute().length];
//fill the array
for (int x = 0; x < kandidaatRoute.getRoute().length; x++) {
int y = kandidaatRoute.getRoute()[x];
routeArray[x] = y;
}
Random random = new Random();
for (int i = routeArray.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
//Swap
int x = routeArray[index];
routeArray[index] = routeArray[i];
routeArray[i] = x;
}
mutation.setRoute(routeArray);
return mutation;
}
public int getPercentKandidaten(int percentage) {
float p = (float) percentage / 100;
float x = (int) Math.ceil(this.KANDIDATEN * p);
return (int) x;
}
public void volgendeEpoch() {
Collections.sort(this.huidigeKandidaten);
ArrayList<KandidaatRoute> besteOplossingen = new ArrayList<>();
ArrayList<KandidaatRoute> besteOplossingenMutated = new ArrayList<>();
ArrayList<KandidaatRoute> oplossingenRandom = new ArrayList<>();
//45% best solutions to list
for (int i = 0; i < getPercentKandidaten(45); i++) {
besteOplossingen.add(huidigeKandidaten.get(i));
besteOplossingenMutated.add(muteer(huidigeKandidaten.get(i)));
}
//new 10%
for (int i = 0; i < getPercentKandidaten(10); i++) {
oplossingenRandom.add(randomKandidaat());
}
this.huidigeKandidaten.clear();
//add to epoch list
for (KandidaatRoute i : besteOplossingen) {
this.huidigeKandidaten.add(i);
}
for (KandidaatRoute i : besteOplossingenMutated) {
this.huidigeKandidaten.add(i);
}
for (KandidaatRoute i : oplossingenRandom) {
this.huidigeKandidaten.add(i);
}
besteOplossingen.clear();
besteOplossingenMutated.clear();
oplossingenRandom.clear();
for (KandidaatRoute i : huidigeKandidaten) {
System.out.println("test: " + i.getScore());
}
System.out.println("-------einde van volgende epoch --------");
epochTeller++;
}
}
|
36874_4 | package com.example.breakingbad;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharacterAPITask extends AsyncTask<String, Void, List<Character>> {
private final String TAG = getClass().getSimpleName();
private final String JSON_CHARACTER_NAME = "name";
private final String JSON_CHARACTER_NICKNAME = "nickname";
private final String JSON_CHARACTER_IMAGE = "img";
private final String JSON_CHARACTER_STATUS = "status";
private final String JSON_CHARACTER_BIRTHDAY = "birthday";
private final String JSON_CHARACTER_OCCUPATION = "occupation";
private final String JSON_CHARACTER_APPEARANCE = "appearance";
private CharacterListener listener = null;
public CharacterAPITask(CharacterListener listener) {
this.listener = listener;
}
@Override
protected List<Character> doInBackground(String... params) {
// URL maken of ophalen of samenstellen
String characterUrlString = params[0];
HttpURLConnection urlConnection = null;
URL url = null;
try{
url = new URL(characterUrlString);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
String response = scanner.next();
Log.d(TAG, "response: " + response);
ArrayList<Character> resultList = convertJsonToArrayList(response);
return resultList;
} else {
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != urlConnection) {
urlConnection.disconnect();
}
}
// request bouwen en versturen
// response afwachten en bewerken
// ArrayList maken.
return null;
}
@Override
protected void onPostExecute(List<Character> characters) {
super.onPostExecute(characters);
Log.d(TAG, " in onPostExecute: " + characters.size() + " items.");
// Lijst van characters naar adapter brengen
listener.onCharactersAvailable(characters);
}
// Hulpmethode
private ArrayList<Character> convertJsonToArrayList(String response){
ArrayList<Character> resultList = new ArrayList<>();
//Omzetting van String naar ArrayList
try {
JSONArray characters = new JSONArray(response);
for (int i = 0; i<characters.length(); i++){
ArrayList<String> occupations = new ArrayList<>();
ArrayList<Integer> appearances = new ArrayList<>();
JSONObject actor = characters.getJSONObject(i);
String name = actor.getString(JSON_CHARACTER_NAME);
String nickname = actor.getString(JSON_CHARACTER_NICKNAME);
String image = actor.getString(JSON_CHARACTER_IMAGE);
String status = actor.getString(JSON_CHARACTER_STATUS);
String birth = actor.getString(JSON_CHARACTER_BIRTHDAY);
JSONArray occupationA = actor.getJSONArray(JSON_CHARACTER_OCCUPATION);
JSONArray appearanceA = actor.getJSONArray(JSON_CHARACTER_APPEARANCE);
// Loop for occupation arrays
for(int p=0; p<occupationA.length();p++){
String occupation = (String) occupationA.get(p);
occupations.add(occupation);
}
// Loop for appearance arrays
for(int z=0; z<appearanceA.length();z++){
int appear = (Integer) appearanceA.get(z);
appearances.add(appear);
}
// Adding the character
resultList.add(new Character(name, image, nickname, status, birth, occupations, appearances));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "returning " + resultList.size()+ " items.");
return resultList;
}
public interface CharacterListener{
public void onCharactersAvailable(List<Character> characters);
}
}
| AzethS/BreakingBad | app/src/main/java/com/example/breakingbad/CharacterAPITask.java | 1,362 | //Omzetting van String naar ArrayList
| line_comment | nl | package com.example.breakingbad;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharacterAPITask extends AsyncTask<String, Void, List<Character>> {
private final String TAG = getClass().getSimpleName();
private final String JSON_CHARACTER_NAME = "name";
private final String JSON_CHARACTER_NICKNAME = "nickname";
private final String JSON_CHARACTER_IMAGE = "img";
private final String JSON_CHARACTER_STATUS = "status";
private final String JSON_CHARACTER_BIRTHDAY = "birthday";
private final String JSON_CHARACTER_OCCUPATION = "occupation";
private final String JSON_CHARACTER_APPEARANCE = "appearance";
private CharacterListener listener = null;
public CharacterAPITask(CharacterListener listener) {
this.listener = listener;
}
@Override
protected List<Character> doInBackground(String... params) {
// URL maken of ophalen of samenstellen
String characterUrlString = params[0];
HttpURLConnection urlConnection = null;
URL url = null;
try{
url = new URL(characterUrlString);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
String response = scanner.next();
Log.d(TAG, "response: " + response);
ArrayList<Character> resultList = convertJsonToArrayList(response);
return resultList;
} else {
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != urlConnection) {
urlConnection.disconnect();
}
}
// request bouwen en versturen
// response afwachten en bewerken
// ArrayList maken.
return null;
}
@Override
protected void onPostExecute(List<Character> characters) {
super.onPostExecute(characters);
Log.d(TAG, " in onPostExecute: " + characters.size() + " items.");
// Lijst van characters naar adapter brengen
listener.onCharactersAvailable(characters);
}
// Hulpmethode
private ArrayList<Character> convertJsonToArrayList(String response){
ArrayList<Character> resultList = new ArrayList<>();
//Omzetting van<SUF>
try {
JSONArray characters = new JSONArray(response);
for (int i = 0; i<characters.length(); i++){
ArrayList<String> occupations = new ArrayList<>();
ArrayList<Integer> appearances = new ArrayList<>();
JSONObject actor = characters.getJSONObject(i);
String name = actor.getString(JSON_CHARACTER_NAME);
String nickname = actor.getString(JSON_CHARACTER_NICKNAME);
String image = actor.getString(JSON_CHARACTER_IMAGE);
String status = actor.getString(JSON_CHARACTER_STATUS);
String birth = actor.getString(JSON_CHARACTER_BIRTHDAY);
JSONArray occupationA = actor.getJSONArray(JSON_CHARACTER_OCCUPATION);
JSONArray appearanceA = actor.getJSONArray(JSON_CHARACTER_APPEARANCE);
// Loop for occupation arrays
for(int p=0; p<occupationA.length();p++){
String occupation = (String) occupationA.get(p);
occupations.add(occupation);
}
// Loop for appearance arrays
for(int z=0; z<appearanceA.length();z++){
int appear = (Integer) appearanceA.get(z);
appearances.add(appear);
}
// Adding the character
resultList.add(new Character(name, image, nickname, status, birth, occupations, appearances));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "returning " + resultList.size()+ " items.");
return resultList;
}
public interface CharacterListener{
public void onCharactersAvailable(List<Character> characters);
}
}
|
63018_85 | import com.microsoft.azure.cognitiveservices.vision.faceapi.*;
import com.microsoft.azure.cognitiveservices.vision.faceapi.models.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* This quickstart contains:
* - Detect Faces: detect a face or faces in an image and URL
* - Find Similar: find face similar to the single-faced image in the group image
* - Verify: with 2 images, check if they are the same person or different people
* - Identify: with grouped images of the same person, use group to find similar faces in another image
* - Group Faces: groups images into sub-groups based on same person images
* - Face Lists: adds images to a face list, then retrieves them
* - Delete: deletes the person group and face list to enable repeated testing
*
* Prerequisites:
* - Create a Face subscription in the Azure portal.
* - Create a lib folder in the root directory of your project, then add the jars from dependencies.txt
* - Download the FaceAPI library (ms-azure-cs-faceapi.jar) from this repo and add to your lib folder.
* - Replace the "REGION" variable in the authenticate section with your region.
* The "westus" region is used, otherwise, as the default.
* NOTE: this quickstart does not need your Face endpoint.
*
* To compile and run, enter the following at a command prompt:
* javac FaceQuickstart.java -cp .;lib\*
* java -cp .;lib\* FaceQuickstart
*
* Note If you run this sample with JRE 9+, you may encounter the following issue:
* https://github.com/Azure/autorest-clientruntime-for-java/issues/569 which results in the following output:
* WARNING: An illegal reflective access operation has occurred ... (plus several more warnings)
*
* This should not prevent the sample from running correctly, so this can be ignored.
*
* References:
* - Face Documentation: https://docs.microsoft.com/en-us/azure/cognitive-services/face/
* - Face Java SDK: https://docs.microsoft.com/en-us/java/api/overview/azure/cognitiveservices/client/faceapi?view=azure-java-stable
* - API Reference: https://docs.microsoft.com/en-us/azure/cognitive-services/face/apireference
*/
public class FaceQuickstart {
public static void main(String[] args) {
// For Detect Faces and Find Similar Faces examples
// This image should have a single face.
final String SINGLE_FACE_URL = "https://www.biography.com/.image/t_share/MTQ1MzAyNzYzOTgxNTE0NTEz/john-f-kennedy---mini-biography.jpg";
final String SINGLE_IMAGE_NAME =
SINGLE_FACE_URL.substring(SINGLE_FACE_URL.lastIndexOf('/')+1, SINGLE_FACE_URL.length());
// This image should have several faces. At least one should be similar to the face in singleFaceImage.
final String GROUP_FACES_URL = "http://www.historyplace.com/kennedy/president-family-portrait-closeup.jpg";
final String GROUP_IMAGE_NAME =
GROUP_FACES_URL.substring(GROUP_FACES_URL.lastIndexOf('/')+1, GROUP_FACES_URL.length());
// For Identify, Verify, Group Faces, and Face Lists examples
final String IMAGE_BASE_URL = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/";
// Used for the Identify example and Delete examples
final String PERSON_GROUP_ID = "my-families"; // can be any lowercase, 0-9, "-", or "_" character.
// Used for the Face List and Delete examples
final String FACE_LIST_ID = "my-families-list";
/**
* Authenticate
*/
final String KEY = "PASTE_YOUR_FACE_SUBSCRIPTION_KEY_HERE";
// Add your region of your Face subscription, for example 'westus', 'eastus', etc.
// List of Azure Regions: https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.cognitiveservices.vision.faceapi.models.azureregions?view=azure-java-stable
final AzureRegions REGION = AzureRegions.WESTUS;
// Create Face client
FaceAPI client = FaceAPIManager.authenticate(REGION, KEY);
/**
* END - Authenticate
*/
System.out.println("============== Detect Face ==============");
// Detect the face in a single-faced image. Returns a list of UUIDs and prints them.
List<UUID> singleFaceIDs = detectFaces(client, SINGLE_FACE_URL, SINGLE_IMAGE_NAME);
// Detect the faces in a group image. Returns a list of UUIDs and prints them.
List<UUID> groupFaceIDs = detectFaces(client, GROUP_FACES_URL, GROUP_IMAGE_NAME);
System.out.println("============== Find Similar ==============");
// Finds a similar face in group image. Returns a list of UUIDs and prints them.
findSimilar(client, singleFaceIDs, groupFaceIDs, GROUP_IMAGE_NAME);
System.out.println("============== Verify ==============");
// Checks if 2 photos are of the same or different person.
verify(client, IMAGE_BASE_URL);
System.out.println("============== Identify ==============");
// Groups similar photos of a person, then uses that group
// to recognize the person in another photo.
identifyFaces(client, IMAGE_BASE_URL, PERSON_GROUP_ID);
System.out.println("============== Group Faces ==============");
// Groups all faces in list into sub-groups based on similar faces.
groupFaces(client, IMAGE_BASE_URL);
System.out.println("============== Face Lists ==============");
faceLists(client, IMAGE_BASE_URL, FACE_LIST_ID);
System.out.println("============== Delete ==============");
delete(client, PERSON_GROUP_ID, FACE_LIST_ID);
}
/**
* END - Main
*/
/**
* Detect Face
* Detects the face(s) in an image URL.
*/
public static List<UUID> detectFaces(FaceAPI client, String imageURL, String imageName) {
// Create face IDs list
List<DetectedFace> facesList = client.faces().detectWithUrl(imageURL, new DetectWithUrlOptionalParameter().withReturnFaceId(true));
System.out.println("Detected face ID(s) from URL image: " + imageName + " :");
// Get face(s) UUID(s)
List<UUID> faceUuids = new ArrayList<>();
for (DetectedFace face : facesList) {
faceUuids.add(face.faceId());
System.out.println(face.faceId());
}
System.out.println();
return faceUuids;
}
/**
* END - Detect Face
*/
/**
* Find Similar
* Finds a similar face in another image with 2 lists of face IDs.
* Returns the IDs of those that are similar.
*/
public static List<UUID> findSimilar(FaceAPI client, List<UUID> singleFaceList, List<UUID> groupFacesList, String groupImageName) {
// With our list of the single-faced image ID and the list of group IDs, check if any similar faces.
List<SimilarFace> listSimilars = client.faces().findSimilar(singleFaceList.get(0),
new FindSimilarOptionalParameter().withFaceIds(groupFacesList));
// Display the similar faces found
System.out.println();
System.out.println("Similar faces found in group photo " + groupImageName + " are:");
// Create a list of UUIDs to hold the similar faces found
List<UUID> similarUuids = new ArrayList<>();
for (SimilarFace face : listSimilars) {
similarUuids.add(face.faceId());
System.out.println("Face ID: " + face.faceId());
// Get and print the level of certainty that there is a match
// Confidence range is 0.0 to 1.0. Closer to 1.0 is more confident
System.out.println("Confidence: " + face.confidence());
}
System.out.println();
return similarUuids;
}
/**
* END - Find Similar
*/
/**
* Verify
* With 2 photos, compare them to check if they are the same or different person.
*/
public static void verify(FaceAPI client, String imageBaseURL) {
// Source images to use for the query
String sourceImage1 = "Family1-Dad3.jpg";
String sourceImage2 = "Family1-Son1.jpg";
// The target images to find similarities in.
List<String> targetImages = new ArrayList<>();
targetImages.add("Family1-Dad1.jpg");
targetImages.add("Family1-Dad2.jpg");
// Detect faces in the source images
List<UUID> source1ID = detectFaces(client, imageBaseURL + sourceImage1, sourceImage1);
List<UUID> source2ID = detectFaces(client, imageBaseURL + sourceImage2, sourceImage2);
// Create list to hold target image IDs
List<UUID> targetIDs = new ArrayList<>();
// Detect the faces in the target images
for (String face : targetImages) {
List<UUID> faceId = detectFaces(client, imageBaseURL + face, face);
targetIDs.add(faceId.get(0));
}
// Verification example for faces of the same person.
VerifyResult sameResult = client.faces().verifyFaceToFace(source1ID.get(0), targetIDs.get(0));
System.out.println(sameResult.isIdentical() ?
"Faces from " + sourceImage1 + " & " + targetImages.get(0) + " are of the same person." :
"Faces from " + sourceImage1 + " & " + targetImages.get(0) + " are different people.");
// Verification example for faces of different persons.
VerifyResult differentResult = client.faces().verifyFaceToFace(source2ID.get(0), targetIDs.get(0));
System.out.println(differentResult.isIdentical() ?
"Faces from " + sourceImage2 + " & " + targetImages.get(1) + " are of the same person." :
"Faces from " + sourceImage2 + " & " + targetImages.get(1) + " are different people.");
System.out.println();
}
/**
* END - Verify
*/
/**
* Identify Faces
* To identify a face, a list of detected faces and a person group are used.
* The list of similar faces are assigned to one person group person,
* to teach the AI how to identify future images of that person.
* Uses the detectFaces() method from this quickstart.
*/
public static void identifyFaces(FaceAPI client, String imageBaseURL, String personGroupID) {
// Create a dictionary to hold all your faces
Map<String, String[]> facesList = new HashMap<String, String[]>();
facesList.put("Family1-Dad", new String[] { "Family1-Dad1.jpg", "Family1-Dad2.jpg" });
facesList.put("Family1-Mom", new String[] { "Family1-Mom1.jpg", "Family1-Mom2.jpg" });
facesList.put("Family1-Son", new String[] { "Family1-Son1.jpg", "Family1-Son2.jpg" });
facesList.put("Family1-Daughter", new String[] { "Family1-Daughter1.jpg", "Family1-Daughter2.jpg" });
facesList.put("Family2-Lady", new String[] { "Family2-Lady1.jpg", "Family2-Lady2.jpg" });
facesList.put("Family2-Man", new String[] { "Family2-Man1.jpg", "Family2-Man2.jpg" });
// A group photo that includes some of the persons you seek to identify from your dictionary.
String groupPhoto = "identification1.jpg";
System.out.println("Creating the person group " + personGroupID + " ...");
// Create the person group, so our photos have one to belong to.
client.personGroups().create(personGroupID, new CreatePersonGroupsOptionalParameter().withName(personGroupID));
// Group the faces. Each array of similar faces will be grouped into a single person group person.
for (String personName : facesList.keySet()) {
// Associate the family member name with an ID, by creating a Person object.
UUID personID = UUID.randomUUID();
Person person = client.personGroupPersons().create(personGroupID,
new CreatePersonGroupPersonsOptionalParameter().withName(personName));
for (String personImage : facesList.get(personName)) {
// Add each image in array to a person group person (represented by the key and person ID).
client.personGroupPersons().addPersonFaceFromUrl(personGroupID, person.personId(), imageBaseURL + personImage, null);
}
}
// Once images are added to a person group person, train the person group.
System.out.println();
System.out.println("Training person group " + personGroupID + " ...");
client.personGroups().train(personGroupID);
// Wait until the training is completed.
while(true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { e.printStackTrace(); }
// Get training status
TrainingStatus status = client.personGroups().getTrainingStatus(personGroupID);
if (status.status() == TrainingStatusType.SUCCEEDED) {
System.out.println("Training status: " + status.status());
break;
}
System.out.println("Training status: " + status.status());
}
System.out.println();
// Detect faces from our group photo (which may contain one of our person group persons)
List<UUID> detectedFaces = detectFaces(client, imageBaseURL + groupPhoto, groupPhoto);
// Identifies which faces in group photo are in our person group.
List<IdentifyResult> identifyResults = client.faces().identify(personGroupID, detectedFaces, null);
// Print each person group person (the person ID) identified from our results.
System.out.println("Persons identified in group photo " + groupPhoto + ": ");
for (IdentifyResult person : identifyResults) {
System.out.println("Person ID: " + person.faceId().toString()
+ " with confidence " + person.candidates().get(0).confidence());
}
}
/**
* END - Identify Faces
*/
/**
* Group Faces
* This method of grouping is useful if you don't need to create a person group. It will automatically group similar
* images, whereas the person group method allows you to define the grouping.
* A single "messyGroup" array contains face IDs for which no similarities were found.
*/
public static void groupFaces(FaceAPI client, String imageBaseURL) {
// Images we want to group
List<String> imagesList = new ArrayList<>();
imagesList.add("Family1-Dad1.jpg");
imagesList.add("Family1-Dad2.jpg");
imagesList.add("Family3-Lady1.jpg");
imagesList.add("Family1-Daughter1.jpg");
imagesList.add("Family1-Daughter2.jpg");
imagesList.add("Family1-Daughter3.jpg");
// Create empty dictionary to store the groups
Map<String, String> faces = new HashMap<>();
List<UUID> faceIds = new ArrayList<>();
// First, detect the faces in your images
for (String image : imagesList) {
// Detect faces from image url (prints detected face results)
List<UUID> detectedFaces = detectFaces(client, imageBaseURL + image, image);
// Add detected faceId to faceIds and faces.
faceIds.add(detectedFaces.get(0)); // get first in list, since all images only have 1 face.
faces.put(detectedFaces.get(0).toString(), image);
}
// Group the faces. Grouping result is a collection that contains similar faces and a "messy group".
GroupResult results = client.faces().group(faceIds);
// Find the number of groups (inner lists) found in all images.
// GroupResult.groups() returns a List<List<UUID>>.
for (int i = 0; i < results.groups().size(); i++) {
System.out.println("Found face group " + (i + 1) + ": ");
for (UUID id : results.groups().get(i)) {
// Print the IDs from each group found, as seen associated in your map.
System.out.println(id);
}
System.out.println();
}
// MessyGroup contains all faces which are not similar to any other faces.
// The faces that cannot be grouped by similarities. Odd ones out.
System.out.println("Found messy group: ");
for (UUID mID : results.messyGroup()) {
System.out.println(mID);
}
System.out.println();
}
/**
* END - Group Faces
*/
/**
* Face Lists
* This example adds images to a face list. Can add up to 1 million.
*/
public static void faceLists(FaceAPI client, String imageBaseURL, String faceListID) {
// Images we want to the face list
List<String> imagesList = new ArrayList<>();
imagesList.add("Family1-Dad1.jpg");
imagesList.add("Family1-Dad2.jpg");
imagesList.add("Family3-Lady1.jpg");
imagesList.add("Family1-Daughter1.jpg");
imagesList.add("Family1-Daughter2.jpg");
imagesList.add("Family1-Daughter3.jpg");
// Create an empty face list with a face list ID
// (optional) Add the name you want to give the list to the CreateFaceListsOptionalParameter
System.out.println("Creating the face list " + faceListID + " ...");
client.faceLists().create(faceListID, new CreateFaceListsOptionalParameter().withName(faceListID));
// Add each image from our ArrayList to our face list
for (String image : imagesList) {
// Returns a PersistedFace object
client.faceLists().addFaceFromUrl(faceListID, imageBaseURL + image, null);
}
// Get the persisted faces we added to our face list.
FaceList retrievedFaceList = client.faceLists().get(faceListID);
// Print the UUIDs retrieved
System.out.println("Face list IDs: ");
for (PersistedFace face : retrievedFaceList.persistedFaces()) {
System.out.println(face.persistedFaceId());
}
System.out.println();
}
/**
* END - Face Lists
*/
/**
* Delete
* The delete operations erase the person group and face list from your API account,
* so you can test multiple times with the same name.
*/
public static void delete(FaceAPI client, String personGroupID, String faceListID){
// Delete the person group
// There is also an option in the SDK to delete one Person
// from the person group, but we don't show that here.
System.out.println("Deleting the person group...");
client.personGroups().delete(personGroupID);
System.out.println("Deleted the person group " + personGroupID);
// Delete the entire face list
// There is also an option in the SDK to delete one face
// from the list, but we don't show that here.
System.out.println("Deleting the face list...");
client.faceLists().delete(faceListID);
System.out.println("Deleted the face list " + faceListID);
}
/**
* END - Delete
*/
}
| Azure-Samples/cognitive-services-quickstart-code | java/Face/FaceQuickstart.java | 5,315 | /**
* END - Delete
*/ | block_comment | nl | import com.microsoft.azure.cognitiveservices.vision.faceapi.*;
import com.microsoft.azure.cognitiveservices.vision.faceapi.models.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* This quickstart contains:
* - Detect Faces: detect a face or faces in an image and URL
* - Find Similar: find face similar to the single-faced image in the group image
* - Verify: with 2 images, check if they are the same person or different people
* - Identify: with grouped images of the same person, use group to find similar faces in another image
* - Group Faces: groups images into sub-groups based on same person images
* - Face Lists: adds images to a face list, then retrieves them
* - Delete: deletes the person group and face list to enable repeated testing
*
* Prerequisites:
* - Create a Face subscription in the Azure portal.
* - Create a lib folder in the root directory of your project, then add the jars from dependencies.txt
* - Download the FaceAPI library (ms-azure-cs-faceapi.jar) from this repo and add to your lib folder.
* - Replace the "REGION" variable in the authenticate section with your region.
* The "westus" region is used, otherwise, as the default.
* NOTE: this quickstart does not need your Face endpoint.
*
* To compile and run, enter the following at a command prompt:
* javac FaceQuickstart.java -cp .;lib\*
* java -cp .;lib\* FaceQuickstart
*
* Note If you run this sample with JRE 9+, you may encounter the following issue:
* https://github.com/Azure/autorest-clientruntime-for-java/issues/569 which results in the following output:
* WARNING: An illegal reflective access operation has occurred ... (plus several more warnings)
*
* This should not prevent the sample from running correctly, so this can be ignored.
*
* References:
* - Face Documentation: https://docs.microsoft.com/en-us/azure/cognitive-services/face/
* - Face Java SDK: https://docs.microsoft.com/en-us/java/api/overview/azure/cognitiveservices/client/faceapi?view=azure-java-stable
* - API Reference: https://docs.microsoft.com/en-us/azure/cognitive-services/face/apireference
*/
public class FaceQuickstart {
public static void main(String[] args) {
// For Detect Faces and Find Similar Faces examples
// This image should have a single face.
final String SINGLE_FACE_URL = "https://www.biography.com/.image/t_share/MTQ1MzAyNzYzOTgxNTE0NTEz/john-f-kennedy---mini-biography.jpg";
final String SINGLE_IMAGE_NAME =
SINGLE_FACE_URL.substring(SINGLE_FACE_URL.lastIndexOf('/')+1, SINGLE_FACE_URL.length());
// This image should have several faces. At least one should be similar to the face in singleFaceImage.
final String GROUP_FACES_URL = "http://www.historyplace.com/kennedy/president-family-portrait-closeup.jpg";
final String GROUP_IMAGE_NAME =
GROUP_FACES_URL.substring(GROUP_FACES_URL.lastIndexOf('/')+1, GROUP_FACES_URL.length());
// For Identify, Verify, Group Faces, and Face Lists examples
final String IMAGE_BASE_URL = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/";
// Used for the Identify example and Delete examples
final String PERSON_GROUP_ID = "my-families"; // can be any lowercase, 0-9, "-", or "_" character.
// Used for the Face List and Delete examples
final String FACE_LIST_ID = "my-families-list";
/**
* Authenticate
*/
final String KEY = "PASTE_YOUR_FACE_SUBSCRIPTION_KEY_HERE";
// Add your region of your Face subscription, for example 'westus', 'eastus', etc.
// List of Azure Regions: https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.cognitiveservices.vision.faceapi.models.azureregions?view=azure-java-stable
final AzureRegions REGION = AzureRegions.WESTUS;
// Create Face client
FaceAPI client = FaceAPIManager.authenticate(REGION, KEY);
/**
* END - Authenticate
*/
System.out.println("============== Detect Face ==============");
// Detect the face in a single-faced image. Returns a list of UUIDs and prints them.
List<UUID> singleFaceIDs = detectFaces(client, SINGLE_FACE_URL, SINGLE_IMAGE_NAME);
// Detect the faces in a group image. Returns a list of UUIDs and prints them.
List<UUID> groupFaceIDs = detectFaces(client, GROUP_FACES_URL, GROUP_IMAGE_NAME);
System.out.println("============== Find Similar ==============");
// Finds a similar face in group image. Returns a list of UUIDs and prints them.
findSimilar(client, singleFaceIDs, groupFaceIDs, GROUP_IMAGE_NAME);
System.out.println("============== Verify ==============");
// Checks if 2 photos are of the same or different person.
verify(client, IMAGE_BASE_URL);
System.out.println("============== Identify ==============");
// Groups similar photos of a person, then uses that group
// to recognize the person in another photo.
identifyFaces(client, IMAGE_BASE_URL, PERSON_GROUP_ID);
System.out.println("============== Group Faces ==============");
// Groups all faces in list into sub-groups based on similar faces.
groupFaces(client, IMAGE_BASE_URL);
System.out.println("============== Face Lists ==============");
faceLists(client, IMAGE_BASE_URL, FACE_LIST_ID);
System.out.println("============== Delete ==============");
delete(client, PERSON_GROUP_ID, FACE_LIST_ID);
}
/**
* END - Main
*/
/**
* Detect Face
* Detects the face(s) in an image URL.
*/
public static List<UUID> detectFaces(FaceAPI client, String imageURL, String imageName) {
// Create face IDs list
List<DetectedFace> facesList = client.faces().detectWithUrl(imageURL, new DetectWithUrlOptionalParameter().withReturnFaceId(true));
System.out.println("Detected face ID(s) from URL image: " + imageName + " :");
// Get face(s) UUID(s)
List<UUID> faceUuids = new ArrayList<>();
for (DetectedFace face : facesList) {
faceUuids.add(face.faceId());
System.out.println(face.faceId());
}
System.out.println();
return faceUuids;
}
/**
* END - Detect Face
*/
/**
* Find Similar
* Finds a similar face in another image with 2 lists of face IDs.
* Returns the IDs of those that are similar.
*/
public static List<UUID> findSimilar(FaceAPI client, List<UUID> singleFaceList, List<UUID> groupFacesList, String groupImageName) {
// With our list of the single-faced image ID and the list of group IDs, check if any similar faces.
List<SimilarFace> listSimilars = client.faces().findSimilar(singleFaceList.get(0),
new FindSimilarOptionalParameter().withFaceIds(groupFacesList));
// Display the similar faces found
System.out.println();
System.out.println("Similar faces found in group photo " + groupImageName + " are:");
// Create a list of UUIDs to hold the similar faces found
List<UUID> similarUuids = new ArrayList<>();
for (SimilarFace face : listSimilars) {
similarUuids.add(face.faceId());
System.out.println("Face ID: " + face.faceId());
// Get and print the level of certainty that there is a match
// Confidence range is 0.0 to 1.0. Closer to 1.0 is more confident
System.out.println("Confidence: " + face.confidence());
}
System.out.println();
return similarUuids;
}
/**
* END - Find Similar
*/
/**
* Verify
* With 2 photos, compare them to check if they are the same or different person.
*/
public static void verify(FaceAPI client, String imageBaseURL) {
// Source images to use for the query
String sourceImage1 = "Family1-Dad3.jpg";
String sourceImage2 = "Family1-Son1.jpg";
// The target images to find similarities in.
List<String> targetImages = new ArrayList<>();
targetImages.add("Family1-Dad1.jpg");
targetImages.add("Family1-Dad2.jpg");
// Detect faces in the source images
List<UUID> source1ID = detectFaces(client, imageBaseURL + sourceImage1, sourceImage1);
List<UUID> source2ID = detectFaces(client, imageBaseURL + sourceImage2, sourceImage2);
// Create list to hold target image IDs
List<UUID> targetIDs = new ArrayList<>();
// Detect the faces in the target images
for (String face : targetImages) {
List<UUID> faceId = detectFaces(client, imageBaseURL + face, face);
targetIDs.add(faceId.get(0));
}
// Verification example for faces of the same person.
VerifyResult sameResult = client.faces().verifyFaceToFace(source1ID.get(0), targetIDs.get(0));
System.out.println(sameResult.isIdentical() ?
"Faces from " + sourceImage1 + " & " + targetImages.get(0) + " are of the same person." :
"Faces from " + sourceImage1 + " & " + targetImages.get(0) + " are different people.");
// Verification example for faces of different persons.
VerifyResult differentResult = client.faces().verifyFaceToFace(source2ID.get(0), targetIDs.get(0));
System.out.println(differentResult.isIdentical() ?
"Faces from " + sourceImage2 + " & " + targetImages.get(1) + " are of the same person." :
"Faces from " + sourceImage2 + " & " + targetImages.get(1) + " are different people.");
System.out.println();
}
/**
* END - Verify
*/
/**
* Identify Faces
* To identify a face, a list of detected faces and a person group are used.
* The list of similar faces are assigned to one person group person,
* to teach the AI how to identify future images of that person.
* Uses the detectFaces() method from this quickstart.
*/
public static void identifyFaces(FaceAPI client, String imageBaseURL, String personGroupID) {
// Create a dictionary to hold all your faces
Map<String, String[]> facesList = new HashMap<String, String[]>();
facesList.put("Family1-Dad", new String[] { "Family1-Dad1.jpg", "Family1-Dad2.jpg" });
facesList.put("Family1-Mom", new String[] { "Family1-Mom1.jpg", "Family1-Mom2.jpg" });
facesList.put("Family1-Son", new String[] { "Family1-Son1.jpg", "Family1-Son2.jpg" });
facesList.put("Family1-Daughter", new String[] { "Family1-Daughter1.jpg", "Family1-Daughter2.jpg" });
facesList.put("Family2-Lady", new String[] { "Family2-Lady1.jpg", "Family2-Lady2.jpg" });
facesList.put("Family2-Man", new String[] { "Family2-Man1.jpg", "Family2-Man2.jpg" });
// A group photo that includes some of the persons you seek to identify from your dictionary.
String groupPhoto = "identification1.jpg";
System.out.println("Creating the person group " + personGroupID + " ...");
// Create the person group, so our photos have one to belong to.
client.personGroups().create(personGroupID, new CreatePersonGroupsOptionalParameter().withName(personGroupID));
// Group the faces. Each array of similar faces will be grouped into a single person group person.
for (String personName : facesList.keySet()) {
// Associate the family member name with an ID, by creating a Person object.
UUID personID = UUID.randomUUID();
Person person = client.personGroupPersons().create(personGroupID,
new CreatePersonGroupPersonsOptionalParameter().withName(personName));
for (String personImage : facesList.get(personName)) {
// Add each image in array to a person group person (represented by the key and person ID).
client.personGroupPersons().addPersonFaceFromUrl(personGroupID, person.personId(), imageBaseURL + personImage, null);
}
}
// Once images are added to a person group person, train the person group.
System.out.println();
System.out.println("Training person group " + personGroupID + " ...");
client.personGroups().train(personGroupID);
// Wait until the training is completed.
while(true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { e.printStackTrace(); }
// Get training status
TrainingStatus status = client.personGroups().getTrainingStatus(personGroupID);
if (status.status() == TrainingStatusType.SUCCEEDED) {
System.out.println("Training status: " + status.status());
break;
}
System.out.println("Training status: " + status.status());
}
System.out.println();
// Detect faces from our group photo (which may contain one of our person group persons)
List<UUID> detectedFaces = detectFaces(client, imageBaseURL + groupPhoto, groupPhoto);
// Identifies which faces in group photo are in our person group.
List<IdentifyResult> identifyResults = client.faces().identify(personGroupID, detectedFaces, null);
// Print each person group person (the person ID) identified from our results.
System.out.println("Persons identified in group photo " + groupPhoto + ": ");
for (IdentifyResult person : identifyResults) {
System.out.println("Person ID: " + person.faceId().toString()
+ " with confidence " + person.candidates().get(0).confidence());
}
}
/**
* END - Identify Faces
*/
/**
* Group Faces
* This method of grouping is useful if you don't need to create a person group. It will automatically group similar
* images, whereas the person group method allows you to define the grouping.
* A single "messyGroup" array contains face IDs for which no similarities were found.
*/
public static void groupFaces(FaceAPI client, String imageBaseURL) {
// Images we want to group
List<String> imagesList = new ArrayList<>();
imagesList.add("Family1-Dad1.jpg");
imagesList.add("Family1-Dad2.jpg");
imagesList.add("Family3-Lady1.jpg");
imagesList.add("Family1-Daughter1.jpg");
imagesList.add("Family1-Daughter2.jpg");
imagesList.add("Family1-Daughter3.jpg");
// Create empty dictionary to store the groups
Map<String, String> faces = new HashMap<>();
List<UUID> faceIds = new ArrayList<>();
// First, detect the faces in your images
for (String image : imagesList) {
// Detect faces from image url (prints detected face results)
List<UUID> detectedFaces = detectFaces(client, imageBaseURL + image, image);
// Add detected faceId to faceIds and faces.
faceIds.add(detectedFaces.get(0)); // get first in list, since all images only have 1 face.
faces.put(detectedFaces.get(0).toString(), image);
}
// Group the faces. Grouping result is a collection that contains similar faces and a "messy group".
GroupResult results = client.faces().group(faceIds);
// Find the number of groups (inner lists) found in all images.
// GroupResult.groups() returns a List<List<UUID>>.
for (int i = 0; i < results.groups().size(); i++) {
System.out.println("Found face group " + (i + 1) + ": ");
for (UUID id : results.groups().get(i)) {
// Print the IDs from each group found, as seen associated in your map.
System.out.println(id);
}
System.out.println();
}
// MessyGroup contains all faces which are not similar to any other faces.
// The faces that cannot be grouped by similarities. Odd ones out.
System.out.println("Found messy group: ");
for (UUID mID : results.messyGroup()) {
System.out.println(mID);
}
System.out.println();
}
/**
* END - Group Faces
*/
/**
* Face Lists
* This example adds images to a face list. Can add up to 1 million.
*/
public static void faceLists(FaceAPI client, String imageBaseURL, String faceListID) {
// Images we want to the face list
List<String> imagesList = new ArrayList<>();
imagesList.add("Family1-Dad1.jpg");
imagesList.add("Family1-Dad2.jpg");
imagesList.add("Family3-Lady1.jpg");
imagesList.add("Family1-Daughter1.jpg");
imagesList.add("Family1-Daughter2.jpg");
imagesList.add("Family1-Daughter3.jpg");
// Create an empty face list with a face list ID
// (optional) Add the name you want to give the list to the CreateFaceListsOptionalParameter
System.out.println("Creating the face list " + faceListID + " ...");
client.faceLists().create(faceListID, new CreateFaceListsOptionalParameter().withName(faceListID));
// Add each image from our ArrayList to our face list
for (String image : imagesList) {
// Returns a PersistedFace object
client.faceLists().addFaceFromUrl(faceListID, imageBaseURL + image, null);
}
// Get the persisted faces we added to our face list.
FaceList retrievedFaceList = client.faceLists().get(faceListID);
// Print the UUIDs retrieved
System.out.println("Face list IDs: ");
for (PersistedFace face : retrievedFaceList.persistedFaces()) {
System.out.println(face.persistedFaceId());
}
System.out.println();
}
/**
* END - Face Lists
*/
/**
* Delete
* The delete operations erase the person group and face list from your API account,
* so you can test multiple times with the same name.
*/
public static void delete(FaceAPI client, String personGroupID, String faceListID){
// Delete the person group
// There is also an option in the SDK to delete one Person
// from the person group, but we don't show that here.
System.out.println("Deleting the person group...");
client.personGroups().delete(personGroupID);
System.out.println("Deleted the person group " + personGroupID);
// Delete the entire face list
// There is also an option in the SDK to delete one face
// from the list, but we don't show that here.
System.out.println("Deleting the face list...");
client.faceLists().delete(faceListID);
System.out.println("Deleted the face list " + faceListID);
}
/**
* END - Delete<SUF>*/
}
|
84300_13 | /*
* Copyright 2013 FasterXML.com
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package com.azure.android.core.serde.jackson.implementation.threeten;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.Temporal;
import org.threeten.bp.temporal.TemporalAccessor;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.regex.Pattern;
/**
* Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s.
*
* @author Nick Williams
* @since 2.2
*/
class InstantDeserializer<T extends Temporal>
extends ThreeTenDateTimeDeserializerBase<T> {
private static final long serialVersionUID = 1L;
/**
* Constants used to check if the time offset is zero. See [jackson-modules-java8#18]
*
* @since 2.9.0
*/
private static final Pattern ISO8601_UTC_ZERO_OFFSET_SUFFIX_REGEX = Pattern.compile("\\+00:?(00)?$");
// public static final InstantDeserializer<Instant> INSTANT = new InstantDeserializer<>(
// Instant.class, DateTimeFormatter.ISO_INSTANT,
// temporalAccessor -> Instant.from(temporalAccessor),
// a -> Instant.ofEpochMilli(a.value),
// a -> Instant.ofEpochSecond(a.integer, a.fraction),
// null,
// true // yes, replace zero offset with Z
// );
public static final InstantDeserializer<OffsetDateTime> OFFSET_DATE_TIME = new InstantDeserializer<>(
OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
temporalAccessor -> OffsetDateTime.from(temporalAccessor),
a -> OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId),
a -> OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId),
(d, z) -> d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())),
true // yes, replace zero offset with Z
);
// public static final InstantDeserializer<ZonedDateTime> ZONED_DATE_TIME = new InstantDeserializer<>(
// ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME,
// temporalAccessor -> ZonedDateTime.from(temporalAccessor),
// a -> ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId),
// a -> ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId),
// (zonedDateTime, zoneId) -> zonedDateTime.withZoneSameInstant(zoneId),
// false // keep zero offset and Z separate since zones explicitly supported
// );
protected final Function<FromIntegerArguments, T> fromMilliseconds;
protected final Function<FromDecimalArguments, T> fromNanoseconds;
protected final Function<TemporalAccessor, T> parsedToValue;
protected final BiFunction<T, ZoneId, T> adjust;
/**
* In case of vanilla `Instant` we seem to need to translate "+0000 | +00:00 | +00"
* timezone designator into plain "Z" for some reason; see
* [jackson-modules-java8#18] for more info
*
* @since 2.9.0
*/
protected final boolean replaceZeroOffsetAsZ;
/**
* Flag for <code>JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE</code>
*
* @since 2.8
*/
protected final Boolean _adjustToContextTZOverride;
protected InstantDeserializer(Class<T> supportedType,
DateTimeFormatter formatter,
Function<TemporalAccessor, T> parsedToValue,
Function<FromIntegerArguments, T> fromMilliseconds,
Function<FromDecimalArguments, T> fromNanoseconds,
BiFunction<T, ZoneId, T> adjust,
boolean replaceZeroOffsetAsZ) {
super(supportedType, formatter);
this.parsedToValue = parsedToValue;
this.fromMilliseconds = fromMilliseconds;
this.fromNanoseconds = fromNanoseconds;
this.adjust = adjust == null ? (d, z) -> d : adjust;
this.replaceZeroOffsetAsZ = replaceZeroOffsetAsZ;
_adjustToContextTZOverride = null;
}
@SuppressWarnings("unchecked")
protected InstantDeserializer(InstantDeserializer<T> base, DateTimeFormatter f) {
super((Class<T>) base.handledType(), f);
parsedToValue = base.parsedToValue;
fromMilliseconds = base.fromMilliseconds;
fromNanoseconds = base.fromNanoseconds;
adjust = base.adjust;
replaceZeroOffsetAsZ = (_formatter == DateTimeFormatter.ISO_INSTANT);
_adjustToContextTZOverride = base._adjustToContextTZOverride;
}
@SuppressWarnings("unchecked")
protected InstantDeserializer(InstantDeserializer<T> base, Boolean adjustToContextTimezoneOverride) {
super((Class<T>) base.handledType(), base._formatter);
parsedToValue = base.parsedToValue;
fromMilliseconds = base.fromMilliseconds;
fromNanoseconds = base.fromNanoseconds;
adjust = base.adjust;
replaceZeroOffsetAsZ = base.replaceZeroOffsetAsZ;
_adjustToContextTZOverride = adjustToContextTimezoneOverride;
}
@Override
protected InstantDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
if (dtf == _formatter) {
return this;
}
return new InstantDeserializer<T>(this, dtf);
}
// !!! TODO: lenient vs strict?
@Override
protected InstantDeserializer<T> withLeniency(Boolean leniency) {
return this;
}
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
//NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only
//string values have to be adjusted to the configured TZ.
switch (parser.getCurrentTokenId()) {
case JsonTokenId.ID_NUMBER_FLOAT:
return _fromDecimal(context, parser.getDecimalValue());
case JsonTokenId.ID_NUMBER_INT:
return _fromLong(context, parser.getLongValue());
case JsonTokenId.ID_STRING: {
String string = parser.getText().trim();
if (string.length() == 0) {
return null;
}
// only check for other parsing modes if we are using default formatter
if (_formatter == DateTimeFormatter.ISO_INSTANT ||
_formatter == DateTimeFormatter.ISO_OFFSET_DATE_TIME ||
_formatter == DateTimeFormatter.ISO_ZONED_DATE_TIME) {
// 22-Jan-2016, [datatype-jsr310#16]: Allow quoted numbers too
int dots = _countPeriods(string);
if (dots >= 0) { // negative if not simple number
try {
if (dots == 0) {
return _fromLong(context, Long.parseLong(string));
}
if (dots == 1) {
return _fromDecimal(context, new BigDecimal(string));
}
} catch (NumberFormatException e) {
// fall through to default handling, to get error there
}
}
string = replaceZeroOffsetAsZIfNecessary(string);
}
T value;
try {
TemporalAccessor acc = _formatter.parse(string);
value = parsedToValue.apply(acc);
if (shouldAdjustToContextTimezone(context)) {
return adjust.apply(value, this.getZone(context));
}
} catch (DateTimeException e) {
value = _handleDateTimeException(context, e, string);
}
return value;
}
case JsonTokenId.ID_EMBEDDED_OBJECT:
// 20-Apr-2016, tatu: Related to [databind#1208], can try supporting embedded
// values quite easily
return (T) parser.getEmbeddedObject();
case JsonTokenId.ID_START_ARRAY:
return _deserializeFromArray(parser, context);
}
return _handleUnexpectedToken(context, parser, JsonToken.VALUE_STRING,
JsonToken.VALUE_NUMBER_INT, JsonToken.VALUE_NUMBER_FLOAT);
}
@SuppressWarnings("unchecked")
@Override
public JsonDeserializer<T> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
InstantDeserializer<T> deserializer =
(InstantDeserializer<T>)super.createContextual(ctxt, property);
if (deserializer != this) {
JsonFormat.Value val = findFormatOverrides(ctxt, property, handledType());
if (val != null) {
return new InstantDeserializer<>(deserializer, val.getFeature(JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE));
}
}
return this;
}
protected boolean shouldAdjustToContextTimezone(DeserializationContext context) {
return (_adjustToContextTZOverride != null) ? _adjustToContextTZOverride :
context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
}
// Helper method to find Strings of form "all digits" and "digits-comma-digits"
protected int _countPeriods(String str) {
int commas = 0;
for (int i = 0, end = str.length(); i < end; ++i) {
int ch = str.charAt(i);
if (ch < '0' || ch > '9') {
if (ch == '.') {
++commas;
} else {
return -1;
}
}
}
return commas;
}
protected T _fromLong(DeserializationContext context, long timestamp) {
if(context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)){
return fromNanoseconds.apply(new FromDecimalArguments(
timestamp, 0, this.getZone(context)
));
}
return fromMilliseconds.apply(new FromIntegerArguments(
timestamp, this.getZone(context)));
}
protected T _fromDecimal(final DeserializationContext context, BigDecimal value) {
FromDecimalArguments args =
DecimalUtils.extractSecondsAndNanos(value, (s, ns) -> new FromDecimalArguments(s, ns, getZone(context)));
return fromNanoseconds.apply(args);
}
private ZoneId getZone(DeserializationContext context) {
// Instants are always in UTC, so don't waste compute cycles
return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone());
}
private String replaceZeroOffsetAsZIfNecessary(String text) {
if (replaceZeroOffsetAsZ) {
return ISO8601_UTC_ZERO_OFFSET_SUFFIX_REGEX.matcher(text).replaceFirst("Z");
}
return text;
}
// since 2.8.3
public static class FromIntegerArguments {
public final long value;
public final ZoneId zoneId;
private FromIntegerArguments(long value, ZoneId zoneId) {
this.value = value;
this.zoneId = zoneId;
}
}
// since 2.8.3
public static class FromDecimalArguments {
public final long integer;
public final int fraction;
public final ZoneId zoneId;
private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) {
this.integer = integer;
this.fraction = fraction;
this.zoneId = zoneId;
}
}
}
| Azure/azure-sdk-for-android | sdk/core/azure-core-jackson/src/main/java/com/azure/android/core/serde/jackson/implementation/threeten/InstantDeserializer.java | 3,720 | // (zonedDateTime, zoneId) -> zonedDateTime.withZoneSameInstant(zoneId), | line_comment | nl | /*
* Copyright 2013 FasterXML.com
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package com.azure.android.core.serde.jackson.implementation.threeten;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.Temporal;
import org.threeten.bp.temporal.TemporalAccessor;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.regex.Pattern;
/**
* Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s.
*
* @author Nick Williams
* @since 2.2
*/
class InstantDeserializer<T extends Temporal>
extends ThreeTenDateTimeDeserializerBase<T> {
private static final long serialVersionUID = 1L;
/**
* Constants used to check if the time offset is zero. See [jackson-modules-java8#18]
*
* @since 2.9.0
*/
private static final Pattern ISO8601_UTC_ZERO_OFFSET_SUFFIX_REGEX = Pattern.compile("\\+00:?(00)?$");
// public static final InstantDeserializer<Instant> INSTANT = new InstantDeserializer<>(
// Instant.class, DateTimeFormatter.ISO_INSTANT,
// temporalAccessor -> Instant.from(temporalAccessor),
// a -> Instant.ofEpochMilli(a.value),
// a -> Instant.ofEpochSecond(a.integer, a.fraction),
// null,
// true // yes, replace zero offset with Z
// );
public static final InstantDeserializer<OffsetDateTime> OFFSET_DATE_TIME = new InstantDeserializer<>(
OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
temporalAccessor -> OffsetDateTime.from(temporalAccessor),
a -> OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId),
a -> OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId),
(d, z) -> d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())),
true // yes, replace zero offset with Z
);
// public static final InstantDeserializer<ZonedDateTime> ZONED_DATE_TIME = new InstantDeserializer<>(
// ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME,
// temporalAccessor -> ZonedDateTime.from(temporalAccessor),
// a -> ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId),
// a -> ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId),
// (zonedDateTime, zoneId)<SUF>
// false // keep zero offset and Z separate since zones explicitly supported
// );
protected final Function<FromIntegerArguments, T> fromMilliseconds;
protected final Function<FromDecimalArguments, T> fromNanoseconds;
protected final Function<TemporalAccessor, T> parsedToValue;
protected final BiFunction<T, ZoneId, T> adjust;
/**
* In case of vanilla `Instant` we seem to need to translate "+0000 | +00:00 | +00"
* timezone designator into plain "Z" for some reason; see
* [jackson-modules-java8#18] for more info
*
* @since 2.9.0
*/
protected final boolean replaceZeroOffsetAsZ;
/**
* Flag for <code>JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE</code>
*
* @since 2.8
*/
protected final Boolean _adjustToContextTZOverride;
protected InstantDeserializer(Class<T> supportedType,
DateTimeFormatter formatter,
Function<TemporalAccessor, T> parsedToValue,
Function<FromIntegerArguments, T> fromMilliseconds,
Function<FromDecimalArguments, T> fromNanoseconds,
BiFunction<T, ZoneId, T> adjust,
boolean replaceZeroOffsetAsZ) {
super(supportedType, formatter);
this.parsedToValue = parsedToValue;
this.fromMilliseconds = fromMilliseconds;
this.fromNanoseconds = fromNanoseconds;
this.adjust = adjust == null ? (d, z) -> d : adjust;
this.replaceZeroOffsetAsZ = replaceZeroOffsetAsZ;
_adjustToContextTZOverride = null;
}
@SuppressWarnings("unchecked")
protected InstantDeserializer(InstantDeserializer<T> base, DateTimeFormatter f) {
super((Class<T>) base.handledType(), f);
parsedToValue = base.parsedToValue;
fromMilliseconds = base.fromMilliseconds;
fromNanoseconds = base.fromNanoseconds;
adjust = base.adjust;
replaceZeroOffsetAsZ = (_formatter == DateTimeFormatter.ISO_INSTANT);
_adjustToContextTZOverride = base._adjustToContextTZOverride;
}
@SuppressWarnings("unchecked")
protected InstantDeserializer(InstantDeserializer<T> base, Boolean adjustToContextTimezoneOverride) {
super((Class<T>) base.handledType(), base._formatter);
parsedToValue = base.parsedToValue;
fromMilliseconds = base.fromMilliseconds;
fromNanoseconds = base.fromNanoseconds;
adjust = base.adjust;
replaceZeroOffsetAsZ = base.replaceZeroOffsetAsZ;
_adjustToContextTZOverride = adjustToContextTimezoneOverride;
}
@Override
protected InstantDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
if (dtf == _formatter) {
return this;
}
return new InstantDeserializer<T>(this, dtf);
}
// !!! TODO: lenient vs strict?
@Override
protected InstantDeserializer<T> withLeniency(Boolean leniency) {
return this;
}
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
//NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only
//string values have to be adjusted to the configured TZ.
switch (parser.getCurrentTokenId()) {
case JsonTokenId.ID_NUMBER_FLOAT:
return _fromDecimal(context, parser.getDecimalValue());
case JsonTokenId.ID_NUMBER_INT:
return _fromLong(context, parser.getLongValue());
case JsonTokenId.ID_STRING: {
String string = parser.getText().trim();
if (string.length() == 0) {
return null;
}
// only check for other parsing modes if we are using default formatter
if (_formatter == DateTimeFormatter.ISO_INSTANT ||
_formatter == DateTimeFormatter.ISO_OFFSET_DATE_TIME ||
_formatter == DateTimeFormatter.ISO_ZONED_DATE_TIME) {
// 22-Jan-2016, [datatype-jsr310#16]: Allow quoted numbers too
int dots = _countPeriods(string);
if (dots >= 0) { // negative if not simple number
try {
if (dots == 0) {
return _fromLong(context, Long.parseLong(string));
}
if (dots == 1) {
return _fromDecimal(context, new BigDecimal(string));
}
} catch (NumberFormatException e) {
// fall through to default handling, to get error there
}
}
string = replaceZeroOffsetAsZIfNecessary(string);
}
T value;
try {
TemporalAccessor acc = _formatter.parse(string);
value = parsedToValue.apply(acc);
if (shouldAdjustToContextTimezone(context)) {
return adjust.apply(value, this.getZone(context));
}
} catch (DateTimeException e) {
value = _handleDateTimeException(context, e, string);
}
return value;
}
case JsonTokenId.ID_EMBEDDED_OBJECT:
// 20-Apr-2016, tatu: Related to [databind#1208], can try supporting embedded
// values quite easily
return (T) parser.getEmbeddedObject();
case JsonTokenId.ID_START_ARRAY:
return _deserializeFromArray(parser, context);
}
return _handleUnexpectedToken(context, parser, JsonToken.VALUE_STRING,
JsonToken.VALUE_NUMBER_INT, JsonToken.VALUE_NUMBER_FLOAT);
}
@SuppressWarnings("unchecked")
@Override
public JsonDeserializer<T> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
InstantDeserializer<T> deserializer =
(InstantDeserializer<T>)super.createContextual(ctxt, property);
if (deserializer != this) {
JsonFormat.Value val = findFormatOverrides(ctxt, property, handledType());
if (val != null) {
return new InstantDeserializer<>(deserializer, val.getFeature(JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE));
}
}
return this;
}
protected boolean shouldAdjustToContextTimezone(DeserializationContext context) {
return (_adjustToContextTZOverride != null) ? _adjustToContextTZOverride :
context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
}
// Helper method to find Strings of form "all digits" and "digits-comma-digits"
protected int _countPeriods(String str) {
int commas = 0;
for (int i = 0, end = str.length(); i < end; ++i) {
int ch = str.charAt(i);
if (ch < '0' || ch > '9') {
if (ch == '.') {
++commas;
} else {
return -1;
}
}
}
return commas;
}
protected T _fromLong(DeserializationContext context, long timestamp) {
if(context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)){
return fromNanoseconds.apply(new FromDecimalArguments(
timestamp, 0, this.getZone(context)
));
}
return fromMilliseconds.apply(new FromIntegerArguments(
timestamp, this.getZone(context)));
}
protected T _fromDecimal(final DeserializationContext context, BigDecimal value) {
FromDecimalArguments args =
DecimalUtils.extractSecondsAndNanos(value, (s, ns) -> new FromDecimalArguments(s, ns, getZone(context)));
return fromNanoseconds.apply(args);
}
private ZoneId getZone(DeserializationContext context) {
// Instants are always in UTC, so don't waste compute cycles
return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone());
}
private String replaceZeroOffsetAsZIfNecessary(String text) {
if (replaceZeroOffsetAsZ) {
return ISO8601_UTC_ZERO_OFFSET_SUFFIX_REGEX.matcher(text).replaceFirst("Z");
}
return text;
}
// since 2.8.3
public static class FromIntegerArguments {
public final long value;
public final ZoneId zoneId;
private FromIntegerArguments(long value, ZoneId zoneId) {
this.value = value;
this.zoneId = zoneId;
}
}
// since 2.8.3
public static class FromDecimalArguments {
public final long integer;
public final int fraction;
public final ZoneId zoneId;
private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) {
this.integer = integer;
this.fraction = fraction;
this.zoneId = zoneId;
}
}
}
|
177259_22 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;
import com.azure.core.util.CoreUtils;
import java.util.concurrent.atomic.AtomicReference;
/**
* Used internally. HTTP constants in the Azure Cosmos DB database service Java
* SDK.
*/
public class HttpConstants {
public static class HttpMethods {
public static final String GET = "GET";
public static final String POST = "POST";
public static final String PUT = "PUT";
public static final String DELETE = "DELETE";
public static final String HEAD = "HEAD";
public static final String OPTIONS = "OPTIONS";
public static final String PATCH = "PATCH";
}
public static class QueryStrings {
public static final String URL = "$resolveFor";
public static final String FILTER = "$filter";
public static final String PARTITION_KEY_RANGE_IDS = "$partitionKeyRangeIds";
}
public static class HttpHeaders {
public static final String AUTHORIZATION = "authorization";
public static final String E_TAG = "etag";
public static final String METHOD_OVERRIDE = "X-HTTP-Method";
public static final String SLUG = "Slug";
public static final String CONTENT_TYPE = "Content-Type";
public static final String LAST_MODIFIED = "Last-Modified";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String CHARACTER_SET = "CharacterSet";
public static final String USER_AGENT = "User-Agent";
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String IF_MATCH = "If-Match";
public static final String IF_NONE_MATCH = "If-None-Match";
public static final String CONTENT_LENGTH = "Content-Length";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String KEEP_ALIVE = "Keep-Alive";
public static final String CONNECTION = "Connection";
public static final String CACHE_CONTROL = "Cache-Control";
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
public static final String CONTENT_LANGUAGE = "Content-Language";
public static final String CONTENT_LOCATION = "Content-Location";
public static final String CONTENT_MD5 = "Content-Md5";
public static final String CONTENT_RANGE = "Content-RANGE";
public static final String ACCEPT = "Accept";
public static final String ACCEPT_CHARSET = "Accept-Charset";
public static final String ACCEPT_LANGUAGE = "Accept-Language";
public static final String IF_RANGE = "If-RANGE";
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
public static final String MAX_FORWARDS = "Max-Forwards";
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
public static final String ACCEPT_RANGES = "Accept-Ranges";
public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";
public static final String RETRY_AFTER = "Retry-After";
public static final String SET_COOKIE = "Set-Cookie";
public static final String WWW_AUTHENTICATE = "Www-Authenticate";
public static final String ORIGIN = "Origin";
public static final String HOST = "Host";
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
public static final String KEY_VALUE_ENCODING_FORMAT = "application/x-www-form-urlencoded";
public static final String WRAP_ASSERTION_FORMAT = "wrap_assertion_format";
public static final String WRAP_ASSERTION = "wrap_assertion";
public static final String WRAP_SCOPE = "wrap_scope";
public static final String SIMPLE_TOKEN = "SWT";
public static final String HTTP_DATE = "date";
public static final String PREFER = "Prefer";
public static final String LOCATION = "Location";
public static final String REFERER = "referer";
// Query
public static final String QUERY = "x-ms-documentdb-query";
public static final String IS_QUERY = "x-ms-documentdb-isquery";
public static final String ENABLE_CROSS_PARTITION_QUERY = "x-ms-documentdb-query-enablecrosspartition";
public static final String PARALLELIZE_CROSS_PARTITION_QUERY = "x-ms-documentdb-query-parallelizecrosspartitionquery";
public static final String IS_QUERY_PLAN_REQUEST = "x-ms-cosmos-is-query-plan-request";
public static final String SUPPORTED_QUERY_FEATURES = "x-ms-cosmos-supported-query-features";
public static final String QUERY_VERSION = "x-ms-cosmos-query-version";
public static final String CORRELATED_ACTIVITY_ID = "x-ms-cosmos-correlated-activityid";
// Our custom DocDB headers
public static final String CONTINUATION = "x-ms-continuation";
public static final String PAGE_SIZE = "x-ms-max-item-count";
public static final String RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB = "x-ms-documentdb-responsecontinuationtokenlimitinkb";
// Request sender generated. Simply echoed by backend.
public static final String ACTIVITY_ID = "x-ms-activity-id";
public static final String PRE_TRIGGER_INCLUDE = "x-ms-documentdb-pre-trigger-include";
public static final String PRE_TRIGGER_EXCLUDE = "x-ms-documentdb-pre-trigger-exclude";
public static final String POST_TRIGGER_INCLUDE = "x-ms-documentdb-post-trigger-include";
public static final String POST_TRIGGER_EXCLUDE = "x-ms-documentdb-post-trigger-exclude";
public static final String INDEXING_DIRECTIVE = "x-ms-indexing-directive";
public static final String SESSION_TOKEN = "x-ms-session-token";
public static final String CONSISTENCY_LEVEL = "x-ms-consistency-level";
public static final String X_DATE = "x-ms-date";
public static final String COLLECTION_PARTITION_INFO = "x-ms-collection-partition-info";
public static final String COLLECTION_SERVICE_INFO = "x-ms-collection-service-info";
public static final String RETRY_AFTER_IN_MILLISECONDS = "x-ms-retry-after-ms";
public static final String IS_FEED_UNFILTERED = "x-ms-is-feed-unfiltered";
public static final String RESOURCE_TOKEN_EXPIRY = "x-ms-documentdb-expiry-seconds";
public static final String ENABLE_SCAN_IN_QUERY = "x-ms-documentdb-query-enable-scan";
public static final String EMIT_VERBOSE_TRACES_IN_QUERY = "x-ms-documentdb-query-emit-traces";
// target lsn for head requests
public static final String TARGET_LSN = "x-ms-target-lsn";
public static final String TARGET_GLOBAL_COMMITTED_LSN = "x-ms-target-global-committed-lsn";
// Request validation
public static final String REQUEST_VALIDATION_FAILURE = "x-ms-request-validation-failure";
public static final String WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH = "x-ms-write-request-trigger-refresh";
// Quota Info
public static final String MAX_RESOURCE_QUOTA = "x-ms-resource-quota";
public static final String CURRENT_RESOURCE_QUOTA_USAGE = "x-ms-resource-usage";
public static final String MAX_MEDIA_STORAGE_USAGE_IN_MB = "x-ms-max-media-storage-usage-mb";
// Usage Info
public static final String REQUEST_CHARGE = "x-ms-request-charge";
public static final String CURRENT_MEDIA_STORAGE_USAGE_IN_MB = "x-ms-media-storage-usage-mb";
public static final String DATABASE_ACCOUNT_CONSUMED_DOCUMENT_STORAGE_IN_MB = "x-ms-databaseaccount-consumed-mb";
public static final String DATABASE_ACCOUNT_RESERVED_DOCUMENT_STORAGE_IN_MB = "x-ms-databaseaccount-reserved-mb";
public static final String DATABASE_ACCOUNT_PROVISIONED_DOCUMENT_STORAGE_IN_MB = "x-ms-databaseaccount-provisioned-mb";
// Address related headers.
public static final String FORCE_REFRESH = "x-ms-force-refresh";
public static final String FORCE_COLLECTION_ROUTING_MAP_REFRESH = "x-ms-collectionroutingmap-refresh";
public static final String ITEM_COUNT = "x-ms-item-count";
public static final String NEW_RESOURCE_ID = "x-ms-new-resource-id";
public static final String USE_MASTER_COLLECTION_RESOLVER = "x-ms-use-master-collection-resolver";
// Admin Headers
public static final String FULL_UPGRADE = "x-ms-force-full-upgrade";
public static final String ONLY_UPGRADE_SYSTEM_APPLICATIONS = "x-ms-only-upgrade-system-applications";
public static final String ONLY_UPGRADE_NON_SYSTEM_APPLICATIONS = "x-ms-only-upgrade-non-system-applications";
public static final String UPGRADE_FABRIC_RING_CODE_AND_CONFIG = "x-ms-upgrade-fabric-code-config";
public static final String IGNORE_IN_PROGRESS_UPGRADE = "x-ms-ignore-inprogress-upgrade";
public static final String UPGRADE_VERIFICATION_KIND = "x-ms-upgrade-verification-kind";
public static final String IS_CANARY = "x-ms-iscanary";
public static final String FORCE_DELETE = "x-ms-force-delete";
// Version headers and values
public static final String VERSION = "x-ms-version";
public static final String SCHEMA_VERSION = "x-ms-schemaversion";
public static final String SERVER_VERSION = "x-ms-serviceversion";
public static final String GATEWAY_VERSION = "x-ms-gatewayversion";
// RDFE Resource Provider headers
public static final String OCP_RESOURCE_PROVIDER_REGISTERED_URI = "ocp-resourceprovider-registered-uri";
// For Document service management operations only. This is in
// essence a 'handle' to (long running) operations.
public static final String REQUEST_ID = "x-ms-request-id";
// Object returning this determines what constitutes state and what
// last state change means. For replica, it is the last role change.
public static final String LAST_STATE_CHANGE_UTC = "x-ms-last-state-change-utc";
// CSM specific headers
// Client-request-id: Optional caller-specified request ID, in the form
// of a GUID
public static final String CLIENT_REQUEST_ID = "x-ms-client-request-id";
// Offer header
public static final String OFFER_TYPE = "x-ms-offer-type";
public static final String OFFER_THROUGHPUT = "x-ms-offer-throughput";
public static final String OFFER_IS_RU_PER_MINUTE_THROUGHPUT_ENABLED = "x-ms-offer-is-ru-per-minute-throughput-enabled";
public static final String OFFER_MIN_THROUGHPUT = "x-ms-cosmos-min-throughput";
public static final String OFFER_AUTOPILOT_SETTINGS = "x-ms-cosmos-offer-autopilot-settings";
public static final String OFFER_REPLACE_PENDING = "x-ms-offer-replace-pending";
// Upsert header
public static final String IS_UPSERT = "x-ms-documentdb-is-upsert";
// Index progress headers
public static final String INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress";
public static final String LAZY_INDEXING_PROGRESS = "x-ms-documentdb-collection-lazy-indexing-progress";
// Owner name
public static final String OWNER_FULL_NAME = "x-ms-alt-content-path";
// Owner ID used for name based request in session token.
public static final String OWNER_ID = "x-ms-content-path";
// Partition headers
public static final String PARTITION_KEY = "x-ms-documentdb-partitionkey";
public static final String PARTITION_KEY_RANGE_ID = "x-ms-documentdb-partitionkeyrangeid";
// Error response sub status code
public static final String SUB_STATUS = "x-ms-substatus";
public static final String LSN = "lsn";
// CUSTOM DocDB JavaScript logging headers
public static final String SCRIPT_ENABLE_LOGGING = "x-ms-documentdb-script-enable-logging";
public static final String SCRIPT_LOG_RESULTS = "x-ms-documentdb-script-log-results";
// Collection quota
public static final String POPULATE_QUOTA_INFO = "x-ms-documentdb-populatequotainfo";
// ChangeFeed
public static final String A_IM = "A-IM";
public static final String ALLOW_TENTATIVE_WRITES = "x-ms-cosmos-allow-tentative-writes";
public static final String CHANGE_FEED_WIRE_FORMAT_VERSION = "x-ms-cosmos-changefeed-wire-format-version";
// These properties were added to support RNTBD and they've been added here to
// reduce merge conflicts
public static final String CAN_CHARGE = "x-ms-cancharge";
public static final String CAN_OFFER_REPLACE_COMPLETE = "x-ms-can-offer-replace-complete";
public static final String CAN_THROTTLE = "x-ms-canthrottle";
public static final String CLIENT_RETRY_ATTEMPT_COUNT = "x-ms-client-retry-attempt-count";
public static final String COLLECTION_INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress";
public static final String COLLECTION_LAZY_INDEXING_PROGRESS = "x-ms-documentdb-collection-lazy-indexing-progress";
public static final String COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER = "x-ms-collection-security-identifier";
public static final String CONTENT_SERIALIZATION_FORMAT = "x-ms-documentdb-content-serialization-format";
public static final String DISABLE_RNTBD_CHANNEL = "x-ms-disable-rntbd-channel";
public static final String DISABLE_RU_PER_MINUTE_USAGE = "x-ms-documentdb-disable-ru-per-minute-usage";
public static final String ENABLE_LOGGING = "x-ms-documentdb-script-enable-logging";
public static final String ENABLE_LOW_PRECISION_ORDER_BY = "x-ms-documentdb-query-enable-low-precision-order-by";
public static final String END_EPK = "x-ms-end-epk";
public static final String END_ID = "x-ms-end-id";
public static final String ENUMERATION_DIRECTION = "x-ms-enumeration-direction";
public static final String FILTER_BY_SCHEMA_RESOURCE_ID = "x-ms-documentdb-filterby-schema-rid";
public static final String FORCE_QUERY_SCAN = "x-ms-documentdb-force-query-scan";
public static final String GATEWAY_SIGNATURE = "x-ms-gateway-signature";
public static final String IS_AUTO_SCALE_REQUEST = "x-ms-is-auto-scale";
public static final String IS_READ_ONLY_SCRIPT = "x-ms-is-readonly-script";
public static final String LOG_RESULTS = "x-ms-documentdb-script-log-results";
public static final String MIGRATE_COLLECTION_DIRECTIVE = "x-ms-migratecollection-directive";
public static final String POPULATE_COLLECTION_THROUGHPUT_INFO = "x-ms-documentdb-populatecollectionthroughputinfo";
public static final String POPULATE_PARTITION_STATISTICS = "x-ms-documentdb-populatepartitionstatistics";
public static final String POPULATE_QUERY_METRICS = "x-ms-documentdb-populatequerymetrics";
public static final String PROFILE_REQUEST = "x-ms-profile-request";
public static final String READ_FEED_KEY_TYPE = "x-ms-read-key-type";
public static final String REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST = "x-ms-remaining-time-in-ms-on-client";
public static final String RESTORE_METADATA_FILTER = "x-ms-restore-metadata-filter";
public static final String SHARED_OFFER_THROUGHPUT = "x-ms-cosmos-shared-offer-throughput";
public static final String START_EPK = "x-ms-start-epk";
public static final String START_ID = "x-ms-start-id";
public static final String SUPPORT_SPATIAL_LEGACY_COORDINATES = "x-ms-documentdb-supportspatiallegacycoordinates";
public static final String TRANSPORT_REQUEST_ID = "x-ms-transport-request-id";
public static final String USE_POLYGONS_SMALLER_THAN_AHEMISPHERE = "x-ms-documentdb-usepolygonssmallerthanahemisphere";
public static final String API_TYPE = "x-ms-cosmos-apitype";
public static final String QUERY_METRICS = "x-ms-documentdb-query-metrics";
public static final String POPULATE_INDEX_METRICS = "x-ms-cosmos-populateindexmetrics";
public static final String INDEX_UTILIZATION = "x-ms-cosmos-index-utilization";
public static final String QUERY_EXECUTION_INFO = "x-ms-cosmos-query-execution-info";
// Batch operations
public static final String IS_BATCH_ATOMIC = "x-ms-cosmos-batch-atomic";
public static final String IS_BATCH_ORDERED = "x-ms-cosmos-batch-ordered";
public static final String IS_BATCH_REQUEST = "x-ms-cosmos-is-batch-request";
public static final String SHOULD_BATCH_CONTINUE_ON_ERROR = "x-ms-cosmos-batch-continue-on-error";
// Client telemetry header
public static final String DATABASE_ACCOUNT_NAME = "x-ms-databaseaccount-name";
public static final String ENVIRONMENT_NAME = "x-ms-environment-name";
// Backend request duration header
public static final String BACKEND_REQUEST_DURATION_MILLISECONDS = "x-ms-request-duration-ms";
// Dedicated Gateway Headers
public static final String DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS = "x-ms-dedicatedgateway-max-age";
public static final String DEDICATED_GATEWAY_PER_REQUEST_BYPASS_CACHE = "x-ms-dedicatedgateway-bypass-cache";
// Client Encryption Headers
public static final String IS_CLIENT_ENCRYPTED_HEADER = "x-ms-cosmos-is-client-encrypted";
public static final String INTENDED_COLLECTION_RID_HEADER = "x-ms-cosmos-intended-collection-rid";
// SDK supported capacities headers
public static final String SDK_SUPPORTED_CAPABILITIES = "x-ms-cosmos-sdk-supportedcapabilities";
// Priority Level for throttling
public static final String PRIORITY_LEVEL = "x-ms-cosmos-priority-level";
}
public static class A_IMHeaderValues {
public static final String INCREMENTAL_FEED = "Incremental Feed";
public static final String FULL_FIDELITY_FEED = "Full-Fidelity Feed";
}
public static class SDKSupportedCapabilities {
private static final long NONE = 0; // 0
private static final long PARTITION_MERGE = 1; // 1 << 0
private static final long CHANGE_FEED_WITH_START_TIME_POST_MERGE = 2; // 1 << 1
public static final String SUPPORTED_CAPABILITIES;
public static final String SUPPORTED_CAPABILITIES_NONE;
static {
SUPPORTED_CAPABILITIES = String.valueOf(PARTITION_MERGE);
SUPPORTED_CAPABILITIES_NONE = String.valueOf(NONE);
}
}
public static class Versions {
public static final String CURRENT_VERSION = "2020-07-15";
public static final String QUERY_VERSION = "1.0";
public static final String AZURE_COSMOS_PROPERTIES_FILE_NAME = "azure-cosmos.properties";
private static boolean SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA = false;
public static final String SDK_NAME = "cosmos";
private static final String SDK_VERSION_RAW = CoreUtils.getProperties(AZURE_COSMOS_PROPERTIES_FILE_NAME).get("version");
private static final AtomicReference<String> SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED =
new AtomicReference<String>(null);
public static String getSdkVersion() {
return SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA ?
getSdkVersionWithSnapshotInsteadOfBeta() : SDK_VERSION_RAW;
}
public static void useSnapshotInsteadOfBeta() {
SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA = true;
}
public static void resetSnapshotInsteadOfBeta() {
SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA = false;
}
private static String getSdkVersionWithSnapshotInsteadOfBeta() {
String snapshot = SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED.get();
if (snapshot != null) {
return snapshot;
}
String newPolishedVersion = SDK_VERSION_RAW.replaceAll("(?i)beta", "snapshot");
if (SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED.compareAndSet(null, newPolishedVersion)) {
return newPolishedVersion;
} else {
return SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED.get();
}
}
}
public static class ChangeFeedWireFormatVersions {
public static final String SEPARATE_METADATA_WITH_CRTS = "2021-09-15";
}
public static class StatusCodes {
public static final int OK = 200;
public static final int CREATED = 201;
public static final int NO_CONTENT = 204;
public static final int NOT_MODIFIED = 304;
// Success
public static final int MINIMUM_SUCCESS_STATUSCODE = 200;
public static final int MAXIMUM_SUCCESS_STATUSCODE = 299;
// Client error
public static final int MINIMUM_STATUSCODE_AS_ERROR_GATEWAY = 400;
public static final int BADREQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int FORBIDDEN = 403;
public static final int NOTFOUND = 404;
public static final int METHOD_NOT_ALLOWED = 405;
public static final int REQUEST_TIMEOUT = 408;
public static final int CONFLICT = 409;
public static final int GONE = 410;
public static final int PRECONDITION_FAILED = 412;
public static final int REQUEST_ENTITY_TOO_LARGE = 413;
public static final int LOCKED = 423;
public static final int TOO_MANY_REQUESTS = 429;
public static final int RETRY_WITH = 449;
public static final int SERVICE_UNAVAILABLE = 503;
public static final int INTERNAL_SERVER_ERROR = 500;
}
public static class SubStatusCodes {
// Unknown SubStatus Code
public static final int UNKNOWN = 0;
// 400: Bad Request substatus
public static final int PARTITION_KEY_MISMATCH = 1001;
public static final int CROSS_PARTITION_QUERY_NOT_SERVABLE = 1004;
// 410: StatusCodeType_Gone: substatus
// Merge or split share the same status code and subStatusCode
public static final int NAME_CACHE_IS_STALE = 1000;
public static final int PARTITION_KEY_RANGE_GONE = 1002;
public static final int COMPLETING_SPLIT_OR_MERGE = 1007;
public static final int COMPLETING_PARTITION_MIGRATION = 1008;
// 403: Forbidden substatus
public static final int FORBIDDEN_WRITEFORBIDDEN = 3;
public static final int DATABASE_ACCOUNT_NOTFOUND = 1008;
// 404: LSN in session token is higher
public static final int READ_SESSION_NOT_AVAILABLE = 1002;
public static final int OWNER_RESOURCE_NOT_EXISTS = 1003;
public static final int INCORRECT_CONTAINER_RID_SUB_STATUS = 1024;
// SDK Codes - Java specific clinet-side substatus codes
// IMPORTANT - whenever possible rather use consistency substaus codes that .Net SDK also uses
// 20000-20999 - consistent client side sdk status codes
// 21000-21999 - consistent service sdk status codes
// Client generated gateway network error substatus
public static final int GATEWAY_ENDPOINT_UNAVAILABLE = 10001;
// Client generated gateway network error on ReadTimeoutException
public static final int GATEWAY_ENDPOINT_READ_TIMEOUT = 10002;
// Client generated request rate too large exception
public static final int THROUGHPUT_CONTROL_REQUEST_RATE_TOO_LARGE = 10003;
// Client generated offer not configured exception
public static final int OFFER_NOT_CONFIGURED = 10004;
// Client generated request rate too large exception
public static final int THROUGHPUT_CONTROL_BULK_REQUEST_RATE_TOO_LARGE = 10005;
public static final int USER_REQUEST_RATE_TOO_LARGE = 3200;
//SDK Codes(Client)
// IMPORTANT - whenever possible use consistency substatus codes that .Net SDK also uses
public static final int TRANSPORT_GENERATED_410 = 20001;
public static final int TIMEOUT_GENERATED_410 = 20002;
// Client generated operation timeout exception
public static final int CLIENT_OPERATION_TIMEOUT = 20008;
// IMPORTANT - below sub status codes have no corresponding .Net
// version, because they are only applicable in Java
public static final int NEGATIVE_TIMEOUT_PROVIDED = 20901; // .Net has different cancellation concept
// SubStatusCodes for Client generated 500
public static final int MISSING_PARTITION_KEY_RANGE_ID_IN_CONTEXT = 20902;
public static final int INVALID_REGIONS_IN_SESSION_TOKEN = 20903;
public static final int NON_PARTITIONED_RESOURCES = 20904;
public static final int PARTITION_KEY_IS_NULL = 20905;
public static final int UNKNOWN_AUTHORIZATION_TOKEN_KIND= 20906;
public static final int RECREATE_REQUEST_ON_HTTP_CLIENT = 20907;
public static final int INVALID_BACKEND_RESPONSE = 20908;
public static final int UNKNOWN_QUORUM_RESULT = 20909;
public static final int INVALID_RESULT = 20910;
//SDK Codes (Server)
// IMPORTANT - whenever possible use consistency substatus codes that .Net SDK also uses
public static final int NAME_CACHE_IS_STALE_EXCEEDED_RETRY_LIMIT = 21001;
public static final int PARTITION_KEY_RANGE_GONE_EXCEEDED_RETRY_LIMIT = 21002;
public static final int COMPLETING_SPLIT_EXCEEDED_RETRY_LIMIT = 21003;
public static final int COMPLETING_PARTITION_MIGRATION_EXCEEDED_RETRY_LIMIT = 21004;
public static final int SERVER_GENERATED_410 = 21005;
public static final int GLOBAL_STRONG_WRITE_BARRIER_NOT_MET = 21006;
public static final int READ_QUORUM_NOT_MET = 21007;
public static final int SERVER_GENERATED_503 = 21008;
public static final int NO_VALID_STORE_RESPONSE = 21009;
public static final int SERVER_GENERATED_408 = 21010;
}
public static class HeaderValues {
public static final String NO_CACHE = "no-cache";
public static final String PREFER_RETURN_MINIMAL = "return=minimal";
public static final String IF_NONE_MATCH_ALL = "*";
}
}
| Azure/azure-sdk-for-java | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HttpConstants.java | 8,077 | // Client telemetry header | line_comment | nl | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;
import com.azure.core.util.CoreUtils;
import java.util.concurrent.atomic.AtomicReference;
/**
* Used internally. HTTP constants in the Azure Cosmos DB database service Java
* SDK.
*/
public class HttpConstants {
public static class HttpMethods {
public static final String GET = "GET";
public static final String POST = "POST";
public static final String PUT = "PUT";
public static final String DELETE = "DELETE";
public static final String HEAD = "HEAD";
public static final String OPTIONS = "OPTIONS";
public static final String PATCH = "PATCH";
}
public static class QueryStrings {
public static final String URL = "$resolveFor";
public static final String FILTER = "$filter";
public static final String PARTITION_KEY_RANGE_IDS = "$partitionKeyRangeIds";
}
public static class HttpHeaders {
public static final String AUTHORIZATION = "authorization";
public static final String E_TAG = "etag";
public static final String METHOD_OVERRIDE = "X-HTTP-Method";
public static final String SLUG = "Slug";
public static final String CONTENT_TYPE = "Content-Type";
public static final String LAST_MODIFIED = "Last-Modified";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String CHARACTER_SET = "CharacterSet";
public static final String USER_AGENT = "User-Agent";
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String IF_MATCH = "If-Match";
public static final String IF_NONE_MATCH = "If-None-Match";
public static final String CONTENT_LENGTH = "Content-Length";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String KEEP_ALIVE = "Keep-Alive";
public static final String CONNECTION = "Connection";
public static final String CACHE_CONTROL = "Cache-Control";
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
public static final String CONTENT_LANGUAGE = "Content-Language";
public static final String CONTENT_LOCATION = "Content-Location";
public static final String CONTENT_MD5 = "Content-Md5";
public static final String CONTENT_RANGE = "Content-RANGE";
public static final String ACCEPT = "Accept";
public static final String ACCEPT_CHARSET = "Accept-Charset";
public static final String ACCEPT_LANGUAGE = "Accept-Language";
public static final String IF_RANGE = "If-RANGE";
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
public static final String MAX_FORWARDS = "Max-Forwards";
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
public static final String ACCEPT_RANGES = "Accept-Ranges";
public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";
public static final String RETRY_AFTER = "Retry-After";
public static final String SET_COOKIE = "Set-Cookie";
public static final String WWW_AUTHENTICATE = "Www-Authenticate";
public static final String ORIGIN = "Origin";
public static final String HOST = "Host";
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
public static final String KEY_VALUE_ENCODING_FORMAT = "application/x-www-form-urlencoded";
public static final String WRAP_ASSERTION_FORMAT = "wrap_assertion_format";
public static final String WRAP_ASSERTION = "wrap_assertion";
public static final String WRAP_SCOPE = "wrap_scope";
public static final String SIMPLE_TOKEN = "SWT";
public static final String HTTP_DATE = "date";
public static final String PREFER = "Prefer";
public static final String LOCATION = "Location";
public static final String REFERER = "referer";
// Query
public static final String QUERY = "x-ms-documentdb-query";
public static final String IS_QUERY = "x-ms-documentdb-isquery";
public static final String ENABLE_CROSS_PARTITION_QUERY = "x-ms-documentdb-query-enablecrosspartition";
public static final String PARALLELIZE_CROSS_PARTITION_QUERY = "x-ms-documentdb-query-parallelizecrosspartitionquery";
public static final String IS_QUERY_PLAN_REQUEST = "x-ms-cosmos-is-query-plan-request";
public static final String SUPPORTED_QUERY_FEATURES = "x-ms-cosmos-supported-query-features";
public static final String QUERY_VERSION = "x-ms-cosmos-query-version";
public static final String CORRELATED_ACTIVITY_ID = "x-ms-cosmos-correlated-activityid";
// Our custom DocDB headers
public static final String CONTINUATION = "x-ms-continuation";
public static final String PAGE_SIZE = "x-ms-max-item-count";
public static final String RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB = "x-ms-documentdb-responsecontinuationtokenlimitinkb";
// Request sender generated. Simply echoed by backend.
public static final String ACTIVITY_ID = "x-ms-activity-id";
public static final String PRE_TRIGGER_INCLUDE = "x-ms-documentdb-pre-trigger-include";
public static final String PRE_TRIGGER_EXCLUDE = "x-ms-documentdb-pre-trigger-exclude";
public static final String POST_TRIGGER_INCLUDE = "x-ms-documentdb-post-trigger-include";
public static final String POST_TRIGGER_EXCLUDE = "x-ms-documentdb-post-trigger-exclude";
public static final String INDEXING_DIRECTIVE = "x-ms-indexing-directive";
public static final String SESSION_TOKEN = "x-ms-session-token";
public static final String CONSISTENCY_LEVEL = "x-ms-consistency-level";
public static final String X_DATE = "x-ms-date";
public static final String COLLECTION_PARTITION_INFO = "x-ms-collection-partition-info";
public static final String COLLECTION_SERVICE_INFO = "x-ms-collection-service-info";
public static final String RETRY_AFTER_IN_MILLISECONDS = "x-ms-retry-after-ms";
public static final String IS_FEED_UNFILTERED = "x-ms-is-feed-unfiltered";
public static final String RESOURCE_TOKEN_EXPIRY = "x-ms-documentdb-expiry-seconds";
public static final String ENABLE_SCAN_IN_QUERY = "x-ms-documentdb-query-enable-scan";
public static final String EMIT_VERBOSE_TRACES_IN_QUERY = "x-ms-documentdb-query-emit-traces";
// target lsn for head requests
public static final String TARGET_LSN = "x-ms-target-lsn";
public static final String TARGET_GLOBAL_COMMITTED_LSN = "x-ms-target-global-committed-lsn";
// Request validation
public static final String REQUEST_VALIDATION_FAILURE = "x-ms-request-validation-failure";
public static final String WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH = "x-ms-write-request-trigger-refresh";
// Quota Info
public static final String MAX_RESOURCE_QUOTA = "x-ms-resource-quota";
public static final String CURRENT_RESOURCE_QUOTA_USAGE = "x-ms-resource-usage";
public static final String MAX_MEDIA_STORAGE_USAGE_IN_MB = "x-ms-max-media-storage-usage-mb";
// Usage Info
public static final String REQUEST_CHARGE = "x-ms-request-charge";
public static final String CURRENT_MEDIA_STORAGE_USAGE_IN_MB = "x-ms-media-storage-usage-mb";
public static final String DATABASE_ACCOUNT_CONSUMED_DOCUMENT_STORAGE_IN_MB = "x-ms-databaseaccount-consumed-mb";
public static final String DATABASE_ACCOUNT_RESERVED_DOCUMENT_STORAGE_IN_MB = "x-ms-databaseaccount-reserved-mb";
public static final String DATABASE_ACCOUNT_PROVISIONED_DOCUMENT_STORAGE_IN_MB = "x-ms-databaseaccount-provisioned-mb";
// Address related headers.
public static final String FORCE_REFRESH = "x-ms-force-refresh";
public static final String FORCE_COLLECTION_ROUTING_MAP_REFRESH = "x-ms-collectionroutingmap-refresh";
public static final String ITEM_COUNT = "x-ms-item-count";
public static final String NEW_RESOURCE_ID = "x-ms-new-resource-id";
public static final String USE_MASTER_COLLECTION_RESOLVER = "x-ms-use-master-collection-resolver";
// Admin Headers
public static final String FULL_UPGRADE = "x-ms-force-full-upgrade";
public static final String ONLY_UPGRADE_SYSTEM_APPLICATIONS = "x-ms-only-upgrade-system-applications";
public static final String ONLY_UPGRADE_NON_SYSTEM_APPLICATIONS = "x-ms-only-upgrade-non-system-applications";
public static final String UPGRADE_FABRIC_RING_CODE_AND_CONFIG = "x-ms-upgrade-fabric-code-config";
public static final String IGNORE_IN_PROGRESS_UPGRADE = "x-ms-ignore-inprogress-upgrade";
public static final String UPGRADE_VERIFICATION_KIND = "x-ms-upgrade-verification-kind";
public static final String IS_CANARY = "x-ms-iscanary";
public static final String FORCE_DELETE = "x-ms-force-delete";
// Version headers and values
public static final String VERSION = "x-ms-version";
public static final String SCHEMA_VERSION = "x-ms-schemaversion";
public static final String SERVER_VERSION = "x-ms-serviceversion";
public static final String GATEWAY_VERSION = "x-ms-gatewayversion";
// RDFE Resource Provider headers
public static final String OCP_RESOURCE_PROVIDER_REGISTERED_URI = "ocp-resourceprovider-registered-uri";
// For Document service management operations only. This is in
// essence a 'handle' to (long running) operations.
public static final String REQUEST_ID = "x-ms-request-id";
// Object returning this determines what constitutes state and what
// last state change means. For replica, it is the last role change.
public static final String LAST_STATE_CHANGE_UTC = "x-ms-last-state-change-utc";
// CSM specific headers
// Client-request-id: Optional caller-specified request ID, in the form
// of a GUID
public static final String CLIENT_REQUEST_ID = "x-ms-client-request-id";
// Offer header
public static final String OFFER_TYPE = "x-ms-offer-type";
public static final String OFFER_THROUGHPUT = "x-ms-offer-throughput";
public static final String OFFER_IS_RU_PER_MINUTE_THROUGHPUT_ENABLED = "x-ms-offer-is-ru-per-minute-throughput-enabled";
public static final String OFFER_MIN_THROUGHPUT = "x-ms-cosmos-min-throughput";
public static final String OFFER_AUTOPILOT_SETTINGS = "x-ms-cosmos-offer-autopilot-settings";
public static final String OFFER_REPLACE_PENDING = "x-ms-offer-replace-pending";
// Upsert header
public static final String IS_UPSERT = "x-ms-documentdb-is-upsert";
// Index progress headers
public static final String INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress";
public static final String LAZY_INDEXING_PROGRESS = "x-ms-documentdb-collection-lazy-indexing-progress";
// Owner name
public static final String OWNER_FULL_NAME = "x-ms-alt-content-path";
// Owner ID used for name based request in session token.
public static final String OWNER_ID = "x-ms-content-path";
// Partition headers
public static final String PARTITION_KEY = "x-ms-documentdb-partitionkey";
public static final String PARTITION_KEY_RANGE_ID = "x-ms-documentdb-partitionkeyrangeid";
// Error response sub status code
public static final String SUB_STATUS = "x-ms-substatus";
public static final String LSN = "lsn";
// CUSTOM DocDB JavaScript logging headers
public static final String SCRIPT_ENABLE_LOGGING = "x-ms-documentdb-script-enable-logging";
public static final String SCRIPT_LOG_RESULTS = "x-ms-documentdb-script-log-results";
// Collection quota
public static final String POPULATE_QUOTA_INFO = "x-ms-documentdb-populatequotainfo";
// ChangeFeed
public static final String A_IM = "A-IM";
public static final String ALLOW_TENTATIVE_WRITES = "x-ms-cosmos-allow-tentative-writes";
public static final String CHANGE_FEED_WIRE_FORMAT_VERSION = "x-ms-cosmos-changefeed-wire-format-version";
// These properties were added to support RNTBD and they've been added here to
// reduce merge conflicts
public static final String CAN_CHARGE = "x-ms-cancharge";
public static final String CAN_OFFER_REPLACE_COMPLETE = "x-ms-can-offer-replace-complete";
public static final String CAN_THROTTLE = "x-ms-canthrottle";
public static final String CLIENT_RETRY_ATTEMPT_COUNT = "x-ms-client-retry-attempt-count";
public static final String COLLECTION_INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress";
public static final String COLLECTION_LAZY_INDEXING_PROGRESS = "x-ms-documentdb-collection-lazy-indexing-progress";
public static final String COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER = "x-ms-collection-security-identifier";
public static final String CONTENT_SERIALIZATION_FORMAT = "x-ms-documentdb-content-serialization-format";
public static final String DISABLE_RNTBD_CHANNEL = "x-ms-disable-rntbd-channel";
public static final String DISABLE_RU_PER_MINUTE_USAGE = "x-ms-documentdb-disable-ru-per-minute-usage";
public static final String ENABLE_LOGGING = "x-ms-documentdb-script-enable-logging";
public static final String ENABLE_LOW_PRECISION_ORDER_BY = "x-ms-documentdb-query-enable-low-precision-order-by";
public static final String END_EPK = "x-ms-end-epk";
public static final String END_ID = "x-ms-end-id";
public static final String ENUMERATION_DIRECTION = "x-ms-enumeration-direction";
public static final String FILTER_BY_SCHEMA_RESOURCE_ID = "x-ms-documentdb-filterby-schema-rid";
public static final String FORCE_QUERY_SCAN = "x-ms-documentdb-force-query-scan";
public static final String GATEWAY_SIGNATURE = "x-ms-gateway-signature";
public static final String IS_AUTO_SCALE_REQUEST = "x-ms-is-auto-scale";
public static final String IS_READ_ONLY_SCRIPT = "x-ms-is-readonly-script";
public static final String LOG_RESULTS = "x-ms-documentdb-script-log-results";
public static final String MIGRATE_COLLECTION_DIRECTIVE = "x-ms-migratecollection-directive";
public static final String POPULATE_COLLECTION_THROUGHPUT_INFO = "x-ms-documentdb-populatecollectionthroughputinfo";
public static final String POPULATE_PARTITION_STATISTICS = "x-ms-documentdb-populatepartitionstatistics";
public static final String POPULATE_QUERY_METRICS = "x-ms-documentdb-populatequerymetrics";
public static final String PROFILE_REQUEST = "x-ms-profile-request";
public static final String READ_FEED_KEY_TYPE = "x-ms-read-key-type";
public static final String REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST = "x-ms-remaining-time-in-ms-on-client";
public static final String RESTORE_METADATA_FILTER = "x-ms-restore-metadata-filter";
public static final String SHARED_OFFER_THROUGHPUT = "x-ms-cosmos-shared-offer-throughput";
public static final String START_EPK = "x-ms-start-epk";
public static final String START_ID = "x-ms-start-id";
public static final String SUPPORT_SPATIAL_LEGACY_COORDINATES = "x-ms-documentdb-supportspatiallegacycoordinates";
public static final String TRANSPORT_REQUEST_ID = "x-ms-transport-request-id";
public static final String USE_POLYGONS_SMALLER_THAN_AHEMISPHERE = "x-ms-documentdb-usepolygonssmallerthanahemisphere";
public static final String API_TYPE = "x-ms-cosmos-apitype";
public static final String QUERY_METRICS = "x-ms-documentdb-query-metrics";
public static final String POPULATE_INDEX_METRICS = "x-ms-cosmos-populateindexmetrics";
public static final String INDEX_UTILIZATION = "x-ms-cosmos-index-utilization";
public static final String QUERY_EXECUTION_INFO = "x-ms-cosmos-query-execution-info";
// Batch operations
public static final String IS_BATCH_ATOMIC = "x-ms-cosmos-batch-atomic";
public static final String IS_BATCH_ORDERED = "x-ms-cosmos-batch-ordered";
public static final String IS_BATCH_REQUEST = "x-ms-cosmos-is-batch-request";
public static final String SHOULD_BATCH_CONTINUE_ON_ERROR = "x-ms-cosmos-batch-continue-on-error";
// Client telemetry<SUF>
public static final String DATABASE_ACCOUNT_NAME = "x-ms-databaseaccount-name";
public static final String ENVIRONMENT_NAME = "x-ms-environment-name";
// Backend request duration header
public static final String BACKEND_REQUEST_DURATION_MILLISECONDS = "x-ms-request-duration-ms";
// Dedicated Gateway Headers
public static final String DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS = "x-ms-dedicatedgateway-max-age";
public static final String DEDICATED_GATEWAY_PER_REQUEST_BYPASS_CACHE = "x-ms-dedicatedgateway-bypass-cache";
// Client Encryption Headers
public static final String IS_CLIENT_ENCRYPTED_HEADER = "x-ms-cosmos-is-client-encrypted";
public static final String INTENDED_COLLECTION_RID_HEADER = "x-ms-cosmos-intended-collection-rid";
// SDK supported capacities headers
public static final String SDK_SUPPORTED_CAPABILITIES = "x-ms-cosmos-sdk-supportedcapabilities";
// Priority Level for throttling
public static final String PRIORITY_LEVEL = "x-ms-cosmos-priority-level";
}
public static class A_IMHeaderValues {
public static final String INCREMENTAL_FEED = "Incremental Feed";
public static final String FULL_FIDELITY_FEED = "Full-Fidelity Feed";
}
public static class SDKSupportedCapabilities {
private static final long NONE = 0; // 0
private static final long PARTITION_MERGE = 1; // 1 << 0
private static final long CHANGE_FEED_WITH_START_TIME_POST_MERGE = 2; // 1 << 1
public static final String SUPPORTED_CAPABILITIES;
public static final String SUPPORTED_CAPABILITIES_NONE;
static {
SUPPORTED_CAPABILITIES = String.valueOf(PARTITION_MERGE);
SUPPORTED_CAPABILITIES_NONE = String.valueOf(NONE);
}
}
public static class Versions {
public static final String CURRENT_VERSION = "2020-07-15";
public static final String QUERY_VERSION = "1.0";
public static final String AZURE_COSMOS_PROPERTIES_FILE_NAME = "azure-cosmos.properties";
private static boolean SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA = false;
public static final String SDK_NAME = "cosmos";
private static final String SDK_VERSION_RAW = CoreUtils.getProperties(AZURE_COSMOS_PROPERTIES_FILE_NAME).get("version");
private static final AtomicReference<String> SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED =
new AtomicReference<String>(null);
public static String getSdkVersion() {
return SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA ?
getSdkVersionWithSnapshotInsteadOfBeta() : SDK_VERSION_RAW;
}
public static void useSnapshotInsteadOfBeta() {
SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA = true;
}
public static void resetSnapshotInsteadOfBeta() {
SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA = false;
}
private static String getSdkVersionWithSnapshotInsteadOfBeta() {
String snapshot = SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED.get();
if (snapshot != null) {
return snapshot;
}
String newPolishedVersion = SDK_VERSION_RAW.replaceAll("(?i)beta", "snapshot");
if (SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED.compareAndSet(null, newPolishedVersion)) {
return newPolishedVersion;
} else {
return SDK_VERSION_SNAPSHOT_INSTEAD_OF_BETA_CACHED.get();
}
}
}
public static class ChangeFeedWireFormatVersions {
public static final String SEPARATE_METADATA_WITH_CRTS = "2021-09-15";
}
public static class StatusCodes {
public static final int OK = 200;
public static final int CREATED = 201;
public static final int NO_CONTENT = 204;
public static final int NOT_MODIFIED = 304;
// Success
public static final int MINIMUM_SUCCESS_STATUSCODE = 200;
public static final int MAXIMUM_SUCCESS_STATUSCODE = 299;
// Client error
public static final int MINIMUM_STATUSCODE_AS_ERROR_GATEWAY = 400;
public static final int BADREQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int FORBIDDEN = 403;
public static final int NOTFOUND = 404;
public static final int METHOD_NOT_ALLOWED = 405;
public static final int REQUEST_TIMEOUT = 408;
public static final int CONFLICT = 409;
public static final int GONE = 410;
public static final int PRECONDITION_FAILED = 412;
public static final int REQUEST_ENTITY_TOO_LARGE = 413;
public static final int LOCKED = 423;
public static final int TOO_MANY_REQUESTS = 429;
public static final int RETRY_WITH = 449;
public static final int SERVICE_UNAVAILABLE = 503;
public static final int INTERNAL_SERVER_ERROR = 500;
}
public static class SubStatusCodes {
// Unknown SubStatus Code
public static final int UNKNOWN = 0;
// 400: Bad Request substatus
public static final int PARTITION_KEY_MISMATCH = 1001;
public static final int CROSS_PARTITION_QUERY_NOT_SERVABLE = 1004;
// 410: StatusCodeType_Gone: substatus
// Merge or split share the same status code and subStatusCode
public static final int NAME_CACHE_IS_STALE = 1000;
public static final int PARTITION_KEY_RANGE_GONE = 1002;
public static final int COMPLETING_SPLIT_OR_MERGE = 1007;
public static final int COMPLETING_PARTITION_MIGRATION = 1008;
// 403: Forbidden substatus
public static final int FORBIDDEN_WRITEFORBIDDEN = 3;
public static final int DATABASE_ACCOUNT_NOTFOUND = 1008;
// 404: LSN in session token is higher
public static final int READ_SESSION_NOT_AVAILABLE = 1002;
public static final int OWNER_RESOURCE_NOT_EXISTS = 1003;
public static final int INCORRECT_CONTAINER_RID_SUB_STATUS = 1024;
// SDK Codes - Java specific clinet-side substatus codes
// IMPORTANT - whenever possible rather use consistency substaus codes that .Net SDK also uses
// 20000-20999 - consistent client side sdk status codes
// 21000-21999 - consistent service sdk status codes
// Client generated gateway network error substatus
public static final int GATEWAY_ENDPOINT_UNAVAILABLE = 10001;
// Client generated gateway network error on ReadTimeoutException
public static final int GATEWAY_ENDPOINT_READ_TIMEOUT = 10002;
// Client generated request rate too large exception
public static final int THROUGHPUT_CONTROL_REQUEST_RATE_TOO_LARGE = 10003;
// Client generated offer not configured exception
public static final int OFFER_NOT_CONFIGURED = 10004;
// Client generated request rate too large exception
public static final int THROUGHPUT_CONTROL_BULK_REQUEST_RATE_TOO_LARGE = 10005;
public static final int USER_REQUEST_RATE_TOO_LARGE = 3200;
//SDK Codes(Client)
// IMPORTANT - whenever possible use consistency substatus codes that .Net SDK also uses
public static final int TRANSPORT_GENERATED_410 = 20001;
public static final int TIMEOUT_GENERATED_410 = 20002;
// Client generated operation timeout exception
public static final int CLIENT_OPERATION_TIMEOUT = 20008;
// IMPORTANT - below sub status codes have no corresponding .Net
// version, because they are only applicable in Java
public static final int NEGATIVE_TIMEOUT_PROVIDED = 20901; // .Net has different cancellation concept
// SubStatusCodes for Client generated 500
public static final int MISSING_PARTITION_KEY_RANGE_ID_IN_CONTEXT = 20902;
public static final int INVALID_REGIONS_IN_SESSION_TOKEN = 20903;
public static final int NON_PARTITIONED_RESOURCES = 20904;
public static final int PARTITION_KEY_IS_NULL = 20905;
public static final int UNKNOWN_AUTHORIZATION_TOKEN_KIND= 20906;
public static final int RECREATE_REQUEST_ON_HTTP_CLIENT = 20907;
public static final int INVALID_BACKEND_RESPONSE = 20908;
public static final int UNKNOWN_QUORUM_RESULT = 20909;
public static final int INVALID_RESULT = 20910;
//SDK Codes (Server)
// IMPORTANT - whenever possible use consistency substatus codes that .Net SDK also uses
public static final int NAME_CACHE_IS_STALE_EXCEEDED_RETRY_LIMIT = 21001;
public static final int PARTITION_KEY_RANGE_GONE_EXCEEDED_RETRY_LIMIT = 21002;
public static final int COMPLETING_SPLIT_EXCEEDED_RETRY_LIMIT = 21003;
public static final int COMPLETING_PARTITION_MIGRATION_EXCEEDED_RETRY_LIMIT = 21004;
public static final int SERVER_GENERATED_410 = 21005;
public static final int GLOBAL_STRONG_WRITE_BARRIER_NOT_MET = 21006;
public static final int READ_QUORUM_NOT_MET = 21007;
public static final int SERVER_GENERATED_503 = 21008;
public static final int NO_VALID_STORE_RESPONSE = 21009;
public static final int SERVER_GENERATED_408 = 21010;
}
public static class HeaderValues {
public static final String NO_CACHE = "no-cache";
public static final String PREFER_RETURN_MINIMAL = "return=minimal";
public static final String IF_NONE_MATCH_ALL = "*";
}
}
|
27562_38 | // Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.identity.client;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.microsoft.identity.common.exception.ServiceException;
import com.microsoft.identity.common.internal.cache.ICacheRecord;
import com.microsoft.identity.common.internal.dto.AccountRecord;
import com.microsoft.identity.common.internal.providers.oauth2.IDToken;
import com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache;
import com.microsoft.identity.common.internal.util.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class AccountAdapter {
private static final String TAG = AccountAdapter.class.getSimpleName();
/**
* Abstract class representing a filter for ICacheRecords.
*/
private interface CacheRecordFilter {
List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records);
}
private static class GuestAccountFilter implements CacheRecordFilter {
@Override
public List<ICacheRecord> filter(@NonNull List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
for (final ICacheRecord cacheRecord : records) {
final String acctHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
final String acctLocalAccountId = cacheRecord.getAccount().getLocalAccountId();
if (!acctHomeAccountId.contains(acctLocalAccountId)) {
result.add(cacheRecord);
}
}
return result;
}
}
/**
* A filter for ICacheRecords that filters out home or guest accounts, based on its
* constructor initialization.
*/
private static class HomeAccountFilter implements CacheRecordFilter {
@Override
public List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
for (final ICacheRecord cacheRecord : records) {
final String acctHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
final String acctLocalAccountId = cacheRecord.getAccount().getLocalAccountId();
if (acctHomeAccountId.contains(acctLocalAccountId)) {
result.add(cacheRecord);
}
}
return result;
}
}
/**
* A filter which finds guest accounts which have no corresponding home tenant account.
*/
private static final CacheRecordFilter guestAccountsWithNoHomeTenantAccountFilter = new CacheRecordFilter() {
private boolean hasNoCorrespondingHomeAccount(@NonNull final ICacheRecord guestRecord,
@NonNull final List<ICacheRecord> homeRecords) {
// Init our sought value
final String guestAccountHomeAccountId = guestRecord.getAccount().getHomeAccountId();
// Create a List of home_account_ids from the homeRecords...
final List<String> homeAccountIds = new ArrayList<String>() {{
for (final ICacheRecord cacheRecord : homeRecords) {
add(cacheRecord.getAccount().getHomeAccountId());
}
}};
return !homeAccountIds.contains(guestAccountHomeAccountId);
}
@Override
public List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
// First, get the home accounts....
final List<ICacheRecord> homeRecords =
filterCacheRecords(
records,
new HomeAccountFilter()
);
// Then, get the guest accounts...
final List<ICacheRecord> guestRecords =
filterCacheRecords(
records,
new GuestAccountFilter()
);
// Iterate over the guest accounts and find those which have no associated home account
for (final ICacheRecord guestRecord : guestRecords) {
if (hasNoCorrespondingHomeAccount(guestRecord, homeRecords)) {
result.add(guestRecord);
}
}
return result;
}
};
/**
* For a supplied List of ICacheRecords, create each root IAccount based on the home
* account and then add child-nodes based on any authorized tenants.
*
* @param allCacheRecords
* @return
*/
@NonNull
static List<IAccount> adapt(@NonNull final List<ICacheRecord> allCacheRecords) {
// First, get all of the ICacheRecords for home accounts...
final List<ICacheRecord> homeCacheRecords = filterCacheRecords(
allCacheRecords,
new HomeAccountFilter()
);
// Then, get all of the guest accounts...
// Note that the guestCacheRecordsWithNoHomeAccount (see below) will be *removed* from this
// List.
final List<ICacheRecord> guestCacheRecords = filterCacheRecords(
allCacheRecords,
new GuestAccountFilter()
);
// Get the guest cache records which have no homeAccount
final List<ICacheRecord> guestCacheRecordsWithNoHomeAccount = filterCacheRecords(
allCacheRecords,
guestAccountsWithNoHomeTenantAccountFilter
);
// Remove the guest records that have no corresponding home account from the complete list of
// guest records...
guestCacheRecords.removeAll(guestCacheRecordsWithNoHomeAccount);
final List<IAccount> rootAccounts = createRootAccounts(homeCacheRecords);
appendChildren(rootAccounts, guestCacheRecords);
rootAccounts.addAll(
createIAccountsForGuestsNotSignedIntoHomeTenant(guestCacheRecordsWithNoHomeAccount)
);
return rootAccounts;
}
@NonNull
private static List<IAccount> createIAccountsForGuestsNotSignedIntoHomeTenant(
@NonNull final List<ICacheRecord> guestCacheRecords) {
// First, bucket the records by homeAccountId to create affinities
final Map<String, List<ICacheRecord>> bucketedRecords = new HashMap<>();
for (final ICacheRecord cacheRecord : guestCacheRecords) {
final String cacheRecordHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
// Initialize the multi-map
if (null == bucketedRecords.get(cacheRecordHomeAccountId)) {
bucketedRecords.put(cacheRecordHomeAccountId, new ArrayList<ICacheRecord>());
}
// Add the record to the multi-map
bucketedRecords.get(cacheRecordHomeAccountId).add(cacheRecord);
}
// Declare our result holder...
final List<IAccount> result = new ArrayList<>();
// Now that all of the tokens have been bucketed by an account affinity
// box those into a 'rootless' IAccount
for (final Map.Entry<String, List<ICacheRecord>> entry : bucketedRecords.entrySet()) {
// Create our empty root...
final MultiTenantAccount emptyRoot = new MultiTenantAccount(
null,
null // home tenant IdToken.... doesn't exist!
);
// Set the home oid & home tid of the root, even though we don't have the IdToken...
// hooray for client_info
emptyRoot.setId(StringUtil.getTenantInfo(entry.getKey()).first);
emptyRoot.setTenantId(StringUtil.getTenantInfo(entry.getKey()).second);
emptyRoot.setEnvironment( // Look ahead into our CacheRecords to determine the environment
entry
.getValue()
.get(0)
.getAccount()
.getEnvironment()
);
// Create the Map of TenantProfiles to set...
final Map<String, ITenantProfile> tenantProfileMap = new HashMap<>();
for (final ICacheRecord cacheRecord : entry.getValue()) {
final String tenantId = cacheRecord.getAccount().getRealm();
final TenantProfile profile = new TenantProfile(
// Intentionally do NOT supply the client info here.
// If client info is present, getId() will return the home tenant OID
// instead of the OID from the guest tenant.
null,
getIdToken(cacheRecord)
);
tenantProfileMap.put(tenantId, profile);
}
emptyRoot.setTenantProfiles(tenantProfileMap);
result.add(emptyRoot);
}
return result;
}
private static void appendChildren(@NonNull final List<IAccount> rootAccounts,
@NonNull final List<ICacheRecord> guestCacheRecords) {
// Iterate over the roots, adding the children as we go...
for (final IAccount account : rootAccounts) {
// Iterate over the potential children, adding them if they match
final Map<String, ITenantProfile> tenantProfiles = new HashMap<>();
for (final ICacheRecord guestRecord : guestCacheRecords) {
final String guestRecordHomeAccountId = guestRecord.getAccount().getHomeAccountId();
if (guestRecordHomeAccountId.contains(account.getId())) {
final TenantProfile profile = new TenantProfile(
// Intentionally do NOT supply the client info here.
// If client info is present, getId() will return the home tenant OID
// instead of the OID from the guest tenant.
null,
getIdToken(guestRecord)
);
profile.setEnvironment(guestRecord.getAccount().getEnvironment());
tenantProfiles.put(guestRecord.getAccount().getRealm(), profile);
}
}
// Cast the root account for initialization...
final MultiTenantAccount multiTenantAccount = (MultiTenantAccount) account;
multiTenantAccount.setTenantProfiles(tenantProfiles);
}
}
@NonNull
private static List<IAccount> createRootAccounts(
@NonNull final List<ICacheRecord> homeCacheRecords) {
final List<IAccount> result = new ArrayList<>();
for (ICacheRecord homeCacheRecord : homeCacheRecords) {
// Each IAccount will be initialized as a MultiTenantAccount whether it really is or not...
// This allows us to cast the results however the caller sees fit...
final IAccount rootAccount;
rootAccount = new MultiTenantAccount(
// Because this is a home account, we'll supply the client info
// the uid value is the "id" of the account.
// For B2C, this value will contain the policy name appended to the OID.
homeCacheRecord.getAccount().getClientInfo(),
getIdToken(homeCacheRecord)
);
((MultiTenantAccount) rootAccount).setHomeAccountId(homeCacheRecord.getAccount().getHomeAccountId());
// Set the tenant_id
((MultiTenantAccount) rootAccount).setTenantId(
StringUtil.getTenantInfo(
homeCacheRecord
.getAccount()
.getHomeAccountId()
).second
);
// Set the environment...
((MultiTenantAccount) rootAccount).setEnvironment(
homeCacheRecord
.getAccount()
.getEnvironment()
);
result.add(rootAccount);
}
return result;
}
@Nullable
private static IDToken getIdToken(@NonNull final ICacheRecord cacheRecord) {
final String rawIdToken;
if (null != cacheRecord.getIdToken()) {
rawIdToken = cacheRecord.getIdToken().getSecret();
} else if (null != cacheRecord.getV1IdToken()) {
rawIdToken = cacheRecord.getV1IdToken().getSecret();
} else {
// We have no id_token for this account
return null;
}
try {
return new IDToken(rawIdToken);
} catch (ServiceException e) {
// This should never happen - the IDToken was verified when it was originally
// returned from the service and saved.
throw new IllegalStateException("Failed to restore IdToken");
}
}
/**
* Filters ICacheRecords based on the criteria specified by the {@link CacheRecordFilter}.
* Results may be empty, but never null.
*
* @param allCacheRecords The ICacheRecords to inspect.
* @param filter The CacheRecordFilter to consult.
* @return A List of ICacheRecords matching the supplied filter criteria.
*/
@NonNull
private static List<ICacheRecord> filterCacheRecords(
@NonNull final List<ICacheRecord> allCacheRecords,
@NonNull final CacheRecordFilter filter) {
return filter.filter(allCacheRecords);
}
@Nullable
static AccountRecord getAccountInternal(@NonNull final String clientId,
@NonNull OAuth2TokenCache oAuth2TokenCache,
@NonNull final String homeAccountIdentifier,
@Nullable final String realm) {
final AccountRecord accountToReturn;
if (!StringUtil.isEmpty(homeAccountIdentifier)) {
accountToReturn = oAuth2TokenCache.getAccount(
null, // * wildcard
clientId,
homeAccountIdentifier,
realm
);
} else {
com.microsoft.identity.common.internal.logging.Logger.warn(
TAG,
"homeAccountIdentifier was null or empty -- invalid criteria"
);
accountToReturn = null;
}
return accountToReturn;
}
}
| AzureAD/microsoft-authentication-library-for-android | msal/src/main/java/com/microsoft/identity/client/AccountAdapter.java | 3,816 | // home tenant IdToken.... doesn't exist! | line_comment | nl | // Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.identity.client;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.microsoft.identity.common.exception.ServiceException;
import com.microsoft.identity.common.internal.cache.ICacheRecord;
import com.microsoft.identity.common.internal.dto.AccountRecord;
import com.microsoft.identity.common.internal.providers.oauth2.IDToken;
import com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache;
import com.microsoft.identity.common.internal.util.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class AccountAdapter {
private static final String TAG = AccountAdapter.class.getSimpleName();
/**
* Abstract class representing a filter for ICacheRecords.
*/
private interface CacheRecordFilter {
List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records);
}
private static class GuestAccountFilter implements CacheRecordFilter {
@Override
public List<ICacheRecord> filter(@NonNull List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
for (final ICacheRecord cacheRecord : records) {
final String acctHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
final String acctLocalAccountId = cacheRecord.getAccount().getLocalAccountId();
if (!acctHomeAccountId.contains(acctLocalAccountId)) {
result.add(cacheRecord);
}
}
return result;
}
}
/**
* A filter for ICacheRecords that filters out home or guest accounts, based on its
* constructor initialization.
*/
private static class HomeAccountFilter implements CacheRecordFilter {
@Override
public List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
for (final ICacheRecord cacheRecord : records) {
final String acctHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
final String acctLocalAccountId = cacheRecord.getAccount().getLocalAccountId();
if (acctHomeAccountId.contains(acctLocalAccountId)) {
result.add(cacheRecord);
}
}
return result;
}
}
/**
* A filter which finds guest accounts which have no corresponding home tenant account.
*/
private static final CacheRecordFilter guestAccountsWithNoHomeTenantAccountFilter = new CacheRecordFilter() {
private boolean hasNoCorrespondingHomeAccount(@NonNull final ICacheRecord guestRecord,
@NonNull final List<ICacheRecord> homeRecords) {
// Init our sought value
final String guestAccountHomeAccountId = guestRecord.getAccount().getHomeAccountId();
// Create a List of home_account_ids from the homeRecords...
final List<String> homeAccountIds = new ArrayList<String>() {{
for (final ICacheRecord cacheRecord : homeRecords) {
add(cacheRecord.getAccount().getHomeAccountId());
}
}};
return !homeAccountIds.contains(guestAccountHomeAccountId);
}
@Override
public List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
// First, get the home accounts....
final List<ICacheRecord> homeRecords =
filterCacheRecords(
records,
new HomeAccountFilter()
);
// Then, get the guest accounts...
final List<ICacheRecord> guestRecords =
filterCacheRecords(
records,
new GuestAccountFilter()
);
// Iterate over the guest accounts and find those which have no associated home account
for (final ICacheRecord guestRecord : guestRecords) {
if (hasNoCorrespondingHomeAccount(guestRecord, homeRecords)) {
result.add(guestRecord);
}
}
return result;
}
};
/**
* For a supplied List of ICacheRecords, create each root IAccount based on the home
* account and then add child-nodes based on any authorized tenants.
*
* @param allCacheRecords
* @return
*/
@NonNull
static List<IAccount> adapt(@NonNull final List<ICacheRecord> allCacheRecords) {
// First, get all of the ICacheRecords for home accounts...
final List<ICacheRecord> homeCacheRecords = filterCacheRecords(
allCacheRecords,
new HomeAccountFilter()
);
// Then, get all of the guest accounts...
// Note that the guestCacheRecordsWithNoHomeAccount (see below) will be *removed* from this
// List.
final List<ICacheRecord> guestCacheRecords = filterCacheRecords(
allCacheRecords,
new GuestAccountFilter()
);
// Get the guest cache records which have no homeAccount
final List<ICacheRecord> guestCacheRecordsWithNoHomeAccount = filterCacheRecords(
allCacheRecords,
guestAccountsWithNoHomeTenantAccountFilter
);
// Remove the guest records that have no corresponding home account from the complete list of
// guest records...
guestCacheRecords.removeAll(guestCacheRecordsWithNoHomeAccount);
final List<IAccount> rootAccounts = createRootAccounts(homeCacheRecords);
appendChildren(rootAccounts, guestCacheRecords);
rootAccounts.addAll(
createIAccountsForGuestsNotSignedIntoHomeTenant(guestCacheRecordsWithNoHomeAccount)
);
return rootAccounts;
}
@NonNull
private static List<IAccount> createIAccountsForGuestsNotSignedIntoHomeTenant(
@NonNull final List<ICacheRecord> guestCacheRecords) {
// First, bucket the records by homeAccountId to create affinities
final Map<String, List<ICacheRecord>> bucketedRecords = new HashMap<>();
for (final ICacheRecord cacheRecord : guestCacheRecords) {
final String cacheRecordHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
// Initialize the multi-map
if (null == bucketedRecords.get(cacheRecordHomeAccountId)) {
bucketedRecords.put(cacheRecordHomeAccountId, new ArrayList<ICacheRecord>());
}
// Add the record to the multi-map
bucketedRecords.get(cacheRecordHomeAccountId).add(cacheRecord);
}
// Declare our result holder...
final List<IAccount> result = new ArrayList<>();
// Now that all of the tokens have been bucketed by an account affinity
// box those into a 'rootless' IAccount
for (final Map.Entry<String, List<ICacheRecord>> entry : bucketedRecords.entrySet()) {
// Create our empty root...
final MultiTenantAccount emptyRoot = new MultiTenantAccount(
null,
null // home tenant<SUF>
);
// Set the home oid & home tid of the root, even though we don't have the IdToken...
// hooray for client_info
emptyRoot.setId(StringUtil.getTenantInfo(entry.getKey()).first);
emptyRoot.setTenantId(StringUtil.getTenantInfo(entry.getKey()).second);
emptyRoot.setEnvironment( // Look ahead into our CacheRecords to determine the environment
entry
.getValue()
.get(0)
.getAccount()
.getEnvironment()
);
// Create the Map of TenantProfiles to set...
final Map<String, ITenantProfile> tenantProfileMap = new HashMap<>();
for (final ICacheRecord cacheRecord : entry.getValue()) {
final String tenantId = cacheRecord.getAccount().getRealm();
final TenantProfile profile = new TenantProfile(
// Intentionally do NOT supply the client info here.
// If client info is present, getId() will return the home tenant OID
// instead of the OID from the guest tenant.
null,
getIdToken(cacheRecord)
);
tenantProfileMap.put(tenantId, profile);
}
emptyRoot.setTenantProfiles(tenantProfileMap);
result.add(emptyRoot);
}
return result;
}
private static void appendChildren(@NonNull final List<IAccount> rootAccounts,
@NonNull final List<ICacheRecord> guestCacheRecords) {
// Iterate over the roots, adding the children as we go...
for (final IAccount account : rootAccounts) {
// Iterate over the potential children, adding them if they match
final Map<String, ITenantProfile> tenantProfiles = new HashMap<>();
for (final ICacheRecord guestRecord : guestCacheRecords) {
final String guestRecordHomeAccountId = guestRecord.getAccount().getHomeAccountId();
if (guestRecordHomeAccountId.contains(account.getId())) {
final TenantProfile profile = new TenantProfile(
// Intentionally do NOT supply the client info here.
// If client info is present, getId() will return the home tenant OID
// instead of the OID from the guest tenant.
null,
getIdToken(guestRecord)
);
profile.setEnvironment(guestRecord.getAccount().getEnvironment());
tenantProfiles.put(guestRecord.getAccount().getRealm(), profile);
}
}
// Cast the root account for initialization...
final MultiTenantAccount multiTenantAccount = (MultiTenantAccount) account;
multiTenantAccount.setTenantProfiles(tenantProfiles);
}
}
@NonNull
private static List<IAccount> createRootAccounts(
@NonNull final List<ICacheRecord> homeCacheRecords) {
final List<IAccount> result = new ArrayList<>();
for (ICacheRecord homeCacheRecord : homeCacheRecords) {
// Each IAccount will be initialized as a MultiTenantAccount whether it really is or not...
// This allows us to cast the results however the caller sees fit...
final IAccount rootAccount;
rootAccount = new MultiTenantAccount(
// Because this is a home account, we'll supply the client info
// the uid value is the "id" of the account.
// For B2C, this value will contain the policy name appended to the OID.
homeCacheRecord.getAccount().getClientInfo(),
getIdToken(homeCacheRecord)
);
((MultiTenantAccount) rootAccount).setHomeAccountId(homeCacheRecord.getAccount().getHomeAccountId());
// Set the tenant_id
((MultiTenantAccount) rootAccount).setTenantId(
StringUtil.getTenantInfo(
homeCacheRecord
.getAccount()
.getHomeAccountId()
).second
);
// Set the environment...
((MultiTenantAccount) rootAccount).setEnvironment(
homeCacheRecord
.getAccount()
.getEnvironment()
);
result.add(rootAccount);
}
return result;
}
@Nullable
private static IDToken getIdToken(@NonNull final ICacheRecord cacheRecord) {
final String rawIdToken;
if (null != cacheRecord.getIdToken()) {
rawIdToken = cacheRecord.getIdToken().getSecret();
} else if (null != cacheRecord.getV1IdToken()) {
rawIdToken = cacheRecord.getV1IdToken().getSecret();
} else {
// We have no id_token for this account
return null;
}
try {
return new IDToken(rawIdToken);
} catch (ServiceException e) {
// This should never happen - the IDToken was verified when it was originally
// returned from the service and saved.
throw new IllegalStateException("Failed to restore IdToken");
}
}
/**
* Filters ICacheRecords based on the criteria specified by the {@link CacheRecordFilter}.
* Results may be empty, but never null.
*
* @param allCacheRecords The ICacheRecords to inspect.
* @param filter The CacheRecordFilter to consult.
* @return A List of ICacheRecords matching the supplied filter criteria.
*/
@NonNull
private static List<ICacheRecord> filterCacheRecords(
@NonNull final List<ICacheRecord> allCacheRecords,
@NonNull final CacheRecordFilter filter) {
return filter.filter(allCacheRecords);
}
@Nullable
static AccountRecord getAccountInternal(@NonNull final String clientId,
@NonNull OAuth2TokenCache oAuth2TokenCache,
@NonNull final String homeAccountIdentifier,
@Nullable final String realm) {
final AccountRecord accountToReturn;
if (!StringUtil.isEmpty(homeAccountIdentifier)) {
accountToReturn = oAuth2TokenCache.getAccount(
null, // * wildcard
clientId,
homeAccountIdentifier,
realm
);
} else {
com.microsoft.identity.common.internal.logging.Logger.warn(
TAG,
"homeAccountIdentifier was null or empty -- invalid criteria"
);
accountToReturn = null;
}
return accountToReturn;
}
}
|
108554_5 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.catalog.stripes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Geert Plaisier
*/
public class GeoBrabantAction extends DefaultAction {
@Validate(required=false)
private String searchString;
@Validate(required=false)
private String searchType;
@Validate(required=false)
private String uuid;
private List<MapsBean> mapsList;
@DefaultHandler
public Resolution home() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/home.jsp");
}
/* Static pages */
public Resolution overgeobrabant() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/overgeobrabant.jsp");
}
public Resolution diensten() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/diensten.jsp");
}
public Resolution contact() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/contact.jsp");
}
public Resolution kaarten() {
// This JSON should be fetched from a server somewhere
String mapsJson = "[" +
"{ \"class\": \"wat-mag-waar\", \"title\": \"Wat mag waar?\", \"description\": \"Waar ligt dat stukje grond? Zou ik hier mogen bouwen? Vragen die u beantwoord zult zien worden via dit thema. Bekijk welk perceel waar ligt en wat je ermee mag doen.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN01/v1\" }," +
"{ \"class\": \"bekendmakingen\", \"title\": \"Bekendmakingen\", \"description\": \"Via bekendmakingen kunt u zien welke vergunningaanvragen in uw buurt zijn ingediend of verleend zijn. Hierdoor blijft u op de hoogte van de ontwikkelingen bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN02/v1\" }," +
"{ \"class\": \"bereikbaarheid\", \"title\": \"Bereikbaarheid\", \"description\": \"Via dit thema kunt u erachter komen hoe de beriekbaarheid van een bepaald gebied is. Zo vindt u bijvoorbeeld waar de dichtstbijzijnde parkeergarage is, waar u oplaadpalen aantreft en actuele informatie over verkeer en wegwerkzaamheden\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN03/v1\" }," +
"{ \"class\": \"veiligheid\", \"title\": \"Veiligheid\", \"description\": \"In dit thema vindt u informatie over de veiligheid in uw buurt. Waar zit de politie en brandweer, maar ook overstromingsrisico, waterkeringen en de veiligheidsregio staan hier.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN04/v1\" }," +
"{ \"class\": \"zorg\", \"title\": \"Zorg\", \"description\": \"Ziekenhuizen, doktersposten en verzorgingshuizen. Alle data met betrekking tot de (medische) zorg staan in dit thema beschreven.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN05/v1\" }," +
"{ \"class\": \"onderwijs-kinderopvang\", \"title\": \"Onderwijs & Kinderopvang\", \"description\": \"In dit thema vindt u de locatie van alle scholen en kinderopvang.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN06/v1\" }," +
"{ \"class\": \"wijkvoorzieningen\", \"title\": \"Wijkvoorzieningen\", \"description\": \"Waar bij mij in de buurt bevinden zich afvalbakken, hondenuitlaatplaatsen en de speeltuin? Dergelijke wijkvoorzieningen vindt u in dit thema, evenals buurthuizen, winkelcentra, etc.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN07/v1\" }," +
"{ \"class\": \"recreatie\", \"title\": \"Recreatie\", \"description\": \"Waar kan ik bij mij in de buurt vrije tijd besteden? In dit thema ziet u waar u kunt sporten en ontspannen. Ook wandel- en fietspaden, natuurgebieden en horecagelegenheden vindt u hier terug.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN08/v1\" }," +
"{ \"class\": \"kunst-cultuur\", \"title\": \"Kunst & Cultuur\", \"description\": \"In dit thema vindt u alle informatie over cultuurhistorie en musea: gemeentelijke- en rijksmonumenten, maar ook archeologische monumenten.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN09/v1\" }," +
"{ \"class\": \"werklocaties\", \"title\": \"Werklocaties\", \"description\": \"In dit thema vindt u alles over bedrijvigheid. Bedrijventerreinen en kantoorlocaties, maar ook winkelcentra bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN10/v1\" }" +
"]";
this.mapsList = new ArrayList<>();
try {
JSONArray maps = new JSONArray(mapsJson);
for (int i = 0; i < maps.length(); ++i) {
JSONObject rec = maps.getJSONObject(i);
MapsBean map = new MapsBean();
map.setTitle(rec.getString("title"));
map.setDescription(rec.getString("description"));
map.setUrl(rec.getString("url"));
map.setCssClass(rec.getString("class"));
this.mapsList.add(map);
}
} catch (JSONException ex) {
Logger.getLogger(GeoBrabantAction.class.getName()).log(Level.SEVERE, null, ex);
}
return new ForwardResolution("/WEB-INF/jsp/geobrabant/kaarten.jsp");
}
public Resolution catalogus() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/catalogus.jsp");
}
public Resolution zoeken() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/zoeken.jsp");
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<MapsBean> getMapsList() {
return mapsList;
}
public void setMapsList(List<MapsBean> mapsList) {
this.mapsList = mapsList;
}
public class MapsBean {
private String title;
private String description;
private String url;
private String cssClass;
public MapsBean() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
}
}
| B3Partners/B3pCatalog | src/main/java/nl/b3p/catalog/stripes/GeoBrabantAction.java | 2,384 | //acc.geobrabant.nl/viewer/app/RIN03/v1\" }," + | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.catalog.stripes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Geert Plaisier
*/
public class GeoBrabantAction extends DefaultAction {
@Validate(required=false)
private String searchString;
@Validate(required=false)
private String searchType;
@Validate(required=false)
private String uuid;
private List<MapsBean> mapsList;
@DefaultHandler
public Resolution home() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/home.jsp");
}
/* Static pages */
public Resolution overgeobrabant() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/overgeobrabant.jsp");
}
public Resolution diensten() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/diensten.jsp");
}
public Resolution contact() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/contact.jsp");
}
public Resolution kaarten() {
// This JSON should be fetched from a server somewhere
String mapsJson = "[" +
"{ \"class\": \"wat-mag-waar\", \"title\": \"Wat mag waar?\", \"description\": \"Waar ligt dat stukje grond? Zou ik hier mogen bouwen? Vragen die u beantwoord zult zien worden via dit thema. Bekijk welk perceel waar ligt en wat je ermee mag doen.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN01/v1\" }," +
"{ \"class\": \"bekendmakingen\", \"title\": \"Bekendmakingen\", \"description\": \"Via bekendmakingen kunt u zien welke vergunningaanvragen in uw buurt zijn ingediend of verleend zijn. Hierdoor blijft u op de hoogte van de ontwikkelingen bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN02/v1\" }," +
"{ \"class\": \"bereikbaarheid\", \"title\": \"Bereikbaarheid\", \"description\": \"Via dit thema kunt u erachter komen hoe de beriekbaarheid van een bepaald gebied is. Zo vindt u bijvoorbeeld waar de dichtstbijzijnde parkeergarage is, waar u oplaadpalen aantreft en actuele informatie over verkeer en wegwerkzaamheden\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN03/v1\" },"<SUF>
"{ \"class\": \"veiligheid\", \"title\": \"Veiligheid\", \"description\": \"In dit thema vindt u informatie over de veiligheid in uw buurt. Waar zit de politie en brandweer, maar ook overstromingsrisico, waterkeringen en de veiligheidsregio staan hier.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN04/v1\" }," +
"{ \"class\": \"zorg\", \"title\": \"Zorg\", \"description\": \"Ziekenhuizen, doktersposten en verzorgingshuizen. Alle data met betrekking tot de (medische) zorg staan in dit thema beschreven.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN05/v1\" }," +
"{ \"class\": \"onderwijs-kinderopvang\", \"title\": \"Onderwijs & Kinderopvang\", \"description\": \"In dit thema vindt u de locatie van alle scholen en kinderopvang.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN06/v1\" }," +
"{ \"class\": \"wijkvoorzieningen\", \"title\": \"Wijkvoorzieningen\", \"description\": \"Waar bij mij in de buurt bevinden zich afvalbakken, hondenuitlaatplaatsen en de speeltuin? Dergelijke wijkvoorzieningen vindt u in dit thema, evenals buurthuizen, winkelcentra, etc.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN07/v1\" }," +
"{ \"class\": \"recreatie\", \"title\": \"Recreatie\", \"description\": \"Waar kan ik bij mij in de buurt vrije tijd besteden? In dit thema ziet u waar u kunt sporten en ontspannen. Ook wandel- en fietspaden, natuurgebieden en horecagelegenheden vindt u hier terug.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN08/v1\" }," +
"{ \"class\": \"kunst-cultuur\", \"title\": \"Kunst & Cultuur\", \"description\": \"In dit thema vindt u alle informatie over cultuurhistorie en musea: gemeentelijke- en rijksmonumenten, maar ook archeologische monumenten.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN09/v1\" }," +
"{ \"class\": \"werklocaties\", \"title\": \"Werklocaties\", \"description\": \"In dit thema vindt u alles over bedrijvigheid. Bedrijventerreinen en kantoorlocaties, maar ook winkelcentra bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN10/v1\" }" +
"]";
this.mapsList = new ArrayList<>();
try {
JSONArray maps = new JSONArray(mapsJson);
for (int i = 0; i < maps.length(); ++i) {
JSONObject rec = maps.getJSONObject(i);
MapsBean map = new MapsBean();
map.setTitle(rec.getString("title"));
map.setDescription(rec.getString("description"));
map.setUrl(rec.getString("url"));
map.setCssClass(rec.getString("class"));
this.mapsList.add(map);
}
} catch (JSONException ex) {
Logger.getLogger(GeoBrabantAction.class.getName()).log(Level.SEVERE, null, ex);
}
return new ForwardResolution("/WEB-INF/jsp/geobrabant/kaarten.jsp");
}
public Resolution catalogus() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/catalogus.jsp");
}
public Resolution zoeken() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/zoeken.jsp");
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<MapsBean> getMapsList() {
return mapsList;
}
public void setMapsList(List<MapsBean> mapsList) {
this.mapsList = mapsList;
}
public class MapsBean {
private String title;
private String description;
private String url;
private String cssClass;
public MapsBean() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
}
}
|
140373_1 | /*
* Copyright 2009 B3Partners BV
*
*/
package nl.b3p.csw.util;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.output.DOMOutputter;
/**
*
* @author Erik van de Pol
*/
public class MarshallUtil {
protected static Log log = LogFactory.getLog(MarshallUtil.class);
protected final static String CSW_PACKAGE = "nl.b3p.csw.jaxb.csw";
protected final static String ELEMENTS_PACKAGE = "nl.b3p.csw.jaxb.elements";
protected final static String FILTER_PACKAGE = "nl.b3p.csw.jaxb.filter";
protected final static String GML_PACKAGE = "nl.b3p.csw.jaxb.gml";
protected final static String OWS_PACKAGE = "nl.b3p.csw.jaxb.ows";
protected final static String TERMS_PACKAGE = "nl.b3p.csw.jaxb.terms";
protected final static String SEPARATOR = ":";
protected static String JAXB_PACKAGES =
CSW_PACKAGE + SEPARATOR +
ELEMENTS_PACKAGE + SEPARATOR +
FILTER_PACKAGE + SEPARATOR +
GML_PACKAGE + SEPARATOR +
OWS_PACKAGE + SEPARATOR +
TERMS_PACKAGE;
public static void addPackage(String packageName) {
JAXB_PACKAGES += SEPARATOR + packageName;
}
public static String marshall(JAXBElement input, Schema schema) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_PACKAGES);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setSchema(schema);
marshaller.setProperty("jaxb.formatted.output", true);
//Geonetwork heeft per se csw als ns prefix nodig
//niet hier oplossen omdat dan jaxb-ri nodig is, veel conflicten
//marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CswNamespaceMapper());
StringWriter stringWriter = new StringWriter();
marshaller.marshal(input, stringWriter);
return stringWriter.toString();
}
public static JAXBElement unMarshall(org.w3c.dom.Document xmlDocument, Schema schema, Class clazz) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_PACKAGES);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
return unmarshaller.unmarshal(xmlDocument, clazz);
}
public static JAXBElement unMarshall(Document xmlDocument, Schema schema, Class clazz) throws JAXBException, JDOMException {
// transform to w3c dom to be able to use jaxb to unmarshal.
DOMOutputter domOutputter = new DOMOutputter();
org.w3c.dom.Document w3cDomDoc = domOutputter.output(xmlDocument);
return unMarshall(w3cDomDoc, schema, clazz);
}
}
| B3Partners/b3p-commons-csw | src/main/java/nl/b3p/csw/util/MarshallUtil.java | 970 | /**
*
* @author Erik van de Pol
*/ | block_comment | nl | /*
* Copyright 2009 B3Partners BV
*
*/
package nl.b3p.csw.util;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.output.DOMOutputter;
/**
*
* @author Erik van<SUF>*/
public class MarshallUtil {
protected static Log log = LogFactory.getLog(MarshallUtil.class);
protected final static String CSW_PACKAGE = "nl.b3p.csw.jaxb.csw";
protected final static String ELEMENTS_PACKAGE = "nl.b3p.csw.jaxb.elements";
protected final static String FILTER_PACKAGE = "nl.b3p.csw.jaxb.filter";
protected final static String GML_PACKAGE = "nl.b3p.csw.jaxb.gml";
protected final static String OWS_PACKAGE = "nl.b3p.csw.jaxb.ows";
protected final static String TERMS_PACKAGE = "nl.b3p.csw.jaxb.terms";
protected final static String SEPARATOR = ":";
protected static String JAXB_PACKAGES =
CSW_PACKAGE + SEPARATOR +
ELEMENTS_PACKAGE + SEPARATOR +
FILTER_PACKAGE + SEPARATOR +
GML_PACKAGE + SEPARATOR +
OWS_PACKAGE + SEPARATOR +
TERMS_PACKAGE;
public static void addPackage(String packageName) {
JAXB_PACKAGES += SEPARATOR + packageName;
}
public static String marshall(JAXBElement input, Schema schema) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_PACKAGES);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setSchema(schema);
marshaller.setProperty("jaxb.formatted.output", true);
//Geonetwork heeft per se csw als ns prefix nodig
//niet hier oplossen omdat dan jaxb-ri nodig is, veel conflicten
//marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CswNamespaceMapper());
StringWriter stringWriter = new StringWriter();
marshaller.marshal(input, stringWriter);
return stringWriter.toString();
}
public static JAXBElement unMarshall(org.w3c.dom.Document xmlDocument, Schema schema, Class clazz) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_PACKAGES);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
return unmarshaller.unmarshal(xmlDocument, clazz);
}
public static JAXBElement unMarshall(Document xmlDocument, Schema schema, Class clazz) throws JAXBException, JDOMException {
// transform to w3c dom to be able to use jaxb to unmarshal.
DOMOutputter domOutputter = new DOMOutputter();
org.w3c.dom.Document w3cDomDoc = domOutputter.output(xmlDocument);
return unMarshall(w3cDomDoc, schema, clazz);
}
}
|
181878_4 | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2008 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Commons GIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.gis.csv;
import org.locationtech.jts.jump.feature.Feature;
import org.locationtech.jts.jump.feature.FeatureDataset;
import org.locationtech.jts.jump.feature.FeatureSchema;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import nl.b3p.commons.csv.CsvFormatException;
import nl.b3p.commons.csv.CsvInputStream;
import nl.b3p.gis.FeatureFactory;
import nl.b3p.gis.FeatureSchemaFactory;
import nl.b3p.gis.writers.B3pOgcSqlWriter;
/**
*
* @author Chris
*/
public class CsvReader {
public static final String DEFAULT_ignoredColumnName1 = "id";
public static final String DEFAULT_geomColumnName = "the_geom";
public static final String DEFAULT_srs = "28992";
public static final String DEFAULT_tsColumnName = "TS";
public static final String DEFAULT_rdxColumnName = "RDX";
public static final String DEFAULT_rdyColumnName = "RDY"; // FC
private String tableName;
private String[] ignoredColumnNames;
private String geomColumnName;
private String srs;
private String tsColumnName;
private String timestamp;
private String spaceName;
private String spaceValue;
private String[] uidNames;
// CSV
private String rdxColumnName;
private String rdyColumnName;
// Locale
private Locale csvLocale;
private DecimalFormatSymbols dfs;
private char csvSeparator; // Translation
private HashMap translatorMap = null;
private boolean useMultiPoint = false;
private String ignoreValue;
private boolean doInsert = false;
public CsvReader(String tableName, String spaceName, String spaceValue, String[] uidNames) {
this(tableName, spaceName, spaceValue, uidNames, null, ',', false);
}
public CsvReader(String tableName, String spaceName, String spaceValue, String[] uidNames, Locale loc, char csvSeparator, boolean useMultiPoint) {
this.setTableName(tableName);
this.setSpaceName(spaceName);
this.setSpaceValue(spaceValue);
this.setUidNames(uidNames);
this.setCsvLocale(loc);
this.setCsvSeparator(csvSeparator);
this.fillDefaults();
this.useMultiPoint = useMultiPoint;
}
protected void fillDefaults() {
SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
sdf.applyPattern("yyyy-MM-dd HH:mm:sss");
this.timestamp = sdf.format(new Date());
this.ignoredColumnNames = new String[]{DEFAULT_ignoredColumnName1};
this.geomColumnName = DEFAULT_geomColumnName;
this.srs = DEFAULT_srs;
this.tsColumnName = DEFAULT_tsColumnName;
this.rdxColumnName = DEFAULT_rdxColumnName;
this.rdyColumnName = DEFAULT_rdyColumnName;
}
public void csvOgcSqlETL(Connection conn, CsvInputStream cis) throws SQLException, IOException, CsvFormatException, Exception {
FeatureSchema fs = getFeatureSchema(conn);
FeatureDataset fc = readFeatureDataset(fs, cis);
writeFeatureDataset(conn, fc);
}
public FeatureSchema getFeatureSchema(Connection conn) throws SQLException, Exception {
return FeatureSchemaFactory.createFeatureSchemaFromDbTable(conn, getTableName(), getIgnoredColumnNames());
}
public FeatureDataset readFeatureDataset(FeatureSchema fs, CsvInputStream cis) throws IOException, CsvFormatException {
cis.setSeparator(getCsvSeparator());
FeatureDataset fc = new FeatureDataset(fs);
int columnCount = fs.getAttributeCount();
List columnList = cis.readRecordAsList();
if (columnList == null || columnList.isEmpty()) {
throw new CsvFormatException("No file found");
}
if ((columnCount > 1) && (columnList.size() <= 1)) {
// simpele test of juiste separator is gebruikt
throw new CsvFormatException("More columns expected (separator used: '" + getCsvSeparator() + "')");
}
cis.setCheckColumnCount(true);
int rdxindex = -1, rdyindex = -1;
/* eerst de processColumns doen voordat de rdx of rdy index
* wordt bekeken. De rdx en rdy moeten namelijk uppercase zijn
* wil de indexOf hieronder de juiste index teruggeven.
* processColumns geeft de mogelijkheid om dit te doen.
*/
columnList = processColumns(columnList);
if (columnList != null) {
rdxindex = columnList.indexOf(getRdxColumnName());
rdyindex = columnList.indexOf(getRdyColumnName());
}
String[] columns = null;
if (columnList != null) {
columns = (String[]) columnList.toArray(new String[]{});
}
List attributeList = null;
while ((attributeList = cis.readRecordAsList()) != null) {
attributeList = processAttributes(attributeList, columnList);
double rdx = 0.0d, rdy = 0.0d;
if (rdxindex >= 0) {
rdx = getDoubleFromString((String) attributeList.get(rdxindex));
}
if (rdyindex >= 0) {
rdy = getDoubleFromString((String) attributeList.get(rdyindex));
}
Object[] attributes = (Object[]) attributeList.toArray(new Object[]{});
Feature f = FeatureFactory.createPointFeature(attributes, columns, rdx, rdy, fs, useMultiPoint);
fc.add(f);
}
return fc;
}
public void writeFeatureDataset(Connection conn, FeatureDataset fc) throws SQLException, Exception {
B3pOgcSqlWriter bow = new B3pOgcSqlWriter(conn);
bow.setBatchValue(0);
String[] columnsToCheck = null;
/* Als er altijd een insert gedaan moetn worden dan kan
* voor columnsToCheck null worden meegegeven */
if (!doInsert) {
int len = 0;
if (getUidNames() != null)
len = getUidNames().length;
if (len == 0 && getSpaceName() != null) {
columnsToCheck = new String[]{getSpaceName()};
} else if (getSpaceName() != null) {
columnsToCheck = new String[len + 1];
for (int i = 0; i < len; i++) {
columnsToCheck[i] = getUidNames()[i];
}
columnsToCheck[len] = getSpaceName();
} else {
columnsToCheck = getUidNames();
}
}
bow.write(fc, getTableName(), getGeomColumnName(), getSrs(), 2, false, true, columnsToCheck, getIgnoreValue());
}
protected List translateColumns(List columns) {
if (columns == null) {
return null;
}
List newColumns = new ArrayList();
if (getTranslatorMap() != null) {
for (int i = 0; i < columns.size(); i++) {
String newColumnName = (String) getTranslatorMap().get(columns.get(i));
if (newColumnName != null && newColumnName.length() > 0) {
newColumns.add(newColumnName);
} else {
newColumns.add(columns.get(i));
}
}
}
return newColumns;
}
protected List processColumns(List columns) {
if (columns == null) {
return null;
}
List newColumns = translateColumns(columns);
if (getTsColumnName() != null && getTsColumnName().length() > 0) {
newColumns.add(getTsColumnName());
}
if (getSpaceName() != null && getSpaceName().length() > 0) {
newColumns.add(getSpaceName());
}
return newColumns;
}
protected List processAttributes(List attributes, List columns) {
if (attributes == null) {
return null;
}
if (getTsColumnName() != null && getTsColumnName().length() > 0) {
attributes.add(getTimestamp()); // TODO juiste format?
}
if (getSpaceName() != null && getSpaceName().length() > 0) {
attributes.add(getSpaceValue());
}
return attributes;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String[] getIgnoredColumnNames() {
return ignoredColumnNames;
}
public void setIgnoredColumnNames(String[] ignoredColumnNames) {
this.ignoredColumnNames = ignoredColumnNames;
}
public String getGeomColumnName() {
return geomColumnName;
}
public void setGeomColumnName(String geomColumnName) {
this.geomColumnName = geomColumnName;
}
public String getSrs() {
return srs;
}
public void setSrs(String srs) {
this.srs = srs;
}
public String getTsColumnName() {
return tsColumnName;
}
public void setTsColumnName(String tsColumnName) {
this.tsColumnName = tsColumnName;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getSpaceName() {
return spaceName;
}
public void setSpaceName(String spaceName) {
this.spaceName = spaceName;
}
public String getSpaceValue() {
return spaceValue;
}
public void setSpaceValue(String spaceValue) {
this.spaceValue = spaceValue;
}
public String[] getUidNames() {
return uidNames;
}
public void setUidNames(String[] uidNames) {
this.uidNames = uidNames;
}
public String getRdxColumnName() {
return rdxColumnName;
}
public void setRdxColumnName(String rdxColumnName) {
this.rdxColumnName = rdxColumnName;
}
public String getRdyColumnName() {
return rdyColumnName;
}
public void setRdyColumnName(String rdyColumnName) {
this.rdyColumnName = rdyColumnName;
}
public HashMap getTranslatorMap() {
return translatorMap;
}
public void setTranslatorMap(HashMap translatorMap) {
this.translatorMap = translatorMap;
}
public Locale getCsvLocale() {
return csvLocale;
}
public void setCsvLocale(Locale csvLocale) {
this.csvLocale = csvLocale;
}
public DecimalFormatSymbols getDfs() {
if (csvLocale == null) {
csvLocale = Locale.getDefault();
}
dfs = new DecimalFormatSymbols(this.csvLocale);
return dfs;
}
public char getCsvSeparator() {
return csvSeparator;
}
public void setCsvSeparator(char csvSeparator) {
this.csvSeparator = csvSeparator;
}
public String getIgnoreValue() {
return ignoreValue;
}
public void setIgnoreValue(String ignoreValue) {
this.ignoreValue = ignoreValue;
}
private double getDoubleFromString(String d) {
if (d == null) {
return 0.0d;
}
DecimalFormat df = new DecimalFormat("#", getDfs());
ParsePosition pos = new ParsePosition(0);
Number n = df.parse(d.trim(), pos);
if (n == null) {
return 0.0d;
}
return n.doubleValue();
}
public boolean isDoInsert() {
return doInsert;
}
public void setDoInsert(boolean doInsert) {
this.doInsert = doInsert;
}
}
| B3Partners/b3p-commons-gis | src/main/java/nl/b3p/gis/csv/CsvReader.java | 3,614 | /* Als er altijd een insert gedaan moetn worden dan kan
* voor columnsToCheck null worden meegegeven */ | block_comment | nl | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2008 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Commons GIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.gis.csv;
import org.locationtech.jts.jump.feature.Feature;
import org.locationtech.jts.jump.feature.FeatureDataset;
import org.locationtech.jts.jump.feature.FeatureSchema;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import nl.b3p.commons.csv.CsvFormatException;
import nl.b3p.commons.csv.CsvInputStream;
import nl.b3p.gis.FeatureFactory;
import nl.b3p.gis.FeatureSchemaFactory;
import nl.b3p.gis.writers.B3pOgcSqlWriter;
/**
*
* @author Chris
*/
public class CsvReader {
public static final String DEFAULT_ignoredColumnName1 = "id";
public static final String DEFAULT_geomColumnName = "the_geom";
public static final String DEFAULT_srs = "28992";
public static final String DEFAULT_tsColumnName = "TS";
public static final String DEFAULT_rdxColumnName = "RDX";
public static final String DEFAULT_rdyColumnName = "RDY"; // FC
private String tableName;
private String[] ignoredColumnNames;
private String geomColumnName;
private String srs;
private String tsColumnName;
private String timestamp;
private String spaceName;
private String spaceValue;
private String[] uidNames;
// CSV
private String rdxColumnName;
private String rdyColumnName;
// Locale
private Locale csvLocale;
private DecimalFormatSymbols dfs;
private char csvSeparator; // Translation
private HashMap translatorMap = null;
private boolean useMultiPoint = false;
private String ignoreValue;
private boolean doInsert = false;
public CsvReader(String tableName, String spaceName, String spaceValue, String[] uidNames) {
this(tableName, spaceName, spaceValue, uidNames, null, ',', false);
}
public CsvReader(String tableName, String spaceName, String spaceValue, String[] uidNames, Locale loc, char csvSeparator, boolean useMultiPoint) {
this.setTableName(tableName);
this.setSpaceName(spaceName);
this.setSpaceValue(spaceValue);
this.setUidNames(uidNames);
this.setCsvLocale(loc);
this.setCsvSeparator(csvSeparator);
this.fillDefaults();
this.useMultiPoint = useMultiPoint;
}
protected void fillDefaults() {
SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
sdf.applyPattern("yyyy-MM-dd HH:mm:sss");
this.timestamp = sdf.format(new Date());
this.ignoredColumnNames = new String[]{DEFAULT_ignoredColumnName1};
this.geomColumnName = DEFAULT_geomColumnName;
this.srs = DEFAULT_srs;
this.tsColumnName = DEFAULT_tsColumnName;
this.rdxColumnName = DEFAULT_rdxColumnName;
this.rdyColumnName = DEFAULT_rdyColumnName;
}
public void csvOgcSqlETL(Connection conn, CsvInputStream cis) throws SQLException, IOException, CsvFormatException, Exception {
FeatureSchema fs = getFeatureSchema(conn);
FeatureDataset fc = readFeatureDataset(fs, cis);
writeFeatureDataset(conn, fc);
}
public FeatureSchema getFeatureSchema(Connection conn) throws SQLException, Exception {
return FeatureSchemaFactory.createFeatureSchemaFromDbTable(conn, getTableName(), getIgnoredColumnNames());
}
public FeatureDataset readFeatureDataset(FeatureSchema fs, CsvInputStream cis) throws IOException, CsvFormatException {
cis.setSeparator(getCsvSeparator());
FeatureDataset fc = new FeatureDataset(fs);
int columnCount = fs.getAttributeCount();
List columnList = cis.readRecordAsList();
if (columnList == null || columnList.isEmpty()) {
throw new CsvFormatException("No file found");
}
if ((columnCount > 1) && (columnList.size() <= 1)) {
// simpele test of juiste separator is gebruikt
throw new CsvFormatException("More columns expected (separator used: '" + getCsvSeparator() + "')");
}
cis.setCheckColumnCount(true);
int rdxindex = -1, rdyindex = -1;
/* eerst de processColumns doen voordat de rdx of rdy index
* wordt bekeken. De rdx en rdy moeten namelijk uppercase zijn
* wil de indexOf hieronder de juiste index teruggeven.
* processColumns geeft de mogelijkheid om dit te doen.
*/
columnList = processColumns(columnList);
if (columnList != null) {
rdxindex = columnList.indexOf(getRdxColumnName());
rdyindex = columnList.indexOf(getRdyColumnName());
}
String[] columns = null;
if (columnList != null) {
columns = (String[]) columnList.toArray(new String[]{});
}
List attributeList = null;
while ((attributeList = cis.readRecordAsList()) != null) {
attributeList = processAttributes(attributeList, columnList);
double rdx = 0.0d, rdy = 0.0d;
if (rdxindex >= 0) {
rdx = getDoubleFromString((String) attributeList.get(rdxindex));
}
if (rdyindex >= 0) {
rdy = getDoubleFromString((String) attributeList.get(rdyindex));
}
Object[] attributes = (Object[]) attributeList.toArray(new Object[]{});
Feature f = FeatureFactory.createPointFeature(attributes, columns, rdx, rdy, fs, useMultiPoint);
fc.add(f);
}
return fc;
}
public void writeFeatureDataset(Connection conn, FeatureDataset fc) throws SQLException, Exception {
B3pOgcSqlWriter bow = new B3pOgcSqlWriter(conn);
bow.setBatchValue(0);
String[] columnsToCheck = null;
/* Als er altijd<SUF>*/
if (!doInsert) {
int len = 0;
if (getUidNames() != null)
len = getUidNames().length;
if (len == 0 && getSpaceName() != null) {
columnsToCheck = new String[]{getSpaceName()};
} else if (getSpaceName() != null) {
columnsToCheck = new String[len + 1];
for (int i = 0; i < len; i++) {
columnsToCheck[i] = getUidNames()[i];
}
columnsToCheck[len] = getSpaceName();
} else {
columnsToCheck = getUidNames();
}
}
bow.write(fc, getTableName(), getGeomColumnName(), getSrs(), 2, false, true, columnsToCheck, getIgnoreValue());
}
protected List translateColumns(List columns) {
if (columns == null) {
return null;
}
List newColumns = new ArrayList();
if (getTranslatorMap() != null) {
for (int i = 0; i < columns.size(); i++) {
String newColumnName = (String) getTranslatorMap().get(columns.get(i));
if (newColumnName != null && newColumnName.length() > 0) {
newColumns.add(newColumnName);
} else {
newColumns.add(columns.get(i));
}
}
}
return newColumns;
}
protected List processColumns(List columns) {
if (columns == null) {
return null;
}
List newColumns = translateColumns(columns);
if (getTsColumnName() != null && getTsColumnName().length() > 0) {
newColumns.add(getTsColumnName());
}
if (getSpaceName() != null && getSpaceName().length() > 0) {
newColumns.add(getSpaceName());
}
return newColumns;
}
protected List processAttributes(List attributes, List columns) {
if (attributes == null) {
return null;
}
if (getTsColumnName() != null && getTsColumnName().length() > 0) {
attributes.add(getTimestamp()); // TODO juiste format?
}
if (getSpaceName() != null && getSpaceName().length() > 0) {
attributes.add(getSpaceValue());
}
return attributes;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String[] getIgnoredColumnNames() {
return ignoredColumnNames;
}
public void setIgnoredColumnNames(String[] ignoredColumnNames) {
this.ignoredColumnNames = ignoredColumnNames;
}
public String getGeomColumnName() {
return geomColumnName;
}
public void setGeomColumnName(String geomColumnName) {
this.geomColumnName = geomColumnName;
}
public String getSrs() {
return srs;
}
public void setSrs(String srs) {
this.srs = srs;
}
public String getTsColumnName() {
return tsColumnName;
}
public void setTsColumnName(String tsColumnName) {
this.tsColumnName = tsColumnName;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getSpaceName() {
return spaceName;
}
public void setSpaceName(String spaceName) {
this.spaceName = spaceName;
}
public String getSpaceValue() {
return spaceValue;
}
public void setSpaceValue(String spaceValue) {
this.spaceValue = spaceValue;
}
public String[] getUidNames() {
return uidNames;
}
public void setUidNames(String[] uidNames) {
this.uidNames = uidNames;
}
public String getRdxColumnName() {
return rdxColumnName;
}
public void setRdxColumnName(String rdxColumnName) {
this.rdxColumnName = rdxColumnName;
}
public String getRdyColumnName() {
return rdyColumnName;
}
public void setRdyColumnName(String rdyColumnName) {
this.rdyColumnName = rdyColumnName;
}
public HashMap getTranslatorMap() {
return translatorMap;
}
public void setTranslatorMap(HashMap translatorMap) {
this.translatorMap = translatorMap;
}
public Locale getCsvLocale() {
return csvLocale;
}
public void setCsvLocale(Locale csvLocale) {
this.csvLocale = csvLocale;
}
public DecimalFormatSymbols getDfs() {
if (csvLocale == null) {
csvLocale = Locale.getDefault();
}
dfs = new DecimalFormatSymbols(this.csvLocale);
return dfs;
}
public char getCsvSeparator() {
return csvSeparator;
}
public void setCsvSeparator(char csvSeparator) {
this.csvSeparator = csvSeparator;
}
public String getIgnoreValue() {
return ignoreValue;
}
public void setIgnoreValue(String ignoreValue) {
this.ignoreValue = ignoreValue;
}
private double getDoubleFromString(String d) {
if (d == null) {
return 0.0d;
}
DecimalFormat df = new DecimalFormat("#", getDfs());
ParsePosition pos = new ParsePosition(0);
Number n = df.parse(d.trim(), pos);
if (n == null) {
return 0.0d;
}
return n.doubleValue();
}
public boolean isDoInsert() {
return doInsert;
}
public void setDoInsert(boolean doInsert) {
this.doInsert = doInsert;
}
}
|
116460_3 | package nl.b3p.geotools.data.linker;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.datastorelinker.entity.Database;
import nl.b3p.datastorelinker.util.Namespaces;
import nl.b3p.datastorelinker.util.Util;
import nl.b3p.geotools.data.linker.blocks.Action;
import nl.b3p.geotools.data.linker.blocks.WritableAction;
import nl.b3p.geotools.data.linker.feature.EasyFeature;
import nl.b3p.geotools.data.linker.util.LocalizationUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.DataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.oracle.OracleNGDataStoreFactory;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.jdbc.JDBCDataStore;
import org.geotools.jdbc.JDBCFeatureStore;
import org.geotools.jdbc.PrimaryKey;
import org.jdom2.Element;
import org.jdom2.input.DOMBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
/**
* Convert batch to actionList and execute it
*
* @author Gertjan Al, B3Partners
*/
public class DataStoreLinker implements Runnable {
private static final Log log = LogFactory.getLog(DataStoreLinker.class);
private final static ResourceBundle resources = LocalizationUtil.getResources();
public static final String ACTIONLIST_PREFIX = "actionlist";
public static final String ACTION_PREFIX = "action";
public static final String TYPE_PREFIX = "type";
public static final String SETTINGS_PREFIX = "settings";
public static final String DATASTORE2READ_PREFIX = "read.datastore.";
public static final String READ_TYPENAME = "read.typename";
protected static final String DEFAULT_WRITER = "ActionCombo_GeometrySingle_Writer";
public static String DEFAULT_SMTPHOST = "kmail.b3partners.nl";
public static String DEFAULT_FROM = "[email protected]";
protected Status status;
protected DataStore dataStore2Read;
protected ActionList actionList;
protected Properties batch;
protected nl.b3p.datastorelinker.entity.Process process;
protected boolean disposed;
private int exceptionLogCount = 0;
private static final int MAX_EXCEPTION_LOG_COUNT = 10;
public static final String TYPE_ORACLE = "oracle";
public static final String TYPE_POSTGIS = "postgis";
public static final String TYPE_WFS = "wfs";
public synchronized Status getStatus() {
return status;
}
public DataStoreLinker(nl.b3p.datastorelinker.entity.Process process) throws Exception {
init(process);
dataStore2Read = openDataStore();
actionList = createActionList();
postInit();
}
public DataStoreLinker(Properties batch) throws Exception {
init(batch);
dataStore2Read = createDataStore2Read(batch);
actionList = createActionList(batch);
postInit();
}
public DataStoreLinker(Map<String, Object> input, Map<String, Object> actions, Properties batch) throws Exception {
init(batch);
dataStore2Read = openDataStore(input);
actionList = createActionList(actions);
postInit();
}
private void init(nl.b3p.datastorelinker.entity.Process process) throws ConfigurationException, IOException {
this.process = process;
disposed = false;
status = new Status(process);
}
private void init(Properties batch) throws ConfigurationException, IOException {
this.batch = batch;
disposed = false;
status = new Status(batch);
}
/**
* Calculating the size can take a very long time depending on the
* implementation of the chosen datastore. Some implementations walk through
* all features to calculate the size.
*
* @throws IOException
*/
private void calculateSizes() throws IOException {
int totalFeatureSize = 0;
if (dataStore2Read != null) {
for (String typeName2Read : getTypeNames()) {
FeatureCollection fc = dataStore2Read.getFeatureSource(typeName2Read).getFeatures();
totalFeatureSize += fc.size();
}
}
status.setTotalFeatureSize(totalFeatureSize);
}
private void postInit() throws IOException {
calculateSizes();
log.info("dsl init complete.");
}
public void run() {
try {
process();
} catch (Exception ex) {
log.error(ex);
}
}
public boolean isDisposed(){
return disposed;
}
public synchronized void dispose() throws Exception {
if (!disposed) {
try {
dataStore2Read.dispose();
actionList.close();
} finally {
disposed = true;
}
}
}
/**
* Process all features in dataStore2Read
*
* @throws Exception generic exception
*/
public void process() throws Exception {
if (disposed) {
throw new Exception("Dsl already used. Please create a new instance of this class");
}
try {
for (String typeName2Read : getTypeNames()) {
processTypeName(typeName2Read);
}
} finally {
try {
if (batch != null) {
DataStoreLinkerMail.mail(batch, status.getNonFatalErrorReport("\n", 3));
} else if (process != null) {
DataStoreLinkerMail.mail(process, status.getNonFatalErrorReport("\n", 3));
}
} catch (Exception mex) {
status.addNonFatalError(mex.getLocalizedMessage(), "");
}
log.info("Error report: " + status.getNonFatalErrorReport("\n", 3));
dispose();
}
}
private void processTypeName(String typeName2Read) throws Exception, IOException {
SimpleFeature feature = null;
String filterName = process.getFilter();
Query query = new Query();
if(filterName!=null){
Filter filter = ECQL.toFilter(filterName);
query.setFilter(filter);
}
FeatureCollection fc = dataStore2Read.getFeatureSource(typeName2Read).getFeatures(query);
FeatureIterator iterator = fc.features();
PrimaryKey pk = null;
if (dataStore2Read != null && (dataStore2Read instanceof JDBCDataStore)) {
FeatureSource fs = ((JDBCDataStore) dataStore2Read).getFeatureSource(typeName2Read);
if (fs instanceof JDBCFeatureStore) {
pk = ((JDBCFeatureStore) fs).getPrimaryKey();
}
}
Map properties = null;
if (batch != null) {
properties = new HashMap(batch);
} else if (process != null) {
properties = process.toOutputMap();
}
try {
while (iterator.hasNext()) {
try {
feature = (SimpleFeature) iterator.next();
} catch (Exception ex) {
log.error("Fout bij inlezen feature ", ex);
String id = null;
if (feature != null ) {
id = feature.getID();
}
status.addNonFatalError(ExceptionUtils.getRootCauseMessage(ex), id);
status.incrementVisitedFeatures();
continue;
}
Map userData = feature.getUserData();
if (pk != null && userData != null) {
userData.put("sourcePks", pk);
}
processFeature(feature);
if (status.getVisitedFeatures() % 10000 == 0) {
log.info("" + status.getVisitedFeatures() + "/" + status.getTotalFeatureSize() + " features processed (" + typeName2Read + ")");
}
if (status.isInterrupted()) {
actionList.flush(status, properties);
actionList.processPostCollectionActions(status, properties);
throw new InterruptedException("User canceled the process.");
}
}
actionList.flush(status, properties);
log.info("Try to do the Post actions");
actionList.processPostCollectionActions(status, properties);
log.info("Total of: " + status.getVisitedFeatures() + " features processed (" + typeName2Read + ")");
} finally {
iterator.close();
JpaUtilServlet.closeThreadEntityManager();
}
}
private void processFeature(SimpleFeature feature) throws Exception {
if (!mustProcessFeature()) {
return;
}
/*TODO: Onderscheid maken tussen fatal Exception en niet Fatal Exception. Als er een Fatal
wordt gethrowed dan moet er worden gestopt met features processen.*/
try {
EasyFeature ef = new EasyFeature(feature);
if (ef.getFeature().getDefaultGeometry() != null) {
// repair if necessary (e.g. no geom metadata in oracle)
ef.repairGeometry();
}
if (actionList.process(ef) != null) {
// hier niet zetten, maar bij writer action
//status.incrementProcessedFeatures();
}
} catch (IllegalStateException ex) {
status.addWriteError(ex.getLocalizedMessage(), feature.getID());
log.error("Cannot write to datastore: ",ex);
throw ex;
} catch (Exception e) {
if (exceptionLogCount++ < MAX_EXCEPTION_LOG_COUNT) {
log.error("Exception tijdens processen van feature (exception nr. " + exceptionLogCount + " van max " + MAX_EXCEPTION_LOG_COUNT + " die worden gelogd)", e);
}
status.addNonFatalError(ExceptionUtils.getRootCauseMessage(e), feature.getID());
}
status.incrementVisitedFeatures();
}
private boolean mustProcessFeature() {
return status.getVisitedFeatures() >= status.getFeatureStart() && ((status.getVisitedFeatures() <= status.getFeatureEnd() && status.getFeatureEnd() >= 0)
|| (status.getFeatureEnd() < 0));
}
/**
* Create dataStore2Read from properties
*/
private DataStore createDataStore2Read(Properties batch) throws Exception {
return openDataStore(propertiesToMaps(batch, DATASTORE2READ_PREFIX));
}
private ActionList createActionList() throws Exception {
ActionList newActionList = new ActionList();
String outputWriter = null;
org.w3c.dom.Element actions = process.getActions();
if (actions != null) {
Element actionsElement = new DOMBuilder().build(actions);
for (Object actionObject : actionsElement.getChildren("action", Namespaces.DSL_NAMESPACE)) {
Element actionElement = (Element) actionObject;
Map<String, Object> parameters = new HashMap<String, Object>();
Element parametersElement = actionElement.getChild("parameters", Namespaces.DSL_NAMESPACE);
if (parametersElement != null) {
for (Object parameterObject : parametersElement.getChildren("parameter", Namespaces.DSL_NAMESPACE)) {
Element parameterElement = (Element) parameterObject;
String key = parameterElement.getChildTextTrim("paramId", Namespaces.DSL_NAMESPACE);
Object value = parameterElement.getChildTextTrim("value", Namespaces.DSL_NAMESPACE);
parameters.put(key, value);
}
}
String actionType = actionElement.getChildTextTrim("type", Namespaces.DSL_NAMESPACE);
//if (ActionFactory.isDataStoreAction(actionType)) { // lelijke constructie; nooit meer gebruiken aub
// FIXME: we moeten echt ophouden die oude meuk te ondersteunen.
// De doorgegeven class moet natuurlijk gewoon de fully qualified class name zijn:
// i.e.: nl.b3p.datastorelinker.actions.MyAction
//if (WritableAction.class.isAssignableFrom(Class.forName(actionType))) {
if (WritableAction.class.isAssignableFrom(
Class.forName("nl.b3p.geotools.data.linker.blocks." + actionType))) {
outputWriter = actionType;
} else {
newActionList.add(ActionFactory.createAction(actionType, parameters));
}
}
}
// Finally: add output database to action list:
if (outputWriter == null) {
newActionList.add(ActionFactory.createAction(DEFAULT_WRITER,
process.toOutputMap()));
} else {
newActionList.add(ActionFactory.createAction(outputWriter,
process.toOutputMap()));
}
log.debug("Actions to be executed (in this order):");
for (Action action : newActionList) {
log.debug(action.getName());
}
return newActionList;
}
private Boolean parseBoolean(String bool) throws Exception {
if (bool.equalsIgnoreCase("true")) {
return Boolean.TRUE;
} else if (bool.equalsIgnoreCase("false")) {
return Boolean.FALSE;
} else {
throw new Exception(MessageFormat.format(resources.getString("parseBooleanFailed"), bool));
}
}
/**
* Create actionList from batch
*/
private ActionList createActionList(Properties batch) throws Exception {
Map<String, Object> actionlistParams = propertiesToMaps(batch, ACTIONLIST_PREFIX + "." + ACTION_PREFIX);
return createActionList(actionlistParams);
}
public static ActionList createActionList(Map<String, Object> actionlistParams) throws Exception {
ActionList actionList = new ActionList();
int count = 1;
while (true) {
if (actionlistParams.containsKey(Integer.toString(count))) {
Map<String, Object> params = (Map) actionlistParams.get(Integer.toString(count));
if (params.containsKey(TYPE_PREFIX)) {
if (params.containsKey(SETTINGS_PREFIX)) {
if (params.get(TYPE_PREFIX) instanceof String && params.get(SETTINGS_PREFIX) instanceof Map) {
actionList.add(ActionFactory.createAction((String) params.get(TYPE_PREFIX), (Map) params.get(SETTINGS_PREFIX)));
} else {
throw new Exception("Expected " + ACTION_PREFIX + Integer.toString(count) + "." + TYPE_PREFIX + " to be String and " + ACTION_PREFIX + Integer.toString(count) + "." + SETTINGS_PREFIX + " to be a Map");
}
} else {
if (params.get(TYPE_PREFIX) instanceof String) {
actionList.add(ActionFactory.createAction((String) params.get(TYPE_PREFIX), new HashMap()));
} else {
throw new Exception("Expected " + ACTION_PREFIX + Integer.toString(count) + "." + TYPE_PREFIX + " to be String");
}
}
/*
if (params.get(TYPE_PREFIX) instanceof String && params.get(SETTINGS_PREFIX) instanceof Map) {
actionList.add(ActionFactory.createAction((String) params.get(TYPE_PREFIX), (Map) params.get(SETTINGS_PREFIX)));
} else {
throw new Exception("Expected " + ACTION_PREFIX + Integer.toString(count) + "." + TYPE_PREFIX + " to be String and " + ACTION_PREFIX + Integer.toString(count) + "." + SETTINGS_PREFIX + " to be a Map");
}
* */
} else {
throw new Exception("No type found for action" + Integer.toString(count));
}
} else {
break;
}
count++;
}
return actionList;
}
private DataStore openDataStore() throws ConfigurationException, Exception {
Database database = process.getInput().getDatabase();
String file = process.getInput().getFile();
if (database != null) {
return openDataStore(database);
} else if (file != null) { // TODO: this should be a file now; change xsd to reflect this "xsd:choice"
return openDataStore(file);
} else { // safeguard:
throw new ConfigurationException("Xml configuration exception: No input database or file specified.");
}
}
public static DataStore openDataStore(Database database) throws ConfigurationException, Exception {
return openDataStore(database.toGeotoolsDataStoreParametersMap());
}
public static DataStore openDataStore(String file) throws ConfigurationException, Exception {
return openDataStore(Util.fileToMap(new File(file)));
}
public static DataStore openDataStore(Map params) throws Exception {
return openDataStore(params, false);
}
/**
* Open a dataStore (save). If create new is set to true, a datastore wil be
* created even if the file is not there yet.
*
* @param params the datastore parameters
* @param createNew create new or not
* @return boolean indicating success
* @throws Exception generic exception
*/
public static DataStore openDataStore(Map params, boolean createNew) throws Exception {
log.debug("openDataStore with: " + params);
DataStore dataStore = null;
// TODO: indien je bij het aanmaken van een nieuwe datastore primary
// keys wil opgeven dan kan dat via PK_METADATA_TABLE.
// Nu nog buggy, fix in 8.7
String dbType = (String) params.get("dbtype");
if (dbType != null && dbType.equals(TYPE_ORACLE)) {
params.put(OracleNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
params.put("min connections", 0);
params.put("max connections", 50);
params.put("connection timeout", 60);
params.put("validate connections", Boolean.FALSE);
log.debug("Created OracleNGDataStoreFactory with: " + params);
/* TODO: nagaan of je Geotools naar eigen gemaakte
* geometry columns kunt laten kijken */
//params.put("Geometry metadata table", "GEOMETRY_COLUMNS");
return (new OracleNGDataStoreFactory()).createDataStore(params);
} else if (dbType != null && dbType.equals(TYPE_POSTGIS)) {
params.put(PostgisNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
params.put("min connections", 0);
params.put("max connections", 50);
params.put("connection timeout", 60);
params.put("validate connections", Boolean.FALSE);
log.debug("Created PostgisNGDataStoreFactory with: " + params);
return (new PostgisNGDataStoreFactory()).createDataStore(params);
} else if (dbType != null && dbType.equals(TYPE_WFS)){
log.debug("Created WFSDataStoreFactory with: " + params);
return (new WFSDataStoreFactory()).createDataStore(params);
}
String errormsg = "DataStore could not be found using parameters";
try {
dataStore = DataStoreFinder.getDataStore(params);
if (dataStore == null && createNew) {
if (params.containsKey("url")) {
String url = (String) params.get("url");
if (url.lastIndexOf(".shp") == (url.length() - ".shp".length())) {
ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
// FileDataStoreFactorySpi factory = new IndexedShapefileDataStoreFactory();
params.put("url", new File(url).toURL());
dataStore = factory.createNewDataStore(params);
} else {
log.warn("Can not create a new datastore, filetype unknown.");
}
}
}
} catch (NullPointerException nullEx) {
if (!urlExists(params)) {
throw new Exception("URL in parameters seems to point to a non-existing file \n\n" + params.toString());
} else {
throw new Exception(errormsg + " " + params.toString());
}
}
if (dataStore == null) {
if (!urlExists(params)) {
throw new Exception("URL in parameters may point to a non-existing file \n\n" + params.toString());
} else {
throw new Exception("DataStoreFinder returned null for \n\n" + params.toString());
}
} else {
log.debug("DataStore class: " + dataStore.getClass());
return dataStore;
}
}
private static boolean urlExists(Map params) {
try {
if (params.containsKey("url")) {
if (params.get("url") instanceof URL) {
URL url = (URL) params.get("url");
log.debug("Checking url exists: " + url);
File file = new File(url.toURI());
log.debug("Checking file url exists: " + file.getAbsolutePath());
return file.exists();
} else if (params.get("url") instanceof String) {
String url = params.get("url").toString();
log.debug("Checking url exists: " + url);
File file = new File(url);
log.debug("Checking file url exists: " + file.getAbsolutePath());
return file.exists();
}
}
} catch (URISyntaxException uriEx) {
return false;
}
return true;
}
public static String getSaveProp(Properties batch, String key, String defaultValue) {
if (batch.containsKey(key)) {
return batch.getProperty(key);
} else {
return defaultValue;
}
}
/**
* Make HashMap structure from propertylist
*
* @param batch Original properties list
* @param filter Specified to filter start of properties, like
* 'actionlist.action'
* @return the mapped propertylist
* @throws IOException general IOexception
*/
public static Map<String, Object> propertiesToMaps(Properties batch, String filter) throws IOException {
Map<String, Object> map = new HashMap();
Iterator iter = batch.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
if (key.startsWith(filter)) {
String value = batch.getProperty(key);
String keypart = key.substring(filter.length());
Map<String, Object> stepIn = map;
while (keypart.contains(".")) {
String step = keypart.substring(0, keypart.indexOf("."));
keypart = keypart.substring(keypart.indexOf(".") + 1);
if (stepIn.containsKey(step)) {
if (stepIn.get(step) instanceof Map) {
stepIn = (Map) stepIn.get(step);
} else {
throw new IOException("Tried to save settingsMap for property '" + key + "', but property has already a value?\nValue = '" + stepIn.get(step).toString() + "'");
}
} else {
Map<String, Object> newStep = new HashMap();
stepIn.put(step, newStep);
stepIn = newStep;
}
}
if (value.toLowerCase().equals("false")) {
stepIn.put(keypart, false);
} else if (value.toLowerCase().equals("true")) {
stepIn.put(keypart, true);
} else if (keypart.toLowerCase().equals("url")) {
File file = new File(value);
if (file.exists()) {
stepIn.put(keypart, file.toURL());
} else {
stepIn.put(keypart, value);
}
} else {
stepIn.put(keypart, value);
}
}
}
return map;
}
private String[] getTypeNames() throws IOException {
String[] typenames = null;
if (batch != null && batch.containsKey(READ_TYPENAME)) {
// One table / schema
typenames = new String[]{
batch.getProperty(READ_TYPENAME)
};
} else if (process != null && process.getInput().getTableName() != null) {
// One table / schema
typenames = new String[]{
process.getInput().getTableName()
};
}
if (typenames == null) {
// All tables / schema's
typenames = dataStore2Read.getTypeNames();
}
return typenames;
}
}
| B3Partners/b3p-datastorelinker | src/main/java/nl/b3p/geotools/data/linker/DataStoreLinker.java | 6,824 | /*TODO: Onderscheid maken tussen fatal Exception en niet Fatal Exception. Als er een Fatal
wordt gethrowed dan moet er worden gestopt met features processen.*/ | block_comment | nl | package nl.b3p.geotools.data.linker;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.datastorelinker.entity.Database;
import nl.b3p.datastorelinker.util.Namespaces;
import nl.b3p.datastorelinker.util.Util;
import nl.b3p.geotools.data.linker.blocks.Action;
import nl.b3p.geotools.data.linker.blocks.WritableAction;
import nl.b3p.geotools.data.linker.feature.EasyFeature;
import nl.b3p.geotools.data.linker.util.LocalizationUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.DataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.oracle.OracleNGDataStoreFactory;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.jdbc.JDBCDataStore;
import org.geotools.jdbc.JDBCFeatureStore;
import org.geotools.jdbc.PrimaryKey;
import org.jdom2.Element;
import org.jdom2.input.DOMBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
/**
* Convert batch to actionList and execute it
*
* @author Gertjan Al, B3Partners
*/
public class DataStoreLinker implements Runnable {
private static final Log log = LogFactory.getLog(DataStoreLinker.class);
private final static ResourceBundle resources = LocalizationUtil.getResources();
public static final String ACTIONLIST_PREFIX = "actionlist";
public static final String ACTION_PREFIX = "action";
public static final String TYPE_PREFIX = "type";
public static final String SETTINGS_PREFIX = "settings";
public static final String DATASTORE2READ_PREFIX = "read.datastore.";
public static final String READ_TYPENAME = "read.typename";
protected static final String DEFAULT_WRITER = "ActionCombo_GeometrySingle_Writer";
public static String DEFAULT_SMTPHOST = "kmail.b3partners.nl";
public static String DEFAULT_FROM = "[email protected]";
protected Status status;
protected DataStore dataStore2Read;
protected ActionList actionList;
protected Properties batch;
protected nl.b3p.datastorelinker.entity.Process process;
protected boolean disposed;
private int exceptionLogCount = 0;
private static final int MAX_EXCEPTION_LOG_COUNT = 10;
public static final String TYPE_ORACLE = "oracle";
public static final String TYPE_POSTGIS = "postgis";
public static final String TYPE_WFS = "wfs";
public synchronized Status getStatus() {
return status;
}
public DataStoreLinker(nl.b3p.datastorelinker.entity.Process process) throws Exception {
init(process);
dataStore2Read = openDataStore();
actionList = createActionList();
postInit();
}
public DataStoreLinker(Properties batch) throws Exception {
init(batch);
dataStore2Read = createDataStore2Read(batch);
actionList = createActionList(batch);
postInit();
}
public DataStoreLinker(Map<String, Object> input, Map<String, Object> actions, Properties batch) throws Exception {
init(batch);
dataStore2Read = openDataStore(input);
actionList = createActionList(actions);
postInit();
}
private void init(nl.b3p.datastorelinker.entity.Process process) throws ConfigurationException, IOException {
this.process = process;
disposed = false;
status = new Status(process);
}
private void init(Properties batch) throws ConfigurationException, IOException {
this.batch = batch;
disposed = false;
status = new Status(batch);
}
/**
* Calculating the size can take a very long time depending on the
* implementation of the chosen datastore. Some implementations walk through
* all features to calculate the size.
*
* @throws IOException
*/
private void calculateSizes() throws IOException {
int totalFeatureSize = 0;
if (dataStore2Read != null) {
for (String typeName2Read : getTypeNames()) {
FeatureCollection fc = dataStore2Read.getFeatureSource(typeName2Read).getFeatures();
totalFeatureSize += fc.size();
}
}
status.setTotalFeatureSize(totalFeatureSize);
}
private void postInit() throws IOException {
calculateSizes();
log.info("dsl init complete.");
}
public void run() {
try {
process();
} catch (Exception ex) {
log.error(ex);
}
}
public boolean isDisposed(){
return disposed;
}
public synchronized void dispose() throws Exception {
if (!disposed) {
try {
dataStore2Read.dispose();
actionList.close();
} finally {
disposed = true;
}
}
}
/**
* Process all features in dataStore2Read
*
* @throws Exception generic exception
*/
public void process() throws Exception {
if (disposed) {
throw new Exception("Dsl already used. Please create a new instance of this class");
}
try {
for (String typeName2Read : getTypeNames()) {
processTypeName(typeName2Read);
}
} finally {
try {
if (batch != null) {
DataStoreLinkerMail.mail(batch, status.getNonFatalErrorReport("\n", 3));
} else if (process != null) {
DataStoreLinkerMail.mail(process, status.getNonFatalErrorReport("\n", 3));
}
} catch (Exception mex) {
status.addNonFatalError(mex.getLocalizedMessage(), "");
}
log.info("Error report: " + status.getNonFatalErrorReport("\n", 3));
dispose();
}
}
private void processTypeName(String typeName2Read) throws Exception, IOException {
SimpleFeature feature = null;
String filterName = process.getFilter();
Query query = new Query();
if(filterName!=null){
Filter filter = ECQL.toFilter(filterName);
query.setFilter(filter);
}
FeatureCollection fc = dataStore2Read.getFeatureSource(typeName2Read).getFeatures(query);
FeatureIterator iterator = fc.features();
PrimaryKey pk = null;
if (dataStore2Read != null && (dataStore2Read instanceof JDBCDataStore)) {
FeatureSource fs = ((JDBCDataStore) dataStore2Read).getFeatureSource(typeName2Read);
if (fs instanceof JDBCFeatureStore) {
pk = ((JDBCFeatureStore) fs).getPrimaryKey();
}
}
Map properties = null;
if (batch != null) {
properties = new HashMap(batch);
} else if (process != null) {
properties = process.toOutputMap();
}
try {
while (iterator.hasNext()) {
try {
feature = (SimpleFeature) iterator.next();
} catch (Exception ex) {
log.error("Fout bij inlezen feature ", ex);
String id = null;
if (feature != null ) {
id = feature.getID();
}
status.addNonFatalError(ExceptionUtils.getRootCauseMessage(ex), id);
status.incrementVisitedFeatures();
continue;
}
Map userData = feature.getUserData();
if (pk != null && userData != null) {
userData.put("sourcePks", pk);
}
processFeature(feature);
if (status.getVisitedFeatures() % 10000 == 0) {
log.info("" + status.getVisitedFeatures() + "/" + status.getTotalFeatureSize() + " features processed (" + typeName2Read + ")");
}
if (status.isInterrupted()) {
actionList.flush(status, properties);
actionList.processPostCollectionActions(status, properties);
throw new InterruptedException("User canceled the process.");
}
}
actionList.flush(status, properties);
log.info("Try to do the Post actions");
actionList.processPostCollectionActions(status, properties);
log.info("Total of: " + status.getVisitedFeatures() + " features processed (" + typeName2Read + ")");
} finally {
iterator.close();
JpaUtilServlet.closeThreadEntityManager();
}
}
private void processFeature(SimpleFeature feature) throws Exception {
if (!mustProcessFeature()) {
return;
}
/*TODO: Onderscheid maken<SUF>*/
try {
EasyFeature ef = new EasyFeature(feature);
if (ef.getFeature().getDefaultGeometry() != null) {
// repair if necessary (e.g. no geom metadata in oracle)
ef.repairGeometry();
}
if (actionList.process(ef) != null) {
// hier niet zetten, maar bij writer action
//status.incrementProcessedFeatures();
}
} catch (IllegalStateException ex) {
status.addWriteError(ex.getLocalizedMessage(), feature.getID());
log.error("Cannot write to datastore: ",ex);
throw ex;
} catch (Exception e) {
if (exceptionLogCount++ < MAX_EXCEPTION_LOG_COUNT) {
log.error("Exception tijdens processen van feature (exception nr. " + exceptionLogCount + " van max " + MAX_EXCEPTION_LOG_COUNT + " die worden gelogd)", e);
}
status.addNonFatalError(ExceptionUtils.getRootCauseMessage(e), feature.getID());
}
status.incrementVisitedFeatures();
}
private boolean mustProcessFeature() {
return status.getVisitedFeatures() >= status.getFeatureStart() && ((status.getVisitedFeatures() <= status.getFeatureEnd() && status.getFeatureEnd() >= 0)
|| (status.getFeatureEnd() < 0));
}
/**
* Create dataStore2Read from properties
*/
private DataStore createDataStore2Read(Properties batch) throws Exception {
return openDataStore(propertiesToMaps(batch, DATASTORE2READ_PREFIX));
}
private ActionList createActionList() throws Exception {
ActionList newActionList = new ActionList();
String outputWriter = null;
org.w3c.dom.Element actions = process.getActions();
if (actions != null) {
Element actionsElement = new DOMBuilder().build(actions);
for (Object actionObject : actionsElement.getChildren("action", Namespaces.DSL_NAMESPACE)) {
Element actionElement = (Element) actionObject;
Map<String, Object> parameters = new HashMap<String, Object>();
Element parametersElement = actionElement.getChild("parameters", Namespaces.DSL_NAMESPACE);
if (parametersElement != null) {
for (Object parameterObject : parametersElement.getChildren("parameter", Namespaces.DSL_NAMESPACE)) {
Element parameterElement = (Element) parameterObject;
String key = parameterElement.getChildTextTrim("paramId", Namespaces.DSL_NAMESPACE);
Object value = parameterElement.getChildTextTrim("value", Namespaces.DSL_NAMESPACE);
parameters.put(key, value);
}
}
String actionType = actionElement.getChildTextTrim("type", Namespaces.DSL_NAMESPACE);
//if (ActionFactory.isDataStoreAction(actionType)) { // lelijke constructie; nooit meer gebruiken aub
// FIXME: we moeten echt ophouden die oude meuk te ondersteunen.
// De doorgegeven class moet natuurlijk gewoon de fully qualified class name zijn:
// i.e.: nl.b3p.datastorelinker.actions.MyAction
//if (WritableAction.class.isAssignableFrom(Class.forName(actionType))) {
if (WritableAction.class.isAssignableFrom(
Class.forName("nl.b3p.geotools.data.linker.blocks." + actionType))) {
outputWriter = actionType;
} else {
newActionList.add(ActionFactory.createAction(actionType, parameters));
}
}
}
// Finally: add output database to action list:
if (outputWriter == null) {
newActionList.add(ActionFactory.createAction(DEFAULT_WRITER,
process.toOutputMap()));
} else {
newActionList.add(ActionFactory.createAction(outputWriter,
process.toOutputMap()));
}
log.debug("Actions to be executed (in this order):");
for (Action action : newActionList) {
log.debug(action.getName());
}
return newActionList;
}
private Boolean parseBoolean(String bool) throws Exception {
if (bool.equalsIgnoreCase("true")) {
return Boolean.TRUE;
} else if (bool.equalsIgnoreCase("false")) {
return Boolean.FALSE;
} else {
throw new Exception(MessageFormat.format(resources.getString("parseBooleanFailed"), bool));
}
}
/**
* Create actionList from batch
*/
private ActionList createActionList(Properties batch) throws Exception {
Map<String, Object> actionlistParams = propertiesToMaps(batch, ACTIONLIST_PREFIX + "." + ACTION_PREFIX);
return createActionList(actionlistParams);
}
public static ActionList createActionList(Map<String, Object> actionlistParams) throws Exception {
ActionList actionList = new ActionList();
int count = 1;
while (true) {
if (actionlistParams.containsKey(Integer.toString(count))) {
Map<String, Object> params = (Map) actionlistParams.get(Integer.toString(count));
if (params.containsKey(TYPE_PREFIX)) {
if (params.containsKey(SETTINGS_PREFIX)) {
if (params.get(TYPE_PREFIX) instanceof String && params.get(SETTINGS_PREFIX) instanceof Map) {
actionList.add(ActionFactory.createAction((String) params.get(TYPE_PREFIX), (Map) params.get(SETTINGS_PREFIX)));
} else {
throw new Exception("Expected " + ACTION_PREFIX + Integer.toString(count) + "." + TYPE_PREFIX + " to be String and " + ACTION_PREFIX + Integer.toString(count) + "." + SETTINGS_PREFIX + " to be a Map");
}
} else {
if (params.get(TYPE_PREFIX) instanceof String) {
actionList.add(ActionFactory.createAction((String) params.get(TYPE_PREFIX), new HashMap()));
} else {
throw new Exception("Expected " + ACTION_PREFIX + Integer.toString(count) + "." + TYPE_PREFIX + " to be String");
}
}
/*
if (params.get(TYPE_PREFIX) instanceof String && params.get(SETTINGS_PREFIX) instanceof Map) {
actionList.add(ActionFactory.createAction((String) params.get(TYPE_PREFIX), (Map) params.get(SETTINGS_PREFIX)));
} else {
throw new Exception("Expected " + ACTION_PREFIX + Integer.toString(count) + "." + TYPE_PREFIX + " to be String and " + ACTION_PREFIX + Integer.toString(count) + "." + SETTINGS_PREFIX + " to be a Map");
}
* */
} else {
throw new Exception("No type found for action" + Integer.toString(count));
}
} else {
break;
}
count++;
}
return actionList;
}
private DataStore openDataStore() throws ConfigurationException, Exception {
Database database = process.getInput().getDatabase();
String file = process.getInput().getFile();
if (database != null) {
return openDataStore(database);
} else if (file != null) { // TODO: this should be a file now; change xsd to reflect this "xsd:choice"
return openDataStore(file);
} else { // safeguard:
throw new ConfigurationException("Xml configuration exception: No input database or file specified.");
}
}
public static DataStore openDataStore(Database database) throws ConfigurationException, Exception {
return openDataStore(database.toGeotoolsDataStoreParametersMap());
}
public static DataStore openDataStore(String file) throws ConfigurationException, Exception {
return openDataStore(Util.fileToMap(new File(file)));
}
public static DataStore openDataStore(Map params) throws Exception {
return openDataStore(params, false);
}
/**
* Open a dataStore (save). If create new is set to true, a datastore wil be
* created even if the file is not there yet.
*
* @param params the datastore parameters
* @param createNew create new or not
* @return boolean indicating success
* @throws Exception generic exception
*/
public static DataStore openDataStore(Map params, boolean createNew) throws Exception {
log.debug("openDataStore with: " + params);
DataStore dataStore = null;
// TODO: indien je bij het aanmaken van een nieuwe datastore primary
// keys wil opgeven dan kan dat via PK_METADATA_TABLE.
// Nu nog buggy, fix in 8.7
String dbType = (String) params.get("dbtype");
if (dbType != null && dbType.equals(TYPE_ORACLE)) {
params.put(OracleNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
params.put("min connections", 0);
params.put("max connections", 50);
params.put("connection timeout", 60);
params.put("validate connections", Boolean.FALSE);
log.debug("Created OracleNGDataStoreFactory with: " + params);
/* TODO: nagaan of je Geotools naar eigen gemaakte
* geometry columns kunt laten kijken */
//params.put("Geometry metadata table", "GEOMETRY_COLUMNS");
return (new OracleNGDataStoreFactory()).createDataStore(params);
} else if (dbType != null && dbType.equals(TYPE_POSTGIS)) {
params.put(PostgisNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
params.put("min connections", 0);
params.put("max connections", 50);
params.put("connection timeout", 60);
params.put("validate connections", Boolean.FALSE);
log.debug("Created PostgisNGDataStoreFactory with: " + params);
return (new PostgisNGDataStoreFactory()).createDataStore(params);
} else if (dbType != null && dbType.equals(TYPE_WFS)){
log.debug("Created WFSDataStoreFactory with: " + params);
return (new WFSDataStoreFactory()).createDataStore(params);
}
String errormsg = "DataStore could not be found using parameters";
try {
dataStore = DataStoreFinder.getDataStore(params);
if (dataStore == null && createNew) {
if (params.containsKey("url")) {
String url = (String) params.get("url");
if (url.lastIndexOf(".shp") == (url.length() - ".shp".length())) {
ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
// FileDataStoreFactorySpi factory = new IndexedShapefileDataStoreFactory();
params.put("url", new File(url).toURL());
dataStore = factory.createNewDataStore(params);
} else {
log.warn("Can not create a new datastore, filetype unknown.");
}
}
}
} catch (NullPointerException nullEx) {
if (!urlExists(params)) {
throw new Exception("URL in parameters seems to point to a non-existing file \n\n" + params.toString());
} else {
throw new Exception(errormsg + " " + params.toString());
}
}
if (dataStore == null) {
if (!urlExists(params)) {
throw new Exception("URL in parameters may point to a non-existing file \n\n" + params.toString());
} else {
throw new Exception("DataStoreFinder returned null for \n\n" + params.toString());
}
} else {
log.debug("DataStore class: " + dataStore.getClass());
return dataStore;
}
}
private static boolean urlExists(Map params) {
try {
if (params.containsKey("url")) {
if (params.get("url") instanceof URL) {
URL url = (URL) params.get("url");
log.debug("Checking url exists: " + url);
File file = new File(url.toURI());
log.debug("Checking file url exists: " + file.getAbsolutePath());
return file.exists();
} else if (params.get("url") instanceof String) {
String url = params.get("url").toString();
log.debug("Checking url exists: " + url);
File file = new File(url);
log.debug("Checking file url exists: " + file.getAbsolutePath());
return file.exists();
}
}
} catch (URISyntaxException uriEx) {
return false;
}
return true;
}
public static String getSaveProp(Properties batch, String key, String defaultValue) {
if (batch.containsKey(key)) {
return batch.getProperty(key);
} else {
return defaultValue;
}
}
/**
* Make HashMap structure from propertylist
*
* @param batch Original properties list
* @param filter Specified to filter start of properties, like
* 'actionlist.action'
* @return the mapped propertylist
* @throws IOException general IOexception
*/
public static Map<String, Object> propertiesToMaps(Properties batch, String filter) throws IOException {
Map<String, Object> map = new HashMap();
Iterator iter = batch.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
if (key.startsWith(filter)) {
String value = batch.getProperty(key);
String keypart = key.substring(filter.length());
Map<String, Object> stepIn = map;
while (keypart.contains(".")) {
String step = keypart.substring(0, keypart.indexOf("."));
keypart = keypart.substring(keypart.indexOf(".") + 1);
if (stepIn.containsKey(step)) {
if (stepIn.get(step) instanceof Map) {
stepIn = (Map) stepIn.get(step);
} else {
throw new IOException("Tried to save settingsMap for property '" + key + "', but property has already a value?\nValue = '" + stepIn.get(step).toString() + "'");
}
} else {
Map<String, Object> newStep = new HashMap();
stepIn.put(step, newStep);
stepIn = newStep;
}
}
if (value.toLowerCase().equals("false")) {
stepIn.put(keypart, false);
} else if (value.toLowerCase().equals("true")) {
stepIn.put(keypart, true);
} else if (keypart.toLowerCase().equals("url")) {
File file = new File(value);
if (file.exists()) {
stepIn.put(keypart, file.toURL());
} else {
stepIn.put(keypart, value);
}
} else {
stepIn.put(keypart, value);
}
}
}
return map;
}
private String[] getTypeNames() throws IOException {
String[] typenames = null;
if (batch != null && batch.containsKey(READ_TYPENAME)) {
// One table / schema
typenames = new String[]{
batch.getProperty(READ_TYPENAME)
};
} else if (process != null && process.getInput().getTableName() != null) {
// One table / schema
typenames = new String[]{
process.getInput().getTableName()
};
}
if (typenames == null) {
// All tables / schema's
typenames = dataStore2Read.getTypeNames();
}
return typenames;
}
}
|
143928_27 | package nl.b3p.gis.viewer;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import nl.b3p.gis.viewer.admindata.CollectAdmindata;
import nl.b3p.gis.viewer.db.CMSMenu;
import nl.b3p.gis.viewer.db.CMSMenuItem;
import nl.b3p.gis.viewer.db.CMSPagina;
import nl.b3p.gis.viewer.db.Clusters;
import nl.b3p.gis.viewer.db.Gegevensbron;
import nl.b3p.gis.viewer.db.Tekstblok;
import nl.b3p.gis.viewer.db.Themas;
import nl.b3p.gis.viewer.db.UserKaartlaag;
import nl.b3p.gis.viewer.services.GisPrincipal;
import nl.b3p.gis.viewer.services.HibernateUtil;
import nl.b3p.gis.viewer.services.SpatialUtil;
import nl.b3p.gis.viewer.struts.BaseHibernateAction;
import nl.b3p.wms.capabilities.Layer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;
import org.hibernate.Session;
public abstract class BaseGisAction extends BaseHibernateAction {
private static final Log logger = LogFactory.getLog(BaseGisAction.class);
public static final String URL_AUTH = "code";
public static final String APP_AUTH = "appCode";
public static final String CMS_PAGE_ID = "cmsPageId";
protected static final double DEFAULTTOLERANCE = 5.0;
protected static final String ACKNOWLEDGE_MESSAGES = "acknowledgeMessages";
private static final Pattern NONLATIN = Pattern.compile("[^\\w-]");
private static final Pattern WHITESPACE = Pattern.compile("[\\s]");
protected void createLists(DynaValidatorForm dynaForm, HttpServletRequest request) throws Exception {
GisPrincipal gp = GisPrincipal.getGisPrincipal(request);
String code = null;
if (gp != null) {
code = gp.getCode();
}
// zet kaartenbalie url
request.setAttribute("kburl", HibernateUtil.createPersonalKbUrl(code));
request.setAttribute("kbcode", code);
String organizationcode = CollectAdmindata.getOrganizationCode(request);
if (organizationcode != null && organizationcode.length() > 0) {
request.setAttribute("organizationcode", organizationcode);
}
}
/**
* Haal alle themas op uit de database door middel van een in het request
* meegegeven thema id comma seperated list.
*
* @param mapping ActionMapping
* @param dynaForm DynaValidatorForm
* @param request HttpServletRequest
*
* @return Themas
*
* @see Themas
*/
protected ArrayList getThemas(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request) {
String themaids = (String) request.getParameter("themaid");
if (themaids == null || themaids.length() == 0) {
return null;
}
String[] ids = themaids.split(",");
ArrayList themas = null;
for (int i = 0; i < ids.length; i++) {
Themas t = getThema(ids[i], request);
if (t != null) {
if (themas == null) {
themas = new ArrayList();
}
themas.add(t);
}
}
if (themas != null && themas.size() > 0) {
Collections.sort(themas);
}
return themas;
}
/**
* Haal een Thema op uit de database door middel van een in het request
* meegegeven thema id.
*
* @param mapping ActionMapping
* @param dynaForm DynaValidatorForm
* @param request HttpServletRequest
*
* @return Themas
*
* @see Themas
*/
protected Themas getThema(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request) {
String themaid = (String) request.getParameter("themaid");
return getThema(themaid, request);
}
protected Gegevensbron getGegevensbron(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request) {
String bronId = (String) request.getParameter("themaid");
return getGegevensbron(bronId, request);
}
private Gegevensbron getGegevensbron(String bronId, HttpServletRequest request) {
Gegevensbron gb = SpatialUtil.getGegevensbron(bronId);
if (!HibernateUtil.isCheckLoginKaartenbalie()) {
return gb;
}
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user == null) {
return null;
}
List layersFromRoles = user.getLayerNames(false);
if (layersFromRoles == null) {
return null;
}
return gb;
}
protected Themas getThema(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request, boolean analysethemaid) {
String themaid = "";
if (analysethemaid) {
themaid = (String) request.getParameter("analysethemaid");
} else {
themaid = (String) request.getParameter("themaid");
}
return getThema(themaid, request);
}
/**
* Get the thema en doe wat checks
*/
private Themas getThema(String themaid, HttpServletRequest request) {
Themas t = SpatialUtil.getThema(themaid);
if (t == null) {
return null;
}
/*
if (!HibernateUtil.isCheckLoginKaartenbalie()) {
logger.debug("No kb login required, thema: " + t == null ? "<null>" : t.getNaam());
return t;
}
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user == null) {
logger.debug("No user found, thema: " + t == null ? "<null>" : t.getNaam());
return null;
}
List layersFromRoles = user.getLayerNames(false);
if (layersFromRoles == null) {
logger.debug("No layers found, thema: " + t == null ? "<null>" : t.getNaam());
return null;
}
// Check de rechten op alle layers uit het thema
if (!checkThemaLayers(t, layersFromRoles)) {
logger.debug("No rights for layers found, thema: " + t == null ? "<null>" : t.getNaam());
return null;
}
*/
return t;
}
/**
* Indien een cluster wordt meegegeven dan voegt deze functie ook de layers
* die niet als thema geconfigureerd zijn, maar toch als role aan de
* principal zijn meegegeven als dummy thema toe. Als dit niet de bedoeling
* is dan dient null als cluster meegegeven te worden.
*
* @param locatie
* @param request
* @return
*/
protected List getValidThemas(boolean locatie, List ctl, HttpServletRequest request) {
List configuredThemasList = SpatialUtil.getValidThemas(locatie);
List layersFromRoles = null;
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user != null) {
layersFromRoles = user.getLayerNames(false);
}
if (layersFromRoles == null) {
return null;
}
// Voeg alle themas toe die layers hebben die volgens de rollen
// acceptabel zijn (voldoende rechten dus).
List layersFound = new ArrayList();
List checkedThemaList = new ArrayList();
if (configuredThemasList != null) {
Iterator it2 = configuredThemasList.iterator();
while (it2.hasNext()) {
Themas t = (Themas) it2.next();
// Als geen check via kaartenbalie dan alle layers doorgeven
if (checkThemaLayers(t, layersFromRoles)
|| !HibernateUtil.isCheckLoginKaartenbalie()) {
checkedThemaList.add(t);
layersFound.add(t.getWms_layers_real());
}
}
}
// als alleen configureerde layers getoond mogen worden,
// dan hier stoppen
if (!HibernateUtil.isUseKaartenbalieCluster()) {
return checkedThemaList;
}
//zoek of maak een cluster aan voor als er kaarten worden gevonden die geen thema hebben.
Clusters c = SpatialUtil.getDefaultCluster();
if (c == null) {
c = new Clusters();
c.setNaam(HibernateUtil.getKaartenbalieCluster());
c.setParent(null);
}
Iterator it = layersFromRoles.iterator();
int tid = 100000;
ArrayList extraThemaList = new ArrayList();
// Kijk welke lagen uit de rollen nog niet zijn toegevoegd
// en voeg deze alsnog toe via dummy thema en cluster.
while (it.hasNext()) {
String layer = (String) it.next();
if (layersFound.contains(layer)) {
continue;
}
// Layer bestaat nog niet dus aanmaken
Layer l = user.getLayer(layer);
if (l != null) {
Themas t = new Themas();
t.setNaam(l.getTitle());
t.setId(new Integer(tid++));
if (user.hasLegendGraphic(l)) {
t.setWms_legendlayer_real(layer);
}
if ("1".equalsIgnoreCase(l.getQueryable())) {
t.setWms_querylayers_real(layer);
}
t.setWms_layers_real(layer);
t.setCluster(c);
// voeg extra laag als nieuw thema toe
extraThemaList.add(t);
}
}
if (extraThemaList.size() > 0) {
if (ctl == null) {
ctl = new ArrayList();
}
ctl.add(c);
for (int i = 0; i < extraThemaList.size(); i++) {
checkedThemaList.add(extraThemaList.get(i));
}
}
return checkedThemaList;
}
/**
* Indien een cluster wordt meegegeven dan voegt deze functie ook de layers
* die niet als thema geconfigureerd zijn, maar toch als role aan de
* principal zijn meegegeven als dummy thema toe. Als dit niet de bedoeling
* is dan dient null als cluster meegegeven te worden.
*
* @param locatie
* @param request
* @return
*/
protected List getValidUserThemas(boolean locatie, List ctl, HttpServletRequest request) {
List configuredThemasList = SpatialUtil.getValidThemas(locatie);
List layersFromRoles = null;
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user != null) {
layersFromRoles = user.getLayerNames(false);
}
if (layersFromRoles == null) {
return null;
}
/* ophalen user kaartlagen om custom boom op te bouwen */
List<UserKaartlaag> lagen = SpatialUtil.getUserKaartLagen(user.getCode());
// Voeg alle themas toe die layers hebben die volgens de rollen
// acceptabel zijn (voldoende rechten dus).
List layersFound = new ArrayList();
List checkedThemaList = new ArrayList();
if (configuredThemasList != null) {
Iterator it2 = configuredThemasList.iterator();
while (it2.hasNext()) {
Themas t = (Themas) it2.next();
/* controleren of thema in user kaartlagen voorkomt */
if (lagen != null && lagen.size() > 0) {
boolean isInList = false;
for (UserKaartlaag laag : lagen) {
if (laag.getThemaid() == t.getId()) {
isInList = true;
}
}
if (!isInList) {
continue;
}
}
// Als geen check via kaartenbalie dan alle layers doorgeven
if (checkThemaLayers(t, layersFromRoles)
|| !HibernateUtil.isCheckLoginKaartenbalie()) {
checkedThemaList.add(t);
layersFound.add(t.getWms_layers_real());
}
}
}
// als alleen configureerde layers getoond mogen worden,
// dan hier stoppen
if (!HibernateUtil.isUseKaartenbalieCluster()) {
return checkedThemaList;
}
//zoek of maak een cluster aan voor als er kaarten worden gevonden die geen thema hebben.
Clusters c = SpatialUtil.getDefaultCluster();
if (c == null) {
c = new Clusters();
c.setNaam(HibernateUtil.getKaartenbalieCluster());
c.setParent(null);
}
Iterator it = layersFromRoles.iterator();
int tid = 100000;
ArrayList extraThemaList = new ArrayList();
// Kijk welke lagen uit de rollen nog niet zijn toegevoegd
// en voeg deze alsnog toe via dummy thema en cluster.
while (it.hasNext()) {
String layer = (String) it.next();
if (layersFound.contains(layer)) {
continue;
}
// Layer bestaat nog niet dus aanmaken
Layer l = user.getLayer(layer);
if (l != null) {
Themas t = new Themas();
t.setNaam(l.getTitle());
t.setId(new Integer(tid++));
if (user.hasLegendGraphic(l)) {
t.setWms_legendlayer_real(layer);
}
if ("1".equalsIgnoreCase(l.getQueryable())) {
t.setWms_querylayers_real(layer);
}
t.setWms_layers_real(layer);
t.setCluster(c);
// voeg extra laag als nieuw thema toe
extraThemaList.add(t);
}
}
if (extraThemaList.size() > 0) {
if (ctl == null) {
ctl = new ArrayList();
}
ctl.add(c);
for (int i = 0; i < extraThemaList.size(); i++) {
checkedThemaList.add(extraThemaList.get(i));
}
}
return checkedThemaList;
}
/**
* Voeg alle layers samen voor een thema en controleer of de gebruiker voor
* alle layers rechten heeft. Zo nee, thema niet toevoegen.
*
* @param t
* @param request
* @return
*/
protected boolean checkThemaLayers(Themas t, List acceptableLayers) {
if (t == null || acceptableLayers == null) {
return false;
}
String wmsls = t.getWms_layers_real();
if (wmsls == null || wmsls.length() == 0) {
return false;
}
// Dit is te streng, alleen op wms layer checken
// String wmsqls = t.getWms_querylayers_real();
// if (wmsqls!=null && wmsqls.length()>0)
// wmsls += "," + wmsqls;
// String wmslls = t.getWms_legendlayer_real();
// if (wmslls!=null && wmslls.length()>0)
// wmsls += "," + wmslls;
String[] wmsla = wmsls.split(",");
for (int i = 0; i < wmsla.length; i++) {
if (!acceptableLayers.contains(wmsla[i])) {
return false;
}
}
return true;
}
/**
* Een protected methode het object thema ophaalt dat hoort bij een bepaald
* id.
*
* @param identifier String which identifies the object thema to be found.
*
* @return a Themas object representing the object thema.
*
*/
protected Themas getObjectThema(String identifier) {
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
Themas objectThema = null;
try {
int id = Integer.parseInt(identifier);
objectThema = (Themas) sess.get(Themas.class, new Integer(id));
} catch (NumberFormatException nfe) {
objectThema = (Themas) sess.get(Themas.class, identifier);
}
return objectThema;
}
protected List getTekstBlokken(Integer cmsPageId) {
List<Tekstblok> tekstBlokken = new ArrayList();
if (cmsPageId != null && cmsPageId > 0) {
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
tekstBlokken = sess.createQuery("from Tekstblok where cms_pagina = :id"
+ " order by volgordenr, cdate").setParameter("id", cmsPageId).list();
}
return tekstBlokken;
}
protected static void setCMSPageFromRequest(HttpServletRequest request) {
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
String param = request.getParameter(BaseGisAction.CMS_PAGE_ID);
Integer cmsPageId = null;
if (param != null && !param.equals("")) {
cmsPageId = new Integer(param);
}
/* CMS Theme klaarzetten */
if (cmsPageId != null && cmsPageId > 0) {
CMSPagina cmsPage = (CMSPagina) sess.get(CMSPagina.class, cmsPageId);
request.setAttribute("cmsPageId", cmsPageId);
if (cmsPage != null && cmsPage.getThema() != null && !cmsPage.getThema().equals("")) {
request.setAttribute("theme", cmsPage.getThema());
}
}
}
protected CMSPagina getCMSPage(Integer pageID) {
if (pageID == null || pageID < 1) {
return null;
}
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
return (CMSPagina) sess.get(CMSPagina.class, pageID);
}
protected CMSMenu getCMSMenu(Integer id) {
if (id == null || id < 1) {
return null;
}
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
return (CMSMenu) sess.get(CMSMenu.class, id);
}
protected List<CMSMenuItem> getCMSMenuItems(Integer menuId) {
List<CMSMenuItem> menuItems = new ArrayList<CMSMenuItem>();
if (menuId == null || menuId < 1) {
return menuItems;
}
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
menuItems = sess.createQuery("select item from CMSMenuItem item"
+ " where item.id in (select cmsMenuItems.id"
+ " from CMSMenu menu inner join menu.cmsMenuItems cmsMenuItems"
+ " where menu.id = :menuId) order by item.volgordenr DESC")
.setParameter("menuId", menuId)
.list();
return menuItems;
}
protected List<CMSPagina> getCMSPaginas() {
List<CMSPagina> paginas;
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
paginas = sess.createQuery("from CMSPagina order by id").list();
return paginas;
}
protected String prettifyCMSPageUrl(HttpServletRequest request, CMSPagina cmsPage) {
String baseURL = request.getRequestURL().toString().replace(request.getRequestURI().substring(0), request.getContextPath());
String nowhitespace = WHITESPACE.matcher(cmsPage.getTitel()).replaceAll("-");
String normalized = Normalizer.normalize(nowhitespace, Normalizer.Form.NFD);
String slug = NONLATIN.matcher(normalized).replaceAll("");
String url = slug.toLowerCase(Locale.ENGLISH);
return baseURL + "/cms/" + cmsPage.getId() + "/" + url + ".htm";
}
}
| B3Partners/b3p-gisviewer | src/main/java/nl/b3p/gis/viewer/BaseGisAction.java | 5,824 | //zoek of maak een cluster aan voor als er kaarten worden gevonden die geen thema hebben. | line_comment | nl | package nl.b3p.gis.viewer;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import nl.b3p.gis.viewer.admindata.CollectAdmindata;
import nl.b3p.gis.viewer.db.CMSMenu;
import nl.b3p.gis.viewer.db.CMSMenuItem;
import nl.b3p.gis.viewer.db.CMSPagina;
import nl.b3p.gis.viewer.db.Clusters;
import nl.b3p.gis.viewer.db.Gegevensbron;
import nl.b3p.gis.viewer.db.Tekstblok;
import nl.b3p.gis.viewer.db.Themas;
import nl.b3p.gis.viewer.db.UserKaartlaag;
import nl.b3p.gis.viewer.services.GisPrincipal;
import nl.b3p.gis.viewer.services.HibernateUtil;
import nl.b3p.gis.viewer.services.SpatialUtil;
import nl.b3p.gis.viewer.struts.BaseHibernateAction;
import nl.b3p.wms.capabilities.Layer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;
import org.hibernate.Session;
public abstract class BaseGisAction extends BaseHibernateAction {
private static final Log logger = LogFactory.getLog(BaseGisAction.class);
public static final String URL_AUTH = "code";
public static final String APP_AUTH = "appCode";
public static final String CMS_PAGE_ID = "cmsPageId";
protected static final double DEFAULTTOLERANCE = 5.0;
protected static final String ACKNOWLEDGE_MESSAGES = "acknowledgeMessages";
private static final Pattern NONLATIN = Pattern.compile("[^\\w-]");
private static final Pattern WHITESPACE = Pattern.compile("[\\s]");
protected void createLists(DynaValidatorForm dynaForm, HttpServletRequest request) throws Exception {
GisPrincipal gp = GisPrincipal.getGisPrincipal(request);
String code = null;
if (gp != null) {
code = gp.getCode();
}
// zet kaartenbalie url
request.setAttribute("kburl", HibernateUtil.createPersonalKbUrl(code));
request.setAttribute("kbcode", code);
String organizationcode = CollectAdmindata.getOrganizationCode(request);
if (organizationcode != null && organizationcode.length() > 0) {
request.setAttribute("organizationcode", organizationcode);
}
}
/**
* Haal alle themas op uit de database door middel van een in het request
* meegegeven thema id comma seperated list.
*
* @param mapping ActionMapping
* @param dynaForm DynaValidatorForm
* @param request HttpServletRequest
*
* @return Themas
*
* @see Themas
*/
protected ArrayList getThemas(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request) {
String themaids = (String) request.getParameter("themaid");
if (themaids == null || themaids.length() == 0) {
return null;
}
String[] ids = themaids.split(",");
ArrayList themas = null;
for (int i = 0; i < ids.length; i++) {
Themas t = getThema(ids[i], request);
if (t != null) {
if (themas == null) {
themas = new ArrayList();
}
themas.add(t);
}
}
if (themas != null && themas.size() > 0) {
Collections.sort(themas);
}
return themas;
}
/**
* Haal een Thema op uit de database door middel van een in het request
* meegegeven thema id.
*
* @param mapping ActionMapping
* @param dynaForm DynaValidatorForm
* @param request HttpServletRequest
*
* @return Themas
*
* @see Themas
*/
protected Themas getThema(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request) {
String themaid = (String) request.getParameter("themaid");
return getThema(themaid, request);
}
protected Gegevensbron getGegevensbron(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request) {
String bronId = (String) request.getParameter("themaid");
return getGegevensbron(bronId, request);
}
private Gegevensbron getGegevensbron(String bronId, HttpServletRequest request) {
Gegevensbron gb = SpatialUtil.getGegevensbron(bronId);
if (!HibernateUtil.isCheckLoginKaartenbalie()) {
return gb;
}
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user == null) {
return null;
}
List layersFromRoles = user.getLayerNames(false);
if (layersFromRoles == null) {
return null;
}
return gb;
}
protected Themas getThema(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request, boolean analysethemaid) {
String themaid = "";
if (analysethemaid) {
themaid = (String) request.getParameter("analysethemaid");
} else {
themaid = (String) request.getParameter("themaid");
}
return getThema(themaid, request);
}
/**
* Get the thema en doe wat checks
*/
private Themas getThema(String themaid, HttpServletRequest request) {
Themas t = SpatialUtil.getThema(themaid);
if (t == null) {
return null;
}
/*
if (!HibernateUtil.isCheckLoginKaartenbalie()) {
logger.debug("No kb login required, thema: " + t == null ? "<null>" : t.getNaam());
return t;
}
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user == null) {
logger.debug("No user found, thema: " + t == null ? "<null>" : t.getNaam());
return null;
}
List layersFromRoles = user.getLayerNames(false);
if (layersFromRoles == null) {
logger.debug("No layers found, thema: " + t == null ? "<null>" : t.getNaam());
return null;
}
// Check de rechten op alle layers uit het thema
if (!checkThemaLayers(t, layersFromRoles)) {
logger.debug("No rights for layers found, thema: " + t == null ? "<null>" : t.getNaam());
return null;
}
*/
return t;
}
/**
* Indien een cluster wordt meegegeven dan voegt deze functie ook de layers
* die niet als thema geconfigureerd zijn, maar toch als role aan de
* principal zijn meegegeven als dummy thema toe. Als dit niet de bedoeling
* is dan dient null als cluster meegegeven te worden.
*
* @param locatie
* @param request
* @return
*/
protected List getValidThemas(boolean locatie, List ctl, HttpServletRequest request) {
List configuredThemasList = SpatialUtil.getValidThemas(locatie);
List layersFromRoles = null;
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user != null) {
layersFromRoles = user.getLayerNames(false);
}
if (layersFromRoles == null) {
return null;
}
// Voeg alle themas toe die layers hebben die volgens de rollen
// acceptabel zijn (voldoende rechten dus).
List layersFound = new ArrayList();
List checkedThemaList = new ArrayList();
if (configuredThemasList != null) {
Iterator it2 = configuredThemasList.iterator();
while (it2.hasNext()) {
Themas t = (Themas) it2.next();
// Als geen check via kaartenbalie dan alle layers doorgeven
if (checkThemaLayers(t, layersFromRoles)
|| !HibernateUtil.isCheckLoginKaartenbalie()) {
checkedThemaList.add(t);
layersFound.add(t.getWms_layers_real());
}
}
}
// als alleen configureerde layers getoond mogen worden,
// dan hier stoppen
if (!HibernateUtil.isUseKaartenbalieCluster()) {
return checkedThemaList;
}
//zoek of maak een cluster aan voor als er kaarten worden gevonden die geen thema hebben.
Clusters c = SpatialUtil.getDefaultCluster();
if (c == null) {
c = new Clusters();
c.setNaam(HibernateUtil.getKaartenbalieCluster());
c.setParent(null);
}
Iterator it = layersFromRoles.iterator();
int tid = 100000;
ArrayList extraThemaList = new ArrayList();
// Kijk welke lagen uit de rollen nog niet zijn toegevoegd
// en voeg deze alsnog toe via dummy thema en cluster.
while (it.hasNext()) {
String layer = (String) it.next();
if (layersFound.contains(layer)) {
continue;
}
// Layer bestaat nog niet dus aanmaken
Layer l = user.getLayer(layer);
if (l != null) {
Themas t = new Themas();
t.setNaam(l.getTitle());
t.setId(new Integer(tid++));
if (user.hasLegendGraphic(l)) {
t.setWms_legendlayer_real(layer);
}
if ("1".equalsIgnoreCase(l.getQueryable())) {
t.setWms_querylayers_real(layer);
}
t.setWms_layers_real(layer);
t.setCluster(c);
// voeg extra laag als nieuw thema toe
extraThemaList.add(t);
}
}
if (extraThemaList.size() > 0) {
if (ctl == null) {
ctl = new ArrayList();
}
ctl.add(c);
for (int i = 0; i < extraThemaList.size(); i++) {
checkedThemaList.add(extraThemaList.get(i));
}
}
return checkedThemaList;
}
/**
* Indien een cluster wordt meegegeven dan voegt deze functie ook de layers
* die niet als thema geconfigureerd zijn, maar toch als role aan de
* principal zijn meegegeven als dummy thema toe. Als dit niet de bedoeling
* is dan dient null als cluster meegegeven te worden.
*
* @param locatie
* @param request
* @return
*/
protected List getValidUserThemas(boolean locatie, List ctl, HttpServletRequest request) {
List configuredThemasList = SpatialUtil.getValidThemas(locatie);
List layersFromRoles = null;
// Zoek layers die via principal binnen komen
GisPrincipal user = GisPrincipal.getGisPrincipal(request);
if (user != null) {
layersFromRoles = user.getLayerNames(false);
}
if (layersFromRoles == null) {
return null;
}
/* ophalen user kaartlagen om custom boom op te bouwen */
List<UserKaartlaag> lagen = SpatialUtil.getUserKaartLagen(user.getCode());
// Voeg alle themas toe die layers hebben die volgens de rollen
// acceptabel zijn (voldoende rechten dus).
List layersFound = new ArrayList();
List checkedThemaList = new ArrayList();
if (configuredThemasList != null) {
Iterator it2 = configuredThemasList.iterator();
while (it2.hasNext()) {
Themas t = (Themas) it2.next();
/* controleren of thema in user kaartlagen voorkomt */
if (lagen != null && lagen.size() > 0) {
boolean isInList = false;
for (UserKaartlaag laag : lagen) {
if (laag.getThemaid() == t.getId()) {
isInList = true;
}
}
if (!isInList) {
continue;
}
}
// Als geen check via kaartenbalie dan alle layers doorgeven
if (checkThemaLayers(t, layersFromRoles)
|| !HibernateUtil.isCheckLoginKaartenbalie()) {
checkedThemaList.add(t);
layersFound.add(t.getWms_layers_real());
}
}
}
// als alleen configureerde layers getoond mogen worden,
// dan hier stoppen
if (!HibernateUtil.isUseKaartenbalieCluster()) {
return checkedThemaList;
}
//zoek of<SUF>
Clusters c = SpatialUtil.getDefaultCluster();
if (c == null) {
c = new Clusters();
c.setNaam(HibernateUtil.getKaartenbalieCluster());
c.setParent(null);
}
Iterator it = layersFromRoles.iterator();
int tid = 100000;
ArrayList extraThemaList = new ArrayList();
// Kijk welke lagen uit de rollen nog niet zijn toegevoegd
// en voeg deze alsnog toe via dummy thema en cluster.
while (it.hasNext()) {
String layer = (String) it.next();
if (layersFound.contains(layer)) {
continue;
}
// Layer bestaat nog niet dus aanmaken
Layer l = user.getLayer(layer);
if (l != null) {
Themas t = new Themas();
t.setNaam(l.getTitle());
t.setId(new Integer(tid++));
if (user.hasLegendGraphic(l)) {
t.setWms_legendlayer_real(layer);
}
if ("1".equalsIgnoreCase(l.getQueryable())) {
t.setWms_querylayers_real(layer);
}
t.setWms_layers_real(layer);
t.setCluster(c);
// voeg extra laag als nieuw thema toe
extraThemaList.add(t);
}
}
if (extraThemaList.size() > 0) {
if (ctl == null) {
ctl = new ArrayList();
}
ctl.add(c);
for (int i = 0; i < extraThemaList.size(); i++) {
checkedThemaList.add(extraThemaList.get(i));
}
}
return checkedThemaList;
}
/**
* Voeg alle layers samen voor een thema en controleer of de gebruiker voor
* alle layers rechten heeft. Zo nee, thema niet toevoegen.
*
* @param t
* @param request
* @return
*/
protected boolean checkThemaLayers(Themas t, List acceptableLayers) {
if (t == null || acceptableLayers == null) {
return false;
}
String wmsls = t.getWms_layers_real();
if (wmsls == null || wmsls.length() == 0) {
return false;
}
// Dit is te streng, alleen op wms layer checken
// String wmsqls = t.getWms_querylayers_real();
// if (wmsqls!=null && wmsqls.length()>0)
// wmsls += "," + wmsqls;
// String wmslls = t.getWms_legendlayer_real();
// if (wmslls!=null && wmslls.length()>0)
// wmsls += "," + wmslls;
String[] wmsla = wmsls.split(",");
for (int i = 0; i < wmsla.length; i++) {
if (!acceptableLayers.contains(wmsla[i])) {
return false;
}
}
return true;
}
/**
* Een protected methode het object thema ophaalt dat hoort bij een bepaald
* id.
*
* @param identifier String which identifies the object thema to be found.
*
* @return a Themas object representing the object thema.
*
*/
protected Themas getObjectThema(String identifier) {
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
Themas objectThema = null;
try {
int id = Integer.parseInt(identifier);
objectThema = (Themas) sess.get(Themas.class, new Integer(id));
} catch (NumberFormatException nfe) {
objectThema = (Themas) sess.get(Themas.class, identifier);
}
return objectThema;
}
protected List getTekstBlokken(Integer cmsPageId) {
List<Tekstblok> tekstBlokken = new ArrayList();
if (cmsPageId != null && cmsPageId > 0) {
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
tekstBlokken = sess.createQuery("from Tekstblok where cms_pagina = :id"
+ " order by volgordenr, cdate").setParameter("id", cmsPageId).list();
}
return tekstBlokken;
}
protected static void setCMSPageFromRequest(HttpServletRequest request) {
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
String param = request.getParameter(BaseGisAction.CMS_PAGE_ID);
Integer cmsPageId = null;
if (param != null && !param.equals("")) {
cmsPageId = new Integer(param);
}
/* CMS Theme klaarzetten */
if (cmsPageId != null && cmsPageId > 0) {
CMSPagina cmsPage = (CMSPagina) sess.get(CMSPagina.class, cmsPageId);
request.setAttribute("cmsPageId", cmsPageId);
if (cmsPage != null && cmsPage.getThema() != null && !cmsPage.getThema().equals("")) {
request.setAttribute("theme", cmsPage.getThema());
}
}
}
protected CMSPagina getCMSPage(Integer pageID) {
if (pageID == null || pageID < 1) {
return null;
}
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
return (CMSPagina) sess.get(CMSPagina.class, pageID);
}
protected CMSMenu getCMSMenu(Integer id) {
if (id == null || id < 1) {
return null;
}
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
return (CMSMenu) sess.get(CMSMenu.class, id);
}
protected List<CMSMenuItem> getCMSMenuItems(Integer menuId) {
List<CMSMenuItem> menuItems = new ArrayList<CMSMenuItem>();
if (menuId == null || menuId < 1) {
return menuItems;
}
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
menuItems = sess.createQuery("select item from CMSMenuItem item"
+ " where item.id in (select cmsMenuItems.id"
+ " from CMSMenu menu inner join menu.cmsMenuItems cmsMenuItems"
+ " where menu.id = :menuId) order by item.volgordenr DESC")
.setParameter("menuId", menuId)
.list();
return menuItems;
}
protected List<CMSPagina> getCMSPaginas() {
List<CMSPagina> paginas;
Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
paginas = sess.createQuery("from CMSPagina order by id").list();
return paginas;
}
protected String prettifyCMSPageUrl(HttpServletRequest request, CMSPagina cmsPage) {
String baseURL = request.getRequestURL().toString().replace(request.getRequestURI().substring(0), request.getContextPath());
String nowhitespace = WHITESPACE.matcher(cmsPage.getTitel()).replaceAll("-");
String normalized = Normalizer.normalize(nowhitespace, Normalizer.Form.NFD);
String slug = NONLATIN.matcher(normalized).replaceAll("");
String url = slug.toLowerCase(Locale.ENGLISH);
return baseURL + "/cms/" + cmsPage.getId() + "/" + url + ".htm";
}
}
|
126166_15 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.zoeker.configuratie;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.oracle.OracleNGDataStoreFactory;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.data.wfs.v1_0_0.WFSCapabilities;
import org.geotools.data.wfs.v1_0_0.WFS_1_0_0_DataStore;
import org.geotools.filter.FilterCapabilities;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Roy
*/
public class Bron {
private Integer id = null;
private String naam = null;
private String url = null;
private String gebruikersnaam = null;
private String wachtwoord = null;
private Integer volgorde = null;
private static final int TIMEOUT = 60000;
public static final String TYPE_JDBC = "jdbc";
public static final String TYPE_ORACLE = "oracle";
public static final String TYPE_WFS = "wfs";
public static final String TYPE_EMPTY = "unknown";
static protected Map<Map, WFSDataStore> perParameterSetDataStoreCache = new HashMap();
static protected long dataStoreTimestamp = 0l;
private static long dataStoreLifecycle = 0l;
public static final String LIFECYCLE_CACHE_PARAM = "cachelifecycle";
private static final Log log = LogFactory.getLog(Bron.class);
public Bron() {
}
public Bron(Integer id, String naam, String url, String gebruikersnaam, String wachtwoord, Integer volgorde) {
this.id = id;
this.naam = naam;
this.url = url;
this.gebruikersnaam = gebruikersnaam;
this.wachtwoord = wachtwoord;
this.volgorde = volgorde;
}
public Bron(Integer id, String naam, String url) {
this(id, naam, url, null, null, null);
}
/**
* @return the Id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the naam
*/
public String getNaam() {
return naam;
}
/**
* @param naam the naam to set
*/
public void setNaam(String naam) {
this.naam = naam;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the volgorde
*/
public Integer getVolgorde() {
return volgorde;
}
/**
* @param volgorde the volgorde to set
*/
public void setVolgorde(Integer volgorde) {
this.volgorde = volgorde;
}
/**
* @return the gebruikersnaam
*/
public String getGebruikersnaam() {
return gebruikersnaam;
}
/**
* @param gebruikersnaam the gebruikersnaam to set
*/
public void setGebruikersnaam(String gebruikersnaam) {
this.gebruikersnaam = gebruikersnaam;
}
/**
* @return the wachtwoord
*/
public String getWachtwoord() {
return wachtwoord;
}
/**
* @param wachtwoord the wachtwoord to set
*/
public void setWachtwoord(String wachtwoord) {
this.wachtwoord = wachtwoord;
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put("id", id);
json.put("naam", getNaam());
json.put("url", getUrl());
json.put("volgorde", getVolgorde());
return json;
}
public String getType() {
if (checkType(TYPE_JDBC)) {
return TYPE_JDBC;
}
if (checkType(TYPE_WFS)) {
return TYPE_WFS;
}
return TYPE_EMPTY;
}
public boolean checkType(String type) {
if (this.getUrl() == null || type == null || type.length() == 0) {
return false;
}
if (this.getUrl().toLowerCase().startsWith("jdbc:")) {
if (this.getUrl().toLowerCase().startsWith("jdbc:oracle:")) {
if (type.equals(TYPE_ORACLE)) {
return true;
}
}
if (type.equals(TYPE_JDBC)) {
return true;
}
} else if (type.equals(TYPE_WFS)) {
return true;
}
return false;
}
public DataStore toDatastore() throws IOException, Exception {
if (this.getUrl() == null) {
return null;
}
HashMap params = new HashMap();
if (checkType(TYPE_ORACLE)) {
int firstIndex;
int lastIndex;
firstIndex = this.getUrl().indexOf("@") + 1;
lastIndex = this.getUrl().indexOf(":", firstIndex);
String host = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
lastIndex = this.getUrl().indexOf(":", firstIndex);
String port = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
lastIndex = this.getUrl().indexOf(".", firstIndex);
String schema = null;
if (lastIndex == -1) {
lastIndex = this.getUrl().length();
} else {
schema = this.getUrl().substring(lastIndex + 1, this.getUrl().length());
}
String instance = this.getUrl().substring(firstIndex, lastIndex);
params.put(OracleNGDataStoreFactory.HOST.key, host);
params.put(OracleNGDataStoreFactory.PORT.key, port);
if (schema != null) {
params.put(OracleNGDataStoreFactory.SCHEMA.key, schema);
}
params.put(OracleNGDataStoreFactory.FETCHSIZE.key, 50);
params.put(OracleNGDataStoreFactory.DATABASE.key, instance);
params.put(OracleNGDataStoreFactory.USER.key, this.getGebruikersnaam());
params.put(OracleNGDataStoreFactory.PASSWD.key, this.getWachtwoord());
params.put(OracleNGDataStoreFactory.DBTYPE.key, "oracle");
params.put(OracleNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
return (new OracleNGDataStoreFactory()).createDataStore(params);
}
if (checkType(TYPE_JDBC)) {
int firstIndex;
int lastIndex;
firstIndex = this.getUrl().indexOf("//") + 2;
lastIndex = this.getUrl().indexOf(":", firstIndex);
String host = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
lastIndex = this.getUrl().indexOf("/", firstIndex);
String port = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
String database = this.getUrl().substring(firstIndex, this.getUrl().length());
String schema = "public";
if (database.indexOf(".") >= 0) {
String[] tokens = database.split("\\.");
if (tokens.length == 2) {
schema = tokens[1];
database = tokens[0];
}
}
params.put(PostgisNGDataStoreFactory.FETCHSIZE.key, 50);
params.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
params.put(PostgisNGDataStoreFactory.HOST.key, host);
params.put(PostgisNGDataStoreFactory.PORT.key, port);
params.put(PostgisNGDataStoreFactory.SCHEMA.key, schema);
params.put(PostgisNGDataStoreFactory.DATABASE.key, database);
if (this.getGebruikersnaam() != null) {
params.put(PostgisNGDataStoreFactory.USER.key, this.getGebruikersnaam());
}
if (this.getWachtwoord() != null) {
params.put(PostgisNGDataStoreFactory.PASSWD.key, this.getWachtwoord());
}
params.put(PostgisNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
}
if (checkType(TYPE_WFS)) {
String url = this.getUrl();
if (this.getUrl().toLowerCase().indexOf("request=") == -1) {
if (url.indexOf('?') < 0) {
url += "?request=GetCapabilities&service=WFS";
} else if (url.indexOf('?') == url.length() - 1) {
url += "request=GetCapabilities&service=WFS";
} else if (url.lastIndexOf('&') == url.length() - 1) {
url += "request=GetCapabilities&service=WFS";
} else {
url += "&request=GetCapabilities&service=WFS";
}
if (url.toLowerCase().indexOf("version") == -1) {
url += "&Version=1.1.0";
}
}
params.put(WFSDataStoreFactory.URL.key, url);
if (this.getGebruikersnaam() != null && this.getWachtwoord() != null) {
params.put(WFSDataStoreFactory.USERNAME.key, this.getGebruikersnaam());
params.put(WFSDataStoreFactory.PASSWORD.key, this.getWachtwoord());
}
params.put(WFSDataStoreFactory.TIMEOUT.key, TIMEOUT);
params.put(WFSDataStoreFactory.PROTOCOL.key, Boolean.TRUE);
//Geotools zoekt Geoserver automatisch obv "geoserver" in url.
//Daarnaast worden ionic, arcgis en cubewerx gevonden.
//Mapserver moeten we dus zelf uitzoeken.
if (url.contains("mapserv") && url.contains(".map")) {
// als mapserver dus verborgen zit achter een algemene url, jammer!
params.put(WFSDataStoreFactory.WFS_STRATEGY.key, "mapserver");
}
DataStore ds = getWfsCache(params);
if (ds == null) {
if (!perParameterSetDataStoreCache.containsKey(params)) {
ds = (new WFSDataStoreFactory()).createDataStore(params);
putWfsCache(params, (WFSDataStore) repairDataStore(ds));
}
}
return ds;
}
return createDataStoreFromParams(params);
}
public static synchronized void flushWfsCache() {
perParameterSetDataStoreCache = new HashMap();
log.info("Cache WFS leeggemaakt.");
}
public static synchronized void putWfsCache(HashMap p, WFSDataStore ds) {
perParameterSetDataStoreCache.put(p, ds);
}
public static synchronized WFSDataStore getWfsCache(HashMap p) {
if (isCacheExpired()) {
flushWfsCache();
return null;
}
if (perParameterSetDataStoreCache.containsKey(p)) {
return perParameterSetDataStoreCache.get(p);
}
return null;
}
public static boolean isCacheExpired() {
long nowTimestamp = (new Date()).getTime();
if (getDataStoreLifecycle() > 0 && (nowTimestamp - dataStoreTimestamp) > getDataStoreLifecycle()) {
dataStoreTimestamp = nowTimestamp;
return true;
}
return false;
}
/**
* @return the dataStoreLifecycle
*/
public static long getDataStoreLifecycle() {
return dataStoreLifecycle;
}
/**
* @param aDataStoreLifecycle the dataStoreLifecycle to set
*/
public static void setDataStoreLifecycle(long aDataStoreLifecycle) {
dataStoreLifecycle = aDataStoreLifecycle;
}
public static DataStore createDataStoreFromParams(Map params) throws IOException, Exception {
DataStore ds = null;
try {
ds = repairDataStore(DataStoreFinder.getDataStore(params));
} catch (IOException ex) {
throw new Exception("Connectie naar gegevensbron mislukt. Controleer de bron instellingen.");
}
return ds;
}
private static DataStore repairDataStore(DataStore ds) throws Exception {
if (ds instanceof WFS_1_0_0_DataStore) {
WFS_1_0_0_DataStore wfs100ds = (WFS_1_0_0_DataStore) ds;
WFSCapabilities wfscap = wfs100ds.getCapabilities();
// wfs 1.0.0 haalt prefix er niet af en zet de namespace niet
// wfs 1.1.0 doet dit wel en hier fixen we dit.
// List<FeatureSetDescription> fdsl = wfscap.getFeatureTypes();
// for (FeatureSetDescription fds : fdsl) {
// if (fds.getNamespace() != null) {
// continue;
// }
//
// String[] lna = fds.getName().split(":");
// if (lna.length > 1) {
// String localName = lna[1];
// String nsPrefix = lna[0];
// URI nsUri = null;
// if (!nsPrefix.isEmpty()) {
// Schema[] schemas = SchemaFactory.getSchemas(nsPrefix);
// if (schemas.length > 0) {
// nsUri = schemas[0].getTargetNamespace();
// } else {
// try {
// nsUri = new URI(nsPrefix);
// } catch (URISyntaxException ex) {}
// }
// }
// fds.setName(localName);
// fds.setNamespace(nsUri);
// }
// }
//omdat de WFS_1_0_0_Datastore niet met de opengis filters werkt even toevoegen dat
//er simpele vergelijkingen kunnen worden gedaan. (de meeste servers kunnen dit natuurlijk);
FilterCapabilities filterCap = wfscap.getFilterCapabilities();
filterCap.addAll(FilterCapabilities.SIMPLE_COMPARISONS_OPENGIS);
boolean b = filterCap.supports(FilterCapabilities.SIMPLE_COMPARISONS_OPENGIS);
wfscap.setFilterCapabilities(filterCap);
}
return ds;
}
@Override
public String toString() {
String returnValue = "";
if (getNaam() != null) {
returnValue += getNaam() + " ";
}
if (getUrl() != null) {
returnValue += "(" + getUrl() + ")";
}
return returnValue;
}
}
| B3Partners/b3p-zoeker | src/main/java/nl/b3p/zoeker/configuratie/Bron.java | 4,286 | //Geotools zoekt Geoserver automatisch obv "geoserver" in url. | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.zoeker.configuratie;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.oracle.OracleNGDataStoreFactory;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.data.wfs.v1_0_0.WFSCapabilities;
import org.geotools.data.wfs.v1_0_0.WFS_1_0_0_DataStore;
import org.geotools.filter.FilterCapabilities;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Roy
*/
public class Bron {
private Integer id = null;
private String naam = null;
private String url = null;
private String gebruikersnaam = null;
private String wachtwoord = null;
private Integer volgorde = null;
private static final int TIMEOUT = 60000;
public static final String TYPE_JDBC = "jdbc";
public static final String TYPE_ORACLE = "oracle";
public static final String TYPE_WFS = "wfs";
public static final String TYPE_EMPTY = "unknown";
static protected Map<Map, WFSDataStore> perParameterSetDataStoreCache = new HashMap();
static protected long dataStoreTimestamp = 0l;
private static long dataStoreLifecycle = 0l;
public static final String LIFECYCLE_CACHE_PARAM = "cachelifecycle";
private static final Log log = LogFactory.getLog(Bron.class);
public Bron() {
}
public Bron(Integer id, String naam, String url, String gebruikersnaam, String wachtwoord, Integer volgorde) {
this.id = id;
this.naam = naam;
this.url = url;
this.gebruikersnaam = gebruikersnaam;
this.wachtwoord = wachtwoord;
this.volgorde = volgorde;
}
public Bron(Integer id, String naam, String url) {
this(id, naam, url, null, null, null);
}
/**
* @return the Id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the naam
*/
public String getNaam() {
return naam;
}
/**
* @param naam the naam to set
*/
public void setNaam(String naam) {
this.naam = naam;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the volgorde
*/
public Integer getVolgorde() {
return volgorde;
}
/**
* @param volgorde the volgorde to set
*/
public void setVolgorde(Integer volgorde) {
this.volgorde = volgorde;
}
/**
* @return the gebruikersnaam
*/
public String getGebruikersnaam() {
return gebruikersnaam;
}
/**
* @param gebruikersnaam the gebruikersnaam to set
*/
public void setGebruikersnaam(String gebruikersnaam) {
this.gebruikersnaam = gebruikersnaam;
}
/**
* @return the wachtwoord
*/
public String getWachtwoord() {
return wachtwoord;
}
/**
* @param wachtwoord the wachtwoord to set
*/
public void setWachtwoord(String wachtwoord) {
this.wachtwoord = wachtwoord;
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put("id", id);
json.put("naam", getNaam());
json.put("url", getUrl());
json.put("volgorde", getVolgorde());
return json;
}
public String getType() {
if (checkType(TYPE_JDBC)) {
return TYPE_JDBC;
}
if (checkType(TYPE_WFS)) {
return TYPE_WFS;
}
return TYPE_EMPTY;
}
public boolean checkType(String type) {
if (this.getUrl() == null || type == null || type.length() == 0) {
return false;
}
if (this.getUrl().toLowerCase().startsWith("jdbc:")) {
if (this.getUrl().toLowerCase().startsWith("jdbc:oracle:")) {
if (type.equals(TYPE_ORACLE)) {
return true;
}
}
if (type.equals(TYPE_JDBC)) {
return true;
}
} else if (type.equals(TYPE_WFS)) {
return true;
}
return false;
}
public DataStore toDatastore() throws IOException, Exception {
if (this.getUrl() == null) {
return null;
}
HashMap params = new HashMap();
if (checkType(TYPE_ORACLE)) {
int firstIndex;
int lastIndex;
firstIndex = this.getUrl().indexOf("@") + 1;
lastIndex = this.getUrl().indexOf(":", firstIndex);
String host = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
lastIndex = this.getUrl().indexOf(":", firstIndex);
String port = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
lastIndex = this.getUrl().indexOf(".", firstIndex);
String schema = null;
if (lastIndex == -1) {
lastIndex = this.getUrl().length();
} else {
schema = this.getUrl().substring(lastIndex + 1, this.getUrl().length());
}
String instance = this.getUrl().substring(firstIndex, lastIndex);
params.put(OracleNGDataStoreFactory.HOST.key, host);
params.put(OracleNGDataStoreFactory.PORT.key, port);
if (schema != null) {
params.put(OracleNGDataStoreFactory.SCHEMA.key, schema);
}
params.put(OracleNGDataStoreFactory.FETCHSIZE.key, 50);
params.put(OracleNGDataStoreFactory.DATABASE.key, instance);
params.put(OracleNGDataStoreFactory.USER.key, this.getGebruikersnaam());
params.put(OracleNGDataStoreFactory.PASSWD.key, this.getWachtwoord());
params.put(OracleNGDataStoreFactory.DBTYPE.key, "oracle");
params.put(OracleNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
return (new OracleNGDataStoreFactory()).createDataStore(params);
}
if (checkType(TYPE_JDBC)) {
int firstIndex;
int lastIndex;
firstIndex = this.getUrl().indexOf("//") + 2;
lastIndex = this.getUrl().indexOf(":", firstIndex);
String host = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
lastIndex = this.getUrl().indexOf("/", firstIndex);
String port = this.getUrl().substring(firstIndex, lastIndex);
firstIndex = lastIndex + 1;
String database = this.getUrl().substring(firstIndex, this.getUrl().length());
String schema = "public";
if (database.indexOf(".") >= 0) {
String[] tokens = database.split("\\.");
if (tokens.length == 2) {
schema = tokens[1];
database = tokens[0];
}
}
params.put(PostgisNGDataStoreFactory.FETCHSIZE.key, 50);
params.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
params.put(PostgisNGDataStoreFactory.HOST.key, host);
params.put(PostgisNGDataStoreFactory.PORT.key, port);
params.put(PostgisNGDataStoreFactory.SCHEMA.key, schema);
params.put(PostgisNGDataStoreFactory.DATABASE.key, database);
if (this.getGebruikersnaam() != null) {
params.put(PostgisNGDataStoreFactory.USER.key, this.getGebruikersnaam());
}
if (this.getWachtwoord() != null) {
params.put(PostgisNGDataStoreFactory.PASSWD.key, this.getWachtwoord());
}
params.put(PostgisNGDataStoreFactory.EXPOSE_PK.key, Boolean.TRUE);
}
if (checkType(TYPE_WFS)) {
String url = this.getUrl();
if (this.getUrl().toLowerCase().indexOf("request=") == -1) {
if (url.indexOf('?') < 0) {
url += "?request=GetCapabilities&service=WFS";
} else if (url.indexOf('?') == url.length() - 1) {
url += "request=GetCapabilities&service=WFS";
} else if (url.lastIndexOf('&') == url.length() - 1) {
url += "request=GetCapabilities&service=WFS";
} else {
url += "&request=GetCapabilities&service=WFS";
}
if (url.toLowerCase().indexOf("version") == -1) {
url += "&Version=1.1.0";
}
}
params.put(WFSDataStoreFactory.URL.key, url);
if (this.getGebruikersnaam() != null && this.getWachtwoord() != null) {
params.put(WFSDataStoreFactory.USERNAME.key, this.getGebruikersnaam());
params.put(WFSDataStoreFactory.PASSWORD.key, this.getWachtwoord());
}
params.put(WFSDataStoreFactory.TIMEOUT.key, TIMEOUT);
params.put(WFSDataStoreFactory.PROTOCOL.key, Boolean.TRUE);
//Geotools zoekt<SUF>
//Daarnaast worden ionic, arcgis en cubewerx gevonden.
//Mapserver moeten we dus zelf uitzoeken.
if (url.contains("mapserv") && url.contains(".map")) {
// als mapserver dus verborgen zit achter een algemene url, jammer!
params.put(WFSDataStoreFactory.WFS_STRATEGY.key, "mapserver");
}
DataStore ds = getWfsCache(params);
if (ds == null) {
if (!perParameterSetDataStoreCache.containsKey(params)) {
ds = (new WFSDataStoreFactory()).createDataStore(params);
putWfsCache(params, (WFSDataStore) repairDataStore(ds));
}
}
return ds;
}
return createDataStoreFromParams(params);
}
public static synchronized void flushWfsCache() {
perParameterSetDataStoreCache = new HashMap();
log.info("Cache WFS leeggemaakt.");
}
public static synchronized void putWfsCache(HashMap p, WFSDataStore ds) {
perParameterSetDataStoreCache.put(p, ds);
}
public static synchronized WFSDataStore getWfsCache(HashMap p) {
if (isCacheExpired()) {
flushWfsCache();
return null;
}
if (perParameterSetDataStoreCache.containsKey(p)) {
return perParameterSetDataStoreCache.get(p);
}
return null;
}
public static boolean isCacheExpired() {
long nowTimestamp = (new Date()).getTime();
if (getDataStoreLifecycle() > 0 && (nowTimestamp - dataStoreTimestamp) > getDataStoreLifecycle()) {
dataStoreTimestamp = nowTimestamp;
return true;
}
return false;
}
/**
* @return the dataStoreLifecycle
*/
public static long getDataStoreLifecycle() {
return dataStoreLifecycle;
}
/**
* @param aDataStoreLifecycle the dataStoreLifecycle to set
*/
public static void setDataStoreLifecycle(long aDataStoreLifecycle) {
dataStoreLifecycle = aDataStoreLifecycle;
}
public static DataStore createDataStoreFromParams(Map params) throws IOException, Exception {
DataStore ds = null;
try {
ds = repairDataStore(DataStoreFinder.getDataStore(params));
} catch (IOException ex) {
throw new Exception("Connectie naar gegevensbron mislukt. Controleer de bron instellingen.");
}
return ds;
}
private static DataStore repairDataStore(DataStore ds) throws Exception {
if (ds instanceof WFS_1_0_0_DataStore) {
WFS_1_0_0_DataStore wfs100ds = (WFS_1_0_0_DataStore) ds;
WFSCapabilities wfscap = wfs100ds.getCapabilities();
// wfs 1.0.0 haalt prefix er niet af en zet de namespace niet
// wfs 1.1.0 doet dit wel en hier fixen we dit.
// List<FeatureSetDescription> fdsl = wfscap.getFeatureTypes();
// for (FeatureSetDescription fds : fdsl) {
// if (fds.getNamespace() != null) {
// continue;
// }
//
// String[] lna = fds.getName().split(":");
// if (lna.length > 1) {
// String localName = lna[1];
// String nsPrefix = lna[0];
// URI nsUri = null;
// if (!nsPrefix.isEmpty()) {
// Schema[] schemas = SchemaFactory.getSchemas(nsPrefix);
// if (schemas.length > 0) {
// nsUri = schemas[0].getTargetNamespace();
// } else {
// try {
// nsUri = new URI(nsPrefix);
// } catch (URISyntaxException ex) {}
// }
// }
// fds.setName(localName);
// fds.setNamespace(nsUri);
// }
// }
//omdat de WFS_1_0_0_Datastore niet met de opengis filters werkt even toevoegen dat
//er simpele vergelijkingen kunnen worden gedaan. (de meeste servers kunnen dit natuurlijk);
FilterCapabilities filterCap = wfscap.getFilterCapabilities();
filterCap.addAll(FilterCapabilities.SIMPLE_COMPARISONS_OPENGIS);
boolean b = filterCap.supports(FilterCapabilities.SIMPLE_COMPARISONS_OPENGIS);
wfscap.setFilterCapabilities(filterCap);
}
return ds;
}
@Override
public String toString() {
String returnValue = "";
if (getNaam() != null) {
returnValue += getNaam() + " ";
}
if (getUrl() != null) {
returnValue += "(" + getUrl() + ")";
}
return returnValue;
}
}
|
17292_2 | /*
* Copyright (C) 2016 - 2017 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.topnl;
import org.locationtech.jts.io.ParseException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;
/**
*
* @author Meine Toonen [email protected]
*/
public class Main {
protected final static Log log = LogFactory.getLog(Main.class);
// voeg deze dependency toe als je wilt draaien
// <dependency>
// <groupId>org.apache.commons</groupId>
// <artifactId>commons-dbcp2</artifactId>
// </dependency>
public static void main (String[] args) throws Exception{
try {
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:postgresql://localhost:5432/topnl");
ds.setDriverClassName("org.postgresql.Driver");
// ds.setUsername("rsgb");
// ds.setPassword("rsgb");
// ds.setUrl("jdbc:oracle:thin:@b3p-demoserver:1521/ORCL");
// ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
// ds.setUsername("top50nl");
// ds.setPassword("top50nl");
Processor p = new Processor(ds);
// loadtopnl("/mnt/data/Documents/TopNL/Top50NL/TOP50NL_GML_Filechunks_november_2016/TOP50NL_GML_Filechunks", p, TopNLType.TOP50NL);
//loadtopnl("/mnt/data/Documents/TopNL/Top10NL/TOP10NL_GML_Filechuncks_november_2016/TOP10NL_GML_Filechuncks", p, TopNLType.TOP10NL);
loadtopnl("/mnt/data/Documents/TopNL/Tynaarlo/Top10NL", p, TopNLType.TOP10NL);
//loadtopnl("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks", p, TopNLType.TOP100NL);
//process("top250NL.gml", p);
//process("Hoogte_top250nl.xml", TopNLType.TOP250NL, p);
//process("Hoogte_top100nl.xml", TopNLType.TOP100NL, p);
} catch (SAXException | ParserConfigurationException | TransformerException ex) {
log.error("Cannot parse/convert/save entity: ", ex);
}
}
private static void loadtopnl(String dir, Processor p, TopNLType type) throws Exception{
File f = new File (dir);
FilenameFilter filter = (dir1, name) -> name.toLowerCase().endsWith(".gml");
/*File f = new File("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks/Top100NL_000002.gml");
p.importIntoDb(f.toURL(), TopNLType.TOP100NL);*/
File[] files = f.listFiles(filter);
for (File file : files) {
// String fileString = file.getCanonicalPath();
p.importIntoDb(file.toURI().toURL(), type);
}
}
private static void process(String file, Processor p, TopNLType type) throws Exception {
URL in = Main.class.getResource(file);
p.importIntoDb(in, type);
/* List obj = p.parse(in, type);
List<TopNLEntity> entities = p.convert(obj, type);
p.save(entities, type);*/
}
}
| B3Partners/brmo | brmo-topnl-loader/src/src-main/java/nl/b3p/topnl/Main.java | 1,299 | // voeg deze dependency toe als je wilt draaien | line_comment | nl | /*
* Copyright (C) 2016 - 2017 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.topnl;
import org.locationtech.jts.io.ParseException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;
/**
*
* @author Meine Toonen [email protected]
*/
public class Main {
protected final static Log log = LogFactory.getLog(Main.class);
// voeg deze<SUF>
// <dependency>
// <groupId>org.apache.commons</groupId>
// <artifactId>commons-dbcp2</artifactId>
// </dependency>
public static void main (String[] args) throws Exception{
try {
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:postgresql://localhost:5432/topnl");
ds.setDriverClassName("org.postgresql.Driver");
// ds.setUsername("rsgb");
// ds.setPassword("rsgb");
// ds.setUrl("jdbc:oracle:thin:@b3p-demoserver:1521/ORCL");
// ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
// ds.setUsername("top50nl");
// ds.setPassword("top50nl");
Processor p = new Processor(ds);
// loadtopnl("/mnt/data/Documents/TopNL/Top50NL/TOP50NL_GML_Filechunks_november_2016/TOP50NL_GML_Filechunks", p, TopNLType.TOP50NL);
//loadtopnl("/mnt/data/Documents/TopNL/Top10NL/TOP10NL_GML_Filechuncks_november_2016/TOP10NL_GML_Filechuncks", p, TopNLType.TOP10NL);
loadtopnl("/mnt/data/Documents/TopNL/Tynaarlo/Top10NL", p, TopNLType.TOP10NL);
//loadtopnl("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks", p, TopNLType.TOP100NL);
//process("top250NL.gml", p);
//process("Hoogte_top250nl.xml", TopNLType.TOP250NL, p);
//process("Hoogte_top100nl.xml", TopNLType.TOP100NL, p);
} catch (SAXException | ParserConfigurationException | TransformerException ex) {
log.error("Cannot parse/convert/save entity: ", ex);
}
}
private static void loadtopnl(String dir, Processor p, TopNLType type) throws Exception{
File f = new File (dir);
FilenameFilter filter = (dir1, name) -> name.toLowerCase().endsWith(".gml");
/*File f = new File("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks/Top100NL_000002.gml");
p.importIntoDb(f.toURL(), TopNLType.TOP100NL);*/
File[] files = f.listFiles(filter);
for (File file : files) {
// String fileString = file.getCanonicalPath();
p.importIntoDb(file.toURI().toURL(), type);
}
}
private static void process(String file, Processor p, TopNLType type) throws Exception {
URL in = Main.class.getResource(file);
p.importIntoDb(in, type);
/* List obj = p.parse(in, type);
List<TopNLEntity> entities = p.convert(obj, type);
p.save(entities, type);*/
}
}
|
79800_7 | /*
* Copyright (C) 2018 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.brmo.verschil.stripes;
import nl.b3p.brmo.verschil.testutil.TestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseDataSourceConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.ext.postgresql.PostgresqlDataTypeFactory;
import org.junit.Ignore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Draaien met:
* {@code mvn -Dit.test=MutatiesActionBeanIntegrationTest -Dtest.skipTs=true verify -Ppostgresql > target/pgtests.log}
*
* @author mark
*/
public class MutatiesActionBeanIntegrationTest extends TestUtil {
private static final Log LOG = LogFactory.getLog(MutatiesActionBeanIntegrationTest.class);
private final Lock sequential = new ReentrantLock(true);
private IDatabaseConnection rsgb;
private HttpResponse response = null;
private final Map<String, String> jsonNames = new HashMap<String, String>() {{
put("NieuweOnroerendGoed.json", "nieuw");
put("GekoppeldeObjecten.json", "koppeling");
put("VervallenOnroerendGoed.json", "vervallen");
put("GewijzigdeOpp.json", "gewijzigdeopp");
put("Verkopen.json", "verkopen");
put("NieuweSubjecten.json", "nieuwe_subjecten");
put("BsnAangevuld.json", "bsnaangevuld");
}};
private final List<String> cvsNames = Arrays.asList(new String[]{
"NieuweOnroerendGoed.csv",
"GekoppeldeObjecten.csv",
"VervallenOnroerendGoed.csv",
"GewijzigdeOpp.csv",
"Verkopen.csv",
"NieuweSubjecten.csv",
"BsnAangevuld.csv"
});
@BeforeEach
@Override
public void setUp() throws Exception {
BasicDataSource dsRsgb = new BasicDataSource();
dsRsgb.setUrl(DBPROPS.getProperty("rsgb.url"));
dsRsgb.setUsername(DBPROPS.getProperty("rsgb.username"));
dsRsgb.setPassword(DBPROPS.getProperty("rsgb.password"));
dsRsgb.setAccessToUnderlyingConnectionAllowed(true);
dsRsgb.setConnectionProperties(DBPROPS.getProperty("rsgb.options", ""));
rsgb = new DatabaseDataSourceConnection(dsRsgb);
setupJNDI(dsRsgb, null);
rsgb.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactory());
sequential.lock();
}
@AfterEach
public void cleanup() throws Exception {
response = null;
rsgb.close();
sequential.unlock();
}
/**
* test of er een geldige zipfile met de genoemde json bestanden uit de service komt.
*
* @throws IOException if any
*/
@Test
public void testValidZipforJsonReturned() throws IOException {
response = client.execute(new HttpGet(BASE_TEST_URL + "rest/mutaties?van=2018-12-01&tot=2019-01-01&f=json"));
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode(), "Response status is niet OK.");
int filesInZip = 0;
try (ZipInputStream zis = new ZipInputStream(response.getEntity().getContent())) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOG.debug("file: " + entry.getName() + ", compressed size: " + entry.getCompressedSize());
assertTrue(jsonNames.containsKey(entry.getName()), "De verwachte sleutel komt niet voor");
StringBuilder actual = new StringBuilder();
byte[] buffer = new byte[1024];
int read = 0;
while (zis.available() > 0) {
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
actual.append(new String(buffer, 0, read));
}
}
// TODO check inhoud van entry bijvoorbeeld {"bsnaangevuld":[]}
//assertJsonEquals("{\"" + jsonNames.get(entry.getName()) + "\":[]}", actual.toString());
// check dat de node begint met bijv. '{"bsnaangevuld":['
assertTrue(actual.toString().startsWith("{\"" + jsonNames.get(entry.getName()) + "\":["));
LOG.trace("json data dump voor: " + entry.getName() + "\n##################\n" + actual);
filesInZip++;
}
}
assertEquals(jsonNames.size(), filesInZip, "Onverwacht aantal json files in zipfile");
// see: https://stackoverflow.com/questions/2085637/how-to-check-if-a-generated-zip-file-is-corrupted
}
/**
* test of er een geldige zipfile met de genoemde csv bestanden uit de service komt.
*
* @throws IOException if any
*/
@Test
@Ignore
public void testValidZipforCSVReturned() throws IOException {
response = client.execute(new HttpGet(BASE_TEST_URL + "rest/mutaties?van=2018-12-01&tot=2019-02-01&f=csv"));
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode(), "Response status is niet OK.");
int filesInZip = 0;
try (ZipInputStream zis = new ZipInputStream(response.getEntity().getContent())) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOG.debug("file: " + entry.getName() + ", compressed size: " + entry.getCompressedSize());
assertTrue(cvsNames.contains(entry.getName()), "De verwachte sleutel komt niet voor");
StringBuilder actual = new StringBuilder("csv data dump voor: " + entry.getName() + "\n##################\n");
byte[] buffer = new byte[1024];
int read = 0;
while (zis.available() > 0) {
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
actual.append(new String(buffer, 0, read));
}
}
LOG.trace(actual);
// TODO evt testen op kolom headers, bijv. voor NieuweSubjecten.csv
// begin_geldigheid;soort;geslachtsnaam;voorvoegsel;voornamen;naam;woonadres;geboortedatum;overlijdensdatum;bsn;rsin;kvk_nummer;straatnaam;huisnummer;huisletter;huisnummer_toev;postcode;woonplaats
filesInZip++;
}
}
assertEquals(cvsNames.size(), filesInZip, "Onverwacht aantal csv files in zipfile");
}
}
| B3Partners/brmo-brkverschil-service | src/test/java/nl/b3p/brmo/verschil/stripes/MutatiesActionBeanIntegrationTest.java | 2,365 | // TODO evt testen op kolom headers, bijv. voor NieuweSubjecten.csv | line_comment | nl | /*
* Copyright (C) 2018 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.brmo.verschil.stripes;
import nl.b3p.brmo.verschil.testutil.TestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseDataSourceConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.ext.postgresql.PostgresqlDataTypeFactory;
import org.junit.Ignore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Draaien met:
* {@code mvn -Dit.test=MutatiesActionBeanIntegrationTest -Dtest.skipTs=true verify -Ppostgresql > target/pgtests.log}
*
* @author mark
*/
public class MutatiesActionBeanIntegrationTest extends TestUtil {
private static final Log LOG = LogFactory.getLog(MutatiesActionBeanIntegrationTest.class);
private final Lock sequential = new ReentrantLock(true);
private IDatabaseConnection rsgb;
private HttpResponse response = null;
private final Map<String, String> jsonNames = new HashMap<String, String>() {{
put("NieuweOnroerendGoed.json", "nieuw");
put("GekoppeldeObjecten.json", "koppeling");
put("VervallenOnroerendGoed.json", "vervallen");
put("GewijzigdeOpp.json", "gewijzigdeopp");
put("Verkopen.json", "verkopen");
put("NieuweSubjecten.json", "nieuwe_subjecten");
put("BsnAangevuld.json", "bsnaangevuld");
}};
private final List<String> cvsNames = Arrays.asList(new String[]{
"NieuweOnroerendGoed.csv",
"GekoppeldeObjecten.csv",
"VervallenOnroerendGoed.csv",
"GewijzigdeOpp.csv",
"Verkopen.csv",
"NieuweSubjecten.csv",
"BsnAangevuld.csv"
});
@BeforeEach
@Override
public void setUp() throws Exception {
BasicDataSource dsRsgb = new BasicDataSource();
dsRsgb.setUrl(DBPROPS.getProperty("rsgb.url"));
dsRsgb.setUsername(DBPROPS.getProperty("rsgb.username"));
dsRsgb.setPassword(DBPROPS.getProperty("rsgb.password"));
dsRsgb.setAccessToUnderlyingConnectionAllowed(true);
dsRsgb.setConnectionProperties(DBPROPS.getProperty("rsgb.options", ""));
rsgb = new DatabaseDataSourceConnection(dsRsgb);
setupJNDI(dsRsgb, null);
rsgb.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactory());
sequential.lock();
}
@AfterEach
public void cleanup() throws Exception {
response = null;
rsgb.close();
sequential.unlock();
}
/**
* test of er een geldige zipfile met de genoemde json bestanden uit de service komt.
*
* @throws IOException if any
*/
@Test
public void testValidZipforJsonReturned() throws IOException {
response = client.execute(new HttpGet(BASE_TEST_URL + "rest/mutaties?van=2018-12-01&tot=2019-01-01&f=json"));
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode(), "Response status is niet OK.");
int filesInZip = 0;
try (ZipInputStream zis = new ZipInputStream(response.getEntity().getContent())) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOG.debug("file: " + entry.getName() + ", compressed size: " + entry.getCompressedSize());
assertTrue(jsonNames.containsKey(entry.getName()), "De verwachte sleutel komt niet voor");
StringBuilder actual = new StringBuilder();
byte[] buffer = new byte[1024];
int read = 0;
while (zis.available() > 0) {
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
actual.append(new String(buffer, 0, read));
}
}
// TODO check inhoud van entry bijvoorbeeld {"bsnaangevuld":[]}
//assertJsonEquals("{\"" + jsonNames.get(entry.getName()) + "\":[]}", actual.toString());
// check dat de node begint met bijv. '{"bsnaangevuld":['
assertTrue(actual.toString().startsWith("{\"" + jsonNames.get(entry.getName()) + "\":["));
LOG.trace("json data dump voor: " + entry.getName() + "\n##################\n" + actual);
filesInZip++;
}
}
assertEquals(jsonNames.size(), filesInZip, "Onverwacht aantal json files in zipfile");
// see: https://stackoverflow.com/questions/2085637/how-to-check-if-a-generated-zip-file-is-corrupted
}
/**
* test of er een geldige zipfile met de genoemde csv bestanden uit de service komt.
*
* @throws IOException if any
*/
@Test
@Ignore
public void testValidZipforCSVReturned() throws IOException {
response = client.execute(new HttpGet(BASE_TEST_URL + "rest/mutaties?van=2018-12-01&tot=2019-02-01&f=csv"));
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode(), "Response status is niet OK.");
int filesInZip = 0;
try (ZipInputStream zis = new ZipInputStream(response.getEntity().getContent())) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOG.debug("file: " + entry.getName() + ", compressed size: " + entry.getCompressedSize());
assertTrue(cvsNames.contains(entry.getName()), "De verwachte sleutel komt niet voor");
StringBuilder actual = new StringBuilder("csv data dump voor: " + entry.getName() + "\n##################\n");
byte[] buffer = new byte[1024];
int read = 0;
while (zis.available() > 0) {
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
actual.append(new String(buffer, 0, read));
}
}
LOG.trace(actual);
// TODO evt<SUF>
// begin_geldigheid;soort;geslachtsnaam;voorvoegsel;voornamen;naam;woonadres;geboortedatum;overlijdensdatum;bsn;rsin;kvk_nummer;straatnaam;huisnummer;huisletter;huisnummer_toev;postcode;woonplaats
filesInZip++;
}
}
assertEquals(cvsNames.size(), filesInZip, "Onverwacht aantal csv files in zipfile");
}
}
|
117221_1 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.datastorelinker.gui.stripes;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import net.sf.json.JSONArray;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesRequestWrapper;
import net.sourceforge.stripes.util.Log;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.commons.stripes.Transactional;
import nl.b3p.datastorelinker.entity.Inout;
import nl.b3p.datastorelinker.entity.Organization;
import nl.b3p.datastorelinker.json.ArraySuccessMessage;
import nl.b3p.datastorelinker.json.JSONResolution;
import nl.b3p.datastorelinker.json.ProgressMessage;
import nl.b3p.datastorelinker.json.UploaderStatus;
import nl.b3p.datastorelinker.uploadprogress.UploadProgressListener;
import nl.b3p.datastorelinker.util.DefaultErrorResolution;
import nl.b3p.datastorelinker.util.Dir;
import nl.b3p.datastorelinker.util.DirContent;
import org.hibernate.Session;
/**
*
* @author Erik van de Pol
*/
@Transactional
public class FileAction extends DefaultAction {
private final static Log log = Log.getInstance(FileAction.class);
protected final static String SHAPE_EXT = ".shp";
protected final static String ZIP_EXT = ".zip";
protected final static String PRETTY_DIR_SEPARATOR = "/";
protected final static String[] ALLOWED_CONTENT_TYPES = {
""
};
private final static String CREATE_JSP = "/WEB-INF/jsp/main/file/create.jsp";
private final static String LIST_JSP = "/WEB-INF/jsp/main/file/list.jsp";
private final static String WRAPPER_JSP = "/WEB-INF/jsp/main/file/filetreeWrapper.jsp";
private final static String ADMIN_JSP = "/WEB-INF/jsp/management/fileAdmin.jsp";
private final static String DIRCONTENTS_JSP = "/WEB-INF/jsp/main/file/filetreeConnector.jsp";
private DirContent dirContent;
private FileBean filedata;
private UploaderStatus uploaderStatus;
private String dir;
private String expandTo;
private String selectedFilePath;
private String selectedFilePaths;
private boolean adminPage = false;
public Resolution listDir() {
log.debug("Directory requested: " + dir);
log.debug("expandTo: " + expandTo);
Boolean expandDir = Boolean.valueOf(getContext().getServletContext().getInitParameter("expandAllDirsDirectly"));
File directory = null;
if (dir != null) {
// wordt dit niet gewoon goed geregeld met user privileges?
// De tomcat user kan in *nix niet naar de root / parent dir?
// Voorbeelden bekijken / info inwinnen.
if (dir.contains("..")) {
log.error("Possible hack attempt; Dir requested: " + dir);
return null;
}
directory = getFileFromPPFileName(dir);
} else {
directory = getOrganizationUploadDir();
}
if (expandDir) {
dirContent = getDirContent(directory, null,expandDir);
} else if (expandTo == null) {
dirContent = getDirContent(directory, null,expandDir);
} else {
selectedFilePath = expandTo.trim().replace("\n", "").replace("\r", "");
log.debug("selectedFilePath/expandTo: " + selectedFilePath);
List<String> subDirList = new LinkedList<String>();
File currentDirFile = getFileFromPPFileName(selectedFilePath);
while (!currentDirFile.getAbsolutePath().equals(directory.getAbsolutePath())) {
subDirList.add(0, currentDirFile.getName());
currentDirFile = currentDirFile.getParentFile();
}
dirContent = getDirContent(directory, subDirList,expandDir);
}
//log.debug("dirs: " + directories.size());
//log.debug("files: " + files.size());
return new ForwardResolution(DIRCONTENTS_JSP);
}
protected DirContent getDirContent(File directory, List<String> subDirList, Boolean expandDirs) {
DirContent dc = new DirContent();
File[] dirs = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
List<Dir> dirsList = new ArrayList<Dir>();
if (dirs != null) {
for (File dir : dirs) {
Dir newDir = new Dir();
newDir.setName(dir.getName());
newDir.setPath(getFileNameRelativeToUploadDirPP(dir));
dirsList.add(newDir);
}
}
List<nl.b3p.datastorelinker.util.File> filesList = new ArrayList<nl.b3p.datastorelinker.util.File>();
if (files != null) {
for (File file : files) {
nl.b3p.datastorelinker.util.File newFile = new nl.b3p.datastorelinker.util.File();
newFile.setName(file.getName());
newFile.setPath(getFileNameRelativeToUploadDirPP(file));
filesList.add(newFile);
}
}
Collections.sort(dirsList, new DirExtensionComparator());
Collections.sort(filesList, new FileExtensionComparator());
dc.setDirs(dirsList);
dc.setFiles(filesList);
filterOutFilesToHide(dc);
if (expandDirs) {
for (Dir subDir : dc.getDirs()) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, null,expandDirs));
}
} else if (subDirList != null && subDirList.size() > 0) {
String subDirString = subDirList.remove(0);
for (Dir subDir : dc.getDirs()) {
if (subDir.getName().equals(subDirString)) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, subDirList,expandDirs));
break;
}
}
}
return dc;
}
protected void filterOutFilesToHide(DirContent dc) {
filterOutShapeExtraFiles(dc);
}
protected void filterOutShapeExtraFiles(DirContent dc) {
List<String> shapeNames = new ArrayList<String>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().endsWith(SHAPE_EXT)) {
shapeNames.add(file.getName().substring(0, file.getName().length() - SHAPE_EXT.length()));
}
}
for (String shapeName : shapeNames) {
List<nl.b3p.datastorelinker.util.File> toBeIgnoredFiles = new ArrayList<nl.b3p.datastorelinker.util.File>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().startsWith(shapeName) && !file.getName().endsWith(SHAPE_EXT)) {
toBeIgnoredFiles.add(file);
}
}
for (nl.b3p.datastorelinker.util.File file : toBeIgnoredFiles) {
dc.getFiles().remove(file);
}
}
}
public Resolution admin() {
list();
return new ForwardResolution(ADMIN_JSP);
}
public Resolution list() {
return new ForwardResolution(LIST_JSP);
}
public Resolution deleteCheck() {
log.debug(selectedFilePaths);
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
try {
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String pathToDelete = (String) filePathObj;
String relativePathToDelete = pathToDelete.replace(PRETTY_DIR_SEPARATOR, File.separator);
File fileToDelete = new File(getUploadDirectoryIOFile(), relativePathToDelete);
List<LocalizableMessage> deleteMessages = deleteCheckImpl(fileToDelete);
messages.addAll(deleteMessages);
}
} catch (IOException ioex) {
log.error(ioex);
// Still needed?
// if anything goes wrong here something is wrong with the uploadDir.
}
if (messages.isEmpty()) {
return new JSONResolution(new ArraySuccessMessage(true));
} else {
JSONArray jsonArray = new JSONArray();
for (LocalizableMessage m : messages) {
jsonArray.element(m.getMessage(getContext().getLocale()));
}
return new JSONResolution(new ArraySuccessMessage(false, jsonArray));
}
}
private List<LocalizableMessage> deleteCheckImpl(File fileToDelete) throws IOException {
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
if (fileToDelete.isDirectory()) {
for (File fileInDir : fileToDelete.listFiles()) {
messages.addAll(deleteCheckImpl(fileInDir));
}
} else {
String ppFileName = getFileNameRelativeToUploadDirPP(fileToDelete);
List<Inout> inouts = getDependingInouts(fileToDelete);
if (inouts != null && !inouts.isEmpty()) {
for (Inout inout : inouts) {
if (inout.getType() == Inout.Type.INPUT) {
messages.add(new LocalizableMessage("file.inuseInput", ppFileName, inout.getName()));
if (inout.getInputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getInputProcessList()) {
messages.add(new LocalizableMessage("input.inuse", inout.getName(), process.getName()));
}
}
} else { // output
messages.add(new LocalizableMessage("file.inuseOutput", ppFileName, inout.getName()));
if (inout.getOutputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getOutputProcessList()) {
messages.add(new LocalizableMessage("output.inuse", inout.getName(), process.getName()));
}
}
}
}
}
}
return messages;
}
private List<Inout> getDependingInouts(File file) throws IOException {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
List<Inout> inouts = session.createQuery("from Inout where file = :file").setParameter("file", file.getAbsolutePath()).list();
return inouts;
}
private File getFileFromPPFileName(String fileName) {
return getFileFromPPFileName(fileName, getContext());
}
private String getFileNameFromPPFileName(String fileName) {
File file = getFileFromPPFileName(fileName);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
private static File getFileFromPPFileName(String fileName, ActionBeanContext context) {
String subPath = fileName.replace(PRETTY_DIR_SEPARATOR, File.separator);
return new File(getUploadDirectoryIOFile(context), subPath);
}
public static String getFileNameFromPPFileName(String fileName, ActionBeanContext context) {
File file = getFileFromPPFileName(fileName, context);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
// Pretty printed version of getFileNameRelativeToUploadDir(File file).
// This name is uniform on all systems where the server runs (*nix or Windows).
public static String getFileNameRelativeToUploadDirPP(String file, ActionBeanContext context) {
return getFileNameRelativeToUploadDirPP(new File(file), context);
}
private String getFileNameRelativeToUploadDirPP(File file) {
return getFileNameRelativeToUploadDirPP(file, getContext());
}
private static String getFileNameRelativeToUploadDirPP(File file, ActionBeanContext context) {
String name = getFileNameRelativeToUploadDir(file, context);
if (name == null) {
return null;
} else {
return name.replace(File.separator, PRETTY_DIR_SEPARATOR);
}
}
private String getFileNameRelativeToUploadDir(File file) {
return getFileNameRelativeToUploadDir(file, getContext());
}
private static String getFileNameRelativeToUploadDir(File file, ActionBeanContext context) {
String absName = file.getAbsolutePath();
String uploadDir = getUploadDirectory(context);
if (uploadDir == null || !absName.startsWith(uploadDir)) {
return null;
} else {
return absName.substring(getUploadDirectory(context).length());
}
}
public Resolution delete() {
log.debug(selectedFilePaths);
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String filePath = (String) filePathObj;
deleteImpl(getFileFromPPFileName(filePath));
}
return list();
}
protected void deleteImpl(File file) {
if (file != null) {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
// file could already be deleted if an ancestor directory was also deleted in the same request.
if (!file.isDirectory() && file.exists()) {
boolean deleteSuccess = file.delete();
if (!deleteSuccess) {
log.error("Failed to delete file: " + file.getAbsolutePath());
}
}
try {
List<Inout> inouts = getDependingInouts(file);
for (Inout inout : inouts) {
session.delete(inout);
}
} catch (IOException ioex) {
log.error(ioex);
}
deleteExtraShapeFilesInSameDir(file);
deleteDirIfDir(file);
}
}
private void deleteExtraShapeFilesInSameDir(final File file) {
if (!file.isDirectory() && file.getName().endsWith(SHAPE_EXT)) {
final String fileBaseName = file.getName().substring(0, file.getName().length() - SHAPE_EXT.length());
File currentDir = file.getParentFile();
log.debug("currentDir == " + currentDir);
if (currentDir != null && currentDir.exists()) {
File[] extraShapeFilesInDir = currentDir.listFiles(new FileFilter() {
public boolean accept(File extraFile) {
return extraFile.getName().startsWith(fileBaseName)
&& extraFile.getName().length() == file.getName().length();
}
});
for (File extraShapeFile : extraShapeFilesInDir) {
if (!extraShapeFile.isDirectory()) {
deleteImpl(extraShapeFile);
}
}
}
}
}
protected void deleteDirIfDir(File dir) {
// Does this still apply?
// can be null if we tried to delete a directory first and then
// one or more (recursively) deleted files within it.
if (dir != null && dir.isDirectory() && dir.exists()) {
for (File fileInDir : dir.listFiles()) {
deleteImpl(fileInDir);
}
// dir must be empty when deleting it
boolean deleteDirSuccess = dir.delete();
if (!deleteDirSuccess) {
log.error("Failed to delete dir: " + dir.getAbsolutePath() + "; This could happen if the dir was not empty at the time of deletion. This should not happen.");
}
}
}
@DontValidate
public Resolution create() {
return new ForwardResolution(CREATE_JSP);
}
public Resolution createComplete() {
//return list();
return new ForwardResolution(WRAPPER_JSP);
}
@SuppressWarnings("unused")
@Before(stages = LifecycleStage.BindingAndValidation)
private void rehydrate() {
StripesRequestWrapper req = StripesRequestWrapper.findStripesWrapper(getContext().getRequest());
try {
if (req.isMultipart()) {
filedata = req.getFileParameterValue("uploader");
} /*else if (req.getParameter("status") != null) {
log.debug("req.getParameter('status'): " + req.getParameter("status"));
JSONObject jsonObject = JSONObject.fromObject(req.getParameter("status"));
uploaderStatus = (UploaderStatus) JSONObject.toBean(jsonObject, UploaderStatus.class);
}*/
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@DefaultHandler
public Resolution upload() {
if (filedata != null) {
log.debug("Filedata: " + filedata.getFileName());
try {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
if (isZipFile(filedata.getFileName())) {
File tempFile = File.createTempFile(filedata.getFileName() , null);
tempFile.delete();
filedata.save(tempFile);
File zipDir = new File(getOrganizationUploadString(), getZipName(filedata.getFileName()));
extractZip(tempFile, zipDir);
} else {
File destinationFile = new File(dirFile, filedata.getFileName());
filedata.save(destinationFile);
log.info("Saved file " + destinationFile.getAbsolutePath() + ", Successfully!");
selectedFilePath = getFileNameRelativeToUploadDirPP(destinationFile);
log.debug("selectedFilePath: " + selectedFilePath);
}
} catch (IOException e) {
String errorMsg = e.getMessage();
log.error("Error while writing file: " + filedata.getFileName() + " :: " + errorMsg);
return new DefaultErrorResolution(errorMsg);
}
return createComplete();
}
return new DefaultErrorResolution("An unknown error has occurred!");
}
public Resolution uploadProgress() {
int progress;
UploadProgressListener listener = (UploadProgressListener) getContext().getRequest().getSession().getAttribute(UploadProgressListener.class.toString());
if (listener != null) {
progress = (int) (listener.getProgress() * 100);
} else {
progress = 100;
}
return new JSONResolution(new ProgressMessage(progress));
}
/**
* Extract a zip tempfile to a directory. The tempfile will be deleted by
* this method.
*
* @param tempFile The zip file to extract. This tempfile will be deleted by
* this method.
* @param zipDir Directory to extract files into
* @throws IOException
*/
private void extractZip(File tempFile, File zipDir) throws IOException {
if (!tempFile.exists()) {
return;
}
if (!zipDir.exists()) {
zipDir.mkdirs();
}
byte[] buffer = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry = null;
try {
zipinputstream = new ZipInputStream(new FileInputStream(tempFile));
while ((zipentry = zipinputstream.getNextEntry()) != null) {
log.debug("extractZip zipentry name: " + zipentry.getName());
File newFile = new File(zipDir, zipentry.getName());
if (zipentry.isDirectory()) {
// ZipInputStream does not work recursively
// files within this directory will be encountered as a later zipEntry
newFile.mkdirs();
} else if (isZipFile(zipentry.getName())) {
// If the zipfile is in a subdir of the zip,
// we have to extract the filename without the dir.
// It seems the zip-implementation of java always uses "/"
// as file separator in a zip. Even on a windows system.
int lastIndexOfFileSeparator = zipentry.getName().lastIndexOf("/");
String zipName = null;
if (lastIndexOfFileSeparator < 0) {
zipName = zipentry.getName().substring(0);
} else {
zipName = zipentry.getName().substring(lastIndexOfFileSeparator + 1);
}
File tempZipFile = File.createTempFile(zipName + ".", null);
File newZipDir = new File(zipDir, getZipName(zipentry.getName()));
copyZipEntryTo(zipinputstream, tempZipFile, buffer);
extractZip(tempZipFile, newZipDir);
} else {
// TODO: is valid file in zip (delete newFile if necessary)
copyZipEntryTo(zipinputstream, newFile, buffer);
}
zipinputstream.closeEntry();
}
} catch (IOException ioex) {
if (zipentry == null) {
throw ioex;
} else {
throw new IOException(ioex.getMessage()
+ "\nProcessing zip entry: " + zipentry.getName());
}
} finally {
if (zipinputstream != null) {
zipinputstream.close();
}
boolean deleteSuccess = tempFile.delete();
/*if (!deleteSuccess)
log.warn("Could not delete: " + tempFile.getAbsolutePath());*/
}
}
private void copyZipEntryTo(ZipInputStream zipinputstream, File newFile, byte[] buffer) throws IOException {
FileOutputStream fileoutputstream = null;
try {
fileoutputstream = new FileOutputStream(newFile);
int n;
while ((n = zipinputstream.read(buffer)) > -1) {
fileoutputstream.write(buffer, 0, n);
}
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
}
}
public Resolution check() {
if (uploaderStatus != null) {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdir();
}
File tempFile = new File(dirFile, uploaderStatus.getFname());
log.debug(tempFile.getAbsolutePath());
log.debug(tempFile.getPath());
log.debug("check fpath: ");
if (uploaderStatus.getFpath() != null) {
log.debug(uploaderStatus.getFpath());
}
// TODO: check ook op andere dingen, size enzo. Dit blijft natuurlijk alleen maar een convenience check. Heeft niets met safety te maken.
Map resultMap = new HashMap();
// TODO: exists check is niet goed
if (tempFile.exists()) {
uploaderStatus.setErrtype("exists");
}
if (isZipFile(tempFile) && zipFileToDirFile(tempFile, new File(getOrganizationUploadString())).exists()) {
uploaderStatus.setErrtype("exists");
} else {
uploaderStatus.setErrtype("none");
}
resultMap.put("0", uploaderStatus);
return new JSONResolution(resultMap);
}
return new JSONResolution(false);
}
private boolean isZipFile(String fileName) {
return fileName.toLowerCase().endsWith(ZIP_EXT);
}
private boolean isZipFile(File file) {
return isZipFile(file.getName());
}
private String getZipName(String zipFileName) {
return zipFileName.substring(0, zipFileName.length() - ZIP_EXT.length());
}
private String getZipName(File zipFile) {
return getZipName(zipFile.getName());
}
private File zipFileToDirFile(File zipFile, File parent) {
return new File(parent, getZipName(zipFile));
}
private String getUploadDirectory() {
return getUploadDirectory(getContext());
}
public static String getUploadDirectory(ActionBeanContext context) {
return getUploadDirectoryIOFile(context).getAbsolutePath();
}
private File getUploadDirectoryIOFile() {
return getUploadDirectoryIOFile(getContext());
}
public static File getUploadDirectoryIOFile(ActionBeanContext context) {
return new File(context.getServletContext().getInitParameter("uploadDirectory"));
}
public DirContent getDirContent() {
return dirContent;
}
public void setDirContent(DirContent dirContent) {
this.dirContent = dirContent;
}
public String getExpandTo() {
return expandTo;
}
public void setExpandTo(String expandTo) {
this.expandTo = expandTo;
}
public String getSelectedFilePaths() {
return selectedFilePaths;
}
public void setSelectedFilePaths(String selectedFilePaths) {
this.selectedFilePaths = selectedFilePaths;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSelectedFilePath() {
return selectedFilePath;
}
public void setSelectedFilePath(String selectedFilePath) {
this.selectedFilePath = selectedFilePath;
}
public boolean getAdminPage() {
return adminPage;
}
public void setAdminPage(boolean adminPage) {
this.adminPage = adminPage;
}
public File getOrganizationUploadDir() {
if (isUserAdmin()) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory"));
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath());
}
return null;
}
public String getOrganizationUploadString() {
String uploadPath = null;
if (isUserAdmin()) {
return getContext().getServletContext().getInitParameter("uploadDirectory");
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
uploadPath = getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath();
}
return uploadPath;
}
// <editor-fold defaultstate="collapsed" desc="Comparison methods for file/dir sorting">
private int compareExtensions(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an extension (otherwise we'll end up comparing the extension of one
// to the start of the other, or else throwing an exception)
final int s1Dot = s1.lastIndexOf('.');
final int s2Dot = s2.lastIndexOf('.');
if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
s1 = s1.substring(s1Dot + 1);
s2 = s2.substring(s2Dot + 1);
return s1.compareTo(s2);
} else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
return -1;
} else { // only s1 has an extension, so s1 goes second
return 1;
}
}
private class DirExtensionComparator implements Comparator<Dir> {
@Override
public int compare(Dir d1, Dir d2) {
String s1 = d1.getName();
String s2 = d2.getName();
return compareExtensions(s1, s2);
}
}
private class FileExtensionComparator implements Comparator<nl.b3p.datastorelinker.util.File> {
@Override
public int compare(nl.b3p.datastorelinker.util.File f1, nl.b3p.datastorelinker.util.File f2) {
String s1 = f1.getName();
String s2 = f2.getName();
return compareExtensions(s1, s2);
}
}
// </editor-fold>
}
| B3Partners/datastorelinker | datastorelinker/src/main/java/nl/b3p/datastorelinker/gui/stripes/FileAction.java | 8,148 | /**
*
* @author Erik van de Pol
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.datastorelinker.gui.stripes;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import net.sf.json.JSONArray;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesRequestWrapper;
import net.sourceforge.stripes.util.Log;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.commons.stripes.Transactional;
import nl.b3p.datastorelinker.entity.Inout;
import nl.b3p.datastorelinker.entity.Organization;
import nl.b3p.datastorelinker.json.ArraySuccessMessage;
import nl.b3p.datastorelinker.json.JSONResolution;
import nl.b3p.datastorelinker.json.ProgressMessage;
import nl.b3p.datastorelinker.json.UploaderStatus;
import nl.b3p.datastorelinker.uploadprogress.UploadProgressListener;
import nl.b3p.datastorelinker.util.DefaultErrorResolution;
import nl.b3p.datastorelinker.util.Dir;
import nl.b3p.datastorelinker.util.DirContent;
import org.hibernate.Session;
/**
*
* @author Erik van<SUF>*/
@Transactional
public class FileAction extends DefaultAction {
private final static Log log = Log.getInstance(FileAction.class);
protected final static String SHAPE_EXT = ".shp";
protected final static String ZIP_EXT = ".zip";
protected final static String PRETTY_DIR_SEPARATOR = "/";
protected final static String[] ALLOWED_CONTENT_TYPES = {
""
};
private final static String CREATE_JSP = "/WEB-INF/jsp/main/file/create.jsp";
private final static String LIST_JSP = "/WEB-INF/jsp/main/file/list.jsp";
private final static String WRAPPER_JSP = "/WEB-INF/jsp/main/file/filetreeWrapper.jsp";
private final static String ADMIN_JSP = "/WEB-INF/jsp/management/fileAdmin.jsp";
private final static String DIRCONTENTS_JSP = "/WEB-INF/jsp/main/file/filetreeConnector.jsp";
private DirContent dirContent;
private FileBean filedata;
private UploaderStatus uploaderStatus;
private String dir;
private String expandTo;
private String selectedFilePath;
private String selectedFilePaths;
private boolean adminPage = false;
public Resolution listDir() {
log.debug("Directory requested: " + dir);
log.debug("expandTo: " + expandTo);
Boolean expandDir = Boolean.valueOf(getContext().getServletContext().getInitParameter("expandAllDirsDirectly"));
File directory = null;
if (dir != null) {
// wordt dit niet gewoon goed geregeld met user privileges?
// De tomcat user kan in *nix niet naar de root / parent dir?
// Voorbeelden bekijken / info inwinnen.
if (dir.contains("..")) {
log.error("Possible hack attempt; Dir requested: " + dir);
return null;
}
directory = getFileFromPPFileName(dir);
} else {
directory = getOrganizationUploadDir();
}
if (expandDir) {
dirContent = getDirContent(directory, null,expandDir);
} else if (expandTo == null) {
dirContent = getDirContent(directory, null,expandDir);
} else {
selectedFilePath = expandTo.trim().replace("\n", "").replace("\r", "");
log.debug("selectedFilePath/expandTo: " + selectedFilePath);
List<String> subDirList = new LinkedList<String>();
File currentDirFile = getFileFromPPFileName(selectedFilePath);
while (!currentDirFile.getAbsolutePath().equals(directory.getAbsolutePath())) {
subDirList.add(0, currentDirFile.getName());
currentDirFile = currentDirFile.getParentFile();
}
dirContent = getDirContent(directory, subDirList,expandDir);
}
//log.debug("dirs: " + directories.size());
//log.debug("files: " + files.size());
return new ForwardResolution(DIRCONTENTS_JSP);
}
protected DirContent getDirContent(File directory, List<String> subDirList, Boolean expandDirs) {
DirContent dc = new DirContent();
File[] dirs = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
List<Dir> dirsList = new ArrayList<Dir>();
if (dirs != null) {
for (File dir : dirs) {
Dir newDir = new Dir();
newDir.setName(dir.getName());
newDir.setPath(getFileNameRelativeToUploadDirPP(dir));
dirsList.add(newDir);
}
}
List<nl.b3p.datastorelinker.util.File> filesList = new ArrayList<nl.b3p.datastorelinker.util.File>();
if (files != null) {
for (File file : files) {
nl.b3p.datastorelinker.util.File newFile = new nl.b3p.datastorelinker.util.File();
newFile.setName(file.getName());
newFile.setPath(getFileNameRelativeToUploadDirPP(file));
filesList.add(newFile);
}
}
Collections.sort(dirsList, new DirExtensionComparator());
Collections.sort(filesList, new FileExtensionComparator());
dc.setDirs(dirsList);
dc.setFiles(filesList);
filterOutFilesToHide(dc);
if (expandDirs) {
for (Dir subDir : dc.getDirs()) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, null,expandDirs));
}
} else if (subDirList != null && subDirList.size() > 0) {
String subDirString = subDirList.remove(0);
for (Dir subDir : dc.getDirs()) {
if (subDir.getName().equals(subDirString)) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, subDirList,expandDirs));
break;
}
}
}
return dc;
}
protected void filterOutFilesToHide(DirContent dc) {
filterOutShapeExtraFiles(dc);
}
protected void filterOutShapeExtraFiles(DirContent dc) {
List<String> shapeNames = new ArrayList<String>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().endsWith(SHAPE_EXT)) {
shapeNames.add(file.getName().substring(0, file.getName().length() - SHAPE_EXT.length()));
}
}
for (String shapeName : shapeNames) {
List<nl.b3p.datastorelinker.util.File> toBeIgnoredFiles = new ArrayList<nl.b3p.datastorelinker.util.File>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().startsWith(shapeName) && !file.getName().endsWith(SHAPE_EXT)) {
toBeIgnoredFiles.add(file);
}
}
for (nl.b3p.datastorelinker.util.File file : toBeIgnoredFiles) {
dc.getFiles().remove(file);
}
}
}
public Resolution admin() {
list();
return new ForwardResolution(ADMIN_JSP);
}
public Resolution list() {
return new ForwardResolution(LIST_JSP);
}
public Resolution deleteCheck() {
log.debug(selectedFilePaths);
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
try {
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String pathToDelete = (String) filePathObj;
String relativePathToDelete = pathToDelete.replace(PRETTY_DIR_SEPARATOR, File.separator);
File fileToDelete = new File(getUploadDirectoryIOFile(), relativePathToDelete);
List<LocalizableMessage> deleteMessages = deleteCheckImpl(fileToDelete);
messages.addAll(deleteMessages);
}
} catch (IOException ioex) {
log.error(ioex);
// Still needed?
// if anything goes wrong here something is wrong with the uploadDir.
}
if (messages.isEmpty()) {
return new JSONResolution(new ArraySuccessMessage(true));
} else {
JSONArray jsonArray = new JSONArray();
for (LocalizableMessage m : messages) {
jsonArray.element(m.getMessage(getContext().getLocale()));
}
return new JSONResolution(new ArraySuccessMessage(false, jsonArray));
}
}
private List<LocalizableMessage> deleteCheckImpl(File fileToDelete) throws IOException {
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
if (fileToDelete.isDirectory()) {
for (File fileInDir : fileToDelete.listFiles()) {
messages.addAll(deleteCheckImpl(fileInDir));
}
} else {
String ppFileName = getFileNameRelativeToUploadDirPP(fileToDelete);
List<Inout> inouts = getDependingInouts(fileToDelete);
if (inouts != null && !inouts.isEmpty()) {
for (Inout inout : inouts) {
if (inout.getType() == Inout.Type.INPUT) {
messages.add(new LocalizableMessage("file.inuseInput", ppFileName, inout.getName()));
if (inout.getInputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getInputProcessList()) {
messages.add(new LocalizableMessage("input.inuse", inout.getName(), process.getName()));
}
}
} else { // output
messages.add(new LocalizableMessage("file.inuseOutput", ppFileName, inout.getName()));
if (inout.getOutputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getOutputProcessList()) {
messages.add(new LocalizableMessage("output.inuse", inout.getName(), process.getName()));
}
}
}
}
}
}
return messages;
}
private List<Inout> getDependingInouts(File file) throws IOException {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
List<Inout> inouts = session.createQuery("from Inout where file = :file").setParameter("file", file.getAbsolutePath()).list();
return inouts;
}
private File getFileFromPPFileName(String fileName) {
return getFileFromPPFileName(fileName, getContext());
}
private String getFileNameFromPPFileName(String fileName) {
File file = getFileFromPPFileName(fileName);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
private static File getFileFromPPFileName(String fileName, ActionBeanContext context) {
String subPath = fileName.replace(PRETTY_DIR_SEPARATOR, File.separator);
return new File(getUploadDirectoryIOFile(context), subPath);
}
public static String getFileNameFromPPFileName(String fileName, ActionBeanContext context) {
File file = getFileFromPPFileName(fileName, context);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
// Pretty printed version of getFileNameRelativeToUploadDir(File file).
// This name is uniform on all systems where the server runs (*nix or Windows).
public static String getFileNameRelativeToUploadDirPP(String file, ActionBeanContext context) {
return getFileNameRelativeToUploadDirPP(new File(file), context);
}
private String getFileNameRelativeToUploadDirPP(File file) {
return getFileNameRelativeToUploadDirPP(file, getContext());
}
private static String getFileNameRelativeToUploadDirPP(File file, ActionBeanContext context) {
String name = getFileNameRelativeToUploadDir(file, context);
if (name == null) {
return null;
} else {
return name.replace(File.separator, PRETTY_DIR_SEPARATOR);
}
}
private String getFileNameRelativeToUploadDir(File file) {
return getFileNameRelativeToUploadDir(file, getContext());
}
private static String getFileNameRelativeToUploadDir(File file, ActionBeanContext context) {
String absName = file.getAbsolutePath();
String uploadDir = getUploadDirectory(context);
if (uploadDir == null || !absName.startsWith(uploadDir)) {
return null;
} else {
return absName.substring(getUploadDirectory(context).length());
}
}
public Resolution delete() {
log.debug(selectedFilePaths);
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String filePath = (String) filePathObj;
deleteImpl(getFileFromPPFileName(filePath));
}
return list();
}
protected void deleteImpl(File file) {
if (file != null) {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
// file could already be deleted if an ancestor directory was also deleted in the same request.
if (!file.isDirectory() && file.exists()) {
boolean deleteSuccess = file.delete();
if (!deleteSuccess) {
log.error("Failed to delete file: " + file.getAbsolutePath());
}
}
try {
List<Inout> inouts = getDependingInouts(file);
for (Inout inout : inouts) {
session.delete(inout);
}
} catch (IOException ioex) {
log.error(ioex);
}
deleteExtraShapeFilesInSameDir(file);
deleteDirIfDir(file);
}
}
private void deleteExtraShapeFilesInSameDir(final File file) {
if (!file.isDirectory() && file.getName().endsWith(SHAPE_EXT)) {
final String fileBaseName = file.getName().substring(0, file.getName().length() - SHAPE_EXT.length());
File currentDir = file.getParentFile();
log.debug("currentDir == " + currentDir);
if (currentDir != null && currentDir.exists()) {
File[] extraShapeFilesInDir = currentDir.listFiles(new FileFilter() {
public boolean accept(File extraFile) {
return extraFile.getName().startsWith(fileBaseName)
&& extraFile.getName().length() == file.getName().length();
}
});
for (File extraShapeFile : extraShapeFilesInDir) {
if (!extraShapeFile.isDirectory()) {
deleteImpl(extraShapeFile);
}
}
}
}
}
protected void deleteDirIfDir(File dir) {
// Does this still apply?
// can be null if we tried to delete a directory first and then
// one or more (recursively) deleted files within it.
if (dir != null && dir.isDirectory() && dir.exists()) {
for (File fileInDir : dir.listFiles()) {
deleteImpl(fileInDir);
}
// dir must be empty when deleting it
boolean deleteDirSuccess = dir.delete();
if (!deleteDirSuccess) {
log.error("Failed to delete dir: " + dir.getAbsolutePath() + "; This could happen if the dir was not empty at the time of deletion. This should not happen.");
}
}
}
@DontValidate
public Resolution create() {
return new ForwardResolution(CREATE_JSP);
}
public Resolution createComplete() {
//return list();
return new ForwardResolution(WRAPPER_JSP);
}
@SuppressWarnings("unused")
@Before(stages = LifecycleStage.BindingAndValidation)
private void rehydrate() {
StripesRequestWrapper req = StripesRequestWrapper.findStripesWrapper(getContext().getRequest());
try {
if (req.isMultipart()) {
filedata = req.getFileParameterValue("uploader");
} /*else if (req.getParameter("status") != null) {
log.debug("req.getParameter('status'): " + req.getParameter("status"));
JSONObject jsonObject = JSONObject.fromObject(req.getParameter("status"));
uploaderStatus = (UploaderStatus) JSONObject.toBean(jsonObject, UploaderStatus.class);
}*/
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@DefaultHandler
public Resolution upload() {
if (filedata != null) {
log.debug("Filedata: " + filedata.getFileName());
try {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
if (isZipFile(filedata.getFileName())) {
File tempFile = File.createTempFile(filedata.getFileName() , null);
tempFile.delete();
filedata.save(tempFile);
File zipDir = new File(getOrganizationUploadString(), getZipName(filedata.getFileName()));
extractZip(tempFile, zipDir);
} else {
File destinationFile = new File(dirFile, filedata.getFileName());
filedata.save(destinationFile);
log.info("Saved file " + destinationFile.getAbsolutePath() + ", Successfully!");
selectedFilePath = getFileNameRelativeToUploadDirPP(destinationFile);
log.debug("selectedFilePath: " + selectedFilePath);
}
} catch (IOException e) {
String errorMsg = e.getMessage();
log.error("Error while writing file: " + filedata.getFileName() + " :: " + errorMsg);
return new DefaultErrorResolution(errorMsg);
}
return createComplete();
}
return new DefaultErrorResolution("An unknown error has occurred!");
}
public Resolution uploadProgress() {
int progress;
UploadProgressListener listener = (UploadProgressListener) getContext().getRequest().getSession().getAttribute(UploadProgressListener.class.toString());
if (listener != null) {
progress = (int) (listener.getProgress() * 100);
} else {
progress = 100;
}
return new JSONResolution(new ProgressMessage(progress));
}
/**
* Extract a zip tempfile to a directory. The tempfile will be deleted by
* this method.
*
* @param tempFile The zip file to extract. This tempfile will be deleted by
* this method.
* @param zipDir Directory to extract files into
* @throws IOException
*/
private void extractZip(File tempFile, File zipDir) throws IOException {
if (!tempFile.exists()) {
return;
}
if (!zipDir.exists()) {
zipDir.mkdirs();
}
byte[] buffer = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry = null;
try {
zipinputstream = new ZipInputStream(new FileInputStream(tempFile));
while ((zipentry = zipinputstream.getNextEntry()) != null) {
log.debug("extractZip zipentry name: " + zipentry.getName());
File newFile = new File(zipDir, zipentry.getName());
if (zipentry.isDirectory()) {
// ZipInputStream does not work recursively
// files within this directory will be encountered as a later zipEntry
newFile.mkdirs();
} else if (isZipFile(zipentry.getName())) {
// If the zipfile is in a subdir of the zip,
// we have to extract the filename without the dir.
// It seems the zip-implementation of java always uses "/"
// as file separator in a zip. Even on a windows system.
int lastIndexOfFileSeparator = zipentry.getName().lastIndexOf("/");
String zipName = null;
if (lastIndexOfFileSeparator < 0) {
zipName = zipentry.getName().substring(0);
} else {
zipName = zipentry.getName().substring(lastIndexOfFileSeparator + 1);
}
File tempZipFile = File.createTempFile(zipName + ".", null);
File newZipDir = new File(zipDir, getZipName(zipentry.getName()));
copyZipEntryTo(zipinputstream, tempZipFile, buffer);
extractZip(tempZipFile, newZipDir);
} else {
// TODO: is valid file in zip (delete newFile if necessary)
copyZipEntryTo(zipinputstream, newFile, buffer);
}
zipinputstream.closeEntry();
}
} catch (IOException ioex) {
if (zipentry == null) {
throw ioex;
} else {
throw new IOException(ioex.getMessage()
+ "\nProcessing zip entry: " + zipentry.getName());
}
} finally {
if (zipinputstream != null) {
zipinputstream.close();
}
boolean deleteSuccess = tempFile.delete();
/*if (!deleteSuccess)
log.warn("Could not delete: " + tempFile.getAbsolutePath());*/
}
}
private void copyZipEntryTo(ZipInputStream zipinputstream, File newFile, byte[] buffer) throws IOException {
FileOutputStream fileoutputstream = null;
try {
fileoutputstream = new FileOutputStream(newFile);
int n;
while ((n = zipinputstream.read(buffer)) > -1) {
fileoutputstream.write(buffer, 0, n);
}
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
}
}
public Resolution check() {
if (uploaderStatus != null) {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdir();
}
File tempFile = new File(dirFile, uploaderStatus.getFname());
log.debug(tempFile.getAbsolutePath());
log.debug(tempFile.getPath());
log.debug("check fpath: ");
if (uploaderStatus.getFpath() != null) {
log.debug(uploaderStatus.getFpath());
}
// TODO: check ook op andere dingen, size enzo. Dit blijft natuurlijk alleen maar een convenience check. Heeft niets met safety te maken.
Map resultMap = new HashMap();
// TODO: exists check is niet goed
if (tempFile.exists()) {
uploaderStatus.setErrtype("exists");
}
if (isZipFile(tempFile) && zipFileToDirFile(tempFile, new File(getOrganizationUploadString())).exists()) {
uploaderStatus.setErrtype("exists");
} else {
uploaderStatus.setErrtype("none");
}
resultMap.put("0", uploaderStatus);
return new JSONResolution(resultMap);
}
return new JSONResolution(false);
}
private boolean isZipFile(String fileName) {
return fileName.toLowerCase().endsWith(ZIP_EXT);
}
private boolean isZipFile(File file) {
return isZipFile(file.getName());
}
private String getZipName(String zipFileName) {
return zipFileName.substring(0, zipFileName.length() - ZIP_EXT.length());
}
private String getZipName(File zipFile) {
return getZipName(zipFile.getName());
}
private File zipFileToDirFile(File zipFile, File parent) {
return new File(parent, getZipName(zipFile));
}
private String getUploadDirectory() {
return getUploadDirectory(getContext());
}
public static String getUploadDirectory(ActionBeanContext context) {
return getUploadDirectoryIOFile(context).getAbsolutePath();
}
private File getUploadDirectoryIOFile() {
return getUploadDirectoryIOFile(getContext());
}
public static File getUploadDirectoryIOFile(ActionBeanContext context) {
return new File(context.getServletContext().getInitParameter("uploadDirectory"));
}
public DirContent getDirContent() {
return dirContent;
}
public void setDirContent(DirContent dirContent) {
this.dirContent = dirContent;
}
public String getExpandTo() {
return expandTo;
}
public void setExpandTo(String expandTo) {
this.expandTo = expandTo;
}
public String getSelectedFilePaths() {
return selectedFilePaths;
}
public void setSelectedFilePaths(String selectedFilePaths) {
this.selectedFilePaths = selectedFilePaths;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSelectedFilePath() {
return selectedFilePath;
}
public void setSelectedFilePath(String selectedFilePath) {
this.selectedFilePath = selectedFilePath;
}
public boolean getAdminPage() {
return adminPage;
}
public void setAdminPage(boolean adminPage) {
this.adminPage = adminPage;
}
public File getOrganizationUploadDir() {
if (isUserAdmin()) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory"));
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath());
}
return null;
}
public String getOrganizationUploadString() {
String uploadPath = null;
if (isUserAdmin()) {
return getContext().getServletContext().getInitParameter("uploadDirectory");
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
uploadPath = getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath();
}
return uploadPath;
}
// <editor-fold defaultstate="collapsed" desc="Comparison methods for file/dir sorting">
private int compareExtensions(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an extension (otherwise we'll end up comparing the extension of one
// to the start of the other, or else throwing an exception)
final int s1Dot = s1.lastIndexOf('.');
final int s2Dot = s2.lastIndexOf('.');
if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
s1 = s1.substring(s1Dot + 1);
s2 = s2.substring(s2Dot + 1);
return s1.compareTo(s2);
} else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
return -1;
} else { // only s1 has an extension, so s1 goes second
return 1;
}
}
private class DirExtensionComparator implements Comparator<Dir> {
@Override
public int compare(Dir d1, Dir d2) {
String s1 = d1.getName();
String s2 = d2.getName();
return compareExtensions(s1, s2);
}
}
private class FileExtensionComparator implements Comparator<nl.b3p.datastorelinker.util.File> {
@Override
public int compare(nl.b3p.datastorelinker.util.File f1, nl.b3p.datastorelinker.util.File f2) {
String s1 = f1.getName();
String s2 = f2.getName();
return compareExtensions(s1, s2);
}
}
// </editor-fold>
}
|
117220_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.datastorelinker.gui.stripes;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import net.sf.json.JSONArray;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesRequestWrapper;
import net.sourceforge.stripes.util.Log;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.commons.stripes.Transactional;
import nl.b3p.datastorelinker.entity.Inout;
import nl.b3p.datastorelinker.entity.Organization;
import nl.b3p.datastorelinker.json.ArraySuccessMessage;
import nl.b3p.datastorelinker.json.JSONResolution;
import nl.b3p.datastorelinker.json.ProgressMessage;
import nl.b3p.datastorelinker.json.UploaderStatus;
import nl.b3p.datastorelinker.uploadprogress.UploadProgressListener;
import nl.b3p.datastorelinker.util.DefaultErrorResolution;
import nl.b3p.datastorelinker.util.Dir;
import nl.b3p.datastorelinker.util.DirContent;
import org.hibernate.Session;
/**
*
* @author Erik van de Pol
*/
@Transactional
public class FileAction extends DefaultAction {
private final static Log log = Log.getInstance(FileAction.class);
protected final static String SHAPE_EXT = ".shp";
protected final static String ZIP_EXT = ".zip";
protected final static String PRETTY_DIR_SEPARATOR = "/";
protected final static String[] ALLOWED_CONTENT_TYPES = {
""
};
private final static String CREATE_JSP = "/WEB-INF/jsp/main/file/create.jsp";
private final static String LIST_JSP = "/WEB-INF/jsp/main/file/list.jsp";
private final static String WRAPPER_JSP = "/WEB-INF/jsp/main/file/filetreeWrapper.jsp";
private final static String ADMIN_JSP = "/WEB-INF/jsp/management/fileAdmin.jsp";
private final static String DIRCONTENTS_JSP = "/WEB-INF/jsp/main/file/filetreeConnector.jsp";
private DirContent dirContent;
private FileBean filedata;
private UploaderStatus uploaderStatus;
private String dir;
private String expandTo;
private String selectedFilePath;
private String selectedFilePaths;
private boolean adminPage = false;
public Resolution listDir() {
log.debug("Directory requested: " + dir);
log.debug("expandTo: " + expandTo);
Boolean expandDir = Boolean.valueOf(getContext().getServletContext().getInitParameter("expandAllDirsDirectly"));
File directory = null;
if (dir != null) {
// wordt dit niet gewoon goed geregeld met user privileges?
// De tomcat user kan in *nix niet naar de root / parent dir?
// Voorbeelden bekijken / info inwinnen.
if (dir.contains("..")) {
log.error("Possible hack attempt; Dir requested: " + dir);
return null;
}
directory = getFileFromPPFileName(dir);
} else {
directory = getOrganizationUploadDir();
}
if (expandDir) {
dirContent = getDirContent(directory, null,expandDir);
} else if (expandTo == null) {
dirContent = getDirContent(directory, null,expandDir);
} else {
selectedFilePath = expandTo.trim().replace("\n", "").replace("\r", "");
log.debug("selectedFilePath/expandTo: " + selectedFilePath);
List<String> subDirList = new LinkedList<String>();
File currentDirFile = getFileFromPPFileName(selectedFilePath);
while (!currentDirFile.getAbsolutePath().equals(directory.getAbsolutePath())) {
subDirList.add(0, currentDirFile.getName());
currentDirFile = currentDirFile.getParentFile();
}
dirContent = getDirContent(directory, subDirList,expandDir);
}
//log.debug("dirs: " + directories.size());
//log.debug("files: " + files.size());
return new ForwardResolution(DIRCONTENTS_JSP);
}
protected DirContent getDirContent(File directory, List<String> subDirList, Boolean expandDirs) {
DirContent dc = new DirContent();
File[] dirs = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
List<Dir> dirsList = new ArrayList<Dir>();
if (dirs != null) {
for (File dir : dirs) {
Dir newDir = new Dir();
newDir.setName(dir.getName());
newDir.setPath(getFileNameRelativeToUploadDirPP(dir));
dirsList.add(newDir);
}
}
List<nl.b3p.datastorelinker.util.File> filesList = new ArrayList<nl.b3p.datastorelinker.util.File>();
if (files != null) {
for (File file : files) {
nl.b3p.datastorelinker.util.File newFile = new nl.b3p.datastorelinker.util.File();
newFile.setName(file.getName());
newFile.setPath(getFileNameRelativeToUploadDirPP(file));
filesList.add(newFile);
}
}
Collections.sort(dirsList, new DirExtensionComparator());
Collections.sort(filesList, new FileExtensionComparator());
dc.setDirs(dirsList);
dc.setFiles(filesList);
filterOutFilesToHide(dc);
if (expandDirs) {
for (Dir subDir : dc.getDirs()) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, null,expandDirs));
}
} else if (subDirList != null && subDirList.size() > 0) {
String subDirString = subDirList.remove(0);
for (Dir subDir : dc.getDirs()) {
if (subDir.getName().equals(subDirString)) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, subDirList,expandDirs));
break;
}
}
}
return dc;
}
protected void filterOutFilesToHide(DirContent dc) {
filterOutShapeExtraFiles(dc);
}
protected void filterOutShapeExtraFiles(DirContent dc) {
List<String> shapeNames = new ArrayList<String>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().endsWith(SHAPE_EXT)) {
shapeNames.add(file.getName().substring(0, file.getName().length() - SHAPE_EXT.length()));
}
}
for (String shapeName : shapeNames) {
List<nl.b3p.datastorelinker.util.File> toBeIgnoredFiles = new ArrayList<nl.b3p.datastorelinker.util.File>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().startsWith(shapeName) && !file.getName().endsWith(SHAPE_EXT)) {
toBeIgnoredFiles.add(file);
}
}
for (nl.b3p.datastorelinker.util.File file : toBeIgnoredFiles) {
dc.getFiles().remove(file);
}
}
}
public Resolution admin() {
list();
return new ForwardResolution(ADMIN_JSP);
}
public Resolution list() {
return new ForwardResolution(LIST_JSP);
}
public Resolution deleteCheck() {
log.debug(selectedFilePaths);
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
try {
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String pathToDelete = (String) filePathObj;
String relativePathToDelete = pathToDelete.replace(PRETTY_DIR_SEPARATOR, File.separator);
File fileToDelete = new File(getUploadDirectoryIOFile(), relativePathToDelete);
List<LocalizableMessage> deleteMessages = deleteCheckImpl(fileToDelete);
messages.addAll(deleteMessages);
}
} catch (IOException ioex) {
log.error(ioex);
// Still needed?
// if anything goes wrong here something is wrong with the uploadDir.
}
if (messages.isEmpty()) {
return new JSONResolution(new ArraySuccessMessage(true));
} else {
JSONArray jsonArray = new JSONArray();
for (LocalizableMessage m : messages) {
jsonArray.element(m.getMessage(getContext().getLocale()));
}
return new JSONResolution(new ArraySuccessMessage(false, jsonArray));
}
}
private List<LocalizableMessage> deleteCheckImpl(File fileToDelete) throws IOException {
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
if (fileToDelete.isDirectory()) {
for (File fileInDir : fileToDelete.listFiles()) {
messages.addAll(deleteCheckImpl(fileInDir));
}
} else {
String ppFileName = getFileNameRelativeToUploadDirPP(fileToDelete);
List<Inout> inouts = getDependingInouts(fileToDelete);
if (inouts != null && !inouts.isEmpty()) {
for (Inout inout : inouts) {
if (inout.getType() == Inout.Type.INPUT) {
messages.add(new LocalizableMessage("file.inuseInput", ppFileName, inout.getName()));
if (inout.getInputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getInputProcessList()) {
messages.add(new LocalizableMessage("input.inuse", inout.getName(), process.getName()));
}
}
} else { // output
messages.add(new LocalizableMessage("file.inuseOutput", ppFileName, inout.getName()));
if (inout.getOutputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getOutputProcessList()) {
messages.add(new LocalizableMessage("output.inuse", inout.getName(), process.getName()));
}
}
}
}
}
}
return messages;
}
private List<Inout> getDependingInouts(File file) throws IOException {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
List<Inout> inouts = session.createQuery("from Inout where file = :file").setParameter("file", file.getAbsolutePath()).list();
return inouts;
}
private File getFileFromPPFileName(String fileName) {
return getFileFromPPFileName(fileName, getContext());
}
private String getFileNameFromPPFileName(String fileName) {
File file = getFileFromPPFileName(fileName);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
private static File getFileFromPPFileName(String fileName, ActionBeanContext context) {
String subPath = fileName.replace(PRETTY_DIR_SEPARATOR, File.separator);
return new File(getUploadDirectoryIOFile(context), subPath);
}
public static String getFileNameFromPPFileName(String fileName, ActionBeanContext context) {
File file = getFileFromPPFileName(fileName, context);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
// Pretty printed version of getFileNameRelativeToUploadDir(File file).
// This name is uniform on all systems where the server runs (*nix or Windows).
public static String getFileNameRelativeToUploadDirPP(String file, ActionBeanContext context) {
return getFileNameRelativeToUploadDirPP(new File(file), context);
}
private String getFileNameRelativeToUploadDirPP(File file) {
return getFileNameRelativeToUploadDirPP(file, getContext());
}
private static String getFileNameRelativeToUploadDirPP(File file, ActionBeanContext context) {
String name = getFileNameRelativeToUploadDir(file, context);
if (name == null) {
return null;
} else {
return name.replace(File.separator, PRETTY_DIR_SEPARATOR);
}
}
private String getFileNameRelativeToUploadDir(File file) {
return getFileNameRelativeToUploadDir(file, getContext());
}
private static String getFileNameRelativeToUploadDir(File file, ActionBeanContext context) {
String absName = file.getAbsolutePath();
String uploadDir = getUploadDirectory(context);
if (uploadDir == null || !absName.startsWith(uploadDir)) {
return null;
} else {
return absName.substring(getUploadDirectory(context).length());
}
}
public Resolution delete() {
log.debug(selectedFilePaths);
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String filePath = (String) filePathObj;
deleteImpl(getFileFromPPFileName(filePath));
}
return list();
}
protected void deleteImpl(File file) {
if (file != null) {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
// file could already be deleted if an ancestor directory was also deleted in the same request.
if (!file.isDirectory() && file.exists()) {
boolean deleteSuccess = file.delete();
if (!deleteSuccess) {
log.error("Failed to delete file: " + file.getAbsolutePath());
}
}
try {
List<Inout> inouts = getDependingInouts(file);
for (Inout inout : inouts) {
session.delete(inout);
}
} catch (IOException ioex) {
log.error(ioex);
}
deleteExtraShapeFilesInSameDir(file);
deleteDirIfDir(file);
}
}
private void deleteExtraShapeFilesInSameDir(final File file) {
if (!file.isDirectory() && file.getName().endsWith(SHAPE_EXT)) {
final String fileBaseName = file.getName().substring(0, file.getName().length() - SHAPE_EXT.length());
File currentDir = file.getParentFile();
log.debug("currentDir == " + currentDir);
if (currentDir != null && currentDir.exists()) {
File[] extraShapeFilesInDir = currentDir.listFiles(new FileFilter() {
public boolean accept(File extraFile) {
return extraFile.getName().startsWith(fileBaseName)
&& extraFile.getName().length() == file.getName().length();
}
});
for (File extraShapeFile : extraShapeFilesInDir) {
if (!extraShapeFile.isDirectory()) {
deleteImpl(extraShapeFile);
}
}
}
}
}
protected void deleteDirIfDir(File dir) {
// Does this still apply?
// can be null if we tried to delete a directory first and then
// one or more (recursively) deleted files within it.
if (dir != null && dir.isDirectory() && dir.exists()) {
for (File fileInDir : dir.listFiles()) {
deleteImpl(fileInDir);
}
// dir must be empty when deleting it
boolean deleteDirSuccess = dir.delete();
if (!deleteDirSuccess) {
log.error("Failed to delete dir: " + dir.getAbsolutePath() + "; This could happen if the dir was not empty at the time of deletion. This should not happen.");
}
}
}
@DontValidate
public Resolution create() {
return new ForwardResolution(CREATE_JSP);
}
public Resolution createComplete() {
//return list();
return new ForwardResolution(WRAPPER_JSP);
}
@SuppressWarnings("unused")
@Before(stages = LifecycleStage.BindingAndValidation)
private void rehydrate() {
StripesRequestWrapper req = StripesRequestWrapper.findStripesWrapper(getContext().getRequest());
try {
if (req.isMultipart()) {
filedata = req.getFileParameterValue("uploader");
} /*else if (req.getParameter("status") != null) {
log.debug("req.getParameter('status'): " + req.getParameter("status"));
JSONObject jsonObject = JSONObject.fromObject(req.getParameter("status"));
uploaderStatus = (UploaderStatus) JSONObject.toBean(jsonObject, UploaderStatus.class);
}*/
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@DefaultHandler
public Resolution upload() {
if (filedata != null) {
log.debug("Filedata: " + filedata.getFileName());
try {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
if (isZipFile(filedata.getFileName())) {
File tempFile = File.createTempFile(filedata.getFileName() + ".", null);
filedata.save(tempFile);
File zipDir = new File(getOrganizationUploadString(), getZipName(filedata.getFileName()));
extractZip(tempFile, zipDir);
} else {
File destinationFile = new File(dirFile, filedata.getFileName());
filedata.save(destinationFile);
log.info("Saved file " + destinationFile.getAbsolutePath() + ", Successfully!");
selectedFilePath = getFileNameRelativeToUploadDirPP(destinationFile);
log.debug("selectedFilePath: " + selectedFilePath);
}
} catch (IOException e) {
String errorMsg = e.getMessage();
log.error("Error while writing file: " + filedata.getFileName() + " :: " + errorMsg);
return new DefaultErrorResolution(errorMsg);
}
return createComplete();
}
return new DefaultErrorResolution("An unknown error has occurred!");
}
public Resolution uploadProgress() {
int progress;
UploadProgressListener listener = (UploadProgressListener) getContext().getRequest().getSession().getAttribute(UploadProgressListener.class.toString());
if (listener != null) {
progress = (int) (listener.getProgress() * 100);
} else {
progress = 100;
}
return new JSONResolution(new ProgressMessage(progress));
}
/**
* Extract a zip tempfile to a directory. The tempfile will be deleted by
* this method.
*
* @param tempFile The zip file to extract. This tempfile will be deleted by
* this method.
* @param zipDir Directory to extract files into
* @throws IOException
*/
private void extractZip(File tempFile, File zipDir) throws IOException {
if (!tempFile.exists()) {
return;
}
if (!zipDir.exists()) {
zipDir.mkdirs();
}
byte[] buffer = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry = null;
try {
zipinputstream = new ZipInputStream(new FileInputStream(tempFile));
while ((zipentry = zipinputstream.getNextEntry()) != null) {
log.debug("extractZip zipentry name: " + zipentry.getName());
File newFile = new File(zipDir, zipentry.getName());
if (zipentry.isDirectory()) {
// ZipInputStream does not work recursively
// files within this directory will be encountered as a later zipEntry
newFile.mkdirs();
} else if (isZipFile(zipentry.getName())) {
// If the zipfile is in a subdir of the zip,
// we have to extract the filename without the dir.
// It seems the zip-implementation of java always uses "/"
// as file separator in a zip. Even on a windows system.
int lastIndexOfFileSeparator = zipentry.getName().lastIndexOf("/");
String zipName = null;
if (lastIndexOfFileSeparator < 0) {
zipName = zipentry.getName().substring(0);
} else {
zipName = zipentry.getName().substring(lastIndexOfFileSeparator + 1);
}
File tempZipFile = File.createTempFile(zipName + ".", null);
File newZipDir = new File(zipDir, getZipName(zipentry.getName()));
copyZipEntryTo(zipinputstream, tempZipFile, buffer);
extractZip(tempZipFile, newZipDir);
} else {
// TODO: is valid file in zip (delete newFile if necessary)
copyZipEntryTo(zipinputstream, newFile, buffer);
}
zipinputstream.closeEntry();
}
} catch (IOException ioex) {
if (zipentry == null) {
throw ioex;
} else {
throw new IOException(ioex.getMessage()
+ "\nProcessing zip entry: " + zipentry.getName());
}
} finally {
if (zipinputstream != null) {
zipinputstream.close();
}
boolean deleteSuccess = tempFile.delete();
/*if (!deleteSuccess)
log.warn("Could not delete: " + tempFile.getAbsolutePath());*/
}
}
private void copyZipEntryTo(ZipInputStream zipinputstream, File newFile, byte[] buffer) throws IOException {
FileOutputStream fileoutputstream = null;
try {
fileoutputstream = new FileOutputStream(newFile);
int n;
while ((n = zipinputstream.read(buffer)) > -1) {
fileoutputstream.write(buffer, 0, n);
}
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
}
}
public Resolution check() {
if (uploaderStatus != null) {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdir();
}
File tempFile = new File(dirFile, uploaderStatus.getFname());
log.debug(tempFile.getAbsolutePath());
log.debug(tempFile.getPath());
log.debug("check fpath: ");
if (uploaderStatus.getFpath() != null) {
log.debug(uploaderStatus.getFpath());
}
// TODO: check ook op andere dingen, size enzo. Dit blijft natuurlijk alleen maar een convenience check. Heeft niets met safety te maken.
Map resultMap = new HashMap();
// TODO: exists check is niet goed
if (tempFile.exists()) {
uploaderStatus.setErrtype("exists");
}
if (isZipFile(tempFile) && zipFileToDirFile(tempFile, new File(getOrganizationUploadString())).exists()) {
uploaderStatus.setErrtype("exists");
} else {
uploaderStatus.setErrtype("none");
}
resultMap.put("0", uploaderStatus);
return new JSONResolution(resultMap);
}
return new JSONResolution(false);
}
private boolean isZipFile(String fileName) {
return fileName.toLowerCase().endsWith(ZIP_EXT);
}
private boolean isZipFile(File file) {
return isZipFile(file.getName());
}
private String getZipName(String zipFileName) {
return zipFileName.substring(0, zipFileName.length() - ZIP_EXT.length());
}
private String getZipName(File zipFile) {
return getZipName(zipFile.getName());
}
private File zipFileToDirFile(File zipFile, File parent) {
return new File(parent, getZipName(zipFile));
}
private String getUploadDirectory() {
return getUploadDirectory(getContext());
}
public static String getUploadDirectory(ActionBeanContext context) {
return getUploadDirectoryIOFile(context).getAbsolutePath();
}
private File getUploadDirectoryIOFile() {
return getUploadDirectoryIOFile(getContext());
}
public static File getUploadDirectoryIOFile(ActionBeanContext context) {
return new File(context.getServletContext().getInitParameter("uploadDirectory"));
}
public DirContent getDirContent() {
return dirContent;
}
public void setDirContent(DirContent dirContent) {
this.dirContent = dirContent;
}
public String getExpandTo() {
return expandTo;
}
public void setExpandTo(String expandTo) {
this.expandTo = expandTo;
}
public String getSelectedFilePaths() {
return selectedFilePaths;
}
public void setSelectedFilePaths(String selectedFilePaths) {
this.selectedFilePaths = selectedFilePaths;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSelectedFilePath() {
return selectedFilePath;
}
public void setSelectedFilePath(String selectedFilePath) {
this.selectedFilePath = selectedFilePath;
}
public boolean getAdminPage() {
return adminPage;
}
public void setAdminPage(boolean adminPage) {
this.adminPage = adminPage;
}
public File getOrganizationUploadDir() {
if (isUserAdmin()) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory"));
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath());
}
return null;
}
public String getOrganizationUploadString() {
String uploadPath = null;
if (isUserAdmin()) {
return getContext().getServletContext().getInitParameter("uploadDirectory");
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
uploadPath = getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath();
}
return uploadPath;
}
// <editor-fold defaultstate="collapsed" desc="Comparison methods for file/dir sorting">
private int compareExtensions(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an extension (otherwise we'll end up comparing the extension of one
// to the start of the other, or else throwing an exception)
final int s1Dot = s1.lastIndexOf('.');
final int s2Dot = s2.lastIndexOf('.');
if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
s1 = s1.substring(s1Dot + 1);
s2 = s2.substring(s2Dot + 1);
return s1.compareTo(s2);
} else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
return -1;
} else { // only s1 has an extension, so s1 goes second
return 1;
}
}
private class DirExtensionComparator implements Comparator<Dir> {
@Override
public int compare(Dir d1, Dir d2) {
String s1 = d1.getName();
String s2 = d2.getName();
return compareExtensions(s1, s2);
}
}
private class FileExtensionComparator implements Comparator<nl.b3p.datastorelinker.util.File> {
@Override
public int compare(nl.b3p.datastorelinker.util.File f1, nl.b3p.datastorelinker.util.File f2) {
String s1 = f1.getName();
String s2 = f2.getName();
return compareExtensions(s1, s2);
}
}
// </editor-fold>
}
| B3Partners/datastorelinker.old | src/main/java/nl/b3p/datastorelinker/gui/stripes/FileAction.java | 8,142 | // Voorbeelden bekijken / info inwinnen. | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.datastorelinker.gui.stripes;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import net.sf.json.JSONArray;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesRequestWrapper;
import net.sourceforge.stripes.util.Log;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.commons.stripes.Transactional;
import nl.b3p.datastorelinker.entity.Inout;
import nl.b3p.datastorelinker.entity.Organization;
import nl.b3p.datastorelinker.json.ArraySuccessMessage;
import nl.b3p.datastorelinker.json.JSONResolution;
import nl.b3p.datastorelinker.json.ProgressMessage;
import nl.b3p.datastorelinker.json.UploaderStatus;
import nl.b3p.datastorelinker.uploadprogress.UploadProgressListener;
import nl.b3p.datastorelinker.util.DefaultErrorResolution;
import nl.b3p.datastorelinker.util.Dir;
import nl.b3p.datastorelinker.util.DirContent;
import org.hibernate.Session;
/**
*
* @author Erik van de Pol
*/
@Transactional
public class FileAction extends DefaultAction {
private final static Log log = Log.getInstance(FileAction.class);
protected final static String SHAPE_EXT = ".shp";
protected final static String ZIP_EXT = ".zip";
protected final static String PRETTY_DIR_SEPARATOR = "/";
protected final static String[] ALLOWED_CONTENT_TYPES = {
""
};
private final static String CREATE_JSP = "/WEB-INF/jsp/main/file/create.jsp";
private final static String LIST_JSP = "/WEB-INF/jsp/main/file/list.jsp";
private final static String WRAPPER_JSP = "/WEB-INF/jsp/main/file/filetreeWrapper.jsp";
private final static String ADMIN_JSP = "/WEB-INF/jsp/management/fileAdmin.jsp";
private final static String DIRCONTENTS_JSP = "/WEB-INF/jsp/main/file/filetreeConnector.jsp";
private DirContent dirContent;
private FileBean filedata;
private UploaderStatus uploaderStatus;
private String dir;
private String expandTo;
private String selectedFilePath;
private String selectedFilePaths;
private boolean adminPage = false;
public Resolution listDir() {
log.debug("Directory requested: " + dir);
log.debug("expandTo: " + expandTo);
Boolean expandDir = Boolean.valueOf(getContext().getServletContext().getInitParameter("expandAllDirsDirectly"));
File directory = null;
if (dir != null) {
// wordt dit niet gewoon goed geregeld met user privileges?
// De tomcat user kan in *nix niet naar de root / parent dir?
// Voorbeelden bekijken<SUF>
if (dir.contains("..")) {
log.error("Possible hack attempt; Dir requested: " + dir);
return null;
}
directory = getFileFromPPFileName(dir);
} else {
directory = getOrganizationUploadDir();
}
if (expandDir) {
dirContent = getDirContent(directory, null,expandDir);
} else if (expandTo == null) {
dirContent = getDirContent(directory, null,expandDir);
} else {
selectedFilePath = expandTo.trim().replace("\n", "").replace("\r", "");
log.debug("selectedFilePath/expandTo: " + selectedFilePath);
List<String> subDirList = new LinkedList<String>();
File currentDirFile = getFileFromPPFileName(selectedFilePath);
while (!currentDirFile.getAbsolutePath().equals(directory.getAbsolutePath())) {
subDirList.add(0, currentDirFile.getName());
currentDirFile = currentDirFile.getParentFile();
}
dirContent = getDirContent(directory, subDirList,expandDir);
}
//log.debug("dirs: " + directories.size());
//log.debug("files: " + files.size());
return new ForwardResolution(DIRCONTENTS_JSP);
}
protected DirContent getDirContent(File directory, List<String> subDirList, Boolean expandDirs) {
DirContent dc = new DirContent();
File[] dirs = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
List<Dir> dirsList = new ArrayList<Dir>();
if (dirs != null) {
for (File dir : dirs) {
Dir newDir = new Dir();
newDir.setName(dir.getName());
newDir.setPath(getFileNameRelativeToUploadDirPP(dir));
dirsList.add(newDir);
}
}
List<nl.b3p.datastorelinker.util.File> filesList = new ArrayList<nl.b3p.datastorelinker.util.File>();
if (files != null) {
for (File file : files) {
nl.b3p.datastorelinker.util.File newFile = new nl.b3p.datastorelinker.util.File();
newFile.setName(file.getName());
newFile.setPath(getFileNameRelativeToUploadDirPP(file));
filesList.add(newFile);
}
}
Collections.sort(dirsList, new DirExtensionComparator());
Collections.sort(filesList, new FileExtensionComparator());
dc.setDirs(dirsList);
dc.setFiles(filesList);
filterOutFilesToHide(dc);
if (expandDirs) {
for (Dir subDir : dc.getDirs()) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, null,expandDirs));
}
} else if (subDirList != null && subDirList.size() > 0) {
String subDirString = subDirList.remove(0);
for (Dir subDir : dc.getDirs()) {
if (subDir.getName().equals(subDirString)) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, subDirList,expandDirs));
break;
}
}
}
return dc;
}
protected void filterOutFilesToHide(DirContent dc) {
filterOutShapeExtraFiles(dc);
}
protected void filterOutShapeExtraFiles(DirContent dc) {
List<String> shapeNames = new ArrayList<String>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().endsWith(SHAPE_EXT)) {
shapeNames.add(file.getName().substring(0, file.getName().length() - SHAPE_EXT.length()));
}
}
for (String shapeName : shapeNames) {
List<nl.b3p.datastorelinker.util.File> toBeIgnoredFiles = new ArrayList<nl.b3p.datastorelinker.util.File>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().startsWith(shapeName) && !file.getName().endsWith(SHAPE_EXT)) {
toBeIgnoredFiles.add(file);
}
}
for (nl.b3p.datastorelinker.util.File file : toBeIgnoredFiles) {
dc.getFiles().remove(file);
}
}
}
public Resolution admin() {
list();
return new ForwardResolution(ADMIN_JSP);
}
public Resolution list() {
return new ForwardResolution(LIST_JSP);
}
public Resolution deleteCheck() {
log.debug(selectedFilePaths);
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
try {
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String pathToDelete = (String) filePathObj;
String relativePathToDelete = pathToDelete.replace(PRETTY_DIR_SEPARATOR, File.separator);
File fileToDelete = new File(getUploadDirectoryIOFile(), relativePathToDelete);
List<LocalizableMessage> deleteMessages = deleteCheckImpl(fileToDelete);
messages.addAll(deleteMessages);
}
} catch (IOException ioex) {
log.error(ioex);
// Still needed?
// if anything goes wrong here something is wrong with the uploadDir.
}
if (messages.isEmpty()) {
return new JSONResolution(new ArraySuccessMessage(true));
} else {
JSONArray jsonArray = new JSONArray();
for (LocalizableMessage m : messages) {
jsonArray.element(m.getMessage(getContext().getLocale()));
}
return new JSONResolution(new ArraySuccessMessage(false, jsonArray));
}
}
private List<LocalizableMessage> deleteCheckImpl(File fileToDelete) throws IOException {
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
if (fileToDelete.isDirectory()) {
for (File fileInDir : fileToDelete.listFiles()) {
messages.addAll(deleteCheckImpl(fileInDir));
}
} else {
String ppFileName = getFileNameRelativeToUploadDirPP(fileToDelete);
List<Inout> inouts = getDependingInouts(fileToDelete);
if (inouts != null && !inouts.isEmpty()) {
for (Inout inout : inouts) {
if (inout.getType() == Inout.Type.INPUT) {
messages.add(new LocalizableMessage("file.inuseInput", ppFileName, inout.getName()));
if (inout.getInputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getInputProcessList()) {
messages.add(new LocalizableMessage("input.inuse", inout.getName(), process.getName()));
}
}
} else { // output
messages.add(new LocalizableMessage("file.inuseOutput", ppFileName, inout.getName()));
if (inout.getOutputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getOutputProcessList()) {
messages.add(new LocalizableMessage("output.inuse", inout.getName(), process.getName()));
}
}
}
}
}
}
return messages;
}
private List<Inout> getDependingInouts(File file) throws IOException {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
List<Inout> inouts = session.createQuery("from Inout where file = :file").setParameter("file", file.getAbsolutePath()).list();
return inouts;
}
private File getFileFromPPFileName(String fileName) {
return getFileFromPPFileName(fileName, getContext());
}
private String getFileNameFromPPFileName(String fileName) {
File file = getFileFromPPFileName(fileName);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
private static File getFileFromPPFileName(String fileName, ActionBeanContext context) {
String subPath = fileName.replace(PRETTY_DIR_SEPARATOR, File.separator);
return new File(getUploadDirectoryIOFile(context), subPath);
}
public static String getFileNameFromPPFileName(String fileName, ActionBeanContext context) {
File file = getFileFromPPFileName(fileName, context);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
// Pretty printed version of getFileNameRelativeToUploadDir(File file).
// This name is uniform on all systems where the server runs (*nix or Windows).
public static String getFileNameRelativeToUploadDirPP(String file, ActionBeanContext context) {
return getFileNameRelativeToUploadDirPP(new File(file), context);
}
private String getFileNameRelativeToUploadDirPP(File file) {
return getFileNameRelativeToUploadDirPP(file, getContext());
}
private static String getFileNameRelativeToUploadDirPP(File file, ActionBeanContext context) {
String name = getFileNameRelativeToUploadDir(file, context);
if (name == null) {
return null;
} else {
return name.replace(File.separator, PRETTY_DIR_SEPARATOR);
}
}
private String getFileNameRelativeToUploadDir(File file) {
return getFileNameRelativeToUploadDir(file, getContext());
}
private static String getFileNameRelativeToUploadDir(File file, ActionBeanContext context) {
String absName = file.getAbsolutePath();
String uploadDir = getUploadDirectory(context);
if (uploadDir == null || !absName.startsWith(uploadDir)) {
return null;
} else {
return absName.substring(getUploadDirectory(context).length());
}
}
public Resolution delete() {
log.debug(selectedFilePaths);
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String filePath = (String) filePathObj;
deleteImpl(getFileFromPPFileName(filePath));
}
return list();
}
protected void deleteImpl(File file) {
if (file != null) {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
// file could already be deleted if an ancestor directory was also deleted in the same request.
if (!file.isDirectory() && file.exists()) {
boolean deleteSuccess = file.delete();
if (!deleteSuccess) {
log.error("Failed to delete file: " + file.getAbsolutePath());
}
}
try {
List<Inout> inouts = getDependingInouts(file);
for (Inout inout : inouts) {
session.delete(inout);
}
} catch (IOException ioex) {
log.error(ioex);
}
deleteExtraShapeFilesInSameDir(file);
deleteDirIfDir(file);
}
}
private void deleteExtraShapeFilesInSameDir(final File file) {
if (!file.isDirectory() && file.getName().endsWith(SHAPE_EXT)) {
final String fileBaseName = file.getName().substring(0, file.getName().length() - SHAPE_EXT.length());
File currentDir = file.getParentFile();
log.debug("currentDir == " + currentDir);
if (currentDir != null && currentDir.exists()) {
File[] extraShapeFilesInDir = currentDir.listFiles(new FileFilter() {
public boolean accept(File extraFile) {
return extraFile.getName().startsWith(fileBaseName)
&& extraFile.getName().length() == file.getName().length();
}
});
for (File extraShapeFile : extraShapeFilesInDir) {
if (!extraShapeFile.isDirectory()) {
deleteImpl(extraShapeFile);
}
}
}
}
}
protected void deleteDirIfDir(File dir) {
// Does this still apply?
// can be null if we tried to delete a directory first and then
// one or more (recursively) deleted files within it.
if (dir != null && dir.isDirectory() && dir.exists()) {
for (File fileInDir : dir.listFiles()) {
deleteImpl(fileInDir);
}
// dir must be empty when deleting it
boolean deleteDirSuccess = dir.delete();
if (!deleteDirSuccess) {
log.error("Failed to delete dir: " + dir.getAbsolutePath() + "; This could happen if the dir was not empty at the time of deletion. This should not happen.");
}
}
}
@DontValidate
public Resolution create() {
return new ForwardResolution(CREATE_JSP);
}
public Resolution createComplete() {
//return list();
return new ForwardResolution(WRAPPER_JSP);
}
@SuppressWarnings("unused")
@Before(stages = LifecycleStage.BindingAndValidation)
private void rehydrate() {
StripesRequestWrapper req = StripesRequestWrapper.findStripesWrapper(getContext().getRequest());
try {
if (req.isMultipart()) {
filedata = req.getFileParameterValue("uploader");
} /*else if (req.getParameter("status") != null) {
log.debug("req.getParameter('status'): " + req.getParameter("status"));
JSONObject jsonObject = JSONObject.fromObject(req.getParameter("status"));
uploaderStatus = (UploaderStatus) JSONObject.toBean(jsonObject, UploaderStatus.class);
}*/
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@DefaultHandler
public Resolution upload() {
if (filedata != null) {
log.debug("Filedata: " + filedata.getFileName());
try {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
if (isZipFile(filedata.getFileName())) {
File tempFile = File.createTempFile(filedata.getFileName() + ".", null);
filedata.save(tempFile);
File zipDir = new File(getOrganizationUploadString(), getZipName(filedata.getFileName()));
extractZip(tempFile, zipDir);
} else {
File destinationFile = new File(dirFile, filedata.getFileName());
filedata.save(destinationFile);
log.info("Saved file " + destinationFile.getAbsolutePath() + ", Successfully!");
selectedFilePath = getFileNameRelativeToUploadDirPP(destinationFile);
log.debug("selectedFilePath: " + selectedFilePath);
}
} catch (IOException e) {
String errorMsg = e.getMessage();
log.error("Error while writing file: " + filedata.getFileName() + " :: " + errorMsg);
return new DefaultErrorResolution(errorMsg);
}
return createComplete();
}
return new DefaultErrorResolution("An unknown error has occurred!");
}
public Resolution uploadProgress() {
int progress;
UploadProgressListener listener = (UploadProgressListener) getContext().getRequest().getSession().getAttribute(UploadProgressListener.class.toString());
if (listener != null) {
progress = (int) (listener.getProgress() * 100);
} else {
progress = 100;
}
return new JSONResolution(new ProgressMessage(progress));
}
/**
* Extract a zip tempfile to a directory. The tempfile will be deleted by
* this method.
*
* @param tempFile The zip file to extract. This tempfile will be deleted by
* this method.
* @param zipDir Directory to extract files into
* @throws IOException
*/
private void extractZip(File tempFile, File zipDir) throws IOException {
if (!tempFile.exists()) {
return;
}
if (!zipDir.exists()) {
zipDir.mkdirs();
}
byte[] buffer = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry = null;
try {
zipinputstream = new ZipInputStream(new FileInputStream(tempFile));
while ((zipentry = zipinputstream.getNextEntry()) != null) {
log.debug("extractZip zipentry name: " + zipentry.getName());
File newFile = new File(zipDir, zipentry.getName());
if (zipentry.isDirectory()) {
// ZipInputStream does not work recursively
// files within this directory will be encountered as a later zipEntry
newFile.mkdirs();
} else if (isZipFile(zipentry.getName())) {
// If the zipfile is in a subdir of the zip,
// we have to extract the filename without the dir.
// It seems the zip-implementation of java always uses "/"
// as file separator in a zip. Even on a windows system.
int lastIndexOfFileSeparator = zipentry.getName().lastIndexOf("/");
String zipName = null;
if (lastIndexOfFileSeparator < 0) {
zipName = zipentry.getName().substring(0);
} else {
zipName = zipentry.getName().substring(lastIndexOfFileSeparator + 1);
}
File tempZipFile = File.createTempFile(zipName + ".", null);
File newZipDir = new File(zipDir, getZipName(zipentry.getName()));
copyZipEntryTo(zipinputstream, tempZipFile, buffer);
extractZip(tempZipFile, newZipDir);
} else {
// TODO: is valid file in zip (delete newFile if necessary)
copyZipEntryTo(zipinputstream, newFile, buffer);
}
zipinputstream.closeEntry();
}
} catch (IOException ioex) {
if (zipentry == null) {
throw ioex;
} else {
throw new IOException(ioex.getMessage()
+ "\nProcessing zip entry: " + zipentry.getName());
}
} finally {
if (zipinputstream != null) {
zipinputstream.close();
}
boolean deleteSuccess = tempFile.delete();
/*if (!deleteSuccess)
log.warn("Could not delete: " + tempFile.getAbsolutePath());*/
}
}
private void copyZipEntryTo(ZipInputStream zipinputstream, File newFile, byte[] buffer) throws IOException {
FileOutputStream fileoutputstream = null;
try {
fileoutputstream = new FileOutputStream(newFile);
int n;
while ((n = zipinputstream.read(buffer)) > -1) {
fileoutputstream.write(buffer, 0, n);
}
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
}
}
public Resolution check() {
if (uploaderStatus != null) {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdir();
}
File tempFile = new File(dirFile, uploaderStatus.getFname());
log.debug(tempFile.getAbsolutePath());
log.debug(tempFile.getPath());
log.debug("check fpath: ");
if (uploaderStatus.getFpath() != null) {
log.debug(uploaderStatus.getFpath());
}
// TODO: check ook op andere dingen, size enzo. Dit blijft natuurlijk alleen maar een convenience check. Heeft niets met safety te maken.
Map resultMap = new HashMap();
// TODO: exists check is niet goed
if (tempFile.exists()) {
uploaderStatus.setErrtype("exists");
}
if (isZipFile(tempFile) && zipFileToDirFile(tempFile, new File(getOrganizationUploadString())).exists()) {
uploaderStatus.setErrtype("exists");
} else {
uploaderStatus.setErrtype("none");
}
resultMap.put("0", uploaderStatus);
return new JSONResolution(resultMap);
}
return new JSONResolution(false);
}
private boolean isZipFile(String fileName) {
return fileName.toLowerCase().endsWith(ZIP_EXT);
}
private boolean isZipFile(File file) {
return isZipFile(file.getName());
}
private String getZipName(String zipFileName) {
return zipFileName.substring(0, zipFileName.length() - ZIP_EXT.length());
}
private String getZipName(File zipFile) {
return getZipName(zipFile.getName());
}
private File zipFileToDirFile(File zipFile, File parent) {
return new File(parent, getZipName(zipFile));
}
private String getUploadDirectory() {
return getUploadDirectory(getContext());
}
public static String getUploadDirectory(ActionBeanContext context) {
return getUploadDirectoryIOFile(context).getAbsolutePath();
}
private File getUploadDirectoryIOFile() {
return getUploadDirectoryIOFile(getContext());
}
public static File getUploadDirectoryIOFile(ActionBeanContext context) {
return new File(context.getServletContext().getInitParameter("uploadDirectory"));
}
public DirContent getDirContent() {
return dirContent;
}
public void setDirContent(DirContent dirContent) {
this.dirContent = dirContent;
}
public String getExpandTo() {
return expandTo;
}
public void setExpandTo(String expandTo) {
this.expandTo = expandTo;
}
public String getSelectedFilePaths() {
return selectedFilePaths;
}
public void setSelectedFilePaths(String selectedFilePaths) {
this.selectedFilePaths = selectedFilePaths;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSelectedFilePath() {
return selectedFilePath;
}
public void setSelectedFilePath(String selectedFilePath) {
this.selectedFilePath = selectedFilePath;
}
public boolean getAdminPage() {
return adminPage;
}
public void setAdminPage(boolean adminPage) {
this.adminPage = adminPage;
}
public File getOrganizationUploadDir() {
if (isUserAdmin()) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory"));
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath());
}
return null;
}
public String getOrganizationUploadString() {
String uploadPath = null;
if (isUserAdmin()) {
return getContext().getServletContext().getInitParameter("uploadDirectory");
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
uploadPath = getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath();
}
return uploadPath;
}
// <editor-fold defaultstate="collapsed" desc="Comparison methods for file/dir sorting">
private int compareExtensions(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an extension (otherwise we'll end up comparing the extension of one
// to the start of the other, or else throwing an exception)
final int s1Dot = s1.lastIndexOf('.');
final int s2Dot = s2.lastIndexOf('.');
if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
s1 = s1.substring(s1Dot + 1);
s2 = s2.substring(s2Dot + 1);
return s1.compareTo(s2);
} else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
return -1;
} else { // only s1 has an extension, so s1 goes second
return 1;
}
}
private class DirExtensionComparator implements Comparator<Dir> {
@Override
public int compare(Dir d1, Dir d2) {
String s1 = d1.getName();
String s2 = d2.getName();
return compareExtensions(s1, s2);
}
}
private class FileExtensionComparator implements Comparator<nl.b3p.datastorelinker.util.File> {
@Override
public int compare(nl.b3p.datastorelinker.util.File f1, nl.b3p.datastorelinker.util.File f2) {
String s1 = f1.getName();
String s2 = f2.getName();
return compareExtensions(s1, s2);
}
}
// </editor-fold>
}
|
77098_9 | /*
* Copyright (C) 2015 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.stripes;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.ibis.util.IbisConstants;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKTReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import javax.persistence.EntityManager;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.services.Layer;
import nl.b3p.viewer.ibis.util.WorkflowStatus;
import nl.b3p.viewer.ibis.util.WorkflowUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.filter.identity.FeatureIdImpl;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortOrder;
import org.stripesstuff.stripersist.Stripersist;
/**
* edit component met ibis workflow.
*
* @author mprins
*/
@UrlBinding("/action/feature/ibisedit")
@StrictBinding
public class IbisEditFeatureActionBean extends EditFeatureActionBean implements IbisConstants {
private static final Log log = LogFactory.getLog(IbisEditFeatureActionBean.class);
@Validate
private boolean historisch;
@Validate
private boolean reject;
@Override
protected String addNewFeature() throws Exception {
String kavelID = super.addNewFeature();
//update terrein
Object terreinID = this.getJsonFeature().optString(KAVEL_TERREIN_ID_FIELDNAME, null);
WorkflowStatus status = WorkflowStatus.valueOf(this.getJsonFeature().optString(WORKFLOW_FIELDNAME, WorkflowStatus.bewerkt.name()));
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), status, this.getApplication(), Stripersist.getEntityManager());
}
return kavelID;
}
/**
* Override to not delete a feature but set workflow status to
* {@code WorkflowStatus.archief}
*
* @param fid feature id
* @throws IOException if any
* @throws Exception if any
* @see WorkflowStatus
*/
@Override
protected void deleteFeature(String fid) throws IOException, Exception {
if(this.isHistorisch()){
this.deleteFeatureHistorisch(fid);
} else if (this.isReject()){
this.rejectFeature(fid);
} else{
log.debug("ibis deleteFeature: " + fid);
Transaction transaction = new DefaultTransaction("ibis_delete");
this.getStore().setTransaction(transaction);
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
Filter filter = ff.id(new FeatureIdImpl(fid));
try {
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.afgevoerd, filter);
SimpleFeature original = this.getStore().getFeatures(filter).features().next();
transaction.commit();
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), WorkflowStatus.afgevoerd, this.getApplication(), Stripersist.getEntityManager());
}
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
}
/**
* verwijder historische record.
* Als het een "archief" record is dan gewoon verwijderen,
* als het een "afgevoerd" record is dan verwijderen en jongste "archief" record "afgevoerd" maken.
* als er geen "archief" te vinden is dan laten.
*
* @param fid feature to remove
* @throws IOException if any
* @throws Exception if any
*/
private void deleteFeatureHistorisch(String fid) throws IOException, Exception {
log.debug("ibis deleteFeatureHistorisch: " + fid);
Transaction transaction = new DefaultTransaction("ibis_delete_historisch");
this.getStore().setTransaction(transaction);
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
Filter fidFilter = ff.id(new FeatureIdImpl(fid));
Filter hist = ff.or(
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.archief.name()), false),
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.afgevoerd.name()), false)
);
try {
SimpleFeature original = this.getStore().getFeatures(fidFilter).features().next();
Number ibisId = (Number) original.getAttribute(ID_FIELDNAME);
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
log.debug(String.format("Delete from feature source #%d fid=%s",
this.getLayer().getFeatureType().getId(), fid));
switch (WorkflowStatus.valueOf( original.getAttribute(WORKFLOW_FIELDNAME).toString()) ) {
case archief:
// archief record gewoon verwijderen
this.getStore().removeFeatures(fidFilter);
break;
case afgevoerd:
// zoek alle historische kavels voor dit kavel nummer
SimpleFeatureCollection histRecords = this.getStore().getFeatures(
ff.and(
hist,
ff.equals(ff.property(ID_FIELDNAME), ff.literal(ibisId))
));
if (histRecords.size() > 1) {
// als er naast deze afgevoerd nog andere zijn
histRecords.sort(ff.sort(MUTATIEDATUM_FIELDNAME, SortOrder.DESCENDING));
// dan de jongste daarvan (eerste uit de lijst) op afgevoerd zetten
String updateFid = histRecords.features().next().getID();
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.afgevoerd, ff.id(new FeatureIdImpl(updateFid)));
// en gevraagde verwijderen uit database
this.getStore().removeFeatures(fidFilter);
}
break;
default:
throw new UnsupportedOperationException("Historische record met status anders dan 'archief' of 'afgevoerd' kan niet worden verwijderd.");
}
transaction.commit();
// update terrein van kavel
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), WorkflowStatus.afgevoerd, this.getApplication(), Stripersist.getEntityManager());
}
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
/** voor "afkeur" van een bewerkt kavel.
*
* @param fid feature to remove
* @throws Exception if any
*/
private void rejectFeature(String fid) throws Exception {
log.debug("ibis rejectFeature: " + fid);
Transaction transaction = new DefaultTransaction("ibis_reject");
this.getStore().setTransaction(transaction);
Filter filter = CommonFactoryFinder.getFilterFactory2().id(new FeatureIdImpl(fid));
try {
SimpleFeature original = this.getStore().getFeatures(filter).features().next();
if (!(original.getAttribute(WORKFLOW_FIELDNAME).toString().equalsIgnoreCase(WorkflowStatus.bewerkt.label()) &&
(this.getLayer().getName().equalsIgnoreCase(KAVEL_LAYER_NAME) || this.getLayer().getName().equalsIgnoreCase(TERREIN_LAYER_NAME)))) {
throw new IllegalArgumentException("Alleen 'bewerkt' kavels en terreinen kunnen worden afgekeurd.");
}
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
this.getStore().removeFeatures(filter);
transaction.commit();
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), WorkflowStatus.afgevoerd, this.getApplication(), Stripersist.getEntityManager());
}
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
/**
* Override the method from the base class to process our workflow.
*
* @param fid feature id
* @throws Exception if any
*/
@Override
protected void editFeature(String fid) throws Exception {
log.debug("ibis editFeature:" + fid);
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
Filter fidFilter = ff.id(new FeatureIdImpl(fid));
List<String> attributes = new ArrayList();
List values = new ArrayList();
WorkflowStatus incomingWorkflowStatus = null;
// parse json
for (Iterator<String> it = this.getJsonFeature().keys(); it.hasNext();) {
String attribute = it.next();
if (!this.getFID().equals(attribute)) {
AttributeDescriptor ad = this.getStore().getSchema().getDescriptor(attribute);
if (ad != null) {
if (!isAttributeUserEditingDisabled(attribute)) {
attributes.add(attribute);
if (ad.getType() instanceof GeometryType) {
String wkt = this.getJsonFeature().getString(ad.getLocalName());
Geometry g = null;
if (wkt != null) {
g = new WKTReader().read(wkt);
}
values.add(g);
} else {
String v = this.getJsonFeature().getString(attribute);
values.add(StringUtils.defaultIfBlank(v, null));
// remember the incoming workflow status
if (attribute.equals(WORKFLOW_FIELDNAME)) {
incomingWorkflowStatus = WorkflowStatus.valueOf(v);
}
}
} else {
log.info(String.format("Attribute \"%s\" not user editable; ignoring", attribute));
}
} else {
log.warn(String.format("Attribute \"%s\" not in feature type; ignoring", attribute));
}
}
}
log.debug(String.format("Modifying feature source #%d fid=%s, attributes=%s, values=%s",
this.getLayer().getFeatureType().getId(), fid, attributes.toString(), values.toString()));
Transaction editTransaction = new DefaultTransaction("ibis_edit");
this.getStore().setTransaction(editTransaction);
try {
if (incomingWorkflowStatus == null) {
throw new IllegalArgumentException("Workflow status van edit feature is null, dit wordt niet ondersteund.");
}
SimpleFeature original = this.getStore().getFeatures(fidFilter).features().next();
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
WorkflowStatus originalWorkflowStatus = WorkflowStatus.valueOf(original.getAttribute(WORKFLOW_FIELDNAME).toString());
// make a copy of the original feature and set (new) attribute values on the copy
SimpleFeature editedNewFeature = createCopy(original);
for (int i = 0; i < attributes.size(); i++) {
editedNewFeature.setAttribute(attributes.get(i), values.get(i));
}
Filter definitief = ff.and(
ff.equals(ff.property(ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME))),
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.definitief.name()), false)
);
boolean definitiefExists = (this.getStore().getFeatures(definitief).size() > 0);
Filter bewerkt = ff.and(
ff.equals(ff.property(ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME))),
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.bewerkt.name()), false)
);
int aantalBewerkt = this.getStore().getFeatures(bewerkt).size();
boolean bewerktExists = (aantalBewerkt > 0);
switch (incomingWorkflowStatus) {
case bewerkt:
if (originalWorkflowStatus.equals(WorkflowStatus.definitief)) {
// definitief -> bewerkt
if (bewerktExists) {
// delete existing bewerkt
this.getStore().removeFeatures(bewerkt);
}
// insert new record with original id and workflowstatus "bewerkt", leave original "definitief"
this.getStore().addFeatures(DataUtilities.collection(editedNewFeature));
} else if (originalWorkflowStatus.equals(WorkflowStatus.bewerkt)) {
// bewerkt -> bewerkt, overwrite, only one 'bewerkt' is allowed
if (aantalBewerkt > 1) {
log.error("Er is meer dan 1 bewerkt kavel/terrein voor " + ID_FIELDNAME + "=" + original.getAttribute(ID_FIELDNAME));
// more than 1 bewerkt, move them to archief
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, bewerkt);
}
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
} else {
// other behaviour not documented eg. archief -> bewerkt, afgevoerd -> bewerkt
// and not possible to occur in the application as only definitief and bewerkt can be edited
throw new IllegalArgumentException(String.format(
"Niet ondersteunde workflow stap van %s naar %s",
originalWorkflowStatus.label(),
incomingWorkflowStatus.label()));
}
break;
case definitief:
if (definitiefExists) {
// check if any "definitief" exists for this id and move that to "archief"
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, definitief);
}
if (originalWorkflowStatus.equals(WorkflowStatus.definitief)) {
// if the original was "definitief" insert a new "definitief"
this.getStore().addFeatures(DataUtilities.collection(editedNewFeature));
} else if (originalWorkflowStatus.equals(WorkflowStatus.bewerkt)) {
// if original was "bewerkt" update this to "definitief" with the edits
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
} else {
// other behaviour not documented eg. archief -> definitief, afgevoerd -> definitief
// and not possible to occur in the application as only definitief and bewerkt can be edited
throw new IllegalArgumentException(String.format(
"Niet ondersteunde workflow stap van %s naar %s",
originalWorkflowStatus.label(),
incomingWorkflowStatus.label()));
}
break;
case afgevoerd:
if (definitiefExists) {
// update any "definitief" for this id to "archief"
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, definitief);
}
// update original with the new/edited data including "afgevoerd"
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
if (terreinID == null) {
// find any kavels related to this terrein and also set them to "afgevoerd"
Filter kavelFilter = ff.equals(ff.property(KAVEL_TERREIN_ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME)));
this.updateKavelWorkflowForTerrein(kavelFilter, WorkflowStatus.afgevoerd);
}
break;
case archief: {
// not described, for now just edit the feature
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
break;
}
default:
throw new IllegalArgumentException("Workflow status van edit feature is null, dit wordt niet ondersteund.");
}
editTransaction.commit();
editTransaction.close();
// update terrein geometry
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), incomingWorkflowStatus, this.getApplication(), Stripersist.getEntityManager());
}
} catch (IllegalArgumentException | IOException | NoSuchElementException e) {
editTransaction.rollback();
log.error("Ibis editFeature error", e);
throw e;
}
}
/**
* Make a copy of the original, but with a new fid.
*
* @param copyFrom original
* @return copy having same attribute values as original and a new fid
*/
private SimpleFeature createCopy(SimpleFeature copyFrom) {
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(copyFrom.getFeatureType());
builder.init(copyFrom);
return builder.buildFeature(null);
}
/**
* Update any of the selected kavels to the given workflow.
*
* @param kavelFilter filter definitie
* @param newStatus de nieuwe status
*/
private void updateKavelWorkflowForTerrein(Filter kavelFilter, WorkflowStatus newStatus) {
SimpleFeatureStore kavelStore = null;
try (Transaction kavelTransaction = new DefaultTransaction("get-related-kavel-geom")) {
EntityManager em = Stripersist.getEntityManager();
log.debug("updating kavels voor terrein met filter: " + kavelFilter);
// find kavel appLayer
ApplicationLayer kavelAppLyr = null;
List<ApplicationLayer> lyrs = this.getApplication().loadTreeCache(em).getApplicationLayers();
for (ListIterator<ApplicationLayer> it = lyrs.listIterator(); it.hasNext();) {
kavelAppLyr = it.next();
if (kavelAppLyr.getLayerName().equalsIgnoreCase(KAVEL_LAYER_NAME)) {
break;
}
}
Layer l = kavelAppLyr.getService().getLayer(KAVEL_LAYER_NAME, em);
kavelStore = (SimpleFeatureStore) l.getFeatureType().openGeoToolsFeatureSource();
kavelStore.setTransaction(kavelTransaction);
// update kavels
kavelStore.modifyFeatures(WORKFLOW_FIELDNAME, newStatus, kavelFilter);
kavelTransaction.commit();
kavelTransaction.close();
} catch (Exception e) {
log.error(String.format("Bijwerken van kavel workflow status naar %s voor terrein met %s is mislukt.",
newStatus, kavelFilter), e);
} finally {
if (kavelStore != null) {
kavelStore.getDataStore().dispose();
}
}
}
/**
* Check that if {@code disableUserEdit} flag is set on the attribute.
* Override superclass behaviour for the workflow field, so that it's not
* editable client side, but it can be set programatically in the client.
*
* @param attrName attribute to check
* @return {@code true} when the configured attribute is flagged as
* "readOnly" except when this is workflow status
*/
@Override
protected boolean isAttributeUserEditingDisabled(String attrName) {
boolean isAttributeUserEditingDisabled = super.isAttributeUserEditingDisabled(attrName);
if (attrName.equalsIgnoreCase(WORKFLOW_FIELDNAME)) {
isAttributeUserEditingDisabled = false;
}
return isAttributeUserEditingDisabled;
}
private boolean isSameMutatiedatum(Object datum1, Object datum2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
return sdf.format(datum1).equals(sdf.format(datum2));
}
public boolean isHistorisch() {
return historisch;
}
public void setHistorisch(boolean historisch) {
this.historisch = historisch;
}
public boolean isReject() {
return reject;
}
public void setReject(boolean reject) {
this.reject = reject;
}
}
| B3Partners/flamingo-ibis | viewer/src/main/java/nl/b3p/viewer/stripes/IbisEditFeatureActionBean.java | 6,047 | // en gevraagde verwijderen uit database | line_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.stripes;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.ibis.util.IbisConstants;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKTReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import javax.persistence.EntityManager;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.services.Layer;
import nl.b3p.viewer.ibis.util.WorkflowStatus;
import nl.b3p.viewer.ibis.util.WorkflowUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.filter.identity.FeatureIdImpl;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortOrder;
import org.stripesstuff.stripersist.Stripersist;
/**
* edit component met ibis workflow.
*
* @author mprins
*/
@UrlBinding("/action/feature/ibisedit")
@StrictBinding
public class IbisEditFeatureActionBean extends EditFeatureActionBean implements IbisConstants {
private static final Log log = LogFactory.getLog(IbisEditFeatureActionBean.class);
@Validate
private boolean historisch;
@Validate
private boolean reject;
@Override
protected String addNewFeature() throws Exception {
String kavelID = super.addNewFeature();
//update terrein
Object terreinID = this.getJsonFeature().optString(KAVEL_TERREIN_ID_FIELDNAME, null);
WorkflowStatus status = WorkflowStatus.valueOf(this.getJsonFeature().optString(WORKFLOW_FIELDNAME, WorkflowStatus.bewerkt.name()));
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), status, this.getApplication(), Stripersist.getEntityManager());
}
return kavelID;
}
/**
* Override to not delete a feature but set workflow status to
* {@code WorkflowStatus.archief}
*
* @param fid feature id
* @throws IOException if any
* @throws Exception if any
* @see WorkflowStatus
*/
@Override
protected void deleteFeature(String fid) throws IOException, Exception {
if(this.isHistorisch()){
this.deleteFeatureHistorisch(fid);
} else if (this.isReject()){
this.rejectFeature(fid);
} else{
log.debug("ibis deleteFeature: " + fid);
Transaction transaction = new DefaultTransaction("ibis_delete");
this.getStore().setTransaction(transaction);
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
Filter filter = ff.id(new FeatureIdImpl(fid));
try {
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.afgevoerd, filter);
SimpleFeature original = this.getStore().getFeatures(filter).features().next();
transaction.commit();
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), WorkflowStatus.afgevoerd, this.getApplication(), Stripersist.getEntityManager());
}
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
}
/**
* verwijder historische record.
* Als het een "archief" record is dan gewoon verwijderen,
* als het een "afgevoerd" record is dan verwijderen en jongste "archief" record "afgevoerd" maken.
* als er geen "archief" te vinden is dan laten.
*
* @param fid feature to remove
* @throws IOException if any
* @throws Exception if any
*/
private void deleteFeatureHistorisch(String fid) throws IOException, Exception {
log.debug("ibis deleteFeatureHistorisch: " + fid);
Transaction transaction = new DefaultTransaction("ibis_delete_historisch");
this.getStore().setTransaction(transaction);
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
Filter fidFilter = ff.id(new FeatureIdImpl(fid));
Filter hist = ff.or(
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.archief.name()), false),
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.afgevoerd.name()), false)
);
try {
SimpleFeature original = this.getStore().getFeatures(fidFilter).features().next();
Number ibisId = (Number) original.getAttribute(ID_FIELDNAME);
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
log.debug(String.format("Delete from feature source #%d fid=%s",
this.getLayer().getFeatureType().getId(), fid));
switch (WorkflowStatus.valueOf( original.getAttribute(WORKFLOW_FIELDNAME).toString()) ) {
case archief:
// archief record gewoon verwijderen
this.getStore().removeFeatures(fidFilter);
break;
case afgevoerd:
// zoek alle historische kavels voor dit kavel nummer
SimpleFeatureCollection histRecords = this.getStore().getFeatures(
ff.and(
hist,
ff.equals(ff.property(ID_FIELDNAME), ff.literal(ibisId))
));
if (histRecords.size() > 1) {
// als er naast deze afgevoerd nog andere zijn
histRecords.sort(ff.sort(MUTATIEDATUM_FIELDNAME, SortOrder.DESCENDING));
// dan de jongste daarvan (eerste uit de lijst) op afgevoerd zetten
String updateFid = histRecords.features().next().getID();
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.afgevoerd, ff.id(new FeatureIdImpl(updateFid)));
// en gevraagde<SUF>
this.getStore().removeFeatures(fidFilter);
}
break;
default:
throw new UnsupportedOperationException("Historische record met status anders dan 'archief' of 'afgevoerd' kan niet worden verwijderd.");
}
transaction.commit();
// update terrein van kavel
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), WorkflowStatus.afgevoerd, this.getApplication(), Stripersist.getEntityManager());
}
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
/** voor "afkeur" van een bewerkt kavel.
*
* @param fid feature to remove
* @throws Exception if any
*/
private void rejectFeature(String fid) throws Exception {
log.debug("ibis rejectFeature: " + fid);
Transaction transaction = new DefaultTransaction("ibis_reject");
this.getStore().setTransaction(transaction);
Filter filter = CommonFactoryFinder.getFilterFactory2().id(new FeatureIdImpl(fid));
try {
SimpleFeature original = this.getStore().getFeatures(filter).features().next();
if (!(original.getAttribute(WORKFLOW_FIELDNAME).toString().equalsIgnoreCase(WorkflowStatus.bewerkt.label()) &&
(this.getLayer().getName().equalsIgnoreCase(KAVEL_LAYER_NAME) || this.getLayer().getName().equalsIgnoreCase(TERREIN_LAYER_NAME)))) {
throw new IllegalArgumentException("Alleen 'bewerkt' kavels en terreinen kunnen worden afgekeurd.");
}
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
this.getStore().removeFeatures(filter);
transaction.commit();
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), WorkflowStatus.afgevoerd, this.getApplication(), Stripersist.getEntityManager());
}
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
/**
* Override the method from the base class to process our workflow.
*
* @param fid feature id
* @throws Exception if any
*/
@Override
protected void editFeature(String fid) throws Exception {
log.debug("ibis editFeature:" + fid);
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
Filter fidFilter = ff.id(new FeatureIdImpl(fid));
List<String> attributes = new ArrayList();
List values = new ArrayList();
WorkflowStatus incomingWorkflowStatus = null;
// parse json
for (Iterator<String> it = this.getJsonFeature().keys(); it.hasNext();) {
String attribute = it.next();
if (!this.getFID().equals(attribute)) {
AttributeDescriptor ad = this.getStore().getSchema().getDescriptor(attribute);
if (ad != null) {
if (!isAttributeUserEditingDisabled(attribute)) {
attributes.add(attribute);
if (ad.getType() instanceof GeometryType) {
String wkt = this.getJsonFeature().getString(ad.getLocalName());
Geometry g = null;
if (wkt != null) {
g = new WKTReader().read(wkt);
}
values.add(g);
} else {
String v = this.getJsonFeature().getString(attribute);
values.add(StringUtils.defaultIfBlank(v, null));
// remember the incoming workflow status
if (attribute.equals(WORKFLOW_FIELDNAME)) {
incomingWorkflowStatus = WorkflowStatus.valueOf(v);
}
}
} else {
log.info(String.format("Attribute \"%s\" not user editable; ignoring", attribute));
}
} else {
log.warn(String.format("Attribute \"%s\" not in feature type; ignoring", attribute));
}
}
}
log.debug(String.format("Modifying feature source #%d fid=%s, attributes=%s, values=%s",
this.getLayer().getFeatureType().getId(), fid, attributes.toString(), values.toString()));
Transaction editTransaction = new DefaultTransaction("ibis_edit");
this.getStore().setTransaction(editTransaction);
try {
if (incomingWorkflowStatus == null) {
throw new IllegalArgumentException("Workflow status van edit feature is null, dit wordt niet ondersteund.");
}
SimpleFeature original = this.getStore().getFeatures(fidFilter).features().next();
Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
WorkflowStatus originalWorkflowStatus = WorkflowStatus.valueOf(original.getAttribute(WORKFLOW_FIELDNAME).toString());
// make a copy of the original feature and set (new) attribute values on the copy
SimpleFeature editedNewFeature = createCopy(original);
for (int i = 0; i < attributes.size(); i++) {
editedNewFeature.setAttribute(attributes.get(i), values.get(i));
}
Filter definitief = ff.and(
ff.equals(ff.property(ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME))),
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.definitief.name()), false)
);
boolean definitiefExists = (this.getStore().getFeatures(definitief).size() > 0);
Filter bewerkt = ff.and(
ff.equals(ff.property(ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME))),
ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.bewerkt.name()), false)
);
int aantalBewerkt = this.getStore().getFeatures(bewerkt).size();
boolean bewerktExists = (aantalBewerkt > 0);
switch (incomingWorkflowStatus) {
case bewerkt:
if (originalWorkflowStatus.equals(WorkflowStatus.definitief)) {
// definitief -> bewerkt
if (bewerktExists) {
// delete existing bewerkt
this.getStore().removeFeatures(bewerkt);
}
// insert new record with original id and workflowstatus "bewerkt", leave original "definitief"
this.getStore().addFeatures(DataUtilities.collection(editedNewFeature));
} else if (originalWorkflowStatus.equals(WorkflowStatus.bewerkt)) {
// bewerkt -> bewerkt, overwrite, only one 'bewerkt' is allowed
if (aantalBewerkt > 1) {
log.error("Er is meer dan 1 bewerkt kavel/terrein voor " + ID_FIELDNAME + "=" + original.getAttribute(ID_FIELDNAME));
// more than 1 bewerkt, move them to archief
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, bewerkt);
}
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
} else {
// other behaviour not documented eg. archief -> bewerkt, afgevoerd -> bewerkt
// and not possible to occur in the application as only definitief and bewerkt can be edited
throw new IllegalArgumentException(String.format(
"Niet ondersteunde workflow stap van %s naar %s",
originalWorkflowStatus.label(),
incomingWorkflowStatus.label()));
}
break;
case definitief:
if (definitiefExists) {
// check if any "definitief" exists for this id and move that to "archief"
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, definitief);
}
if (originalWorkflowStatus.equals(WorkflowStatus.definitief)) {
// if the original was "definitief" insert a new "definitief"
this.getStore().addFeatures(DataUtilities.collection(editedNewFeature));
} else if (originalWorkflowStatus.equals(WorkflowStatus.bewerkt)) {
// if original was "bewerkt" update this to "definitief" with the edits
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
} else {
// other behaviour not documented eg. archief -> definitief, afgevoerd -> definitief
// and not possible to occur in the application as only definitief and bewerkt can be edited
throw new IllegalArgumentException(String.format(
"Niet ondersteunde workflow stap van %s naar %s",
originalWorkflowStatus.label(),
incomingWorkflowStatus.label()));
}
break;
case afgevoerd:
if (definitiefExists) {
// update any "definitief" for this id to "archief"
this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, definitief);
}
// update original with the new/edited data including "afgevoerd"
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
if (terreinID == null) {
// find any kavels related to this terrein and also set them to "afgevoerd"
Filter kavelFilter = ff.equals(ff.property(KAVEL_TERREIN_ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME)));
this.updateKavelWorkflowForTerrein(kavelFilter, WorkflowStatus.afgevoerd);
}
break;
case archief: {
// not described, for now just edit the feature
this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(), fidFilter);
break;
}
default:
throw new IllegalArgumentException("Workflow status van edit feature is null, dit wordt niet ondersteund.");
}
editTransaction.commit();
editTransaction.close();
// update terrein geometry
if (terreinID != null) {
WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(), incomingWorkflowStatus, this.getApplication(), Stripersist.getEntityManager());
}
} catch (IllegalArgumentException | IOException | NoSuchElementException e) {
editTransaction.rollback();
log.error("Ibis editFeature error", e);
throw e;
}
}
/**
* Make a copy of the original, but with a new fid.
*
* @param copyFrom original
* @return copy having same attribute values as original and a new fid
*/
private SimpleFeature createCopy(SimpleFeature copyFrom) {
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(copyFrom.getFeatureType());
builder.init(copyFrom);
return builder.buildFeature(null);
}
/**
* Update any of the selected kavels to the given workflow.
*
* @param kavelFilter filter definitie
* @param newStatus de nieuwe status
*/
private void updateKavelWorkflowForTerrein(Filter kavelFilter, WorkflowStatus newStatus) {
SimpleFeatureStore kavelStore = null;
try (Transaction kavelTransaction = new DefaultTransaction("get-related-kavel-geom")) {
EntityManager em = Stripersist.getEntityManager();
log.debug("updating kavels voor terrein met filter: " + kavelFilter);
// find kavel appLayer
ApplicationLayer kavelAppLyr = null;
List<ApplicationLayer> lyrs = this.getApplication().loadTreeCache(em).getApplicationLayers();
for (ListIterator<ApplicationLayer> it = lyrs.listIterator(); it.hasNext();) {
kavelAppLyr = it.next();
if (kavelAppLyr.getLayerName().equalsIgnoreCase(KAVEL_LAYER_NAME)) {
break;
}
}
Layer l = kavelAppLyr.getService().getLayer(KAVEL_LAYER_NAME, em);
kavelStore = (SimpleFeatureStore) l.getFeatureType().openGeoToolsFeatureSource();
kavelStore.setTransaction(kavelTransaction);
// update kavels
kavelStore.modifyFeatures(WORKFLOW_FIELDNAME, newStatus, kavelFilter);
kavelTransaction.commit();
kavelTransaction.close();
} catch (Exception e) {
log.error(String.format("Bijwerken van kavel workflow status naar %s voor terrein met %s is mislukt.",
newStatus, kavelFilter), e);
} finally {
if (kavelStore != null) {
kavelStore.getDataStore().dispose();
}
}
}
/**
* Check that if {@code disableUserEdit} flag is set on the attribute.
* Override superclass behaviour for the workflow field, so that it's not
* editable client side, but it can be set programatically in the client.
*
* @param attrName attribute to check
* @return {@code true} when the configured attribute is flagged as
* "readOnly" except when this is workflow status
*/
@Override
protected boolean isAttributeUserEditingDisabled(String attrName) {
boolean isAttributeUserEditingDisabled = super.isAttributeUserEditingDisabled(attrName);
if (attrName.equalsIgnoreCase(WORKFLOW_FIELDNAME)) {
isAttributeUserEditingDisabled = false;
}
return isAttributeUserEditingDisabled;
}
private boolean isSameMutatiedatum(Object datum1, Object datum2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
return sdf.format(datum1).equals(sdf.format(datum2));
}
public boolean isHistorisch() {
return historisch;
}
public void setHistorisch(boolean historisch) {
this.historisch = historisch;
}
public boolean isReject() {
return reject;
}
public void setReject(boolean reject) {
this.reject = reject;
}
}
|
187060_8 | /*
* Copyright (C) 2017 B3Partners B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package nl.b3p.jdbc.util.converter;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInfo;
/**
* Utility om database properties te laden en methods te loggen.
*
* @author mprins
*/
public abstract class AbstractDatabaseIntegrationTest {
private static final Log LOG = LogFactory.getLog(AbstractDatabaseIntegrationTest.class);
/**
* properties uit {@code <DB smaak>.properties} en {@code local.<DB smaak>.properties}.
*
* @see #loadProps()
*/
protected final Properties params = new Properties();
/** {@code true} als we met een Oracle database bezig zijn. */
protected boolean isOracle;
/** {@code true} als we met een MS SQL Server database bezig zijn. */
protected boolean isMsSQL;
/** {@code true} als we met een Postgis database bezig zijn. */
protected boolean isPostgis;
/** {@code true} als we met een HSQLDB database bezig zijn. */
protected boolean isHSQLDB;
/**
* test of de database properties zijn aangegeven, zo niet dan skippen we alle tests in deze test.
*/
@BeforeAll
public static void checkDatabaseIsProvided() {
// als je vanuit de IDE wilt draaien kun je hier de database property instellen
// System.setProperty("database.properties.file", "postgis.properties");
// System.setProperty("database.properties.file", "sqlserver.properties");
// System.setProperty("database.properties.file", "oracle.properties");
assumeFalse(
null == System.getProperty("database.properties.file"),
"Verwacht database omgeving te zijn aangegeven.");
}
/**
* subklassen dienen zelf een setup te hebben.
*
* @throws Exception if any
*/
@BeforeEach
public abstract void setUp() throws Exception;
/**
* Laadt de database propery file en eventuele overrides.
*
* @throws IOException als laden van property file mislukt
*/
public void loadProps() throws IOException {
// de `database.properties.file` is in de pom.xml of via commandline ingesteld
params.load(
AbstractDatabaseIntegrationTest.class
.getClassLoader()
.getResourceAsStream(System.getProperty("database.properties.file")));
try {
// probeer een local (override) versie te laden als die bestaat
params.load(
AbstractDatabaseIntegrationTest.class
.getClassLoader()
.getResourceAsStream("local." + System.getProperty("database.properties.file")));
} catch (IOException | NullPointerException e) {
// negeren; het override bestand is normaal niet aanwezig
}
isOracle = "oracle".equalsIgnoreCase(params.getProperty("dbtype"));
isMsSQL = "sqlserver".equalsIgnoreCase(params.getProperty("dbtype"));
isPostgis = "postgis".equalsIgnoreCase(params.getProperty("dbtype"));
isHSQLDB = "hsqldb".equalsIgnoreCase(params.getProperty("dbtype"));
try {
Class.forName(params.getProperty("staging.jdbc.driverClassName"));
} catch (ClassNotFoundException ex) {
LOG.error("Database driver niet gevonden.", ex);
}
}
/** Log de naam van de test als deze begint. */
@BeforeEach
public void startTest(TestInfo testInfo) {
LOG.info("==== Start test methode: " + testInfo.getDisplayName());
}
/** Log de naam van de test als deze eindigt. */
@AfterEach
public void endTest(TestInfo testInfo) {
LOG.info("==== Einde test methode: " + testInfo.getDisplayName());
}
public ColumnMetadata getColumnMetadata(Connection c, String tableName, String colName)
throws SQLException {
ColumnMetadata columnMetadata = null;
try (ResultSet columnsRs =
c.getMetaData()
.getColumns(null, c.getSchema(), getCasedName(tableName), getCasedName(colName))) {
while (columnsRs.next()) {
columnMetadata = new ColumnMetadata(columnsRs);
}
}
LOG.debug("metadata voor kolom: " + colName + " is: " + columnMetadata);
return columnMetadata;
}
private String getCasedName(String name) {
if (this.isHSQLDB || this.isOracle) {
return name.toUpperCase(Locale.ROOT);
}
return name;
}
}
| B3Partners/jdbc-util | src/test/java/nl/b3p/jdbc/util/converter/AbstractDatabaseIntegrationTest.java | 1,651 | // als je vanuit de IDE wilt draaien kun je hier de database property instellen | line_comment | nl | /*
* Copyright (C) 2017 B3Partners B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package nl.b3p.jdbc.util.converter;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInfo;
/**
* Utility om database properties te laden en methods te loggen.
*
* @author mprins
*/
public abstract class AbstractDatabaseIntegrationTest {
private static final Log LOG = LogFactory.getLog(AbstractDatabaseIntegrationTest.class);
/**
* properties uit {@code <DB smaak>.properties} en {@code local.<DB smaak>.properties}.
*
* @see #loadProps()
*/
protected final Properties params = new Properties();
/** {@code true} als we met een Oracle database bezig zijn. */
protected boolean isOracle;
/** {@code true} als we met een MS SQL Server database bezig zijn. */
protected boolean isMsSQL;
/** {@code true} als we met een Postgis database bezig zijn. */
protected boolean isPostgis;
/** {@code true} als we met een HSQLDB database bezig zijn. */
protected boolean isHSQLDB;
/**
* test of de database properties zijn aangegeven, zo niet dan skippen we alle tests in deze test.
*/
@BeforeAll
public static void checkDatabaseIsProvided() {
// als je<SUF>
// System.setProperty("database.properties.file", "postgis.properties");
// System.setProperty("database.properties.file", "sqlserver.properties");
// System.setProperty("database.properties.file", "oracle.properties");
assumeFalse(
null == System.getProperty("database.properties.file"),
"Verwacht database omgeving te zijn aangegeven.");
}
/**
* subklassen dienen zelf een setup te hebben.
*
* @throws Exception if any
*/
@BeforeEach
public abstract void setUp() throws Exception;
/**
* Laadt de database propery file en eventuele overrides.
*
* @throws IOException als laden van property file mislukt
*/
public void loadProps() throws IOException {
// de `database.properties.file` is in de pom.xml of via commandline ingesteld
params.load(
AbstractDatabaseIntegrationTest.class
.getClassLoader()
.getResourceAsStream(System.getProperty("database.properties.file")));
try {
// probeer een local (override) versie te laden als die bestaat
params.load(
AbstractDatabaseIntegrationTest.class
.getClassLoader()
.getResourceAsStream("local." + System.getProperty("database.properties.file")));
} catch (IOException | NullPointerException e) {
// negeren; het override bestand is normaal niet aanwezig
}
isOracle = "oracle".equalsIgnoreCase(params.getProperty("dbtype"));
isMsSQL = "sqlserver".equalsIgnoreCase(params.getProperty("dbtype"));
isPostgis = "postgis".equalsIgnoreCase(params.getProperty("dbtype"));
isHSQLDB = "hsqldb".equalsIgnoreCase(params.getProperty("dbtype"));
try {
Class.forName(params.getProperty("staging.jdbc.driverClassName"));
} catch (ClassNotFoundException ex) {
LOG.error("Database driver niet gevonden.", ex);
}
}
/** Log de naam van de test als deze begint. */
@BeforeEach
public void startTest(TestInfo testInfo) {
LOG.info("==== Start test methode: " + testInfo.getDisplayName());
}
/** Log de naam van de test als deze eindigt. */
@AfterEach
public void endTest(TestInfo testInfo) {
LOG.info("==== Einde test methode: " + testInfo.getDisplayName());
}
public ColumnMetadata getColumnMetadata(Connection c, String tableName, String colName)
throws SQLException {
ColumnMetadata columnMetadata = null;
try (ResultSet columnsRs =
c.getMetaData()
.getColumns(null, c.getSchema(), getCasedName(tableName), getCasedName(colName))) {
while (columnsRs.next()) {
columnMetadata = new ColumnMetadata(columnsRs);
}
}
LOG.debug("metadata voor kolom: " + colName + " is: " + columnMetadata);
return columnMetadata;
}
private String getCasedName(String name) {
if (this.isHSQLDB || this.isOracle) {
return name.toUpperCase(Locale.ROOT);
}
return name;
}
}
|
181879_15 | /*
* B3P Kaartenbalie is a OGC WMS/WFS proxy that adds functionality
* for authentication/authorization, pricing and usage reporting.
*
* Copyright 2006, 2007, 2008 B3Partners BV
*
* This file is part of B3P Kaartenbalie.
*
* B3P Kaartenbalie is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Kaartenbalie is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Kaartenbalie. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.kaartenbalie.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import nl.b3p.wms.capabilities.Layer;
import nl.b3p.wms.capabilities.SrsBoundingBox;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Roy
*/
public class LayerValidator {
private static final Log log = LogFactory.getLog(LayerValidator.class);
private Set layers;
/** Creates a new Instance of LayerValidator with the given layers
*/
public LayerValidator(Set layers) {
setLayers(layers);
}
/* Getters and setters */
public Set getLayers() {
return layers;
}
public void setLayers(Set layers) {
this.layers = layers;
Iterator it = layers.iterator();
while (it.hasNext()) {
Layer l = (Layer) it.next();
Set srsbb = l.getSrsbb();
if (srsbb == null) {
log.debug("Layer: " + l.getUniqueName() + " does not have a SRS");
}
}
}
public boolean validate() {
return this.validateSRS().length > 0;
}
public SrsBoundingBox validateLatLonBoundingBox() {
Iterator it = layers.iterator();
ArrayList supportedLLBB = new ArrayList();
while (it.hasNext()) {
addLayerSupportedLLBB((Layer) it.next(), supportedLLBB);
}
//nu hebben we een lijst met alle LLBB's
//van deze LLBB's moet nu per item bekeken worden welke de uiterste waarden
//heeft voor de minx, miny, maxx, maxy
// volgende waarden geinitialiseerd op extreme omgekeerde waarde
double minx = 180.0, miny = 90.0, maxx = -180.0, maxy = -90.0;
it = supportedLLBB.iterator();
while (it.hasNext()) {
SrsBoundingBox llbb = (SrsBoundingBox) it.next();
double xmin = Double.parseDouble(llbb.getMinx());
double ymin = Double.parseDouble(llbb.getMiny());
double xmax = Double.parseDouble(llbb.getMaxx());
double ymax = Double.parseDouble(llbb.getMaxy());
if (xmin < minx) {
minx = xmin;
}
if (ymin < miny) {
miny = ymin;
}
if (xmax > maxx) {
maxx = xmax;
}
if (ymax > maxy) {
maxy = ymax;
}
}
SrsBoundingBox llbb = new SrsBoundingBox();
llbb.setMinx(Double.toString(minx));
llbb.setMiny(Double.toString(miny));
llbb.setMaxx(Double.toString(maxx));
llbb.setMaxy(Double.toString(maxy));
return llbb;
}
/**
* Checks wether or not a layer has a LatLonBoundingBox. If so this LatLonBoundingBox is added to the supported hashmap
*/
// <editor-fold defaultstate="" desc="default DescribeLayerRequestHandler() constructor">
private void addLayerSupportedLLBB(Layer layer, ArrayList supported) {
Set srsen = layer.getSrsbb();
if (srsen == null) {
return;
}
Iterator it = srsen.iterator();
while (it.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) it.next();
String type = srsbb.getType();
if (type != null) {
if (type.equalsIgnoreCase("LatLonBoundingBox")) {
supported.add(srsbb);
}
}
}
if (layer.getParent() != null) {
addLayerSupportedLLBB(layer.getParent(), supported);
}
}
// </editor-fold>
/** add a srs supported by this layer or a parent of the layer to the supported hashmap
*/
public void addLayerSupportedSRS(Layer l, HashMap supported) {
Set srsen = l.getSrsbb();
if (srsen == null) {
return;
}
Iterator i = srsen.iterator();
while (i.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) i.next();
if (srsbb.getSrs() != null) {
// alleen srs zonder boundingbox coords
if (srsbb.getMinx() == null && srsbb.getMiny() == null && srsbb.getMaxx() == null && srsbb.getMaxy() == null) {
supported.put(srsbb.getSrs(), srsbb.getSrs());
}
}
}
if (l.getParent() != null) {
addLayerSupportedSRS(l.getParent(), supported);
}
}
/** Returns the combined srs's that all layers given supports
*
* Every Layer shall have at least one <SRS> element that is either stated explicitly or
* inherited from a parent Layer (Section 7.1.4.6). The root <Layer> element shall include a
* sequence of zero or more SRS elements listing all SRSes that are common to all
* subsidiary layers. Use a single SRS element with empty content (like so: "<SRS></SRS>") if
* there is no common SRS. Layers may optionally add to the global SRS list, or to the list
* inherited from a parent layer. Any duplication shall be ignored by clients.
*/
public String[] validateSRS() {
HashMap hm = new HashMap();
Iterator lit = layers.iterator();
//Een teller die alle layers telt die een SRS hebben.
int tellerMeeTellendeLayers = 0;
//doorloop de layers
while (lit.hasNext()) {
HashMap supportedByLayer = new HashMap();
addLayerSupportedSRS((Layer) lit.next(), supportedByLayer);
if (supportedByLayer.size() > 0) {
tellerMeeTellendeLayers++;
Iterator i = supportedByLayer.values().iterator();
while (i.hasNext()) {
String srs = (String) i.next();
addSrsCount(hm, srs);
}
}
}
ArrayList supportedSrsen = new ArrayList();
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
int i = ((Integer) entry.getValue()).intValue();
if (i >= tellerMeeTellendeLayers) {
supportedSrsen.add((String) entry.getKey());
}
}
//Voeg lege srs toe indien geen overeenkomstige gevonden
if (supportedSrsen.isEmpty()) {
supportedSrsen.add("");
}
String[] returnValue = new String[supportedSrsen.size()];
for (int i = 0; i < returnValue.length; i++) {
if (supportedSrsen.get(i) != null) {
returnValue[i] = (String) supportedSrsen.get(i);
}
}
return returnValue;
}
/** Methode that counts the different SRS's
* @parameter hm The hashmap that contains the counted srsen
* @parameter srs The srs to add to the count.
*/
private void addSrsCount(HashMap hm, String srs) {
if (hm.containsKey(srs)) {
int i = ((Integer) hm.get(srs)).intValue() + 1;
hm.put(srs, new Integer(i));
} else {
hm.put(srs, new Integer("1"));
}
}
}
| B3Partners/kaartenbalie | src/main/java/nl/b3p/kaartenbalie/service/LayerValidator.java | 2,392 | //Voeg lege srs toe indien geen overeenkomstige gevonden | line_comment | nl | /*
* B3P Kaartenbalie is a OGC WMS/WFS proxy that adds functionality
* for authentication/authorization, pricing and usage reporting.
*
* Copyright 2006, 2007, 2008 B3Partners BV
*
* This file is part of B3P Kaartenbalie.
*
* B3P Kaartenbalie is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Kaartenbalie is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Kaartenbalie. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.kaartenbalie.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import nl.b3p.wms.capabilities.Layer;
import nl.b3p.wms.capabilities.SrsBoundingBox;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Roy
*/
public class LayerValidator {
private static final Log log = LogFactory.getLog(LayerValidator.class);
private Set layers;
/** Creates a new Instance of LayerValidator with the given layers
*/
public LayerValidator(Set layers) {
setLayers(layers);
}
/* Getters and setters */
public Set getLayers() {
return layers;
}
public void setLayers(Set layers) {
this.layers = layers;
Iterator it = layers.iterator();
while (it.hasNext()) {
Layer l = (Layer) it.next();
Set srsbb = l.getSrsbb();
if (srsbb == null) {
log.debug("Layer: " + l.getUniqueName() + " does not have a SRS");
}
}
}
public boolean validate() {
return this.validateSRS().length > 0;
}
public SrsBoundingBox validateLatLonBoundingBox() {
Iterator it = layers.iterator();
ArrayList supportedLLBB = new ArrayList();
while (it.hasNext()) {
addLayerSupportedLLBB((Layer) it.next(), supportedLLBB);
}
//nu hebben we een lijst met alle LLBB's
//van deze LLBB's moet nu per item bekeken worden welke de uiterste waarden
//heeft voor de minx, miny, maxx, maxy
// volgende waarden geinitialiseerd op extreme omgekeerde waarde
double minx = 180.0, miny = 90.0, maxx = -180.0, maxy = -90.0;
it = supportedLLBB.iterator();
while (it.hasNext()) {
SrsBoundingBox llbb = (SrsBoundingBox) it.next();
double xmin = Double.parseDouble(llbb.getMinx());
double ymin = Double.parseDouble(llbb.getMiny());
double xmax = Double.parseDouble(llbb.getMaxx());
double ymax = Double.parseDouble(llbb.getMaxy());
if (xmin < minx) {
minx = xmin;
}
if (ymin < miny) {
miny = ymin;
}
if (xmax > maxx) {
maxx = xmax;
}
if (ymax > maxy) {
maxy = ymax;
}
}
SrsBoundingBox llbb = new SrsBoundingBox();
llbb.setMinx(Double.toString(minx));
llbb.setMiny(Double.toString(miny));
llbb.setMaxx(Double.toString(maxx));
llbb.setMaxy(Double.toString(maxy));
return llbb;
}
/**
* Checks wether or not a layer has a LatLonBoundingBox. If so this LatLonBoundingBox is added to the supported hashmap
*/
// <editor-fold defaultstate="" desc="default DescribeLayerRequestHandler() constructor">
private void addLayerSupportedLLBB(Layer layer, ArrayList supported) {
Set srsen = layer.getSrsbb();
if (srsen == null) {
return;
}
Iterator it = srsen.iterator();
while (it.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) it.next();
String type = srsbb.getType();
if (type != null) {
if (type.equalsIgnoreCase("LatLonBoundingBox")) {
supported.add(srsbb);
}
}
}
if (layer.getParent() != null) {
addLayerSupportedLLBB(layer.getParent(), supported);
}
}
// </editor-fold>
/** add a srs supported by this layer or a parent of the layer to the supported hashmap
*/
public void addLayerSupportedSRS(Layer l, HashMap supported) {
Set srsen = l.getSrsbb();
if (srsen == null) {
return;
}
Iterator i = srsen.iterator();
while (i.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) i.next();
if (srsbb.getSrs() != null) {
// alleen srs zonder boundingbox coords
if (srsbb.getMinx() == null && srsbb.getMiny() == null && srsbb.getMaxx() == null && srsbb.getMaxy() == null) {
supported.put(srsbb.getSrs(), srsbb.getSrs());
}
}
}
if (l.getParent() != null) {
addLayerSupportedSRS(l.getParent(), supported);
}
}
/** Returns the combined srs's that all layers given supports
*
* Every Layer shall have at least one <SRS> element that is either stated explicitly or
* inherited from a parent Layer (Section 7.1.4.6). The root <Layer> element shall include a
* sequence of zero or more SRS elements listing all SRSes that are common to all
* subsidiary layers. Use a single SRS element with empty content (like so: "<SRS></SRS>") if
* there is no common SRS. Layers may optionally add to the global SRS list, or to the list
* inherited from a parent layer. Any duplication shall be ignored by clients.
*/
public String[] validateSRS() {
HashMap hm = new HashMap();
Iterator lit = layers.iterator();
//Een teller die alle layers telt die een SRS hebben.
int tellerMeeTellendeLayers = 0;
//doorloop de layers
while (lit.hasNext()) {
HashMap supportedByLayer = new HashMap();
addLayerSupportedSRS((Layer) lit.next(), supportedByLayer);
if (supportedByLayer.size() > 0) {
tellerMeeTellendeLayers++;
Iterator i = supportedByLayer.values().iterator();
while (i.hasNext()) {
String srs = (String) i.next();
addSrsCount(hm, srs);
}
}
}
ArrayList supportedSrsen = new ArrayList();
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
int i = ((Integer) entry.getValue()).intValue();
if (i >= tellerMeeTellendeLayers) {
supportedSrsen.add((String) entry.getKey());
}
}
//Voeg lege<SUF>
if (supportedSrsen.isEmpty()) {
supportedSrsen.add("");
}
String[] returnValue = new String[supportedSrsen.size()];
for (int i = 0; i < returnValue.length; i++) {
if (supportedSrsen.get(i) != null) {
returnValue[i] = (String) supportedSrsen.get(i);
}
}
return returnValue;
}
/** Methode that counts the different SRS's
* @parameter hm The hashmap that contains the counted srsen
* @parameter srs The srs to add to the count.
*/
private void addSrsCount(HashMap hm, String srs) {
if (hm.containsKey(srs)) {
int i = ((Integer) hm.get(srs)).intValue() + 1;
hm.put(srs, new Integer(i));
} else {
hm.put(srs, new Integer("1"));
}
}
}
|
17542_31 | /*
* Copyright (C) 2018 B3Partners B.V.
*/
package nl.b3p.gds2;
import com.sun.xml.ws.developer.JAXWSProperties;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import static nl.b3p.gds2.GDS2Util.*;
import nl.b3p.soap.logging.LogMessageHandler;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstresultaat.afgifte.v20170401.AfgifteType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20170401.AfgifteSelectieCriteriaType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20170401.BestandKenmerkenType;
import nl.kadaster.schemas.gds2.afgifte_proces.v20170401.FilterDatumTijdType;
import nl.kadaster.schemas.gds2.afgifte_proces.v20170401.KlantAfgiftenummerReeksType;
import nl.kadaster.schemas.gds2.imgds.baseurl.v20170401.BaseURLType;
import nl.kadaster.schemas.gds2.service.afgifte.v20170401.Gds2AfgifteServiceV20170401;
import nl.kadaster.schemas.gds2.service.afgifte.v20170401.Gds2AfgifteServiceV20170401Service;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenRequest;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenResponse;
import nl.logius.digikoppeling.gb._2010._10.DataReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Test klasse om gds2 te bevragen met koppelvlak v20170401.
* <p>
* quick run:
* {@code
* cp some.private.key private.key && cp some.public.key public.key
* mvn clean install -DskipTests
* java -Dlog4j.configuration=file:///home/mark/dev/projects/kadaster-gds2/target/test-classes/log4j.xml -cp ./target/kadaster-gds2-2.4-SNAPSHOT.jar:./target/lib/* nl.b3p.gds2.Main2
* }
*
* @author mprins
*/
public class Main2 {
private static final Log LOG = LogFactory.getLog(Main2.class);
private static final String MOCK_ENDPOINT = "http://localhost:8088/AfgifteService";
public static void main(String[] args) throws Exception {
// java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
// java.lang.System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");
// java.lang.System.setProperty("javax.net.debug", "ssl,plaintext");
Gds2AfgifteServiceV20170401 gds2 = new Gds2AfgifteServiceV20170401Service().getAGds2AfgifteServiceV20170401();
BindingProvider bp = (BindingProvider) gds2;
Map<String, Object> ctxt = bp.getRequestContext();
// soap berichten logger inhaken (actief met TRACE level)
List<Handler> handlerChain = bp.getBinding().getHandlerChain();
handlerChain.add(new LogMessageHandler());
bp.getBinding().setHandlerChain(handlerChain);
String endpoint = (String) ctxt.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
LOG.info("Origineel endpoint: " + endpoint);
// om tegen soapui mock te praten
// ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, MOCK_ENDPOINT);
// LOG.info("Endpoint protocol gewijzigd naar mock: " + MOCK_ENDPOINT);
final char[] thePassword = "changeit".toCharArray();
LOG.debug("Loading keystore");
KeyStore ks = KeyStore.getInstance("jks");
ks.load(Main2.class.getResourceAsStream("/pkioverheid.jks"), thePassword);
LOG.debug("Initializing TrustManagerFactory");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
LOG.debug("Initializing KeyManagerFactory");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
ks = KeyStore.getInstance("jks");
if (args.length > 0) {
String keystore = "/gds2_key.jks";
ks.load(Main2.class.getResourceAsStream(keystore), thePassword);
kmf.init(ks, thePassword);
} else {
ks.load(null);
PrivateKey privateKey = GDS2Util.getPrivateKeyFromPEM(new String(Files.readAllBytes(Paths.get("private.key"))).trim());
Certificate certificate = GDS2Util.getCertificateFromPEM(new String(Files.readAllBytes(Paths.get("public.key"))).trim());
ks.setKeyEntry("thekey", privateKey, thePassword, new Certificate[]{certificate});
kmf.init(ks, thePassword);
}
LOG.debug("Initializing SSLContext");
SSLContext context = SSLContext.getInstance("TLS", "SunJSSE");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLContext.setDefault(context);
ctxt.put(JAXWSProperties.SSL_SOCKET_FACTORY, context.getSocketFactory());
BestandenlijstOpvragenRequest request = new BestandenlijstOpvragenRequest();
BestandenlijstOpvragenType verzoek = new BestandenlijstOpvragenType();
request.setVerzoek(verzoek);
AfgifteSelectieCriteriaType criteria = new AfgifteSelectieCriteriaType();
verzoek.setAfgifteSelectieCriteria(criteria);
criteria.setBestandKenmerken(new BestandKenmerkenType());
// Indicatie nog niet gerapporteerd
// Met deze indicatie wordt aangegeven of uitsluitend de nog niet gerapporteerde afgiftes
// moeten worden opgenomen in de lijst, of dat alle beschikbare afgiftes worden genoemd.
// Als deze indicator wordt gebruikt, dan worden na terugmelding van de bestandenlijst
// de bijbehorende bestanden gemarkeerd als zijnde ‘gerapporteerd’ in het systeem van GDS.
// alGerapporteerd
final Boolean alGerapporteerd = Boolean.TRUE;
criteria.setNogNietGerapporteerd(alGerapporteerd);
// vanaf
GregorianCalendar vanaf = getDatumTijd("01-09-2020");
GregorianCalendar tot;
// tot vandaag
//tot = getDatumTijd(new Date());
// tot 1 aug 2019
tot = getDatumTijd("10-09-2020");
// om bepaalde periode te selecteren; kan/mag niet samen met afgiftenummers
criteria.setPeriode(new FilterDatumTijdType());
// Indien vermeld worden alleen de afgiftes opgenomen in de lijst met een
// aanmeldingstijdstip NA genoemde datum/tijd.
criteria.getPeriode().setDatumTijdVanaf(getXMLDatumTijd(vanaf));
// Idem, met een aanmeldingstijdstip TOT en MET genoemde datum/tijd
// (tijdstip op seconde nauwkeurig).
criteria.getPeriode().setDatumTijdTotmet(getXMLDatumTijd(tot));
// om bepaalde afgiftenummers te selecteren; kan/mag niet samen met periode
KlantAfgiftenummerReeksType afgiftenummers = new KlantAfgiftenummerReeksType();
// Indien vermeld worden alleen afgiftes opgenomen in de lijst met een klantAfgiftenummer
// groter of gelijk aan het genoemde nummer
afgiftenummers.setKlantAfgiftenummerVanaf(BigInteger.ONE);
// Indien vermeld worden alleen afgiftes opgenomen in de lijst met een klantAfgiftenummer
// kleiner of gelijk aan het genoemde nummer.
// Deze bovengrens is alleen mogelijk in combinatie met een ondergrens (klantAfgiftenummer vanaf).
afgiftenummers.setKlantAfgiftenummerTotmet(BigInteger.valueOf(10000));
// criteria.setKlantAfgiftenummerReeks(afgiftenummers);
//
// artikelnummer
// Indien vermeld dan worden alleen de afgiftes opgenomen in de lijst die
// horen bij het genoemde artikelnummer
//
// maandelijkse BAG mutaties NL
// criteria.getBestandKenmerken().setArtikelnummer("2508");
// dagelijkse BAG mutaties NL
criteria.getBestandKenmerken().setArtikelnummer("2516");
//
// contractnummer voor BRK
//
// Indien vermeld dan worden alleen de afgiftes opgenomen in de lijst die
// gekoppeld zijn aan het genoemde contractnummer
//
// criteria.getBestandKenmerken().setContractnummer("9700005117");
LOG.info("Contract nummer: " + criteria.getBestandKenmerken().getContractnummer());
LOG.info("Artikel nummer: " + criteria.getBestandKenmerken().getArtikelnummer());
LOG.info("DatumTijdVanaf criterium: " + vanaf);
LOG.info("DatumTijdTot criterium: " + tot);
LOG.info("alGerapporteerd criterium: " + alGerapporteerd);
BestandenlijstOpvragenRequest bestandenlijstOpvragenRequest = new BestandenlijstOpvragenRequest();
BestandenlijstOpvragenType bestandenlijstOpvragenVerzoek = new BestandenlijstOpvragenType();
bestandenlijstOpvragenRequest.setVerzoek(bestandenlijstOpvragenVerzoek);
bestandenlijstOpvragenVerzoek.setAfgifteSelectieCriteria(criteria);
// BestandenlijstOpvragenResponse bestandenlijstOpvragenResponse = retryBestandenLijstOpvragen(
// gds2, bestandenlijstOpvragenRequest, 1, 10000
// );
// // basis meta info van antwoord
// int afgifteAantalInLijst = bestandenlijstOpvragenResponse.getAntwoord().getAfgifteAantalInLijst();
// LOG.info("Aantal geselecteerde afgiftes in de lijst: " + afgifteAantalInLijst);
// int hoogsteAfgifteNummer = bestandenlijstOpvragenResponse.getAntwoord().getKlantAfgiftenummerMax();
// LOG.info("Hoogst toegekende klant afgiftenummer:" + hoogsteAfgifteNummer);
// BaseURLType baseUrlAnon = getAnoniemBaseURL(bestandenlijstOpvragenResponse.getAntwoord());
// BaseURLType baseUrlCert = getCertificaatBaseURL(bestandenlijstOpvragenResponse.getAntwoord());
// LOG.info("Baseurl te gebruiken als prefix voor anon download urls: " + baseUrlAnon.getValue());
// LOG.info("Baseurl te gebruiken als prefix voor anon certificaat urls: " + baseUrlCert.getValue());
// // true als er meer dan het maximum aantal afgiftes zijn gevonden _voor de selectie criteria_
// boolean hasMore = bestandenlijstOpvragenResponse.getAntwoord().isMeerAfgiftesbeschikbaar();
// LOG.info("Meer afgiftes beschikbaar? " + hasMore);
// TODO logica om datum periode of nummerreeks kleiner te maken dan max aantal
GregorianCalendar currentMoment = null;
boolean parseblePeriod = false;
int loopType = Calendar.DAY_OF_MONTH;
int loopMax = 180;
int loopNum = 0;
boolean reducePeriod = false;
boolean increasePeriod = false;
if (vanaf.before(tot)) {
parseblePeriod = true;
currentMoment = vanaf;
}
List<AfgifteType> afgiftes = new ArrayList<>();
BestandenlijstOpvragenResponse response = null;
int hoogsteKlantAfgifteNummer = -1;
boolean morePeriods2Process = false;
do /* while morePeriods2Process is true */ {
System.out.println("\n*** start periode ***");
//zet periode in criteria indien gewenst
if (parseblePeriod) {
//check of de periodeduur verkleind moet worden
if (reducePeriod) {
switch (loopType) {
case Calendar.DAY_OF_MONTH:
currentMoment.add(loopType, -1);
loopType = Calendar.HOUR_OF_DAY;
System.out.println("* Verklein loop periode naar uur");
break;
case Calendar.HOUR_OF_DAY:
currentMoment.add(loopType, -1);
loopType = Calendar.MINUTE;
System.out.println("* Verklein loop periode naar minuut");
break;
case Calendar.MINUTE:
default:
/*
* Hier kom je alleen als binnen een minuut meer
* dan 2000 berichten zijn aangamaakt en het
* vinkje ook "al rapporteerde berichten
* ophalen" staat aan.
*/
System.out.println("Niet alle gevraagde berichten zijn opgehaald");
}
reducePeriod = false;
}
//check of de periodeduur vergroot moet worden
if (increasePeriod) {
switch (loopType) {
case Calendar.HOUR_OF_DAY:
loopType = Calendar.DAY_OF_MONTH;
System.out.println("* Vergroot loop periode naar dag");
break;
case Calendar.MINUTE:
loopType = Calendar.HOUR_OF_DAY;
System.out.println("* Vergroot loop periode naar uur");
break;
case Calendar.DAY_OF_MONTH:
default:
//not possible
}
increasePeriod = false;
}
FilterDatumTijdType d = new FilterDatumTijdType();
d.setDatumTijdVanaf(getXMLDatumTijd(currentMoment));
System.out.println(String.format("Datum vanaf: %tc", currentMoment.getTime()));
currentMoment.add(loopType, 1);
d.setDatumTijdTotmet(getXMLDatumTijd(currentMoment));
System.out.println(String.format("Datum tot: %tc", currentMoment.getTime()));
criteria.setPeriode(d);
switch (loopType) {
case Calendar.HOUR_OF_DAY:
//0-23
if (currentMoment.get(loopType) == 0) {
increasePeriod = true;
}
break;
case Calendar.MINUTE:
//0-59
if (currentMoment.get(loopType) == 0) {
increasePeriod = true;
}
break;
case Calendar.DAY_OF_MONTH:
default:
//alleen dagen tellen, uur en minuut altijd helemaal
loopNum++;
}
//bereken of einde van periode bereikt is
if (currentMoment.before(tot) && loopNum < loopMax) {
morePeriods2Process = true;
} else {
morePeriods2Process = false;
}
}
verzoek.setAfgifteSelectieCriteria(criteria);
response = retryBestandenLijstOpvragen(gds2, request, 1, 10000);
hoogsteKlantAfgifteNummer = response.getAntwoord().getKlantAfgiftenummerMax();
int aantalInAntwoord = response.getAntwoord().getAfgifteAantalInLijst();
System.out.println("Aantal in antwoord: " + aantalInAntwoord);
// opletten; in de xsd staat een default value van 'J' voor meerAfgiftesbeschikbaar
boolean hasMore = response.getAntwoord().isMeerAfgiftesbeschikbaar();
System.out.println("Meer afgiftes beschikbaar: " + hasMore);
/*
* Als "al gerapporteerde berichten" moeten worden opgehaald en
* er zitten dan 2000 berichten in het antwoord dan heeft het
* geen zin om meer keer de berichten op te halen, je krijgt
* telkens dezelfde.
*/
if (hasMore && "true".equals(alGerapporteerd)) {
reducePeriod = true;
morePeriods2Process = true;
increasePeriod = false;
// als er geen parsable periode is
// (geen periode ingevuld en alGerapporteerd is true
// dan moet morePeriods2Process false worden om een
// eindloze while loop te voorkomen
if (!parseblePeriod) {
morePeriods2Process = false;
} else {
continue;
}
}
if (aantalInAntwoord > 0) {
afgiftes.addAll(response.getAntwoord().getBestandenLijst().getAfgifte());
}
/*
* Indicatie nog niet gerapporteerd: Met deze indicatie wordt
* aangegeven of uitsluitend de nog niet gerapporteerde
* bestanden moeten worden opgenomen in de lijst, of dat alle
* beschikbare bestanden worden genoemd. Niet gerapporteerd
* betekent in dit geval ‘niet eerder opgevraagd in deze
* bestandenlijst’. Als deze indicator wordt gebruikt, dan
* worden na terugmelding van de bestandenlijst de bijbehorende
* bestanden gemarkeerd als zijnde ‘gerapporteerd’ in het
* systeem van GDS.
*/
int moreCount = 0;
while (hasMore) {
System.out.println("Uitvoeren SOAP request naar Kadaster voor meer afgiftes..." + moreCount++);
criteria.setNogNietGerapporteerd(true);
response = retryBestandenLijstOpvragen(gds2, request, 1, 10000);
hoogsteKlantAfgifteNummer = response.getAntwoord().getKlantAfgiftenummerMax();
List<AfgifteType> afgifteLijst = response.getAntwoord().getBestandenLijst().getAfgifte();
for (AfgifteType t : afgiftes) {
// lijst urls naar aparte logfile loggen
if (t.getDigikoppelingExternalDatareferences() != null
&& t.getDigikoppelingExternalDatareferences().getDataReference() != null) {
for (DataReference dr : t.getDigikoppelingExternalDatareferences().getDataReference()) {
LOG.info("GDS2url te downloaden: " + dr.getTransport().getLocation().getSenderUrl().getValue());
break;
}
}
}
afgiftes.addAll(afgifteLijst);
aantalInAntwoord = response.getAntwoord().getAfgifteAantalInLijst();
System.out.println("Aantal in antwoord: " + aantalInAntwoord);
hasMore = response.getAntwoord().isMeerAfgiftesbeschikbaar();
System.out.println("Nog meer afgiftes beschikbaar: " + hasMore);
}
} while (morePeriods2Process);
System.out.println("Totaal aantal op te halen berichten: " + afgiftes.size());
System.out.println("Hoogste klant afgifte nummer: " + hoogsteKlantAfgifteNummer);
if (criteria.getBestandKenmerken().getContractnummer() == null) {
// bag response.getAntwoord()
printAfgiftes(afgiftes, getAnoniemBaseURL(response.getAntwoord()));
} else {
// brk
printAfgiftes(afgiftes, getCertificaatBaseURL(response.getAntwoord()));
}
}
private static void printAfgiftes(List<AfgifteType> afgiftes, BaseURLType baseUrl) {
LOG.info("Schrijf afgiftegegevens, bestandskenmerken en Digikoppeling datareference gegevens van de afgiftes in CSV.");
try (PrintWriter out = new PrintWriter("afgiftelijst.csv")) {
out.println("ID\treferentie\tdownloadUrl\tbestandsnaam\tbestandref\tbeschikbaarTot\tcontractafgiftenr\tklantafgiftenr\tcontractnr\tartikelnr\tartikelomschrijving\tcontextId\tcreationTime\texpirationTime\tfilename\tchecksum\ttype\tsize\tsenderUrl\treceiverUrl");
for (AfgifteType a : afgiftes) {
String kenmerken = "-\t-\t-";
if (a.getBestandKenmerken() != null) {
kenmerken = String.format("%s\t%s\t%s",
a.getBestandKenmerken().getContractnummer(),
a.getBestandKenmerken().getArtikelnummer(),
a.getBestandKenmerken().getArtikelomschrijving()
);
}
LOG.debug("Afgifte id: " + a.getAfgifteID());
out.printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t",
a.getAfgifteID(),
a.getAfgiftereferentie(),
getAfgifteURL(a, baseUrl),
a.getBestand().getBestandsnaam(),
a.getBestand().getBestandsreferentie(),
a.getBeschikbaarTot(),
a.getContractAfgiftenummer(),
a.getKlantAfgiftenummer(),
kenmerken);
if (a.getDigikoppelingExternalDatareferences() != null
&& a.getDigikoppelingExternalDatareferences().getDataReference() != null) {
for (DataReference dr : a.getDigikoppelingExternalDatareferences().getDataReference()) {
out.printf("%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n",
dr.getContextId() == null ? "-" : dr.getContextId(),
dr.getLifetime().getCreationTime().getValue(),
dr.getLifetime().getExpirationTime().getValue(),
dr.getContent().getFilename(),
dr.getContent().getChecksum().getValue(),
dr.getContent().getContentType(),
dr.getContent().getSize(),
dr.getTransport().getLocation().getSenderUrl() == null ? "-" : dr.getTransport().getLocation().getSenderUrl().getValue(),
dr.getTransport().getLocation().getReceiverUrl() == null ? "-" : dr.getTransport().getLocation().getReceiverUrl().getValue());
}
}
}
} catch (FileNotFoundException e) {
LOG.error("CSV maken is mislukt", e);
}
}
}
| B3Partners/kadaster-gds2 | src/main/java/nl/b3p/gds2/Main2.java | 6,802 | // gds2, bestandenlijstOpvragenRequest, 1, 10000 | line_comment | nl | /*
* Copyright (C) 2018 B3Partners B.V.
*/
package nl.b3p.gds2;
import com.sun.xml.ws.developer.JAXWSProperties;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import static nl.b3p.gds2.GDS2Util.*;
import nl.b3p.soap.logging.LogMessageHandler;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstresultaat.afgifte.v20170401.AfgifteType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20170401.AfgifteSelectieCriteriaType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20170401.BestandKenmerkenType;
import nl.kadaster.schemas.gds2.afgifte_proces.v20170401.FilterDatumTijdType;
import nl.kadaster.schemas.gds2.afgifte_proces.v20170401.KlantAfgiftenummerReeksType;
import nl.kadaster.schemas.gds2.imgds.baseurl.v20170401.BaseURLType;
import nl.kadaster.schemas.gds2.service.afgifte.v20170401.Gds2AfgifteServiceV20170401;
import nl.kadaster.schemas.gds2.service.afgifte.v20170401.Gds2AfgifteServiceV20170401Service;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenRequest;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenResponse;
import nl.logius.digikoppeling.gb._2010._10.DataReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Test klasse om gds2 te bevragen met koppelvlak v20170401.
* <p>
* quick run:
* {@code
* cp some.private.key private.key && cp some.public.key public.key
* mvn clean install -DskipTests
* java -Dlog4j.configuration=file:///home/mark/dev/projects/kadaster-gds2/target/test-classes/log4j.xml -cp ./target/kadaster-gds2-2.4-SNAPSHOT.jar:./target/lib/* nl.b3p.gds2.Main2
* }
*
* @author mprins
*/
public class Main2 {
private static final Log LOG = LogFactory.getLog(Main2.class);
private static final String MOCK_ENDPOINT = "http://localhost:8088/AfgifteService";
public static void main(String[] args) throws Exception {
// java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
// java.lang.System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");
// java.lang.System.setProperty("javax.net.debug", "ssl,plaintext");
Gds2AfgifteServiceV20170401 gds2 = new Gds2AfgifteServiceV20170401Service().getAGds2AfgifteServiceV20170401();
BindingProvider bp = (BindingProvider) gds2;
Map<String, Object> ctxt = bp.getRequestContext();
// soap berichten logger inhaken (actief met TRACE level)
List<Handler> handlerChain = bp.getBinding().getHandlerChain();
handlerChain.add(new LogMessageHandler());
bp.getBinding().setHandlerChain(handlerChain);
String endpoint = (String) ctxt.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
LOG.info("Origineel endpoint: " + endpoint);
// om tegen soapui mock te praten
// ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, MOCK_ENDPOINT);
// LOG.info("Endpoint protocol gewijzigd naar mock: " + MOCK_ENDPOINT);
final char[] thePassword = "changeit".toCharArray();
LOG.debug("Loading keystore");
KeyStore ks = KeyStore.getInstance("jks");
ks.load(Main2.class.getResourceAsStream("/pkioverheid.jks"), thePassword);
LOG.debug("Initializing TrustManagerFactory");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
LOG.debug("Initializing KeyManagerFactory");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
ks = KeyStore.getInstance("jks");
if (args.length > 0) {
String keystore = "/gds2_key.jks";
ks.load(Main2.class.getResourceAsStream(keystore), thePassword);
kmf.init(ks, thePassword);
} else {
ks.load(null);
PrivateKey privateKey = GDS2Util.getPrivateKeyFromPEM(new String(Files.readAllBytes(Paths.get("private.key"))).trim());
Certificate certificate = GDS2Util.getCertificateFromPEM(new String(Files.readAllBytes(Paths.get("public.key"))).trim());
ks.setKeyEntry("thekey", privateKey, thePassword, new Certificate[]{certificate});
kmf.init(ks, thePassword);
}
LOG.debug("Initializing SSLContext");
SSLContext context = SSLContext.getInstance("TLS", "SunJSSE");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLContext.setDefault(context);
ctxt.put(JAXWSProperties.SSL_SOCKET_FACTORY, context.getSocketFactory());
BestandenlijstOpvragenRequest request = new BestandenlijstOpvragenRequest();
BestandenlijstOpvragenType verzoek = new BestandenlijstOpvragenType();
request.setVerzoek(verzoek);
AfgifteSelectieCriteriaType criteria = new AfgifteSelectieCriteriaType();
verzoek.setAfgifteSelectieCriteria(criteria);
criteria.setBestandKenmerken(new BestandKenmerkenType());
// Indicatie nog niet gerapporteerd
// Met deze indicatie wordt aangegeven of uitsluitend de nog niet gerapporteerde afgiftes
// moeten worden opgenomen in de lijst, of dat alle beschikbare afgiftes worden genoemd.
// Als deze indicator wordt gebruikt, dan worden na terugmelding van de bestandenlijst
// de bijbehorende bestanden gemarkeerd als zijnde ‘gerapporteerd’ in het systeem van GDS.
// alGerapporteerd
final Boolean alGerapporteerd = Boolean.TRUE;
criteria.setNogNietGerapporteerd(alGerapporteerd);
// vanaf
GregorianCalendar vanaf = getDatumTijd("01-09-2020");
GregorianCalendar tot;
// tot vandaag
//tot = getDatumTijd(new Date());
// tot 1 aug 2019
tot = getDatumTijd("10-09-2020");
// om bepaalde periode te selecteren; kan/mag niet samen met afgiftenummers
criteria.setPeriode(new FilterDatumTijdType());
// Indien vermeld worden alleen de afgiftes opgenomen in de lijst met een
// aanmeldingstijdstip NA genoemde datum/tijd.
criteria.getPeriode().setDatumTijdVanaf(getXMLDatumTijd(vanaf));
// Idem, met een aanmeldingstijdstip TOT en MET genoemde datum/tijd
// (tijdstip op seconde nauwkeurig).
criteria.getPeriode().setDatumTijdTotmet(getXMLDatumTijd(tot));
// om bepaalde afgiftenummers te selecteren; kan/mag niet samen met periode
KlantAfgiftenummerReeksType afgiftenummers = new KlantAfgiftenummerReeksType();
// Indien vermeld worden alleen afgiftes opgenomen in de lijst met een klantAfgiftenummer
// groter of gelijk aan het genoemde nummer
afgiftenummers.setKlantAfgiftenummerVanaf(BigInteger.ONE);
// Indien vermeld worden alleen afgiftes opgenomen in de lijst met een klantAfgiftenummer
// kleiner of gelijk aan het genoemde nummer.
// Deze bovengrens is alleen mogelijk in combinatie met een ondergrens (klantAfgiftenummer vanaf).
afgiftenummers.setKlantAfgiftenummerTotmet(BigInteger.valueOf(10000));
// criteria.setKlantAfgiftenummerReeks(afgiftenummers);
//
// artikelnummer
// Indien vermeld dan worden alleen de afgiftes opgenomen in de lijst die
// horen bij het genoemde artikelnummer
//
// maandelijkse BAG mutaties NL
// criteria.getBestandKenmerken().setArtikelnummer("2508");
// dagelijkse BAG mutaties NL
criteria.getBestandKenmerken().setArtikelnummer("2516");
//
// contractnummer voor BRK
//
// Indien vermeld dan worden alleen de afgiftes opgenomen in de lijst die
// gekoppeld zijn aan het genoemde contractnummer
//
// criteria.getBestandKenmerken().setContractnummer("9700005117");
LOG.info("Contract nummer: " + criteria.getBestandKenmerken().getContractnummer());
LOG.info("Artikel nummer: " + criteria.getBestandKenmerken().getArtikelnummer());
LOG.info("DatumTijdVanaf criterium: " + vanaf);
LOG.info("DatumTijdTot criterium: " + tot);
LOG.info("alGerapporteerd criterium: " + alGerapporteerd);
BestandenlijstOpvragenRequest bestandenlijstOpvragenRequest = new BestandenlijstOpvragenRequest();
BestandenlijstOpvragenType bestandenlijstOpvragenVerzoek = new BestandenlijstOpvragenType();
bestandenlijstOpvragenRequest.setVerzoek(bestandenlijstOpvragenVerzoek);
bestandenlijstOpvragenVerzoek.setAfgifteSelectieCriteria(criteria);
// BestandenlijstOpvragenResponse bestandenlijstOpvragenResponse = retryBestandenLijstOpvragen(
// gds2, bestandenlijstOpvragenRequest,<SUF>
// );
// // basis meta info van antwoord
// int afgifteAantalInLijst = bestandenlijstOpvragenResponse.getAntwoord().getAfgifteAantalInLijst();
// LOG.info("Aantal geselecteerde afgiftes in de lijst: " + afgifteAantalInLijst);
// int hoogsteAfgifteNummer = bestandenlijstOpvragenResponse.getAntwoord().getKlantAfgiftenummerMax();
// LOG.info("Hoogst toegekende klant afgiftenummer:" + hoogsteAfgifteNummer);
// BaseURLType baseUrlAnon = getAnoniemBaseURL(bestandenlijstOpvragenResponse.getAntwoord());
// BaseURLType baseUrlCert = getCertificaatBaseURL(bestandenlijstOpvragenResponse.getAntwoord());
// LOG.info("Baseurl te gebruiken als prefix voor anon download urls: " + baseUrlAnon.getValue());
// LOG.info("Baseurl te gebruiken als prefix voor anon certificaat urls: " + baseUrlCert.getValue());
// // true als er meer dan het maximum aantal afgiftes zijn gevonden _voor de selectie criteria_
// boolean hasMore = bestandenlijstOpvragenResponse.getAntwoord().isMeerAfgiftesbeschikbaar();
// LOG.info("Meer afgiftes beschikbaar? " + hasMore);
// TODO logica om datum periode of nummerreeks kleiner te maken dan max aantal
GregorianCalendar currentMoment = null;
boolean parseblePeriod = false;
int loopType = Calendar.DAY_OF_MONTH;
int loopMax = 180;
int loopNum = 0;
boolean reducePeriod = false;
boolean increasePeriod = false;
if (vanaf.before(tot)) {
parseblePeriod = true;
currentMoment = vanaf;
}
List<AfgifteType> afgiftes = new ArrayList<>();
BestandenlijstOpvragenResponse response = null;
int hoogsteKlantAfgifteNummer = -1;
boolean morePeriods2Process = false;
do /* while morePeriods2Process is true */ {
System.out.println("\n*** start periode ***");
//zet periode in criteria indien gewenst
if (parseblePeriod) {
//check of de periodeduur verkleind moet worden
if (reducePeriod) {
switch (loopType) {
case Calendar.DAY_OF_MONTH:
currentMoment.add(loopType, -1);
loopType = Calendar.HOUR_OF_DAY;
System.out.println("* Verklein loop periode naar uur");
break;
case Calendar.HOUR_OF_DAY:
currentMoment.add(loopType, -1);
loopType = Calendar.MINUTE;
System.out.println("* Verklein loop periode naar minuut");
break;
case Calendar.MINUTE:
default:
/*
* Hier kom je alleen als binnen een minuut meer
* dan 2000 berichten zijn aangamaakt en het
* vinkje ook "al rapporteerde berichten
* ophalen" staat aan.
*/
System.out.println("Niet alle gevraagde berichten zijn opgehaald");
}
reducePeriod = false;
}
//check of de periodeduur vergroot moet worden
if (increasePeriod) {
switch (loopType) {
case Calendar.HOUR_OF_DAY:
loopType = Calendar.DAY_OF_MONTH;
System.out.println("* Vergroot loop periode naar dag");
break;
case Calendar.MINUTE:
loopType = Calendar.HOUR_OF_DAY;
System.out.println("* Vergroot loop periode naar uur");
break;
case Calendar.DAY_OF_MONTH:
default:
//not possible
}
increasePeriod = false;
}
FilterDatumTijdType d = new FilterDatumTijdType();
d.setDatumTijdVanaf(getXMLDatumTijd(currentMoment));
System.out.println(String.format("Datum vanaf: %tc", currentMoment.getTime()));
currentMoment.add(loopType, 1);
d.setDatumTijdTotmet(getXMLDatumTijd(currentMoment));
System.out.println(String.format("Datum tot: %tc", currentMoment.getTime()));
criteria.setPeriode(d);
switch (loopType) {
case Calendar.HOUR_OF_DAY:
//0-23
if (currentMoment.get(loopType) == 0) {
increasePeriod = true;
}
break;
case Calendar.MINUTE:
//0-59
if (currentMoment.get(loopType) == 0) {
increasePeriod = true;
}
break;
case Calendar.DAY_OF_MONTH:
default:
//alleen dagen tellen, uur en minuut altijd helemaal
loopNum++;
}
//bereken of einde van periode bereikt is
if (currentMoment.before(tot) && loopNum < loopMax) {
morePeriods2Process = true;
} else {
morePeriods2Process = false;
}
}
verzoek.setAfgifteSelectieCriteria(criteria);
response = retryBestandenLijstOpvragen(gds2, request, 1, 10000);
hoogsteKlantAfgifteNummer = response.getAntwoord().getKlantAfgiftenummerMax();
int aantalInAntwoord = response.getAntwoord().getAfgifteAantalInLijst();
System.out.println("Aantal in antwoord: " + aantalInAntwoord);
// opletten; in de xsd staat een default value van 'J' voor meerAfgiftesbeschikbaar
boolean hasMore = response.getAntwoord().isMeerAfgiftesbeschikbaar();
System.out.println("Meer afgiftes beschikbaar: " + hasMore);
/*
* Als "al gerapporteerde berichten" moeten worden opgehaald en
* er zitten dan 2000 berichten in het antwoord dan heeft het
* geen zin om meer keer de berichten op te halen, je krijgt
* telkens dezelfde.
*/
if (hasMore && "true".equals(alGerapporteerd)) {
reducePeriod = true;
morePeriods2Process = true;
increasePeriod = false;
// als er geen parsable periode is
// (geen periode ingevuld en alGerapporteerd is true
// dan moet morePeriods2Process false worden om een
// eindloze while loop te voorkomen
if (!parseblePeriod) {
morePeriods2Process = false;
} else {
continue;
}
}
if (aantalInAntwoord > 0) {
afgiftes.addAll(response.getAntwoord().getBestandenLijst().getAfgifte());
}
/*
* Indicatie nog niet gerapporteerd: Met deze indicatie wordt
* aangegeven of uitsluitend de nog niet gerapporteerde
* bestanden moeten worden opgenomen in de lijst, of dat alle
* beschikbare bestanden worden genoemd. Niet gerapporteerd
* betekent in dit geval ‘niet eerder opgevraagd in deze
* bestandenlijst’. Als deze indicator wordt gebruikt, dan
* worden na terugmelding van de bestandenlijst de bijbehorende
* bestanden gemarkeerd als zijnde ‘gerapporteerd’ in het
* systeem van GDS.
*/
int moreCount = 0;
while (hasMore) {
System.out.println("Uitvoeren SOAP request naar Kadaster voor meer afgiftes..." + moreCount++);
criteria.setNogNietGerapporteerd(true);
response = retryBestandenLijstOpvragen(gds2, request, 1, 10000);
hoogsteKlantAfgifteNummer = response.getAntwoord().getKlantAfgiftenummerMax();
List<AfgifteType> afgifteLijst = response.getAntwoord().getBestandenLijst().getAfgifte();
for (AfgifteType t : afgiftes) {
// lijst urls naar aparte logfile loggen
if (t.getDigikoppelingExternalDatareferences() != null
&& t.getDigikoppelingExternalDatareferences().getDataReference() != null) {
for (DataReference dr : t.getDigikoppelingExternalDatareferences().getDataReference()) {
LOG.info("GDS2url te downloaden: " + dr.getTransport().getLocation().getSenderUrl().getValue());
break;
}
}
}
afgiftes.addAll(afgifteLijst);
aantalInAntwoord = response.getAntwoord().getAfgifteAantalInLijst();
System.out.println("Aantal in antwoord: " + aantalInAntwoord);
hasMore = response.getAntwoord().isMeerAfgiftesbeschikbaar();
System.out.println("Nog meer afgiftes beschikbaar: " + hasMore);
}
} while (morePeriods2Process);
System.out.println("Totaal aantal op te halen berichten: " + afgiftes.size());
System.out.println("Hoogste klant afgifte nummer: " + hoogsteKlantAfgifteNummer);
if (criteria.getBestandKenmerken().getContractnummer() == null) {
// bag response.getAntwoord()
printAfgiftes(afgiftes, getAnoniemBaseURL(response.getAntwoord()));
} else {
// brk
printAfgiftes(afgiftes, getCertificaatBaseURL(response.getAntwoord()));
}
}
private static void printAfgiftes(List<AfgifteType> afgiftes, BaseURLType baseUrl) {
LOG.info("Schrijf afgiftegegevens, bestandskenmerken en Digikoppeling datareference gegevens van de afgiftes in CSV.");
try (PrintWriter out = new PrintWriter("afgiftelijst.csv")) {
out.println("ID\treferentie\tdownloadUrl\tbestandsnaam\tbestandref\tbeschikbaarTot\tcontractafgiftenr\tklantafgiftenr\tcontractnr\tartikelnr\tartikelomschrijving\tcontextId\tcreationTime\texpirationTime\tfilename\tchecksum\ttype\tsize\tsenderUrl\treceiverUrl");
for (AfgifteType a : afgiftes) {
String kenmerken = "-\t-\t-";
if (a.getBestandKenmerken() != null) {
kenmerken = String.format("%s\t%s\t%s",
a.getBestandKenmerken().getContractnummer(),
a.getBestandKenmerken().getArtikelnummer(),
a.getBestandKenmerken().getArtikelomschrijving()
);
}
LOG.debug("Afgifte id: " + a.getAfgifteID());
out.printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t",
a.getAfgifteID(),
a.getAfgiftereferentie(),
getAfgifteURL(a, baseUrl),
a.getBestand().getBestandsnaam(),
a.getBestand().getBestandsreferentie(),
a.getBeschikbaarTot(),
a.getContractAfgiftenummer(),
a.getKlantAfgiftenummer(),
kenmerken);
if (a.getDigikoppelingExternalDatareferences() != null
&& a.getDigikoppelingExternalDatareferences().getDataReference() != null) {
for (DataReference dr : a.getDigikoppelingExternalDatareferences().getDataReference()) {
out.printf("%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n",
dr.getContextId() == null ? "-" : dr.getContextId(),
dr.getLifetime().getCreationTime().getValue(),
dr.getLifetime().getExpirationTime().getValue(),
dr.getContent().getFilename(),
dr.getContent().getChecksum().getValue(),
dr.getContent().getContentType(),
dr.getContent().getSize(),
dr.getTransport().getLocation().getSenderUrl() == null ? "-" : dr.getTransport().getLocation().getSenderUrl().getValue(),
dr.getTransport().getLocation().getReceiverUrl() == null ? "-" : dr.getTransport().getLocation().getReceiverUrl().getValue());
}
}
}
} catch (FileNotFoundException e) {
LOG.error("CSV maken is mislukt", e);
}
}
}
|
26219_0 | /*
* Copyright (C) 2024 Provincie Zeeland
*
* SPDX-License-Identifier: MIT
*/
package nl.b3p.planmonitorwonen.api.model;
import java.time.OffsetDateTime;
public final class Planregistratie {
private String id;
private String geometrie;
private String creator;
private OffsetDateTime createdAt;
private String editor;
private OffsetDateTime editedAt;
private String planNaam;
private String provincie;
private String gemeente;
private String regio;
private String plaatsnaam;
private String vertrouwelijkheid;
private String opdrachtgeverType;
private String opdrachtgeverNaam;
private Integer jaarStartProject;
private Integer opleveringEerste;
private Integer opleveringLaatste;
private String opmerkingen;
private String plantype;
private String bestemmingsplan;
private String statusProject;
private String statusPlanologisch;
private String knelpuntenMeerkeuze;
private String regionalePlanlijst;
private String toelichtingKnelpunten;
private Integer flexwoningen;
private Integer levensloopbestendigJa;
private Integer levensloopbestendigNee;
private String beoogdWoonmilieuAbf5;
private String beoogdWoonmilieuAbf13;
private Integer aantalStudentenwoningen;
private String toelichtingKwalitatief;
public String getId() {
return id;
}
public Planregistratie setId(String id) {
this.id = id;
return this;
}
public String getGeometrie() {
return geometrie;
}
public Planregistratie setGeometrie(String geometrie) {
this.geometrie = geometrie;
return this;
}
public String getCreator() {
return creator;
}
public Planregistratie setCreator(String creator) {
this.creator = creator;
return this;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public Planregistratie setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
return this;
}
public String getEditor() {
return editor;
}
public Planregistratie setEditor(String editor) {
this.editor = editor;
return this;
}
public OffsetDateTime getEditedAt() {
return editedAt;
}
public Planregistratie setEditedAt(OffsetDateTime editedAt) {
this.editedAt = editedAt;
return this;
}
public String getPlanNaam() {
return planNaam;
}
public Planregistratie setPlanNaam(String planNaam) {
this.planNaam = planNaam;
return this;
}
public String getProvincie() {
return provincie;
}
public Planregistratie setProvincie(String provincie) {
this.provincie = provincie;
return this;
}
public String getGemeente() {
return gemeente;
}
public Planregistratie setGemeente(String gemeente) {
this.gemeente = gemeente;
return this;
}
public String getRegio() {
return regio;
}
public Planregistratie setRegio(String regio) {
this.regio = regio;
return this;
}
public String getPlaatsnaam() {
return plaatsnaam;
}
public Planregistratie setPlaatsnaam(String plaatsnaam) {
this.plaatsnaam = plaatsnaam;
return this;
}
public String getVertrouwelijkheid() {
return vertrouwelijkheid;
}
public Planregistratie setVertrouwelijkheid(String vertrouwelijkheid) {
this.vertrouwelijkheid = vertrouwelijkheid;
return this;
}
public String getOpdrachtgeverType() {
return opdrachtgeverType;
}
public Planregistratie setOpdrachtgeverType(String opdrachtgeverType) {
this.opdrachtgeverType = opdrachtgeverType;
return this;
}
public String getOpdrachtgeverNaam() {
return opdrachtgeverNaam;
}
public Planregistratie setOpdrachtgeverNaam(String opdrachtgeverNaam) {
this.opdrachtgeverNaam = opdrachtgeverNaam;
return this;
}
public Integer getJaarStartProject() {
return jaarStartProject;
}
public Planregistratie setJaarStartProject(Integer jaarStartProject) {
this.jaarStartProject = jaarStartProject;
return this;
}
public Integer getOpleveringEerste() {
return opleveringEerste;
}
public Planregistratie setOpleveringEerste(Integer opleveringEerste) {
this.opleveringEerste = opleveringEerste;
return this;
}
public Integer getOpleveringLaatste() {
return opleveringLaatste;
}
public Planregistratie setOpleveringLaatste(Integer opleveringLaatste) {
this.opleveringLaatste = opleveringLaatste;
return this;
}
public String getOpmerkingen() {
return opmerkingen;
}
public Planregistratie setOpmerkingen(String opmerkingen) {
this.opmerkingen = opmerkingen;
return this;
}
public String getPlantype() {
return plantype;
}
public Planregistratie setPlantype(String plantype) {
this.plantype = plantype;
return this;
}
public String getBestemmingsplan() {
return bestemmingsplan;
}
public Planregistratie setBestemmingsplan(String bestemmingsplan) {
this.bestemmingsplan = bestemmingsplan;
return this;
}
public String getStatusProject() {
return statusProject;
}
public Planregistratie setStatusProject(String statusProject) {
this.statusProject = statusProject;
return this;
}
public String getStatusPlanologisch() {
return statusPlanologisch;
}
public Planregistratie setStatusPlanologisch(String statusPlanologisch) {
this.statusPlanologisch = statusPlanologisch;
return this;
}
public String getKnelpuntenMeerkeuze() {
return knelpuntenMeerkeuze;
}
public Planregistratie setKnelpuntenMeerkeuze(String knelpuntenMeerkeuze) {
this.knelpuntenMeerkeuze = knelpuntenMeerkeuze;
return this;
}
public String getRegionalePlanlijst() {
return regionalePlanlijst;
}
public Planregistratie setRegionalePlanlijst(String regionalePlanlijst) {
this.regionalePlanlijst = regionalePlanlijst;
return this;
}
public String getToelichtingKnelpunten() {
return toelichtingKnelpunten;
}
public Planregistratie setToelichtingKnelpunten(String toelichtingKnelpunten) {
this.toelichtingKnelpunten = toelichtingKnelpunten;
return this;
}
public Integer getFlexwoningen() {
return flexwoningen;
}
public Planregistratie setFlexwoningen(Integer flexwoningen) {
this.flexwoningen = flexwoningen;
return this;
}
public Integer getLevensloopbestendigJa() {
return levensloopbestendigJa;
}
public Planregistratie setLevensloopbestendigJa(Integer levensloopbestendigJa) {
this.levensloopbestendigJa = levensloopbestendigJa;
return this;
}
public Integer getLevensloopbestendigNee() {
return levensloopbestendigNee;
}
public Planregistratie setLevensloopbestendigNee(Integer levensloopbestendigNee) {
this.levensloopbestendigNee = levensloopbestendigNee;
return this;
}
public String getBeoogdWoonmilieuAbf5() {
return beoogdWoonmilieuAbf5;
}
public Planregistratie setBeoogdWoonmilieuAbf5(String beoogdWoonmilieuAbf5) {
this.beoogdWoonmilieuAbf5 = beoogdWoonmilieuAbf5;
return this;
}
public String getBeoogdWoonmilieuAbf13() {
return beoogdWoonmilieuAbf13;
}
public Planregistratie setBeoogdWoonmilieuAbf13(String beoogdWoonmilieuAbf13) {
this.beoogdWoonmilieuAbf13 = beoogdWoonmilieuAbf13;
return this;
}
public Integer getAantalStudentenwoningen() {
return aantalStudentenwoningen;
}
public Planregistratie setAantalStudentenwoningen(Integer aantalStudentenwoningen) {
this.aantalStudentenwoningen = aantalStudentenwoningen;
return this;
}
public String getToelichtingKwalitatief() {
return toelichtingKwalitatief;
}
public Planregistratie setToelichtingKwalitatief(String toelichtingKwalitatief) {
this.toelichtingKwalitatief = toelichtingKwalitatief;
return this;
}
}
| B3Partners/planmonitor-wonen-api | src/main/java/nl/b3p/planmonitorwonen/api/model/Planregistratie.java | 2,615 | /*
* Copyright (C) 2024 Provincie Zeeland
*
* SPDX-License-Identifier: MIT
*/ | block_comment | nl | /*
* Copyright (C) 2024<SUF>*/
package nl.b3p.planmonitorwonen.api.model;
import java.time.OffsetDateTime;
public final class Planregistratie {
private String id;
private String geometrie;
private String creator;
private OffsetDateTime createdAt;
private String editor;
private OffsetDateTime editedAt;
private String planNaam;
private String provincie;
private String gemeente;
private String regio;
private String plaatsnaam;
private String vertrouwelijkheid;
private String opdrachtgeverType;
private String opdrachtgeverNaam;
private Integer jaarStartProject;
private Integer opleveringEerste;
private Integer opleveringLaatste;
private String opmerkingen;
private String plantype;
private String bestemmingsplan;
private String statusProject;
private String statusPlanologisch;
private String knelpuntenMeerkeuze;
private String regionalePlanlijst;
private String toelichtingKnelpunten;
private Integer flexwoningen;
private Integer levensloopbestendigJa;
private Integer levensloopbestendigNee;
private String beoogdWoonmilieuAbf5;
private String beoogdWoonmilieuAbf13;
private Integer aantalStudentenwoningen;
private String toelichtingKwalitatief;
public String getId() {
return id;
}
public Planregistratie setId(String id) {
this.id = id;
return this;
}
public String getGeometrie() {
return geometrie;
}
public Planregistratie setGeometrie(String geometrie) {
this.geometrie = geometrie;
return this;
}
public String getCreator() {
return creator;
}
public Planregistratie setCreator(String creator) {
this.creator = creator;
return this;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public Planregistratie setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
return this;
}
public String getEditor() {
return editor;
}
public Planregistratie setEditor(String editor) {
this.editor = editor;
return this;
}
public OffsetDateTime getEditedAt() {
return editedAt;
}
public Planregistratie setEditedAt(OffsetDateTime editedAt) {
this.editedAt = editedAt;
return this;
}
public String getPlanNaam() {
return planNaam;
}
public Planregistratie setPlanNaam(String planNaam) {
this.planNaam = planNaam;
return this;
}
public String getProvincie() {
return provincie;
}
public Planregistratie setProvincie(String provincie) {
this.provincie = provincie;
return this;
}
public String getGemeente() {
return gemeente;
}
public Planregistratie setGemeente(String gemeente) {
this.gemeente = gemeente;
return this;
}
public String getRegio() {
return regio;
}
public Planregistratie setRegio(String regio) {
this.regio = regio;
return this;
}
public String getPlaatsnaam() {
return plaatsnaam;
}
public Planregistratie setPlaatsnaam(String plaatsnaam) {
this.plaatsnaam = plaatsnaam;
return this;
}
public String getVertrouwelijkheid() {
return vertrouwelijkheid;
}
public Planregistratie setVertrouwelijkheid(String vertrouwelijkheid) {
this.vertrouwelijkheid = vertrouwelijkheid;
return this;
}
public String getOpdrachtgeverType() {
return opdrachtgeverType;
}
public Planregistratie setOpdrachtgeverType(String opdrachtgeverType) {
this.opdrachtgeverType = opdrachtgeverType;
return this;
}
public String getOpdrachtgeverNaam() {
return opdrachtgeverNaam;
}
public Planregistratie setOpdrachtgeverNaam(String opdrachtgeverNaam) {
this.opdrachtgeverNaam = opdrachtgeverNaam;
return this;
}
public Integer getJaarStartProject() {
return jaarStartProject;
}
public Planregistratie setJaarStartProject(Integer jaarStartProject) {
this.jaarStartProject = jaarStartProject;
return this;
}
public Integer getOpleveringEerste() {
return opleveringEerste;
}
public Planregistratie setOpleveringEerste(Integer opleveringEerste) {
this.opleveringEerste = opleveringEerste;
return this;
}
public Integer getOpleveringLaatste() {
return opleveringLaatste;
}
public Planregistratie setOpleveringLaatste(Integer opleveringLaatste) {
this.opleveringLaatste = opleveringLaatste;
return this;
}
public String getOpmerkingen() {
return opmerkingen;
}
public Planregistratie setOpmerkingen(String opmerkingen) {
this.opmerkingen = opmerkingen;
return this;
}
public String getPlantype() {
return plantype;
}
public Planregistratie setPlantype(String plantype) {
this.plantype = plantype;
return this;
}
public String getBestemmingsplan() {
return bestemmingsplan;
}
public Planregistratie setBestemmingsplan(String bestemmingsplan) {
this.bestemmingsplan = bestemmingsplan;
return this;
}
public String getStatusProject() {
return statusProject;
}
public Planregistratie setStatusProject(String statusProject) {
this.statusProject = statusProject;
return this;
}
public String getStatusPlanologisch() {
return statusPlanologisch;
}
public Planregistratie setStatusPlanologisch(String statusPlanologisch) {
this.statusPlanologisch = statusPlanologisch;
return this;
}
public String getKnelpuntenMeerkeuze() {
return knelpuntenMeerkeuze;
}
public Planregistratie setKnelpuntenMeerkeuze(String knelpuntenMeerkeuze) {
this.knelpuntenMeerkeuze = knelpuntenMeerkeuze;
return this;
}
public String getRegionalePlanlijst() {
return regionalePlanlijst;
}
public Planregistratie setRegionalePlanlijst(String regionalePlanlijst) {
this.regionalePlanlijst = regionalePlanlijst;
return this;
}
public String getToelichtingKnelpunten() {
return toelichtingKnelpunten;
}
public Planregistratie setToelichtingKnelpunten(String toelichtingKnelpunten) {
this.toelichtingKnelpunten = toelichtingKnelpunten;
return this;
}
public Integer getFlexwoningen() {
return flexwoningen;
}
public Planregistratie setFlexwoningen(Integer flexwoningen) {
this.flexwoningen = flexwoningen;
return this;
}
public Integer getLevensloopbestendigJa() {
return levensloopbestendigJa;
}
public Planregistratie setLevensloopbestendigJa(Integer levensloopbestendigJa) {
this.levensloopbestendigJa = levensloopbestendigJa;
return this;
}
public Integer getLevensloopbestendigNee() {
return levensloopbestendigNee;
}
public Planregistratie setLevensloopbestendigNee(Integer levensloopbestendigNee) {
this.levensloopbestendigNee = levensloopbestendigNee;
return this;
}
public String getBeoogdWoonmilieuAbf5() {
return beoogdWoonmilieuAbf5;
}
public Planregistratie setBeoogdWoonmilieuAbf5(String beoogdWoonmilieuAbf5) {
this.beoogdWoonmilieuAbf5 = beoogdWoonmilieuAbf5;
return this;
}
public String getBeoogdWoonmilieuAbf13() {
return beoogdWoonmilieuAbf13;
}
public Planregistratie setBeoogdWoonmilieuAbf13(String beoogdWoonmilieuAbf13) {
this.beoogdWoonmilieuAbf13 = beoogdWoonmilieuAbf13;
return this;
}
public Integer getAantalStudentenwoningen() {
return aantalStudentenwoningen;
}
public Planregistratie setAantalStudentenwoningen(Integer aantalStudentenwoningen) {
this.aantalStudentenwoningen = aantalStudentenwoningen;
return this;
}
public String getToelichtingKwalitatief() {
return toelichtingKwalitatief;
}
public Planregistratie setToelichtingKwalitatief(String toelichtingKwalitatief) {
this.toelichtingKwalitatief = toelichtingKwalitatief;
return this;
}
}
|
128166_10 | /**
* $Id$
*/
package org.securityfilter.authenticator;
import java.io.IOException;
import java.security.Principal;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.FilterConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.securityfilter.config.SecurityConfig;
import org.securityfilter.filter.SecurityRequestWrapper;
import org.securityfilter.filter.URLPatternMatcher;
import org.securityfilter.realm.ExternalAuthenticatedRealm;
/**
* Idem als FormAuthenticator, maar zet na de login een cookie voor andere webapps
* op hetzelfde domein met login info. Deze login info kan door webapps met
* een secret key worden gedecrypt en daarmee de gebruiker inloggen.
*/
public class FormDomainCookieTokenAuthenticator extends FormAuthenticator {
private final static Log log = LogFactory.getLog(FormDomainCookieTokenAuthenticator.class);
protected final static String AUTH_TOKEN_COOKIE_PRINCIPAL = FormDomainCookieTokenAuthenticator.class.getName() + ".AUTH_TOKEN_COOKIE_PRINCIPAL";
protected final static String AUTHORIZED_BY_AUTH_TOKEN = FormDomainCookieTokenAuthenticator.class.getName() + ".AUTHORIZED_BY_AUTH_TOKEN";
protected final static String COOKIE_NAME = "AuthToken";
protected final static String CHARSET = "US-ASCII";
protected final static String encryptionAlgorithm = "AES";
/**
* Key waarmee het cookie wordt encrypt/decrypt.
*/
protected SecretKey secretKey;
/**
* String die wordt toegevoegd aan het cookie voor het hashen, dit om de
* geldigheid van de gedecypte waardes te controleren.
*/
protected String extraHashString;
/**
* Paden waarvoor cookies moeten worden gezet.
*/
protected String[] cookiePaths;
/**
* Aantal seconden dat het auth token cookie geldig is
*/
protected int cookieExpire;
/**
* Of na inloggen cookies moeten worden gemaakt.
*/
protected boolean setCookies;
/**
* Of voor inloggen gechecked moet worden of er een geldig auth token cookie
* aanwezig is.
*/
protected boolean acceptCookie;
public void init(FilterConfig filterConfig, SecurityConfig securityConfig) throws Exception {
super.init(filterConfig, securityConfig);
/* lees configuratie uit */
setCookies = securityConfig.isSetCookies();
acceptCookie = securityConfig.isAcceptCookie();
if(acceptCookie && !(securityConfig.getRealm() instanceof ExternalAuthenticatedRealm)) {
throw new IllegalArgumentException("Security realm must implement ExternalAuthenticatedRealm to accept auth token cookies");
}
String secretKeyHex = securityConfig.getSecretKey();
log.info("secrey key hex length: " + secretKeyHex.length());
setEncryptionKey(new Hex().decode(secretKeyHex.getBytes(CHARSET)));
extraHashString = securityConfig.getExtraHashString();
if(setCookies) {
cookiePaths = securityConfig.getCookiePaths().split(";");
for(int i = 0; i < cookiePaths.length; i++) {
cookiePaths[i] = cookiePaths[i].trim();
}
cookieExpire = securityConfig.getCookieExpire();
}
}
/** Wrapper voor HttpServletResponse die het response object voor het
* aanroepen van de super-methode, omdat na het aanroepen van
* response.sendRedirect() geen cookies meer kunnen worden toegevoegd.
*/
private class DelayRedirectHttpServletResponseWrapper extends HttpServletResponseWrapper {
private String redirectLocation = null;
public DelayRedirectHttpServletResponseWrapper(HttpServletResponse response) {
super(response);
}
public void sendRedirect(String location) {
/* sla alleen het argument van de eerste aanroep op */
if(this.redirectLocation == null) {
this.redirectLocation = location;
}
}
/**
* Geeft null indien geen sendRedirect() op de wrapper is aangeroepen,
* of het location argument voor de sendRedirect() aanroep indien
* wel.
*/
public String getRedirectLocation() {
return this.redirectLocation;
}
public void sendDelayedRedirect() throws IOException {
if(this.redirectLocation != null) {
super.sendRedirect(getRedirectLocation());
}
}
}
public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response) throws Exception {
/* Indien acceptCookies en er is nog geen principal, check of er een
* geldig auth token cookie aanwezig is voordat de super methode wordt
* aangeroepen.
*
* Dit stukje code lijkt erg op het eerste stuk in de super-methode
* welke persistant login checked.
*/
boolean loggedInByToken = false;
if(acceptCookie) {
if(Boolean.TRUE.equals(request.getSession().getAttribute(AUTHORIZED_BY_AUTH_TOKEN))) {
loggedInByToken = true;
} else if(request.getRemoteUser() == null) {
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(int i = 0; i < cookies.length; i++) {
if(COOKIE_NAME.equals(cookies[i].getName())) {
Principal authTokenPrincipal = getAuthTokenPrincipal(request, cookies[i]);
if(authTokenPrincipal != null) {
request.setUserPrincipal(authTokenPrincipal);
request.getSession().setAttribute(AUTHORIZED_BY_AUTH_TOKEN, Boolean.TRUE);
log.info("user " + request.getRemoteUser() + " logged in by auth token cookie (" + cookies[i].getValue() + ")");
loggedInByToken = true;
}
break;
}
}
}
}
}
if(!setCookies || loggedInByToken) {
/* geen speciale processing, roep alleen super-methode aan */
return super.processLogin(request, response);
} else {
/* Check na het aanroepen van de super-methode of er een principal
* is waarvoor we een cookie moeten zetten.
*/
/* Zorg er wel voor dat eventuele redirects niet direct worden
* verstuurd, want dan is het niet meer mogelijk om cookies aan het
* request toe te voegen.
*/
DelayRedirectHttpServletResponseWrapper wrappedResponse = new DelayRedirectHttpServletResponseWrapper(response);
boolean processLogin = super.processLogin(request, wrappedResponse);
/* indien gebruiker is ingelogd en eerder nog geen cookie is gezet,
* voeg cookie toe.
*/
if(request.getUserPrincipal() != null && request.getUserPrincipal() != request.getSession().getAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL)) {
request.getSession().setAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL, request.getUserPrincipal());
setAuthTokenCookies(request, response);
}
/* verwijder eventueel bestaand cookie indien niet ingelogd */
if(request.getUserPrincipal() == null && request.getSession().getAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL) != null) {
removeCookies(request, response);
request.getSession().removeAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL);
}
/* Indien door de super-methode sendRedirect() was aangeroepen op de
* wrapper, doe dit nu op de originele response (nadat hierboven
* eventueel cookies zijn toegevoegd).
*/
wrappedResponse.sendDelayedRedirect();
return processLogin;
}
}
private void setAuthTokenCookies(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter(FORM_USERNAME);
String password = request.getParameter(FORM_PASSWORD);
if(log.isDebugEnabled()) {
log.debug("set AuthToken cookie(s) for user: " + username);
}
/* Maak voor elk path een cookie aan */
for(int i = 0; i < cookiePaths.length; i++) {
String path = cookiePaths[i];
/* De inhoud van het cookie is het path (om te checken met het path
* van het cookie in het request, zodat niet door het veranderen
* van het path iemand op een webapp kan inloggen terwijl dat niet
* bedoeld is), username, password, geldigheidsduur en huidige tijd
* (om geldigheidsduur van het token te controleren).
*/
String value = System.currentTimeMillis()
+ ";" + cookieExpire
+ ";" + username
+ ";" + password
+ ";" + path;
/* Voeg een extra waarde toe zodat met behulp van een hash de
* geldigheid kan worden gecontroleerd.
*/
value = value + ";" + DigestUtils.shaHex((value + ";" + extraHashString).getBytes(CHARSET));
String encryptedValue = encryptText(value, getCipherParameters(), secretKey, CHARSET);
/* Verwijder eventuele \r\n karakters die door Commons-Codec 1.4
* zijn toegevoegd. Deze zijn niet toegestaan in een cookie.
*/
encryptedValue = encryptedValue.replaceAll("[\r\n]", "");
log.debug("settting auth token cookie value (len=" + value.length() + "): " + value + " - encrypted: (len=" + encryptedValue.length() + "): " + encryptedValue);
Cookie token = new Cookie(COOKIE_NAME, encryptedValue);
token.setPath(path);
token.setMaxAge(cookieExpire);
response.addCookie(token);
}
}
private Principal getAuthTokenPrincipal(SecurityRequestWrapper request, Cookie authToken) throws Exception {
String value = authToken.getValue();
/* Decrypt cookie */
try {
value = decryptText(value, getCipherParameters(), secretKey, CHARSET);
} catch(Exception e) {
log.info("Not accepting auth token cookie because of exception during decryption: " + e.getClass() + ": " + e.getMessage());;
log.debug("Exception decrypting auth token cookie", e);
return null;
}
String[] fields = value.split(";");
if(fields.length != 6) {
log.warn("invalid auth token cookie (invalid field count: " + fields.length + ")");
return null;
}
long cookieSetTime = -1;
int cookieExpire = -1;
try {
cookieSetTime = Long.parseLong(fields[0]);
cookieExpire = Integer.parseInt(fields[1]);
} catch(NumberFormatException nfe) {
log.warn("invalid auth token cookie, wrong number format");
return null;
}
String username = fields[2];
String password = fields[3];
String path = fields[4];
String hash = fields[5];
if(!request.getContextPath().equals(path)) {
log.warn("auth token cookie path invalid: " + path);
return null;
}
String hashInput = cookieSetTime + ";" + cookieExpire + ";" + username + ";" + password + ";" + path + ";" + extraHashString;
String hashed = DigestUtils.shaHex(hashInput.getBytes(CHARSET));
if(!hashed.equals(hash)) {
log.warn("auth token cookie hash mismatch: input=" + hashInput + "; hashed=" + hashed + "; cookie hash=" + fields[4]);
return null;
}
log.info("accepting auth token cookie for user " + username);
return ((ExternalAuthenticatedRealm)realm).getAuthenticatedPrincipal(username, password);
}
private String getCipherParameters() {
return encryptionAlgorithm;
}
/**
* Encrypt a string.
*
* @param clearText
* @return clearText, encrypted
*/
private String encryptText(String clearText, String cipherParameters, SecretKey secretKey, String charset) throws Exception {
Base64 encoder = new Base64();
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.ENCRYPT_MODE, secretKey);
byte clearTextBytes[];
clearTextBytes = clearText.getBytes();
byte encryptedText[] = c1.doFinal(clearTextBytes);
String encryptedEncodedText = new String(encoder.encode(encryptedText), charset);
return encryptedEncodedText;
}
/**
* Decrypt a string.
*
* @param encryptedText
* @return encryptedText, decrypted
*/
private static String decryptText(String encryptedText, String cipherParameters, SecretKey secretKey, String charset) throws Exception {
Base64 decoder = new Base64();
byte decodedEncryptedText[] = decoder.decode(encryptedText.getBytes(charset));
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = c1.doFinal(decodedEncryptedText);
String decryptedTextString = new String(decryptedText);
return decryptedTextString;
}
private void removeCookies(HttpServletRequest request, HttpServletResponse response) {
if(log.isDebugEnabled()) {
log.debug("removing AuthToken cookies in request: " + request.getRequestURI());
}
for(int i = 0; i < cookiePaths.length; i++) {
Cookie expired = new Cookie(COOKIE_NAME, "none");
expired.setPath(cookiePaths[i]);
expired.setMaxAge(0);
response.addCookie(expired);
}
}
public boolean processLogout(SecurityRequestWrapper request, HttpServletResponse response, URLPatternMatcher patternMatcher) throws Exception {
boolean processLogout = super.processLogout(request, response, patternMatcher);
if(processLogout) {
if(request.getSession().getAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL) != null) {
removeCookies(request, response);
request.getSession().removeAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL);
}
/* indien auth token geaccepteerd is, verwijder dat cookie voor ons
* path
*/
if(Boolean.TRUE.equals(request.getSession().getAttribute(AUTHORIZED_BY_AUTH_TOKEN))) {
log.debug("processLogout(): principal was authorized by auth token cookie, removing cookie");
Cookie authToken = new Cookie(COOKIE_NAME, "none");
authToken.setPath(request.getContextPath());
authToken.setMaxAge(0);
response.addCookie(authToken);
}
}
return processLogout;
}
private void setEncryptionKey(byte[] encryptionkey) throws Exception {
secretKey = new SecretKeySpec(encryptionkey, encryptionAlgorithm);
}
} | B3Partners/securityfilter-b3p | src/main/java/org/securityfilter/authenticator/FormDomainCookieTokenAuthenticator.java | 4,176 | /**
* Geeft null indien geen sendRedirect() op de wrapper is aangeroepen,
* of het location argument voor de sendRedirect() aanroep indien
* wel.
*/ | block_comment | nl | /**
* $Id$
*/
package org.securityfilter.authenticator;
import java.io.IOException;
import java.security.Principal;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.FilterConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.securityfilter.config.SecurityConfig;
import org.securityfilter.filter.SecurityRequestWrapper;
import org.securityfilter.filter.URLPatternMatcher;
import org.securityfilter.realm.ExternalAuthenticatedRealm;
/**
* Idem als FormAuthenticator, maar zet na de login een cookie voor andere webapps
* op hetzelfde domein met login info. Deze login info kan door webapps met
* een secret key worden gedecrypt en daarmee de gebruiker inloggen.
*/
public class FormDomainCookieTokenAuthenticator extends FormAuthenticator {
private final static Log log = LogFactory.getLog(FormDomainCookieTokenAuthenticator.class);
protected final static String AUTH_TOKEN_COOKIE_PRINCIPAL = FormDomainCookieTokenAuthenticator.class.getName() + ".AUTH_TOKEN_COOKIE_PRINCIPAL";
protected final static String AUTHORIZED_BY_AUTH_TOKEN = FormDomainCookieTokenAuthenticator.class.getName() + ".AUTHORIZED_BY_AUTH_TOKEN";
protected final static String COOKIE_NAME = "AuthToken";
protected final static String CHARSET = "US-ASCII";
protected final static String encryptionAlgorithm = "AES";
/**
* Key waarmee het cookie wordt encrypt/decrypt.
*/
protected SecretKey secretKey;
/**
* String die wordt toegevoegd aan het cookie voor het hashen, dit om de
* geldigheid van de gedecypte waardes te controleren.
*/
protected String extraHashString;
/**
* Paden waarvoor cookies moeten worden gezet.
*/
protected String[] cookiePaths;
/**
* Aantal seconden dat het auth token cookie geldig is
*/
protected int cookieExpire;
/**
* Of na inloggen cookies moeten worden gemaakt.
*/
protected boolean setCookies;
/**
* Of voor inloggen gechecked moet worden of er een geldig auth token cookie
* aanwezig is.
*/
protected boolean acceptCookie;
public void init(FilterConfig filterConfig, SecurityConfig securityConfig) throws Exception {
super.init(filterConfig, securityConfig);
/* lees configuratie uit */
setCookies = securityConfig.isSetCookies();
acceptCookie = securityConfig.isAcceptCookie();
if(acceptCookie && !(securityConfig.getRealm() instanceof ExternalAuthenticatedRealm)) {
throw new IllegalArgumentException("Security realm must implement ExternalAuthenticatedRealm to accept auth token cookies");
}
String secretKeyHex = securityConfig.getSecretKey();
log.info("secrey key hex length: " + secretKeyHex.length());
setEncryptionKey(new Hex().decode(secretKeyHex.getBytes(CHARSET)));
extraHashString = securityConfig.getExtraHashString();
if(setCookies) {
cookiePaths = securityConfig.getCookiePaths().split(";");
for(int i = 0; i < cookiePaths.length; i++) {
cookiePaths[i] = cookiePaths[i].trim();
}
cookieExpire = securityConfig.getCookieExpire();
}
}
/** Wrapper voor HttpServletResponse die het response object voor het
* aanroepen van de super-methode, omdat na het aanroepen van
* response.sendRedirect() geen cookies meer kunnen worden toegevoegd.
*/
private class DelayRedirectHttpServletResponseWrapper extends HttpServletResponseWrapper {
private String redirectLocation = null;
public DelayRedirectHttpServletResponseWrapper(HttpServletResponse response) {
super(response);
}
public void sendRedirect(String location) {
/* sla alleen het argument van de eerste aanroep op */
if(this.redirectLocation == null) {
this.redirectLocation = location;
}
}
/**
* Geeft null indien<SUF>*/
public String getRedirectLocation() {
return this.redirectLocation;
}
public void sendDelayedRedirect() throws IOException {
if(this.redirectLocation != null) {
super.sendRedirect(getRedirectLocation());
}
}
}
public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response) throws Exception {
/* Indien acceptCookies en er is nog geen principal, check of er een
* geldig auth token cookie aanwezig is voordat de super methode wordt
* aangeroepen.
*
* Dit stukje code lijkt erg op het eerste stuk in de super-methode
* welke persistant login checked.
*/
boolean loggedInByToken = false;
if(acceptCookie) {
if(Boolean.TRUE.equals(request.getSession().getAttribute(AUTHORIZED_BY_AUTH_TOKEN))) {
loggedInByToken = true;
} else if(request.getRemoteUser() == null) {
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(int i = 0; i < cookies.length; i++) {
if(COOKIE_NAME.equals(cookies[i].getName())) {
Principal authTokenPrincipal = getAuthTokenPrincipal(request, cookies[i]);
if(authTokenPrincipal != null) {
request.setUserPrincipal(authTokenPrincipal);
request.getSession().setAttribute(AUTHORIZED_BY_AUTH_TOKEN, Boolean.TRUE);
log.info("user " + request.getRemoteUser() + " logged in by auth token cookie (" + cookies[i].getValue() + ")");
loggedInByToken = true;
}
break;
}
}
}
}
}
if(!setCookies || loggedInByToken) {
/* geen speciale processing, roep alleen super-methode aan */
return super.processLogin(request, response);
} else {
/* Check na het aanroepen van de super-methode of er een principal
* is waarvoor we een cookie moeten zetten.
*/
/* Zorg er wel voor dat eventuele redirects niet direct worden
* verstuurd, want dan is het niet meer mogelijk om cookies aan het
* request toe te voegen.
*/
DelayRedirectHttpServletResponseWrapper wrappedResponse = new DelayRedirectHttpServletResponseWrapper(response);
boolean processLogin = super.processLogin(request, wrappedResponse);
/* indien gebruiker is ingelogd en eerder nog geen cookie is gezet,
* voeg cookie toe.
*/
if(request.getUserPrincipal() != null && request.getUserPrincipal() != request.getSession().getAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL)) {
request.getSession().setAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL, request.getUserPrincipal());
setAuthTokenCookies(request, response);
}
/* verwijder eventueel bestaand cookie indien niet ingelogd */
if(request.getUserPrincipal() == null && request.getSession().getAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL) != null) {
removeCookies(request, response);
request.getSession().removeAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL);
}
/* Indien door de super-methode sendRedirect() was aangeroepen op de
* wrapper, doe dit nu op de originele response (nadat hierboven
* eventueel cookies zijn toegevoegd).
*/
wrappedResponse.sendDelayedRedirect();
return processLogin;
}
}
private void setAuthTokenCookies(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter(FORM_USERNAME);
String password = request.getParameter(FORM_PASSWORD);
if(log.isDebugEnabled()) {
log.debug("set AuthToken cookie(s) for user: " + username);
}
/* Maak voor elk path een cookie aan */
for(int i = 0; i < cookiePaths.length; i++) {
String path = cookiePaths[i];
/* De inhoud van het cookie is het path (om te checken met het path
* van het cookie in het request, zodat niet door het veranderen
* van het path iemand op een webapp kan inloggen terwijl dat niet
* bedoeld is), username, password, geldigheidsduur en huidige tijd
* (om geldigheidsduur van het token te controleren).
*/
String value = System.currentTimeMillis()
+ ";" + cookieExpire
+ ";" + username
+ ";" + password
+ ";" + path;
/* Voeg een extra waarde toe zodat met behulp van een hash de
* geldigheid kan worden gecontroleerd.
*/
value = value + ";" + DigestUtils.shaHex((value + ";" + extraHashString).getBytes(CHARSET));
String encryptedValue = encryptText(value, getCipherParameters(), secretKey, CHARSET);
/* Verwijder eventuele \r\n karakters die door Commons-Codec 1.4
* zijn toegevoegd. Deze zijn niet toegestaan in een cookie.
*/
encryptedValue = encryptedValue.replaceAll("[\r\n]", "");
log.debug("settting auth token cookie value (len=" + value.length() + "): " + value + " - encrypted: (len=" + encryptedValue.length() + "): " + encryptedValue);
Cookie token = new Cookie(COOKIE_NAME, encryptedValue);
token.setPath(path);
token.setMaxAge(cookieExpire);
response.addCookie(token);
}
}
private Principal getAuthTokenPrincipal(SecurityRequestWrapper request, Cookie authToken) throws Exception {
String value = authToken.getValue();
/* Decrypt cookie */
try {
value = decryptText(value, getCipherParameters(), secretKey, CHARSET);
} catch(Exception e) {
log.info("Not accepting auth token cookie because of exception during decryption: " + e.getClass() + ": " + e.getMessage());;
log.debug("Exception decrypting auth token cookie", e);
return null;
}
String[] fields = value.split(";");
if(fields.length != 6) {
log.warn("invalid auth token cookie (invalid field count: " + fields.length + ")");
return null;
}
long cookieSetTime = -1;
int cookieExpire = -1;
try {
cookieSetTime = Long.parseLong(fields[0]);
cookieExpire = Integer.parseInt(fields[1]);
} catch(NumberFormatException nfe) {
log.warn("invalid auth token cookie, wrong number format");
return null;
}
String username = fields[2];
String password = fields[3];
String path = fields[4];
String hash = fields[5];
if(!request.getContextPath().equals(path)) {
log.warn("auth token cookie path invalid: " + path);
return null;
}
String hashInput = cookieSetTime + ";" + cookieExpire + ";" + username + ";" + password + ";" + path + ";" + extraHashString;
String hashed = DigestUtils.shaHex(hashInput.getBytes(CHARSET));
if(!hashed.equals(hash)) {
log.warn("auth token cookie hash mismatch: input=" + hashInput + "; hashed=" + hashed + "; cookie hash=" + fields[4]);
return null;
}
log.info("accepting auth token cookie for user " + username);
return ((ExternalAuthenticatedRealm)realm).getAuthenticatedPrincipal(username, password);
}
private String getCipherParameters() {
return encryptionAlgorithm;
}
/**
* Encrypt a string.
*
* @param clearText
* @return clearText, encrypted
*/
private String encryptText(String clearText, String cipherParameters, SecretKey secretKey, String charset) throws Exception {
Base64 encoder = new Base64();
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.ENCRYPT_MODE, secretKey);
byte clearTextBytes[];
clearTextBytes = clearText.getBytes();
byte encryptedText[] = c1.doFinal(clearTextBytes);
String encryptedEncodedText = new String(encoder.encode(encryptedText), charset);
return encryptedEncodedText;
}
/**
* Decrypt a string.
*
* @param encryptedText
* @return encryptedText, decrypted
*/
private static String decryptText(String encryptedText, String cipherParameters, SecretKey secretKey, String charset) throws Exception {
Base64 decoder = new Base64();
byte decodedEncryptedText[] = decoder.decode(encryptedText.getBytes(charset));
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = c1.doFinal(decodedEncryptedText);
String decryptedTextString = new String(decryptedText);
return decryptedTextString;
}
private void removeCookies(HttpServletRequest request, HttpServletResponse response) {
if(log.isDebugEnabled()) {
log.debug("removing AuthToken cookies in request: " + request.getRequestURI());
}
for(int i = 0; i < cookiePaths.length; i++) {
Cookie expired = new Cookie(COOKIE_NAME, "none");
expired.setPath(cookiePaths[i]);
expired.setMaxAge(0);
response.addCookie(expired);
}
}
public boolean processLogout(SecurityRequestWrapper request, HttpServletResponse response, URLPatternMatcher patternMatcher) throws Exception {
boolean processLogout = super.processLogout(request, response, patternMatcher);
if(processLogout) {
if(request.getSession().getAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL) != null) {
removeCookies(request, response);
request.getSession().removeAttribute(AUTH_TOKEN_COOKIE_PRINCIPAL);
}
/* indien auth token geaccepteerd is, verwijder dat cookie voor ons
* path
*/
if(Boolean.TRUE.equals(request.getSession().getAttribute(AUTHORIZED_BY_AUTH_TOKEN))) {
log.debug("processLogout(): principal was authorized by auth token cookie, removing cookie");
Cookie authToken = new Cookie(COOKIE_NAME, "none");
authToken.setPath(request.getContextPath());
authToken.setMaxAge(0);
response.addCookie(authToken);
}
}
return processLogout;
}
private void setEncryptionKey(byte[] encryptionkey) throws Exception {
secretKey = new SecretKeySpec(encryptionkey, encryptionAlgorithm);
}
} |
8391_11 | /*
* Copyright (C) 2011-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.config.services;
import java.util.*;
import javax.persistence.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.filter.Filter;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@Table(name="feature_type")
@org.hibernate.annotations.Entity(dynamicUpdate = true)
public class SimpleFeatureType {
private static final Log log = LogFactory.getLog(SimpleFeatureType.class);
public static final int MAX_FEATURES_DEFAULT = 250;
public static final int MAX_FEATURES_UNBOUNDED = -1;
@Id
private Long id;
@ManyToOne(cascade=CascadeType.PERSIST)
private FeatureSource featureSource;
private String typeName;
private String description;
private boolean writeable;
private String geometryAttribute;
@OneToMany (cascade=CascadeType.ALL, mappedBy="featureType")
private List<FeatureTypeRelation> relations = new ArrayList<FeatureTypeRelation>();
@ManyToMany(cascade=CascadeType.ALL) // Actually @OneToMany, workaround for HHH-1268
@JoinTable(inverseJoinColumns=@JoinColumn(name="attribute_descriptor"))
@OrderColumn(name="list_index")
private List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public List<AttributeDescriptor> getAttributes() {
return attributes;
}
public void setAttributes(List<AttributeDescriptor> attributes) {
this.attributes = attributes;
}
public FeatureSource getFeatureSource() {
return featureSource;
}
public void setFeatureSource(FeatureSource featureSource) {
this.featureSource = featureSource;
}
public String getGeometryAttribute() {
return geometryAttribute;
}
public void setGeometryAttribute(String geometryAttribute) {
this.geometryAttribute = geometryAttribute;
}
public boolean isWriteable() {
return writeable;
}
public void setWriteable(boolean writeable) {
this.writeable = writeable;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<FeatureTypeRelation> getRelations() {
return relations;
}
public void setRelations(List<FeatureTypeRelation> relations) {
this.relations = relations;
}
//</editor-fold>
public Object getMaxValue ( String attributeName, Filter f )throws Exception {
return featureSource.getMaxValue(this, attributeName, MAX_FEATURES_DEFAULT, f);
}
public Object getMaxValue ( String attributeName, int maxFeatures )throws Exception {
return featureSource.getMaxValue(this, attributeName, maxFeatures,null);
}
public Object getMinValue ( String attributeName, Filter f )throws Exception {
return featureSource.getMinValue(this, attributeName, MAX_FEATURES_DEFAULT, f);
}
public Object getMinValue ( String attributeName, int maxFeatures )throws Exception {
return featureSource.getMinValue(this, attributeName, maxFeatures, null);
}
public List<String> calculateUniqueValues(String attributeName) throws Exception {
return featureSource.calculateUniqueValues(this, attributeName, MAX_FEATURES_DEFAULT,null);
}
public List<String> calculateUniqueValues(String attributeName, int maxFeatures) throws Exception {
return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, null);
}
public List<String> calculateUniqueValues(String attributeName, int maxFeatures, Filter filter) throws Exception {
return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, filter);
}
public Map<String, String> getKeysValues(String key, String label, int maxFeatures) throws Exception {
return featureSource.getKeyValuePairs(this, key, label, maxFeatures);
}
public Map<String, String> getKeysValues(String key, String label) throws Exception {
return featureSource.getKeyValuePairs(this, key, label, MAX_FEATURES_DEFAULT);
}
public org.geotools.data.FeatureSource openGeoToolsFeatureSource() throws Exception {
return featureSource.openGeoToolsFeatureSource(this);
}
public org.geotools.data.FeatureSource openGeoToolsFeatureSource(int timeout) throws Exception {
return featureSource.openGeoToolsFeatureSource(this, timeout);
}
public boolean update(SimpleFeatureType update) {
if(!getTypeName().equals(update.getTypeName())) {
throw new IllegalArgumentException("Cannot update feature type with properties from feature type with different type name!");
}
description = update.description;
writeable = update.writeable;
geometryAttribute = update.geometryAttribute;
boolean changed = false;
// Retain user set aliases for attributes
// Does not work correctly for Arc* feature sources which set attribute
// title in alias... Needs other field to differentiate user set title
Map<String,String> aliasesByAttributeName = new HashMap();
for(AttributeDescriptor ad: attributes) {
if(StringUtils.isNotBlank(ad.getAlias())) {
aliasesByAttributeName.put(ad.getName(), ad.getAlias());
}
}
//loop over oude attributes
// voor iedere oude attr kijk of er een attib ib de update.attributes zit
// zo ja kijk of type gelijk is
// als type niet gelijk dan oude attr verwijderen en vervangen door nieuwe, evt met alias kopieren
// zo niet dan toevoegen nieuw attr aan oude set
// loop over nieuwe attributen om te kijken of er oude verwijderd moeten worden
// todo: Het is handiger om deze check op basis van 2 hashmaps uittevoeren
if(!attributes.equals(update.attributes)) {
changed = true;
for(int i = 0; i < attributes.size();i++){
boolean notFound = true;
for(AttributeDescriptor newAttribute: update.attributes){
if(attributes.get(i).getName().equals(newAttribute.getName())){
notFound = false;
AttributeDescriptor oldAttr = attributes.get(i);
if(Objects.equals(oldAttr.getType(), newAttribute.getType())){
// ! expression didnt work(???) so dummy if-else (else is only used)
}else{
attributes.remove(i);
attributes.add(i, newAttribute);
}
break;
}
}
if(notFound){
attributes.remove(i);
}
}
//nieuwe attributen worden hier toegevoegd aan de oude attributen lijst
for(int i = 0; i < update.attributes.size();i++){
boolean notFound = true;
for(AttributeDescriptor oldAttribute: attributes){
if(update.attributes.get(i).getName().equals(oldAttribute.getName())){
notFound = false;
break;
}
}
if(notFound){
attributes.add(update.attributes.get(i));
}
}
}
//update.attributes ID = NULL so the attributes list is getting NULL aswell
//if(!attributes.equals(update.attributes)) {
//attributes.clear();
//attributes.addAll(update.attributes);
//changed = true;
//}
for(AttributeDescriptor ad: attributes) {
String alias = aliasesByAttributeName.get(ad.getName());
if(alias != null) {
ad.setAlias(alias);
}
}
return changed;
}
public static void clearReferences(Collection<SimpleFeatureType> typesToRemove) {
// Clear references
int removed = Stripersist.getEntityManager().createQuery("update Layer set featureType = null where featureType in (:types)")
.setParameter("types", typesToRemove)
.executeUpdate();
if(removed > 0) {
log.warn("Cleared " + removed + " references to " + typesToRemove.size() + " type names which are to be removed");
}
// Ignore Layar references
}
public AttributeDescriptor getAttribute(String attributeName) {
for(AttributeDescriptor ad: attributes) {
if(ad.getName().equals(attributeName)) {
return ad;
}
}
return null;
}
public JSONObject toJSONObject() throws JSONException {
JSONObject o = new JSONObject();
o.put("id", id);
o.put("typeName", typeName);
o.put("writeable", writeable);
o.put("geometryAttribute", geometryAttribute);
JSONArray atts = new JSONArray();
o.put("attributes", atts);
for(AttributeDescriptor a: attributes) {
JSONObject ja = new JSONObject();
ja.put("id", a.getId());
ja.put("name", a.getName());
ja.put("alias", a.getAlias());
ja.put("type", a.getType());
atts.put(ja);
}
return o;
}
public boolean hasRelations() {
return this.relations!=null && this.relations.size()>0;
}
}
| B3Partners/tailormap | viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/SimpleFeatureType.java | 2,881 | // zo niet dan toevoegen nieuw attr aan oude set | line_comment | nl | /*
* Copyright (C) 2011-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.config.services;
import java.util.*;
import javax.persistence.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.filter.Filter;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@Table(name="feature_type")
@org.hibernate.annotations.Entity(dynamicUpdate = true)
public class SimpleFeatureType {
private static final Log log = LogFactory.getLog(SimpleFeatureType.class);
public static final int MAX_FEATURES_DEFAULT = 250;
public static final int MAX_FEATURES_UNBOUNDED = -1;
@Id
private Long id;
@ManyToOne(cascade=CascadeType.PERSIST)
private FeatureSource featureSource;
private String typeName;
private String description;
private boolean writeable;
private String geometryAttribute;
@OneToMany (cascade=CascadeType.ALL, mappedBy="featureType")
private List<FeatureTypeRelation> relations = new ArrayList<FeatureTypeRelation>();
@ManyToMany(cascade=CascadeType.ALL) // Actually @OneToMany, workaround for HHH-1268
@JoinTable(inverseJoinColumns=@JoinColumn(name="attribute_descriptor"))
@OrderColumn(name="list_index")
private List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public List<AttributeDescriptor> getAttributes() {
return attributes;
}
public void setAttributes(List<AttributeDescriptor> attributes) {
this.attributes = attributes;
}
public FeatureSource getFeatureSource() {
return featureSource;
}
public void setFeatureSource(FeatureSource featureSource) {
this.featureSource = featureSource;
}
public String getGeometryAttribute() {
return geometryAttribute;
}
public void setGeometryAttribute(String geometryAttribute) {
this.geometryAttribute = geometryAttribute;
}
public boolean isWriteable() {
return writeable;
}
public void setWriteable(boolean writeable) {
this.writeable = writeable;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<FeatureTypeRelation> getRelations() {
return relations;
}
public void setRelations(List<FeatureTypeRelation> relations) {
this.relations = relations;
}
//</editor-fold>
public Object getMaxValue ( String attributeName, Filter f )throws Exception {
return featureSource.getMaxValue(this, attributeName, MAX_FEATURES_DEFAULT, f);
}
public Object getMaxValue ( String attributeName, int maxFeatures )throws Exception {
return featureSource.getMaxValue(this, attributeName, maxFeatures,null);
}
public Object getMinValue ( String attributeName, Filter f )throws Exception {
return featureSource.getMinValue(this, attributeName, MAX_FEATURES_DEFAULT, f);
}
public Object getMinValue ( String attributeName, int maxFeatures )throws Exception {
return featureSource.getMinValue(this, attributeName, maxFeatures, null);
}
public List<String> calculateUniqueValues(String attributeName) throws Exception {
return featureSource.calculateUniqueValues(this, attributeName, MAX_FEATURES_DEFAULT,null);
}
public List<String> calculateUniqueValues(String attributeName, int maxFeatures) throws Exception {
return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, null);
}
public List<String> calculateUniqueValues(String attributeName, int maxFeatures, Filter filter) throws Exception {
return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, filter);
}
public Map<String, String> getKeysValues(String key, String label, int maxFeatures) throws Exception {
return featureSource.getKeyValuePairs(this, key, label, maxFeatures);
}
public Map<String, String> getKeysValues(String key, String label) throws Exception {
return featureSource.getKeyValuePairs(this, key, label, MAX_FEATURES_DEFAULT);
}
public org.geotools.data.FeatureSource openGeoToolsFeatureSource() throws Exception {
return featureSource.openGeoToolsFeatureSource(this);
}
public org.geotools.data.FeatureSource openGeoToolsFeatureSource(int timeout) throws Exception {
return featureSource.openGeoToolsFeatureSource(this, timeout);
}
public boolean update(SimpleFeatureType update) {
if(!getTypeName().equals(update.getTypeName())) {
throw new IllegalArgumentException("Cannot update feature type with properties from feature type with different type name!");
}
description = update.description;
writeable = update.writeable;
geometryAttribute = update.geometryAttribute;
boolean changed = false;
// Retain user set aliases for attributes
// Does not work correctly for Arc* feature sources which set attribute
// title in alias... Needs other field to differentiate user set title
Map<String,String> aliasesByAttributeName = new HashMap();
for(AttributeDescriptor ad: attributes) {
if(StringUtils.isNotBlank(ad.getAlias())) {
aliasesByAttributeName.put(ad.getName(), ad.getAlias());
}
}
//loop over oude attributes
// voor iedere oude attr kijk of er een attib ib de update.attributes zit
// zo ja kijk of type gelijk is
// als type niet gelijk dan oude attr verwijderen en vervangen door nieuwe, evt met alias kopieren
// zo niet<SUF>
// loop over nieuwe attributen om te kijken of er oude verwijderd moeten worden
// todo: Het is handiger om deze check op basis van 2 hashmaps uittevoeren
if(!attributes.equals(update.attributes)) {
changed = true;
for(int i = 0; i < attributes.size();i++){
boolean notFound = true;
for(AttributeDescriptor newAttribute: update.attributes){
if(attributes.get(i).getName().equals(newAttribute.getName())){
notFound = false;
AttributeDescriptor oldAttr = attributes.get(i);
if(Objects.equals(oldAttr.getType(), newAttribute.getType())){
// ! expression didnt work(???) so dummy if-else (else is only used)
}else{
attributes.remove(i);
attributes.add(i, newAttribute);
}
break;
}
}
if(notFound){
attributes.remove(i);
}
}
//nieuwe attributen worden hier toegevoegd aan de oude attributen lijst
for(int i = 0; i < update.attributes.size();i++){
boolean notFound = true;
for(AttributeDescriptor oldAttribute: attributes){
if(update.attributes.get(i).getName().equals(oldAttribute.getName())){
notFound = false;
break;
}
}
if(notFound){
attributes.add(update.attributes.get(i));
}
}
}
//update.attributes ID = NULL so the attributes list is getting NULL aswell
//if(!attributes.equals(update.attributes)) {
//attributes.clear();
//attributes.addAll(update.attributes);
//changed = true;
//}
for(AttributeDescriptor ad: attributes) {
String alias = aliasesByAttributeName.get(ad.getName());
if(alias != null) {
ad.setAlias(alias);
}
}
return changed;
}
public static void clearReferences(Collection<SimpleFeatureType> typesToRemove) {
// Clear references
int removed = Stripersist.getEntityManager().createQuery("update Layer set featureType = null where featureType in (:types)")
.setParameter("types", typesToRemove)
.executeUpdate();
if(removed > 0) {
log.warn("Cleared " + removed + " references to " + typesToRemove.size() + " type names which are to be removed");
}
// Ignore Layar references
}
public AttributeDescriptor getAttribute(String attributeName) {
for(AttributeDescriptor ad: attributes) {
if(ad.getName().equals(attributeName)) {
return ad;
}
}
return null;
}
public JSONObject toJSONObject() throws JSONException {
JSONObject o = new JSONObject();
o.put("id", id);
o.put("typeName", typeName);
o.put("writeable", writeable);
o.put("geometryAttribute", geometryAttribute);
JSONArray atts = new JSONArray();
o.put("attributes", atts);
for(AttributeDescriptor a: attributes) {
JSONObject ja = new JSONObject();
ja.put("id", a.getId());
ja.put("name", a.getName());
ja.put("alias", a.getAlias());
ja.put("type", a.getType());
atts.put(ja);
}
return o;
}
public boolean hasRelations() {
return this.relations!=null && this.relations.size()>0;
}
}
|
187737_5 | /*
* Copyright (C) 2012-2016 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.tailormap.viewer.admin.stripes;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import nl.tailormap.viewer.config.CRS;
import nl.tailormap.viewer.config.ClobElement;
import nl.tailormap.viewer.config.app.Application;
import nl.tailormap.viewer.config.app.Level;
import nl.tailormap.viewer.config.security.Group;
import nl.tailormap.viewer.config.security.User;
import nl.tailormap.viewer.config.services.BoundingBox;
import nl.tailormap.viewer.config.services.CoordinateReferenceSystem;
import nl.tailormap.viewer.helpers.app.ApplicationHelper;
import nl.tailormap.viewer.util.SelectedContentCache;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.stripesstuff.stripersist.Stripersist;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Jytte Schaeffer
*/
@UrlBinding("/action/applicationsettings/")
@StrictBinding
@RolesAllowed({Group.ADMIN,Group.APPLICATION_ADMIN})
public class ApplicationSettingsActionBean extends ApplicationActionBean {
private static final Log log = LogFactory.getLog(ApplicationSettingsActionBean.class);
private static final String JSP = "/WEB-INF/jsp/application/applicationSettings.jsp";
private static final String DEFAULT_SPRITE = "/viewer/viewer-html/sprite.svg";
private static final String LANGUAGE_CODES_KEY = "tailormap.i18n.languagecodes";
public static final String PROJECTION_NAMES_KEY = "tailormap.projections.epsgnames";
public static final String PROJECTION_CODES_KEY = "tailormap.projections.epsgcodes";
@Validate
private String name;
@Validate
private String version;
@Validate
private String title;
@Validate
private String language;
@Validate
private String owner;
@Validate
private boolean authenticatedRequired;
@Validate
private boolean mashupMustPointToPublishedVersion = false;
@Validate
private String mashupName;
@Validate
private boolean mustUpdateComponents;
@Validate
private Map<String,ClobElement> details = new HashMap<>();
private String[] languageCodes;
private List<CRS> crses;
@Validate
private String projection;
@ValidateNestedProperties({
@Validate(field="minx", maxlength=255),
@Validate(field="miny", maxlength=255),
@Validate(field="maxx", maxlength=255),
@Validate(field="maxy", maxlength=255)
})
private BoundingBox startExtent;
@ValidateNestedProperties({
@Validate(field="minx", maxlength=255),
@Validate(field="miny", maxlength=255),
@Validate(field="maxx", maxlength=255),
@Validate(field="maxy", maxlength=255)
})
private BoundingBox maxExtent;
@Validate
private List<String> groupsRead = new ArrayList<>();
//<editor-fold defaultstate="collapsed" desc="getters & setters">
public Map<String,ClobElement> getDetails() {
return details;
}
public void setDetails(Map<String, ClobElement> details) {
this.details = details;
}
public boolean getAuthenticatedRequired() {
return authenticatedRequired;
}
public void setAuthenticatedRequired(boolean authenticatedRequired) {
this.authenticatedRequired = authenticatedRequired;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getLanguage() { return language; }
public void setLanguage(String language) { this.language = language; }
public BoundingBox getStartExtent() {
return startExtent;
}
public void setStartExtent(BoundingBox startExtent) {
this.startExtent = startExtent;
}
public BoundingBox getMaxExtent() {
return maxExtent;
}
public void setMaxExtent(BoundingBox maxExtent) {
this.maxExtent = maxExtent;
}
public String getMashupName() {
return mashupName;
}
public void setMashupName(String mashupName) {
this.mashupName = mashupName;
}
public boolean isMashupMustPointToPublishedVersion() {
return mashupMustPointToPublishedVersion;
}
public void setMashupMustPointToPublishedVersion(boolean mashupMustPointToPublishedVersion) {
this.mashupMustPointToPublishedVersion = mashupMustPointToPublishedVersion;
}
public boolean isMustUpdateComponents() {
return mustUpdateComponents;
}
public void setMustUpdateComponents(boolean mustUpdateComponents) {
this.mustUpdateComponents = mustUpdateComponents;
}
public List<String> getGroupsRead() {
return groupsRead;
}
public void setGroupsRead(List<String> groupsRead) {
this.groupsRead = groupsRead;
}
public String[] getLanguageCodes() { return languageCodes; }
public void setLanguageCodes(String[] languageCodes) { this.languageCodes = languageCodes; }
public List<CRS> getCrses() {
return crses;
}
public void setCrses(List<CRS> crses) {
this.crses = crses;
}
public String getProjection() {
return projection;
}
public void setProjection(String projection) {
this.projection = projection;
}
//</editor-fold>
@DefaultHandler
@DontValidate
public Resolution view(){
if(application != null){
details = application.getDetails();
if(application.getOwner() != null){
owner = application.getOwner().getUsername();
}
startExtent = application.getStartExtent();
maxExtent = application.getMaxExtent();
name = application.getName();
title = application.getTitle();
language = application.getLang();
version = application.getVersion();
authenticatedRequired = application.isAuthenticatedRequired();
groupsRead.addAll (application.getReaders());
projection = application.getProjectionCode();
}
// DEFAULT VALUES
if(!details.containsKey("iconSprite")) {
details.put("iconSprite", new ClobElement(DEFAULT_SPRITE));
}
if(!details.containsKey("stylesheetMetadata")) {
// TODO: Default value stylesheet metadata
details.put("stylesheetMetadata", new ClobElement(""));
}
if(!details.containsKey("stylesheetPrint")) {
// TODO: Default value stylesheet printen
details.put("stylesheetPrint", new ClobElement(""));
}
String languageCodesString = context.getServletContext().getInitParameter(LANGUAGE_CODES_KEY);
languageCodes = StringUtils.stripAll(languageCodesString.split(","));
String codesString = context.getServletContext().getInitParameter(PROJECTION_CODES_KEY);
String namesString = context.getServletContext().getInitParameter(PROJECTION_NAMES_KEY);
String[] codes = codesString.split(";");
String[] names = namesString.split(",");
crses = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
CRS c = new CRS(names[i], codes[i]);
crses.add(c);
}
if(projection == null && !crses.isEmpty()){
projection = crses.get(0).getCode();
}
return new ForwardResolution(JSP);
}
@DontValidate
public Resolution newApplication(){
application = null;
applicationId = -1L;
// DEFAULT VALUES
details.put("iconSprite", new ClobElement(DEFAULT_SPRITE));
// TODO: Default value stylesheet metadata
details.put("stylesheetMetadata", new ClobElement(""));
// TODO: Default value stylesheet printen
details.put("stylesheetPrint", new ClobElement(""));
return view();
}
@DontBind
public Resolution cancel() {
return new ForwardResolution(JSP);
}
public Resolution save() {
if(application == null){
application = new Application();
/*
* A new application always has a root and a background level.
*/
Level root = new Level();
root.setName(getBundle().getString("viewer_admin.applicationsettingsbean.applabel"));
Level background = new Level();
background.setName(getBundle().getString("viewer_admin.applicationsettingsbean.background"));
background.setBackground(true);
root.getChildren().add(background);
background.setParent(root);
Stripersist.getEntityManager().persist(background);
Stripersist.getEntityManager().persist(root);
application.setRoot(root);
}
bindAppProperties();
Stripersist.getEntityManager().persist(application);
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage(getBundle().getString("viewer_admin.applicationsettingsbean.appsaved")));
setApplication(application);
return view();
}
/* XXX */
private void bindAppProperties() {
application.setName(name);
application.setVersion(version);
application.setTitle(title);
application.setLang(language);
if (owner != null) {
User appOwner = Stripersist.getEntityManager().find(User.class, owner);
application.setOwner(appOwner);
}
application.setStartExtent(startExtent);
application.setMaxExtent(maxExtent);
application.setAuthenticatedRequired(authenticatedRequired);
application.getReaders().clear();
for (String group : groupsRead) {
application.getReaders().add(group);
}
application.authorizationsModified();
application.setProjectionCode(projection);
for (Map.Entry<String, ClobElement> e : application.getDetails().entrySet()) {
if (Application.preventClearDetails.contains(e.getKey())) {
details.put(e.getKey(), e.getValue());
}
}
application.getDetails().clear();
application.getDetails().putAll(details);
}
@ValidationMethod(on="save")
public void validate(ValidationErrors errors) throws Exception {
if(name == null) {
errors.add("name", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.noname")));
return;
}
try {
Long foundId;
if(version == null){
foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version is null")
.setMaxResults(1)
.setParameter("name", name)
.getSingleResult();
}else{
foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version = :version")
.setMaxResults(1)
.setParameter("name", name)
.setParameter("version", version)
.getSingleResult();
}
if(application != null && application.getId() != null){
if( !foundId.equals(application.getId()) ){
errors.add("name", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.appnotfound")));
}
}else{
errors.add("name", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.appnotfound")));
}
} catch(NoResultException nre) {
// name version combination is unique
}
/*
* Check if owner is an existing user.
*/
if(owner != null){
try {
User appOwner = Stripersist.getEntityManager().find(User.class, owner);
if(appOwner == null){
errors.add("owner", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nouser")));
}
} catch(NoResultException nre) {
errors.add("owner", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nouser")));
}
}
if(startExtent != null){
if(startExtent.getMinx() == null || startExtent.getMiny() == null || startExtent.getMaxx() == null || startExtent.getMaxy() == null ){
errors.add("startExtent", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nostartext")));
}
// force application CRS on startExtent
if (null == startExtent.getCrs())
startExtent.setCrs(new CoordinateReferenceSystem(projection.substring(0, projection.indexOf('['))));
}
if(maxExtent != null){
if(maxExtent.getMinx() == null || maxExtent.getMiny() == null || maxExtent.getMaxx() == null || maxExtent.getMaxy() == null ){
errors.add("maxExtent", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nomaxext")));
}
// force application CRS on maxExtent
if (null == maxExtent.getCrs())
maxExtent.setCrs(new CoordinateReferenceSystem(projection.substring(0, projection.indexOf('['))));
}
}
public Resolution copy() throws Exception {
EntityManager em = Stripersist.getEntityManager();
try {
Object o = em.createQuery("select 1 from Application where name = :name")
.setMaxResults(1)
.setParameter("name", name)
.getSingleResult();
getContext().getMessages().add(new SimpleMessage(getBundle().getString("viewer_admin.applicationsettingsbean.copyexists"), name));
return new RedirectResolution(this.getClass());
} catch(NoResultException nre) {
// name is unique
}
try {
copyApplication(em);
getContext().getMessages().add(new SimpleMessage(getBundle().getString("viewer_admin.applicationsettingsbean.appcopied")));
return new RedirectResolution(this.getClass());
} catch(Exception e) {
log.error(String.format("Error copying application #%d named %s %swith new name %s",
application.getId(),
application.getName(),
application.getVersion() == null ? "" : "v" + application.getVersion() + " ",
name), e);
StringBuilder ex = new StringBuilder(e.toString());
Throwable cause = e.getCause();
while(cause != null) {
ex.append(";\n<br>").append(cause);
cause = cause.getCause();
}
getContext().getValidationErrors().addGlobalError(new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.copyerror"), ex.toString()));
return new ForwardResolution(JSP);
}
}
protected void copyApplication(EntityManager em) throws Exception {
Application copy = null;
// When the selected application is a mashup, don't use the copy routine, but make another mashup of it. This prevents some detached entity exceptions.
if(application.isMashup()){
copy = ApplicationHelper.createMashup(application, name, em, false);
// SelectedContentCache.setApplicationCacheDirty(copy, Boolean.TRUE, true, em);
}else{
bindAppProperties();
copy = ApplicationHelper.deepCopy(application);
// don't save changes to original app
em.detach(application);
em.persist(copy);
em.persist(copy);
em.flush();
// SelectedContentCache.setApplicationCacheDirty(copy, Boolean.TRUE, false, em);
}
em.getTransaction().commit();
setApplication(copy);
}
public Resolution mashup(){
ValidationErrors errors = context.getValidationErrors();
try {
EntityManager em = Stripersist.getEntityManager();
Application mashup = ApplicationHelper.createMashup(application, mashupName, em,mustUpdateComponents);
em.persist(mashup);
em.getTransaction().commit();
setApplication(mashup);
} catch (Exception ex) {
log.error("Error creating mashup",ex);
errors.add("Fout", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nomashup")));
}
return new RedirectResolution(ApplicationSettingsActionBean.class);
}
public Resolution publish (){
// Find current published application and make backup
EntityManager em = Stripersist.getEntityManager();
publish(em);
return new RedirectResolution(ChooseApplicationActionBean.class);
}
protected void publish(EntityManager em){
try {
Application oldPublished = (Application)em.createQuery("from Application where name = :name AND version IS null")
.setMaxResults(1)
.setParameter("name", name)
.getSingleResult();
Date nowDate = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
sdf.applyPattern("HH-mm_dd-MM-yyyy");
String now = sdf.format(nowDate);
String uniqueVersion = findUniqueVersion(name, "B_"+now , em);
oldPublished.setVersion(uniqueVersion);
em.persist(oldPublished);
if(mashupMustPointToPublishedVersion){
for (Application mashup: ApplicationHelper.getMashups(oldPublished, em)) {
mashup.setRoot(application.getRoot());//nog iets doen met veranderde layerids uit cofniguratie
// SelectedContentCache.setApplicationCacheDirty(mashup,true, false,em);
ApplicationHelper.transferMashupLevels(mashup, oldPublished,em);
ApplicationHelper.transferMashupComponents(mashup, application);
em.persist(mashup);
}
}
} catch (NoResultException nre) {
}
application.setVersion(null);
em.persist(application);
em.getTransaction().commit();
setApplication(null);
}
/**
* Checks if a Application with given name already exists and if needed
* returns name with sequence number in brackets added to make it unique.
*
* @param name Name to make unique
* @param version version to check
*
* @return A unique name for a FeatureSource
*/
public static String findUniqueVersion(String name, String version, EntityManager em) {
int uniqueCounter = 0;
while(true) {
String testVersion;
if(uniqueCounter == 0) {
testVersion = version;
} else {
testVersion = version + " (" + uniqueCounter + ")";
}
try {
em.createQuery("select 1 from Application where name = :name AND version = :version")
.setParameter("name", name)
.setParameter("version", testVersion)
.setMaxResults(1)
.getSingleResult();
uniqueCounter++;
} catch(NoResultException nre) {
version = testVersion;
break;
}
}
return version;
}
public Resolution applicationDetails() throws JSONException {
return new ForwardResolution("/WEB-INF/jsp/application/applicationDetails.jsp");
}
}
| B3Partners/tailormap-admin | src/main/java/nl/tailormap/viewer/admin/stripes/ApplicationSettingsActionBean.java | 5,977 | // TODO: Default value stylesheet metadata | line_comment | nl | /*
* Copyright (C) 2012-2016 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.tailormap.viewer.admin.stripes;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import nl.tailormap.viewer.config.CRS;
import nl.tailormap.viewer.config.ClobElement;
import nl.tailormap.viewer.config.app.Application;
import nl.tailormap.viewer.config.app.Level;
import nl.tailormap.viewer.config.security.Group;
import nl.tailormap.viewer.config.security.User;
import nl.tailormap.viewer.config.services.BoundingBox;
import nl.tailormap.viewer.config.services.CoordinateReferenceSystem;
import nl.tailormap.viewer.helpers.app.ApplicationHelper;
import nl.tailormap.viewer.util.SelectedContentCache;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.stripesstuff.stripersist.Stripersist;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Jytte Schaeffer
*/
@UrlBinding("/action/applicationsettings/")
@StrictBinding
@RolesAllowed({Group.ADMIN,Group.APPLICATION_ADMIN})
public class ApplicationSettingsActionBean extends ApplicationActionBean {
private static final Log log = LogFactory.getLog(ApplicationSettingsActionBean.class);
private static final String JSP = "/WEB-INF/jsp/application/applicationSettings.jsp";
private static final String DEFAULT_SPRITE = "/viewer/viewer-html/sprite.svg";
private static final String LANGUAGE_CODES_KEY = "tailormap.i18n.languagecodes";
public static final String PROJECTION_NAMES_KEY = "tailormap.projections.epsgnames";
public static final String PROJECTION_CODES_KEY = "tailormap.projections.epsgcodes";
@Validate
private String name;
@Validate
private String version;
@Validate
private String title;
@Validate
private String language;
@Validate
private String owner;
@Validate
private boolean authenticatedRequired;
@Validate
private boolean mashupMustPointToPublishedVersion = false;
@Validate
private String mashupName;
@Validate
private boolean mustUpdateComponents;
@Validate
private Map<String,ClobElement> details = new HashMap<>();
private String[] languageCodes;
private List<CRS> crses;
@Validate
private String projection;
@ValidateNestedProperties({
@Validate(field="minx", maxlength=255),
@Validate(field="miny", maxlength=255),
@Validate(field="maxx", maxlength=255),
@Validate(field="maxy", maxlength=255)
})
private BoundingBox startExtent;
@ValidateNestedProperties({
@Validate(field="minx", maxlength=255),
@Validate(field="miny", maxlength=255),
@Validate(field="maxx", maxlength=255),
@Validate(field="maxy", maxlength=255)
})
private BoundingBox maxExtent;
@Validate
private List<String> groupsRead = new ArrayList<>();
//<editor-fold defaultstate="collapsed" desc="getters & setters">
public Map<String,ClobElement> getDetails() {
return details;
}
public void setDetails(Map<String, ClobElement> details) {
this.details = details;
}
public boolean getAuthenticatedRequired() {
return authenticatedRequired;
}
public void setAuthenticatedRequired(boolean authenticatedRequired) {
this.authenticatedRequired = authenticatedRequired;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getLanguage() { return language; }
public void setLanguage(String language) { this.language = language; }
public BoundingBox getStartExtent() {
return startExtent;
}
public void setStartExtent(BoundingBox startExtent) {
this.startExtent = startExtent;
}
public BoundingBox getMaxExtent() {
return maxExtent;
}
public void setMaxExtent(BoundingBox maxExtent) {
this.maxExtent = maxExtent;
}
public String getMashupName() {
return mashupName;
}
public void setMashupName(String mashupName) {
this.mashupName = mashupName;
}
public boolean isMashupMustPointToPublishedVersion() {
return mashupMustPointToPublishedVersion;
}
public void setMashupMustPointToPublishedVersion(boolean mashupMustPointToPublishedVersion) {
this.mashupMustPointToPublishedVersion = mashupMustPointToPublishedVersion;
}
public boolean isMustUpdateComponents() {
return mustUpdateComponents;
}
public void setMustUpdateComponents(boolean mustUpdateComponents) {
this.mustUpdateComponents = mustUpdateComponents;
}
public List<String> getGroupsRead() {
return groupsRead;
}
public void setGroupsRead(List<String> groupsRead) {
this.groupsRead = groupsRead;
}
public String[] getLanguageCodes() { return languageCodes; }
public void setLanguageCodes(String[] languageCodes) { this.languageCodes = languageCodes; }
public List<CRS> getCrses() {
return crses;
}
public void setCrses(List<CRS> crses) {
this.crses = crses;
}
public String getProjection() {
return projection;
}
public void setProjection(String projection) {
this.projection = projection;
}
//</editor-fold>
@DefaultHandler
@DontValidate
public Resolution view(){
if(application != null){
details = application.getDetails();
if(application.getOwner() != null){
owner = application.getOwner().getUsername();
}
startExtent = application.getStartExtent();
maxExtent = application.getMaxExtent();
name = application.getName();
title = application.getTitle();
language = application.getLang();
version = application.getVersion();
authenticatedRequired = application.isAuthenticatedRequired();
groupsRead.addAll (application.getReaders());
projection = application.getProjectionCode();
}
// DEFAULT VALUES
if(!details.containsKey("iconSprite")) {
details.put("iconSprite", new ClobElement(DEFAULT_SPRITE));
}
if(!details.containsKey("stylesheetMetadata")) {
// TODO: Default value stylesheet metadata
details.put("stylesheetMetadata", new ClobElement(""));
}
if(!details.containsKey("stylesheetPrint")) {
// TODO: Default value stylesheet printen
details.put("stylesheetPrint", new ClobElement(""));
}
String languageCodesString = context.getServletContext().getInitParameter(LANGUAGE_CODES_KEY);
languageCodes = StringUtils.stripAll(languageCodesString.split(","));
String codesString = context.getServletContext().getInitParameter(PROJECTION_CODES_KEY);
String namesString = context.getServletContext().getInitParameter(PROJECTION_NAMES_KEY);
String[] codes = codesString.split(";");
String[] names = namesString.split(",");
crses = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
CRS c = new CRS(names[i], codes[i]);
crses.add(c);
}
if(projection == null && !crses.isEmpty()){
projection = crses.get(0).getCode();
}
return new ForwardResolution(JSP);
}
@DontValidate
public Resolution newApplication(){
application = null;
applicationId = -1L;
// DEFAULT VALUES
details.put("iconSprite", new ClobElement(DEFAULT_SPRITE));
// TODO: Default<SUF>
details.put("stylesheetMetadata", new ClobElement(""));
// TODO: Default value stylesheet printen
details.put("stylesheetPrint", new ClobElement(""));
return view();
}
@DontBind
public Resolution cancel() {
return new ForwardResolution(JSP);
}
public Resolution save() {
if(application == null){
application = new Application();
/*
* A new application always has a root and a background level.
*/
Level root = new Level();
root.setName(getBundle().getString("viewer_admin.applicationsettingsbean.applabel"));
Level background = new Level();
background.setName(getBundle().getString("viewer_admin.applicationsettingsbean.background"));
background.setBackground(true);
root.getChildren().add(background);
background.setParent(root);
Stripersist.getEntityManager().persist(background);
Stripersist.getEntityManager().persist(root);
application.setRoot(root);
}
bindAppProperties();
Stripersist.getEntityManager().persist(application);
Stripersist.getEntityManager().getTransaction().commit();
getContext().getMessages().add(new SimpleMessage(getBundle().getString("viewer_admin.applicationsettingsbean.appsaved")));
setApplication(application);
return view();
}
/* XXX */
private void bindAppProperties() {
application.setName(name);
application.setVersion(version);
application.setTitle(title);
application.setLang(language);
if (owner != null) {
User appOwner = Stripersist.getEntityManager().find(User.class, owner);
application.setOwner(appOwner);
}
application.setStartExtent(startExtent);
application.setMaxExtent(maxExtent);
application.setAuthenticatedRequired(authenticatedRequired);
application.getReaders().clear();
for (String group : groupsRead) {
application.getReaders().add(group);
}
application.authorizationsModified();
application.setProjectionCode(projection);
for (Map.Entry<String, ClobElement> e : application.getDetails().entrySet()) {
if (Application.preventClearDetails.contains(e.getKey())) {
details.put(e.getKey(), e.getValue());
}
}
application.getDetails().clear();
application.getDetails().putAll(details);
}
@ValidationMethod(on="save")
public void validate(ValidationErrors errors) throws Exception {
if(name == null) {
errors.add("name", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.noname")));
return;
}
try {
Long foundId;
if(version == null){
foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version is null")
.setMaxResults(1)
.setParameter("name", name)
.getSingleResult();
}else{
foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version = :version")
.setMaxResults(1)
.setParameter("name", name)
.setParameter("version", version)
.getSingleResult();
}
if(application != null && application.getId() != null){
if( !foundId.equals(application.getId()) ){
errors.add("name", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.appnotfound")));
}
}else{
errors.add("name", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.appnotfound")));
}
} catch(NoResultException nre) {
// name version combination is unique
}
/*
* Check if owner is an existing user.
*/
if(owner != null){
try {
User appOwner = Stripersist.getEntityManager().find(User.class, owner);
if(appOwner == null){
errors.add("owner", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nouser")));
}
} catch(NoResultException nre) {
errors.add("owner", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nouser")));
}
}
if(startExtent != null){
if(startExtent.getMinx() == null || startExtent.getMiny() == null || startExtent.getMaxx() == null || startExtent.getMaxy() == null ){
errors.add("startExtent", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nostartext")));
}
// force application CRS on startExtent
if (null == startExtent.getCrs())
startExtent.setCrs(new CoordinateReferenceSystem(projection.substring(0, projection.indexOf('['))));
}
if(maxExtent != null){
if(maxExtent.getMinx() == null || maxExtent.getMiny() == null || maxExtent.getMaxx() == null || maxExtent.getMaxy() == null ){
errors.add("maxExtent", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nomaxext")));
}
// force application CRS on maxExtent
if (null == maxExtent.getCrs())
maxExtent.setCrs(new CoordinateReferenceSystem(projection.substring(0, projection.indexOf('['))));
}
}
public Resolution copy() throws Exception {
EntityManager em = Stripersist.getEntityManager();
try {
Object o = em.createQuery("select 1 from Application where name = :name")
.setMaxResults(1)
.setParameter("name", name)
.getSingleResult();
getContext().getMessages().add(new SimpleMessage(getBundle().getString("viewer_admin.applicationsettingsbean.copyexists"), name));
return new RedirectResolution(this.getClass());
} catch(NoResultException nre) {
// name is unique
}
try {
copyApplication(em);
getContext().getMessages().add(new SimpleMessage(getBundle().getString("viewer_admin.applicationsettingsbean.appcopied")));
return new RedirectResolution(this.getClass());
} catch(Exception e) {
log.error(String.format("Error copying application #%d named %s %swith new name %s",
application.getId(),
application.getName(),
application.getVersion() == null ? "" : "v" + application.getVersion() + " ",
name), e);
StringBuilder ex = new StringBuilder(e.toString());
Throwable cause = e.getCause();
while(cause != null) {
ex.append(";\n<br>").append(cause);
cause = cause.getCause();
}
getContext().getValidationErrors().addGlobalError(new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.copyerror"), ex.toString()));
return new ForwardResolution(JSP);
}
}
protected void copyApplication(EntityManager em) throws Exception {
Application copy = null;
// When the selected application is a mashup, don't use the copy routine, but make another mashup of it. This prevents some detached entity exceptions.
if(application.isMashup()){
copy = ApplicationHelper.createMashup(application, name, em, false);
// SelectedContentCache.setApplicationCacheDirty(copy, Boolean.TRUE, true, em);
}else{
bindAppProperties();
copy = ApplicationHelper.deepCopy(application);
// don't save changes to original app
em.detach(application);
em.persist(copy);
em.persist(copy);
em.flush();
// SelectedContentCache.setApplicationCacheDirty(copy, Boolean.TRUE, false, em);
}
em.getTransaction().commit();
setApplication(copy);
}
public Resolution mashup(){
ValidationErrors errors = context.getValidationErrors();
try {
EntityManager em = Stripersist.getEntityManager();
Application mashup = ApplicationHelper.createMashup(application, mashupName, em,mustUpdateComponents);
em.persist(mashup);
em.getTransaction().commit();
setApplication(mashup);
} catch (Exception ex) {
log.error("Error creating mashup",ex);
errors.add("Fout", new SimpleError(getBundle().getString("viewer_admin.applicationsettingsbean.nomashup")));
}
return new RedirectResolution(ApplicationSettingsActionBean.class);
}
public Resolution publish (){
// Find current published application and make backup
EntityManager em = Stripersist.getEntityManager();
publish(em);
return new RedirectResolution(ChooseApplicationActionBean.class);
}
protected void publish(EntityManager em){
try {
Application oldPublished = (Application)em.createQuery("from Application where name = :name AND version IS null")
.setMaxResults(1)
.setParameter("name", name)
.getSingleResult();
Date nowDate = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
sdf.applyPattern("HH-mm_dd-MM-yyyy");
String now = sdf.format(nowDate);
String uniqueVersion = findUniqueVersion(name, "B_"+now , em);
oldPublished.setVersion(uniqueVersion);
em.persist(oldPublished);
if(mashupMustPointToPublishedVersion){
for (Application mashup: ApplicationHelper.getMashups(oldPublished, em)) {
mashup.setRoot(application.getRoot());//nog iets doen met veranderde layerids uit cofniguratie
// SelectedContentCache.setApplicationCacheDirty(mashup,true, false,em);
ApplicationHelper.transferMashupLevels(mashup, oldPublished,em);
ApplicationHelper.transferMashupComponents(mashup, application);
em.persist(mashup);
}
}
} catch (NoResultException nre) {
}
application.setVersion(null);
em.persist(application);
em.getTransaction().commit();
setApplication(null);
}
/**
* Checks if a Application with given name already exists and if needed
* returns name with sequence number in brackets added to make it unique.
*
* @param name Name to make unique
* @param version version to check
*
* @return A unique name for a FeatureSource
*/
public static String findUniqueVersion(String name, String version, EntityManager em) {
int uniqueCounter = 0;
while(true) {
String testVersion;
if(uniqueCounter == 0) {
testVersion = version;
} else {
testVersion = version + " (" + uniqueCounter + ")";
}
try {
em.createQuery("select 1 from Application where name = :name AND version = :version")
.setParameter("name", name)
.setParameter("version", testVersion)
.setMaxResults(1)
.getSingleResult();
uniqueCounter++;
} catch(NoResultException nre) {
version = testVersion;
break;
}
}
return version;
}
public Resolution applicationDetails() throws JSONException {
return new ForwardResolution("/WEB-INF/jsp/application/applicationDetails.jsp");
}
}
|
138967_6 | package com.gamerzdev.serverstatsdashboard;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ServerStatsPlugin extends JavaPlugin {
private final String dashboardEndpoint = "http://localhost:3000/updateStats";
@Override
public void onEnable() {
getLogger().info("ServerStatsPlugin is enabled!");
getServer().getScheduler().runTaskTimer(this, this::updateStats, 0, 20 * 60); // Update elke minuut
}
private void updateStats() {
int onlinePlayers = getServer().getOnlinePlayers().size();
double[] tps = Bukkit.getServer().getTPS();
double cpuUsage = // Implementeer de logica om CPU-gebruik te verkrijgen
// Voeg andere statistieken toe
// Stuur statistieken naar het dashboard
sendStatsToDashboard(onlinePlayers, tps[0], cpuUsage);
}
private void sendStatsToDashboard(int onlinePlayers, double tps, double cpuUsage) {
try {
// Maak een HTTP POST-request naar het dashboard
URL url = new URL(dashboardEndpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
// Bouw de JSON-payload voor het verzoek
String jsonInputString = String.format("{\"onlinePlayers\": %d, \"tps\": %.2f, \"cpuUsage\": %.2f}", onlinePlayers, tps, cpuUsage);
// Stuur de statistieken naar het dashboard
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Ontvang het antwoord van het dashboard (je kunt dit gebruiken voor foutafhandeling)
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
getLogger().info("Stats sent successfully to the dashboard.");
} else {
getLogger().warning("Failed to send stats to the dashboard. Response code: " + responseCode);
}
} catch (Exception e) {
getLogger().warning("Error while sending stats to the dashboard: " + e.getMessage());
}
}
}
| BDStudiosGames/serverstatsdashboard | src/com/gamerzdev/serverstatsdashboard/ServerStatsPlugin.java | 711 | // Stuur de statistieken naar het dashboard
| line_comment | nl | package com.gamerzdev.serverstatsdashboard;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ServerStatsPlugin extends JavaPlugin {
private final String dashboardEndpoint = "http://localhost:3000/updateStats";
@Override
public void onEnable() {
getLogger().info("ServerStatsPlugin is enabled!");
getServer().getScheduler().runTaskTimer(this, this::updateStats, 0, 20 * 60); // Update elke minuut
}
private void updateStats() {
int onlinePlayers = getServer().getOnlinePlayers().size();
double[] tps = Bukkit.getServer().getTPS();
double cpuUsage = // Implementeer de logica om CPU-gebruik te verkrijgen
// Voeg andere statistieken toe
// Stuur statistieken naar het dashboard
sendStatsToDashboard(onlinePlayers, tps[0], cpuUsage);
}
private void sendStatsToDashboard(int onlinePlayers, double tps, double cpuUsage) {
try {
// Maak een HTTP POST-request naar het dashboard
URL url = new URL(dashboardEndpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
// Bouw de JSON-payload voor het verzoek
String jsonInputString = String.format("{\"onlinePlayers\": %d, \"tps\": %.2f, \"cpuUsage\": %.2f}", onlinePlayers, tps, cpuUsage);
// Stuur de<SUF>
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Ontvang het antwoord van het dashboard (je kunt dit gebruiken voor foutafhandeling)
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
getLogger().info("Stats sent successfully to the dashboard.");
} else {
getLogger().warning("Failed to send stats to the dashboard. Response code: " + responseCode);
}
} catch (Exception e) {
getLogger().warning("Error while sending stats to the dashboard: " + e.getMessage());
}
}
}
|
198976_2 | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"},
{"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5};
public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""};
public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""};
public static String ArchivePath = "DLLs/";
public static String LogFilePath = "./Logs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is IPBans on
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean enableLogging = false;
public static int logKeepDuration = 7;
public static boolean RunAdmin = false;
public static String BotNetBotID = "";
public static String BotNetHubPW = "";
public static String BotNetDatabase = "";
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
| BNETDocs/JBLS | util/Constants.java | 1,562 | //default is IPBans on | line_comment | nl | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"},
{"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5};
public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""};
public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""};
public static String ArchivePath = "DLLs/";
public static String LogFilePath = "./Logs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is<SUF>
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean enableLogging = false;
public static int logKeepDuration = 7;
public static boolean RunAdmin = false;
public static String BotNetBotID = "";
public static String BotNetHubPW = "";
public static String BotNetDatabase = "";
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
|
31682_3 | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.dto.gef.validation.impl;
import static nl.bro.dto.gef.validation.support.GefMessageInterpolator.createSubstitutes;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.bro.cpt.gef.dto.SpecimenVar;
import nl.bro.dto.gef.validation.support.GefMessageInterpolator.Substitutes;
import nl.bro.dto.gef.validation.SpecimenVarsValid;
public class SpecimenVarsValidator implements ConstraintValidator<SpecimenVarsValid, List<SpecimenVar>> {
private SpecimenVarsValid annotation;
@Override
public void initialize(SpecimenVarsValid constraintAnnotation) {
annotation = constraintAnnotation;
}
@Override
public boolean isValid(List<SpecimenVar> valueList, ConstraintValidatorContext context) {
if ( valueList == null || valueList.isEmpty() ) {
return true;
}
boolean valid = true;
// Wanneer de specimenvars zijn ingevuld, dan dienen de laag definities te kloppen (dwz: de onderdiepte van
// een laag moet lager zijn dan de bovendiepte). Door de manier waarop GEF de verwijderde lagen definieert
// hoeft dit alleen voor de onderste laag gecontroleerd te worden.
SpecimenVar lastLayer = valueList.get( valueList.size() - 1 );
if ( lastLayer.getOnderdiepte() != null && lastLayer.getBovendiepte() != null && lastLayer.getBovendiepte().compareTo( lastLayer.getOnderdiepte() ) > 0 ) {
valid = false;
}
if ( !valid ) {
// allways add the values, they will always be printed.
Substitutes substitutes = createSubstitutes( annotation, valueList );
substitutes.addValue( "${upperdepth}", lastLayer.getBovendiepte() );
substitutes.addValue( "${predrilledDepth}", lastLayer.getOnderdiepte() );
}
return valid;
}
}
| BROprogramma/CPT_GEF_CONVERTER | gef_impl/src/main/java/nl/bro/dto/gef/validation/impl/SpecimenVarsValidator.java | 782 | // hoeft dit alleen voor de onderste laag gecontroleerd te worden. | line_comment | nl | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.dto.gef.validation.impl;
import static nl.bro.dto.gef.validation.support.GefMessageInterpolator.createSubstitutes;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import nl.bro.cpt.gef.dto.SpecimenVar;
import nl.bro.dto.gef.validation.support.GefMessageInterpolator.Substitutes;
import nl.bro.dto.gef.validation.SpecimenVarsValid;
public class SpecimenVarsValidator implements ConstraintValidator<SpecimenVarsValid, List<SpecimenVar>> {
private SpecimenVarsValid annotation;
@Override
public void initialize(SpecimenVarsValid constraintAnnotation) {
annotation = constraintAnnotation;
}
@Override
public boolean isValid(List<SpecimenVar> valueList, ConstraintValidatorContext context) {
if ( valueList == null || valueList.isEmpty() ) {
return true;
}
boolean valid = true;
// Wanneer de specimenvars zijn ingevuld, dan dienen de laag definities te kloppen (dwz: de onderdiepte van
// een laag moet lager zijn dan de bovendiepte). Door de manier waarop GEF de verwijderde lagen definieert
// hoeft dit<SUF>
SpecimenVar lastLayer = valueList.get( valueList.size() - 1 );
if ( lastLayer.getOnderdiepte() != null && lastLayer.getBovendiepte() != null && lastLayer.getBovendiepte().compareTo( lastLayer.getOnderdiepte() ) > 0 ) {
valid = false;
}
if ( !valid ) {
// allways add the values, they will always be printed.
Substitutes substitutes = createSubstitutes( annotation, valueList );
substitutes.addValue( "${upperdepth}", lastLayer.getBovendiepte() );
substitutes.addValue( "${predrilledDepth}", lastLayer.getOnderdiepte() );
}
return valid;
}
}
|
47878_2 | package com.fsd.inventopilot.dtos;
import lombok.Data;
@Data
public class JwtAuthResponse {
private String jwt;
// Deze wordt meegestuurd voor de opdrachten meegestuurd met de response,
// zodat hij kan worden getest in postman met een dummy functie.
// In de praktijk zou ik deze token niet letterlijk declareren in objecten die worden verzonden
private String refreshToken;
}
// voor extra veiligheid kan nog gecheckt worden of er niet geknoeid is met de jwt en refreshtoken;
// zo ver wordt in de cursus echter niet ingegaan op security
//
// Verify the JWT's Signature:
// To ensure the JWT is not tampered with, you need to verify its signature using the public key
// of the issuer. The public key can be obtained from the issuer's JWKS (JSON Web Key Set) endpoint.
//
// Check the JWT's Claims:
// You should verify the standard claims (e.g., expiration time, issuer, audience)
// and any custom claims you may have added to the JWT.
//
// Check the Refresh Token:
// Verify that the refresh token is valid and not expired.
// The validation process may involve checking against a database
// or cache where valid refresh tokens are stored. | BadKarmaL33t/InventoPilot-Backend | src/main/java/com/fsd/inventopilot/dtos/JwtAuthResponse.java | 339 | // In de praktijk zou ik deze token niet letterlijk declareren in objecten die worden verzonden | line_comment | nl | package com.fsd.inventopilot.dtos;
import lombok.Data;
@Data
public class JwtAuthResponse {
private String jwt;
// Deze wordt meegestuurd voor de opdrachten meegestuurd met de response,
// zodat hij kan worden getest in postman met een dummy functie.
// In de<SUF>
private String refreshToken;
}
// voor extra veiligheid kan nog gecheckt worden of er niet geknoeid is met de jwt en refreshtoken;
// zo ver wordt in de cursus echter niet ingegaan op security
//
// Verify the JWT's Signature:
// To ensure the JWT is not tampered with, you need to verify its signature using the public key
// of the issuer. The public key can be obtained from the issuer's JWKS (JSON Web Key Set) endpoint.
//
// Check the JWT's Claims:
// You should verify the standard claims (e.g., expiration time, issuer, audience)
// and any custom claims you may have added to the JWT.
//
// Check the Refresh Token:
// Verify that the refresh token is valid and not expired.
// The validation process may involve checking against a database
// or cache where valid refresh tokens are stored. |
205155_2 | package be.pbo.jeugdcup.ranking.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Data
@Builder(toBuilder = true, builderClassName = "EventInternalBuilder", builderMethodName = "internalBuilder")
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Slf4j
public class Event {
private static final AgeCategoryDetector ageCategoryDetector = new AgeCategoryDetector();
private static final ReeksDetector reeksDetector = new ReeksDetector();
private Integer id;
private String name;
private Gender gender;
private EventType eventType;
private AgeCategory ageCategory = AgeCategory.DEFAULT_AGE_CATEGORY;
private Reeks reeks = Reeks.DEFAULT_REEKS;
private List<Round> rounds = new ArrayList<>();
private List<EliminationScheme> eliminationSchemes = new ArrayList<>();
public void init() {
ageCategory = ageCategoryDetector.resolveFromEventName(this.name);
reeks = reeksDetector.resolveFromEventName(this.name);
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends EventInternalBuilder {
Builder() {
super();
}
@Override
public Event build() {
final Event event = super.build();
event.init();
return event;
}
}
// Returns teams sorted by their results for this event
// It's possible that not all teams play in the Elimination phase.
// For example: 13 inschijvingen, dubbel/gemengd -> vierde & vijfde uit poule spelen geen eindronde
// In that case multiple teams end at the same Event-rank and should get equal points
public SortedMap<Integer, List<Team>> sortTeamsByEventResult() {
final TreeMap<Integer, List<Team>> result = new TreeMap<>();
if (rounds.isEmpty()) {
log.info("Event has no rounds:" + this);
} else if (eliminationSchemes.isEmpty() && rounds.size() == 1) {
//Geen eindrondes, enkel 1 poule
final List<Team> teamsSortedByPouleResult = rounds.get(0).getTeamsSortedByPouleResult();
for (int i = 0; i < teamsSortedByPouleResult.size(); i++) {
result.put(i + 1, Arrays.asList(teamsSortedByPouleResult.get(i)));
}
} else if (eliminationSchemes.size() > 0) {
//Sort EliminationScheme so winners scheme come in front
eliminationSchemes.sort(new EliminationSchemeComparator(this));
final AtomicInteger resultPosition = new AtomicInteger(0);
for (final EliminationScheme eliminationScheme : eliminationSchemes) {
final SortedMap<Integer, List<Team>> teamsSortedByEliminationResult = eliminationScheme.getTeamsSortedByEliminationResult();
teamsSortedByEliminationResult.keySet().forEach(k -> result.put(resultPosition.addAndGet(1), teamsSortedByEliminationResult.get(k)));
}
//Add teams that are part of a round but did not make it into the EliminationSchemes
final List<Team> teamsPartOfEliminationsSchemes = eliminationSchemes.stream().flatMap(e -> e.getAllTeams().stream()).collect(Collectors.toList());
final TreeMap<Integer, List<Team>> remainingTeams = new TreeMap<>(Comparator.reverseOrder());
this.getRounds().forEach(round -> {
final List<Team> teamsSortedByPouleResult = round.getTeamsSortedByPouleResult();
for (int i = 0; i < teamsSortedByPouleResult.size(); i++) {
final Team team = teamsSortedByPouleResult.get(i);
if (!teamsPartOfEliminationsSchemes.contains(team)) {
remainingTeams.compute(i, (k, v) -> {
if (v == null) {
return new ArrayList<>(Arrays.asList(team));
} else {
v.add(team);
return v;
}
});
}
}
});
remainingTeams.keySet().stream()
.sorted()
.forEach(k -> {
result.put(resultPosition.addAndGet(1), remainingTeams.get(k));
});
return result;
} else {
throw new IllegalArgumentException("Event has more than one round but no eliminationscheme." + this);
}
return result;
}
private Set<Team> getTeams() {
if (rounds.isEmpty()) {
throw new RuntimeException("No rounds are yet assigned to this Event" + this);
}
return rounds.stream().flatMap(r -> r.getAllTeams().stream()).collect(Collectors.toSet());
}
}
| Badminton-PBO/pbo-jeugdcupranking | core/src/main/java/be/pbo/jeugdcup/ranking/domain/Event.java | 1,453 | // For example: 13 inschijvingen, dubbel/gemengd -> vierde & vijfde uit poule spelen geen eindronde | line_comment | nl | package be.pbo.jeugdcup.ranking.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Data
@Builder(toBuilder = true, builderClassName = "EventInternalBuilder", builderMethodName = "internalBuilder")
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Slf4j
public class Event {
private static final AgeCategoryDetector ageCategoryDetector = new AgeCategoryDetector();
private static final ReeksDetector reeksDetector = new ReeksDetector();
private Integer id;
private String name;
private Gender gender;
private EventType eventType;
private AgeCategory ageCategory = AgeCategory.DEFAULT_AGE_CATEGORY;
private Reeks reeks = Reeks.DEFAULT_REEKS;
private List<Round> rounds = new ArrayList<>();
private List<EliminationScheme> eliminationSchemes = new ArrayList<>();
public void init() {
ageCategory = ageCategoryDetector.resolveFromEventName(this.name);
reeks = reeksDetector.resolveFromEventName(this.name);
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends EventInternalBuilder {
Builder() {
super();
}
@Override
public Event build() {
final Event event = super.build();
event.init();
return event;
}
}
// Returns teams sorted by their results for this event
// It's possible that not all teams play in the Elimination phase.
// For example:<SUF>
// In that case multiple teams end at the same Event-rank and should get equal points
public SortedMap<Integer, List<Team>> sortTeamsByEventResult() {
final TreeMap<Integer, List<Team>> result = new TreeMap<>();
if (rounds.isEmpty()) {
log.info("Event has no rounds:" + this);
} else if (eliminationSchemes.isEmpty() && rounds.size() == 1) {
//Geen eindrondes, enkel 1 poule
final List<Team> teamsSortedByPouleResult = rounds.get(0).getTeamsSortedByPouleResult();
for (int i = 0; i < teamsSortedByPouleResult.size(); i++) {
result.put(i + 1, Arrays.asList(teamsSortedByPouleResult.get(i)));
}
} else if (eliminationSchemes.size() > 0) {
//Sort EliminationScheme so winners scheme come in front
eliminationSchemes.sort(new EliminationSchemeComparator(this));
final AtomicInteger resultPosition = new AtomicInteger(0);
for (final EliminationScheme eliminationScheme : eliminationSchemes) {
final SortedMap<Integer, List<Team>> teamsSortedByEliminationResult = eliminationScheme.getTeamsSortedByEliminationResult();
teamsSortedByEliminationResult.keySet().forEach(k -> result.put(resultPosition.addAndGet(1), teamsSortedByEliminationResult.get(k)));
}
//Add teams that are part of a round but did not make it into the EliminationSchemes
final List<Team> teamsPartOfEliminationsSchemes = eliminationSchemes.stream().flatMap(e -> e.getAllTeams().stream()).collect(Collectors.toList());
final TreeMap<Integer, List<Team>> remainingTeams = new TreeMap<>(Comparator.reverseOrder());
this.getRounds().forEach(round -> {
final List<Team> teamsSortedByPouleResult = round.getTeamsSortedByPouleResult();
for (int i = 0; i < teamsSortedByPouleResult.size(); i++) {
final Team team = teamsSortedByPouleResult.get(i);
if (!teamsPartOfEliminationsSchemes.contains(team)) {
remainingTeams.compute(i, (k, v) -> {
if (v == null) {
return new ArrayList<>(Arrays.asList(team));
} else {
v.add(team);
return v;
}
});
}
}
});
remainingTeams.keySet().stream()
.sorted()
.forEach(k -> {
result.put(resultPosition.addAndGet(1), remainingTeams.get(k));
});
return result;
} else {
throw new IllegalArgumentException("Event has more than one round but no eliminationscheme." + this);
}
return result;
}
private Set<Team> getTeams() {
if (rounds.isEmpty()) {
throw new RuntimeException("No rounds are yet assigned to this Event" + this);
}
return rounds.stream().flatMap(r -> r.getAllTeams().stream()).collect(Collectors.toSet());
}
}
|
25618_1 | package Machiavelli.Controllers;
import Machiavelli.Interfaces.Remotes.BeurtRemote;
import Machiavelli.Interfaces.Remotes.SpelRemote;
import Machiavelli.Interfaces.Remotes.SpelerRemote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
*
* Deze klasse bestuurt het model van het spel.
*
*/
public class SpelController extends UnicastRemoteObject {
private SpelerRemote speler;
private SpelRemote spel;
private BeurtRemote beurt;
private GebouwKaartController gebouwKaartController;
private SpeelveldController speelveldController;
public SpelController(SpelRemote spel) throws RemoteException {
// super(1099);
try {
this.spel = spel;
this.speler = this.spel.getSpelers().get(this.spel.getSpelers().size() - 1);
this.beurt = this.spel.getBeurt();
this.gebouwKaartController = new GebouwKaartController(this.spel, this.speler);
// Start nieuwe SpeelveldController
new SpeelveldController(this.spel, speler, this.gebouwKaartController, this.beurt);
} catch (Exception re) {
re.printStackTrace();
}
}
public GebouwKaartController getGebouwKaartController() {
return this.gebouwKaartController;
}
public SpeelveldController getSpeelveldController()
{
return this.speelveldController;
}
}
| Badmuts/Machiavelli | src/Machiavelli/Controllers/SpelController.java | 443 | // Start nieuwe SpeelveldController | line_comment | nl | package Machiavelli.Controllers;
import Machiavelli.Interfaces.Remotes.BeurtRemote;
import Machiavelli.Interfaces.Remotes.SpelRemote;
import Machiavelli.Interfaces.Remotes.SpelerRemote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
*
* Deze klasse bestuurt het model van het spel.
*
*/
public class SpelController extends UnicastRemoteObject {
private SpelerRemote speler;
private SpelRemote spel;
private BeurtRemote beurt;
private GebouwKaartController gebouwKaartController;
private SpeelveldController speelveldController;
public SpelController(SpelRemote spel) throws RemoteException {
// super(1099);
try {
this.spel = spel;
this.speler = this.spel.getSpelers().get(this.spel.getSpelers().size() - 1);
this.beurt = this.spel.getBeurt();
this.gebouwKaartController = new GebouwKaartController(this.spel, this.speler);
// Start nieuwe<SUF>
new SpeelveldController(this.spel, speler, this.gebouwKaartController, this.beurt);
} catch (Exception re) {
re.printStackTrace();
}
}
public GebouwKaartController getGebouwKaartController() {
return this.gebouwKaartController;
}
public SpeelveldController getSpeelveldController()
{
return this.speelveldController;
}
}
|
10948_11 | package nl.appcetera.mapp;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import nl.appcetera.mapp.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* Mapp main activity
* @author Mathijs
* @author Joost
* @group AppCetera
*/
public class Mapp extends MapActivity
{
private MapView mapView;
private MapController mapController;
private GeoPoint point;
private PolygonData database;
private OverlayManager om;
private ServerSync s;
public SharedPreferences settings;
public static final boolean LOGIN_DISABLED = false;
public static final String SETTINGS_KEY = "MAPP_SETTINGS";
public static final int pointPixelTreshold = 25; // Maximaal verschil tussen 2 punten in pixels voor ze als gelijk worden beschouwd
public static final String TAG = "AppCetera"; // Log-tag
public static final int maxTouchDuration = 500;
public static final int polygonMinDisplayWidth = 5; // Wanneer een polygoon smaller is dan dit wordt ie niet getoond
public static int syncInterval = 60*1000; // Interval tussen synchronisaties in milliseconden
public static final int offlineRetryInterval = 30*60*1000; // Interval tussen sync-attempts als toestel offline is
public static final int metaTouchDuration = 500; //touch-duration waarna we naar de meta-activity gaan
public static final int META_EDITSCREEN_ACTIVITYCODE = 42;
public static final int SETTINGSSCREEN_ACTIVITYCODE = 314;
public static final int ACCOUNTSCREEN_ACTIVITYCODE = 271;
public static final int LOGINSCREEN_ACTIVITYCODE = 404;
private static final int GROUPSSCREEN_ACTIVITYCODE = 162;
private static final int INVITESSCREEN_ACTIVITYCODE = 505;
public static Mapp instance;
/**
* Wordt aangeroepen wanneer deze activity wordt aangemaakt
* @param savedInstanceState de bundle die de activity meekrijgt wanneer hij wordt gemaakt
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
// Constructor van de parent aanroepen
super.onCreate(savedInstanceState);
// Juiste layout (mapview) zetten
setContentView(R.layout.main);
// Instantie van deze klasse beschikbaar maken met een statische variabele
Mapp.instance = this;
// Settings ophalen
settings = getSharedPreferences(SETTINGS_KEY, MODE_PRIVATE);
// Mapview ophalen
mapView = (MapView) findViewById(R.id.mapview);
// Databaseklasse opstarten
database = new PolygonData(this);
// Opgeslagen overlays laden
om = new OverlayManager(mapView, database);
// Syncservice starten
s = new ServerSync(getApplicationContext(), database);
mapView.invalidate();
applySettings();
}
private void applySettings() {
syncInterval = settings.getInt("syncInterval", syncInterval);
mapView.setBuiltInZoomControls(settings.getBoolean("zoomControls", true));
mapView.setSatellite(settings.getBoolean("satelliteMode", true));
}
/**
* Wanneer de app gekilled wordt
*/
@Override
public void onDestroy()
{
super.onDestroy();
database.close();
s.stopSync();
}
/**
* De applicatie gaat weer verder
*/
@Override
public void onResume()
{
super.onResume();
if (isLoggedIn()) {
// Naar de juiste plaats op de kaart gaan
mapController = mapView.getController();
point = new GeoPoint(settings.getInt("pos_lat", 51824167),
settings.getInt("pos_long", 5867374));
mapController.setZoom(settings.getInt("zoomlevel", 10));
mapController.animateTo(point);
// Database opstarten
database = new PolygonData(this);
// Syncservice hervatten
s.startSync();
// Juiste groep ophalen en polygonen laden
//om.setGroup(settings.getInt("group", 1));
OverlayManager.setGroup(1);
om.loadOverlays();
}
else
{
database = new PolygonData(this);
database.empty();
settings.edit().clear().commit();
showLoginScreen();
}
}
/**
* Er komt een andere app overheen, deze wordt gepauzeerd
*/
@Override
public void onPause()
{
super.onPause();
// Settings opslaan
SharedPreferences.Editor editor = settings.edit();
editor.putInt("zoomlevel", mapView.getZoomLevel());
editor.putInt("pos_long", mapView.getMapCenter().getLongitudeE6());
editor.putInt("pos_lat", mapView.getMapCenter().getLatitudeE6());
editor.putInt("group", 0);
editor.commit();
// Database afsluiten
database.close();
// Syncservice stoppen
s.stopSync();
OverlayManager.editModeMutex(false);
}
/**
* Verplaatst een overlay naar de bovenste laag
* @param po de overlay om naar boven te verplaatsen
*/
public static void moveToFront(PolygonOverlay po)
{
List<Overlay> listOfOverlays = Mapp.instance.mapView.getOverlays();
listOfOverlays.remove(po);
listOfOverlays.add(po);
}
/**
* Controleert of de gegeven overlay de eerste (=onderste) overlay is
* @param po de te checken overlay
* @return true indien gegeven overlay de onderste laag is
*/
public static boolean isFirstOverlay(PolygonOverlay po)
{
List<Overlay> listOfOverlays = Mapp.instance.mapView.getOverlays();
return (listOfOverlays.get(0).equals(po));
}
/**
* Voegt een nieuwe overlay toe
* @param het event dat doorgegeven zal worden aan de nieuwe laag
*/
public static void addNewOverlay(MotionEvent event)
{
PolygonOverlay po = Mapp.instance.om.addOverlay();
if(po != null)
{
// Geef het touchevent door, zodat we gelijk een nieuw punt kunnen maken
event.setAction(MotionEvent.ACTION_DOWN);
po.onTouchEvent(event, Mapp.instance.mapView);
event.setAction(MotionEvent.ACTION_UP);
po.onTouchEvent(event, Mapp.instance.mapView);
}
}
/**
* MapActivities moeten deze functie verplicht overriden
*/
@Override
protected boolean isRouteDisplayed()
{
return false;
}
/**
* Geeft een instantie van de databasemanager terug
* @return PolygonData
*/
public static PolygonData getDatabase()
{
return Mapp.instance.database;
}
/**
* Herlaad overlays
*/
public static void reload()
{
Mapp.instance.om.loadOverlays();
}
/**
* Deze functie wordt aangeroepen wanneer een Activity die vanuit Mapp is aangeroepen zn finish() aanroept
* @param requestCode een int die aangeeft om welke Activity het gaat
* @param resultCode een int die de status van terminatie van de Activity aangeeft
* @param data een intent die eventuele result-data bevat
*/
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(data == null)
{
return;
}
Bundle bundle = data.getExtras();
switch(requestCode) {
case META_EDITSCREEN_ACTIVITYCODE:
if (resultCode == MetaEditScreen.RESULT_SAVE)
{
int id = bundle.getInt(MetaEditScreen.ID_KEY);
int color = bundle.getInt(MetaEditScreen.COLOR_KEY);
String name = bundle.getString(MetaEditScreen.NAME_KEY);
String description = bundle.getString(MetaEditScreen.DESCRIPTION_KEY);
database.editPolygon(id, color, true, name, description);
}
else if (resultCode == MetaEditScreen.RESULT_DELETE)
{
int id = bundle.getInt(MetaEditScreen.ID_KEY);
database.removePolygon(id, true);
}
break;
case SETTINGSSCREEN_ACTIVITYCODE:
if (resultCode == SettingsScreen.RESULT_SAVE)
{
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("satelliteMode", bundle.getBoolean(SettingsScreen.SATMODE_KEY));
editor.putBoolean("zoomControls", bundle.getBoolean(SettingsScreen.ZOOMCONTROLS_KEY));
editor.putInt("syncInterval", bundle.getInt(SettingsScreen.SYNCINTERVAL_KEY));
editor.commit();
applySettings();
}
break;
case ACCOUNTSCREEN_ACTIVITYCODE:
if (resultCode == AccountScreen.RESULT_LOGOUT)
{
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", null);
editor.putString("password", null);
editor.commit();
showLoginScreen();
}
break;
case GROUPSSCREEN_ACTIVITYCODE:
if (bundle.getInt(GroupsScreen.ID_KEY) != OverlayManager.getGroupId()) {
OverlayManager.setGroup(bundle.getInt(GroupsScreen.ID_KEY));
Mapp.reload();
}
break;
}
}
@Override
/**
* Deze functie wordt aangeroepen wanneer iemand op de menuknop duwt
* Het menu uit mainmenu.xml wordt geopend
*/
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
@Override
/**
* Deze functie wordt aangeroepen wanneer een item uit het main-menu wordt aangetapt
* @param item het item van het menu dat is aangetapt
*/
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.groupsbutton:
showGroupsMenu();
return true;
case R.id.invitesbutton:
showInvites();
return true;
case R.id.accountbutton:
showAccountMenu();
return true;
case R.id.settingsbutton:
showSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het groups-scherm probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showGroupsMenu() {
Intent intent = new Intent(instance, GroupsScreen.class);
instance.startActivityForResult(intent, Mapp.GROUPSSCREEN_ACTIVITYCODE);
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het accountscherm probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showAccountMenu() {
Intent intent = new Intent(instance, AccountScreen.class);
Bundle bundle = new Bundle();
bundle.putString(AccountScreen.USERNAME_KEY, settings.getString("username", "Joe"));
intent.putExtras(bundle);
instance.startActivityForResult(intent, Mapp.ACCOUNTSCREEN_ACTIVITYCODE);
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het invitesmenu probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showInvites() {
Intent intent = new Intent(instance, InvitesScreen.class);
instance.startActivityForResult(intent, Mapp.INVITESSCREEN_ACTIVITYCODE);
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het settingsmenu probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showSettings() {
Intent intent = new Intent(instance, SettingsScreen.class);
//We maken een nieuwe bundle om data in mee te sturen
Bundle bundle = new Bundle();
//De data wordt aan de bundle toegevoegd
bundle.putBoolean(SettingsScreen.SATMODE_KEY, mapView.isSatellite());
bundle.putBoolean(SettingsScreen.ZOOMCONTROLS_KEY, settings.getBoolean("zoomControls", true));
bundle.putInt(SettingsScreen.SYNCINTERVAL_KEY, syncInterval);
//En we voegen de bundle bij de intent
intent.putExtras(bundle);
//We starten een nieuwe Activity
instance.startActivityForResult(intent, Mapp.SETTINGSSCREEN_ACTIVITYCODE);
}
/**
* Deze functie kijkt of er op dit moment een gebruiker ingelogd is
* @return true indien er een gebruiker ingelogd is
*/
private boolean isLoggedIn() {
return settings.getString("username", null) != "" && settings.getString("password", null) != "" && settings.getString("username", null) != null && settings.getString("password", null) != null;
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker nog niet ingelogd is
* en we dus naar het loginscherm moeten
*/
private void showLoginScreen() {
Intent intent = new Intent(instance, LoginScreen.class);
instance.startActivityForResult(intent, Mapp.LOGINSCREEN_ACTIVITYCODE);
}
}
| Balu-Varanasi/mapp-android | src/nl/appcetera/mapp/Mapp.java | 4,194 | /**
* Wanneer de app gekilled wordt
*/ | block_comment | nl | package nl.appcetera.mapp;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import nl.appcetera.mapp.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* Mapp main activity
* @author Mathijs
* @author Joost
* @group AppCetera
*/
public class Mapp extends MapActivity
{
private MapView mapView;
private MapController mapController;
private GeoPoint point;
private PolygonData database;
private OverlayManager om;
private ServerSync s;
public SharedPreferences settings;
public static final boolean LOGIN_DISABLED = false;
public static final String SETTINGS_KEY = "MAPP_SETTINGS";
public static final int pointPixelTreshold = 25; // Maximaal verschil tussen 2 punten in pixels voor ze als gelijk worden beschouwd
public static final String TAG = "AppCetera"; // Log-tag
public static final int maxTouchDuration = 500;
public static final int polygonMinDisplayWidth = 5; // Wanneer een polygoon smaller is dan dit wordt ie niet getoond
public static int syncInterval = 60*1000; // Interval tussen synchronisaties in milliseconden
public static final int offlineRetryInterval = 30*60*1000; // Interval tussen sync-attempts als toestel offline is
public static final int metaTouchDuration = 500; //touch-duration waarna we naar de meta-activity gaan
public static final int META_EDITSCREEN_ACTIVITYCODE = 42;
public static final int SETTINGSSCREEN_ACTIVITYCODE = 314;
public static final int ACCOUNTSCREEN_ACTIVITYCODE = 271;
public static final int LOGINSCREEN_ACTIVITYCODE = 404;
private static final int GROUPSSCREEN_ACTIVITYCODE = 162;
private static final int INVITESSCREEN_ACTIVITYCODE = 505;
public static Mapp instance;
/**
* Wordt aangeroepen wanneer deze activity wordt aangemaakt
* @param savedInstanceState de bundle die de activity meekrijgt wanneer hij wordt gemaakt
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
// Constructor van de parent aanroepen
super.onCreate(savedInstanceState);
// Juiste layout (mapview) zetten
setContentView(R.layout.main);
// Instantie van deze klasse beschikbaar maken met een statische variabele
Mapp.instance = this;
// Settings ophalen
settings = getSharedPreferences(SETTINGS_KEY, MODE_PRIVATE);
// Mapview ophalen
mapView = (MapView) findViewById(R.id.mapview);
// Databaseklasse opstarten
database = new PolygonData(this);
// Opgeslagen overlays laden
om = new OverlayManager(mapView, database);
// Syncservice starten
s = new ServerSync(getApplicationContext(), database);
mapView.invalidate();
applySettings();
}
private void applySettings() {
syncInterval = settings.getInt("syncInterval", syncInterval);
mapView.setBuiltInZoomControls(settings.getBoolean("zoomControls", true));
mapView.setSatellite(settings.getBoolean("satelliteMode", true));
}
/**
* Wanneer de app<SUF>*/
@Override
public void onDestroy()
{
super.onDestroy();
database.close();
s.stopSync();
}
/**
* De applicatie gaat weer verder
*/
@Override
public void onResume()
{
super.onResume();
if (isLoggedIn()) {
// Naar de juiste plaats op de kaart gaan
mapController = mapView.getController();
point = new GeoPoint(settings.getInt("pos_lat", 51824167),
settings.getInt("pos_long", 5867374));
mapController.setZoom(settings.getInt("zoomlevel", 10));
mapController.animateTo(point);
// Database opstarten
database = new PolygonData(this);
// Syncservice hervatten
s.startSync();
// Juiste groep ophalen en polygonen laden
//om.setGroup(settings.getInt("group", 1));
OverlayManager.setGroup(1);
om.loadOverlays();
}
else
{
database = new PolygonData(this);
database.empty();
settings.edit().clear().commit();
showLoginScreen();
}
}
/**
* Er komt een andere app overheen, deze wordt gepauzeerd
*/
@Override
public void onPause()
{
super.onPause();
// Settings opslaan
SharedPreferences.Editor editor = settings.edit();
editor.putInt("zoomlevel", mapView.getZoomLevel());
editor.putInt("pos_long", mapView.getMapCenter().getLongitudeE6());
editor.putInt("pos_lat", mapView.getMapCenter().getLatitudeE6());
editor.putInt("group", 0);
editor.commit();
// Database afsluiten
database.close();
// Syncservice stoppen
s.stopSync();
OverlayManager.editModeMutex(false);
}
/**
* Verplaatst een overlay naar de bovenste laag
* @param po de overlay om naar boven te verplaatsen
*/
public static void moveToFront(PolygonOverlay po)
{
List<Overlay> listOfOverlays = Mapp.instance.mapView.getOverlays();
listOfOverlays.remove(po);
listOfOverlays.add(po);
}
/**
* Controleert of de gegeven overlay de eerste (=onderste) overlay is
* @param po de te checken overlay
* @return true indien gegeven overlay de onderste laag is
*/
public static boolean isFirstOverlay(PolygonOverlay po)
{
List<Overlay> listOfOverlays = Mapp.instance.mapView.getOverlays();
return (listOfOverlays.get(0).equals(po));
}
/**
* Voegt een nieuwe overlay toe
* @param het event dat doorgegeven zal worden aan de nieuwe laag
*/
public static void addNewOverlay(MotionEvent event)
{
PolygonOverlay po = Mapp.instance.om.addOverlay();
if(po != null)
{
// Geef het touchevent door, zodat we gelijk een nieuw punt kunnen maken
event.setAction(MotionEvent.ACTION_DOWN);
po.onTouchEvent(event, Mapp.instance.mapView);
event.setAction(MotionEvent.ACTION_UP);
po.onTouchEvent(event, Mapp.instance.mapView);
}
}
/**
* MapActivities moeten deze functie verplicht overriden
*/
@Override
protected boolean isRouteDisplayed()
{
return false;
}
/**
* Geeft een instantie van de databasemanager terug
* @return PolygonData
*/
public static PolygonData getDatabase()
{
return Mapp.instance.database;
}
/**
* Herlaad overlays
*/
public static void reload()
{
Mapp.instance.om.loadOverlays();
}
/**
* Deze functie wordt aangeroepen wanneer een Activity die vanuit Mapp is aangeroepen zn finish() aanroept
* @param requestCode een int die aangeeft om welke Activity het gaat
* @param resultCode een int die de status van terminatie van de Activity aangeeft
* @param data een intent die eventuele result-data bevat
*/
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(data == null)
{
return;
}
Bundle bundle = data.getExtras();
switch(requestCode) {
case META_EDITSCREEN_ACTIVITYCODE:
if (resultCode == MetaEditScreen.RESULT_SAVE)
{
int id = bundle.getInt(MetaEditScreen.ID_KEY);
int color = bundle.getInt(MetaEditScreen.COLOR_KEY);
String name = bundle.getString(MetaEditScreen.NAME_KEY);
String description = bundle.getString(MetaEditScreen.DESCRIPTION_KEY);
database.editPolygon(id, color, true, name, description);
}
else if (resultCode == MetaEditScreen.RESULT_DELETE)
{
int id = bundle.getInt(MetaEditScreen.ID_KEY);
database.removePolygon(id, true);
}
break;
case SETTINGSSCREEN_ACTIVITYCODE:
if (resultCode == SettingsScreen.RESULT_SAVE)
{
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("satelliteMode", bundle.getBoolean(SettingsScreen.SATMODE_KEY));
editor.putBoolean("zoomControls", bundle.getBoolean(SettingsScreen.ZOOMCONTROLS_KEY));
editor.putInt("syncInterval", bundle.getInt(SettingsScreen.SYNCINTERVAL_KEY));
editor.commit();
applySettings();
}
break;
case ACCOUNTSCREEN_ACTIVITYCODE:
if (resultCode == AccountScreen.RESULT_LOGOUT)
{
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", null);
editor.putString("password", null);
editor.commit();
showLoginScreen();
}
break;
case GROUPSSCREEN_ACTIVITYCODE:
if (bundle.getInt(GroupsScreen.ID_KEY) != OverlayManager.getGroupId()) {
OverlayManager.setGroup(bundle.getInt(GroupsScreen.ID_KEY));
Mapp.reload();
}
break;
}
}
@Override
/**
* Deze functie wordt aangeroepen wanneer iemand op de menuknop duwt
* Het menu uit mainmenu.xml wordt geopend
*/
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
@Override
/**
* Deze functie wordt aangeroepen wanneer een item uit het main-menu wordt aangetapt
* @param item het item van het menu dat is aangetapt
*/
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.groupsbutton:
showGroupsMenu();
return true;
case R.id.invitesbutton:
showInvites();
return true;
case R.id.accountbutton:
showAccountMenu();
return true;
case R.id.settingsbutton:
showSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het groups-scherm probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showGroupsMenu() {
Intent intent = new Intent(instance, GroupsScreen.class);
instance.startActivityForResult(intent, Mapp.GROUPSSCREEN_ACTIVITYCODE);
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het accountscherm probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showAccountMenu() {
Intent intent = new Intent(instance, AccountScreen.class);
Bundle bundle = new Bundle();
bundle.putString(AccountScreen.USERNAME_KEY, settings.getString("username", "Joe"));
intent.putExtras(bundle);
instance.startActivityForResult(intent, Mapp.ACCOUNTSCREEN_ACTIVITYCODE);
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het invitesmenu probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showInvites() {
Intent intent = new Intent(instance, InvitesScreen.class);
instance.startActivityForResult(intent, Mapp.INVITESSCREEN_ACTIVITYCODE);
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker het settingsmenu probeert te openen
* De functie start een nieuwe activity, van het type SettingsScreen
*/
private void showSettings() {
Intent intent = new Intent(instance, SettingsScreen.class);
//We maken een nieuwe bundle om data in mee te sturen
Bundle bundle = new Bundle();
//De data wordt aan de bundle toegevoegd
bundle.putBoolean(SettingsScreen.SATMODE_KEY, mapView.isSatellite());
bundle.putBoolean(SettingsScreen.ZOOMCONTROLS_KEY, settings.getBoolean("zoomControls", true));
bundle.putInt(SettingsScreen.SYNCINTERVAL_KEY, syncInterval);
//En we voegen de bundle bij de intent
intent.putExtras(bundle);
//We starten een nieuwe Activity
instance.startActivityForResult(intent, Mapp.SETTINGSSCREEN_ACTIVITYCODE);
}
/**
* Deze functie kijkt of er op dit moment een gebruiker ingelogd is
* @return true indien er een gebruiker ingelogd is
*/
private boolean isLoggedIn() {
return settings.getString("username", null) != "" && settings.getString("password", null) != "" && settings.getString("username", null) != null && settings.getString("password", null) != null;
}
/**
* Deze functie wordt aangeroepen wanneer de gebruiker nog niet ingelogd is
* en we dus naar het loginscherm moeten
*/
private void showLoginScreen() {
Intent intent = new Intent(instance, LoginScreen.class);
instance.startActivityForResult(intent, Mapp.LOGINSCREEN_ACTIVITYCODE);
}
}
|
17508_6 | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands extends AbstractMutableLanguage {
private static final long serialVersionUID = 1L;
static final Random rnd = new Random();
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...ben jij dat? Dat is lang geleden!"))
.then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?"));
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Kom eens hier jij!")
.then(new Action("knuffelt " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(rnd);
@Override
public String apiTimeoutException() {
registerModification();
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + apiTimeoutShuffler.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.",
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
}
| Banbeucmas/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java | 2,674 | //nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", | line_comment | nl | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands extends AbstractMutableLanguage {
private static final long serialVersionUID = 1L;
static final Random rnd = new Random();
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...ben jij dat? Dat is lang geleden!"))
.then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?"));
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Kom eens hier jij!")
.then(new Action("knuffelt " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(rnd);
@Override
public String apiTimeoutException() {
registerModification();
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + apiTimeoutShuffler.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia]<SUF>
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.",
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
}
|
36204_2 | package dao;
import Connector.KetNoiSQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.ThongTinPhong;
import model.ThongTinSVTrongKTX;
public class PhongDAO {
public PhongDAO() {
}
public List<ThongTinPhong> getAllThongTinPhong() {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
ThongTinPhong phong = new ThongTinPhong();
phong.setMaPhong(rs.getString("maPhong"));
phong.setTenPhong(rs.getString("tenPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
listPhong.add(phong);
}
preparedStatement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public List<ThongTinPhong> getAllThongTinPhongSearch(String where, String text) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where " + where + " like N'%" + text + "%'";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
ThongTinPhong phong = new ThongTinPhong();
phong.setMaPhong(rs.getString("maPhong"));
phong.setTenPhong(rs.getString("tenPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
listPhong.add(phong);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public int SoLuongSV(String maPhong) {
int soluongsv = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "select count(*) as soluongSV from Phong where maPhong='" + maPhong + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
soluongsv = rs.getInt("soluongSV");
}
con.close();
} catch (Exception e) {
}
return soluongsv;
}
public int SoLuongSVPhong(String maPhong) {
int soluongsv = 0;
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where maPhong ='" + maPhong + "'";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
soluongsv = rs.getInt("soLuongSVPhong");
}
conn.close();
} catch (Exception e) {
}
return soluongsv;
}
public List<ThongTinPhong> getAllThongTinPhongTheoGT_SL(String gioitinh) {
List<ThongTinPhong> listmaphongtheoGT_SL = new PhongDAO().getAllThongTinPhongGioiTinh(gioitinh);
for (ThongTinPhong phong : listmaphongtheoGT_SL) {
if (new PhongDAO().soluongSVtttheomaPhong(phong.getMaPhong()) >= phong.getSoLuongSVPhong()) {
listmaphongtheoGT_SL.remove(phong);
}
}
return listmaphongtheoGT_SL;
}
public double TienPhong(String maph) {
double tienphong = 0;
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where maPhong ='" + maph + "'";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
tienphong = rs.getDouble("tienPhong");
}
conn.close();
} catch (Exception e) {
}
return tienphong;
}
public boolean KiemTraMaSoPhong(String maphong) {
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where maPhong ='" + maphong + "'";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
return true;
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// xài -----------------
public List<ThongTinPhong> getAllThongTinPhongDK(String gioitinh, String loaiphong) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where gioitinh='" + gioitinh + "' and loaiphong='" + loaiphong + "'";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
listPhong.add(phong);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public List<ThongTinPhong> getAllThongTinPhongGioiTinh(String gioitinh) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
int slsvdango = slsvINPhong(gioitinh);
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where gioiTinh=? ";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, gioitinh);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
if (slsvdango > 0) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
// phong.setSoLuongSVTT(rs.getInt("sinhVienTonTai"));
listPhong.add(phong);
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public List<ThongTinPhong> getAllThongTinPhongGioiTinhLoaiPhong(String gioitinh, String loaiphong) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
int slsvdango = slsvtontaitrongPhong(gioitinh);
String sql = "select * from Phong where loaiPhong=? and gioiTinh=? ";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, loaiphong);
preparedStatement.setString(2, gioitinh);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
if (slsvdango < rs.getInt("soLuongSVPhong")) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
// phong.setSoLuongSVTT(rs.getInt("sinhVienTonTai"));
listPhong.add(phong);
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public int SoLuongPhongTheoGioiTinh(String gioitinh) {
int soluong = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "select count(*) as soluongSV from thongtinphong where gioiTinh='" + gioitinh + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
soluong = rs.getInt("soluongSV");
}
con.close();
} catch (Exception e) {
}
return soluong;
}
public Date getngayHDBD(String masv) {
Date date = null;
//Date dt,dtcp=null;
SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
Connection con = KetNoiSQL.getConnection();
String sql = "Select * from HopDongKTX where maSV=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, masv);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
date = rs.getDate("ngayHDBD");
}
con.close();
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("date dao:" + date);
return date;
}
public int demSVinDT(String maPhong) {
int sl = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "SELECT COUNT(*) AS slsv FROM HopDongKTX WHERE maPhong = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, maPhong); // Truyền tham số maPhong vào câu truy vấn
ResultSet rs = ps.executeQuery();
if (rs.next()) {
sl = rs.getInt("slsv");
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return sl;
}
// public int demSVinDK(String maPhong) {
// int sl = 0;
// Connection con = KetNoiSQL.getConnection();
// String sql = "SELECT COUNT(*) AS slsv FROM DangKyPhong WHERE maPhong = ?";
// try {
// PreparedStatement ps = con.prepareStatement(sql);
// ResultSet rs = ps.executeQuery();
// while (rs.next()) {
// sl = rs.getInt("slsv");
// }
//
// } catch (SQLException ex) {
// Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
// }
// return sl;
// }
public int demSVinDK(String maPhong) {
int sl = 0;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = KetNoiSQL.getConnection();
String sql = "SELECT COUNT(*) AS slsv FROM DangKyPhong WHERE maPhong = ?";
ps = con.prepareStatement(sql);
ps.setString(1, maPhong);
rs = ps.executeQuery();
if (rs.next()) {
sl = rs.getInt("slsv");
}
} catch (SQLException ex) {
Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// Đóng tất cả các tài nguyên
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
return sl;
}
public int slsvINPhong(String maPhong) {
int slsv = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "SELECT soLuongSVPhong FROM Phong WHERE maPhong = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, maPhong); // Gán giá trị của maPhong vào câu truy vấn
ResultSet rs = ps.executeQuery();
if (rs.next()) {
slsv = rs.getInt("soLuongSVPhong");
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return slsv;
}
// public int slsvINPhong(String gioitinh) {
// int slsv = 0;
// Connection con = KetNoiSQL.getConnection();
//
// String sql2 = "select loaiPhong ,sum(soLuongSVPhong) as tongSVtt from Phong where gioiTinh=N'" + gioitinh + "' group by loaiPhong";
// try {
//
// PreparedStatement ps2 = con.prepareStatement(sql2);
//
// ResultSet rs2 = ps2.executeQuery();
//
// while (rs2.next()) {
// slsv = slsv + rs2.getInt("tongSVtt");
// }
//
// } catch (SQLException ex) {
// Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
// }
//
// return slsv;
//
// }
public List<String> listmaphongTheoLoaiPhongAGT(String loaiphong, String gioitinh) {
List<String> listmaphong = new ArrayList<>();
Connection con = KetNoiSQL.getConnection();
String sql2 = "select maPhong from Phong where loaiPhong=N'" + loaiphong + "' and gioiTinh=N'" + gioitinh + "'";
try {
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
listmaphong.add(rs2.getString("maPhong"));
}
ps2.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return listmaphong;
}
public List<String> listmaphongTheoGioiTinh(String gioitinh) {
List<String> listmaphong = new ArrayList<>();
Connection con = KetNoiSQL.getConnection();
String sql2 = "select maPhong from Phong where gioiTinh=N'" + gioitinh + "'";
try {
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
listmaphong.add(rs2.getString("maPhong"));
}
} catch (SQLException ex) {
Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return listmaphong;
}
public int slsvtontaitrongPhong(String loaiphong, String gioitinh) {
List<String> listmp = listmaphongTheoLoaiPhongAGT(loaiphong, gioitinh);
int tongsv = 0;
for (String i : listmp) {
tongsv = tongsv + soluongSVtttheomaPhong(i);
}
return tongsv;
}
public int slsvtontaitrongPhong(String gioitinh) {
List<String> listmp = listmaphongTheoGioiTinh(gioitinh);
int tongsv = 0;
for (String i : listmp) {
tongsv = tongsv + soluongSVtttheomaPhong(i);
}
return tongsv;
}
public int CheckPhong(String maPhong) {
int t = 1;
int slsvdangthue = demSVinDT(maPhong);
int slsvdangky = demSVinDK(maPhong);
int slsv = slsvINPhong(maPhong);
// System.out.println(slsvdangthue);
// System.out.println(slsv);
if (slsvdangthue + slsvdangky >= slsv) {
t = 0;
}
return t;
}
// public int CheckPhong(String gioitinh) {
// int t = 1;
// int slsvDK, slsv, slsvtontai;
// slsvDK = demSVinDK(gioitinh);
// slsv = slsvINPhong(gioitinh);
// slsvtontai = slsvtontaitrongPhong(gioitinh);
// if (slsvtontai + slsvDK >= slsv) {
// t = 0;
// }
//
// return t;
// }
public void AddHopDong(String masv, String maphong, Date ngay1) {
Connection conn = KetNoiSQL.getConnection();
int row = 0;
String sql1 = "insert into HopDongKTX (maSV,maPhong,ngayHDBD) values(?,?,?)";
try {
PreparedStatement ps1 = conn.prepareStatement(sql1);
//String date1,date2,date3;
ps1.setString(1, masv.trim());
ps1.setString(2, maphong);
/* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date1 = sdf.format(ngay1);
date2= sdf.format(ngay2);
date3 = sdf.format(ngay3);*/
ps1.setDate(3, new java.sql.Date(ngay1.getTime()));
//ps1.setString(4, "");
row = ps1.executeUpdate();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void deleteDK(String maSV) {
Connection conn = KetNoiSQL.getConnection();
String sql = "delete from DangKyPhong where maSV = ?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, maSV);
ps.executeUpdate();
} catch (SQLException ex) {
}
}
public Date getNgayHDKT(String masv) {
Date date = null;
Connection con = KetNoiSQL.getConnection();
String sql = "select * from HopDongKTX where maSV='" + masv + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
date = rs.getDate("ngayHDKT");
}
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
}
public void updateNgayHDKT(String masv) {
Date date = new Date();
Connection con = KetNoiSQL.getConnection();
String sql = "update HopDongKTX set ngayHDKT=? where maSV=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(date.getTime()));
ps.setString(2, masv);
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<String> getlistmaphong() {
List<String> listmp = new ArrayList<>();
Connection con = KetNoiSQL.getConnection();
String sql = "select * from Phong";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
listmp.add(rs.getString("maPhong"));
}
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return listmp;
}
public int soluongSVtttheomaPhong(String maphong) {
SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestr = sp.format(date);
Date datefm = null;
try {
datefm = sp.parse(datestr);
} catch (ParseException ex) {
}
int slsvtt = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "select count(hd.maPhong) as slsv from HopDongKTX hd join Phong p on p.maPhong=hd.maPhong where ngayHDKT>? group by hd.maPhong having hd.maPhong='" + maphong + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(date.getTime()));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
slsvtt = rs.getInt("slsv");
}
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return slsvtt;
}
// public void updateSoluongSVtontai(String maphong)
// {
//
// Connection con =KetNoiSQL.getConnection();
// int slsv=soluongSVtttheomaPhong(maphong);
// String sql="update Phong set sinhVienTonTai=? where maPhong=?";
// try {
// PreparedStatement ps =con.prepareStatement(sql);
// ps.setInt(1, slsv);
// ps.setString(2,maphong);
// ps.executeUpdate();
// } catch (SQLException ex) {
// Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
// }
//
// }
// public void updateAllslsvinPHONG()
// {
// List<String> listmp=getlistmaphong();
// for(String i: listmp)
// {
// updateSoluongSVtontai(i);
// }
//
// }
public int CheckGioiTinhHopLe(String masv, String gioiTinh) {
int t = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "SELECT gioiTinh FROM SinhVien WHERE maSV = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, masv); // Truyền tham số maPhong vào câu truy vấn
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String gioiTinhSinhVien = rs.getString("gioiTinh");
if (gioiTinhSinhVien.equals(gioiTinh)) {
t = 1;
}
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(QuanLySinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return t;
}
public List<ThongTinPhong> getAllThongTinPhongTheoGioiTinh(String gioitinh) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
int slsvdango = slsvtontaitrongPhong(gioitinh);
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where gioiTinh=? ";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, gioitinh);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
if (slsvdango < rs.getInt("soLuongSVPhong")) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
// phong.setSoLuongSVTT(rs.getInt("sinhVienTonTai"));
listPhong.add(phong);
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public String layTenSinhVien(String maSV) {
String tenSV = "";
Connection conn = KetNoiSQL.getConnection();
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
String sql = "SELECT tenSV FROM SinhVien WHERE maSV = ?";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, maSV);
rs = preparedStatement.executeQuery();
if (rs.next()) {
tenSV = rs.getString("tenSV");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return tenSV;
}
}
| Bap2907/Thuc_Tap_Co_So | src/dao/PhongDAO.java | 7,970 | // int sl = 0; | line_comment | nl | package dao;
import Connector.KetNoiSQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.ThongTinPhong;
import model.ThongTinSVTrongKTX;
public class PhongDAO {
public PhongDAO() {
}
public List<ThongTinPhong> getAllThongTinPhong() {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
ThongTinPhong phong = new ThongTinPhong();
phong.setMaPhong(rs.getString("maPhong"));
phong.setTenPhong(rs.getString("tenPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
listPhong.add(phong);
}
preparedStatement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public List<ThongTinPhong> getAllThongTinPhongSearch(String where, String text) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where " + where + " like N'%" + text + "%'";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
ThongTinPhong phong = new ThongTinPhong();
phong.setMaPhong(rs.getString("maPhong"));
phong.setTenPhong(rs.getString("tenPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
listPhong.add(phong);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public int SoLuongSV(String maPhong) {
int soluongsv = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "select count(*) as soluongSV from Phong where maPhong='" + maPhong + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
soluongsv = rs.getInt("soluongSV");
}
con.close();
} catch (Exception e) {
}
return soluongsv;
}
public int SoLuongSVPhong(String maPhong) {
int soluongsv = 0;
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where maPhong ='" + maPhong + "'";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
soluongsv = rs.getInt("soLuongSVPhong");
}
conn.close();
} catch (Exception e) {
}
return soluongsv;
}
public List<ThongTinPhong> getAllThongTinPhongTheoGT_SL(String gioitinh) {
List<ThongTinPhong> listmaphongtheoGT_SL = new PhongDAO().getAllThongTinPhongGioiTinh(gioitinh);
for (ThongTinPhong phong : listmaphongtheoGT_SL) {
if (new PhongDAO().soluongSVtttheomaPhong(phong.getMaPhong()) >= phong.getSoLuongSVPhong()) {
listmaphongtheoGT_SL.remove(phong);
}
}
return listmaphongtheoGT_SL;
}
public double TienPhong(String maph) {
double tienphong = 0;
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where maPhong ='" + maph + "'";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
tienphong = rs.getDouble("tienPhong");
}
conn.close();
} catch (Exception e) {
}
return tienphong;
}
public boolean KiemTraMaSoPhong(String maphong) {
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where maPhong ='" + maphong + "'";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
return true;
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// xài -----------------
public List<ThongTinPhong> getAllThongTinPhongDK(String gioitinh, String loaiphong) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where gioitinh='" + gioitinh + "' and loaiphong='" + loaiphong + "'";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
listPhong.add(phong);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public List<ThongTinPhong> getAllThongTinPhongGioiTinh(String gioitinh) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
int slsvdango = slsvINPhong(gioitinh);
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where gioiTinh=? ";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, gioitinh);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
if (slsvdango > 0) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
// phong.setSoLuongSVTT(rs.getInt("sinhVienTonTai"));
listPhong.add(phong);
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public List<ThongTinPhong> getAllThongTinPhongGioiTinhLoaiPhong(String gioitinh, String loaiphong) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
Connection conn = KetNoiSQL.getConnection();
int slsvdango = slsvtontaitrongPhong(gioitinh);
String sql = "select * from Phong where loaiPhong=? and gioiTinh=? ";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, loaiphong);
preparedStatement.setString(2, gioitinh);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
if (slsvdango < rs.getInt("soLuongSVPhong")) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
// phong.setSoLuongSVTT(rs.getInt("sinhVienTonTai"));
listPhong.add(phong);
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public int SoLuongPhongTheoGioiTinh(String gioitinh) {
int soluong = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "select count(*) as soluongSV from thongtinphong where gioiTinh='" + gioitinh + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
soluong = rs.getInt("soluongSV");
}
con.close();
} catch (Exception e) {
}
return soluong;
}
public Date getngayHDBD(String masv) {
Date date = null;
//Date dt,dtcp=null;
SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
Connection con = KetNoiSQL.getConnection();
String sql = "Select * from HopDongKTX where maSV=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, masv);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
date = rs.getDate("ngayHDBD");
}
con.close();
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("date dao:" + date);
return date;
}
public int demSVinDT(String maPhong) {
int sl = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "SELECT COUNT(*) AS slsv FROM HopDongKTX WHERE maPhong = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, maPhong); // Truyền tham số maPhong vào câu truy vấn
ResultSet rs = ps.executeQuery();
if (rs.next()) {
sl = rs.getInt("slsv");
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return sl;
}
// public int demSVinDK(String maPhong) {
// int sl<SUF>
// Connection con = KetNoiSQL.getConnection();
// String sql = "SELECT COUNT(*) AS slsv FROM DangKyPhong WHERE maPhong = ?";
// try {
// PreparedStatement ps = con.prepareStatement(sql);
// ResultSet rs = ps.executeQuery();
// while (rs.next()) {
// sl = rs.getInt("slsv");
// }
//
// } catch (SQLException ex) {
// Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
// }
// return sl;
// }
public int demSVinDK(String maPhong) {
int sl = 0;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = KetNoiSQL.getConnection();
String sql = "SELECT COUNT(*) AS slsv FROM DangKyPhong WHERE maPhong = ?";
ps = con.prepareStatement(sql);
ps.setString(1, maPhong);
rs = ps.executeQuery();
if (rs.next()) {
sl = rs.getInt("slsv");
}
} catch (SQLException ex) {
Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// Đóng tất cả các tài nguyên
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger.getLogger(SinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
return sl;
}
public int slsvINPhong(String maPhong) {
int slsv = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "SELECT soLuongSVPhong FROM Phong WHERE maPhong = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, maPhong); // Gán giá trị của maPhong vào câu truy vấn
ResultSet rs = ps.executeQuery();
if (rs.next()) {
slsv = rs.getInt("soLuongSVPhong");
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return slsv;
}
// public int slsvINPhong(String gioitinh) {
// int slsv = 0;
// Connection con = KetNoiSQL.getConnection();
//
// String sql2 = "select loaiPhong ,sum(soLuongSVPhong) as tongSVtt from Phong where gioiTinh=N'" + gioitinh + "' group by loaiPhong";
// try {
//
// PreparedStatement ps2 = con.prepareStatement(sql2);
//
// ResultSet rs2 = ps2.executeQuery();
//
// while (rs2.next()) {
// slsv = slsv + rs2.getInt("tongSVtt");
// }
//
// } catch (SQLException ex) {
// Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
// }
//
// return slsv;
//
// }
public List<String> listmaphongTheoLoaiPhongAGT(String loaiphong, String gioitinh) {
List<String> listmaphong = new ArrayList<>();
Connection con = KetNoiSQL.getConnection();
String sql2 = "select maPhong from Phong where loaiPhong=N'" + loaiphong + "' and gioiTinh=N'" + gioitinh + "'";
try {
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
listmaphong.add(rs2.getString("maPhong"));
}
ps2.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return listmaphong;
}
public List<String> listmaphongTheoGioiTinh(String gioitinh) {
List<String> listmaphong = new ArrayList<>();
Connection con = KetNoiSQL.getConnection();
String sql2 = "select maPhong from Phong where gioiTinh=N'" + gioitinh + "'";
try {
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
listmaphong.add(rs2.getString("maPhong"));
}
} catch (SQLException ex) {
Logger.getLogger(SinhVienDangKyDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return listmaphong;
}
public int slsvtontaitrongPhong(String loaiphong, String gioitinh) {
List<String> listmp = listmaphongTheoLoaiPhongAGT(loaiphong, gioitinh);
int tongsv = 0;
for (String i : listmp) {
tongsv = tongsv + soluongSVtttheomaPhong(i);
}
return tongsv;
}
public int slsvtontaitrongPhong(String gioitinh) {
List<String> listmp = listmaphongTheoGioiTinh(gioitinh);
int tongsv = 0;
for (String i : listmp) {
tongsv = tongsv + soluongSVtttheomaPhong(i);
}
return tongsv;
}
public int CheckPhong(String maPhong) {
int t = 1;
int slsvdangthue = demSVinDT(maPhong);
int slsvdangky = demSVinDK(maPhong);
int slsv = slsvINPhong(maPhong);
// System.out.println(slsvdangthue);
// System.out.println(slsv);
if (slsvdangthue + slsvdangky >= slsv) {
t = 0;
}
return t;
}
// public int CheckPhong(String gioitinh) {
// int t = 1;
// int slsvDK, slsv, slsvtontai;
// slsvDK = demSVinDK(gioitinh);
// slsv = slsvINPhong(gioitinh);
// slsvtontai = slsvtontaitrongPhong(gioitinh);
// if (slsvtontai + slsvDK >= slsv) {
// t = 0;
// }
//
// return t;
// }
public void AddHopDong(String masv, String maphong, Date ngay1) {
Connection conn = KetNoiSQL.getConnection();
int row = 0;
String sql1 = "insert into HopDongKTX (maSV,maPhong,ngayHDBD) values(?,?,?)";
try {
PreparedStatement ps1 = conn.prepareStatement(sql1);
//String date1,date2,date3;
ps1.setString(1, masv.trim());
ps1.setString(2, maphong);
/* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date1 = sdf.format(ngay1);
date2= sdf.format(ngay2);
date3 = sdf.format(ngay3);*/
ps1.setDate(3, new java.sql.Date(ngay1.getTime()));
//ps1.setString(4, "");
row = ps1.executeUpdate();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void deleteDK(String maSV) {
Connection conn = KetNoiSQL.getConnection();
String sql = "delete from DangKyPhong where maSV = ?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, maSV);
ps.executeUpdate();
} catch (SQLException ex) {
}
}
public Date getNgayHDKT(String masv) {
Date date = null;
Connection con = KetNoiSQL.getConnection();
String sql = "select * from HopDongKTX where maSV='" + masv + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
date = rs.getDate("ngayHDKT");
}
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
}
public void updateNgayHDKT(String masv) {
Date date = new Date();
Connection con = KetNoiSQL.getConnection();
String sql = "update HopDongKTX set ngayHDKT=? where maSV=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(date.getTime()));
ps.setString(2, masv);
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<String> getlistmaphong() {
List<String> listmp = new ArrayList<>();
Connection con = KetNoiSQL.getConnection();
String sql = "select * from Phong";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
listmp.add(rs.getString("maPhong"));
}
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return listmp;
}
public int soluongSVtttheomaPhong(String maphong) {
SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestr = sp.format(date);
Date datefm = null;
try {
datefm = sp.parse(datestr);
} catch (ParseException ex) {
}
int slsvtt = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "select count(hd.maPhong) as slsv from HopDongKTX hd join Phong p on p.maPhong=hd.maPhong where ngayHDKT>? group by hd.maPhong having hd.maPhong='" + maphong + "'";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(date.getTime()));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
slsvtt = rs.getInt("slsv");
}
} catch (SQLException ex) {
Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return slsvtt;
}
// public void updateSoluongSVtontai(String maphong)
// {
//
// Connection con =KetNoiSQL.getConnection();
// int slsv=soluongSVtttheomaPhong(maphong);
// String sql="update Phong set sinhVienTonTai=? where maPhong=?";
// try {
// PreparedStatement ps =con.prepareStatement(sql);
// ps.setInt(1, slsv);
// ps.setString(2,maphong);
// ps.executeUpdate();
// } catch (SQLException ex) {
// Logger.getLogger(PhongDAO.class.getName()).log(Level.SEVERE, null, ex);
// }
//
// }
// public void updateAllslsvinPHONG()
// {
// List<String> listmp=getlistmaphong();
// for(String i: listmp)
// {
// updateSoluongSVtontai(i);
// }
//
// }
public int CheckGioiTinhHopLe(String masv, String gioiTinh) {
int t = 0;
Connection con = KetNoiSQL.getConnection();
String sql = "SELECT gioiTinh FROM SinhVien WHERE maSV = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, masv); // Truyền tham số maPhong vào câu truy vấn
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String gioiTinhSinhVien = rs.getString("gioiTinh");
if (gioiTinhSinhVien.equals(gioiTinh)) {
t = 1;
}
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(QuanLySinhVienDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return t;
}
public List<ThongTinPhong> getAllThongTinPhongTheoGioiTinh(String gioitinh) {
List<ThongTinPhong> listPhong = new ArrayList<ThongTinPhong>();
int slsvdango = slsvtontaitrongPhong(gioitinh);
Connection conn = KetNoiSQL.getConnection();
String sql = "select * from Phong where gioiTinh=? ";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, gioitinh);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
if (slsvdango < rs.getInt("soLuongSVPhong")) {
ThongTinPhong phong = new ThongTinPhong();
phong.setTenPhong(rs.getString("tenPhong"));
phong.setMaPhong(rs.getString("maPhong"));
phong.setSoLuongSVPhong(rs.getInt("soLuongSVPhong"));
phong.setGioiTinh(rs.getString("gioiTinh"));
phong.setTienPhong(rs.getDouble("tienPhong"));
phong.setLoaiPhong(rs.getString("loaiPhong"));
// phong.setSoLuongSVTT(rs.getInt("sinhVienTonTai"));
listPhong.add(phong);
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return listPhong;
}
public String layTenSinhVien(String maSV) {
String tenSV = "";
Connection conn = KetNoiSQL.getConnection();
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
String sql = "SELECT tenSV FROM SinhVien WHERE maSV = ?";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, maSV);
rs = preparedStatement.executeQuery();
if (rs.next()) {
tenSV = rs.getString("tenSV");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return tenSV;
}
}
|
83634_0 | package novi.uni.compserver.model.enums;
public enum ForecastType {
/**
* Type forecast, nodig voor het bepalen van de regels die worden toegepast of er een voorspelling correct zal zijn
*/
FULLTIME,
CORRECT_SCORE,
BOTH_TEAMS_TO_SCORE,
UNDER_OVER
}
| BartGeest/competitiemanager | comp-mng-server/src/main/java/novi/uni/compserver/model/enums/ForecastType.java | 102 | /**
* Type forecast, nodig voor het bepalen van de regels die worden toegepast of er een voorspelling correct zal zijn
*/ | block_comment | nl | package novi.uni.compserver.model.enums;
public enum ForecastType {
/**
* Type forecast, nodig<SUF>*/
FULLTIME,
CORRECT_SCORE,
BOTH_TEAMS_TO_SCORE,
UNDER_OVER
}
|
85518_0 | /**
*
*/
package kuleuven.groep9;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.internal.RealSystem;
import org.junit.internal.TextListener;
import org.junit.runner.manipulation.Sorter;
import org.junit.runner.notification.RunListener;
import org.junit.runners.model.InitializationError;
import kuleuven.groep9.classloading.Project;
import kuleuven.groep9.runner.InterruptingManager;
import kuleuven.groep9.runner.manipulation.CombinedSorter;
import kuleuven.groep9.statistics.FrequencyStatistic;
import kuleuven.groep9.statistics.LastFailStatistic;
import kuleuven.groep9.statistics.IStatisticTracker;
import kuleuven.groep9.statistics.StatisticTracker;
import kuleuven.groep9.statistics.TestGroupManager;
import kuleuven.groep9.statistics.TestGroupStatistic;
/**
* @author OSS groep 9
*
* Dit is de klasse die instaat voor het opstarten van de Daemon.
* Daarvoor wordt er een execution manager aangemaakt,
* ook wordt er een notifier en een listener aangemaakt.
*/
public class JUnitDaemon {
/**
*
*
* @param args
* The arguments of the program are the source directory,
* where the *.class files of the tested project are stored in subdirectories,
* the test directory, where the test classes are kept,
* and a string indicating the statistic by which the tests should
* be sorted at execution.
* The ossrewriter agent should also be given as an argument to the
* Java Virtual Machine.
* @throws InitializationError
* @throws IOException
*/
public static void main(String[] args) throws IOException, InitializationError {
if(args.length < 3)
return;
Path codebase = Paths.get(args[0]);
Path src = Paths.get(args[1]);
Path test = Paths.get(args[2]);
Project project = new Project(codebase, src, codebase, test);
InterruptingManager manager = new InterruptingManager(project);
StatisticTracker<LastFailStatistic> lastFailTracker =
new IStatisticTracker<LastFailStatistic>(new LastFailStatistic(null));
StatisticTracker<FrequencyStatistic> frequencyTracker =
new IStatisticTracker<FrequencyStatistic>(new FrequencyStatistic(null, 20));
StatisticTracker<TestGroupStatistic> testGroupTracker =
new IStatisticTracker<TestGroupStatistic>(new TestGroupStatistic(null, new TestGroupManager()));
manager.addTracker(lastFailTracker);
manager.addTracker(frequencyTracker);
manager.addTracker(testGroupTracker);
if(6 <= args.length){
Sorter[] sorters = new Sorter[3];
sorters[0] = lastFailTracker.getSorter();
sorters[1] = frequencyTracker.getSorter();
sorters[2] = testGroupTracker.getSorter();
int[] weights = {Integer.valueOf(args[3]),Integer.valueOf(args[4]),Integer.valueOf(args[5])};
manager.setSorter(new CombinedSorter(sorters));
}
RunListener listener = new TextListener(new RealSystem());
manager.getCore().addListener(listener);
}
}
| BartOutOfTheBox/JUnitDaemon | src/main/java/kuleuven/groep9/JUnitDaemon.java | 977 | /**
* @author OSS groep 9
*
* Dit is de klasse die instaat voor het opstarten van de Daemon.
* Daarvoor wordt er een execution manager aangemaakt,
* ook wordt er een notifier en een listener aangemaakt.
*/ | block_comment | nl | /**
*
*/
package kuleuven.groep9;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.internal.RealSystem;
import org.junit.internal.TextListener;
import org.junit.runner.manipulation.Sorter;
import org.junit.runner.notification.RunListener;
import org.junit.runners.model.InitializationError;
import kuleuven.groep9.classloading.Project;
import kuleuven.groep9.runner.InterruptingManager;
import kuleuven.groep9.runner.manipulation.CombinedSorter;
import kuleuven.groep9.statistics.FrequencyStatistic;
import kuleuven.groep9.statistics.LastFailStatistic;
import kuleuven.groep9.statistics.IStatisticTracker;
import kuleuven.groep9.statistics.StatisticTracker;
import kuleuven.groep9.statistics.TestGroupManager;
import kuleuven.groep9.statistics.TestGroupStatistic;
/**
* @author OSS groep<SUF>*/
public class JUnitDaemon {
/**
*
*
* @param args
* The arguments of the program are the source directory,
* where the *.class files of the tested project are stored in subdirectories,
* the test directory, where the test classes are kept,
* and a string indicating the statistic by which the tests should
* be sorted at execution.
* The ossrewriter agent should also be given as an argument to the
* Java Virtual Machine.
* @throws InitializationError
* @throws IOException
*/
public static void main(String[] args) throws IOException, InitializationError {
if(args.length < 3)
return;
Path codebase = Paths.get(args[0]);
Path src = Paths.get(args[1]);
Path test = Paths.get(args[2]);
Project project = new Project(codebase, src, codebase, test);
InterruptingManager manager = new InterruptingManager(project);
StatisticTracker<LastFailStatistic> lastFailTracker =
new IStatisticTracker<LastFailStatistic>(new LastFailStatistic(null));
StatisticTracker<FrequencyStatistic> frequencyTracker =
new IStatisticTracker<FrequencyStatistic>(new FrequencyStatistic(null, 20));
StatisticTracker<TestGroupStatistic> testGroupTracker =
new IStatisticTracker<TestGroupStatistic>(new TestGroupStatistic(null, new TestGroupManager()));
manager.addTracker(lastFailTracker);
manager.addTracker(frequencyTracker);
manager.addTracker(testGroupTracker);
if(6 <= args.length){
Sorter[] sorters = new Sorter[3];
sorters[0] = lastFailTracker.getSorter();
sorters[1] = frequencyTracker.getSorter();
sorters[2] = testGroupTracker.getSorter();
int[] weights = {Integer.valueOf(args[3]),Integer.valueOf(args[4]),Integer.valueOf(args[5])};
manager.setSorter(new CombinedSorter(sorters));
}
RunListener listener = new TextListener(new RealSystem());
manager.getCore().addListener(listener);
}
}
|
92263_5 | package smpt42.nl.printmanager.control;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import smpt42.nl.printmanager.model.Scan;
import smpt42.nl.printmanager.model.enums.SORT_TYPE;
/**
* Created by Daan on 12/19/2014.
*/
public class ScanManager {
public static Comparator<Scan> sortByDate = new Comparator<Scan>() {
public int compare(Scan scan1, Scan scan2) {
return scan1.getPrintDate().compareTo(scan2.getPrintDate());
}
};
public static Comparator<Scan> sortByCompany = new Comparator<Scan>() {
public int compare(Scan scan1, Scan scan2) {
return scan1.getCompany().getName().compareTo(scan2.getCompany().getName());
}
};
public static Comparator<Scan> sortByStarred = new Comparator<Scan>() {
public int compare(Scan scan1, Scan scan2) {
Boolean s1 = scan1.getIsStarred();
Boolean s2 = scan2.getIsStarred();
return s2.compareTo(s1);
}
};
ArrayList<Scan> scans;
/**
* Constructor
*/
public ScanManager(ArrayList<Scan> scans) {
this.scans = scans;
//db = new Database();
//try {
// scans = db.getScans();
//} catch (ParseException pe) {
// pe.printStackTrace();
//}
}
/**
* Voeg een scan toe aan de lijst met scans
*
* @param scan De toe te voegen scan
*/
public void addScan(Scan scan) {
scans.add(scan);
}
/**
* Haalt de scans op, gesorteerd op de aangegeven eigenschap
*
* @param sorttype De eigenschap waarop gesorteerd moet worden
* @return De gesorteerde lijst met scans
*/
public ArrayList<Scan> getScans(SORT_TYPE sorttype) {
if (sorttype == SORT_TYPE.DATE) {
Collections.sort(scans, sortByDate);
} else if (sorttype == SORT_TYPE.COMPANY) {
Collections.sort(scans, sortByCompany);
} else if (sorttype == SORT_TYPE.STARRED) {
Collections.sort(scans, sortByStarred);
} else {
return null;
}
return scans;
}
public ArrayList<Scan> getScans(String s) {
ArrayList<Scan> returner = new ArrayList<>();
for (Scan scan : scans) {
if (scan.hasString(s)) {
returner.add(scan);
}
}
return returner;
}
/**
* Zoekt naar scans waarvan de naam (deels) bestaat uit de ingevulde zoekterm.
*
* @param input String met de zoekterm van de gebruiker
* @return Gevonden scans, null bij geen resultaat
*/
public List<Scan> searchByName(String input) {
List<Scan> result = null;
for (Scan s : scans) {
if (s.getName().contains(input)) {
result.add(s);
}
}
return result;
}
/**
* Zoekt naar de scan met de opgegeven barcode
*
* @param barcode String met de barcode waarop gezocht moet worden
* @return Gevonden scan, null bij geen resultaat
*/
public Scan searchByBarcode(String barcode) {
Scan result = null;
for (Scan s : scans) {
if (s.getBarcode() == barcode) {
// Immediately cancel after barcode has been found.
return result;
}
}
return null;
}
}
| BasThomas/SMPT42 | Printmanager/app/src/main/java/smpt42/nl/printmanager/control/ScanManager.java | 1,050 | /**
* Voeg een scan toe aan de lijst met scans
*
* @param scan De toe te voegen scan
*/ | block_comment | nl | package smpt42.nl.printmanager.control;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import smpt42.nl.printmanager.model.Scan;
import smpt42.nl.printmanager.model.enums.SORT_TYPE;
/**
* Created by Daan on 12/19/2014.
*/
public class ScanManager {
public static Comparator<Scan> sortByDate = new Comparator<Scan>() {
public int compare(Scan scan1, Scan scan2) {
return scan1.getPrintDate().compareTo(scan2.getPrintDate());
}
};
public static Comparator<Scan> sortByCompany = new Comparator<Scan>() {
public int compare(Scan scan1, Scan scan2) {
return scan1.getCompany().getName().compareTo(scan2.getCompany().getName());
}
};
public static Comparator<Scan> sortByStarred = new Comparator<Scan>() {
public int compare(Scan scan1, Scan scan2) {
Boolean s1 = scan1.getIsStarred();
Boolean s2 = scan2.getIsStarred();
return s2.compareTo(s1);
}
};
ArrayList<Scan> scans;
/**
* Constructor
*/
public ScanManager(ArrayList<Scan> scans) {
this.scans = scans;
//db = new Database();
//try {
// scans = db.getScans();
//} catch (ParseException pe) {
// pe.printStackTrace();
//}
}
/**
* Voeg een scan<SUF>*/
public void addScan(Scan scan) {
scans.add(scan);
}
/**
* Haalt de scans op, gesorteerd op de aangegeven eigenschap
*
* @param sorttype De eigenschap waarop gesorteerd moet worden
* @return De gesorteerde lijst met scans
*/
public ArrayList<Scan> getScans(SORT_TYPE sorttype) {
if (sorttype == SORT_TYPE.DATE) {
Collections.sort(scans, sortByDate);
} else if (sorttype == SORT_TYPE.COMPANY) {
Collections.sort(scans, sortByCompany);
} else if (sorttype == SORT_TYPE.STARRED) {
Collections.sort(scans, sortByStarred);
} else {
return null;
}
return scans;
}
public ArrayList<Scan> getScans(String s) {
ArrayList<Scan> returner = new ArrayList<>();
for (Scan scan : scans) {
if (scan.hasString(s)) {
returner.add(scan);
}
}
return returner;
}
/**
* Zoekt naar scans waarvan de naam (deels) bestaat uit de ingevulde zoekterm.
*
* @param input String met de zoekterm van de gebruiker
* @return Gevonden scans, null bij geen resultaat
*/
public List<Scan> searchByName(String input) {
List<Scan> result = null;
for (Scan s : scans) {
if (s.getName().contains(input)) {
result.add(s);
}
}
return result;
}
/**
* Zoekt naar de scan met de opgegeven barcode
*
* @param barcode String met de barcode waarop gezocht moet worden
* @return Gevonden scan, null bij geen resultaat
*/
public Scan searchByBarcode(String barcode) {
Scan result = null;
for (Scan s : scans) {
if (s.getBarcode() == barcode) {
// Immediately cancel after barcode has been found.
return result;
}
}
return null;
}
}
|
11661_3 | package server.protocol;
/**
* Protocol voor de te gebruiken commando's tussen server en client.
* Op basis van het protocol van vorig jaar, gemaakt door: Christian Versloot
* Aanpassingen door:
* @author Martijn Gemmink
* @author Bas Hendrikse
* @version 1.2.1 (25-01-2015)
*
*
* Delimeter beschrijving:
* Scheid ALLE commando's en parameters met de delimeter zoals vermeld in ProtocolConstants.java
*
* Gebruikersnaamcriteria:
* Controleer ALLE gebruikersnamen op de regular expression zoals vermeld in ProtocolConstants.java
*
* Param beschrijving:
* Een @param bij een string geeft aan welke parameters het commando daarnaast ook verwacht.
* Volgorde van de @params per commando (van boven naar beneden) geeft de volgorde van versturen aan.
*/
public interface ProtocolControl {
/**
* Vraag het bord op aan de server.
* Richting: [Client] -> [Server]
*/
String getBoard = "getBoard";
/**
* Stuur het bord naar een client.
* Richting: [Server] -> [Client]
* @param 42 keer een veld string gescheiden door een msgSeperator (zie ProtocolConstants.java)
*/
String sendBoard = "sendBoard";
/**
* Verbinden van client met de server
* Richting: [Client] -> [Server]
* @param naam - je naam
*/
String joinRequest = "joinRequest";
/**
* Geef een kleur aan de client mits er geen fouten optreden.
* NOTE: bij het optreden van een fout wordt er een invalidCommand door de server gestuurd. (zie ProtocolConstants.java)
* Richting: [Server] -> [Client]
* @param kleur - je kleur (zie ProtocolConstants.java)
*/
String acceptRequest = "acceptRequest";
/**
* Vertel de spelers dat het spel kan beginnen.
* Richting: [Server] -> [Client]
* @param clientname1
* @param clientname2
*/
String startGame = "startGame";
/**
* Vertel de server dat je een zet hebt gedaan.
* Richting: [Client] -> [Server]
* @param indexcijfer van 0 tot 41, het te zetten vakje.
*/
String doMove = "doMove";
/**
* Vertel een client dat een zet is gedaan.
* Richting: [Server] -> [Client]
* @param index - het gezette vakje
* @param naam - naam van de speler die de zet doet
* @param valid - boolean of de zet valide is
* @param nextplayer - (naam) geeft de beurt aan de volgende speler.
*/
String moveResult = "moveResult";
/**
* Client wil weten welke speler aan zet is.
* Richting: [Client] -> [Server]
*/
String playerTurn = "playerTurn";
/**
* Vertelt de client wie er aan zet is.
* Richting: [Server] -> [Client]
* @param naam - naam van de speler die aan zet is
*/
String turn = "turn";
/**
* Vertel een client dat het spel afgelopen is.
* Richting: [Server] -> [Client]
* @param resultString - wie het spel heeft gewonnen
* @param reden - wat de reden is van het stoppen van het spel
*/
String endGame = "endGame";
// ---- Extensions ----
/**
* Extension - Chatbox
* Richting: [Client] -> [Server]
* @param message - het bericht dat je wilt sturen.
*/
String sendMessage = "sendMessage";
/**
<<<<<<< HEAD
=======
* Extension - Chatbox
* Richting: [Server] -> [Client]
* @param name - de naam van de client die het bericht verstuurd
* @param message - het bericht dat naar alle spelers verbonden aan de server wordt verstuurd
*/
String broadcastMessage = "broadcastMessage";
/**
>>>>>>> origin/Bas
* Extension - Leaderboard
* Client vraagt het leaderboard op.
* Richting: [Client] -> [Server]
*/
String getLeaderboard = "getLeaderboard";
/**
* Extension - Leaderboard
* Server stuurt het leaderboard terug.
* Richting: [Server] -> [Client]
*/
String sendLeaderboard = "sendLeaderboard";
/**
* Een rematch request van de client, als beide clients een rematch request hebben gestuurd, reset de game.
* Richting: [Client] -> [Server]
*/
String rematch = "rematch";
/**
* Een bevestiging van de server dat de twee spelers nog een keer willen spelen.
* De server stuurt, als hij van beide Clients een rematch command binnen krijgt rematchConfirm, hierna zal de game van de server resetten en de games van de Clients, zodat ze beide in dezelfde staat zijn.
* Richting: [Server] -> [Client]
*/
String rematchConfirm = "rematchConfirm";
}
| Bash-/connect-four-game-java | src/server/protocol/ProtocolControl.java | 1,485 | /**
* Verbinden van client met de server
* Richting: [Client] -> [Server]
* @param naam - je naam
*/ | block_comment | nl | package server.protocol;
/**
* Protocol voor de te gebruiken commando's tussen server en client.
* Op basis van het protocol van vorig jaar, gemaakt door: Christian Versloot
* Aanpassingen door:
* @author Martijn Gemmink
* @author Bas Hendrikse
* @version 1.2.1 (25-01-2015)
*
*
* Delimeter beschrijving:
* Scheid ALLE commando's en parameters met de delimeter zoals vermeld in ProtocolConstants.java
*
* Gebruikersnaamcriteria:
* Controleer ALLE gebruikersnamen op de regular expression zoals vermeld in ProtocolConstants.java
*
* Param beschrijving:
* Een @param bij een string geeft aan welke parameters het commando daarnaast ook verwacht.
* Volgorde van de @params per commando (van boven naar beneden) geeft de volgorde van versturen aan.
*/
public interface ProtocolControl {
/**
* Vraag het bord op aan de server.
* Richting: [Client] -> [Server]
*/
String getBoard = "getBoard";
/**
* Stuur het bord naar een client.
* Richting: [Server] -> [Client]
* @param 42 keer een veld string gescheiden door een msgSeperator (zie ProtocolConstants.java)
*/
String sendBoard = "sendBoard";
/**
* Verbinden van client<SUF>*/
String joinRequest = "joinRequest";
/**
* Geef een kleur aan de client mits er geen fouten optreden.
* NOTE: bij het optreden van een fout wordt er een invalidCommand door de server gestuurd. (zie ProtocolConstants.java)
* Richting: [Server] -> [Client]
* @param kleur - je kleur (zie ProtocolConstants.java)
*/
String acceptRequest = "acceptRequest";
/**
* Vertel de spelers dat het spel kan beginnen.
* Richting: [Server] -> [Client]
* @param clientname1
* @param clientname2
*/
String startGame = "startGame";
/**
* Vertel de server dat je een zet hebt gedaan.
* Richting: [Client] -> [Server]
* @param indexcijfer van 0 tot 41, het te zetten vakje.
*/
String doMove = "doMove";
/**
* Vertel een client dat een zet is gedaan.
* Richting: [Server] -> [Client]
* @param index - het gezette vakje
* @param naam - naam van de speler die de zet doet
* @param valid - boolean of de zet valide is
* @param nextplayer - (naam) geeft de beurt aan de volgende speler.
*/
String moveResult = "moveResult";
/**
* Client wil weten welke speler aan zet is.
* Richting: [Client] -> [Server]
*/
String playerTurn = "playerTurn";
/**
* Vertelt de client wie er aan zet is.
* Richting: [Server] -> [Client]
* @param naam - naam van de speler die aan zet is
*/
String turn = "turn";
/**
* Vertel een client dat het spel afgelopen is.
* Richting: [Server] -> [Client]
* @param resultString - wie het spel heeft gewonnen
* @param reden - wat de reden is van het stoppen van het spel
*/
String endGame = "endGame";
// ---- Extensions ----
/**
* Extension - Chatbox
* Richting: [Client] -> [Server]
* @param message - het bericht dat je wilt sturen.
*/
String sendMessage = "sendMessage";
/**
<<<<<<< HEAD
=======
* Extension - Chatbox
* Richting: [Server] -> [Client]
* @param name - de naam van de client die het bericht verstuurd
* @param message - het bericht dat naar alle spelers verbonden aan de server wordt verstuurd
*/
String broadcastMessage = "broadcastMessage";
/**
>>>>>>> origin/Bas
* Extension - Leaderboard
* Client vraagt het leaderboard op.
* Richting: [Client] -> [Server]
*/
String getLeaderboard = "getLeaderboard";
/**
* Extension - Leaderboard
* Server stuurt het leaderboard terug.
* Richting: [Server] -> [Client]
*/
String sendLeaderboard = "sendLeaderboard";
/**
* Een rematch request van de client, als beide clients een rematch request hebben gestuurd, reset de game.
* Richting: [Client] -> [Server]
*/
String rematch = "rematch";
/**
* Een bevestiging van de server dat de twee spelers nog een keer willen spelen.
* De server stuurt, als hij van beide Clients een rematch command binnen krijgt rematchConfirm, hierna zal de game van de server resetten en de games van de Clients, zodat ze beide in dezelfde staat zijn.
* Richting: [Server] -> [Client]
*/
String rematchConfirm = "rematchConfirm";
}
|
109386_6 | package de.sarbot.garleon;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import de.sarbot.garleon.Objects.Creature;
import de.sarbot.garleon.Objects.Npc;
import de.sarbot.garleon.Screens.BootScreen;
import de.sarbot.garleon.Objects.Player;
import java.util.ArrayList;
public class GarleonGame extends Game {
//TODO: sinnvoll grafiken hier zu laden, oder werden die bei jedem übergeben game=gam kopiert neu geschrieben?
//TODO: organize classes (super implement extend parent/child?)
public int width;
public int height;
public float speed;
public float zoom;
public int debug; //0 off, 1 basic, 2 loops, 3 everything
public Player player;
public Array<Creature> creatures;
public Array<Npc> npcs;
@Override
public void create () {
//setup the window and stuff
height = 480;
width = height * Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
debug = 1;
//setup the game
speed = 1; //general game speed
zoom = 1; //general zoom (world)
player = new Player();
//boot the game
if (debug>0) System.out.println("booted");
setScreen(new BootScreen(this));
}
@Override
public void render () {
super.render();
}
@Override
public void dispose () {
super.dispose();
//this.dispose(); //does this makes sense?
}
}
//TODO: compile the game with ./gradlew html:dist
// dann liegt iwo n dist ordner, der die app enthält | Bastelschublade/garleon | core/src/de/sarbot/garleon/GarleonGame.java | 716 | //general zoom (world) | line_comment | nl | package de.sarbot.garleon;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import de.sarbot.garleon.Objects.Creature;
import de.sarbot.garleon.Objects.Npc;
import de.sarbot.garleon.Screens.BootScreen;
import de.sarbot.garleon.Objects.Player;
import java.util.ArrayList;
public class GarleonGame extends Game {
//TODO: sinnvoll grafiken hier zu laden, oder werden die bei jedem übergeben game=gam kopiert neu geschrieben?
//TODO: organize classes (super implement extend parent/child?)
public int width;
public int height;
public float speed;
public float zoom;
public int debug; //0 off, 1 basic, 2 loops, 3 everything
public Player player;
public Array<Creature> creatures;
public Array<Npc> npcs;
@Override
public void create () {
//setup the window and stuff
height = 480;
width = height * Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
debug = 1;
//setup the game
speed = 1; //general game speed
zoom = 1; //general zoom<SUF>
player = new Player();
//boot the game
if (debug>0) System.out.println("booted");
setScreen(new BootScreen(this));
}
@Override
public void render () {
super.render();
}
@Override
public void dispose () {
super.dispose();
//this.dispose(); //does this makes sense?
}
}
//TODO: compile the game with ./gradlew html:dist
// dann liegt iwo n dist ordner, der die app enthält |
11621_26 | package domein;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import exceptions.AccountException;
import exceptions.SpelMakenException;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* De hoofd domain klasse
*
* @author Gilles De Pessemier, Rune De Bruyne, Aaron Everaert, Chiel Meneve
*
*/
public class DomeinController
{
private final SpelerRepository spelerRepository;
private final SpelRepository spelRepository;
private Speler huidigeSpeler;
private Spel huidigSpel;
private ResourceBundle rb = ResourceBundle.getBundle("languages/resource_bundle", Locale.getDefault());
/**
* Domeincontroller constructor
*/
public DomeinController() {
spelerRepository = new SpelerRepository();
spelRepository = new SpelRepository();
}
/**
* Geeft de resourcebundel terug
* @return Geeft de correcte resourcebundel terug
*/
public ResourceBundle getResourceBundle() {
return rb;
}
/**
* Geeft terug of de gebruik adminrights heeft of niet
* @return Geeft terug of de gebruik adminrights heeft of niet
*/
public boolean isAdmin() {
return huidigeSpeler.isAdmin();
}
/**
* Meld een speler aan
* @param ingegeven gebruikersNaam
* @param ingegeven wachtwoord
*
* @exception AccountException
*/
public void aanmeldenSpeler(String gebruikersNaam, String wachtwoord) {
Speler gevondenSpeler = spelerRepository.geefSpeler(gebruikersNaam, wachtwoord);
if (gevondenSpeler != null) {
setSpeler(gevondenSpeler);
} else {
throw new AccountException(rb.getString("geengebruikergevonden"));
}
}
/**
* Registreert een nieuwe speler
* @param achternaam
* @param voornaam
* @param gebruikersNaam
* @param wachtwoord
* @param wachtwoordBevestiging
*
* @exception AccountException
*/
public void registreerSpeler(String naam, String voornaam, String gebruikersNaam, String wachtwoord, String wachtwoord2) {
if (!wachtwoord.equals(wachtwoord2)) { throw new AccountException(rb.getString("wachtwoordenkomennietovereen")); }
Speler nieuweSpeler = new Speler(naam, voornaam, gebruikersNaam, wachtwoord, false);
setSpeler(nieuweSpeler);
spelerRepository.voegSpelerToe(nieuweSpeler);
}
/**
* Geeft de namen van alle spellen terug
* @return Geeft de namen van alle spellen terug
*/
public String[] geefSpelnamen() {
return spelRepository.geefAlleSpelnamen();
}
/**
* Kiest een gekozen spel
* @param Heeft de spelNaam nodig om te kiezen
*/
public void kiesSpel(String spelNaam) {
huidigSpel = spelRepository.kiesSpel(spelNaam);
}
/**
* Geeft true terug als het level compleet is, anders false
* @param Heeft de levelNaam nodig om te kijken als het level voltooid is
*
* @return Geeft true terug als het level compleet is, anders false
*/
public boolean voltooiSpelbord(String levelNaam) {
return huidigSpel.isLevelCompleet(levelNaam);
}
/**
* Verplaatst een speler
* @param Heeft richting nodig om de speler te kunnen verplaatsen
*/
public void verplaatsSpeler(String richting) {
huidigSpel.verplaatsSpeler(richting);
}
/**
* Geeft het aantal verplaatsingen van dat level terug
* @param spelNaam om het spel te vinden
* @param levelNaam om het level te vinden
*
* @return Geeft het aantal verplaatsingen van dat level terug
*/
public int getAantalVerplaatsingen() {
return huidigSpel.getAantalVerplaatsingen();
}
/**
* Geeft een 3D String array terug met alle vakken hun vakinfo
* @param Heeft de levelNaam nodig voor het vinden van alle vakken
*
* @return Geeft een 3D String array terug met alle vakken hun vakinfo
*/
public String[][] getAlleVakken(String levelNaam) {
huidigSpel.setHuidigLevel(levelNaam);
Vak[][] vakken = huidigSpel.getAlleVakken();
String[][] result = new String[vakken.length * vakken[0].length][4];
int intTeller = 0;
for (Vak[] rij : vakken) {
for (Vak v : rij) {
if (v != null)
result[intTeller] = v.getVakInfo();
intTeller++;
}
}
return result;
}
/**
* Maakt een nieuw spel aan
* @param Heeft de spelNaam nodig
*
* @exception SpelMakenException
*/
public void maakNieuwSpel(String spelNaam) {
if (spelNaam.contains(" "))
throw new SpelMakenException(rb.getString("geenspatiesinnaam"));
for (String s : spelRepository.geefAlleSpelnamen())
if (s.equals(spelNaam))
throw new SpelMakenException(rb.getString("naambestaatal"));
spelRepository.maakNieuwSpel(spelNaam, huidigeSpeler.getGebruikersnaam());
huidigSpel = spelRepository.kiesSpel(spelNaam);
}
/**
* Geeft de creatiebevestiging terug
* @return Geeft de creatiebevestiging terug
*/
public String getCreatieBevestiging() {
return String.format(rb.getString("creatiebevestiging"), huidigSpel.getNaam(), huidigSpel.getAantalSpelborden());
}
/**
* Maakt een nieuw spelbord
*/
public void maakNieuwSpelbord() {
spelRepository.maakNieuwSpelbord(huidigSpel);
}
/**
* Stelt de huidige speler in
* @param Heeft de speler nodig om in te stellen
*/
private void setSpeler(Speler speler) { this.huidigeSpeler = speler; }
/**
* Geeft het aantal levels van het huidige spelbord terug
* @return Geeft het aantal levels van het huidige spelbord terug
*/
public int getAantalLevels() { return huidigSpel.getAantalSpelborden(); }
/**
* Geeft de voltooiSpelbordSummary terug
* @param Heeft de levelNaam nodig voor het spelbord te vinden
*
* @return Geeft de voltooiSpelbordSummary terug
*/
public String voltooiSpelbordSummary(String levelNaam) {
return String.format(rb.getString("voltooispelbordsummary"), huidigSpel.getAantalVoltooideSpelborden(), getAantalLevels());
}
/**
* Update een vak in de repository en de database
* @param xcoord voor de x coordinaat
* @param ycoord voor de y coordinaat
* @param nieuwType voor het nieuwe type
* @param isDoel voor te weten als het vak een doel is
*/
public void updateVak(int xcoord, int ycoord, String nieuwType, boolean isDoel) {
huidigSpel.updateVak(xcoord, ycoord, nieuwType, isDoel);
spelRepository.updateVak(xcoord, ycoord, nieuwType, isDoel, huidigSpel);
}
/**
* Geeft het aantal spelborden terug in een string array
* @param Heeft de spelNaam nodig om een spel te kunnen wijzigen
* @return Geeft het aantal spelborden terug in een string array
*/
public String[] wijzigSpel(String spelNaam) {
kiesSpel(spelNaam);
int aantalSpelborden = huidigSpel.getAantalSpelborden();
String[] result = new String[aantalSpelborden];
for (int i = 1; i <= aantalSpelborden; i++)
result[i-1]= String.valueOf(i);
return result;
}
/**
* Update een vak in de repository
* @param xcoord voor de x coordinaat
* @param ycoord voor de y coordinaat
* @param nieuwType voor het nieuwe type
* @param isDoel voor te weten als het vak een doel is
* @param spelbordNr om te weten over welk spelbord het gaat
*/
public void vernieuwVak(int xcoord, int ycoord, String nieuwType, boolean isDoel, String spelbordNr) {
spelRepository.updateVak(xcoord, ycoord, nieuwType, isDoel, huidigSpel);
}
/**
* Geeft het voltooispel bericht terug
* @return Geeft het voltooispel bericht terug
*/
public String voltooiWijzigSpel() {
return String.format(rb.getString("voltooiwijzigspelsummary"), huidigSpel.getNaam());
}
/**
* Geeft het verwijderbevestigingsbericht terug
* @param Heeft de levelNaam nodig om het level te vinden
*
* @return Geeft het verwijderbevestigingsbericht terug
*/
public String verwijderLevel(String levelNaam) {
spelRepository.verwijderLevel(huidigSpel, levelNaam);
huidigSpel.verwijderLevel(levelNaam);
return String.format(rb.getString("verwijderlevelbevestiging"), levelNaam, huidigSpel.getNaam());
}
/**
* Verwijderd spel en geeft een melding terug
* @param Heeft de spelNaam nodig om het spel te vinden
*
* @return Geeft het verwijderbevestigingsbericht terug
*/
public String verwijderSpel(String spelNaam) {
spelRepository.verwijderSpel(spelNaam);
return String.format(rb.getString("verwijderspelbevestiging"), spelNaam);
}
/**
* ResourceBundle updaten
*/
public void updateLanguage() {
rb = ResourceBundle.getBundle("languages/resource_bundle", Locale.getDefault());
}
/**
* Geeft terug of de input null, whitespace of empty is
* @param String
*
* @return Geeft terug of de input null, whitespace of empty is
*/
public boolean isNullOrWhitespaceOrEmpty(String s) {
return s == null || isWhitespace(s) || s.length() == 0;
}
private boolean isWhitespace(String s) {
int length = s.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
return false;
}
/**
* Geeft de gebruikersnaam van de huidige speler terug.
* @return Geeft de gebruikersnaam van de huidige speler terug.
*/
public String geefGebruikersnaam() {
return huidigeSpeler.getGebruikersnaam();
}
/**
* Toont een nieuwe stage en geeft deze terug.
* @param resourceFile in de package gui
* @param FX Controller
* @param Primary stage
* @param Stage width
* @param Stage height
*
* @return geeft de huidige stage terug
*/
public Stage initialize(String resourceFile, Object controller, Stage pstage, double width, double height) {
try {
FXMLLoader fx = new FXMLLoader(getClass().getResource("/gui/" + resourceFile));
fx.setController(controller);
Parent root = fx.load();
Scene scene = new Scene(root, width, height);
pstage.setScene(scene);
pstage.resizableProperty().setValue(false);
pstage.getIcons().add(new Image(getClass().getResource("/icoico.png").toString()));
pstage.show();
pstage.setTitle("Sokoban");
Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
pstage.setX((primScreenBounds.getWidth() - pstage.getWidth()) / 2);
pstage.setY((primScreenBounds.getHeight() - pstage.getHeight()) / 2);
return pstage;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Initialiseert de images van het spel
* 0 muur
* 1 veld
* 2 speler
* 3 kist
* 4 doel
* @return Geeft een image arraylist terug met alle images van het spel.
*/
public Image[] initImages() {
Image[] images = new Image[5];
images[0] = new Image("https://www.beautycolorcode.com/666a6d.png", 40, 40, false, false);
images[1] = new Image("https://sherwin.scene7.com/is/image/sw/color-swatch?_tparam_size=250,250&layer=comp&_tparam_color=C2C0BB", 40, 40, false, false);
//images[2] = new Image("https://miro.medium.com/max/400/1*XAksToqI3TyMLhcszTCmhg.png", 40, 40, false, false);
images[2] = new Image(getClass().getResource("/mannetje.png").toString(), 40, 40, false, false);
images[3] = new Image("http://pixelartmaker.com/art/200ea90c01a0a17.png", 40, 40, false, false);
images[4] = new Image("https://ak.picdn.net/shutterstock/videos/2913229/thumb/3.jpg", 40, 40, false, false);
return images;
}
/**
* Toont een alert op het scherm met showAndWait()
* @param Header text
* @param Text
* @param alertType
*/
public void showAlert(String header, String context, AlertType alertType) {
Alert a = new Alert(alertType);
a.setTitle("Sokoban");
a.setHeaderText(header);
a.setContentText(context);
a.showAndWait();
}
/**
* Herstart het opgegeven level
* @param levelNaam
*/
public void restartLevel(String levelNaam) {
huidigSpel = spelRepository.restartLevel(huidigSpel.getNaam(), levelNaam);
}
/**
* Checkt of het wachtwoord geldig is
* @param wachtwoord
*
* @return Geeft true terug als het een geldig wachtwoord is
*/
public boolean checkPassword(String str) {
char ch;
boolean hoofdletterFlag = false;
boolean kleineletterFlag = false;
boolean nummerFlag = false;
for(int i=0;i < str.length();i++) {
ch = str.charAt(i);
if( Character.isDigit(ch)) {
nummerFlag = true;
}
else if (Character.isUpperCase(ch)) {
hoofdletterFlag = true;
} else if (Character.isLowerCase(ch)) {
kleineletterFlag = true;
}
if(nummerFlag && hoofdletterFlag && kleineletterFlag)
return true;
}
return false;
}
} | BatLine/Sokoban | src/domein/DomeinController.java | 4,712 | /**
* Geeft de gebruikersnaam van de huidige speler terug.
* @return Geeft de gebruikersnaam van de huidige speler terug.
*/ | block_comment | nl | package domein;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import exceptions.AccountException;
import exceptions.SpelMakenException;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* De hoofd domain klasse
*
* @author Gilles De Pessemier, Rune De Bruyne, Aaron Everaert, Chiel Meneve
*
*/
public class DomeinController
{
private final SpelerRepository spelerRepository;
private final SpelRepository spelRepository;
private Speler huidigeSpeler;
private Spel huidigSpel;
private ResourceBundle rb = ResourceBundle.getBundle("languages/resource_bundle", Locale.getDefault());
/**
* Domeincontroller constructor
*/
public DomeinController() {
spelerRepository = new SpelerRepository();
spelRepository = new SpelRepository();
}
/**
* Geeft de resourcebundel terug
* @return Geeft de correcte resourcebundel terug
*/
public ResourceBundle getResourceBundle() {
return rb;
}
/**
* Geeft terug of de gebruik adminrights heeft of niet
* @return Geeft terug of de gebruik adminrights heeft of niet
*/
public boolean isAdmin() {
return huidigeSpeler.isAdmin();
}
/**
* Meld een speler aan
* @param ingegeven gebruikersNaam
* @param ingegeven wachtwoord
*
* @exception AccountException
*/
public void aanmeldenSpeler(String gebruikersNaam, String wachtwoord) {
Speler gevondenSpeler = spelerRepository.geefSpeler(gebruikersNaam, wachtwoord);
if (gevondenSpeler != null) {
setSpeler(gevondenSpeler);
} else {
throw new AccountException(rb.getString("geengebruikergevonden"));
}
}
/**
* Registreert een nieuwe speler
* @param achternaam
* @param voornaam
* @param gebruikersNaam
* @param wachtwoord
* @param wachtwoordBevestiging
*
* @exception AccountException
*/
public void registreerSpeler(String naam, String voornaam, String gebruikersNaam, String wachtwoord, String wachtwoord2) {
if (!wachtwoord.equals(wachtwoord2)) { throw new AccountException(rb.getString("wachtwoordenkomennietovereen")); }
Speler nieuweSpeler = new Speler(naam, voornaam, gebruikersNaam, wachtwoord, false);
setSpeler(nieuweSpeler);
spelerRepository.voegSpelerToe(nieuweSpeler);
}
/**
* Geeft de namen van alle spellen terug
* @return Geeft de namen van alle spellen terug
*/
public String[] geefSpelnamen() {
return spelRepository.geefAlleSpelnamen();
}
/**
* Kiest een gekozen spel
* @param Heeft de spelNaam nodig om te kiezen
*/
public void kiesSpel(String spelNaam) {
huidigSpel = spelRepository.kiesSpel(spelNaam);
}
/**
* Geeft true terug als het level compleet is, anders false
* @param Heeft de levelNaam nodig om te kijken als het level voltooid is
*
* @return Geeft true terug als het level compleet is, anders false
*/
public boolean voltooiSpelbord(String levelNaam) {
return huidigSpel.isLevelCompleet(levelNaam);
}
/**
* Verplaatst een speler
* @param Heeft richting nodig om de speler te kunnen verplaatsen
*/
public void verplaatsSpeler(String richting) {
huidigSpel.verplaatsSpeler(richting);
}
/**
* Geeft het aantal verplaatsingen van dat level terug
* @param spelNaam om het spel te vinden
* @param levelNaam om het level te vinden
*
* @return Geeft het aantal verplaatsingen van dat level terug
*/
public int getAantalVerplaatsingen() {
return huidigSpel.getAantalVerplaatsingen();
}
/**
* Geeft een 3D String array terug met alle vakken hun vakinfo
* @param Heeft de levelNaam nodig voor het vinden van alle vakken
*
* @return Geeft een 3D String array terug met alle vakken hun vakinfo
*/
public String[][] getAlleVakken(String levelNaam) {
huidigSpel.setHuidigLevel(levelNaam);
Vak[][] vakken = huidigSpel.getAlleVakken();
String[][] result = new String[vakken.length * vakken[0].length][4];
int intTeller = 0;
for (Vak[] rij : vakken) {
for (Vak v : rij) {
if (v != null)
result[intTeller] = v.getVakInfo();
intTeller++;
}
}
return result;
}
/**
* Maakt een nieuw spel aan
* @param Heeft de spelNaam nodig
*
* @exception SpelMakenException
*/
public void maakNieuwSpel(String spelNaam) {
if (spelNaam.contains(" "))
throw new SpelMakenException(rb.getString("geenspatiesinnaam"));
for (String s : spelRepository.geefAlleSpelnamen())
if (s.equals(spelNaam))
throw new SpelMakenException(rb.getString("naambestaatal"));
spelRepository.maakNieuwSpel(spelNaam, huidigeSpeler.getGebruikersnaam());
huidigSpel = spelRepository.kiesSpel(spelNaam);
}
/**
* Geeft de creatiebevestiging terug
* @return Geeft de creatiebevestiging terug
*/
public String getCreatieBevestiging() {
return String.format(rb.getString("creatiebevestiging"), huidigSpel.getNaam(), huidigSpel.getAantalSpelborden());
}
/**
* Maakt een nieuw spelbord
*/
public void maakNieuwSpelbord() {
spelRepository.maakNieuwSpelbord(huidigSpel);
}
/**
* Stelt de huidige speler in
* @param Heeft de speler nodig om in te stellen
*/
private void setSpeler(Speler speler) { this.huidigeSpeler = speler; }
/**
* Geeft het aantal levels van het huidige spelbord terug
* @return Geeft het aantal levels van het huidige spelbord terug
*/
public int getAantalLevels() { return huidigSpel.getAantalSpelborden(); }
/**
* Geeft de voltooiSpelbordSummary terug
* @param Heeft de levelNaam nodig voor het spelbord te vinden
*
* @return Geeft de voltooiSpelbordSummary terug
*/
public String voltooiSpelbordSummary(String levelNaam) {
return String.format(rb.getString("voltooispelbordsummary"), huidigSpel.getAantalVoltooideSpelborden(), getAantalLevels());
}
/**
* Update een vak in de repository en de database
* @param xcoord voor de x coordinaat
* @param ycoord voor de y coordinaat
* @param nieuwType voor het nieuwe type
* @param isDoel voor te weten als het vak een doel is
*/
public void updateVak(int xcoord, int ycoord, String nieuwType, boolean isDoel) {
huidigSpel.updateVak(xcoord, ycoord, nieuwType, isDoel);
spelRepository.updateVak(xcoord, ycoord, nieuwType, isDoel, huidigSpel);
}
/**
* Geeft het aantal spelborden terug in een string array
* @param Heeft de spelNaam nodig om een spel te kunnen wijzigen
* @return Geeft het aantal spelborden terug in een string array
*/
public String[] wijzigSpel(String spelNaam) {
kiesSpel(spelNaam);
int aantalSpelborden = huidigSpel.getAantalSpelborden();
String[] result = new String[aantalSpelborden];
for (int i = 1; i <= aantalSpelborden; i++)
result[i-1]= String.valueOf(i);
return result;
}
/**
* Update een vak in de repository
* @param xcoord voor de x coordinaat
* @param ycoord voor de y coordinaat
* @param nieuwType voor het nieuwe type
* @param isDoel voor te weten als het vak een doel is
* @param spelbordNr om te weten over welk spelbord het gaat
*/
public void vernieuwVak(int xcoord, int ycoord, String nieuwType, boolean isDoel, String spelbordNr) {
spelRepository.updateVak(xcoord, ycoord, nieuwType, isDoel, huidigSpel);
}
/**
* Geeft het voltooispel bericht terug
* @return Geeft het voltooispel bericht terug
*/
public String voltooiWijzigSpel() {
return String.format(rb.getString("voltooiwijzigspelsummary"), huidigSpel.getNaam());
}
/**
* Geeft het verwijderbevestigingsbericht terug
* @param Heeft de levelNaam nodig om het level te vinden
*
* @return Geeft het verwijderbevestigingsbericht terug
*/
public String verwijderLevel(String levelNaam) {
spelRepository.verwijderLevel(huidigSpel, levelNaam);
huidigSpel.verwijderLevel(levelNaam);
return String.format(rb.getString("verwijderlevelbevestiging"), levelNaam, huidigSpel.getNaam());
}
/**
* Verwijderd spel en geeft een melding terug
* @param Heeft de spelNaam nodig om het spel te vinden
*
* @return Geeft het verwijderbevestigingsbericht terug
*/
public String verwijderSpel(String spelNaam) {
spelRepository.verwijderSpel(spelNaam);
return String.format(rb.getString("verwijderspelbevestiging"), spelNaam);
}
/**
* ResourceBundle updaten
*/
public void updateLanguage() {
rb = ResourceBundle.getBundle("languages/resource_bundle", Locale.getDefault());
}
/**
* Geeft terug of de input null, whitespace of empty is
* @param String
*
* @return Geeft terug of de input null, whitespace of empty is
*/
public boolean isNullOrWhitespaceOrEmpty(String s) {
return s == null || isWhitespace(s) || s.length() == 0;
}
private boolean isWhitespace(String s) {
int length = s.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
return false;
}
/**
* Geeft de gebruikersnaam<SUF>*/
public String geefGebruikersnaam() {
return huidigeSpeler.getGebruikersnaam();
}
/**
* Toont een nieuwe stage en geeft deze terug.
* @param resourceFile in de package gui
* @param FX Controller
* @param Primary stage
* @param Stage width
* @param Stage height
*
* @return geeft de huidige stage terug
*/
public Stage initialize(String resourceFile, Object controller, Stage pstage, double width, double height) {
try {
FXMLLoader fx = new FXMLLoader(getClass().getResource("/gui/" + resourceFile));
fx.setController(controller);
Parent root = fx.load();
Scene scene = new Scene(root, width, height);
pstage.setScene(scene);
pstage.resizableProperty().setValue(false);
pstage.getIcons().add(new Image(getClass().getResource("/icoico.png").toString()));
pstage.show();
pstage.setTitle("Sokoban");
Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
pstage.setX((primScreenBounds.getWidth() - pstage.getWidth()) / 2);
pstage.setY((primScreenBounds.getHeight() - pstage.getHeight()) / 2);
return pstage;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Initialiseert de images van het spel
* 0 muur
* 1 veld
* 2 speler
* 3 kist
* 4 doel
* @return Geeft een image arraylist terug met alle images van het spel.
*/
public Image[] initImages() {
Image[] images = new Image[5];
images[0] = new Image("https://www.beautycolorcode.com/666a6d.png", 40, 40, false, false);
images[1] = new Image("https://sherwin.scene7.com/is/image/sw/color-swatch?_tparam_size=250,250&layer=comp&_tparam_color=C2C0BB", 40, 40, false, false);
//images[2] = new Image("https://miro.medium.com/max/400/1*XAksToqI3TyMLhcszTCmhg.png", 40, 40, false, false);
images[2] = new Image(getClass().getResource("/mannetje.png").toString(), 40, 40, false, false);
images[3] = new Image("http://pixelartmaker.com/art/200ea90c01a0a17.png", 40, 40, false, false);
images[4] = new Image("https://ak.picdn.net/shutterstock/videos/2913229/thumb/3.jpg", 40, 40, false, false);
return images;
}
/**
* Toont een alert op het scherm met showAndWait()
* @param Header text
* @param Text
* @param alertType
*/
public void showAlert(String header, String context, AlertType alertType) {
Alert a = new Alert(alertType);
a.setTitle("Sokoban");
a.setHeaderText(header);
a.setContentText(context);
a.showAndWait();
}
/**
* Herstart het opgegeven level
* @param levelNaam
*/
public void restartLevel(String levelNaam) {
huidigSpel = spelRepository.restartLevel(huidigSpel.getNaam(), levelNaam);
}
/**
* Checkt of het wachtwoord geldig is
* @param wachtwoord
*
* @return Geeft true terug als het een geldig wachtwoord is
*/
public boolean checkPassword(String str) {
char ch;
boolean hoofdletterFlag = false;
boolean kleineletterFlag = false;
boolean nummerFlag = false;
for(int i=0;i < str.length();i++) {
ch = str.charAt(i);
if( Character.isDigit(ch)) {
nummerFlag = true;
}
else if (Character.isUpperCase(ch)) {
hoofdletterFlag = true;
} else if (Character.isLowerCase(ch)) {
kleineletterFlag = true;
}
if(nummerFlag && hoofdletterFlag && kleineletterFlag)
return true;
}
return false;
}
} |
91761_5 | package ui;
import java.util.*;
class Auteur {
private String naam, voornaam;
public Auteur(String naam, String voornaam) {
setNaam(naam);
setVoornaam(voornaam);
}
public String getNaam() {
return naam;
}
public String getVoornaam() {
return voornaam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setVoornaam(String voornaam) {
this.voornaam = voornaam;
}
@Override
public String toString() {
return String.format("%s %s", naam, voornaam);
}
}
public class OefMap_opgave {
public OefMap_opgave() {
// we zullen een hashmap gebruiken waarbij auteursid de sleutel is en
// de waarde is naam en voornaam van Auteur.
//Cre�er de lege hashMap "auteurs"; de sleutel is van type Integer, de waarde van type Auteur
Map<Integer, Auteur> auteurs = new HashMap<>();
//----------------------------------------------------------------------------------
//Voeg toe aan de hashmap: auteursID = 9876, naam = Gosling, voornaam = James
//Voeg toe aan de hashmap: auteursID = 5648, naam = Chapman, voornaam = Steve
auteurs.put(9876, new Auteur("Gosling", "James"));
auteurs.put(5648, new Auteur("Chapman", "Steve"));
auteurs.put(1233, new Auteur("Doe", "John"));
//-------------------------------------------------------------------------------
//Wijzig de voornaam van Chapman: John ipv Steve4
String teZoeknNaam = "Chapman";
String teVeranderenVoornaam = "John";
for (Map.Entry<Integer, Auteur> ingang : auteurs.entrySet()) {
if (ingang.getValue().getNaam() == teZoeknNaam) {
ingang.getValue().setNaam(teVeranderenVoornaam);
break;
}
}
//----------------------------------------------
//Komt de auteursID 1234 voor in de hashmap
//-----------------------------------------
Integer teZoekenKey = 1234;
if (auteurs.containsKey(teZoekenKey)) {
System.out.println("--- Zoek auteur: ");
System.out.println("auteursID 1234 komt voor\n");
} else {
System.out.println("--- Zoek auteur: ");
System.out.println("auteursID 1234 komt niet voor\n");
}
//Toon de naam en voornaam van auteursID 5648
//-------------------------------------------
Auteur auteur = auteurs.get(5648);
if (auteur != null) {
System.out.println("--- Zoek auteur: ");
System.out.println(auteur);
}
toonAlleAuteurs(auteurs);
//Alle auteursID's worden in stijgende volgorde weergegeven.
// 1) de hashMap kopiëren naar een treeMap (= 1 instructie)
// 2) roep de methode toonAlleSleutels op.
toonAlleSleutels(auteurs);
//---------------------------------------------------------------
}
public void toonAlleSleutels(Map<Integer, Auteur> map) {
System.out.println("--- toonAlleSleutels");
//Alle sleutels van de map worden op het scherm weergegeven.
// Stap 1: Kopiëren naar een TreeMap voor gesorteerde sleutels
TreeMap<Integer, Auteur> gesorteerdeMap = new TreeMap<>(map);
for (Integer sleutel : gesorteerdeMap.keySet()) {
System.out.println("AuteursID: " + sleutel);
}
//---------------------------------------------------------------
System.out.println();
}
public void toonAlleAuteurs(Map<Integer, Auteur> map) {
System.out.println("--- toonAlleAuteurs");
/*Alle gegevens van de map worden op het scherm weergegeven.
Per lijn wordt een auteursnr, naam en voornaam weergegeven.*/
map.forEach((key, value) -> System.out.printf("%d, %S, %s%n", key, value.getNaam(), value
.getVoornaam()));
//---------------------------------------------------------------
System.out.println();
}
public static void main(String args[]) {
new OefMap_opgave();
}
}
| Bataklik/ASD1.0_DesignMaze | Map/ASDI_Java_Map_Oefeningen/src/ui/OefMap_opgave.java | 1,333 | //Wijzig de voornaam van Chapman: John ipv Steve4
| line_comment | nl | package ui;
import java.util.*;
class Auteur {
private String naam, voornaam;
public Auteur(String naam, String voornaam) {
setNaam(naam);
setVoornaam(voornaam);
}
public String getNaam() {
return naam;
}
public String getVoornaam() {
return voornaam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setVoornaam(String voornaam) {
this.voornaam = voornaam;
}
@Override
public String toString() {
return String.format("%s %s", naam, voornaam);
}
}
public class OefMap_opgave {
public OefMap_opgave() {
// we zullen een hashmap gebruiken waarbij auteursid de sleutel is en
// de waarde is naam en voornaam van Auteur.
//Cre�er de lege hashMap "auteurs"; de sleutel is van type Integer, de waarde van type Auteur
Map<Integer, Auteur> auteurs = new HashMap<>();
//----------------------------------------------------------------------------------
//Voeg toe aan de hashmap: auteursID = 9876, naam = Gosling, voornaam = James
//Voeg toe aan de hashmap: auteursID = 5648, naam = Chapman, voornaam = Steve
auteurs.put(9876, new Auteur("Gosling", "James"));
auteurs.put(5648, new Auteur("Chapman", "Steve"));
auteurs.put(1233, new Auteur("Doe", "John"));
//-------------------------------------------------------------------------------
//Wijzig de<SUF>
String teZoeknNaam = "Chapman";
String teVeranderenVoornaam = "John";
for (Map.Entry<Integer, Auteur> ingang : auteurs.entrySet()) {
if (ingang.getValue().getNaam() == teZoeknNaam) {
ingang.getValue().setNaam(teVeranderenVoornaam);
break;
}
}
//----------------------------------------------
//Komt de auteursID 1234 voor in de hashmap
//-----------------------------------------
Integer teZoekenKey = 1234;
if (auteurs.containsKey(teZoekenKey)) {
System.out.println("--- Zoek auteur: ");
System.out.println("auteursID 1234 komt voor\n");
} else {
System.out.println("--- Zoek auteur: ");
System.out.println("auteursID 1234 komt niet voor\n");
}
//Toon de naam en voornaam van auteursID 5648
//-------------------------------------------
Auteur auteur = auteurs.get(5648);
if (auteur != null) {
System.out.println("--- Zoek auteur: ");
System.out.println(auteur);
}
toonAlleAuteurs(auteurs);
//Alle auteursID's worden in stijgende volgorde weergegeven.
// 1) de hashMap kopiëren naar een treeMap (= 1 instructie)
// 2) roep de methode toonAlleSleutels op.
toonAlleSleutels(auteurs);
//---------------------------------------------------------------
}
public void toonAlleSleutels(Map<Integer, Auteur> map) {
System.out.println("--- toonAlleSleutels");
//Alle sleutels van de map worden op het scherm weergegeven.
// Stap 1: Kopiëren naar een TreeMap voor gesorteerde sleutels
TreeMap<Integer, Auteur> gesorteerdeMap = new TreeMap<>(map);
for (Integer sleutel : gesorteerdeMap.keySet()) {
System.out.println("AuteursID: " + sleutel);
}
//---------------------------------------------------------------
System.out.println();
}
public void toonAlleAuteurs(Map<Integer, Auteur> map) {
System.out.println("--- toonAlleAuteurs");
/*Alle gegevens van de map worden op het scherm weergegeven.
Per lijn wordt een auteursnr, naam en voornaam weergegeven.*/
map.forEach((key, value) -> System.out.printf("%d, %S, %s%n", key, value.getNaam(), value
.getVoornaam()));
//---------------------------------------------------------------
System.out.println();
}
public static void main(String args[]) {
new OefMap_opgave();
}
}
|
24068_3 | package resources;
import java.util.ArrayList;
// Linear
public class Linear extends Scurve{
protected int dimension;
protected int width;
protected int height;
protected int size;
public Linear(GhidraSrc cantordust){
super(cantordust);
this.type = "linear";
}
public Linear(GhidraSrc cantordust, int dimension, double size) {
super(cantordust);
this.type = "linear";
this.cantordust.cdprint("checking zig zag size.\n");
double x = Math.ceil(Math.pow(size, 1/(double)dimension));
// double y = Math.pow(x, dimension);
if(!(Math.pow(x, dimension) == size)){
throw new Error("Size does not fit a square Linear curve");
}
this.dimension = dimension;
this.size = (int)x;
this.width = this.size;
this.height = this.size;
}
@Override
public void setWidth(int width){
this.width = width;
}
@Override
public void setHeight(int height){
this.height = height;
}
@Override
public int getWidth(){
return this.width;
}
@Override
public int getHeight(){
return this.height;
}
@Override
public int getLength(){
return (int)Math.pow(this.size, this.dimension);
}
@Override
public TwoIntegerTuple dimensions(){
/*
Size of this curve in each dimension.
*/
return new TwoIntegerTuple(this.width, this.height);
}
@Override
public int index(TwoIntegerTuple p){
int idx = 0;
boolean flip = false;
int fi;
ArrayList<Integer> arrlist = new ArrayList<Integer>(2);
p.reverse();
arrlist.add(p.get(0));
arrlist.add(p.get(1));
for(int power=0;power<2;power++){
int i = arrlist.get(power);
power = this.dimension-power-1;
if(flip){
fi = this.size-i-1;
} else{
fi = i;
}
int v = fi * (int)Math.pow(this.size, power);
idx += v;
if(i%2==1){
flip = !flip;
}
}
return idx;
}
@Override
public TwoIntegerTuple point(int idx){
// cantordust.cdprint("\n----\n");
// TwoIntegerTuple p = new TwoIntegerTuple();
ArrayList<Integer> arrlist = new ArrayList<Integer>(2);
boolean flip = false;
for(int i=this.dimension-1;i>-1;i-=1){
int v = idx/(int)(Math.pow(this.size, i));
if(i>0){
idx = idx - (int)(Math.pow(this.size, i)*v);
}
if(flip){
v = this.size-1-v;
}
arrlist.add((int)v);
if(v%2==1){
flip = !flip;
}
}
TwoIntegerTuple p = new TwoIntegerTuple(arrlist.get(0), arrlist.get(1));
p.reverse();
// cantordust.cdprint("p: "+p.get(0)+", "+p.get(1)+"\n");
return p;
}
} | Battelle/cantordust | resources/Linear.java | 934 | // cantordust.cdprint("p: "+p.get(0)+", "+p.get(1)+"\n"); | line_comment | nl | package resources;
import java.util.ArrayList;
// Linear
public class Linear extends Scurve{
protected int dimension;
protected int width;
protected int height;
protected int size;
public Linear(GhidraSrc cantordust){
super(cantordust);
this.type = "linear";
}
public Linear(GhidraSrc cantordust, int dimension, double size) {
super(cantordust);
this.type = "linear";
this.cantordust.cdprint("checking zig zag size.\n");
double x = Math.ceil(Math.pow(size, 1/(double)dimension));
// double y = Math.pow(x, dimension);
if(!(Math.pow(x, dimension) == size)){
throw new Error("Size does not fit a square Linear curve");
}
this.dimension = dimension;
this.size = (int)x;
this.width = this.size;
this.height = this.size;
}
@Override
public void setWidth(int width){
this.width = width;
}
@Override
public void setHeight(int height){
this.height = height;
}
@Override
public int getWidth(){
return this.width;
}
@Override
public int getHeight(){
return this.height;
}
@Override
public int getLength(){
return (int)Math.pow(this.size, this.dimension);
}
@Override
public TwoIntegerTuple dimensions(){
/*
Size of this curve in each dimension.
*/
return new TwoIntegerTuple(this.width, this.height);
}
@Override
public int index(TwoIntegerTuple p){
int idx = 0;
boolean flip = false;
int fi;
ArrayList<Integer> arrlist = new ArrayList<Integer>(2);
p.reverse();
arrlist.add(p.get(0));
arrlist.add(p.get(1));
for(int power=0;power<2;power++){
int i = arrlist.get(power);
power = this.dimension-power-1;
if(flip){
fi = this.size-i-1;
} else{
fi = i;
}
int v = fi * (int)Math.pow(this.size, power);
idx += v;
if(i%2==1){
flip = !flip;
}
}
return idx;
}
@Override
public TwoIntegerTuple point(int idx){
// cantordust.cdprint("\n----\n");
// TwoIntegerTuple p = new TwoIntegerTuple();
ArrayList<Integer> arrlist = new ArrayList<Integer>(2);
boolean flip = false;
for(int i=this.dimension-1;i>-1;i-=1){
int v = idx/(int)(Math.pow(this.size, i));
if(i>0){
idx = idx - (int)(Math.pow(this.size, i)*v);
}
if(flip){
v = this.size-1-v;
}
arrlist.add((int)v);
if(v%2==1){
flip = !flip;
}
}
TwoIntegerTuple p = new TwoIntegerTuple(arrlist.get(0), arrlist.get(1));
p.reverse();
// cantordust.cdprint("p: "+p.get(0)+",<SUF>
return p;
}
} |