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
|
---|---|---|---|---|---|---|---|---|
23677_4 | package qwirkle;
import java.util.ArrayList;
public class TestMove {
private Tile[][] fields;
private Tile[] hand;
private int[][] move;
private int score;
private char typeRow;
private int nrOfMoves;
private boolean isConnected = false; //checks whether the move is connnected to tiles already on the board
private boolean isFirstMove = false;
public TestMove(Board board, int[][] move, Tile[] hand) {
Board b = board;
fields = board.getBoard();
this.move = move;
this.hand = hand; // nu nog niet nodig, later wel lijkt me
int i = 0;
isFirstMove = (fields[50][50] == null);
while (move[i][0] != -1 && i < 6) {
nrOfMoves++;
b.setField(move[i][0], move[i][1], hand[move[i][2]]);
i++;
}
}
public boolean isLegalMove() { // mag maar in rij/kolom & moet andere stenen raken
if (move[0][0] == -1) {
return false;
}
if (move[0][0] == move[1][0]) { // moves met zelfde x-waarde
int i = 2;
while (move[i][0] != -1) {
if (move[i][0] != move[0][0]) {
return false; // niet allemaal zelfde x-waarde
}
i++;
}
typeRow = 'x';
if (!testVertical(move[0][0],move[0][1],
fields[move[0][0]][move[0][1]].getColor(),fields[move[0][0]][move[0][1]].getShape())) {
return false;
}
} else if (move[0][1] == move[1][1]) { // moves met zelfde y-waarde
int i = 2;
while (move[i][0] != -1) {
if (move[i][1] != move[0][1]) {
return false; // niet allemaal zelfde y-waarde
}
i++;
}
typeRow = 'y';
if (!testHorizontal(move[0][0],move[0][1],
fields[move[0][0]][move[0][1]].getColor(),fields[move[0][0]][move[0][1]].getShape())) {
return false;
}
} else if (move[1][0] == -1) { // maar 1 zet
typeRow = 'z';
}
if (typeRow == 'x') {
int i = 0;
while (move[i][0] != -1) {
if (!testHorizontal(move[i][0],move[i][1],
fields[move[i][0]][move[i][1]].getColor(),fields[move[i][0]][move[i][1]].getShape())) {
return false;
}
i++;
}
return true;
} else if (typeRow == 'y') {
int i = 0;
while (move[i][0] != -1) {
if (!testVertical(move[i][0],move[i][1],
fields[move[i][0]][move[i][1]].getColor(),fields[move[i][0]][move[i][1]].getShape())) {
return false;
}
i++;
}
} else if (typeRow == 'z') {
Tile.Color color = fields[move[0][0]][move[0][1]].getColor();
Tile.Shape shape = fields[move[0][0]][move[0][1]].getShape();
return (testHorizontal(move[0][0],move[0][1],color,shape)&& testVertical(move[0][0],move[0][1],color,shape) && isConnected);
}
return false;
}
public int getScore() {
return score;
}
public boolean testHorizontal(int xValue, int yValue, Tile.Color color, Tile.Shape shape) {
int easternTiles = 0;
char typeOfRow = ' ';
ArrayList<Tile.Color> colors = new ArrayList<Tile.Color>();
colors.add(color);
ArrayList<Tile.Shape> shapes = new ArrayList<Tile.Shape>();
shapes.add(shape);
boolean doorgaan = true;
int c = 0; //counter
while (doorgaan) { // omhoog kijken
c++;
if (!(fields[xValue+c][yValue] == null)) { // kijken of vakje leeg is
if (fields[xValue+c][yValue].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue+c][yValue].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C'; // rij van het type Color
shapes.add(fields[xValue+c][yValue].getShape());
} else if (fields[xValue+c][yValue].getShape().equals(shape)
&& !(colors.contains(fields[xValue+c][yValue].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue+c][yValue].getColor());
} else {
return false;
}
}
doorgaan = false; // stoppen met zoeken als de steen leeg is
}
easternTiles = c - 1;
c = 0; //counter reset
doorgaan = true;
while (doorgaan) { //omlaag
c++;
if (!(fields[xValue-c][yValue] == null)) {
if (fields[xValue-c][yValue].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue-c][yValue].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C';
shapes.add(fields[xValue-c][yValue].getShape());
} else if (fields[xValue-c][yValue].getShape().equals(shape)
&& !(colors.contains(fields[xValue-c][yValue].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue-c][yValue].getColor());
} else {
return false;
}
} else {
doorgaan = false;
}
}
if (c + easternTiles < 6 && c+easternTiles > 1) {
score += c + easternTiles;
} else if (c+easternTiles == 6) {
score += 12;
}
if (typeRow == 'x' && c+easternTiles > 1) {
isConnected = true;
} else if (typeRow == 'y' && c+easternTiles > nrOfMoves) {
isConnected = true;
} else if (typeRow == 'z' && c+easternTiles > 1) {
isConnected = true;
} else if (isFirstMove && fields[50][50]!= null) {
isConnected = true;
}
return true;
}
public boolean testVertical(int xValue, int yValue, Tile.Color color, Tile.Shape shape) {
int northernTiles = 0;
char typeOfRow = ' ';
ArrayList<Tile.Color> colors = new ArrayList<Tile.Color>();
colors.add(color);
ArrayList<Tile.Shape> shapes = new ArrayList<Tile.Shape>();
shapes.add(shape);
boolean doorgaan = true;
int c = 0; //counter
while (doorgaan) { // omhoog kijken
c++;
if (!(fields[xValue][yValue + c] == null)) { // kijken of vakje leeg is
if (fields[xValue][yValue + c].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue][yValue + c].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C';
shapes.add(fields[xValue][yValue + c].getShape());
} else if (fields[xValue][yValue + c].getShape().equals(shape)
&& !(colors.contains(fields[xValue][yValue + c].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue][yValue + c].getColor());
} else {
return false;
}
} else {
doorgaan = false;
}
}
northernTiles = c - 1;
c = 0; //counter reset
doorgaan = true;
while (doorgaan) { //omlaag
c++;
if (!(fields[xValue][yValue - c] == null)) {
if (fields[xValue][yValue - c].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue][yValue - c].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C';
shapes.add(fields[xValue][yValue - c].getShape());
} else if (fields[xValue][yValue - c].getShape().equals(shape)
&& !(colors.contains(fields[xValue][yValue - c].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue][yValue - c].getColor());
} else {
return false;
}
} else {
doorgaan = false;
}
}
if (typeRow == 'y' && c + northernTiles > 1) {
isConnected = true;
} else if (typeRow == 'x' && c+northernTiles > nrOfMoves) {
isConnected = true;
} else if (typeRow == 'z' && c+northernTiles > 1) {
isConnected = true;
} else if (isFirstMove && fields[50][50]!= null) {
isConnected = true;
}
if (c+northernTiles < 6 && c+northernTiles > 1) {
score += c+northernTiles;
} else if (c+northernTiles == 6) {
score += 12;
}
return true;
}
}
| MerijnKleinreesink/SoftwareSystemen | ExtraTest/src/qwirkle/TestMove.java | 2,990 | // niet allemaal zelfde x-waarde
| line_comment | nl | package qwirkle;
import java.util.ArrayList;
public class TestMove {
private Tile[][] fields;
private Tile[] hand;
private int[][] move;
private int score;
private char typeRow;
private int nrOfMoves;
private boolean isConnected = false; //checks whether the move is connnected to tiles already on the board
private boolean isFirstMove = false;
public TestMove(Board board, int[][] move, Tile[] hand) {
Board b = board;
fields = board.getBoard();
this.move = move;
this.hand = hand; // nu nog niet nodig, later wel lijkt me
int i = 0;
isFirstMove = (fields[50][50] == null);
while (move[i][0] != -1 && i < 6) {
nrOfMoves++;
b.setField(move[i][0], move[i][1], hand[move[i][2]]);
i++;
}
}
public boolean isLegalMove() { // mag maar in rij/kolom & moet andere stenen raken
if (move[0][0] == -1) {
return false;
}
if (move[0][0] == move[1][0]) { // moves met zelfde x-waarde
int i = 2;
while (move[i][0] != -1) {
if (move[i][0] != move[0][0]) {
return false; // niet allemaal<SUF>
}
i++;
}
typeRow = 'x';
if (!testVertical(move[0][0],move[0][1],
fields[move[0][0]][move[0][1]].getColor(),fields[move[0][0]][move[0][1]].getShape())) {
return false;
}
} else if (move[0][1] == move[1][1]) { // moves met zelfde y-waarde
int i = 2;
while (move[i][0] != -1) {
if (move[i][1] != move[0][1]) {
return false; // niet allemaal zelfde y-waarde
}
i++;
}
typeRow = 'y';
if (!testHorizontal(move[0][0],move[0][1],
fields[move[0][0]][move[0][1]].getColor(),fields[move[0][0]][move[0][1]].getShape())) {
return false;
}
} else if (move[1][0] == -1) { // maar 1 zet
typeRow = 'z';
}
if (typeRow == 'x') {
int i = 0;
while (move[i][0] != -1) {
if (!testHorizontal(move[i][0],move[i][1],
fields[move[i][0]][move[i][1]].getColor(),fields[move[i][0]][move[i][1]].getShape())) {
return false;
}
i++;
}
return true;
} else if (typeRow == 'y') {
int i = 0;
while (move[i][0] != -1) {
if (!testVertical(move[i][0],move[i][1],
fields[move[i][0]][move[i][1]].getColor(),fields[move[i][0]][move[i][1]].getShape())) {
return false;
}
i++;
}
} else if (typeRow == 'z') {
Tile.Color color = fields[move[0][0]][move[0][1]].getColor();
Tile.Shape shape = fields[move[0][0]][move[0][1]].getShape();
return (testHorizontal(move[0][0],move[0][1],color,shape)&& testVertical(move[0][0],move[0][1],color,shape) && isConnected);
}
return false;
}
public int getScore() {
return score;
}
public boolean testHorizontal(int xValue, int yValue, Tile.Color color, Tile.Shape shape) {
int easternTiles = 0;
char typeOfRow = ' ';
ArrayList<Tile.Color> colors = new ArrayList<Tile.Color>();
colors.add(color);
ArrayList<Tile.Shape> shapes = new ArrayList<Tile.Shape>();
shapes.add(shape);
boolean doorgaan = true;
int c = 0; //counter
while (doorgaan) { // omhoog kijken
c++;
if (!(fields[xValue+c][yValue] == null)) { // kijken of vakje leeg is
if (fields[xValue+c][yValue].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue+c][yValue].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C'; // rij van het type Color
shapes.add(fields[xValue+c][yValue].getShape());
} else if (fields[xValue+c][yValue].getShape().equals(shape)
&& !(colors.contains(fields[xValue+c][yValue].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue+c][yValue].getColor());
} else {
return false;
}
}
doorgaan = false; // stoppen met zoeken als de steen leeg is
}
easternTiles = c - 1;
c = 0; //counter reset
doorgaan = true;
while (doorgaan) { //omlaag
c++;
if (!(fields[xValue-c][yValue] == null)) {
if (fields[xValue-c][yValue].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue-c][yValue].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C';
shapes.add(fields[xValue-c][yValue].getShape());
} else if (fields[xValue-c][yValue].getShape().equals(shape)
&& !(colors.contains(fields[xValue-c][yValue].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue-c][yValue].getColor());
} else {
return false;
}
} else {
doorgaan = false;
}
}
if (c + easternTiles < 6 && c+easternTiles > 1) {
score += c + easternTiles;
} else if (c+easternTiles == 6) {
score += 12;
}
if (typeRow == 'x' && c+easternTiles > 1) {
isConnected = true;
} else if (typeRow == 'y' && c+easternTiles > nrOfMoves) {
isConnected = true;
} else if (typeRow == 'z' && c+easternTiles > 1) {
isConnected = true;
} else if (isFirstMove && fields[50][50]!= null) {
isConnected = true;
}
return true;
}
public boolean testVertical(int xValue, int yValue, Tile.Color color, Tile.Shape shape) {
int northernTiles = 0;
char typeOfRow = ' ';
ArrayList<Tile.Color> colors = new ArrayList<Tile.Color>();
colors.add(color);
ArrayList<Tile.Shape> shapes = new ArrayList<Tile.Shape>();
shapes.add(shape);
boolean doorgaan = true;
int c = 0; //counter
while (doorgaan) { // omhoog kijken
c++;
if (!(fields[xValue][yValue + c] == null)) { // kijken of vakje leeg is
if (fields[xValue][yValue + c].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue][yValue + c].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C';
shapes.add(fields[xValue][yValue + c].getShape());
} else if (fields[xValue][yValue + c].getShape().equals(shape)
&& !(colors.contains(fields[xValue][yValue + c].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue][yValue + c].getColor());
} else {
return false;
}
} else {
doorgaan = false;
}
}
northernTiles = c - 1;
c = 0; //counter reset
doorgaan = true;
while (doorgaan) { //omlaag
c++;
if (!(fields[xValue][yValue - c] == null)) {
if (fields[xValue][yValue - c].getColor().equals(color) // kijken of kleur gelijk is
&& !(shapes.contains(fields[xValue][yValue - c].getShape())) // als kleur gelijk is, vorm mag niet gelijk
&& typeOfRow != 'S') {
typeOfRow = 'C';
shapes.add(fields[xValue][yValue - c].getShape());
} else if (fields[xValue][yValue - c].getShape().equals(shape)
&& !(colors.contains(fields[xValue][yValue - c].getColor()))
&& typeOfRow != 'C') {
typeOfRow = 'S';
colors.add(fields[xValue][yValue - c].getColor());
} else {
return false;
}
} else {
doorgaan = false;
}
}
if (typeRow == 'y' && c + northernTiles > 1) {
isConnected = true;
} else if (typeRow == 'x' && c+northernTiles > nrOfMoves) {
isConnected = true;
} else if (typeRow == 'z' && c+northernTiles > 1) {
isConnected = true;
} else if (isFirstMove && fields[50][50]!= null) {
isConnected = true;
}
if (c+northernTiles < 6 && c+northernTiles > 1) {
score += c+northernTiles;
} else if (c+northernTiles == 6) {
score += 12;
}
return true;
}
}
|
97274_1 | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
public class GmailLogin {
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"/chromedriver");
// Create a new instance of the Chrome driver
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 50);
// Open gmail web site
String appUrl = "http://www.gmail.com";
driver.get(appUrl);
// Login to gmail
driver.findElement(By.xpath("//*[@id=\"identifierId\"]")).sendKeys("[email protected]");
driver.findElement(By.xpath("//*[@id=\"identifierNext\"]/span")).click();
Thread.sleep(4000);
WebElement password = driver.findElement(By.xpath("//*[@id=\"password\"]/div[1]/div/div[1]/input"));
wait.until(ExpectedConditions.elementToBeClickable(password));
password.sendKeys("merry2210");
driver.findElement(By.xpath("//*[@id=\"passwordNext\"]/span/span")).click();
Thread.sleep(5000);
// Get all unread emails
List<WebElement> unread = driver.findElements(By.className("zE"));
System.out.println("You have "+unread.size()+ " unread messages.\n" );
System.out.println("------------------------------------------------------------------------------------------");
for (WebElement email: unread) {
// Get the sender's name
WebElement sender = email.findElement(By.className("zF"));
String senderName = sender.getAttribute("name");
Thread.sleep(10);
// Get the mail's subject
List<WebElement> detail = email.findElements(By.className("bqe"));
String subject = detail.get(1).getText();
Thread.sleep(10);
System.out.println("Sent by: " + senderName + "\tSubject: " + subject);
System.out.println("------------------------------------------------------------------------------------------");
}
driver.close();
}
}
| MeronZerihun/Screen-Mail-Using-Selenium | LoginGmail/src/GmailLogin.java | 661 | // Open gmail web site | line_comment | nl | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
public class GmailLogin {
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"/chromedriver");
// Create a new instance of the Chrome driver
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 50);
// Open gmail<SUF>
String appUrl = "http://www.gmail.com";
driver.get(appUrl);
// Login to gmail
driver.findElement(By.xpath("//*[@id=\"identifierId\"]")).sendKeys("[email protected]");
driver.findElement(By.xpath("//*[@id=\"identifierNext\"]/span")).click();
Thread.sleep(4000);
WebElement password = driver.findElement(By.xpath("//*[@id=\"password\"]/div[1]/div/div[1]/input"));
wait.until(ExpectedConditions.elementToBeClickable(password));
password.sendKeys("merry2210");
driver.findElement(By.xpath("//*[@id=\"passwordNext\"]/span/span")).click();
Thread.sleep(5000);
// Get all unread emails
List<WebElement> unread = driver.findElements(By.className("zE"));
System.out.println("You have "+unread.size()+ " unread messages.\n" );
System.out.println("------------------------------------------------------------------------------------------");
for (WebElement email: unread) {
// Get the sender's name
WebElement sender = email.findElement(By.className("zF"));
String senderName = sender.getAttribute("name");
Thread.sleep(10);
// Get the mail's subject
List<WebElement> detail = email.findElements(By.className("bqe"));
String subject = detail.get(1).getText();
Thread.sleep(10);
System.out.println("Sent by: " + senderName + "\tSubject: " + subject);
System.out.println("------------------------------------------------------------------------------------------");
}
driver.close();
}
}
|
26153_1 | package nl.hu.dp;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.sql.Date;
import java.util.*;
@Entity
@Table(name = "ov_chipkaart")
public class OVChipkaart {
@Id
@Column(name = "kaart_nummer", nullable = false)
private int id;
@Column(name = "geldig_tot")
private Date geldigTot;
private Integer klasse;
private Integer saldo;
@ManyToOne
@JoinColumn(name = "reiziger_id")
private Reiziger reiziger_id;
//https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ManyToMany.html
//ovchipkaart is de owning side hier zitten joins om product en ovchipkaart samen te voegen
//deze joins zorgen dus voor de relationship die we nodig hebben
//zie @ManyToMany van klasse Product
@ManyToMany
@JoinTable(name = "ov_chipkaart_product", joinColumns = @JoinColumn(name = "kaart_nummer")
,inverseJoinColumns = @JoinColumn(name = "product_nummer"))
private List<Product> producten = new ArrayList<>();
public OVChipkaart() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OVChipkaart(int id, Date geldigTot, Integer klasse, Integer saldo) {
this.id = id;
this.geldigTot = geldigTot;
this.klasse = klasse;
this.saldo = saldo;
}
public int getKaartId() {
return id;
}
public void setKaartId(int id) {
this.id=id;
}
public Reiziger getReiziger() {
return reiziger_id;
}
public void setReiziger(Reiziger reiziger) {
this.reiziger_id = reiziger;
}
public Date getGeldigTot() {
return geldigTot;
}
public void setGeldigTot(Date geldigTot) {
this.geldigTot = geldigTot;
}
public Integer getKlasse() {
return klasse;
}
public void setKlasse(Integer klasse) {
this.klasse = klasse;
}
public Integer getSaldo() {
return saldo;
}
public void setSaldo(Integer saldo) {
this.saldo = saldo;
}
public void voegProductToe(Product product) {
producten.add(product);
}
public void verwijderProduct(Product product) {
producten.remove(product);
}
public List<Product> getProducten() {
return producten;
}
public String toString() {
String product = "";
for (Product p : producten) {
product +=
"nummer #" + p.getProductNummer() +
" naam: " + p.getNaam() + " beschrijving: " + p.getBeschrijving() + " ";
}
if (reiziger_id != null && producten == null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
" {ReizigerID: " + "#" + reiziger_id.getId() + "}";
} else if (producten != null && reiziger_id != null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
"\n Producten{" + product + "}" + " Reiziger{"+reiziger_id.getNaam()+"}";
}
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "}";
}
}
| Mertcan417/Data-Persistency_ovchipkaart-hibernate | src/main/java/nl/hu/dp/OVChipkaart.java | 1,106 | //deze joins zorgen dus voor de relationship die we nodig hebben | line_comment | nl | package nl.hu.dp;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.sql.Date;
import java.util.*;
@Entity
@Table(name = "ov_chipkaart")
public class OVChipkaart {
@Id
@Column(name = "kaart_nummer", nullable = false)
private int id;
@Column(name = "geldig_tot")
private Date geldigTot;
private Integer klasse;
private Integer saldo;
@ManyToOne
@JoinColumn(name = "reiziger_id")
private Reiziger reiziger_id;
//https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ManyToMany.html
//ovchipkaart is de owning side hier zitten joins om product en ovchipkaart samen te voegen
//deze joins<SUF>
//zie @ManyToMany van klasse Product
@ManyToMany
@JoinTable(name = "ov_chipkaart_product", joinColumns = @JoinColumn(name = "kaart_nummer")
,inverseJoinColumns = @JoinColumn(name = "product_nummer"))
private List<Product> producten = new ArrayList<>();
public OVChipkaart() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OVChipkaart(int id, Date geldigTot, Integer klasse, Integer saldo) {
this.id = id;
this.geldigTot = geldigTot;
this.klasse = klasse;
this.saldo = saldo;
}
public int getKaartId() {
return id;
}
public void setKaartId(int id) {
this.id=id;
}
public Reiziger getReiziger() {
return reiziger_id;
}
public void setReiziger(Reiziger reiziger) {
this.reiziger_id = reiziger;
}
public Date getGeldigTot() {
return geldigTot;
}
public void setGeldigTot(Date geldigTot) {
this.geldigTot = geldigTot;
}
public Integer getKlasse() {
return klasse;
}
public void setKlasse(Integer klasse) {
this.klasse = klasse;
}
public Integer getSaldo() {
return saldo;
}
public void setSaldo(Integer saldo) {
this.saldo = saldo;
}
public void voegProductToe(Product product) {
producten.add(product);
}
public void verwijderProduct(Product product) {
producten.remove(product);
}
public List<Product> getProducten() {
return producten;
}
public String toString() {
String product = "";
for (Product p : producten) {
product +=
"nummer #" + p.getProductNummer() +
" naam: " + p.getNaam() + " beschrijving: " + p.getBeschrijving() + " ";
}
if (reiziger_id != null && producten == null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
" {ReizigerID: " + "#" + reiziger_id.getId() + "}";
} else if (producten != null && reiziger_id != null) {
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo +
"\n Producten{" + product + "}" + " Reiziger{"+reiziger_id.getNaam()+"}";
}
return "{kaartnummer: #" + id + " geldigTot: " + geldigTot + " klasse: " + klasse + " saldo: " + saldo + "}";
}
}
|
37851_2 | package hu.mt.model;
import java.io.Serializable;
import java.util.ArrayList;
public class Aquarium implements Serializable {
private String naam;
private int lengte;
private int breedte;
private int hoogte;
private String bodemSoort;
private String waterSoort;
private ArrayList<Ornament> ornamenten;
private ArrayList<Bewoner> bewoners;
public Aquarium(String nm, int lt, int bt, int ht, String bs, String ws) throws Exception {
naam = nm;
bodemSoort = bs;
waterSoort = ws;
ornamenten = new ArrayList<Ornament>();
bewoners = new ArrayList<Bewoner>();
lengte = lt;
breedte = bt;
hoogte = ht;
if (lt <= 0 || bt <= 0 || ht <= 0) {
throw new Exception("Het ingevulde getal mag niet negatief zijn!");
}
}
public ArrayList<Ornament> getOrnamenten() {
return ornamenten;
}
public void voegOrnamentToe(Ornament om) throws Exception {
for (Ornament ornament : ornamenten) {
if (ornament.getNaam().equals(om.getNaam())) {
throw new Exception("De ornament bestaat al!");
}
}
ornamenten.add(om);
}
public void verwijderOrnament(Ornament om) throws Exception {
if (!ornamenten.contains(om)) {
throw new Exception("De ornament bestaat niet!");
}
ornamenten.remove(om);
}
public ArrayList<Bewoner> getBewoners() {
return bewoners;
}
public void voegBewonerToe(Bewoner bwn) {
for (Bewoner bewoner : bewoners) {
if (bewoner.getSoortnaam().equals(bwn.getSoortnaam()) && bewoner.getKleurnaam().equals(bwn.getKleurnaam())) {
int bewonerAantal = bewoner.getAantal();
bewoner.setAantal(bewonerAantal + bwn.getAantal());
return;
}
}
bewoners.add(bwn);
}
public void verwijderBewoner(Bewoner bwn) throws Exception {
if (!bewoners.contains(bwn)) {
throw new Exception("De bewoner bestaat niet!");
}
bewoners.remove(bwn);
}
public String getNaam() {
return naam;
}
public void setNaam(String nm) {
naam = nm;
}
public int getLengte() {
return lengte;
}
public void setLengte(int lt) {
lengte = lt;
if (lt <= 0) {
lengte = 0;
//throw new Exception("lengte moet groter zijn dan nul!");
}
}
public int getBreedte() {
return breedte;
}
public void setBreedte(int bt) {
breedte = bt;
if (bt <= 0) {
breedte = 0;
//throw new Exception("breedte moet groter zijn dan nul!");
}
}
public int getHoogte() {
return hoogte;
}
public void setHoogte(int ht) {
hoogte = ht;
if (ht <= 0) {
hoogte = 0;
// throw new Exception("hoogte moet groter zijn dan nul!");
}
}
public String getBodemSoort() {
return bodemSoort;
}
public void setBodemSoort(String bs) {
bodemSoort = bs;
}
public String getWaterSoort() {
return waterSoort;
}
public void setWaterSoort(String ws) {
waterSoort = ws;
}
public String toString() {
return "Aquarium\nnaam: " + naam + "\nlengte: " + lengte +
"\nbreedte: " + breedte +
"\nhoogte: " + hoogte +
"\nbodemsoort: " + bodemSoort +
"\nwatersoort: " + waterSoort;
}
}
| Mertcan417/FA-fishy-system | src/main/java/hu/mt/model/Aquarium.java | 1,165 | // throw new Exception("hoogte moet groter zijn dan nul!"); | line_comment | nl | package hu.mt.model;
import java.io.Serializable;
import java.util.ArrayList;
public class Aquarium implements Serializable {
private String naam;
private int lengte;
private int breedte;
private int hoogte;
private String bodemSoort;
private String waterSoort;
private ArrayList<Ornament> ornamenten;
private ArrayList<Bewoner> bewoners;
public Aquarium(String nm, int lt, int bt, int ht, String bs, String ws) throws Exception {
naam = nm;
bodemSoort = bs;
waterSoort = ws;
ornamenten = new ArrayList<Ornament>();
bewoners = new ArrayList<Bewoner>();
lengte = lt;
breedte = bt;
hoogte = ht;
if (lt <= 0 || bt <= 0 || ht <= 0) {
throw new Exception("Het ingevulde getal mag niet negatief zijn!");
}
}
public ArrayList<Ornament> getOrnamenten() {
return ornamenten;
}
public void voegOrnamentToe(Ornament om) throws Exception {
for (Ornament ornament : ornamenten) {
if (ornament.getNaam().equals(om.getNaam())) {
throw new Exception("De ornament bestaat al!");
}
}
ornamenten.add(om);
}
public void verwijderOrnament(Ornament om) throws Exception {
if (!ornamenten.contains(om)) {
throw new Exception("De ornament bestaat niet!");
}
ornamenten.remove(om);
}
public ArrayList<Bewoner> getBewoners() {
return bewoners;
}
public void voegBewonerToe(Bewoner bwn) {
for (Bewoner bewoner : bewoners) {
if (bewoner.getSoortnaam().equals(bwn.getSoortnaam()) && bewoner.getKleurnaam().equals(bwn.getKleurnaam())) {
int bewonerAantal = bewoner.getAantal();
bewoner.setAantal(bewonerAantal + bwn.getAantal());
return;
}
}
bewoners.add(bwn);
}
public void verwijderBewoner(Bewoner bwn) throws Exception {
if (!bewoners.contains(bwn)) {
throw new Exception("De bewoner bestaat niet!");
}
bewoners.remove(bwn);
}
public String getNaam() {
return naam;
}
public void setNaam(String nm) {
naam = nm;
}
public int getLengte() {
return lengte;
}
public void setLengte(int lt) {
lengte = lt;
if (lt <= 0) {
lengte = 0;
//throw new Exception("lengte moet groter zijn dan nul!");
}
}
public int getBreedte() {
return breedte;
}
public void setBreedte(int bt) {
breedte = bt;
if (bt <= 0) {
breedte = 0;
//throw new Exception("breedte moet groter zijn dan nul!");
}
}
public int getHoogte() {
return hoogte;
}
public void setHoogte(int ht) {
hoogte = ht;
if (ht <= 0) {
hoogte = 0;
// throw new<SUF>
}
}
public String getBodemSoort() {
return bodemSoort;
}
public void setBodemSoort(String bs) {
bodemSoort = bs;
}
public String getWaterSoort() {
return waterSoort;
}
public void setWaterSoort(String ws) {
waterSoort = ws;
}
public String toString() {
return "Aquarium\nnaam: " + naam + "\nlengte: " + lengte +
"\nbreedte: " + breedte +
"\nhoogte: " + hoogte +
"\nbodemsoort: " + bodemSoort +
"\nwatersoort: " + waterSoort;
}
}
|
15383_2 | package nl.hu.webservices;
import com.azure.core.annotation.Get;
import nl.hu.model.Afspraak;
import nl.hu.model.Klant;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.ResourceBundle;
@Path("afspraken")
public class AfspraakResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAfspraken() {
try {
ArrayList<Afspraak> afspraken = Klant.getAlleAfspraken();
return Response.ok(afspraken).build();
} catch (Exception e) {
HashMap<String, String> message = new HashMap<String, String>();
message.put("error", e.getMessage().toString());
return Response.status(Response.Status.CONFLICT).entity(message).build();
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response maakAfspraak(@FormParam("gebruikersnaam") String gn, @FormParam("afspraaktype") String at, @FormParam("datumtijd") Date dt) {
Afspraak as = new Afspraak(at, dt);
ArrayList<Afspraak> afspraken = Klant.getAlleAfspraken();
Klant k = Klant.getKlantByGebruikersnaam(gn);
for (Afspraak afspraak : afspraken) {
if (!afspraak.getDatum().equals(dt)) {
Klant.voegAfspraakToeAanLijst(as);
k.maakAfspraak(as);
return Response.ok(as).build();
}
}
//als de afspraak bezet is, maak dan een throw new Exception("already in use!");
return Response.noContent().build();
}
@GET
@Path("afspraakoverzicht/{gebruikersnaam}")
@Produces(MediaType.APPLICATION_JSON)
public Response getAfspraak(@PathParam("gebruikersnaam") String gn) {
try {
Klant k = Klant.getKlantByGebruikersnaam(gn);
ArrayList<Afspraak> afspraak = k.getAfspraken();
return Response.ok(afspraak).build();
} catch (Exception e) {
return Response.status(Response.Status.CONFLICT).build();
}
}
@DELETE
@Path("verwijderen/{gebruikersnaam}")
@Produces(MediaType.APPLICATION_JSON)
public Response verwijderAfspraak(@PathParam("gebruikersnaam") String gn, @FormParam("datumtijd") Date dt) {
Klant k = Klant.getKlantByGebruikersnaam(gn);
ArrayList<Afspraak> afspraken = k.getAfspraken();
for (Afspraak afspraak : afspraken) {
if (afspraak.getDatum().equals(dt)) {
k.verwijderAfspraak(afspraak);
return Response.ok(afspraak).build();
}
}
return Response.status(Response.Status.CONFLICT).build();
}
}
//maak een methode waarmee je met een getTime de klant eruit kan halen,
// de klant moet wel een afspraak maken deze moet je de dan wel gaan koppelen aan het klant object
//dus met een setAfspraak() en via klasse Afspraak setKlant() gebruiken
//keuze 2: zet dit allemaal in klant resource als een PUT, dan zet je er ook een DELETE in.
| Mertcan417/webapplicationkapperszaak | src/main/java/nl/hu/webservices/AfspraakResource.java | 1,059 | // de klant moet wel een afspraak maken deze moet je de dan wel gaan koppelen aan het klant object | line_comment | nl | package nl.hu.webservices;
import com.azure.core.annotation.Get;
import nl.hu.model.Afspraak;
import nl.hu.model.Klant;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.ResourceBundle;
@Path("afspraken")
public class AfspraakResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAfspraken() {
try {
ArrayList<Afspraak> afspraken = Klant.getAlleAfspraken();
return Response.ok(afspraken).build();
} catch (Exception e) {
HashMap<String, String> message = new HashMap<String, String>();
message.put("error", e.getMessage().toString());
return Response.status(Response.Status.CONFLICT).entity(message).build();
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response maakAfspraak(@FormParam("gebruikersnaam") String gn, @FormParam("afspraaktype") String at, @FormParam("datumtijd") Date dt) {
Afspraak as = new Afspraak(at, dt);
ArrayList<Afspraak> afspraken = Klant.getAlleAfspraken();
Klant k = Klant.getKlantByGebruikersnaam(gn);
for (Afspraak afspraak : afspraken) {
if (!afspraak.getDatum().equals(dt)) {
Klant.voegAfspraakToeAanLijst(as);
k.maakAfspraak(as);
return Response.ok(as).build();
}
}
//als de afspraak bezet is, maak dan een throw new Exception("already in use!");
return Response.noContent().build();
}
@GET
@Path("afspraakoverzicht/{gebruikersnaam}")
@Produces(MediaType.APPLICATION_JSON)
public Response getAfspraak(@PathParam("gebruikersnaam") String gn) {
try {
Klant k = Klant.getKlantByGebruikersnaam(gn);
ArrayList<Afspraak> afspraak = k.getAfspraken();
return Response.ok(afspraak).build();
} catch (Exception e) {
return Response.status(Response.Status.CONFLICT).build();
}
}
@DELETE
@Path("verwijderen/{gebruikersnaam}")
@Produces(MediaType.APPLICATION_JSON)
public Response verwijderAfspraak(@PathParam("gebruikersnaam") String gn, @FormParam("datumtijd") Date dt) {
Klant k = Klant.getKlantByGebruikersnaam(gn);
ArrayList<Afspraak> afspraken = k.getAfspraken();
for (Afspraak afspraak : afspraken) {
if (afspraak.getDatum().equals(dt)) {
k.verwijderAfspraak(afspraak);
return Response.ok(afspraak).build();
}
}
return Response.status(Response.Status.CONFLICT).build();
}
}
//maak een methode waarmee je met een getTime de klant eruit kan halen,
// de klant<SUF>
//dus met een setAfspraak() en via klasse Afspraak setKlant() gebruiken
//keuze 2: zet dit allemaal in klant resource als een PUT, dan zet je er ook een DELETE in.
|
110005_5 | package husacct.validate.domain.factory.violationtype;
import husacct.validate.domain.configuration.ConfigurationServiceImpl;
import husacct.validate.domain.exception.ProgrammingLanguageNotFoundException;
import husacct.validate.domain.exception.RuleTypeNotFoundException;
import husacct.validate.domain.exception.SeverityNotFoundException;
import husacct.validate.domain.exception.ViolationTypeNotFoundException;
import husacct.validate.domain.validation.Severity;
import husacct.validate.domain.validation.ViolationType;
import husacct.validate.domain.validation.internaltransferobjects.CategoryKeySeverityDTO;
import husacct.validate.domain.validation.ruletype.RuleTypes;
import husacct.validate.domain.validation.violationtype.IViolationType;
import java.awt.Color;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
public abstract class AbstractViolationType {
private Logger logger = Logger.getLogger(AbstractViolationType.class);
private final ConfigurationServiceImpl configuration;
protected List<CategoryKeySeverityDTO> allViolationKeys;
protected String languageName;
public abstract List<ViolationType> createViolationTypesByRule(String key);
abstract List<IViolationType> createViolationTypesMetaData();
AbstractViolationType(ConfigurationServiceImpl configuration, String languageName) {
this.configuration = configuration;
this.languageName = languageName;
ViolationtypeGenerator generator = new ViolationtypeGenerator();
this.allViolationKeys = generator.getAllViolationTypes(createViolationTypesMetaData());
}
protected List<ViolationType> generateViolationTypes(String ruleTypeKey, EnumSet<?> enums) {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
for (Enum<?> enumValue : enums) {
ViolationType violationtype = generateViolationType(ruleTypeKey, enumValue);
violationtypes.add(violationtype);
}
return violationtypes;
}
public HashMap<String, List<ViolationType>> getAllViolationTypes() {
return getAllViolationTypes(allViolationKeys);
}
protected HashMap<String, List<ViolationType>> getAllViolationTypes(List<CategoryKeySeverityDTO> keyList) {
HashMap<String, List<ViolationType>> categoryViolations = new HashMap<String, List<ViolationType>>();
for (CategoryKeySeverityDTO dto : keyList) {
if (categoryViolations.containsKey(dto.getCategory())) {
List<ViolationType> violationtypes = categoryViolations.get(dto.getCategory());
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
} else {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
categoryViolations.put(dto.getCategory(), violationtypes);
}
}
return categoryViolations;
}
private ViolationType createViolationType(String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
final Severity severity = createSeverity(languageName, violationTypeKey);
return new ViolationType(violationTypeKey, severity);
} else {
logger.warn(String.format("Warning specified %s not found in the system", violationTypeKey));
}
throw new ViolationTypeNotFoundException();
}
public ViolationType createViolationType(String ruleTypeKey, String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
//System.err.println("ADD key: " + violationtype.getKey() + " - category: " + violationtype.getCategory());
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
//System.err.println("CREATE " + violationTypeKey.toLowerCase());
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
try {
//System.out.println("GIVEN ruleTypeKey: " + ruleTypeKey + " violationTypeKey: " + violationTypeKey);
final Severity severity = createSeverity(languageName, violationTypeKey);
boolean enabled = configuration.isViolationEnabled(languageName, ruleTypeKey, violationTypeKey);
return new ViolationType(violationTypeKey, enabled, severity);
} catch (ProgrammingLanguageNotFoundException e) {
logger.warn(String.format("ProgrammingLanguage %s not found", languageName));
} catch (RuleTypeNotFoundException e) {
logger.warn(String.format("RuleTypeKey: %s not found", ruleTypeKey));
} catch (ViolationTypeNotFoundException e) {
logger.warn(String.format("ViolationTypeKey: %s not found", violationTypeKey));
}
} else {
//logger.warn(String.format("Warning specified %s not found in the system and or configuration", violationTypeKey));
return new ViolationType("", false, new Severity("", Color.GREEN));
}
// //Verbeteren
//return new ViolationType("", false, new Severity("", Color.GREEN));
throw new ViolationTypeNotFoundException(); //TODO: Onaangekondige dependencyTypes ondersteunen (van team Define)
}
private ViolationType generateViolationType(String ruleTypeKey, Enum<?> enumValue) {
final Severity severity = createSeverity(languageName, enumValue.toString());
final boolean isEnabled = configuration.isViolationEnabled(languageName, ruleTypeKey, enumValue.toString());
return new ViolationType(enumValue.toString(), isEnabled, severity);
}
protected boolean isCategoryLegalityOfDependency(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.IS_ONLY_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_THE_ONLY_MODULE_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.MUST_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_BACK_CALL.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_SKIP_CALL.toString())) {
return true;
} else {
return false;
}
}
protected boolean isVisibilityConventionRule(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isNamingConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isInheritanceConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.INHERITANCE_CONVENTION)) {
return true;
} else {
return false;
}
}
private Severity createSeverity(String programmingLanguage, String violationKey) {
try {
return configuration.getSeverityFromKey(programmingLanguage, violationKey);
} catch (SeverityNotFoundException e) {
CategoryKeySeverityDTO violation = getCategoryKeySeverityDTO(violationKey);
if (violation != null) {
return configuration.getSeverityByName(violation.getDefaultSeverity().toString());
}
}
return null;
}
private CategoryKeySeverityDTO getCategoryKeySeverityDTO(String violationKey) {
for (CategoryKeySeverityDTO violation : allViolationKeys) {
if (violation.getKey().toLowerCase().equals(violationKey.toLowerCase())) {
return violation;
}
}
return null;
}
} | Mestway/Patl4J | examples/statistics/husacct/src/husacct/validate/domain/factory/violationtype/AbstractViolationType.java | 2,278 | //TODO: Onaangekondige dependencyTypes ondersteunen (van team Define) | line_comment | nl | package husacct.validate.domain.factory.violationtype;
import husacct.validate.domain.configuration.ConfigurationServiceImpl;
import husacct.validate.domain.exception.ProgrammingLanguageNotFoundException;
import husacct.validate.domain.exception.RuleTypeNotFoundException;
import husacct.validate.domain.exception.SeverityNotFoundException;
import husacct.validate.domain.exception.ViolationTypeNotFoundException;
import husacct.validate.domain.validation.Severity;
import husacct.validate.domain.validation.ViolationType;
import husacct.validate.domain.validation.internaltransferobjects.CategoryKeySeverityDTO;
import husacct.validate.domain.validation.ruletype.RuleTypes;
import husacct.validate.domain.validation.violationtype.IViolationType;
import java.awt.Color;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
public abstract class AbstractViolationType {
private Logger logger = Logger.getLogger(AbstractViolationType.class);
private final ConfigurationServiceImpl configuration;
protected List<CategoryKeySeverityDTO> allViolationKeys;
protected String languageName;
public abstract List<ViolationType> createViolationTypesByRule(String key);
abstract List<IViolationType> createViolationTypesMetaData();
AbstractViolationType(ConfigurationServiceImpl configuration, String languageName) {
this.configuration = configuration;
this.languageName = languageName;
ViolationtypeGenerator generator = new ViolationtypeGenerator();
this.allViolationKeys = generator.getAllViolationTypes(createViolationTypesMetaData());
}
protected List<ViolationType> generateViolationTypes(String ruleTypeKey, EnumSet<?> enums) {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
for (Enum<?> enumValue : enums) {
ViolationType violationtype = generateViolationType(ruleTypeKey, enumValue);
violationtypes.add(violationtype);
}
return violationtypes;
}
public HashMap<String, List<ViolationType>> getAllViolationTypes() {
return getAllViolationTypes(allViolationKeys);
}
protected HashMap<String, List<ViolationType>> getAllViolationTypes(List<CategoryKeySeverityDTO> keyList) {
HashMap<String, List<ViolationType>> categoryViolations = new HashMap<String, List<ViolationType>>();
for (CategoryKeySeverityDTO dto : keyList) {
if (categoryViolations.containsKey(dto.getCategory())) {
List<ViolationType> violationtypes = categoryViolations.get(dto.getCategory());
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
} else {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
categoryViolations.put(dto.getCategory(), violationtypes);
}
}
return categoryViolations;
}
private ViolationType createViolationType(String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
final Severity severity = createSeverity(languageName, violationTypeKey);
return new ViolationType(violationTypeKey, severity);
} else {
logger.warn(String.format("Warning specified %s not found in the system", violationTypeKey));
}
throw new ViolationTypeNotFoundException();
}
public ViolationType createViolationType(String ruleTypeKey, String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
//System.err.println("ADD key: " + violationtype.getKey() + " - category: " + violationtype.getCategory());
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
//System.err.println("CREATE " + violationTypeKey.toLowerCase());
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
try {
//System.out.println("GIVEN ruleTypeKey: " + ruleTypeKey + " violationTypeKey: " + violationTypeKey);
final Severity severity = createSeverity(languageName, violationTypeKey);
boolean enabled = configuration.isViolationEnabled(languageName, ruleTypeKey, violationTypeKey);
return new ViolationType(violationTypeKey, enabled, severity);
} catch (ProgrammingLanguageNotFoundException e) {
logger.warn(String.format("ProgrammingLanguage %s not found", languageName));
} catch (RuleTypeNotFoundException e) {
logger.warn(String.format("RuleTypeKey: %s not found", ruleTypeKey));
} catch (ViolationTypeNotFoundException e) {
logger.warn(String.format("ViolationTypeKey: %s not found", violationTypeKey));
}
} else {
//logger.warn(String.format("Warning specified %s not found in the system and or configuration", violationTypeKey));
return new ViolationType("", false, new Severity("", Color.GREEN));
}
// //Verbeteren
//return new ViolationType("", false, new Severity("", Color.GREEN));
throw new ViolationTypeNotFoundException(); //TODO: Onaangekondige<SUF>
}
private ViolationType generateViolationType(String ruleTypeKey, Enum<?> enumValue) {
final Severity severity = createSeverity(languageName, enumValue.toString());
final boolean isEnabled = configuration.isViolationEnabled(languageName, ruleTypeKey, enumValue.toString());
return new ViolationType(enumValue.toString(), isEnabled, severity);
}
protected boolean isCategoryLegalityOfDependency(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.IS_ONLY_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_THE_ONLY_MODULE_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.MUST_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_BACK_CALL.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_SKIP_CALL.toString())) {
return true;
} else {
return false;
}
}
protected boolean isVisibilityConventionRule(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isNamingConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isInheritanceConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.INHERITANCE_CONVENTION)) {
return true;
} else {
return false;
}
}
private Severity createSeverity(String programmingLanguage, String violationKey) {
try {
return configuration.getSeverityFromKey(programmingLanguage, violationKey);
} catch (SeverityNotFoundException e) {
CategoryKeySeverityDTO violation = getCategoryKeySeverityDTO(violationKey);
if (violation != null) {
return configuration.getSeverityByName(violation.getDefaultSeverity().toString());
}
}
return null;
}
private CategoryKeySeverityDTO getCategoryKeySeverityDTO(String violationKey) {
for (CategoryKeySeverityDTO violation : allViolationKeys) {
if (violation.getKey().toLowerCase().equals(violationKey.toLowerCase())) {
return violation;
}
}
return null;
}
} |
178855_2 | package de.engine.math;
import java.text.MessageFormat;
public class Matrix
{
public enum SubstitutionDirection
{
FORWARD, BACKWARD
}
public static final Integer ZEILENSUMMENNORM = 0;
public static final Integer FROBENIUSNORM = 1;
private int rows = 2;
private int cols = 2;
Double values[][] = new Double[2][2];
public Matrix()
{
}
public Matrix(double d11, double d12, double d21, double d22)
{
values[0][0] = d11;
values[0][1] = d12;
values[1][0] = d21;
values[1][1] = d22;
}
public Vector multVector(Vector vec)
{
return new Vector(values[0][0] * vec.getX() + values[0][1] * vec.getY(), values[1][0] * vec.getX() + values[1][1] * vec.getY());
}
// import from numeric project is major essential for jakobiMatrix calculation
public int getRows()
{
return 2;
}
public int getCols()
{
return 2;
}
public Double get(int row, int col)
{
return values[row][col];
}
public void set(int row, int col, Double value)
{
values[row][col] = value;
}
public Matrix jakobiMatrix(Matrix functions)
{
for (int row = 0; row < functions.getRows(); row++)
{
for (int col = 0; col < functions.getCols(); col++)
{
values[row][col] = functions.get(row, col);
}
}
return this;
}
public Double norm(int n) throws RuntimeException
{
if (n == 0)
return zeilensummenNorm();
if (n == 1)
return frobeniusNorm();
throw new RuntimeException(MessageFormat.format("MathLib.getNorm() liefert den Wert {0}, für welche es keine Normimplementierung für Matrizen gibt.", n));
}
private Double zeilensummenNorm()
{
Double sum = 0d;
Double max = 0d;
for (int t = 0; t < 2; t++)
{
for (int i = 0; i < 2; i++)
{
sum = sum + Math.abs(values[t][i]);
}
if (max.compareTo(sum) == -1)
max = sum;
sum = 0d;
}
return max;
}
private Double frobeniusNorm()
{
Double sum = 0d;
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 2; col++)
{
sum = sum + values[row][col] * values[row][col];
}
}
return Math.sqrt(sum);
}
public Vector solveX(Vector b) throws ArithmeticException
{
Vector clone_b = b.clone();
Matrix L = getL(b.clone());
// System.out.println( "L: "+L.get(0, 0)+"|"+L.get(0,1)+"|"+L.get(1, 0)+"|"+L.get(1,1)+" || Clone_b: "+clone_b.get(0)+"|"+clone_b.get(1) );
Matrix U = getU(clone_b);
// System.out.println( "U: "+ U.get(0, 0)+"|"+U.get(0,1)+"|"+U.get(1, 0)+"|"+U.get(1,1)+" || Clone_b: "+clone_b.get(0)+"|"+clone_b.get(1) );
Vector y = substitution(L, clone_b, SubstitutionDirection.FORWARD);
Vector x = substitution(U, y, SubstitutionDirection.BACKWARD);
// System.out.println( "x: "+ x.get(0)+"|"+x.get(1) );
return x;
}
public Matrix getL(Vector b)
{
return doLUDecomposition(0, b).item2;
}
public Matrix getU(Vector b)
{
return doLUDecomposition(1, b).item2;
}
/**
* Gibt eine Tuple zurück, die entweder eine Matrix (für L oder U) hält oder ein Vector (für die Permutationen)
*
* @param which_matrix
* Gibt an, ob L (=0), U (=1), oder lperm(=2) zurückgegeben wird
* @param b
* Ist ein Vektor, der die Ergebnisse von den Gleichungssystemen darstellt
*/
private Tuple<Vector, Matrix> doLUDecomposition(int which_matrix, Vector b) throws ArithmeticException
{
Double temp = 0d;
Matrix U = clone();
Matrix L = identity();
// Reihenfolge der Vertauschung bei der Pivotstrategie(Permutationen)
Vector lperm = new Vector();
// Ergebnis ist [1, 2, 3, 4, ...] als Vektor
for (int cellOfVector = 0; cellOfVector < rows; cellOfVector++)
{
lperm.set(cellOfVector, cellOfVector + 1d);
}
for (int row = 0; row < L.rows; row++)
{
// Pivotisierung + Gaussschritte, reduzierte Zeilenstufenform
// if (MathLib.isPivotStrategy())
// {
// lperm = lperm.swapRows(row, pivotColumnStrategy(U, b, row ));
// }
for (int t = row; t < U.rows - 1; t++)
{
temp = U.values[t + 1][row] / U.values[row][row];
for (int i = row; i < U.rows; i++)
{
U.values[t + 1][i] = U.values[t + 1][i] - temp * U.values[row][i];
}
U.values[t + 1][row] = temp;
}
}
for (int row = 0; row < L.rows; row++)
{ // Trenne Matizen U und L voneinander
for (int col = 0; col < L.cols; col++)
{
if (row > col)
{
L.values[row][col] = U.values[row][col];
U.values[row][col] = 0d;
}
}
}
if (which_matrix == 0)
{
return new Tuple<Vector, Matrix>(null, L);
}
if (which_matrix == 1)
{
return new Tuple<Vector, Matrix>(null, U);
}
else
{
return new Tuple<Vector, Matrix>(lperm, null);
}
}
/**
* Ermöglicht die Vorwärts und Rückwärtssubstitution von einer Matrix mit einem Vector b
*
* @param matrix
* Matrix, die man Substituieren will
* @param b
* Vektor, den man Substituieren will
* @param str
* gibt an, wie man Substituieren will "forward" oder "backward"
*/
public Vector substitution(Matrix matrix, Vector b, SubstitutionDirection direction) throws ArithmeticException
{
Double term0 = 0d;
Double term1 = 0d;
Double term2 = 0d;
Vector y = new Vector();
if (direction == SubstitutionDirection.FORWARD)
{
y.set(0, b.get(0));
for (int row = 1; row < 2; row++)
{
term0 = term0 + matrix.values[row][0] * y.get(0);
term1 = b.get(row) - term0;
term2 = term1 / matrix.values[row][row];
y.set(row, term2);
}
}
if (direction == SubstitutionDirection.BACKWARD)
{
int dim = 1;
y.set(dim, b.get(dim) / matrix.values[dim][dim]);
for (int row = dim; row >= 0; row--)
{
term0 = 0d;
for (int i = 0; i < dim - row; i++)
{
term0 = term0 + matrix.values[row][dim - i] * y.get(dim - i);
}
term1 = b.get(row) - term0;
term2 = term1 / matrix.values[row][row];
y.set(row, term2);
}
}
return y;
}
@Override
public Matrix clone()
{
Matrix copy = new Matrix();
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
copy.values[row][col] = values[row][col];
}
}
return copy;
}
public Matrix identity()
{
Matrix identity = new Matrix();
for (int i = 0; i < rows; i++)
{
identity.set(i, i, 1d);
}
return identity;
}
/**
* Anwenden der Zeilenpivotstrategie, bei welcher Zeilen vertauscht werden nach dem Kriterium, dass ein absoluter Wert aus einer Zeile der aktuellen Spalte ermittelt wird und die Zeile mit dem höchsten Wert wird mit der aktuellen Reihe int row getauscht Zum Schluss wird die Zeile als int
* ausgegeben, die den maximalen Wert einer Zeile von der aktuellen Spalte besitzt.
*
* @param matrix
* Matrix, für die die Pivotstrategie angewendet werden soll
* @param vector
* Vektor, für die die Pivotstrategie angewendet werden soll
* @param row
* Anfangsreihe, bei welcher angefangen wird, die Zeilen zu vertauschen
*/
public int pivotColumnStrategy(Matrix matrix, Vector b, int row) throws ArithmeticException
{
if (matrix == null)
{
throw new ArithmeticException("Die Matrix als Input für die pivotColumnStrategy-Methode ist Null!");
}
if (b != null)
{
if (this.getRows() != b.getLength())
{
throw new ArithmeticException("Die Inputmatrix und der Inputvektor sind nicht gleichlang für die Methode pivotColumnStrategy!");
}
}
if (row < 0 || row > (matrix.getRows() - 1))
{
throw new ArithmeticException("Der row-Input bei der Methode pivotColumnStrategy liegt ausserhalb des gültigen Bereiches!");
}
Double maximum = 0d;
Double temp = 0d;
int rowposition = matrix.rows == (row + 1) ? row : 0;
boolean rowswap = false;
for (int t = 0; t < matrix.getRows() - row; t++)
{
for (int i = row + t; i < matrix.getCols(); i++)
{
matrix.values[i][row] = Math.abs(matrix.values[i][row]);
if (matrix.values[i][row].compareTo(maximum) == 1)
{
rowposition = i; // Markiere Zeile mit Maximum
maximum = matrix.values[i][row];
rowswap = true;
}
}
if (rowswap && rowposition != row)
{
for (int col = 0; col < matrix.getCols(); col++)
{ // Zeilenvertauschung der Matrix
temp = matrix.values[row][col];
matrix.values[row][col] = matrix.values[rowposition][col];
matrix.values[rowposition][col] = temp;
}
if (b != null)
{
temp = b.get(row); // Zeilenvertauschung des Vektors
b.set(row, b.get(rowposition));
b.set(rowposition, temp);
}
rowswap = false;
}
}
return rowposition;
}
}
| MichaeIDietrich/PhysicsEngine | PhysicsEngine/src/de/engine/math/Matrix.java | 3,443 | // System.out.println( "U: "+ U.get(0, 0)+"|"+U.get(0,1)+"|"+U.get(1, 0)+"|"+U.get(1,1)+" || Clone_b: "+clone_b.get(0)+"|"+clone_b.get(1) ); | line_comment | nl | package de.engine.math;
import java.text.MessageFormat;
public class Matrix
{
public enum SubstitutionDirection
{
FORWARD, BACKWARD
}
public static final Integer ZEILENSUMMENNORM = 0;
public static final Integer FROBENIUSNORM = 1;
private int rows = 2;
private int cols = 2;
Double values[][] = new Double[2][2];
public Matrix()
{
}
public Matrix(double d11, double d12, double d21, double d22)
{
values[0][0] = d11;
values[0][1] = d12;
values[1][0] = d21;
values[1][1] = d22;
}
public Vector multVector(Vector vec)
{
return new Vector(values[0][0] * vec.getX() + values[0][1] * vec.getY(), values[1][0] * vec.getX() + values[1][1] * vec.getY());
}
// import from numeric project is major essential for jakobiMatrix calculation
public int getRows()
{
return 2;
}
public int getCols()
{
return 2;
}
public Double get(int row, int col)
{
return values[row][col];
}
public void set(int row, int col, Double value)
{
values[row][col] = value;
}
public Matrix jakobiMatrix(Matrix functions)
{
for (int row = 0; row < functions.getRows(); row++)
{
for (int col = 0; col < functions.getCols(); col++)
{
values[row][col] = functions.get(row, col);
}
}
return this;
}
public Double norm(int n) throws RuntimeException
{
if (n == 0)
return zeilensummenNorm();
if (n == 1)
return frobeniusNorm();
throw new RuntimeException(MessageFormat.format("MathLib.getNorm() liefert den Wert {0}, für welche es keine Normimplementierung für Matrizen gibt.", n));
}
private Double zeilensummenNorm()
{
Double sum = 0d;
Double max = 0d;
for (int t = 0; t < 2; t++)
{
for (int i = 0; i < 2; i++)
{
sum = sum + Math.abs(values[t][i]);
}
if (max.compareTo(sum) == -1)
max = sum;
sum = 0d;
}
return max;
}
private Double frobeniusNorm()
{
Double sum = 0d;
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 2; col++)
{
sum = sum + values[row][col] * values[row][col];
}
}
return Math.sqrt(sum);
}
public Vector solveX(Vector b) throws ArithmeticException
{
Vector clone_b = b.clone();
Matrix L = getL(b.clone());
// System.out.println( "L: "+L.get(0, 0)+"|"+L.get(0,1)+"|"+L.get(1, 0)+"|"+L.get(1,1)+" || Clone_b: "+clone_b.get(0)+"|"+clone_b.get(1) );
Matrix U = getU(clone_b);
// System.out.println( "U:<SUF>
Vector y = substitution(L, clone_b, SubstitutionDirection.FORWARD);
Vector x = substitution(U, y, SubstitutionDirection.BACKWARD);
// System.out.println( "x: "+ x.get(0)+"|"+x.get(1) );
return x;
}
public Matrix getL(Vector b)
{
return doLUDecomposition(0, b).item2;
}
public Matrix getU(Vector b)
{
return doLUDecomposition(1, b).item2;
}
/**
* Gibt eine Tuple zurück, die entweder eine Matrix (für L oder U) hält oder ein Vector (für die Permutationen)
*
* @param which_matrix
* Gibt an, ob L (=0), U (=1), oder lperm(=2) zurückgegeben wird
* @param b
* Ist ein Vektor, der die Ergebnisse von den Gleichungssystemen darstellt
*/
private Tuple<Vector, Matrix> doLUDecomposition(int which_matrix, Vector b) throws ArithmeticException
{
Double temp = 0d;
Matrix U = clone();
Matrix L = identity();
// Reihenfolge der Vertauschung bei der Pivotstrategie(Permutationen)
Vector lperm = new Vector();
// Ergebnis ist [1, 2, 3, 4, ...] als Vektor
for (int cellOfVector = 0; cellOfVector < rows; cellOfVector++)
{
lperm.set(cellOfVector, cellOfVector + 1d);
}
for (int row = 0; row < L.rows; row++)
{
// Pivotisierung + Gaussschritte, reduzierte Zeilenstufenform
// if (MathLib.isPivotStrategy())
// {
// lperm = lperm.swapRows(row, pivotColumnStrategy(U, b, row ));
// }
for (int t = row; t < U.rows - 1; t++)
{
temp = U.values[t + 1][row] / U.values[row][row];
for (int i = row; i < U.rows; i++)
{
U.values[t + 1][i] = U.values[t + 1][i] - temp * U.values[row][i];
}
U.values[t + 1][row] = temp;
}
}
for (int row = 0; row < L.rows; row++)
{ // Trenne Matizen U und L voneinander
for (int col = 0; col < L.cols; col++)
{
if (row > col)
{
L.values[row][col] = U.values[row][col];
U.values[row][col] = 0d;
}
}
}
if (which_matrix == 0)
{
return new Tuple<Vector, Matrix>(null, L);
}
if (which_matrix == 1)
{
return new Tuple<Vector, Matrix>(null, U);
}
else
{
return new Tuple<Vector, Matrix>(lperm, null);
}
}
/**
* Ermöglicht die Vorwärts und Rückwärtssubstitution von einer Matrix mit einem Vector b
*
* @param matrix
* Matrix, die man Substituieren will
* @param b
* Vektor, den man Substituieren will
* @param str
* gibt an, wie man Substituieren will "forward" oder "backward"
*/
public Vector substitution(Matrix matrix, Vector b, SubstitutionDirection direction) throws ArithmeticException
{
Double term0 = 0d;
Double term1 = 0d;
Double term2 = 0d;
Vector y = new Vector();
if (direction == SubstitutionDirection.FORWARD)
{
y.set(0, b.get(0));
for (int row = 1; row < 2; row++)
{
term0 = term0 + matrix.values[row][0] * y.get(0);
term1 = b.get(row) - term0;
term2 = term1 / matrix.values[row][row];
y.set(row, term2);
}
}
if (direction == SubstitutionDirection.BACKWARD)
{
int dim = 1;
y.set(dim, b.get(dim) / matrix.values[dim][dim]);
for (int row = dim; row >= 0; row--)
{
term0 = 0d;
for (int i = 0; i < dim - row; i++)
{
term0 = term0 + matrix.values[row][dim - i] * y.get(dim - i);
}
term1 = b.get(row) - term0;
term2 = term1 / matrix.values[row][row];
y.set(row, term2);
}
}
return y;
}
@Override
public Matrix clone()
{
Matrix copy = new Matrix();
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
copy.values[row][col] = values[row][col];
}
}
return copy;
}
public Matrix identity()
{
Matrix identity = new Matrix();
for (int i = 0; i < rows; i++)
{
identity.set(i, i, 1d);
}
return identity;
}
/**
* Anwenden der Zeilenpivotstrategie, bei welcher Zeilen vertauscht werden nach dem Kriterium, dass ein absoluter Wert aus einer Zeile der aktuellen Spalte ermittelt wird und die Zeile mit dem höchsten Wert wird mit der aktuellen Reihe int row getauscht Zum Schluss wird die Zeile als int
* ausgegeben, die den maximalen Wert einer Zeile von der aktuellen Spalte besitzt.
*
* @param matrix
* Matrix, für die die Pivotstrategie angewendet werden soll
* @param vector
* Vektor, für die die Pivotstrategie angewendet werden soll
* @param row
* Anfangsreihe, bei welcher angefangen wird, die Zeilen zu vertauschen
*/
public int pivotColumnStrategy(Matrix matrix, Vector b, int row) throws ArithmeticException
{
if (matrix == null)
{
throw new ArithmeticException("Die Matrix als Input für die pivotColumnStrategy-Methode ist Null!");
}
if (b != null)
{
if (this.getRows() != b.getLength())
{
throw new ArithmeticException("Die Inputmatrix und der Inputvektor sind nicht gleichlang für die Methode pivotColumnStrategy!");
}
}
if (row < 0 || row > (matrix.getRows() - 1))
{
throw new ArithmeticException("Der row-Input bei der Methode pivotColumnStrategy liegt ausserhalb des gültigen Bereiches!");
}
Double maximum = 0d;
Double temp = 0d;
int rowposition = matrix.rows == (row + 1) ? row : 0;
boolean rowswap = false;
for (int t = 0; t < matrix.getRows() - row; t++)
{
for (int i = row + t; i < matrix.getCols(); i++)
{
matrix.values[i][row] = Math.abs(matrix.values[i][row]);
if (matrix.values[i][row].compareTo(maximum) == 1)
{
rowposition = i; // Markiere Zeile mit Maximum
maximum = matrix.values[i][row];
rowswap = true;
}
}
if (rowswap && rowposition != row)
{
for (int col = 0; col < matrix.getCols(); col++)
{ // Zeilenvertauschung der Matrix
temp = matrix.values[row][col];
matrix.values[row][col] = matrix.values[rowposition][col];
matrix.values[rowposition][col] = temp;
}
if (b != null)
{
temp = b.get(row); // Zeilenvertauschung des Vektors
b.set(row, b.get(rowposition));
b.set(rowposition, temp);
}
rowswap = false;
}
}
return rowposition;
}
}
|
211034_2 | package michael.koers;
import util.FileInput;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws URISyntaxException, IOException {
List<String> read = FileInput.read(FileInput.INPUT, Main.class);
List<Field> fields = parseInput(read);
// solvePart1(fields);
solvePart2(fields);
}
private static void solvePart2(List<Field> fields) {
List<Integer> hors = new ArrayList<>();
List<Integer> verts = new ArrayList<>();
field:
for (Field field : fields) {
List<String> prevs = new ArrayList<>();
List<String> currentField = field.layout();
// Check horizontal
for (int i = 0; i < field.layout().size(); i++) {
String current = currentField.get(i);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
boolean foundSmudge = false;
for (int d = 0; d < Math.min(prevs.size(), currentField.size() - i); d++) {
if (!foundSmudge && smudgeEquals(prevs.get(i - d - 1), currentField.get(i + d))) {
foundSmudge = true;
} else if (!prevs.get(i - d - 1).equals(currentField.get(i + d))) {
match = false;
break;
}
}
if (match && foundSmudge) {
hors.add(i);
System.out.printf("Field %s has horizontal mirror between %s and %s%n", field.index(), i, i + 1);
continue field;
}
prevs.add(current);
}
// Check vertical
prevs.clear();
// Loop over x-axis
for (int x = 0; x < currentField.get(0).length(); x++) {
// Create vertical line
String current = getLineAtX(currentField, x);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
boolean foundSmudge = false;
for (int d = 0; d < Math.min(prevs.size(), currentField.get(0).length() - x); d++) {
if (!foundSmudge && smudgeEquals(prevs.get(x - d - 1), getLineAtX(currentField, x + d))) {
foundSmudge = true;
} else if (!prevs.get(x - d - 1).equals(getLineAtX(currentField, x + d))) {
match = false;
break;
}
}
if (match && foundSmudge) {
verts.add(x);
System.out.printf("Field %s has vertical mirror between %s and %s%n", field.index(), x, x + 1);
continue field;
}
prevs.add(current);
}
}
long rowValue = hors.stream().mapToLong(i -> i * 100L).sum();
long colValue = verts.stream().mapToLong(Integer::longValue).sum();
System.out.printf("Solved part 2, total of notes: %s%n", rowValue + colValue);
}
private static boolean smudgeEquals(String s, String s1) {
int diffCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s1.charAt(i)) {
diffCount++;
}
}
return diffCount == 1;
}
private static void solvePart1(List<Field> fields) {
List<Integer> hors = new ArrayList<>();
List<Integer> verts = new ArrayList<>();
field:
for (Field field : fields) {
List<String> prevs = new ArrayList<>();
List<String> currentField = field.layout();
// Check horizontal
for (int i = 0; i < field.layout().size(); i++) {
String current = currentField.get(i);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
for (int d = 0; d < Math.min(prevs.size(), currentField.size() - i); d++) {
if (!prevs.get(i - d - 1).equals(currentField.get(i + d))) {
match = false;
break;
}
}
if (match) {
hors.add(i);
System.out.printf("Field %s has horizontal mirror between %s and %s%n", field.index(), i, i + 1);
continue field;
}
prevs.add(current);
}
// Check vertical
prevs.clear();
// Loop over x-axis
for (int x = 0; x < currentField.get(0).length(); x++) {
// Create vertical line
String current = getLineAtX(currentField, x);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
for (int d = 0; d < Math.min(prevs.size(), currentField.get(0).length() - x); d++) {
if (!prevs.get(x - d - 1).equals(getLineAtX(currentField, x + d))) {
match = false;
break;
}
}
if (match) {
verts.add(x);
System.out.printf("Field %s has vertical mirror between %s and %s%n", field.index(), x, x + 1);
continue field;
}
prevs.add(current);
}
}
long rowValue = hors.stream().mapToLong(i -> i * 100L).sum();
long colValue = verts.stream().mapToLong(Integer::longValue).sum();
System.out.printf("Solved part 1, total of notes: %s%n", rowValue + colValue);
}
private static String getLineAtX(List<String> currentField, int x) {
StringBuilder sb = new StringBuilder();
for (String s : currentField) {
sb.append(s.charAt(x));
}
return sb.toString();
}
private static List<Field> parseInput(List<String> lines) {
List<Field> fields = new ArrayList<>();
List<String> tmp = new ArrayList<>();
Integer index = 0;
for (String line : lines) {
if (line.isBlank()) {
fields.add(new Field(index++, new ArrayList<>(tmp)));
tmp.clear();
continue;
}
tmp.add(line);
}
fields.add(new Field(index++, new ArrayList<>(tmp)));
return fields;
}
}
record Field(Integer index, List<String> layout) {
};
| Michael-Koers/CodeAdvent | 2023/day-13-2023/src/main/java/michael/koers/Main.java | 1,909 | // Loop over x-axis | line_comment | nl | package michael.koers;
import util.FileInput;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws URISyntaxException, IOException {
List<String> read = FileInput.read(FileInput.INPUT, Main.class);
List<Field> fields = parseInput(read);
// solvePart1(fields);
solvePart2(fields);
}
private static void solvePart2(List<Field> fields) {
List<Integer> hors = new ArrayList<>();
List<Integer> verts = new ArrayList<>();
field:
for (Field field : fields) {
List<String> prevs = new ArrayList<>();
List<String> currentField = field.layout();
// Check horizontal
for (int i = 0; i < field.layout().size(); i++) {
String current = currentField.get(i);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
boolean foundSmudge = false;
for (int d = 0; d < Math.min(prevs.size(), currentField.size() - i); d++) {
if (!foundSmudge && smudgeEquals(prevs.get(i - d - 1), currentField.get(i + d))) {
foundSmudge = true;
} else if (!prevs.get(i - d - 1).equals(currentField.get(i + d))) {
match = false;
break;
}
}
if (match && foundSmudge) {
hors.add(i);
System.out.printf("Field %s has horizontal mirror between %s and %s%n", field.index(), i, i + 1);
continue field;
}
prevs.add(current);
}
// Check vertical
prevs.clear();
// Loop over x-axis
for (int x = 0; x < currentField.get(0).length(); x++) {
// Create vertical line
String current = getLineAtX(currentField, x);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
boolean foundSmudge = false;
for (int d = 0; d < Math.min(prevs.size(), currentField.get(0).length() - x); d++) {
if (!foundSmudge && smudgeEquals(prevs.get(x - d - 1), getLineAtX(currentField, x + d))) {
foundSmudge = true;
} else if (!prevs.get(x - d - 1).equals(getLineAtX(currentField, x + d))) {
match = false;
break;
}
}
if (match && foundSmudge) {
verts.add(x);
System.out.printf("Field %s has vertical mirror between %s and %s%n", field.index(), x, x + 1);
continue field;
}
prevs.add(current);
}
}
long rowValue = hors.stream().mapToLong(i -> i * 100L).sum();
long colValue = verts.stream().mapToLong(Integer::longValue).sum();
System.out.printf("Solved part 2, total of notes: %s%n", rowValue + colValue);
}
private static boolean smudgeEquals(String s, String s1) {
int diffCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s1.charAt(i)) {
diffCount++;
}
}
return diffCount == 1;
}
private static void solvePart1(List<Field> fields) {
List<Integer> hors = new ArrayList<>();
List<Integer> verts = new ArrayList<>();
field:
for (Field field : fields) {
List<String> prevs = new ArrayList<>();
List<String> currentField = field.layout();
// Check horizontal
for (int i = 0; i < field.layout().size(); i++) {
String current = currentField.get(i);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
for (int d = 0; d < Math.min(prevs.size(), currentField.size() - i); d++) {
if (!prevs.get(i - d - 1).equals(currentField.get(i + d))) {
match = false;
break;
}
}
if (match) {
hors.add(i);
System.out.printf("Field %s has horizontal mirror between %s and %s%n", field.index(), i, i + 1);
continue field;
}
prevs.add(current);
}
// Check vertical
prevs.clear();
// Loop over<SUF>
for (int x = 0; x < currentField.get(0).length(); x++) {
// Create vertical line
String current = getLineAtX(currentField, x);
if (prevs.isEmpty()) {
prevs.add(current);
continue;
}
boolean match = true;
for (int d = 0; d < Math.min(prevs.size(), currentField.get(0).length() - x); d++) {
if (!prevs.get(x - d - 1).equals(getLineAtX(currentField, x + d))) {
match = false;
break;
}
}
if (match) {
verts.add(x);
System.out.printf("Field %s has vertical mirror between %s and %s%n", field.index(), x, x + 1);
continue field;
}
prevs.add(current);
}
}
long rowValue = hors.stream().mapToLong(i -> i * 100L).sum();
long colValue = verts.stream().mapToLong(Integer::longValue).sum();
System.out.printf("Solved part 1, total of notes: %s%n", rowValue + colValue);
}
private static String getLineAtX(List<String> currentField, int x) {
StringBuilder sb = new StringBuilder();
for (String s : currentField) {
sb.append(s.charAt(x));
}
return sb.toString();
}
private static List<Field> parseInput(List<String> lines) {
List<Field> fields = new ArrayList<>();
List<String> tmp = new ArrayList<>();
Integer index = 0;
for (String line : lines) {
if (line.isBlank()) {
fields.add(new Field(index++, new ArrayList<>(tmp)));
tmp.clear();
continue;
}
tmp.add(line);
}
fields.add(new Field(index++, new ArrayList<>(tmp)));
return fields;
}
}
record Field(Integer index, List<String> layout) {
};
|
73610_26 | package org.ontologyengineering.conceptdiagrams.web.client.ui.shapes;
import com.ait.lienzo.client.core.event.*;
import com.ait.lienzo.client.core.shape.Layer;
import com.ait.lienzo.client.core.shape.Node;
import com.ait.lienzo.client.core.shape.Rectangle;
import com.ait.lienzo.client.core.types.BoundingBox;
import com.ait.lienzo.client.core.types.Point2D;
import org.ontologyengineering.conceptdiagrams.web.shared.presenter.DiagramCanvas;
import org.ontologyengineering.conceptdiagrams.web.client.ui.LienzoDiagramCanvas;
import org.ontologyengineering.conceptdiagrams.web.shared.concretesyntax.ConcreteDiagramElement;
import java.util.AbstractSet;
import java.util.HashSet;
/**
* Author: Michael Compton<br>
* Date: September 2015<br>
* See license information in base directory.
*/
public class LienzoDragBoundsGroup extends LienzoDiagramShape<ConcreteDiagramElement, Node> {
private AbstractSet<LienzoDiagramShape> boundedElements;
private Point2D topLeftP, bottomRightP; // canvas coords
private Rectangle rubberband; // drawn on drag layer - screen coords
private Rectangle[] dragBoxes;
private static final int topLeft = 0; // corners
private static final int topRight = 1;
private static final int botRight = 2;
private static final int botLeft = 3;
private static final int top = 4; // sides for selection boxes
private static final int right = 5;
private static final int bot = 6;
private static final int left = 7;
private Point2D unitTest; // canvas unit
public LienzoDragBoundsGroup(LienzoDiagramCanvas canvas) {
super(canvas);
boundedElements = new HashSet<LienzoDiagramShape>();
topLeftP = new Point2D(0,0);
bottomRightP = new Point2D(0,0);
rubberband = new Rectangle(1, 1);
rubberband.setStrokeColor(rubberBandColour);
rubberband.setDraggable(false);
rubberband.setListening(false);
representation = rubberband;
dragBoxes = new Rectangle[8];
for (int i = 0; i < 8; i++) {
dragBoxes[i] = new Rectangle(dragBoxSize, dragBoxSize);
dragBoxes[i].setStrokeColor(dragBoxColour);
dragBoxes[i].setFillColor(dragBoxColour);
dragBoxes[i].setDraggable(true);
}
addHandlers();
unitTest = new Point2D();
}
public void addElement(LienzoDiagramShape element) {
boundedElements.add(element);
element.setAsSelected();
element.drawRubberBand();
if(element.getDiagramElement().getType() != ConcreteDiagramElement.ConcreteDiagramElement_TYPES.CONCRETEARROW) {
if (boundedElements.size() == 1) {
topLeftP.setX(element.getDiagramElement().topLeft().getX());
topLeftP.setY(element.getDiagramElement().topLeft().getY());
bottomRightP.setX(element.getDiagramElement().bottomRight().getX());
bottomRightP.setY(element.getDiagramElement().bottomRight().getY());
} else {
// see if the new element extends the bounds in any way
if (element.getDiagramElement().topLeft().getX() < topLeftP.getX()) {
topLeftP.setX(element.getDiagramElement().topLeft().getX());
}
if (element.getDiagramElement().topLeft().getY() < topLeftP.getY()) {
topLeftP.setY(element.getDiagramElement().topLeft().getY());
}
if (element.getDiagramElement().bottomRight().getX() > bottomRightP.getX()) {
bottomRightP.setX(element.getDiagramElement().bottomRight().getX());
}
if (element.getDiagramElement().bottomRight().getY() > bottomRightP.getY()) {
bottomRightP.setY(element.getDiagramElement().bottomRight().getY());
}
}
}
}
public void clearAndUndraw() {
undraw();
for(LienzoDiagramShape s : boundedElements) {
s.setAsUnSelected();
s.getDragRubberBand().undraw();
}
boundedElements.clear();
}
public Point2D topRight() {
return new Point2D(bottomRightP.getX(), topLeftP.getY());
}
public Point2D bottomLeft() {
return new Point2D(topLeftP.getX(), bottomRightP.getY());
}
// canvas width
public double getWidth() {
return bottomRightP.getX() - topLeftP.getX();
}
// canvas height
public double getHeight() {
return bottomRightP.getY() - topLeftP.getY();
}
public void removeElement(LienzoDiagramShape element) {
if(boundedElements.contains(element)) {
boundedElements.remove(element);
element.setAsUnSelected();
element.getDragRubberBand().undraw();
if(boundedElements.size() == 0) {
topLeftP.setX(0);
topLeftP.setY(0);
bottomRightP.setX(0);
bottomRightP.setY(0);
} else {
double minX = bottomRightP.getX();
double minY = bottomRightP.getY();
double maxX = topLeftP.getX();
double maxY = topLeftP.getY();
for(LienzoDiagramShape e : boundedElements) {
if(e.getDiagramElement().topLeft().getX() < minX) {
minX = e.getDiagramElement().topLeft().getX();
}
if(e.getDiagramElement().topLeft().getY() < minY) {
minY = e.getDiagramElement().topLeft().getY();
}
if(e.getDiagramElement().bottomRight().getX() > maxX) {
maxY = e.getDiagramElement().bottomRight().getX();
}
if(e.getDiagramElement().bottomRight().getY() > maxY) {
maxY = e.getDiagramElement().bottomRight().getY();
}
}
topLeftP.setX(minX);
topLeftP.setY(minY);
bottomRightP.setX(maxX);
bottomRightP.setY(maxY);
}
}
}
public Layer getBoxLayer() {
if(boundedElements.size() != 0) {
return ((LienzoDiagramShape) boundedElements.toArray()[0]).getLayer();
}
return null;
}
@Override
public BoundingBox getBoundingBox() {
return null;
}
@Override
public void dragBoundsMoved(BoundingBox newBoundingBox) {
}
public void draw(Layer layer) {
if(boundedElements.size() > 0) {
if(boundedElements.size() == 1 &&
(((LienzoDiagramShape) boundedElements.toArray()[0]).getDiagramElement().getType() == ConcreteDiagramElement.ConcreteDiagramElement_TYPES.CONCRETESPIDER ||
((LienzoDiagramShape) boundedElements.toArray()[0]).getDiagramElement().getType() == ConcreteDiagramElement.ConcreteDiagramElement_TYPES.CONCRETEARROW)) {
// don't draw things if it's a single spider or an arrow
// FIXME needs to be made cleaner ... why special cases
} else {
Point2D unit = getUnitTest();
Point2D widthHeight = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(getWidth(), getHeight()), widthHeight);
Point2D xy = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(topLeftP.getX(), topLeftP.getY()), xy);
makeRubberband();
getBoxLayer().getViewport().getDragLayer().add(rubberband);
redrawDragBoxes();
for (int i = 0; i < 8; i++) {
getBoxLayer().add(dragBoxes[i]);
}
}
//addZoomPanHandlers();
}
batch();
}
// FIXME ... can't ever get this to register????
// private void addZoomPanHandlers() {
// if (getLayer() != null) {
// getLayer().getScene().getViewport().addViewportTransformChangedHandler(new ViewportTransformChangedHandler() {
// public void onViewportTransformChanged(ViewportTransformChangedEvent viewportTransformChangedEvent) {
// redraw();
// }
// });
// }
// }
@Override
public void setAsSelected() {
}
@Override
public void setAsUnSelected() {
}
// from the new location of the rubber band (Vs the top left and bot right of the bounds)
private void notifyBoundedRubberBands() {
Point2D topLeft = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
Point2D botRight = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double widthChange;// = 1;
double heightChange;// = 1;
// if(rubberband.getWidth() == (botRight.getX() - topLeft.getX()) &&
// rubberband.getHeight() == (botRight.getY() - topLeft.getY())) {
// // MOVE ... nothing to do
// } else {
// // RESIZE
// Calculate the change ratio and adjust each element by that
widthChange = rubberband.getWidth() / (botRight.getX() - topLeft.getX());
heightChange = rubberband.getHeight() / (botRight.getY() - topLeft.getY());
// }
for(LienzoDiagramShape s : boundedElements) {
// placement of the drag rectangle has to be in screen coords
Point2D shapeTL = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(s.getDiagramElement().topLeft().asLienzoPoint2D(), shapeTL);
Point2D shapeBR = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(s.getDiagramElement().bottomRight().asLienzoPoint2D(), shapeBR);
double newWidth = (shapeBR.getX() - shapeTL.getX()) * widthChange;
double newHeight = (shapeBR.getY() - shapeTL.getY()) * heightChange;
// calculate the old top left distance and set the new one based on the percentage change
double xoffset = shapeTL.getX() - topLeft.getX();
double yoffset = shapeTL.getY() - topLeft.getY();
// but the placement has to be relative to the drag rectangle
Point2D topL = new Point2D(rubberband.getX() + (xoffset * widthChange), rubberband.getY() + (yoffset * heightChange));
Point2D botR = new Point2D(topL.getX() + newWidth, topL.getY() + newHeight);
s.getDragRubberBand().dragBoundsMoved(new BoundingBox(topL, botR));
}
}
// assume we've been setting their rubber bands
private void notifyBoundedShapes() {
for(LienzoDiagramShape s : boundedElements) {
Point2D shapeTL = new Point2D();
getBoxLayer().getViewport().getTransform().getInverse().transform(s.getDragRubberBand().getRepresentation().getLocation(), shapeTL);
Point2D shapeBR = new Point2D();
// getBoxLayer().getViewport().getTransform().getInverse().transform(new Point2D(s.getDragRubberBand().getRepresentation().getX() + s.getDragRubberBand().getRepresentation().getWidth(),
// s.getDragRubberBand().getRepresentation().getY() + s.getDragRubberBand().getRepresentation().getHeight()), shapeBR);
getBoxLayer().getViewport().getTransform().getInverse().transform(
new Point2D(s.getDragRubberBand().getRepresentation().getX() + s.getDragRubberBand().getWidth(),
s.getDragRubberBand().getRepresentation().getY() + s.getDragRubberBand().getHeight()), shapeBR);
s.dragBoundsMoved(new BoundingBox(shapeTL, shapeBR));
}
}
private void addHandlers() {
// no rubber band for select on the canvas ... probably bad way to handle this, the canvas should be in control
for (int i = 0; i < 8; i++) {
dragBoxes[i].addNodeMouseDownHandler(new NodeMouseDownHandler() {
public void onNodeMouseDown(NodeMouseDownEvent event) {
// FIXME !!!!
//getCanvas().removeRubberBandRectangle();
//getCanvas().setMode(DiagramCanvas.ModeTypes.SELECTION);
getCanvas().turnOffDragSelect();
}
});
}
for (int i = 0; i < 8; i++) {
dragBoxes[i].addNodeDragEndHandler(new NodeDragEndHandler() {
public void onNodeDragEnd(NodeDragEndEvent nodeDragEndEvent) {
Point2D newTopLeft = new Point2D(rubberband.getX(), rubberband.getY());
Point2D newbotRight = new Point2D(rubberband.getX() + rubberband.getWidth(), rubberband.getY() + rubberband.getHeight());
getBoxLayer().getViewport().getTransform().getInverse().transform(newTopLeft, topLeftP);
getBoxLayer().getViewport().getTransform().getInverse().transform(newbotRight, bottomRightP);
notifyBoundedShapes(); //newTopLeft, newbotRight);
//boundedShape.dragBoundsMoved(new BoundingBox(newTopLeft, newbotRight));
// not sure if this is necessary ... shouldn't be, but there might a race condition between the
// mouse down message above and the one in diagram canvas, so just to make sure, I'm ensuring the
// state I want at the end of the move too.
getCanvas().turnOffDragSelect();
}
});
}
// all these are screen coords ... we just care about the rubberband rectangle
dragBoxes[topLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D botRight = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX());
double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[topRight].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D topLeft = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
Point2D botRight = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[botLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D topLeft = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
Point2D botRight = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX());
double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[botRight].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D topLeft = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[top].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
dragBoxes[right].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
dragBoxes[bot].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
dragBoxes[left].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
}
// all relative to the rubber band, not the original shape
private void redrawDragBoxes() {
// hmmm don't quite understand bounding boxes ... sometimes they seem to be local, othertimes global?
// BoundingBox bbox = rubberband.getBoundingBox();
Point2D topleftXY = new Point2D();
Point2D widthHeight = new Point2D();
getBoxLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getX(), rubberband.getY()), topleftXY);
getBoxLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getWidth(), rubberband.getHeight()), widthHeight);
Point2D unit = getUnitTest(); // no need to keep calculating
// FIXME should be transforms for this right?? ok as is - cause we have done the translation to get a unit size?
double dboxLeftX = topleftXY.getX() - (unit.getX() * dragBoxSize);
double dboxTopY = topleftXY.getY() - (unit.getX() * dragBoxSize);
double dboxCentreX = topleftXY.getX() + ((widthHeight.getX() / 2) - (unit.getX() * dragBoxSize / 2));
double dboxCentreY = topleftXY.getY() + ((widthHeight.getY() / 2) - (unit.getX() * dragBoxSize / 2));
setDragBoxSizes(unit);
// FIXME need to set the drag bounds
dragBoxes[topLeft].setX(dboxLeftX);
dragBoxes[topLeft].setY(dboxTopY);
dragBoxes[topRight].setX((topleftXY.getX() + widthHeight.getX()));
dragBoxes[topRight].setY(dboxTopY);
dragBoxes[botRight].setX(topleftXY.getX() + widthHeight.getX());
dragBoxes[botRight].setY(topleftXY.getY() + widthHeight.getY());
dragBoxes[botLeft].setX(dboxLeftX);
dragBoxes[botLeft].setY(topleftXY.getY() + widthHeight.getY());
dragBoxes[top].setX(dboxCentreX);
dragBoxes[top].setY(dboxTopY);
dragBoxes[right].setX((topleftXY.getX() + widthHeight.getX()));
dragBoxes[right].setY(dboxCentreY);
dragBoxes[bot].setX(dboxCentreX);
dragBoxes[bot].setY(topleftXY.getY() + widthHeight.getY());
dragBoxes[left].setX(dboxLeftX);
dragBoxes[left].setY(dboxCentreY);
}
// does a test for what the point (1,1) translates to in the current viewport
private Point2D getUnitTest() {
if (getBoxLayer() != null) {
Point2D unit = new Point2D(1, 1);
getBoxLayer().getViewport().getTransform().getInverse().transform(unit, unitTest);
}
return unitTest;
}
private void makeRubberband() {
Point2D unit = getUnitTest();
Point2D widthHeight = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(getWidth(), getHeight()), widthHeight);
Point2D xy = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(topLeftP.getX(), topLeftP.getY()), xy);
setRubberband(xy.getX(), xy.getY(), widthHeight.getX(), widthHeight.getY());
rubberband.setStrokeWidth(unit.getX() * rubberbandLineWidth);
}
private void setRubberband(double x, double y, double width, double height) {
rubberband.setWidth(width);
rubberband.setHeight(height);
rubberband.setX(x);
rubberband.setY(y);
}
@Override
public void redraw() {
redrawDragBoxes();
//redrawRubberband();
batch();
}
private void setDragBoxSizes(Point2D unit) {
for (int i = 0; i < 8; i++) {
dragBoxes[i].setWidth(unit.getX() * dragBoxSize).setHeight(unit.getX() * dragBoxSize);
}
}
protected void batch() {
if (getLayer() != null) {
getLayer().batch();
}
if (getBoxLayer() != null) {
getBoxLayer().batch();
}
}
// screen deltas
private void dragByDelta(double dx, double dy) {
Point2D topLeft = new Point2D(); // of the group as screen coords
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
setRubberband(topLeft.getX() + dx, topLeft.getY() + dy, rubberband.getWidth(), rubberband.getHeight());
notifyBoundedRubberBands();
redraw();
}
public void undraw() {
if (getLayer() != null) {
Layer rubberbandLayer = getLayer();
rubberbandLayer.remove(rubberband);
rubberbandLayer.batch();
}
if (getBoxLayer() != null) {
Layer boxesLayer = getBoxLayer();
for (Rectangle r : dragBoxes) {
boxesLayer.remove(r);
}
boxesLayer.batch();
}
}
public void addLabel(String labelText) {
// no labels
}
}
| MichaelJCompton/ConceptDiagrams | src/main/java/org/ontologyengineering/conceptdiagrams/web/client/ui/shapes/LienzoDragBoundsGroup.java | 7,563 | // s.getDragRubberBand().getRepresentation().getY() + s.getDragRubberBand().getRepresentation().getHeight()), shapeBR); | line_comment | nl | package org.ontologyengineering.conceptdiagrams.web.client.ui.shapes;
import com.ait.lienzo.client.core.event.*;
import com.ait.lienzo.client.core.shape.Layer;
import com.ait.lienzo.client.core.shape.Node;
import com.ait.lienzo.client.core.shape.Rectangle;
import com.ait.lienzo.client.core.types.BoundingBox;
import com.ait.lienzo.client.core.types.Point2D;
import org.ontologyengineering.conceptdiagrams.web.shared.presenter.DiagramCanvas;
import org.ontologyengineering.conceptdiagrams.web.client.ui.LienzoDiagramCanvas;
import org.ontologyengineering.conceptdiagrams.web.shared.concretesyntax.ConcreteDiagramElement;
import java.util.AbstractSet;
import java.util.HashSet;
/**
* Author: Michael Compton<br>
* Date: September 2015<br>
* See license information in base directory.
*/
public class LienzoDragBoundsGroup extends LienzoDiagramShape<ConcreteDiagramElement, Node> {
private AbstractSet<LienzoDiagramShape> boundedElements;
private Point2D topLeftP, bottomRightP; // canvas coords
private Rectangle rubberband; // drawn on drag layer - screen coords
private Rectangle[] dragBoxes;
private static final int topLeft = 0; // corners
private static final int topRight = 1;
private static final int botRight = 2;
private static final int botLeft = 3;
private static final int top = 4; // sides for selection boxes
private static final int right = 5;
private static final int bot = 6;
private static final int left = 7;
private Point2D unitTest; // canvas unit
public LienzoDragBoundsGroup(LienzoDiagramCanvas canvas) {
super(canvas);
boundedElements = new HashSet<LienzoDiagramShape>();
topLeftP = new Point2D(0,0);
bottomRightP = new Point2D(0,0);
rubberband = new Rectangle(1, 1);
rubberband.setStrokeColor(rubberBandColour);
rubberband.setDraggable(false);
rubberband.setListening(false);
representation = rubberband;
dragBoxes = new Rectangle[8];
for (int i = 0; i < 8; i++) {
dragBoxes[i] = new Rectangle(dragBoxSize, dragBoxSize);
dragBoxes[i].setStrokeColor(dragBoxColour);
dragBoxes[i].setFillColor(dragBoxColour);
dragBoxes[i].setDraggable(true);
}
addHandlers();
unitTest = new Point2D();
}
public void addElement(LienzoDiagramShape element) {
boundedElements.add(element);
element.setAsSelected();
element.drawRubberBand();
if(element.getDiagramElement().getType() != ConcreteDiagramElement.ConcreteDiagramElement_TYPES.CONCRETEARROW) {
if (boundedElements.size() == 1) {
topLeftP.setX(element.getDiagramElement().topLeft().getX());
topLeftP.setY(element.getDiagramElement().topLeft().getY());
bottomRightP.setX(element.getDiagramElement().bottomRight().getX());
bottomRightP.setY(element.getDiagramElement().bottomRight().getY());
} else {
// see if the new element extends the bounds in any way
if (element.getDiagramElement().topLeft().getX() < topLeftP.getX()) {
topLeftP.setX(element.getDiagramElement().topLeft().getX());
}
if (element.getDiagramElement().topLeft().getY() < topLeftP.getY()) {
topLeftP.setY(element.getDiagramElement().topLeft().getY());
}
if (element.getDiagramElement().bottomRight().getX() > bottomRightP.getX()) {
bottomRightP.setX(element.getDiagramElement().bottomRight().getX());
}
if (element.getDiagramElement().bottomRight().getY() > bottomRightP.getY()) {
bottomRightP.setY(element.getDiagramElement().bottomRight().getY());
}
}
}
}
public void clearAndUndraw() {
undraw();
for(LienzoDiagramShape s : boundedElements) {
s.setAsUnSelected();
s.getDragRubberBand().undraw();
}
boundedElements.clear();
}
public Point2D topRight() {
return new Point2D(bottomRightP.getX(), topLeftP.getY());
}
public Point2D bottomLeft() {
return new Point2D(topLeftP.getX(), bottomRightP.getY());
}
// canvas width
public double getWidth() {
return bottomRightP.getX() - topLeftP.getX();
}
// canvas height
public double getHeight() {
return bottomRightP.getY() - topLeftP.getY();
}
public void removeElement(LienzoDiagramShape element) {
if(boundedElements.contains(element)) {
boundedElements.remove(element);
element.setAsUnSelected();
element.getDragRubberBand().undraw();
if(boundedElements.size() == 0) {
topLeftP.setX(0);
topLeftP.setY(0);
bottomRightP.setX(0);
bottomRightP.setY(0);
} else {
double minX = bottomRightP.getX();
double minY = bottomRightP.getY();
double maxX = topLeftP.getX();
double maxY = topLeftP.getY();
for(LienzoDiagramShape e : boundedElements) {
if(e.getDiagramElement().topLeft().getX() < minX) {
minX = e.getDiagramElement().topLeft().getX();
}
if(e.getDiagramElement().topLeft().getY() < minY) {
minY = e.getDiagramElement().topLeft().getY();
}
if(e.getDiagramElement().bottomRight().getX() > maxX) {
maxY = e.getDiagramElement().bottomRight().getX();
}
if(e.getDiagramElement().bottomRight().getY() > maxY) {
maxY = e.getDiagramElement().bottomRight().getY();
}
}
topLeftP.setX(minX);
topLeftP.setY(minY);
bottomRightP.setX(maxX);
bottomRightP.setY(maxY);
}
}
}
public Layer getBoxLayer() {
if(boundedElements.size() != 0) {
return ((LienzoDiagramShape) boundedElements.toArray()[0]).getLayer();
}
return null;
}
@Override
public BoundingBox getBoundingBox() {
return null;
}
@Override
public void dragBoundsMoved(BoundingBox newBoundingBox) {
}
public void draw(Layer layer) {
if(boundedElements.size() > 0) {
if(boundedElements.size() == 1 &&
(((LienzoDiagramShape) boundedElements.toArray()[0]).getDiagramElement().getType() == ConcreteDiagramElement.ConcreteDiagramElement_TYPES.CONCRETESPIDER ||
((LienzoDiagramShape) boundedElements.toArray()[0]).getDiagramElement().getType() == ConcreteDiagramElement.ConcreteDiagramElement_TYPES.CONCRETEARROW)) {
// don't draw things if it's a single spider or an arrow
// FIXME needs to be made cleaner ... why special cases
} else {
Point2D unit = getUnitTest();
Point2D widthHeight = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(getWidth(), getHeight()), widthHeight);
Point2D xy = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(topLeftP.getX(), topLeftP.getY()), xy);
makeRubberband();
getBoxLayer().getViewport().getDragLayer().add(rubberband);
redrawDragBoxes();
for (int i = 0; i < 8; i++) {
getBoxLayer().add(dragBoxes[i]);
}
}
//addZoomPanHandlers();
}
batch();
}
// FIXME ... can't ever get this to register????
// private void addZoomPanHandlers() {
// if (getLayer() != null) {
// getLayer().getScene().getViewport().addViewportTransformChangedHandler(new ViewportTransformChangedHandler() {
// public void onViewportTransformChanged(ViewportTransformChangedEvent viewportTransformChangedEvent) {
// redraw();
// }
// });
// }
// }
@Override
public void setAsSelected() {
}
@Override
public void setAsUnSelected() {
}
// from the new location of the rubber band (Vs the top left and bot right of the bounds)
private void notifyBoundedRubberBands() {
Point2D topLeft = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
Point2D botRight = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double widthChange;// = 1;
double heightChange;// = 1;
// if(rubberband.getWidth() == (botRight.getX() - topLeft.getX()) &&
// rubberband.getHeight() == (botRight.getY() - topLeft.getY())) {
// // MOVE ... nothing to do
// } else {
// // RESIZE
// Calculate the change ratio and adjust each element by that
widthChange = rubberband.getWidth() / (botRight.getX() - topLeft.getX());
heightChange = rubberband.getHeight() / (botRight.getY() - topLeft.getY());
// }
for(LienzoDiagramShape s : boundedElements) {
// placement of the drag rectangle has to be in screen coords
Point2D shapeTL = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(s.getDiagramElement().topLeft().asLienzoPoint2D(), shapeTL);
Point2D shapeBR = new Point2D(); // of the bounds as screen coords
getBoxLayer().getViewport().getTransform().transform(s.getDiagramElement().bottomRight().asLienzoPoint2D(), shapeBR);
double newWidth = (shapeBR.getX() - shapeTL.getX()) * widthChange;
double newHeight = (shapeBR.getY() - shapeTL.getY()) * heightChange;
// calculate the old top left distance and set the new one based on the percentage change
double xoffset = shapeTL.getX() - topLeft.getX();
double yoffset = shapeTL.getY() - topLeft.getY();
// but the placement has to be relative to the drag rectangle
Point2D topL = new Point2D(rubberband.getX() + (xoffset * widthChange), rubberband.getY() + (yoffset * heightChange));
Point2D botR = new Point2D(topL.getX() + newWidth, topL.getY() + newHeight);
s.getDragRubberBand().dragBoundsMoved(new BoundingBox(topL, botR));
}
}
// assume we've been setting their rubber bands
private void notifyBoundedShapes() {
for(LienzoDiagramShape s : boundedElements) {
Point2D shapeTL = new Point2D();
getBoxLayer().getViewport().getTransform().getInverse().transform(s.getDragRubberBand().getRepresentation().getLocation(), shapeTL);
Point2D shapeBR = new Point2D();
// getBoxLayer().getViewport().getTransform().getInverse().transform(new Point2D(s.getDragRubberBand().getRepresentation().getX() + s.getDragRubberBand().getRepresentation().getWidth(),
// s.getDragRubberBand().getRepresentation().getY() +<SUF>
getBoxLayer().getViewport().getTransform().getInverse().transform(
new Point2D(s.getDragRubberBand().getRepresentation().getX() + s.getDragRubberBand().getWidth(),
s.getDragRubberBand().getRepresentation().getY() + s.getDragRubberBand().getHeight()), shapeBR);
s.dragBoundsMoved(new BoundingBox(shapeTL, shapeBR));
}
}
private void addHandlers() {
// no rubber band for select on the canvas ... probably bad way to handle this, the canvas should be in control
for (int i = 0; i < 8; i++) {
dragBoxes[i].addNodeMouseDownHandler(new NodeMouseDownHandler() {
public void onNodeMouseDown(NodeMouseDownEvent event) {
// FIXME !!!!
//getCanvas().removeRubberBandRectangle();
//getCanvas().setMode(DiagramCanvas.ModeTypes.SELECTION);
getCanvas().turnOffDragSelect();
}
});
}
for (int i = 0; i < 8; i++) {
dragBoxes[i].addNodeDragEndHandler(new NodeDragEndHandler() {
public void onNodeDragEnd(NodeDragEndEvent nodeDragEndEvent) {
Point2D newTopLeft = new Point2D(rubberband.getX(), rubberband.getY());
Point2D newbotRight = new Point2D(rubberband.getX() + rubberband.getWidth(), rubberband.getY() + rubberband.getHeight());
getBoxLayer().getViewport().getTransform().getInverse().transform(newTopLeft, topLeftP);
getBoxLayer().getViewport().getTransform().getInverse().transform(newbotRight, bottomRightP);
notifyBoundedShapes(); //newTopLeft, newbotRight);
//boundedShape.dragBoundsMoved(new BoundingBox(newTopLeft, newbotRight));
// not sure if this is necessary ... shouldn't be, but there might a race condition between the
// mouse down message above and the one in diagram canvas, so just to make sure, I'm ensuring the
// state I want at the end of the move too.
getCanvas().turnOffDragSelect();
}
});
}
// all these are screen coords ... we just care about the rubberband rectangle
dragBoxes[topLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D botRight = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX());
double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[topRight].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D topLeft = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
Point2D botRight = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[botLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D topLeft = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
Point2D botRight = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(bottomRightP, botRight);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX());
double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[botRight].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
Point2D topLeft = new Point2D(); // of the on screen shape
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
double newX = rubberband.getX();
double newY = rubberband.getY();
double newWidth = rubberband.getWidth();
double newHeight = rubberband.getHeight();
double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
if (width >= ConcreteDiagramElement.curveMinWidth) {
newWidth = width;
newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX());
}
if (height >= ConcreteDiagramElement.curveMinHeight) {
newHeight = height;
newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
}
setRubberband(newX, newY, newWidth, newHeight);
notifyBoundedRubberBands();
redraw();
}
});
dragBoxes[top].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
dragBoxes[right].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
dragBoxes[bot].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
dragBoxes[left].addNodeDragMoveHandler(new NodeDragMoveHandler() {
public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) {
dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy());
}
});
}
// all relative to the rubber band, not the original shape
private void redrawDragBoxes() {
// hmmm don't quite understand bounding boxes ... sometimes they seem to be local, othertimes global?
// BoundingBox bbox = rubberband.getBoundingBox();
Point2D topleftXY = new Point2D();
Point2D widthHeight = new Point2D();
getBoxLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getX(), rubberband.getY()), topleftXY);
getBoxLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getWidth(), rubberband.getHeight()), widthHeight);
Point2D unit = getUnitTest(); // no need to keep calculating
// FIXME should be transforms for this right?? ok as is - cause we have done the translation to get a unit size?
double dboxLeftX = topleftXY.getX() - (unit.getX() * dragBoxSize);
double dboxTopY = topleftXY.getY() - (unit.getX() * dragBoxSize);
double dboxCentreX = topleftXY.getX() + ((widthHeight.getX() / 2) - (unit.getX() * dragBoxSize / 2));
double dboxCentreY = topleftXY.getY() + ((widthHeight.getY() / 2) - (unit.getX() * dragBoxSize / 2));
setDragBoxSizes(unit);
// FIXME need to set the drag bounds
dragBoxes[topLeft].setX(dboxLeftX);
dragBoxes[topLeft].setY(dboxTopY);
dragBoxes[topRight].setX((topleftXY.getX() + widthHeight.getX()));
dragBoxes[topRight].setY(dboxTopY);
dragBoxes[botRight].setX(topleftXY.getX() + widthHeight.getX());
dragBoxes[botRight].setY(topleftXY.getY() + widthHeight.getY());
dragBoxes[botLeft].setX(dboxLeftX);
dragBoxes[botLeft].setY(topleftXY.getY() + widthHeight.getY());
dragBoxes[top].setX(dboxCentreX);
dragBoxes[top].setY(dboxTopY);
dragBoxes[right].setX((topleftXY.getX() + widthHeight.getX()));
dragBoxes[right].setY(dboxCentreY);
dragBoxes[bot].setX(dboxCentreX);
dragBoxes[bot].setY(topleftXY.getY() + widthHeight.getY());
dragBoxes[left].setX(dboxLeftX);
dragBoxes[left].setY(dboxCentreY);
}
// does a test for what the point (1,1) translates to in the current viewport
private Point2D getUnitTest() {
if (getBoxLayer() != null) {
Point2D unit = new Point2D(1, 1);
getBoxLayer().getViewport().getTransform().getInverse().transform(unit, unitTest);
}
return unitTest;
}
private void makeRubberband() {
Point2D unit = getUnitTest();
Point2D widthHeight = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(getWidth(), getHeight()), widthHeight);
Point2D xy = new Point2D();
getBoxLayer().getViewport().getTransform().transform(new Point2D(topLeftP.getX(), topLeftP.getY()), xy);
setRubberband(xy.getX(), xy.getY(), widthHeight.getX(), widthHeight.getY());
rubberband.setStrokeWidth(unit.getX() * rubberbandLineWidth);
}
private void setRubberband(double x, double y, double width, double height) {
rubberband.setWidth(width);
rubberband.setHeight(height);
rubberband.setX(x);
rubberband.setY(y);
}
@Override
public void redraw() {
redrawDragBoxes();
//redrawRubberband();
batch();
}
private void setDragBoxSizes(Point2D unit) {
for (int i = 0; i < 8; i++) {
dragBoxes[i].setWidth(unit.getX() * dragBoxSize).setHeight(unit.getX() * dragBoxSize);
}
}
protected void batch() {
if (getLayer() != null) {
getLayer().batch();
}
if (getBoxLayer() != null) {
getBoxLayer().batch();
}
}
// screen deltas
private void dragByDelta(double dx, double dy) {
Point2D topLeft = new Point2D(); // of the group as screen coords
getBoxLayer().getViewport().getTransform().transform(topLeftP, topLeft);
setRubberband(topLeft.getX() + dx, topLeft.getY() + dy, rubberband.getWidth(), rubberband.getHeight());
notifyBoundedRubberBands();
redraw();
}
public void undraw() {
if (getLayer() != null) {
Layer rubberbandLayer = getLayer();
rubberbandLayer.remove(rubberband);
rubberbandLayer.batch();
}
if (getBoxLayer() != null) {
Layer boxesLayer = getBoxLayer();
for (Rectangle r : dragBoxes) {
boxesLayer.remove(r);
}
boxesLayer.batch();
}
}
public void addLabel(String labelText) {
// no labels
}
}
|
28307_8 | /**********************************************************************
* $Source: /cvsroot/hibiscus/hibiscus/src/de/willuhn/jameica/hbci/gui/input/TerminInput.java,v $
* $Revision: 1.3 $
* $Date: 2011/10/20 16:20:05 $
* $Author: willuhn $
*
* Copyright (c) by willuhn - software & services
* All rights reserved
*
**********************************************************************/
package de.willuhn.jameica.hbci.gui.input;
import java.rmi.RemoteException;
import java.util.Date;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import de.willuhn.jameica.gui.input.DateInput;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.hbci.rmi.Terminable;
import de.willuhn.jameica.messaging.QueryMessage;
import de.willuhn.jameica.system.Application;
import de.willuhn.logging.Logger;
import de.willuhn.util.I18N;
/**
* Vorkonfiguriertes Eingabefeld fuer einen Termin.
*/
public class TerminInput extends DateInput
{
/**
* Queue, die bei Aenderungen benachrichtigt wird.
*/
public final static String QUEUE_TERMIN_CHANGED = "hibiscus.termin.changed";
private final static I18N i18n = Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N();
private Terminable auftrag = null;
private Listener listener = null;
/**
* ct.
* @param auftrag der terminierbare Auftrag.
* @throws RemoteException
*/
public TerminInput(Terminable auftrag) throws RemoteException
{
super(getPreset(auftrag),HBCI.DATEFORMAT);
this.auftrag = auftrag;
// Deaktivieren, wenn ein ausgefuehrter Auftrag uebergeben wurde
if (auftrag != null)
this.setEnabled(!auftrag.ausgefuehrt());
this.setName(i18n.tr("Erinnerungstermin"));
this.setTitle(i18n.tr("Erinnerung"));
this.setText(i18n.tr("Bitte wählen Sie ein Datum aus, zu dem\nHibiscus Sie an den Auftrag erinnern soll."));
this.setComment("");
this.setMandatory(true);
this.listener = new MyListener();
this.listener.handleEvent(null); // einmal ausloesen
this.addListener(this.listener);
}
/**
* Liefert das Vorgabedatum fuer den Auftrag.
* @param auftrag
* @return das Vorgabedatum.
* @throws RemoteException
*/
private static Date getPreset(Terminable auftrag) throws RemoteException
{
if (auftrag == null)
return new Date();
Date date = auftrag.getTermin();
return date != null ? date : new Date();
}
/**
* Aktualisiert den Kommentar basierend auf den aktuellen Eigenschaften des Auftrages.
*/
public void updateComment()
{
this.listener.handleEvent(null);
}
/**
* Wird beim Aendern des Termins ausgeloest.
*/
private class MyListener implements Listener
{
/**
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event)
{
try
{
if (auftrag == null)
return;
Date date = (Date) getValue();
if (date == null)
{
date = new Date(); // Wenn der User nichts eingibt, nehmen wir heute
setValue(date);
}
Application.getMessagingFactory().getMessagingQueue(QUEUE_TERMIN_CHANGED).sendMessage(new QueryMessage(date));
// Wir muessen den Termin im Objekt setzen, damit wir die
// Faelligkeits-Entscheidung treffen koennen
auftrag.setTermin(date);
if (auftrag.ausgefuehrt())
{
// checken, ob wir auch noch das Ausfuehrungsdatum haben
Date ausgefuehrt = auftrag.getAusfuehrungsdatum();
if (ausgefuehrt != null)
setComment(i18n.tr("Am {0} ausgeführt",HBCI.DATEFORMAT.format(ausgefuehrt)));
else
setComment(i18n.tr("Bereits ausgeführt"));
}
else if (auftrag.ueberfaellig())
setComment(i18n.tr("Der Auftrag ist fällig"));
else
setComment("");
}
catch (Exception e)
{
Logger.error("unable to check overdue",e);
}
}
}
}
/**********************************************************************
* $Log: TerminInput.java,v $
* Revision 1.3 2011/10/20 16:20:05 willuhn
* @N BUGZILLA 182 - Erste Version von client-seitigen Dauerauftraegen fuer alle Auftragsarten
*
* Revision 1.2 2011-06-24 07:55:41 willuhn
* @C Bei Hibiscus-verwalteten Terminen besser "Fällig am" verwenden - ist nicht so missverstaendlich - der User denkt sonst ggf. es sei ein bankseitig terminierter Auftrag
*
* Revision 1.1 2011-05-20 16:22:31 willuhn
* @N Termin-Eingabefeld in eigene Klasse ausgelagert (verhindert duplizierten Code) - bessere Kommentare
*
**********************************************************************/ | MichaelSp/hibiscus | src/de/willuhn/jameica/hbci/gui/input/TerminInput.java | 1,639 | /**
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/ | block_comment | nl | /**********************************************************************
* $Source: /cvsroot/hibiscus/hibiscus/src/de/willuhn/jameica/hbci/gui/input/TerminInput.java,v $
* $Revision: 1.3 $
* $Date: 2011/10/20 16:20:05 $
* $Author: willuhn $
*
* Copyright (c) by willuhn - software & services
* All rights reserved
*
**********************************************************************/
package de.willuhn.jameica.hbci.gui.input;
import java.rmi.RemoteException;
import java.util.Date;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import de.willuhn.jameica.gui.input.DateInput;
import de.willuhn.jameica.hbci.HBCI;
import de.willuhn.jameica.hbci.rmi.Terminable;
import de.willuhn.jameica.messaging.QueryMessage;
import de.willuhn.jameica.system.Application;
import de.willuhn.logging.Logger;
import de.willuhn.util.I18N;
/**
* Vorkonfiguriertes Eingabefeld fuer einen Termin.
*/
public class TerminInput extends DateInput
{
/**
* Queue, die bei Aenderungen benachrichtigt wird.
*/
public final static String QUEUE_TERMIN_CHANGED = "hibiscus.termin.changed";
private final static I18N i18n = Application.getPluginLoader().getPlugin(HBCI.class).getResources().getI18N();
private Terminable auftrag = null;
private Listener listener = null;
/**
* ct.
* @param auftrag der terminierbare Auftrag.
* @throws RemoteException
*/
public TerminInput(Terminable auftrag) throws RemoteException
{
super(getPreset(auftrag),HBCI.DATEFORMAT);
this.auftrag = auftrag;
// Deaktivieren, wenn ein ausgefuehrter Auftrag uebergeben wurde
if (auftrag != null)
this.setEnabled(!auftrag.ausgefuehrt());
this.setName(i18n.tr("Erinnerungstermin"));
this.setTitle(i18n.tr("Erinnerung"));
this.setText(i18n.tr("Bitte wählen Sie ein Datum aus, zu dem\nHibiscus Sie an den Auftrag erinnern soll."));
this.setComment("");
this.setMandatory(true);
this.listener = new MyListener();
this.listener.handleEvent(null); // einmal ausloesen
this.addListener(this.listener);
}
/**
* Liefert das Vorgabedatum fuer den Auftrag.
* @param auftrag
* @return das Vorgabedatum.
* @throws RemoteException
*/
private static Date getPreset(Terminable auftrag) throws RemoteException
{
if (auftrag == null)
return new Date();
Date date = auftrag.getTermin();
return date != null ? date : new Date();
}
/**
* Aktualisiert den Kommentar basierend auf den aktuellen Eigenschaften des Auftrages.
*/
public void updateComment()
{
this.listener.handleEvent(null);
}
/**
* Wird beim Aendern des Termins ausgeloest.
*/
private class MyListener implements Listener
{
/**
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
<SUF>*/
public void handleEvent(Event event)
{
try
{
if (auftrag == null)
return;
Date date = (Date) getValue();
if (date == null)
{
date = new Date(); // Wenn der User nichts eingibt, nehmen wir heute
setValue(date);
}
Application.getMessagingFactory().getMessagingQueue(QUEUE_TERMIN_CHANGED).sendMessage(new QueryMessage(date));
// Wir muessen den Termin im Objekt setzen, damit wir die
// Faelligkeits-Entscheidung treffen koennen
auftrag.setTermin(date);
if (auftrag.ausgefuehrt())
{
// checken, ob wir auch noch das Ausfuehrungsdatum haben
Date ausgefuehrt = auftrag.getAusfuehrungsdatum();
if (ausgefuehrt != null)
setComment(i18n.tr("Am {0} ausgeführt",HBCI.DATEFORMAT.format(ausgefuehrt)));
else
setComment(i18n.tr("Bereits ausgeführt"));
}
else if (auftrag.ueberfaellig())
setComment(i18n.tr("Der Auftrag ist fällig"));
else
setComment("");
}
catch (Exception e)
{
Logger.error("unable to check overdue",e);
}
}
}
}
/**********************************************************************
* $Log: TerminInput.java,v $
* Revision 1.3 2011/10/20 16:20:05 willuhn
* @N BUGZILLA 182 - Erste Version von client-seitigen Dauerauftraegen fuer alle Auftragsarten
*
* Revision 1.2 2011-06-24 07:55:41 willuhn
* @C Bei Hibiscus-verwalteten Terminen besser "Fällig am" verwenden - ist nicht so missverstaendlich - der User denkt sonst ggf. es sei ein bankseitig terminierter Auftrag
*
* Revision 1.1 2011-05-20 16:22:31 willuhn
* @N Termin-Eingabefeld in eigene Klasse ausgelagert (verhindert duplizierten Code) - bessere Kommentare
*
**********************************************************************/ |
198234_15 | /**
* Copyright (C) 2012 Brendan Robert (BLuRry) [email protected].
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package jace;
import com.sun.javafx.tk.quantum.OverlayWarning;
import jace.apple2e.MOS65C02;
import jace.apple2e.RAM128k;
import jace.apple2e.SoftSwitches;
import jace.config.ConfigurationUIController;
import jace.config.InvokableAction;
import jace.config.Reconfigurable;
import jace.core.CPU;
import jace.core.Computer;
import jace.core.Debugger;
import jace.core.RAM;
import jace.core.RAMListener;
import static jace.core.Utility.*;
import jace.ide.IdeController;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
* This class contains miscellaneous user-invoked actions such as debugger
* operations and running arbitrary files in the emulator. It is possible for
* these methods to be later refactored into more sensible locations. Created on
* April 16, 2007, 10:30 PM
*
* @author Brendan Robert (BLuRry) [email protected]
*/
public class EmulatorUILogic implements Reconfigurable {
static Debugger debugger;
static {
debugger = new Debugger() {
@Override
public void updateStatus() {
enableDebug(true);
MOS65C02 cpu = (MOS65C02) Emulator.computer.getCpu();
updateCPURegisters(cpu);
}
};
}
public static void updateCPURegisters(MOS65C02 cpu) {
// DebuggerPanel debuggerPanel = Emulator.getFrame().getDebuggerPanel();
// debuggerPanel.valueA.setText(Integer.toHexString(cpu.A));
// debuggerPanel.valueX.setText(Integer.toHexString(cpu.X));
// debuggerPanel.valueY.setText(Integer.toHexString(cpu.Y));
// debuggerPanel.valuePC.setText(Integer.toHexString(cpu.getProgramCounter()));
// debuggerPanel.valueSP.setText(Integer.toHexString(cpu.getSTACK()));
// debuggerPanel.valuePC2.setText(cpu.getFlags());
// debuggerPanel.valueINST.setText(cpu.disassemble());
}
public static void enableDebug(boolean b) {
// DebuggerPanel debuggerPanel = Emulator.getFrame().getDebuggerPanel();
// debugger.setActive(b);
// debuggerPanel.enableDebug.setSelected(b);
// debuggerPanel.setBackground(
// b ? Color.RED : new Color(0, 0, 0x040));
}
public static void enableTrace(boolean b) {
Emulator.computer.getCpu().setTraceEnabled(b);
}
public static void stepForward() {
debugger.step = true;
}
static void registerDebugger() {
Emulator.computer.getCpu().setDebug(debugger);
}
public static Integer getValidAddress(String s) {
try {
int addr = Integer.parseInt(s.toUpperCase(), 16);
if (addr >= 0 && addr < 0x10000) {
return addr;
}
return null;
} catch (NumberFormatException ex) {
return null;
}
}
public static List<RAMListener> watches = new ArrayList<>();
// public static void updateWatchList(final DebuggerPanel panel) {
// java.awt.EventQueue.invokeLater(() -> {
// watches.stream().forEach((oldWatch) -> {
// Emulator.computer.getMemory().removeListener(oldWatch);
// });
// if (panel == null) {
// return;
// }
// addWatch(panel.textW1, panel.valueW1);
// addWatch(panel.textW2, panel.valueW2);
// addWatch(panel.textW3, panel.valueW3);
// addWatch(panel.textW4, panel.valueW4);
// });
// }
//
// private static void addWatch(JTextField watch, final JLabel watchValue) {
// final Integer address = getValidAddress(watch.getText());
// if (address != null) {
// //System.out.println("Adding watch for "+Integer.toString(address, 16));
// RAMListener newListener = new RAMListener(RAMEvent.TYPE.WRITE, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {
// @Override
// protected void doConfig() {
// setScopeStart(address);
// }
//
// @Override
// protected void doEvent(RAMEvent e) {
// watchValue.setText(Integer.toHexString(e.getNewValue() & 0x0FF));
// }
// };
// Emulator.computer.getMemory().addListener(newListener);
// watches.add(newListener);
// // Print out the current value right away
// byte b = Emulator.computer.getMemory().readRaw(address);
// watchValue.setText(Integer.toString(b & 0x0ff, 16));
// } else {
// watchValue.setText("00");
// }
// }
// public static void updateBreakpointList(final DebuggerPanel panel) {
// java.awt.EventQueue.invokeLater(() -> {
// Integer address;
// debugger.getBreakpoints().clear();
// if (panel == null) {
// return;
// }
// address = getValidAddress(panel.textBP1.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// address = getValidAddress(panel.textBP2.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// address = getValidAddress(panel.textBP3.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// address = getValidAddress(panel.textBP4.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// debugger.updateBreakpoints();
// });
// }
//
@InvokableAction(
name = "BRUN file",
category = "file",
description = "Loads a binary file in memory and executes it. File should end with #06xxxx, where xxxx is the start address in hex",
alternatives = "Execute program;Load binary;Load program;Load rom;Play single-load game",
defaultKeyMapping = "ctrl+shift+b")
public static void runFile() {
Emulator.computer.pause();
FileChooser select = new FileChooser();
File binary = select.showOpenDialog(JaceApplication.getApplication().primaryStage);
if (binary == null) {
Emulator.computer.resume();
return;
}
runFileNamed(binary);
}
public static void runFileNamed(File binary) {
String fileName = binary.getName().toLowerCase();
try {
if (fileName.contains("#06")) {
String addressStr = fileName.substring(fileName.length() - 4);
int address = Integer.parseInt(addressStr, 16);
brun(binary, address);
} else if (fileName.contains("#fc")) {
gripe("BASIC not supported yet");
}
} catch (NumberFormatException | IOException ex) {
}
Emulator.computer.getCpu().resume();
}
public static void brun(File binary, int address) throws FileNotFoundException, IOException {
// If it was halted already, then it was initiated outside of an opcode execution
// If it was not yet halted, then it is the case that the CPU is processing another opcode
// So if that is the case, the program counter will need to be decremented here to compensate
// TODO: Find a better mousetrap for this one -- it's an ugly hack
Emulator.computer.pause();
FileInputStream in = new FileInputStream(binary);
byte[] data = new byte[in.available()];
in.read(data);
RAM ram = Emulator.computer.getMemory();
for (int i = 0; i < data.length; i++) {
ram.write(address + i, data[i], false, true);
}
CPU cpu = Emulator.computer.getCpu();
Emulator.computer.getCpu().setProgramCounter(address);
Emulator.computer.resume();
}
@InvokableAction(
name = "Toggle Debug",
category = "debug",
description = "Show/hide the debug panel",
alternatives = "Show Debug;Hide Debug",
defaultKeyMapping = "ctrl+shift+d")
public static void toggleDebugPanel() {
// AbstractEmulatorFrame frame = Emulator.getFrame();
// if (frame == null) {
// return;
// }
// frame.setShowDebug(!frame.isShowDebug());
// frame.reconfigure();
// Emulator.resizeVideo();
}
@InvokableAction(
name = "Toggle fullscreen",
category = "general",
description = "Activate/deactivate fullscreen mode",
alternatives = "fullscreen,maximize",
defaultKeyMapping = "ctrl+shift+f")
public static void toggleFullscreen() {
Platform.runLater(() -> {
Stage stage = JaceApplication.getApplication().primaryStage;
stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
stage.setFullScreen(!stage.isFullScreen());
});
}
@InvokableAction(
name = "Save Raw Screenshot",
category = "general",
description = "Save raw (RAM) format of visible screen",
alternatives = "screendump, raw screenshot",
defaultKeyMapping = "ctrl+shift+z")
public static void saveScreenshotRaw() throws FileNotFoundException, IOException {
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
String timestamp = df.format(new Date());
String type;
int start = Emulator.computer.getVideo().getCurrentWriter().actualWriter().getYOffset(0);
int len;
if (start < 0x02000) {
// Lo-res or double-lores
len = 0x0400;
type = "gr";
} else {
// Hi-res or double-hires
len = 0x02000;
type = "hgr";
}
boolean dres = SoftSwitches._80COL.getState() && (SoftSwitches.DHIRES.getState() || start < 0x02000);
if (dres) {
type = "d" + type;
}
File outFile = new File("screen_" + type + "_a" + Integer.toHexString(start) + "_" + timestamp);
try (FileOutputStream out = new FileOutputStream(outFile)) {
RAM128k ram = (RAM128k) Emulator.computer.memory;
Emulator.computer.pause();
if (dres) {
for (int i = 0; i < len; i++) {
out.write(ram.getAuxVideoMemory().readByte(start + i));
}
}
for (int i = 0; i < len; i++) {
out.write(ram.getMainMemory().readByte(start + i));
}
}
System.out.println("Wrote screenshot to " + outFile.getAbsolutePath());
}
@InvokableAction(
name = "Save Screenshot",
category = "general",
description = "Save image of visible screen",
alternatives = "Save image,save framebuffer,screenshot",
defaultKeyMapping = "ctrl+shift+s")
public static void saveScreenshot() throws IOException {
FileChooser select = new FileChooser();
Emulator.computer.pause();
Image i = Emulator.computer.getVideo().getFrameBuffer();
// BufferedImage bufImageARGB = SwingFXUtils.fromFXImage(i, null);
File targetFile = select.showSaveDialog(JaceApplication.getApplication().primaryStage);
if (targetFile == null) {
return;
}
String filename = targetFile.getName();
System.out.println("Writing screenshot to " + filename);
String extension = filename.substring(filename.lastIndexOf(".") + 1);
// BufferedImage bufImageRGB = new BufferedImage(bufImageARGB.getWidth(), bufImageARGB.getHeight(), BufferedImage.OPAQUE);
//
// Graphics2D graphics = bufImageRGB.createGraphics();
// graphics.drawImage(bufImageARGB, 0, 0, null);
//
// ImageIO.write(bufImageRGB, extension, targetFile);
// graphics.dispose();
}
public static final String CONFIGURATION_DIALOG_NAME = "Configuration";
@InvokableAction(
name = "Configuration",
category = "general",
description = "Edit emulator configuraion",
alternatives = "Reconfigure,Preferences,Settings",
defaultKeyMapping = {"f4", "ctrl+shift+c"})
public static void showConfig() {
FXMLLoader fxmlLoader = new FXMLLoader(EmulatorUILogic.class.getResource("/fxml/Configuration.fxml"));
fxmlLoader.setResources(null);
try {
Stage configWindow = new Stage();
AnchorPane node = (AnchorPane) fxmlLoader.load();
ConfigurationUIController controller = fxmlLoader.getController();
controller.initialize();
Scene s = new Scene(node);
configWindow.setScene(s);
configWindow.show();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
@InvokableAction(
name = "Open IDE",
category = "development",
description = "Open new IDE window for Basic/Assembly/Plasma coding",
alternatives = "dev,development,acme,assembler,editor",
defaultKeyMapping = {"ctrl+shift+i"})
public static void showIDE() {
FXMLLoader fxmlLoader = new FXMLLoader(EmulatorUILogic.class.getResource("/fxml/editor.fxml"));
fxmlLoader.setResources(null);
try {
Stage editorWindow = new Stage();
AnchorPane node = (AnchorPane) fxmlLoader.load();
IdeController controller = fxmlLoader.getController();
controller.initialize();
Scene s = new Scene(node);
editorWindow.setScene(s);
editorWindow.show();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
static int size = -1;
@InvokableAction(
name = "Resize window",
category = "general",
description = "Resize the screen to 1x/1.5x/2x/3x video size",
alternatives = "Adjust screen;Adjust window size;Adjust aspect ratio;Fix screen;Fix window size;Fix aspect ratio;Correct aspect ratio;",
defaultKeyMapping = {"ctrl+shift+a"})
public static void scaleIntegerRatio() {
Platform.runLater(() -> {
JaceApplication.getApplication().primaryStage.setFullScreen(false);
size++;
if (size > 3) {
size = 0;
}
int width = 0, height = 0;
switch (size) {
case 0: // 1x
width = 560;
height = 384;
break;
case 1: // 1.5x
width = 840;
height = 576;
break;
case 2: // 2x
width = 560*2;
height = 384*2;
break;
case 3: // 3x (retina) 2880x1800
width = 560*3;
height = 384*3;
break;
default: // 2x
width = 560*2;
height = 384*2;
}
Stage stage = JaceApplication.getApplication().primaryStage;
double vgap = stage.getScene().getY();
double hgap = stage.getScene().getX();
stage.setWidth(hgap*2 + width);
stage.setHeight(vgap + height);
});
}
public static boolean confirm(String message) {
// return JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(Emulator.getFrame(), message);
return false;
}
static final Map<Object, Set<Label>> INDICATORS = new HashMap<>();
static public void addIndicator(Object owner, Label icon) {
addIndicator(owner, icon, 250);
}
static public void addIndicator(Object owner, Label icon, long TTL) {
if (JaceApplication.getApplication() == null) {
return;
}
synchronized (INDICATORS) {
Set<Label> ind = INDICATORS.get(owner);
if (ind == null) {
ind = new HashSet<>();
INDICATORS.put(owner, ind);
}
ind.add(icon);
JaceApplication.getApplication().controller.addIndicator(icon);
}
}
static public void removeIndicator(Object owner, Label icon) {
if (JaceApplication.singleton == null) {
return;
}
synchronized (INDICATORS) {
Set<Label> ind = INDICATORS.get(owner);
if (ind != null) {
ind.remove(icon);
}
JaceApplication.singleton.controller.removeIndicator(icon);
}
}
static public void removeIndicators(Object owner) {
if (JaceApplication.singleton == null) {
return;
}
synchronized (INDICATORS) {
Set<Label> ind = INDICATORS.get(owner);
if (ind == null) {
return;
}
ind.stream().forEach((icon) -> {
JaceApplication.singleton.controller.removeIndicator(icon);
});
INDICATORS.remove(owner);
}
}
static public void addMouseListener(EventHandler<MouseEvent> handler) {
if (JaceApplication.singleton != null) {
JaceApplication.singleton.controller.addMouseListener(handler);
}
}
static public void removeMouseListener(EventHandler<MouseEvent> handler) {
if (JaceApplication.singleton != null) {
JaceApplication.singleton.controller.removeMouseListener(handler);
}
}
public static void simulateCtrlAppleReset() {
Computer computer = JaceApplication.singleton.controller.computer;
computer.keyboard.openApple(true);
computer.warmStart();
Platform.runLater(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(EmulatorUILogic.class.getName()).log(Level.SEVERE, null, ex);
}
computer.keyboard.openApple(false);
});
}
public static void notify(String message) {
if (JaceApplication.singleton != null) {
JaceApplication.singleton.controller.displayNotification(message);
}
}
@Override
public String getName() {
return "Jace User Interface";
}
@Override
public String getShortName() {
return "UI";
}
@Override
public void reconfigure() {
}
}
| Michaelangel007/jace | src/main/java/jace/EmulatorUILogic.java | 5,889 | // protected void doEvent(RAMEvent e) {
| line_comment | nl | /**
* Copyright (C) 2012 Brendan Robert (BLuRry) [email protected].
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package jace;
import com.sun.javafx.tk.quantum.OverlayWarning;
import jace.apple2e.MOS65C02;
import jace.apple2e.RAM128k;
import jace.apple2e.SoftSwitches;
import jace.config.ConfigurationUIController;
import jace.config.InvokableAction;
import jace.config.Reconfigurable;
import jace.core.CPU;
import jace.core.Computer;
import jace.core.Debugger;
import jace.core.RAM;
import jace.core.RAMListener;
import static jace.core.Utility.*;
import jace.ide.IdeController;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
* This class contains miscellaneous user-invoked actions such as debugger
* operations and running arbitrary files in the emulator. It is possible for
* these methods to be later refactored into more sensible locations. Created on
* April 16, 2007, 10:30 PM
*
* @author Brendan Robert (BLuRry) [email protected]
*/
public class EmulatorUILogic implements Reconfigurable {
static Debugger debugger;
static {
debugger = new Debugger() {
@Override
public void updateStatus() {
enableDebug(true);
MOS65C02 cpu = (MOS65C02) Emulator.computer.getCpu();
updateCPURegisters(cpu);
}
};
}
public static void updateCPURegisters(MOS65C02 cpu) {
// DebuggerPanel debuggerPanel = Emulator.getFrame().getDebuggerPanel();
// debuggerPanel.valueA.setText(Integer.toHexString(cpu.A));
// debuggerPanel.valueX.setText(Integer.toHexString(cpu.X));
// debuggerPanel.valueY.setText(Integer.toHexString(cpu.Y));
// debuggerPanel.valuePC.setText(Integer.toHexString(cpu.getProgramCounter()));
// debuggerPanel.valueSP.setText(Integer.toHexString(cpu.getSTACK()));
// debuggerPanel.valuePC2.setText(cpu.getFlags());
// debuggerPanel.valueINST.setText(cpu.disassemble());
}
public static void enableDebug(boolean b) {
// DebuggerPanel debuggerPanel = Emulator.getFrame().getDebuggerPanel();
// debugger.setActive(b);
// debuggerPanel.enableDebug.setSelected(b);
// debuggerPanel.setBackground(
// b ? Color.RED : new Color(0, 0, 0x040));
}
public static void enableTrace(boolean b) {
Emulator.computer.getCpu().setTraceEnabled(b);
}
public static void stepForward() {
debugger.step = true;
}
static void registerDebugger() {
Emulator.computer.getCpu().setDebug(debugger);
}
public static Integer getValidAddress(String s) {
try {
int addr = Integer.parseInt(s.toUpperCase(), 16);
if (addr >= 0 && addr < 0x10000) {
return addr;
}
return null;
} catch (NumberFormatException ex) {
return null;
}
}
public static List<RAMListener> watches = new ArrayList<>();
// public static void updateWatchList(final DebuggerPanel panel) {
// java.awt.EventQueue.invokeLater(() -> {
// watches.stream().forEach((oldWatch) -> {
// Emulator.computer.getMemory().removeListener(oldWatch);
// });
// if (panel == null) {
// return;
// }
// addWatch(panel.textW1, panel.valueW1);
// addWatch(panel.textW2, panel.valueW2);
// addWatch(panel.textW3, panel.valueW3);
// addWatch(panel.textW4, panel.valueW4);
// });
// }
//
// private static void addWatch(JTextField watch, final JLabel watchValue) {
// final Integer address = getValidAddress(watch.getText());
// if (address != null) {
// //System.out.println("Adding watch for "+Integer.toString(address, 16));
// RAMListener newListener = new RAMListener(RAMEvent.TYPE.WRITE, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {
// @Override
// protected void doConfig() {
// setScopeStart(address);
// }
//
// @Override
// protected void<SUF>
// watchValue.setText(Integer.toHexString(e.getNewValue() & 0x0FF));
// }
// };
// Emulator.computer.getMemory().addListener(newListener);
// watches.add(newListener);
// // Print out the current value right away
// byte b = Emulator.computer.getMemory().readRaw(address);
// watchValue.setText(Integer.toString(b & 0x0ff, 16));
// } else {
// watchValue.setText("00");
// }
// }
// public static void updateBreakpointList(final DebuggerPanel panel) {
// java.awt.EventQueue.invokeLater(() -> {
// Integer address;
// debugger.getBreakpoints().clear();
// if (panel == null) {
// return;
// }
// address = getValidAddress(panel.textBP1.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// address = getValidAddress(panel.textBP2.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// address = getValidAddress(panel.textBP3.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// address = getValidAddress(panel.textBP4.getText());
// if (address != null) {
// debugger.getBreakpoints().add(address);
// }
// debugger.updateBreakpoints();
// });
// }
//
@InvokableAction(
name = "BRUN file",
category = "file",
description = "Loads a binary file in memory and executes it. File should end with #06xxxx, where xxxx is the start address in hex",
alternatives = "Execute program;Load binary;Load program;Load rom;Play single-load game",
defaultKeyMapping = "ctrl+shift+b")
public static void runFile() {
Emulator.computer.pause();
FileChooser select = new FileChooser();
File binary = select.showOpenDialog(JaceApplication.getApplication().primaryStage);
if (binary == null) {
Emulator.computer.resume();
return;
}
runFileNamed(binary);
}
public static void runFileNamed(File binary) {
String fileName = binary.getName().toLowerCase();
try {
if (fileName.contains("#06")) {
String addressStr = fileName.substring(fileName.length() - 4);
int address = Integer.parseInt(addressStr, 16);
brun(binary, address);
} else if (fileName.contains("#fc")) {
gripe("BASIC not supported yet");
}
} catch (NumberFormatException | IOException ex) {
}
Emulator.computer.getCpu().resume();
}
public static void brun(File binary, int address) throws FileNotFoundException, IOException {
// If it was halted already, then it was initiated outside of an opcode execution
// If it was not yet halted, then it is the case that the CPU is processing another opcode
// So if that is the case, the program counter will need to be decremented here to compensate
// TODO: Find a better mousetrap for this one -- it's an ugly hack
Emulator.computer.pause();
FileInputStream in = new FileInputStream(binary);
byte[] data = new byte[in.available()];
in.read(data);
RAM ram = Emulator.computer.getMemory();
for (int i = 0; i < data.length; i++) {
ram.write(address + i, data[i], false, true);
}
CPU cpu = Emulator.computer.getCpu();
Emulator.computer.getCpu().setProgramCounter(address);
Emulator.computer.resume();
}
@InvokableAction(
name = "Toggle Debug",
category = "debug",
description = "Show/hide the debug panel",
alternatives = "Show Debug;Hide Debug",
defaultKeyMapping = "ctrl+shift+d")
public static void toggleDebugPanel() {
// AbstractEmulatorFrame frame = Emulator.getFrame();
// if (frame == null) {
// return;
// }
// frame.setShowDebug(!frame.isShowDebug());
// frame.reconfigure();
// Emulator.resizeVideo();
}
@InvokableAction(
name = "Toggle fullscreen",
category = "general",
description = "Activate/deactivate fullscreen mode",
alternatives = "fullscreen,maximize",
defaultKeyMapping = "ctrl+shift+f")
public static void toggleFullscreen() {
Platform.runLater(() -> {
Stage stage = JaceApplication.getApplication().primaryStage;
stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
stage.setFullScreen(!stage.isFullScreen());
});
}
@InvokableAction(
name = "Save Raw Screenshot",
category = "general",
description = "Save raw (RAM) format of visible screen",
alternatives = "screendump, raw screenshot",
defaultKeyMapping = "ctrl+shift+z")
public static void saveScreenshotRaw() throws FileNotFoundException, IOException {
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
String timestamp = df.format(new Date());
String type;
int start = Emulator.computer.getVideo().getCurrentWriter().actualWriter().getYOffset(0);
int len;
if (start < 0x02000) {
// Lo-res or double-lores
len = 0x0400;
type = "gr";
} else {
// Hi-res or double-hires
len = 0x02000;
type = "hgr";
}
boolean dres = SoftSwitches._80COL.getState() && (SoftSwitches.DHIRES.getState() || start < 0x02000);
if (dres) {
type = "d" + type;
}
File outFile = new File("screen_" + type + "_a" + Integer.toHexString(start) + "_" + timestamp);
try (FileOutputStream out = new FileOutputStream(outFile)) {
RAM128k ram = (RAM128k) Emulator.computer.memory;
Emulator.computer.pause();
if (dres) {
for (int i = 0; i < len; i++) {
out.write(ram.getAuxVideoMemory().readByte(start + i));
}
}
for (int i = 0; i < len; i++) {
out.write(ram.getMainMemory().readByte(start + i));
}
}
System.out.println("Wrote screenshot to " + outFile.getAbsolutePath());
}
@InvokableAction(
name = "Save Screenshot",
category = "general",
description = "Save image of visible screen",
alternatives = "Save image,save framebuffer,screenshot",
defaultKeyMapping = "ctrl+shift+s")
public static void saveScreenshot() throws IOException {
FileChooser select = new FileChooser();
Emulator.computer.pause();
Image i = Emulator.computer.getVideo().getFrameBuffer();
// BufferedImage bufImageARGB = SwingFXUtils.fromFXImage(i, null);
File targetFile = select.showSaveDialog(JaceApplication.getApplication().primaryStage);
if (targetFile == null) {
return;
}
String filename = targetFile.getName();
System.out.println("Writing screenshot to " + filename);
String extension = filename.substring(filename.lastIndexOf(".") + 1);
// BufferedImage bufImageRGB = new BufferedImage(bufImageARGB.getWidth(), bufImageARGB.getHeight(), BufferedImage.OPAQUE);
//
// Graphics2D graphics = bufImageRGB.createGraphics();
// graphics.drawImage(bufImageARGB, 0, 0, null);
//
// ImageIO.write(bufImageRGB, extension, targetFile);
// graphics.dispose();
}
public static final String CONFIGURATION_DIALOG_NAME = "Configuration";
@InvokableAction(
name = "Configuration",
category = "general",
description = "Edit emulator configuraion",
alternatives = "Reconfigure,Preferences,Settings",
defaultKeyMapping = {"f4", "ctrl+shift+c"})
public static void showConfig() {
FXMLLoader fxmlLoader = new FXMLLoader(EmulatorUILogic.class.getResource("/fxml/Configuration.fxml"));
fxmlLoader.setResources(null);
try {
Stage configWindow = new Stage();
AnchorPane node = (AnchorPane) fxmlLoader.load();
ConfigurationUIController controller = fxmlLoader.getController();
controller.initialize();
Scene s = new Scene(node);
configWindow.setScene(s);
configWindow.show();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
@InvokableAction(
name = "Open IDE",
category = "development",
description = "Open new IDE window for Basic/Assembly/Plasma coding",
alternatives = "dev,development,acme,assembler,editor",
defaultKeyMapping = {"ctrl+shift+i"})
public static void showIDE() {
FXMLLoader fxmlLoader = new FXMLLoader(EmulatorUILogic.class.getResource("/fxml/editor.fxml"));
fxmlLoader.setResources(null);
try {
Stage editorWindow = new Stage();
AnchorPane node = (AnchorPane) fxmlLoader.load();
IdeController controller = fxmlLoader.getController();
controller.initialize();
Scene s = new Scene(node);
editorWindow.setScene(s);
editorWindow.show();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
static int size = -1;
@InvokableAction(
name = "Resize window",
category = "general",
description = "Resize the screen to 1x/1.5x/2x/3x video size",
alternatives = "Adjust screen;Adjust window size;Adjust aspect ratio;Fix screen;Fix window size;Fix aspect ratio;Correct aspect ratio;",
defaultKeyMapping = {"ctrl+shift+a"})
public static void scaleIntegerRatio() {
Platform.runLater(() -> {
JaceApplication.getApplication().primaryStage.setFullScreen(false);
size++;
if (size > 3) {
size = 0;
}
int width = 0, height = 0;
switch (size) {
case 0: // 1x
width = 560;
height = 384;
break;
case 1: // 1.5x
width = 840;
height = 576;
break;
case 2: // 2x
width = 560*2;
height = 384*2;
break;
case 3: // 3x (retina) 2880x1800
width = 560*3;
height = 384*3;
break;
default: // 2x
width = 560*2;
height = 384*2;
}
Stage stage = JaceApplication.getApplication().primaryStage;
double vgap = stage.getScene().getY();
double hgap = stage.getScene().getX();
stage.setWidth(hgap*2 + width);
stage.setHeight(vgap + height);
});
}
public static boolean confirm(String message) {
// return JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(Emulator.getFrame(), message);
return false;
}
static final Map<Object, Set<Label>> INDICATORS = new HashMap<>();
static public void addIndicator(Object owner, Label icon) {
addIndicator(owner, icon, 250);
}
static public void addIndicator(Object owner, Label icon, long TTL) {
if (JaceApplication.getApplication() == null) {
return;
}
synchronized (INDICATORS) {
Set<Label> ind = INDICATORS.get(owner);
if (ind == null) {
ind = new HashSet<>();
INDICATORS.put(owner, ind);
}
ind.add(icon);
JaceApplication.getApplication().controller.addIndicator(icon);
}
}
static public void removeIndicator(Object owner, Label icon) {
if (JaceApplication.singleton == null) {
return;
}
synchronized (INDICATORS) {
Set<Label> ind = INDICATORS.get(owner);
if (ind != null) {
ind.remove(icon);
}
JaceApplication.singleton.controller.removeIndicator(icon);
}
}
static public void removeIndicators(Object owner) {
if (JaceApplication.singleton == null) {
return;
}
synchronized (INDICATORS) {
Set<Label> ind = INDICATORS.get(owner);
if (ind == null) {
return;
}
ind.stream().forEach((icon) -> {
JaceApplication.singleton.controller.removeIndicator(icon);
});
INDICATORS.remove(owner);
}
}
static public void addMouseListener(EventHandler<MouseEvent> handler) {
if (JaceApplication.singleton != null) {
JaceApplication.singleton.controller.addMouseListener(handler);
}
}
static public void removeMouseListener(EventHandler<MouseEvent> handler) {
if (JaceApplication.singleton != null) {
JaceApplication.singleton.controller.removeMouseListener(handler);
}
}
public static void simulateCtrlAppleReset() {
Computer computer = JaceApplication.singleton.controller.computer;
computer.keyboard.openApple(true);
computer.warmStart();
Platform.runLater(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(EmulatorUILogic.class.getName()).log(Level.SEVERE, null, ex);
}
computer.keyboard.openApple(false);
});
}
public static void notify(String message) {
if (JaceApplication.singleton != null) {
JaceApplication.singleton.controller.displayNotification(message);
}
}
@Override
public String getName() {
return "Jace User Interface";
}
@Override
public String getShortName() {
return "UI";
}
@Override
public void reconfigure() {
}
}
|
204405_7 | /*
* Copyright 2012 Alex Usachev, [email protected]
*
* This file is part of Parallax project.
*
* Parallax is free software: you can redistribute it and/or modify it
* under the terms of the Creative Commons Attribution 3.0 Unported License.
*
* Parallax 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 Creative Commons Attribution
* 3.0 Unported License. for more details.
*
* You should have received a copy of the the Creative Commons Attribution
* 3.0 Unported License along with Parallax.
* If not, see http://creativecommons.org/licenses/by/3.0/.
*/
package thothbot.parallax.core.shared.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import thothbot.parallax.core.shared.Log;
import thothbot.parallax.core.shared.curves.Curve;
import thothbot.parallax.core.shared.curves.CurvePath;
import thothbot.parallax.core.shared.curves.FrenetFrames;
import thothbot.parallax.core.shared.curves.Shape;
import thothbot.parallax.core.shared.math.Box3;
import thothbot.parallax.core.shared.math.Vector;
import thothbot.parallax.core.shared.math.Vector2;
import thothbot.parallax.core.shared.math.Vector3;
import thothbot.parallax.core.shared.utils.ShapeUtils;
/**
* Creates extruded geometry from a path shape.
* <p>
* Based on the three.js code.
*/
public class ExtrudeGeometry extends Geometry
{
public static class ExtrudeGeometryParameters
{
// size of the text
public double size;
// thickness to extrude text
public double height;
// number of points on the curves
public int curveSegments = 12;
// number of points for z-side extrusions / used for subdividing segements of extrude spline too
public int steps = 1;
// Amount
public int amount = 100;
// turn on bevel
public boolean bevelEnabled = true;
// how deep into text bevel goes
public double bevelThickness = 6;
// how far from text outline is bevel
public double bevelSize = bevelThickness - 2;
// number of bevel layers
public int bevelSegments = 3;
// 2d/3d spline path to extrude shape orthogonality to
public Curve extrudePath;
// 2d path for bend the shape around x/y plane
public CurvePath bendPath;
// material index for front and back faces
public int material;
// material index for extrusion and beveled faces
public int extrudeMaterial;
}
private static final double RAD_TO_DEGREES = 180.0 / Math.PI;
private static Vector2 __v1 = new Vector2();
private static Vector2 __v2 = new Vector2();
private static Vector2 __v3 = new Vector2();
private static Vector2 __v4 = new Vector2();
private static Vector2 __v5 = new Vector2();
private static Vector2 __v6 = new Vector2();
private Box3 shapebb;
private List<List<Vector2>> holes;
private List<List<Integer>> localFaces;
private ExtrudeGeometryParameters options;
private int shapesOffset;
private int verticesCount;
public ExtrudeGeometry(ExtrudeGeometryParameters options)
{
this(new ArrayList<Shape>(), options);
}
public ExtrudeGeometry(Shape shape, ExtrudeGeometryParameters options)
{
this(Arrays.asList(shape), options);
}
public ExtrudeGeometry(List<Shape> shapes, ExtrudeGeometryParameters options)
{
super();
this.shapebb = shapes.get( shapes.size() - 1 ).getBoundingBox();
this.options = options;
this.addShape( shapes, options );
this.computeCentroids();
this.computeFaceNormals();
}
public void addShape(List<Shape> shapes, ExtrudeGeometryParameters options)
{
int sl = shapes.size();
for ( int s = 0; s < sl; s ++ )
this.addShape( shapes.get( s ), options );
}
public void addShape( Shape shape, ExtrudeGeometryParameters options )
{
Log.debug("ExtrudeGeometry: Called addShape() shape=" + shape);
List<Vector> extrudePts = null;
boolean extrudeByPath = false;
Vector3 binormal = new Vector3();
Vector3 normal = new Vector3();
Vector3 position2 = new Vector3();
FrenetFrames splineTube = null;
if ( options.extrudePath != null)
{
extrudePts = options.extrudePath.getSpacedPoints( options.steps );
extrudeByPath = true;
// bevels not supported for path extrusion
options.bevelEnabled = false;
// SETUP TNB variables
// Reuse TNB from TubeGeomtry for now.
// TODO - have a .isClosed in spline?
splineTube = new FrenetFrames(options.extrudePath, options.steps, false);
}
// Safeguards if bevels are not enabled
if ( !options.bevelEnabled )
{
options.bevelSegments = 0;
options.bevelThickness = 0;
options.bevelSize = 0;
}
this.shapesOffset = getVertices().size();
if ( options.bendPath != null )
shape.addWrapPath( options.bendPath );
List<Vector2> vertices = shape.getTransformedPoints();
this.holes = shape.getPointsHoles();
boolean reverse = ! ShapeUtils.isClockWise( vertices ) ;
if ( reverse )
{
Collections.reverse(vertices);
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
if ( ShapeUtils.isClockWise( ahole ) )
Collections.reverse(ahole);
}
// If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
reverse = false;
}
localFaces = ShapeUtils.triangulateShape ( vertices, holes );
// Would it be better to move points after triangulation?
// shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
// vertices = shapePoints.shape;
// holes = shapePoints.holes;
////
/// Handle Vertices
////
// vertices has all points but contour has only points of circumference
List<Vector2> contour = new ArrayList<Vector2>(vertices);
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
vertices.addAll( this.holes.get( h ) );
verticesCount = vertices.size();
//
// Find directions for point movement
//
List<Vector2> contourMovements = new ArrayList<Vector2>();
for ( int i = 0, il = contour.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
contourMovements.add(
getBevelVec( contour.get( i ), contour.get( j ), contour.get( k ) ));
}
List<List<Vector2>> holesMovements = new ArrayList<List<Vector2>>();
List<Vector2> verticesMovements = (List<Vector2>) ((ArrayList) contourMovements).clone();
for ( int h = 0, hl = holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = new ArrayList<Vector2>();
for ( int i = 0, il = ahole.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements.add(getBevelVec( ahole.get( i ), ahole.get( j ), ahole.get( k ) ));
}
holesMovements.add( oneHoleMovements );
verticesMovements.addAll( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( int b = 0; b < options.bevelSegments; b ++ )
{
double t = b / (double)options.bevelSegments;
double z = options.bevelThickness * ( 1.0 - t );
double bs = options.bevelSize * ( Math.sin ( t * Math.PI / 2.0 ) ) ; // curved
//bs = bevelSize * t ; // linear
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
//vert = scalePt( contour[ i ], contourCentroid, bs, false );
v( vert.getX(), vert.getY(), - z );
}
// expand holes
for ( int h = 0, hl = holes.size(); h < hl; h++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
//vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
v( vert.getX(), vert.getY(), -z );
}
}
}
// bs = bevelSize;
// Back facing vertices
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), 0 );
}
else
{
// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
normal.copy(splineTube.getNormals().get(0)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(0)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(0)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ());
}
}
// Add stepped vertices...
// Including front facing vertices
for ( int s = 1; s <= options.steps; s ++ )
{
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), (double)options.amount / options.steps * s );
}
else
{
// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
normal.copy(splineTube.getNormals().get(s)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(s)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(s)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ() );
}
}
}
// Add bevel segments planes
for ( int b = options.bevelSegments - 1; b >= 0; b -- )
{
double t = (double)b / options.bevelSegments;
double z = options.bevelThickness * ( 1 - t );
double bs = options.bevelSize * Math.sin ( t * Math.PI/2.0 ) ;
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
v( vert.getX(), vert.getY(), options.amount + z );
}
// expand holes
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
if ( !extrudeByPath )
v( vert.getX(), vert.getY(), options.amount + z );
else
v( vert.getX(),
vert.getY() + ((Vector3)extrudePts.get( options.steps - 1 )).getY(),
((Vector3)extrudePts.get( options.steps - 1 )).getX() + z );
}
}
}
//
// Handle Faces
//
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces(contour);
}
private Vector2 getBevelVec( Vector pt_i, Vector pt_j, Vector pt_k )
{
// Algorithm 2
return getBevelVec2( (Vector2)pt_i, (Vector2)pt_j, (Vector2)pt_k );
}
private Vector2 getBevelVec1( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
double anglea = Math.atan2( pt_j.getY() - pt_i.getY(), pt_j.getX() - pt_i.getX() );
double angleb = Math.atan2( pt_k.getY() - pt_i.getY(), pt_k.getX() - pt_i.getX() );
if ( anglea > angleb )
angleb += Math.PI * 2.0;
double anglec = ( anglea + angleb ) / 2.0;
double x = - Math.cos( anglec );
double y = - Math.sin( anglec );
return new Vector2( x, y ); //.normalize();
}
private Vector2 scalePt2 ( Vector pt, Vector vec, double size )
{
return (Vector2) vec.clone().multiply( size ).add( pt );
}
/*
* good reading for line-line intersection
* http://sputsoft.com/blog/2010/03/line-line-intersection.html
*/
private Vector2 getBevelVec2( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
Vector2 a = ExtrudeGeometry.__v1;
Vector2 b = ExtrudeGeometry.__v2;
Vector2 v_hat = ExtrudeGeometry.__v3;
Vector2 w_hat = ExtrudeGeometry.__v4;
Vector2 p = ExtrudeGeometry.__v5;
Vector2 q = ExtrudeGeometry.__v6;
// define a as vector j->i
// define b as vectot k->i
a.set( pt_i.getX() - pt_j.getX(), pt_i.getY() - pt_j.getY() );
b.set( pt_i.getX() - pt_k.getX(), pt_i.getY() - pt_k.getY() );
// get unit vectors
Vector2 v = a.normalize();
Vector2 w = b.normalize();
// normals from pt i
v_hat.set( -v.getY(), v.getX() );
w_hat.set( w.getY(), -w.getX() );
// pts from i
p.copy( pt_i ).add( v_hat );
q.copy( pt_i ).add( w_hat );
if ( p.equals( q ) )
return w_hat.clone();
// Points from j, k. helps prevents points cross overover most of the time
p.copy( pt_j ).add( v_hat );
q.copy( pt_k ).add( w_hat );
double v_dot_w_hat = v.dot( w_hat );
double q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
// We should not reach these conditions
if ( v_dot_w_hat == 0 )
{
Log.info( "getBevelVec2() Either infinite or no solutions!" );
if ( q_sub_p_dot_w_hat == 0 )
Log.info( "getBevelVec2() Its finite solutions." );
else
Log.error( "getBevelVec2() Too bad, no solutions." );
}
double s = q_sub_p_dot_w_hat / v_dot_w_hat;
// in case of emergecy, revert to algorithm 1.
if ( s < 0 )
return getBevelVec1( pt_i, pt_j, pt_k );
Vector2 intersection = v.multiply( s ).add( p );
// Don't normalize!, otherwise sharp corners become ugly
return intersection.sub( pt_i ).clone();
}
private void buildLidFaces()
{
int flen = this.localFaces.size();
Log.debug("ExtrudeGeometry: buildLidFaces() faces=" + flen);
if ( this.options.bevelEnabled )
{
int layer = 0 ; // steps + 1
int offset = this.shapesOffset * layer;
// Bottom faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(2) + offset, face.get(1) + offset, face.get(0) + offset, true );
}
layer = this.options.steps + this.options.bevelSegments * 2;
offset = verticesCount * layer;
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(0) + offset, face.get(1) + offset, face.get(2) + offset, false );
}
}
else
{
// Bottom faces
for ( int i = 0; i < flen; i++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(2), face.get(1), face.get(0), true );
}
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(0) + verticesCount * this.options.steps,
face.get(1) + verticesCount * this.options.steps,
face.get(2) + verticesCount * this.options.steps, false );
}
}
}
// Create faces for the z-sides of the shape
private void buildSideFaces(List<Vector2> contour)
{
int layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.size();
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.size();
}
}
private void sidewalls( List<Vector2> contour, int layeroffset )
{
int i = contour.size();
while ( --i >= 0 )
{
int j = i;
int k = i - 1;
if ( k < 0 )
k = contour.size() - 1;
int sl = this.options.steps + this.options.bevelSegments * 2;
for ( int s = 0; s < sl; s ++ )
{
int slen1 = this.verticesCount * s;
int slen2 = this.verticesCount * ( s + 1 );
int a = layeroffset + j + slen1;
int b = layeroffset + k + slen1;
int c = layeroffset + k + slen2;
int d = layeroffset + j + slen2;
f4( a, b, c, d);
}
}
}
private void v( double x, double y, double z )
{
getVertices().add( new Vector3( x, y, z ) );
}
private void f3( int a, int b, int c, boolean isBottom )
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
// normal, color, material
getFaces().add( new Face3( a, b, c, this.options.material ) );
List<Vector2> uvs = isBottom
? WorldUVGenerator.generateBottomUV( this, a, b, c)
: WorldUVGenerator.generateTopUV( this, a, b, c);
getFaceVertexUvs().get( 0 ).add(uvs);
}
private void f4( int a, int b, int c, int d)
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
d += this.shapesOffset;
getFaces().add( new Face4( a, b, c, d, null, null, this.options.extrudeMaterial ) );
List<Vector2> uvs = WorldUVGenerator.generateSideWallUV(this, a, b, c, d);
getFaceVertexUvs().get( 0 ).add(uvs);
}
public static class WorldUVGenerator
{
public static List<Vector2> generateTopUV( Geometry geometry, int indexA, int indexB, int indexC )
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
return Arrays.asList(
new Vector2( ax, 1 - ay ),
new Vector2( bx, 1 - by ),
new Vector2( cx, 1 - cy )
);
}
public static List<Vector2> generateBottomUV( ExtrudeGeometry geometry, int indexA, int indexB, int indexC)
{
return generateTopUV( geometry, indexA, indexB, indexC );
}
public static List<Vector2> generateSideWallUV( Geometry geometry, int indexA, int indexB, int indexC, int indexD)
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double az = geometry.getVertices().get( indexA ).getZ();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double bz = geometry.getVertices().get( indexB ).getZ();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
double cz = geometry.getVertices().get( indexC ).getZ();
double dx = geometry.getVertices().get( indexD ).getX();
double dy = geometry.getVertices().get( indexD ).getY();
double dz = geometry.getVertices().get( indexD ).getZ();
if ( Math.abs( ay - by ) < 0.01 )
{
return Arrays.asList(
new Vector2( ax, az ),
new Vector2( bx, bz ),
new Vector2( cx, cz ),
new Vector2( dx, dz )
);
}
else
{
return Arrays.asList(
new Vector2( ay, az ),
new Vector2( by, bz ),
new Vector2( cy, cz ),
new Vector2( dy, dz )
);
}
}
}
}
| MichalBenatsky/parallax | src/main/java/thothbot/parallax/core/shared/core/ExtrudeGeometry.java | 7,021 | // how deep into text bevel goes | line_comment | nl | /*
* Copyright 2012 Alex Usachev, [email protected]
*
* This file is part of Parallax project.
*
* Parallax is free software: you can redistribute it and/or modify it
* under the terms of the Creative Commons Attribution 3.0 Unported License.
*
* Parallax 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 Creative Commons Attribution
* 3.0 Unported License. for more details.
*
* You should have received a copy of the the Creative Commons Attribution
* 3.0 Unported License along with Parallax.
* If not, see http://creativecommons.org/licenses/by/3.0/.
*/
package thothbot.parallax.core.shared.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import thothbot.parallax.core.shared.Log;
import thothbot.parallax.core.shared.curves.Curve;
import thothbot.parallax.core.shared.curves.CurvePath;
import thothbot.parallax.core.shared.curves.FrenetFrames;
import thothbot.parallax.core.shared.curves.Shape;
import thothbot.parallax.core.shared.math.Box3;
import thothbot.parallax.core.shared.math.Vector;
import thothbot.parallax.core.shared.math.Vector2;
import thothbot.parallax.core.shared.math.Vector3;
import thothbot.parallax.core.shared.utils.ShapeUtils;
/**
* Creates extruded geometry from a path shape.
* <p>
* Based on the three.js code.
*/
public class ExtrudeGeometry extends Geometry
{
public static class ExtrudeGeometryParameters
{
// size of the text
public double size;
// thickness to extrude text
public double height;
// number of points on the curves
public int curveSegments = 12;
// number of points for z-side extrusions / used for subdividing segements of extrude spline too
public int steps = 1;
// Amount
public int amount = 100;
// turn on bevel
public boolean bevelEnabled = true;
// how deep<SUF>
public double bevelThickness = 6;
// how far from text outline is bevel
public double bevelSize = bevelThickness - 2;
// number of bevel layers
public int bevelSegments = 3;
// 2d/3d spline path to extrude shape orthogonality to
public Curve extrudePath;
// 2d path for bend the shape around x/y plane
public CurvePath bendPath;
// material index for front and back faces
public int material;
// material index for extrusion and beveled faces
public int extrudeMaterial;
}
private static final double RAD_TO_DEGREES = 180.0 / Math.PI;
private static Vector2 __v1 = new Vector2();
private static Vector2 __v2 = new Vector2();
private static Vector2 __v3 = new Vector2();
private static Vector2 __v4 = new Vector2();
private static Vector2 __v5 = new Vector2();
private static Vector2 __v6 = new Vector2();
private Box3 shapebb;
private List<List<Vector2>> holes;
private List<List<Integer>> localFaces;
private ExtrudeGeometryParameters options;
private int shapesOffset;
private int verticesCount;
public ExtrudeGeometry(ExtrudeGeometryParameters options)
{
this(new ArrayList<Shape>(), options);
}
public ExtrudeGeometry(Shape shape, ExtrudeGeometryParameters options)
{
this(Arrays.asList(shape), options);
}
public ExtrudeGeometry(List<Shape> shapes, ExtrudeGeometryParameters options)
{
super();
this.shapebb = shapes.get( shapes.size() - 1 ).getBoundingBox();
this.options = options;
this.addShape( shapes, options );
this.computeCentroids();
this.computeFaceNormals();
}
public void addShape(List<Shape> shapes, ExtrudeGeometryParameters options)
{
int sl = shapes.size();
for ( int s = 0; s < sl; s ++ )
this.addShape( shapes.get( s ), options );
}
public void addShape( Shape shape, ExtrudeGeometryParameters options )
{
Log.debug("ExtrudeGeometry: Called addShape() shape=" + shape);
List<Vector> extrudePts = null;
boolean extrudeByPath = false;
Vector3 binormal = new Vector3();
Vector3 normal = new Vector3();
Vector3 position2 = new Vector3();
FrenetFrames splineTube = null;
if ( options.extrudePath != null)
{
extrudePts = options.extrudePath.getSpacedPoints( options.steps );
extrudeByPath = true;
// bevels not supported for path extrusion
options.bevelEnabled = false;
// SETUP TNB variables
// Reuse TNB from TubeGeomtry for now.
// TODO - have a .isClosed in spline?
splineTube = new FrenetFrames(options.extrudePath, options.steps, false);
}
// Safeguards if bevels are not enabled
if ( !options.bevelEnabled )
{
options.bevelSegments = 0;
options.bevelThickness = 0;
options.bevelSize = 0;
}
this.shapesOffset = getVertices().size();
if ( options.bendPath != null )
shape.addWrapPath( options.bendPath );
List<Vector2> vertices = shape.getTransformedPoints();
this.holes = shape.getPointsHoles();
boolean reverse = ! ShapeUtils.isClockWise( vertices ) ;
if ( reverse )
{
Collections.reverse(vertices);
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
if ( ShapeUtils.isClockWise( ahole ) )
Collections.reverse(ahole);
}
// If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
reverse = false;
}
localFaces = ShapeUtils.triangulateShape ( vertices, holes );
// Would it be better to move points after triangulation?
// shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
// vertices = shapePoints.shape;
// holes = shapePoints.holes;
////
/// Handle Vertices
////
// vertices has all points but contour has only points of circumference
List<Vector2> contour = new ArrayList<Vector2>(vertices);
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
vertices.addAll( this.holes.get( h ) );
verticesCount = vertices.size();
//
// Find directions for point movement
//
List<Vector2> contourMovements = new ArrayList<Vector2>();
for ( int i = 0, il = contour.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
contourMovements.add(
getBevelVec( contour.get( i ), contour.get( j ), contour.get( k ) ));
}
List<List<Vector2>> holesMovements = new ArrayList<List<Vector2>>();
List<Vector2> verticesMovements = (List<Vector2>) ((ArrayList) contourMovements).clone();
for ( int h = 0, hl = holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = new ArrayList<Vector2>();
for ( int i = 0, il = ahole.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements.add(getBevelVec( ahole.get( i ), ahole.get( j ), ahole.get( k ) ));
}
holesMovements.add( oneHoleMovements );
verticesMovements.addAll( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( int b = 0; b < options.bevelSegments; b ++ )
{
double t = b / (double)options.bevelSegments;
double z = options.bevelThickness * ( 1.0 - t );
double bs = options.bevelSize * ( Math.sin ( t * Math.PI / 2.0 ) ) ; // curved
//bs = bevelSize * t ; // linear
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
//vert = scalePt( contour[ i ], contourCentroid, bs, false );
v( vert.getX(), vert.getY(), - z );
}
// expand holes
for ( int h = 0, hl = holes.size(); h < hl; h++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
//vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
v( vert.getX(), vert.getY(), -z );
}
}
}
// bs = bevelSize;
// Back facing vertices
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), 0 );
}
else
{
// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
normal.copy(splineTube.getNormals().get(0)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(0)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(0)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ());
}
}
// Add stepped vertices...
// Including front facing vertices
for ( int s = 1; s <= options.steps; s ++ )
{
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), (double)options.amount / options.steps * s );
}
else
{
// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
normal.copy(splineTube.getNormals().get(s)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(s)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(s)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ() );
}
}
}
// Add bevel segments planes
for ( int b = options.bevelSegments - 1; b >= 0; b -- )
{
double t = (double)b / options.bevelSegments;
double z = options.bevelThickness * ( 1 - t );
double bs = options.bevelSize * Math.sin ( t * Math.PI/2.0 ) ;
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
v( vert.getX(), vert.getY(), options.amount + z );
}
// expand holes
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
if ( !extrudeByPath )
v( vert.getX(), vert.getY(), options.amount + z );
else
v( vert.getX(),
vert.getY() + ((Vector3)extrudePts.get( options.steps - 1 )).getY(),
((Vector3)extrudePts.get( options.steps - 1 )).getX() + z );
}
}
}
//
// Handle Faces
//
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces(contour);
}
private Vector2 getBevelVec( Vector pt_i, Vector pt_j, Vector pt_k )
{
// Algorithm 2
return getBevelVec2( (Vector2)pt_i, (Vector2)pt_j, (Vector2)pt_k );
}
private Vector2 getBevelVec1( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
double anglea = Math.atan2( pt_j.getY() - pt_i.getY(), pt_j.getX() - pt_i.getX() );
double angleb = Math.atan2( pt_k.getY() - pt_i.getY(), pt_k.getX() - pt_i.getX() );
if ( anglea > angleb )
angleb += Math.PI * 2.0;
double anglec = ( anglea + angleb ) / 2.0;
double x = - Math.cos( anglec );
double y = - Math.sin( anglec );
return new Vector2( x, y ); //.normalize();
}
private Vector2 scalePt2 ( Vector pt, Vector vec, double size )
{
return (Vector2) vec.clone().multiply( size ).add( pt );
}
/*
* good reading for line-line intersection
* http://sputsoft.com/blog/2010/03/line-line-intersection.html
*/
private Vector2 getBevelVec2( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
Vector2 a = ExtrudeGeometry.__v1;
Vector2 b = ExtrudeGeometry.__v2;
Vector2 v_hat = ExtrudeGeometry.__v3;
Vector2 w_hat = ExtrudeGeometry.__v4;
Vector2 p = ExtrudeGeometry.__v5;
Vector2 q = ExtrudeGeometry.__v6;
// define a as vector j->i
// define b as vectot k->i
a.set( pt_i.getX() - pt_j.getX(), pt_i.getY() - pt_j.getY() );
b.set( pt_i.getX() - pt_k.getX(), pt_i.getY() - pt_k.getY() );
// get unit vectors
Vector2 v = a.normalize();
Vector2 w = b.normalize();
// normals from pt i
v_hat.set( -v.getY(), v.getX() );
w_hat.set( w.getY(), -w.getX() );
// pts from i
p.copy( pt_i ).add( v_hat );
q.copy( pt_i ).add( w_hat );
if ( p.equals( q ) )
return w_hat.clone();
// Points from j, k. helps prevents points cross overover most of the time
p.copy( pt_j ).add( v_hat );
q.copy( pt_k ).add( w_hat );
double v_dot_w_hat = v.dot( w_hat );
double q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
// We should not reach these conditions
if ( v_dot_w_hat == 0 )
{
Log.info( "getBevelVec2() Either infinite or no solutions!" );
if ( q_sub_p_dot_w_hat == 0 )
Log.info( "getBevelVec2() Its finite solutions." );
else
Log.error( "getBevelVec2() Too bad, no solutions." );
}
double s = q_sub_p_dot_w_hat / v_dot_w_hat;
// in case of emergecy, revert to algorithm 1.
if ( s < 0 )
return getBevelVec1( pt_i, pt_j, pt_k );
Vector2 intersection = v.multiply( s ).add( p );
// Don't normalize!, otherwise sharp corners become ugly
return intersection.sub( pt_i ).clone();
}
private void buildLidFaces()
{
int flen = this.localFaces.size();
Log.debug("ExtrudeGeometry: buildLidFaces() faces=" + flen);
if ( this.options.bevelEnabled )
{
int layer = 0 ; // steps + 1
int offset = this.shapesOffset * layer;
// Bottom faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(2) + offset, face.get(1) + offset, face.get(0) + offset, true );
}
layer = this.options.steps + this.options.bevelSegments * 2;
offset = verticesCount * layer;
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(0) + offset, face.get(1) + offset, face.get(2) + offset, false );
}
}
else
{
// Bottom faces
for ( int i = 0; i < flen; i++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(2), face.get(1), face.get(0), true );
}
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(0) + verticesCount * this.options.steps,
face.get(1) + verticesCount * this.options.steps,
face.get(2) + verticesCount * this.options.steps, false );
}
}
}
// Create faces for the z-sides of the shape
private void buildSideFaces(List<Vector2> contour)
{
int layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.size();
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.size();
}
}
private void sidewalls( List<Vector2> contour, int layeroffset )
{
int i = contour.size();
while ( --i >= 0 )
{
int j = i;
int k = i - 1;
if ( k < 0 )
k = contour.size() - 1;
int sl = this.options.steps + this.options.bevelSegments * 2;
for ( int s = 0; s < sl; s ++ )
{
int slen1 = this.verticesCount * s;
int slen2 = this.verticesCount * ( s + 1 );
int a = layeroffset + j + slen1;
int b = layeroffset + k + slen1;
int c = layeroffset + k + slen2;
int d = layeroffset + j + slen2;
f4( a, b, c, d);
}
}
}
private void v( double x, double y, double z )
{
getVertices().add( new Vector3( x, y, z ) );
}
private void f3( int a, int b, int c, boolean isBottom )
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
// normal, color, material
getFaces().add( new Face3( a, b, c, this.options.material ) );
List<Vector2> uvs = isBottom
? WorldUVGenerator.generateBottomUV( this, a, b, c)
: WorldUVGenerator.generateTopUV( this, a, b, c);
getFaceVertexUvs().get( 0 ).add(uvs);
}
private void f4( int a, int b, int c, int d)
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
d += this.shapesOffset;
getFaces().add( new Face4( a, b, c, d, null, null, this.options.extrudeMaterial ) );
List<Vector2> uvs = WorldUVGenerator.generateSideWallUV(this, a, b, c, d);
getFaceVertexUvs().get( 0 ).add(uvs);
}
public static class WorldUVGenerator
{
public static List<Vector2> generateTopUV( Geometry geometry, int indexA, int indexB, int indexC )
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
return Arrays.asList(
new Vector2( ax, 1 - ay ),
new Vector2( bx, 1 - by ),
new Vector2( cx, 1 - cy )
);
}
public static List<Vector2> generateBottomUV( ExtrudeGeometry geometry, int indexA, int indexB, int indexC)
{
return generateTopUV( geometry, indexA, indexB, indexC );
}
public static List<Vector2> generateSideWallUV( Geometry geometry, int indexA, int indexB, int indexC, int indexD)
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double az = geometry.getVertices().get( indexA ).getZ();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double bz = geometry.getVertices().get( indexB ).getZ();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
double cz = geometry.getVertices().get( indexC ).getZ();
double dx = geometry.getVertices().get( indexD ).getX();
double dy = geometry.getVertices().get( indexD ).getY();
double dz = geometry.getVertices().get( indexD ).getZ();
if ( Math.abs( ay - by ) < 0.01 )
{
return Arrays.asList(
new Vector2( ax, az ),
new Vector2( bx, bz ),
new Vector2( cx, cz ),
new Vector2( dx, dz )
);
}
else
{
return Arrays.asList(
new Vector2( ay, az ),
new Vector2( by, bz ),
new Vector2( cy, cz ),
new Vector2( dy, dz )
);
}
}
}
}
|
21278_4 | package vpp.DecimalToBinary;
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Input a Decimal Number: ");
int decimal = input.nextInt();
int decimal2 = decimal;
System.out.println(Integer.toBinaryString(decimal));
System.out.println(decimalToBinaryString(decimal));
//teacher's solution
StringBuilder binaryString = new StringBuilder();
while (decimal > 0) {
binaryString.insert(0, decimal % 2);
decimal /= 2;
}
System.out.println("Binary number is: " + binaryString);
//rewriting this solution as a recursive function for self-study
System.out.println(recursiveSolution(decimal2));
}
private static String decimalToBinaryString(int decimal){
String result = "";
int binaryCount = 0;
for(int i = 2; i <= decimal; i*=2){
if(i*2 > decimal){
binaryCount = i;
}
}
for(int i = binaryCount; i > 0; i/=2){
if(decimal >= i){
result = result + 1;
decimal = decimal - i;
}
else result = result + 0;
}
return result;
}
private static String recursiveSolution(int decimal){
//if(decimal > 0)return recursiveSolution(decimal/2).concat("" + decimal%2);
//return "";
return decimal>0 ? recursiveSolution(decimal/2).concat("" + decimal%2) : "";
}
}
//eigen eerste idee was met %, maar ipv "decimal" te halveren,
//zaten mijn gedachten vast op het verhogen v/d noemer v/d breuk.
//Hierdoor kwam ik uit met extra regels code om hetzelfde te realiseren
//Tip voor zelf: geef jezelf wat extra tijd
/*
Write a Java program to convert a decimal number to binary number.
Input Data:
Input a Decimal Number : 5
Expected Output
Binary number is: 101
**Challenge: it is really easy to do this with the Integer class in Java, but
it is kind of a rite of passage to write
your own routine. So if you dare: try both routes
*/
| Michelvdm83/JavaExercises | src/main/java/vpp/DecimalToBinary/DecimalToBinary.java | 623 | //Hierdoor kwam ik uit met extra regels code om hetzelfde te realiseren | line_comment | nl | package vpp.DecimalToBinary;
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Input a Decimal Number: ");
int decimal = input.nextInt();
int decimal2 = decimal;
System.out.println(Integer.toBinaryString(decimal));
System.out.println(decimalToBinaryString(decimal));
//teacher's solution
StringBuilder binaryString = new StringBuilder();
while (decimal > 0) {
binaryString.insert(0, decimal % 2);
decimal /= 2;
}
System.out.println("Binary number is: " + binaryString);
//rewriting this solution as a recursive function for self-study
System.out.println(recursiveSolution(decimal2));
}
private static String decimalToBinaryString(int decimal){
String result = "";
int binaryCount = 0;
for(int i = 2; i <= decimal; i*=2){
if(i*2 > decimal){
binaryCount = i;
}
}
for(int i = binaryCount; i > 0; i/=2){
if(decimal >= i){
result = result + 1;
decimal = decimal - i;
}
else result = result + 0;
}
return result;
}
private static String recursiveSolution(int decimal){
//if(decimal > 0)return recursiveSolution(decimal/2).concat("" + decimal%2);
//return "";
return decimal>0 ? recursiveSolution(decimal/2).concat("" + decimal%2) : "";
}
}
//eigen eerste idee was met %, maar ipv "decimal" te halveren,
//zaten mijn gedachten vast op het verhogen v/d noemer v/d breuk.
//Hierdoor kwam<SUF>
//Tip voor zelf: geef jezelf wat extra tijd
/*
Write a Java program to convert a decimal number to binary number.
Input Data:
Input a Decimal Number : 5
Expected Output
Binary number is: 101
**Challenge: it is really easy to do this with the Integer class in Java, but
it is kind of a rite of passage to write
your own routine. So if you dare: try both routes
*/
|
20849_1 | import java.util.Arrays;
import static generic.CommandLine.*;
public class Week4{
public static void main(String[] args){
int lucas = askForInt("geef een natuurlijk getal: ");
printLucasRow(lucas);
System.out.println("Java".substring(0,1));
/* int a = 5;
int b = 2;
System.out.println(exponent(a,b));
System.out.println(isOdd(b));
System.out.println(isOdd(a));
int[] test = new int[]{1, 2, 3, 4, 5};
System.out.println(Arrays.toString(test));
int[] test2 = invert(test);
System.out.println(Arrays.toString(test));*/
}
private static void printLucasRow(int nrOfNumbers){
int[] lucasRow = getLucasRow(nrOfNumbers);
if(lucasRow == null)return;
System.out.printf("De eerst %d Lucas-getallen:%n", lucasRow.length);
for(int i: lucasRow){
System.out.print(i + " ");
}
System.out.println();
}
private static int[] getLucasRow(int nrOfNumbers){
if(nrOfNumbers < 0){
System.out.println("Getal negatief, fout");
return null;
}
if(nrOfNumbers == 0) return new int[]{};
if(nrOfNumbers < 3) return new int[]{nrOfNumbers == 1? 2 : 2, 1};
int[] totalRow = new int[nrOfNumbers];
totalRow[0] = 2;
totalRow[1] = 1;
for(int i = 2; i < totalRow.length; i++){
totalRow[i] = totalRow[i-1] + totalRow[i-2];
if(((long)totalRow[i] + totalRow[i-1]) > Integer.MAX_VALUE){
System.out.println("Getal te groot, past niet");
return null;
}
}
return totalRow;
}
private static int exponent(int base, int exp){
return (int)Math.pow(base, exp);
}
private static boolean isOdd(int number){
return number%2 != 0;
}
public static int[] invert(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i] *= -1;
}
return array;
}
}
/*
2 1 3 4 7 11 18 …
Het eerste Lucas-getal is 2, het tweede is 1. Daarna krijg je het volgende getal telkens door de twee voorgaande getallen bij elkaar op te tellen.
In je programma moet je testen of het door de gebruiker ingetypte getal wel positief is.
Verder kunnen de getallen van de Lucas-reeks zo groot worden dat ze niet meer passen in een int.
Bouw in je programma een test in, zodat bij een te grote waarde van n niets geprint wordt.
*/ | Michelvdm83/OpdrachtenIT | Week4.java | 853 | /*
2 1 3 4 7 11 18 …
Het eerste Lucas-getal is 2, het tweede is 1. Daarna krijg je het volgende getal telkens door de twee voorgaande getallen bij elkaar op te tellen.
In je programma moet je testen of het door de gebruiker ingetypte getal wel positief is.
Verder kunnen de getallen van de Lucas-reeks zo groot worden dat ze niet meer passen in een int.
Bouw in je programma een test in, zodat bij een te grote waarde van n niets geprint wordt.
*/ | block_comment | nl | import java.util.Arrays;
import static generic.CommandLine.*;
public class Week4{
public static void main(String[] args){
int lucas = askForInt("geef een natuurlijk getal: ");
printLucasRow(lucas);
System.out.println("Java".substring(0,1));
/* int a = 5;
int b = 2;
System.out.println(exponent(a,b));
System.out.println(isOdd(b));
System.out.println(isOdd(a));
int[] test = new int[]{1, 2, 3, 4, 5};
System.out.println(Arrays.toString(test));
int[] test2 = invert(test);
System.out.println(Arrays.toString(test));*/
}
private static void printLucasRow(int nrOfNumbers){
int[] lucasRow = getLucasRow(nrOfNumbers);
if(lucasRow == null)return;
System.out.printf("De eerst %d Lucas-getallen:%n", lucasRow.length);
for(int i: lucasRow){
System.out.print(i + " ");
}
System.out.println();
}
private static int[] getLucasRow(int nrOfNumbers){
if(nrOfNumbers < 0){
System.out.println("Getal negatief, fout");
return null;
}
if(nrOfNumbers == 0) return new int[]{};
if(nrOfNumbers < 3) return new int[]{nrOfNumbers == 1? 2 : 2, 1};
int[] totalRow = new int[nrOfNumbers];
totalRow[0] = 2;
totalRow[1] = 1;
for(int i = 2; i < totalRow.length; i++){
totalRow[i] = totalRow[i-1] + totalRow[i-2];
if(((long)totalRow[i] + totalRow[i-1]) > Integer.MAX_VALUE){
System.out.println("Getal te groot, past niet");
return null;
}
}
return totalRow;
}
private static int exponent(int base, int exp){
return (int)Math.pow(base, exp);
}
private static boolean isOdd(int number){
return number%2 != 0;
}
public static int[] invert(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i] *= -1;
}
return array;
}
}
/*
2 1 3<SUF>*/ |
26112_0 | package qango;
import qango.fielddata.Qango6ColorZone;
//van row een char maken? of zorgen dat 'a' altijd gelijk is aan MINIMUM_COORDINATE_VALUE? dmv bvb een variabele distanceToA
public record Coordinate(int row, int column) implements Comparable<Coordinate>{
public Coordinate {
if (!isValid(row, column)) throw new IllegalArgumentException("Invalid value at Coordinate creation");
}
public static boolean isValid(int row, int column){
return Math.min(row, column) >= Qango6ColorZone.MINIMUM_COORDINATE_VALUE && Math.max(row, column) <= Qango6ColorZone.MAXIMUM_COORDINATE_VALUE;
}
@Override
public String toString(){
return String.format("%c%d", 'a'+row, column);
}
@Override
public int compareTo(Coordinate o) {
if(this.row != o.row){
return this.row - o.row;
}
return this.column - o.column;
}
} | Michelvdm83/Qango | src/qango/Coordinate.java | 275 | //van row een char maken? of zorgen dat 'a' altijd gelijk is aan MINIMUM_COORDINATE_VALUE? dmv bvb een variabele distanceToA | line_comment | nl | package qango;
import qango.fielddata.Qango6ColorZone;
//van row<SUF>
public record Coordinate(int row, int column) implements Comparable<Coordinate>{
public Coordinate {
if (!isValid(row, column)) throw new IllegalArgumentException("Invalid value at Coordinate creation");
}
public static boolean isValid(int row, int column){
return Math.min(row, column) >= Qango6ColorZone.MINIMUM_COORDINATE_VALUE && Math.max(row, column) <= Qango6ColorZone.MAXIMUM_COORDINATE_VALUE;
}
@Override
public String toString(){
return String.format("%c%d", 'a'+row, column);
}
@Override
public int compareTo(Coordinate o) {
if(this.row != o.row){
return this.row - o.row;
}
return this.column - o.column;
}
} |
90304_3 | /*
Copyright 2013 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.adapterframework.webcontrol.action;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.nn.adapterframework.http.HttpUtils;
import nl.nn.adapterframework.scheduler.SchedulerAdapter;
import nl.nn.adapterframework.scheduler.SchedulerHelper;
import nl.nn.adapterframework.unmanaged.DefaultIbisManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
/**
* @author Johan Verrips
*/
public class SchedulerHandler extends ActionBase {
public ActionForward executeSub(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Extract attributes we will need
initAction(request);
String action = request.getParameter("action");
if (null == action)
action = mapping.getParameter();
String jobName = request.getParameter("jobName");
String groupName = request.getParameter("groupName");
if (ibisManager==null) {
error("Cannot find ibismanager",null);
return null;
}
// TODO Dit moet natuurlijk netter...
DefaultIbisManager manager = (DefaultIbisManager)ibisManager;
SchedulerHelper sh = manager.getSchedulerHelper();
SchedulerAdapter schedulerAdapter = new SchedulerAdapter();
Scheduler scheduler;
try {
scheduler = sh.getScheduler();
} catch (SchedulerException e) {
error("Cannot find scheduler",e);
return null;
}
try {
String msg = null;
if (action.equalsIgnoreCase("startScheduler")) {
msg = "start scheduler:" + new Date() + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.start();
} else
if (action.equalsIgnoreCase("pauseScheduler")) {
msg = "pause scheduler:" + new Date() + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.standby();
} else
if (action.equalsIgnoreCase("deleteJob")) {
msg = "delete job jobName [" + jobName + "] groupName [" + groupName + "] " + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.deleteJob(jobName, groupName);
} else
if (action.equalsIgnoreCase("triggerJob")) {
msg = "trigger job jobName [" + jobName + "] groupName [" + groupName + "] " + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.triggerJob(jobName, groupName);
} else {
log.error("no valid argument for SchedulerHandler:" + action);
}
} catch (Exception e) {
error("",e);
}
// Report any errors
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope()))
request.removeAttribute(mapping.getAttribute());
else
session.removeAttribute(mapping.getAttribute());
}
// Forward control to the specified success URI
return (mapping.findForward("success"));
}
}
| MichielCuijpers/iaf | core/src/main/java/nl/nn/adapterframework/webcontrol/action/SchedulerHandler.java | 1,188 | // TODO Dit moet natuurlijk netter... | line_comment | nl | /*
Copyright 2013 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.adapterframework.webcontrol.action;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.nn.adapterframework.http.HttpUtils;
import nl.nn.adapterframework.scheduler.SchedulerAdapter;
import nl.nn.adapterframework.scheduler.SchedulerHelper;
import nl.nn.adapterframework.unmanaged.DefaultIbisManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
/**
* @author Johan Verrips
*/
public class SchedulerHandler extends ActionBase {
public ActionForward executeSub(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Extract attributes we will need
initAction(request);
String action = request.getParameter("action");
if (null == action)
action = mapping.getParameter();
String jobName = request.getParameter("jobName");
String groupName = request.getParameter("groupName");
if (ibisManager==null) {
error("Cannot find ibismanager",null);
return null;
}
// TODO Dit<SUF>
DefaultIbisManager manager = (DefaultIbisManager)ibisManager;
SchedulerHelper sh = manager.getSchedulerHelper();
SchedulerAdapter schedulerAdapter = new SchedulerAdapter();
Scheduler scheduler;
try {
scheduler = sh.getScheduler();
} catch (SchedulerException e) {
error("Cannot find scheduler",e);
return null;
}
try {
String msg = null;
if (action.equalsIgnoreCase("startScheduler")) {
msg = "start scheduler:" + new Date() + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.start();
} else
if (action.equalsIgnoreCase("pauseScheduler")) {
msg = "pause scheduler:" + new Date() + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.standby();
} else
if (action.equalsIgnoreCase("deleteJob")) {
msg = "delete job jobName [" + jobName + "] groupName [" + groupName + "] " + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.deleteJob(jobName, groupName);
} else
if (action.equalsIgnoreCase("triggerJob")) {
msg = "trigger job jobName [" + jobName + "] groupName [" + groupName + "] " + HttpUtils.getCommandIssuedBy(request);
log.info(msg);
secLog.info(msg);
scheduler.triggerJob(jobName, groupName);
} else {
log.error("no valid argument for SchedulerHandler:" + action);
}
} catch (Exception e) {
error("",e);
}
// Report any errors
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
// Remove the obsolete form bean
if (mapping.getAttribute() != null) {
if ("request".equals(mapping.getScope()))
request.removeAttribute(mapping.getAttribute());
else
session.removeAttribute(mapping.getAttribute());
}
// Forward control to the specified success URI
return (mapping.findForward("success"));
}
}
|
33131_7 | package nl.topicus.pages.getobject;
import java.util.Random;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import nl.topicus.pages.BasePage;
import nl.topicus.pages.readwrite.Leerling;
public class FunctionalInterfacePage extends BasePage
{
private static final long serialVersionUID = 1L;
private Label statischLabel, dynamischLabel;
@SuppressWarnings("unused")
@Override
protected void onInitialize()
{
super.onInitialize();
// Dit noemen we een anonymous-inner-class
// Een anonymous-inner-class heeft redelijk veel boilerplate-code
IModel<String> modelOne = new IModel<String>()
{
private static final long serialVersionUID = 1L;
@Override
public String getObject()
{
return getRandom();
}
};
// Daarom heeft Java wat "syntactic sugar" toegevoegd om dit wat korter te noteren. Deze
// "syntactic sugar" kan op _alle_ functional-interfaces toegepast worden:
IModel<String> modelTwo = () -> { return getRandom(); };
IModel<String> modelThree = () -> getRandom();
IModel<String> modelFour = this::getRandom;
// Bovenstaande 4 model-notaties werken dus functioneel _exact_ hetzelfde - zijn 1-op-1 uitwisselbaar
// en door de syntactic sugar is het lastig om het verschil tussen deze 2 te zien en te
// snappen - ik hoop dat door de vorige pagina het duidelijk(er) geworden is:
add(statischLabel = new Label("staticLabel", getRandom()));
add(dynamischLabel = new Label("dynamicLabel", () -> getRandom()));
addClickBehaviour();
// Voorbeeld van een andere functional interface - worden bijvoorbeeld vaak in streams gebruikt:
Function<Boolean, String> function = b -> b.toString(); // == return b.toString();
Predicate<Leerling> filter = leerling -> leerling != null;
}
private String getRandom()
{
return Integer.toString(new Random().nextInt());
}
private void addClickBehaviour()
{
WebMarkupContainer wmc = new WebMarkupContainer("clickContainer");
wmc.add(new AjaxEventBehavior("click")
{
private static final long serialVersionUID = 1L;
@Override
protected void onEvent(AjaxRequestTarget target)
{
// "AjaxRequestTarget" geeft aan dat je met een Ajax-request te maken hebt.
// Je intentie is dus om maar een deel van je scherm opnieuw te renderen - in dit
// geval wil je _2_ componenten opnieuw renderen.
target.add(statischLabel, dynamischLabel);
}
});
add(wmc);
statischLabel.setOutputMarkupId(true);
dynamischLabel.setOutputMarkupId(true);
}
@Override
protected Class< ? extends BasePage> getNextPageClass()
{
return DynamischModelWrapUpPage.class;
}
}
| MichielK/WicketModelsPresentatie | src/main/java/nl/topicus/pages/getobject/FunctionalInterfacePage.java | 968 | // Voorbeeld van een andere functional interface - worden bijvoorbeeld vaak in streams gebruikt:
| line_comment | nl | package nl.topicus.pages.getobject;
import java.util.Random;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import nl.topicus.pages.BasePage;
import nl.topicus.pages.readwrite.Leerling;
public class FunctionalInterfacePage extends BasePage
{
private static final long serialVersionUID = 1L;
private Label statischLabel, dynamischLabel;
@SuppressWarnings("unused")
@Override
protected void onInitialize()
{
super.onInitialize();
// Dit noemen we een anonymous-inner-class
// Een anonymous-inner-class heeft redelijk veel boilerplate-code
IModel<String> modelOne = new IModel<String>()
{
private static final long serialVersionUID = 1L;
@Override
public String getObject()
{
return getRandom();
}
};
// Daarom heeft Java wat "syntactic sugar" toegevoegd om dit wat korter te noteren. Deze
// "syntactic sugar" kan op _alle_ functional-interfaces toegepast worden:
IModel<String> modelTwo = () -> { return getRandom(); };
IModel<String> modelThree = () -> getRandom();
IModel<String> modelFour = this::getRandom;
// Bovenstaande 4 model-notaties werken dus functioneel _exact_ hetzelfde - zijn 1-op-1 uitwisselbaar
// en door de syntactic sugar is het lastig om het verschil tussen deze 2 te zien en te
// snappen - ik hoop dat door de vorige pagina het duidelijk(er) geworden is:
add(statischLabel = new Label("staticLabel", getRandom()));
add(dynamischLabel = new Label("dynamicLabel", () -> getRandom()));
addClickBehaviour();
// Voorbeeld van<SUF>
Function<Boolean, String> function = b -> b.toString(); // == return b.toString();
Predicate<Leerling> filter = leerling -> leerling != null;
}
private String getRandom()
{
return Integer.toString(new Random().nextInt());
}
private void addClickBehaviour()
{
WebMarkupContainer wmc = new WebMarkupContainer("clickContainer");
wmc.add(new AjaxEventBehavior("click")
{
private static final long serialVersionUID = 1L;
@Override
protected void onEvent(AjaxRequestTarget target)
{
// "AjaxRequestTarget" geeft aan dat je met een Ajax-request te maken hebt.
// Je intentie is dus om maar een deel van je scherm opnieuw te renderen - in dit
// geval wil je _2_ componenten opnieuw renderen.
target.add(statischLabel, dynamischLabel);
}
});
add(wmc);
statischLabel.setOutputMarkupId(true);
dynamischLabel.setOutputMarkupId(true);
}
@Override
protected Class< ? extends BasePage> getNextPageClass()
{
return DynamischModelWrapUpPage.class;
}
}
|
18183_3 | import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
/** De klasse voor een Bitmap item
* <P>
* This program is distributed under the terms of the accompanying
* COPYRIGHT.txt file (which is NOT the GNU General Public License).
* Please read it. Your use of the software constitutes acceptance
* of the terms in the COPYRIGHT.txt file.
* @author Ian F. Darwin, [email protected]
* @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn
* @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman
* @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman
* @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman
*/
public class BitmapItem extends SlideItem {
private BufferedImage bufferedImage;
private String imageName;
// level staat voor het item-level; name voor de naam van het bestand met het plaatje
public BitmapItem(int level, String name) {
super(level);
imageName = name;
try {
bufferedImage = ImageIO.read(new File(imageName));
}
catch (IOException e) {
System.err.println("Bestand " + imageName + " niet gevonden") ;
}
}
// Een leeg bitmap-item
public BitmapItem() {
this(0, null);
}
// geef de bestandsnaam van het plaatje
public String getName() {
return imageName;
}
// geef de bounding box van het plaatje
public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {
return new Rectangle((int) (myStyle.indent * scale), 0,
(int) (bufferedImage.getWidth(observer) * scale),
((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));
}
// teken het plaatje
public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {
int width = x + (int) (myStyle.indent * scale);
int height = y + (int) (myStyle.leading * scale);
g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),
(int) (bufferedImage.getHeight(observer)*scale), observer);
}
public String toString() {
return "BitmapItem[" + getLevel() + "," + imageName + "]";
}
}
| MichielMertens/OU_JP_MM_EVB | src/BitmapItem.java | 794 | // geef de bestandsnaam van het plaatje
| line_comment | nl | import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
/** De klasse voor een Bitmap item
* <P>
* This program is distributed under the terms of the accompanying
* COPYRIGHT.txt file (which is NOT the GNU General Public License).
* Please read it. Your use of the software constitutes acceptance
* of the terms in the COPYRIGHT.txt file.
* @author Ian F. Darwin, [email protected]
* @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn
* @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman
* @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman
* @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman
*/
public class BitmapItem extends SlideItem {
private BufferedImage bufferedImage;
private String imageName;
// level staat voor het item-level; name voor de naam van het bestand met het plaatje
public BitmapItem(int level, String name) {
super(level);
imageName = name;
try {
bufferedImage = ImageIO.read(new File(imageName));
}
catch (IOException e) {
System.err.println("Bestand " + imageName + " niet gevonden") ;
}
}
// Een leeg bitmap-item
public BitmapItem() {
this(0, null);
}
// geef de<SUF>
public String getName() {
return imageName;
}
// geef de bounding box van het plaatje
public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {
return new Rectangle((int) (myStyle.indent * scale), 0,
(int) (bufferedImage.getWidth(observer) * scale),
((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));
}
// teken het plaatje
public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {
int width = x + (int) (myStyle.indent * scale);
int height = y + (int) (myStyle.leading * scale);
g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),
(int) (bufferedImage.getHeight(observer)*scale), observer);
}
public String toString() {
return "BitmapItem[" + getLevel() + "," + imageName + "]";
}
}
|
50771_3 | package hhs4a.project2.c42.scenecontrollers;
import hhs4a.project2.c42.scenecontrollers.actionhandlers.accountusernamescreen.SaveUsernameChangesButtonClick;
import hhs4a.project2.c42.utils.account.Account;
import hhs4a.project2.c42.utils.account.LoggedInAccountHolder;
import hhs4a.project2.c42.utils.alert.AlertUtil;
import hhs4a.project2.c42.utils.database.databaseutils.AbstractDatabaseUtilTemplate;
import hhs4a.project2.c42.utils.database.databaseutils.AccountDatabaseUtil;
import io.github.palexdev.materialfx.controls.MFXPasswordField;
import io.github.palexdev.materialfx.controls.MFXTextField;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
public class AccountUsernameScreenController implements Screencontroller {
/*
Variables
*/
@FXML
private MFXTextField usernameTextField;
@FXML
private MFXPasswordField confirmPasswordField;
/*
Getters
*/
public MFXTextField getUsernameTextField() {
return usernameTextField;
}
public MFXPasswordField getConfirmPasswordField() {
return confirmPasswordField;
}
/*
Util methods
*/
public void updateAccountUsernameInDatabase(Account account) {
AbstractDatabaseUtilTemplate<Account> accountDatabaseUtil = AccountDatabaseUtil.getInstance();
if (accountDatabaseUtil.update(account)) {
AlertUtil.getInstance().showAlert(Alert.AlertType.INFORMATION, "Gebruikersnaam aangepast", "Uw gebruikersnaam is succesvol aangepast");
if (LoggedInAccountHolder.getInstance().getAccount().getId() == account.getId()) {
LoggedInAccountHolder.getInstance().getAccount().setUsername(account.getUsername());
}
// velden leeg maken
usernameTextField.clear();
confirmPasswordField.clear();
} else {
AlertUtil.getInstance().showAlert(Alert.AlertType.ERROR, "Fout bij gebruikersnaamwijziging", "Er is een fout opgetreden bij het aanpassen van uw gebruikersnaam. Probeer het alstublieft opnieuw.");
}
}
public boolean checkIfTextFieldEmpty(String username, String confirmPassword) {
// Checken of gebruikersnaam leeg is
if (username.isBlank()) {
AlertUtil.getInstance().showAlert(Alert.AlertType.INFORMATION, "Gebruikersnaam ontbreekt", "Het gebruikersnaamveld is niet ingevuld. Vul alstublieft uw nieuwe gebruikersnaam in.");
return true;
}
// Checken of wachtwoord leeg is
if (confirmPassword.isBlank()) {
AlertUtil.getInstance().showAlert(Alert.AlertType.INFORMATION, "Bevestigingswachtwoord ontbreekt", "Het bevestigingswachtwoordveld is niet ingevuld. Vul alstublieft uw bevestigingswachtwoord in.");
return true;
}
return false;
}
/*
Action handlers
*/
public void onSaveUsernameChangesClick() {
SaveUsernameChangesButtonClick saveUsernameChangesButtonClick = new SaveUsernameChangesButtonClick();
saveUsernameChangesButtonClick.setup(this);
saveUsernameChangesButtonClick.handle();
}
} | Michielo1/C4-2 | src/main/java/hhs4a/project2/c42/scenecontrollers/AccountUsernameScreenController.java | 926 | // velden leeg maken | line_comment | nl | package hhs4a.project2.c42.scenecontrollers;
import hhs4a.project2.c42.scenecontrollers.actionhandlers.accountusernamescreen.SaveUsernameChangesButtonClick;
import hhs4a.project2.c42.utils.account.Account;
import hhs4a.project2.c42.utils.account.LoggedInAccountHolder;
import hhs4a.project2.c42.utils.alert.AlertUtil;
import hhs4a.project2.c42.utils.database.databaseutils.AbstractDatabaseUtilTemplate;
import hhs4a.project2.c42.utils.database.databaseutils.AccountDatabaseUtil;
import io.github.palexdev.materialfx.controls.MFXPasswordField;
import io.github.palexdev.materialfx.controls.MFXTextField;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
public class AccountUsernameScreenController implements Screencontroller {
/*
Variables
*/
@FXML
private MFXTextField usernameTextField;
@FXML
private MFXPasswordField confirmPasswordField;
/*
Getters
*/
public MFXTextField getUsernameTextField() {
return usernameTextField;
}
public MFXPasswordField getConfirmPasswordField() {
return confirmPasswordField;
}
/*
Util methods
*/
public void updateAccountUsernameInDatabase(Account account) {
AbstractDatabaseUtilTemplate<Account> accountDatabaseUtil = AccountDatabaseUtil.getInstance();
if (accountDatabaseUtil.update(account)) {
AlertUtil.getInstance().showAlert(Alert.AlertType.INFORMATION, "Gebruikersnaam aangepast", "Uw gebruikersnaam is succesvol aangepast");
if (LoggedInAccountHolder.getInstance().getAccount().getId() == account.getId()) {
LoggedInAccountHolder.getInstance().getAccount().setUsername(account.getUsername());
}
// velden leeg<SUF>
usernameTextField.clear();
confirmPasswordField.clear();
} else {
AlertUtil.getInstance().showAlert(Alert.AlertType.ERROR, "Fout bij gebruikersnaamwijziging", "Er is een fout opgetreden bij het aanpassen van uw gebruikersnaam. Probeer het alstublieft opnieuw.");
}
}
public boolean checkIfTextFieldEmpty(String username, String confirmPassword) {
// Checken of gebruikersnaam leeg is
if (username.isBlank()) {
AlertUtil.getInstance().showAlert(Alert.AlertType.INFORMATION, "Gebruikersnaam ontbreekt", "Het gebruikersnaamveld is niet ingevuld. Vul alstublieft uw nieuwe gebruikersnaam in.");
return true;
}
// Checken of wachtwoord leeg is
if (confirmPassword.isBlank()) {
AlertUtil.getInstance().showAlert(Alert.AlertType.INFORMATION, "Bevestigingswachtwoord ontbreekt", "Het bevestigingswachtwoordveld is niet ingevuld. Vul alstublieft uw bevestigingswachtwoord in.");
return true;
}
return false;
}
/*
Action handlers
*/
public void onSaveUsernameChangesClick() {
SaveUsernameChangesButtonClick saveUsernameChangesButtonClick = new SaveUsernameChangesButtonClick();
saveUsernameChangesButtonClick.setup(this);
saveUsernameChangesButtonClick.handle();
}
} |
2285_38 | /*!\file NeoRS232.java
** This class implements an Idle RQ Stop & Wait protocol. This is a
* complicated manner to say that a transmitter must wait for an answer
* of the receiver before it can send something again.
* This protocol isn't the most speed-efficient way of communicating,
* but I'm using it to communicate it with a microcontroller. To prevent
* slowing down the microcontroller too much, I have to use a simple
* protocol.
* The protocol also includes a CRC16-error detection.
* \n
* For a user of this library, the above information is of no importance.
* The only thing you need to know is how to implement the following
* functions.
* Oh, remember: to use this package, you must have some version of
* javacomm installed. It's available from the
* <a href="http://java.sun.com">Java</a> website.
*
* \image html LieBtrau_anim.gif
* \author LieBtrau
* \author [email protected]
* \version version 1.1
*
*/
package LieBTrau.comm;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.Timer;
import LieBtrau.util.CRC16;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/*! Main class of the RS232-protcol.
*/
public class NeoRS232 implements Protocol{
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private SimpleWrite sw;
private SimpleRead sr;
private byte[] data;
private TijdKlok tk;
private boolean rxBusyFlag=false;
//set debug to "true" when you want messages in the command window
private boolean debug=false;
//om te laten weten dat er data ontvangen is
private ActionListener actionListener;
//zal de ontvangen data bevatten
private byte[] receivedData=null;
//baudrate of communication
private int baudRate;
/* public static void main(String[] args){
SerieData sd=new SerieData("COM1");
byte[] a=new byte[10];
sd.schrijfData(a);
//sd.sluitPoort();
}//main*/
/** This is a constructor
* @param poort This is a String indicating the type of port
* you want. e.g. "COM1"
* @param baudRate This is the baudRate used for communication
* (e.g. 115200)
* @param debug Make this boolean true if you want debug info,
* otherwise make this boolean false;
*/
public NeoRS232(String poort, int baudRate, boolean debug){
this(poort,baudRate); //call other constructor
this.debug=debug;
sr.setDebug(debug);
}//constructor1
/** This is a constructor
* @param poort This is a String indicating the type of port
* @param baudRate This is the baudRate used for communication
* (e.g. 115200)
* you want. e.g. "COM1"
*/
public NeoRS232(String poort, int baudRate){
this.baudRate=baudRate;
tk=new TijdKlok();
boolean poortOpen=false;
portList = CommPortIdentifier.getPortIdentifiers();
if(!portList.hasMoreElements())System.err.println("No ports found!");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
if (portId.getName().equals(poort))poortOpen=openPoort(poort);
}
}//constructor
//!Returns true when debug info enabled
boolean getDebug(){
return debug;
}//getDebug
//!Stop the timer (packet has arrived before timeout)
void stopTimer(){
tk.timerStoppen();
}//stopTimer
/** Use this function to write data to the port
* @param data A byte-array containing the bytes to be sent.
* Don't use large arrays, because you will flood the receiver.
*/
public void schrijfData(byte[] data){
this.data=data;
data=appendCRC(data);
/*start timer before data is sent because ACK sometimes
*comes in before timer is started
*/
tk.timerStarten();
sw.schrijfString(data,INFO_FRAME);
if(debug)System.out.println("Data geschreven");
}//schrijfData
/** This function closes the communications port. Call this
* function before closing your application. Otherwise the port
* remains open and you won't get the message: "Press any key to
* continue..."
*/
public void sluitPoort(){
/*Only close port when no data is being transferred.
*Check this first!
*/
if(debug)System.out.println("Waiting for closure"+
(tk.isRunning()?"tkTrue":"tkFalse"));
while(tk.isRunning());
try{
sw.close();
sr.close();
}
catch(IOException e){
System.err.println("Not possible to close port: "+e);
}
serialPort.close();
if(debug)System.out.println("All is closed");
}//sluitPoort
/** If you want that your class does something when
* data comes in, then you have to add an ActionListener
* using this method. The implementing
* ActionListener-class should contain a method
* actionPerformed. This method will be called when
* data comes in.
* @see java.awt.event.ActionListener
* @param actionListener an object of a class that
* implements the ActionListener class.
*/
public void addActionListener(ActionListener actionListener){
this.actionListener=actionListener;
}//addActionListener
/** Call this function to get the received data
*/
public byte[] getData(){
if(debug)System.out.println("receivedData: "+receivedData.length);
/*byte[] ret=new byte[receivedData.length];
for(int i=0;i<receivedData.length;i++){
ret[i]=receivedData[i];
}
return ret;*/
return receivedData;
}//getData
//------------------------------------------------------------------------------
//! Low level command to open the comport.
boolean openPoort(String poortNaam){
if(debug)System.out.print("Opening "+poortNaam+"...");
try {
serialPort = (SerialPort)portId.open("SimpleWriteApp", 2000);
/*Wacht 2000ms op het openen van de poort
*Indien de poort niet opent, wordt een PortInUseException gegenereerd
*/
} catch (PortInUseException e) {
System.err.println("\n"+poortNaam+" "+e);
return false;
}
try {
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
} catch (UnsupportedCommOperationException e) {
System.err.println("\n"+poortNaam+" "+e);
return false;
}
sw=new SimpleWrite(serialPort);
sr=new SimpleRead(serialPort,this);
if(debug)System.out.println("Success");
return true;
}//openPoort
private byte[] appendCRC(byte[] ab){
/*Maak data klaar voor verzenden (append CRC)
*parameter = array of bytes to be sent.
*return-value = array of bytes to be sent with CRC appended.
*
*The CRC is appended with the LSB first (little endian order)
*/
int grootte=ab.length;
byte[] result=new byte[grootte+2];
CRC16 crc16=new CRC16();
crc16.update(ab);
short crcValue=crc16.getValue();
if(debug)System.out.println("CRC-Value: 0x"+Integer.toHexString(crcValue));
//vul returnarray met de te zenden data
for(int i=0;i<grootte;i++)result[i]=ab[i];
//voeg er de CRC-bytes aan toe - little endian
for(int i=0;i<2;i++){
result[i+grootte]=(byte)((crcValue>>8*i)&0xFF);
}
return result;
}//appendCRC
private byte[] stripCRC(byte[] buffer){
/*Calculate the checksum
*parameter = received array with CRC at the end
*
*return: null when wrong checksum
* received array without checksum when correct checksum
*/
if(debug){
System.out.println("Buffer length(data+CRC): "+buffer.length);
for(int i=0;i<buffer.length;i++){
String s=Integer.toHexString(buffer[i]);
if(s.length()>2)s=s.substring(s.length()-2);
System.out.print(s+" ");
}
}
CRC16 crc16=new CRC16();
short crc16Ontvangen=0;
int grootte=buffer.length-2;
if(grootte>0){
byte[] result=new byte[grootte];
for(int i=0;i<grootte;i++)result[i]=buffer[i];
crc16.update(result);
//zoek ontvangen CRC op aan het einde van de ontvangen data
for(int i=0;i<2;i++)crc16Ontvangen|=(buffer[grootte+i]&0xFF)<<(8*i);
if(debug)System.out.println(Integer.toHexString(crc16.getValue()));
if(crc16.getValue()!=crc16Ontvangen){
System.err.println("\nFoute Checksum");
return null;
}
else{
if(debug)System.out.println("\nJuiste checksum");
return result;
}
}else{
System.err.println("Invalid data");
return null;
}
}//stripCRC
/*!This function gets called when a complete frame has been
*received.
*It sends the transmitter an acknowledge when data is
*received correctly. It also passes the data on to a
*higher OSI-layer.
*\param inputBuffer Buffer containing data to send.
*/
void bewerkDatagram(ArrayList inputBuffer){
receivedData=stripCRC(toByteArray(inputBuffer));
//toonBuffer(receivedData);
if(receivedData!=null){
//Frame goed ontvangen, stuur dan een acknowledge
if(debug)System.out.println("ACK sent");
sw.schrijfString(null,ACK_FRAME);
//Laat aan de actionListener weten dat we iets ontvangen hebben
if(actionListener!=null)
actionListener.actionPerformed(
new ActionEvent(this,0,"Data ready"));
else
System.err.println("No ActionListener attached.");
}
}//bewerkDatagram
//!Print contents of the buffer on the screen
void toonBuffer(ArrayList buffer){
System.out.println(buffer.size());
for(int i=0;i<buffer.size();i++)System.out.print((Byte)buffer.get(i));
}//toonBuffer
//!Print contents of the buffer on the screen
void toonBuffer(byte[] buffer){
System.out.println(buffer.length);
for(int i=0;i<buffer.length;i++)System.out.print(Byte.toString(buffer[i]));
}//toonBuffer
//!Convert an arraylist to a buffer of bytes
byte[] toByteArray(ArrayList buffer){
byte[] result=new byte[buffer.size()];
for(int i=0;i<buffer.size();i++)result[i]=((Byte)buffer.get(i)).byteValue();
return result;
}//toByteArray
///////////////////////////////////////////////////////////
/*!Timer class added because a transmitter must know how long
*it has to wait for an acknowledge of the receiver.
*/
class TijdKlok implements ActionListener{
Timer timer;//!< Timer object keeping track of time
/*!Variable that counts how many times we tried to
*resend data.
*/
int poging;
final int TIMEDELAY=5000;//!< Timeout (in ms.)
//!Maximum number of times to try resending data
final int MAX_POGING=5;
TijdKlok(){
//Timer zal na TIMEDELAY de actionListener van deze klasse oproepen
timer=new Timer(TIMEDELAY,this);
//Timer zal stoppen als TIMEDELAY bereikt is
timer.setRepeats(false);
}//constructor
/*!Timeout reached. Try five times to send the
* data again.
* \param e timer event that triggers this function.
*/
public void actionPerformed(ActionEvent e){
System.err.println("Het antwoord is niet aangekomen binnen de tijd");
if(poging<MAX_POGING){
poging++;
System.err.println("Poging "+poging+" probeer opnieuw te zenden");
//timer.setInitialDelay(TIMEDELAY);
timer.start();
sw.schrijfString(data,INFO_FRAME);
}
else{
System.err.println("Pogingen gestaakt. Verbinding verbroken");
timerStoppen();
sluitPoort();
}
}//actionPerformed
//!Return true when timer is running.
boolean isRunning(){
return timer.isRunning();
}//isRunning
//!Start the timer
void timerStarten(){
timer.start();
}//timerStarten
//!Stop the timer
void timerStoppen(){
poging=0;
timer.stop();
}//timerStoppen
}//class TijdKlok
}//class | MicrochipTech/avrfreaks-projects | projects/neors232/java_NeoRS232/neoRS232/src/NeoRS232.java | 3,892 | //Timer zal stoppen als TIMEDELAY bereikt is | line_comment | nl | /*!\file NeoRS232.java
** This class implements an Idle RQ Stop & Wait protocol. This is a
* complicated manner to say that a transmitter must wait for an answer
* of the receiver before it can send something again.
* This protocol isn't the most speed-efficient way of communicating,
* but I'm using it to communicate it with a microcontroller. To prevent
* slowing down the microcontroller too much, I have to use a simple
* protocol.
* The protocol also includes a CRC16-error detection.
* \n
* For a user of this library, the above information is of no importance.
* The only thing you need to know is how to implement the following
* functions.
* Oh, remember: to use this package, you must have some version of
* javacomm installed. It's available from the
* <a href="http://java.sun.com">Java</a> website.
*
* \image html LieBtrau_anim.gif
* \author LieBtrau
* \author [email protected]
* \version version 1.1
*
*/
package LieBTrau.comm;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.Timer;
import LieBtrau.util.CRC16;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/*! Main class of the RS232-protcol.
*/
public class NeoRS232 implements Protocol{
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private SimpleWrite sw;
private SimpleRead sr;
private byte[] data;
private TijdKlok tk;
private boolean rxBusyFlag=false;
//set debug to "true" when you want messages in the command window
private boolean debug=false;
//om te laten weten dat er data ontvangen is
private ActionListener actionListener;
//zal de ontvangen data bevatten
private byte[] receivedData=null;
//baudrate of communication
private int baudRate;
/* public static void main(String[] args){
SerieData sd=new SerieData("COM1");
byte[] a=new byte[10];
sd.schrijfData(a);
//sd.sluitPoort();
}//main*/
/** This is a constructor
* @param poort This is a String indicating the type of port
* you want. e.g. "COM1"
* @param baudRate This is the baudRate used for communication
* (e.g. 115200)
* @param debug Make this boolean true if you want debug info,
* otherwise make this boolean false;
*/
public NeoRS232(String poort, int baudRate, boolean debug){
this(poort,baudRate); //call other constructor
this.debug=debug;
sr.setDebug(debug);
}//constructor1
/** This is a constructor
* @param poort This is a String indicating the type of port
* @param baudRate This is the baudRate used for communication
* (e.g. 115200)
* you want. e.g. "COM1"
*/
public NeoRS232(String poort, int baudRate){
this.baudRate=baudRate;
tk=new TijdKlok();
boolean poortOpen=false;
portList = CommPortIdentifier.getPortIdentifiers();
if(!portList.hasMoreElements())System.err.println("No ports found!");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
if (portId.getName().equals(poort))poortOpen=openPoort(poort);
}
}//constructor
//!Returns true when debug info enabled
boolean getDebug(){
return debug;
}//getDebug
//!Stop the timer (packet has arrived before timeout)
void stopTimer(){
tk.timerStoppen();
}//stopTimer
/** Use this function to write data to the port
* @param data A byte-array containing the bytes to be sent.
* Don't use large arrays, because you will flood the receiver.
*/
public void schrijfData(byte[] data){
this.data=data;
data=appendCRC(data);
/*start timer before data is sent because ACK sometimes
*comes in before timer is started
*/
tk.timerStarten();
sw.schrijfString(data,INFO_FRAME);
if(debug)System.out.println("Data geschreven");
}//schrijfData
/** This function closes the communications port. Call this
* function before closing your application. Otherwise the port
* remains open and you won't get the message: "Press any key to
* continue..."
*/
public void sluitPoort(){
/*Only close port when no data is being transferred.
*Check this first!
*/
if(debug)System.out.println("Waiting for closure"+
(tk.isRunning()?"tkTrue":"tkFalse"));
while(tk.isRunning());
try{
sw.close();
sr.close();
}
catch(IOException e){
System.err.println("Not possible to close port: "+e);
}
serialPort.close();
if(debug)System.out.println("All is closed");
}//sluitPoort
/** If you want that your class does something when
* data comes in, then you have to add an ActionListener
* using this method. The implementing
* ActionListener-class should contain a method
* actionPerformed. This method will be called when
* data comes in.
* @see java.awt.event.ActionListener
* @param actionListener an object of a class that
* implements the ActionListener class.
*/
public void addActionListener(ActionListener actionListener){
this.actionListener=actionListener;
}//addActionListener
/** Call this function to get the received data
*/
public byte[] getData(){
if(debug)System.out.println("receivedData: "+receivedData.length);
/*byte[] ret=new byte[receivedData.length];
for(int i=0;i<receivedData.length;i++){
ret[i]=receivedData[i];
}
return ret;*/
return receivedData;
}//getData
//------------------------------------------------------------------------------
//! Low level command to open the comport.
boolean openPoort(String poortNaam){
if(debug)System.out.print("Opening "+poortNaam+"...");
try {
serialPort = (SerialPort)portId.open("SimpleWriteApp", 2000);
/*Wacht 2000ms op het openen van de poort
*Indien de poort niet opent, wordt een PortInUseException gegenereerd
*/
} catch (PortInUseException e) {
System.err.println("\n"+poortNaam+" "+e);
return false;
}
try {
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
} catch (UnsupportedCommOperationException e) {
System.err.println("\n"+poortNaam+" "+e);
return false;
}
sw=new SimpleWrite(serialPort);
sr=new SimpleRead(serialPort,this);
if(debug)System.out.println("Success");
return true;
}//openPoort
private byte[] appendCRC(byte[] ab){
/*Maak data klaar voor verzenden (append CRC)
*parameter = array of bytes to be sent.
*return-value = array of bytes to be sent with CRC appended.
*
*The CRC is appended with the LSB first (little endian order)
*/
int grootte=ab.length;
byte[] result=new byte[grootte+2];
CRC16 crc16=new CRC16();
crc16.update(ab);
short crcValue=crc16.getValue();
if(debug)System.out.println("CRC-Value: 0x"+Integer.toHexString(crcValue));
//vul returnarray met de te zenden data
for(int i=0;i<grootte;i++)result[i]=ab[i];
//voeg er de CRC-bytes aan toe - little endian
for(int i=0;i<2;i++){
result[i+grootte]=(byte)((crcValue>>8*i)&0xFF);
}
return result;
}//appendCRC
private byte[] stripCRC(byte[] buffer){
/*Calculate the checksum
*parameter = received array with CRC at the end
*
*return: null when wrong checksum
* received array without checksum when correct checksum
*/
if(debug){
System.out.println("Buffer length(data+CRC): "+buffer.length);
for(int i=0;i<buffer.length;i++){
String s=Integer.toHexString(buffer[i]);
if(s.length()>2)s=s.substring(s.length()-2);
System.out.print(s+" ");
}
}
CRC16 crc16=new CRC16();
short crc16Ontvangen=0;
int grootte=buffer.length-2;
if(grootte>0){
byte[] result=new byte[grootte];
for(int i=0;i<grootte;i++)result[i]=buffer[i];
crc16.update(result);
//zoek ontvangen CRC op aan het einde van de ontvangen data
for(int i=0;i<2;i++)crc16Ontvangen|=(buffer[grootte+i]&0xFF)<<(8*i);
if(debug)System.out.println(Integer.toHexString(crc16.getValue()));
if(crc16.getValue()!=crc16Ontvangen){
System.err.println("\nFoute Checksum");
return null;
}
else{
if(debug)System.out.println("\nJuiste checksum");
return result;
}
}else{
System.err.println("Invalid data");
return null;
}
}//stripCRC
/*!This function gets called when a complete frame has been
*received.
*It sends the transmitter an acknowledge when data is
*received correctly. It also passes the data on to a
*higher OSI-layer.
*\param inputBuffer Buffer containing data to send.
*/
void bewerkDatagram(ArrayList inputBuffer){
receivedData=stripCRC(toByteArray(inputBuffer));
//toonBuffer(receivedData);
if(receivedData!=null){
//Frame goed ontvangen, stuur dan een acknowledge
if(debug)System.out.println("ACK sent");
sw.schrijfString(null,ACK_FRAME);
//Laat aan de actionListener weten dat we iets ontvangen hebben
if(actionListener!=null)
actionListener.actionPerformed(
new ActionEvent(this,0,"Data ready"));
else
System.err.println("No ActionListener attached.");
}
}//bewerkDatagram
//!Print contents of the buffer on the screen
void toonBuffer(ArrayList buffer){
System.out.println(buffer.size());
for(int i=0;i<buffer.size();i++)System.out.print((Byte)buffer.get(i));
}//toonBuffer
//!Print contents of the buffer on the screen
void toonBuffer(byte[] buffer){
System.out.println(buffer.length);
for(int i=0;i<buffer.length;i++)System.out.print(Byte.toString(buffer[i]));
}//toonBuffer
//!Convert an arraylist to a buffer of bytes
byte[] toByteArray(ArrayList buffer){
byte[] result=new byte[buffer.size()];
for(int i=0;i<buffer.size();i++)result[i]=((Byte)buffer.get(i)).byteValue();
return result;
}//toByteArray
///////////////////////////////////////////////////////////
/*!Timer class added because a transmitter must know how long
*it has to wait for an acknowledge of the receiver.
*/
class TijdKlok implements ActionListener{
Timer timer;//!< Timer object keeping track of time
/*!Variable that counts how many times we tried to
*resend data.
*/
int poging;
final int TIMEDELAY=5000;//!< Timeout (in ms.)
//!Maximum number of times to try resending data
final int MAX_POGING=5;
TijdKlok(){
//Timer zal na TIMEDELAY de actionListener van deze klasse oproepen
timer=new Timer(TIMEDELAY,this);
//Timer zal<SUF>
timer.setRepeats(false);
}//constructor
/*!Timeout reached. Try five times to send the
* data again.
* \param e timer event that triggers this function.
*/
public void actionPerformed(ActionEvent e){
System.err.println("Het antwoord is niet aangekomen binnen de tijd");
if(poging<MAX_POGING){
poging++;
System.err.println("Poging "+poging+" probeer opnieuw te zenden");
//timer.setInitialDelay(TIMEDELAY);
timer.start();
sw.schrijfString(data,INFO_FRAME);
}
else{
System.err.println("Pogingen gestaakt. Verbinding verbroken");
timerStoppen();
sluitPoort();
}
}//actionPerformed
//!Return true when timer is running.
boolean isRunning(){
return timer.isRunning();
}//isRunning
//!Start the timer
void timerStarten(){
timer.start();
}//timerStarten
//!Stop the timer
void timerStoppen(){
poging=0;
timer.stop();
}//timerStoppen
}//class TijdKlok
}//class |
30743_17 | //package sr.unasat.facade;
//
//import sr.unasat.Helper.sr.unasat.Helper;
//import sr.unasat.entity.*;
//import sr.unasat.factory.Voertuig;
//import sr.unasat.service.*;
//
//import java.util.List;
//
//
//public class AdminFacade {
// KlantService ks = new KlantService();
// BestellingService bs = new BestellingService();
// ChauffeurService cs = new ChauffeurService();
// LeveringService ls = new LeveringService();
// ProductService ps = new ProductService();
// VoertuigService vs = new VoertuigService();
// BestellingProductService bps = new BestellingProductService();
//
//
// public void welcome() {
// System.out.println("Welcome to the logistics admin.");
// System.out.println();
// }
//
// public void menuOptions() {
// System.out.println("Menu: ");
//
// System.out.print("[Bestelling] (B)");
// System.out.print(" [Klant] (K)");
// System.out.print(" [Chauffeur] (C)");
// System.out.print(" [Product] (P)");
// System.out.print(" [Levering] (L)");
// System.out.print(" [Vrachtwagen] (V)");
// System.out.print(" (Exit)");
// }
//
// public void nieuwKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// ks.createKlant(voorNaam, achterNaam, adres, telefoon);
// System.out.println("Klant succesvol toegevoegd");
// }
//
// public void lijstKlanten() {
// for (Klant k :
// ks.getKlant()) {
// System.out.println(k);
// }
// }
//
// public void zoekOneKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println(ks.findKlantByName(voorNaam, achterNaam));
// }
//
// public void deleteKlant() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ks.deleteKlant(id);
// System.out.println("klant met ID " + id + " verwijderd");
// }
//
// public void updateKlantNaam() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
//
// ks.updateNaam(id, voorNaam, achterNaam);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantAdres() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ks.updateAdres(id, adres);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantTelefoon() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
// ks.updateAdres(id, telefoon);
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void lijstBestelling() {
// for (Bestelling b : bs.getBestelling()
// ) {
// System.out.println(b);
// }
// }
//
// public void lijstBestellingProducten() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// for (BestellingProduct bp : bs.findBestellingById(id).getProducten()
// ) {
// System.out.println(bp);
// }
// }
//
//
// public void nieuwBestelling() {
// System.out.println("Klant voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("Klant achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
//
// List<String> p = sr.unasat.Helper.scanStringList();
// List<Integer> a = sr.unasat.Helper.scanIntList();
//
// bps.createBestellingProduct(bs.createBestelling(voornaam, achternaam, jaar, maand, dag), p, a);
//
// System.out.println("Bestelling succesvol toegevoegd");
// }
//
// public void zoekOneBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(bs.findBestellingById(id));
// }
//
//// public void updateLeveringKosten() {
//// System.out.println("Bestelling ID: ");
//// int id = sr.unasat.Helper.scanInt();
//// System.out.println("leveringskosten: ");
//// double leveringskosten = sr.unasat.Helper.scandouble();
//// bs.updateLeveringskosten(id, leveringskosten);
//// System.out.println("Bestelling met ID " + id + " updated");
//// }
//
// public void updateLeveringDatum() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
// bs.updateLeveringsDatum(id, jaar, maand, dag);
// System.out.println("Bestelling met ID " + id + " updated");
// }
//
// public void deleteBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// bs.deleteBestelling(id);
// System.out.println("Bestelling met ID " + id + " verwijderd");
// }
//
// public void lijstChauffeur() {
// for (Chauffeur c :
// cs.getChauffeur()) {
// System.out.println(c);
// }
// }
//
// public void nieuwChauffeur() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.createChauffeur(voornaam, achternaam, telefoon);
// System.out.println("Chauffeur succesvol toegevoegd");
// }
//
// public void zoekChauffeurBijNaam() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// System.out.println(cs.findChauffeurByName(voornaam, achternaam));
// }
//
// public void zoekChauffeurBijId() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(cs.findChauffeurById(id));
// }
//
// public void updateChauffeurNaam() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// cs.updateNaam(id, voornaam, achternaam);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void updateChauffeurTelefoon() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.updateTelefoon(id, telefoon);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void deleteChauffeur() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// cs.deleteChauffeur(id);
// System.out.println("Chauffeur met ID " + id + " verwijderd");
// }
//
// public void nieuwLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//// System.out.println("voornaam: ");
//// String voornaam = sr.unasat.Helper.scanstring();
//// System.out.println("achternaam: ");
//// String achternaam = sr.unasat.Helper.scanstring();
//
// ls.createLevering(id);
// System.out.println("Levering succesvol toegevoegd");
// }
//
// public void lijstLevering() {
// for (Levering l :
// ls.getLevering()) {
// System.out.println(l);
// }
// }
//
// public void deleteLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.deleteLevering(id);
// System.out.println("Levering met ID " + id + " verwijderd");
// }
//
// public void zoekLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.findLeveringById(id);
// }
//
// public void updateStatus() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("nieuw status: ");
// String status = sr.unasat.Helper.scanstring();
//
// ls.updateLeveringStatus(id, status);
// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void updateLeveringChauffeur() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println("error: function not ready");
//// ls.updateLeveringChauffeur();
//// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void nieuwProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.createProduct(naam, prijs, adres);
// System.out.println("Product succesvol toegevoegd");
// }
//
// public void deleteProduct() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ps.deleteProduct(id);
// System.out.println("Product met ID " + id + " verwijderd");
// }
//
// public void lijstProduct() {
// for (Product p :
// ps.getAllProducts()) {
// System.out.println(p);
// }
// }
//
// public void updatePrijs() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
//
// ps.updatePrijs(id, prijs);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void updateAdres() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.updateAdres(id, adres);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void zoekOneProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
//
// System.out.println(ps.findProductByName(naam));
// }
//
// public void nieuwVoertuig() {
// System.out.println("type (vrachtwagen of anders): ");
// String type = sr.unasat.Helper.scanstring();
// System.out.println("merk: ");
// String merk = sr.unasat.Helper.scanstring();
// System.out.println("capaciteit: ");
// int capaciteit = sr.unasat.Helper.scanInt();
// System.out.println("kenteken nummer: ");
// String kenteken = sr.unasat.Helper.scanstring();
//
// vs.createVoertuig(type, merk, capaciteit, kenteken);
// System.out.println("Voertuig succesvol toegevoegd");
// }
//
// public void deleteVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
// vs.deleteVoertuig(id);
// System.out.println("Voertuig met ID " + id + " verwijderd");
// }
//
// public void lijstVoertuig() {
// String type = sr.unasat.Helper.scanstring();
// for (Voertuig v :
// vs.getAllVoertuig(type)) {
// System.out.println(v);
// }
// }
//
// public void zoekOneVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(vs.findVoertuigById(id));
// }
//
//// public void subMenuVoertuig() {
//// System.out.println("Functies: ");
//// System.out.print("(add)");
//// System.out.print(" (delete)");
//// System.out.print(" (lijst voertuig)");
//// System.out.print(" (zoek voertuig)");
//// System.out.println(" (back)");
////
//// String menu = sr.unasat.Helper.scanstring();
//// switch (menu.toLowerCase()) {
//// case "add" -> {
//// nieuwVoertuig();
//// subMenuVoertuig();
//// }
//// case "delete" -> {
//// deleteVoertuig();
//// subMenuVoertuig();
//// }
//// case "lijst voertuig" -> {
//// lijstVoertuig();
//// subMenuVoertuig();
//// }
//// case "zoek voertuig" -> {
//// zoekOneVoertuig();
//// subMenuVoertuig();
//// }
//// case "back" -> menu();
//// default -> {
//// System.out.println("Invalid input. Try again.");
//// subMenuVoertuig();
//// }
//// }
//// }
//
// public void subMenuProduct() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst product)");
// System.out.print(" (update prijs)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek product)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwProduct();
// subMenuProduct();
// }
// case "delete" -> {
// deleteProduct();
// subMenuProduct();
// }
// case "lijst product" -> {
// lijstProduct();
// subMenuProduct();
// }
// case "update prijs" -> {
// updatePrijs();
// subMenuKlant();
// }
// case "update adres" -> {
// updateAdres();
// subMenuProduct();
// }
// case "zoek product" -> {
// zoekOneProduct();
// subMenuProduct();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuProduct();
// }
// }
// }
//
// public void subMenuLevering() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst levering)");
// System.out.print(" (update status)");
// System.out.print(" (update chauffeur)");
// System.out.print(" (zoek levering)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwLevering();
// subMenuLevering();
// }
// case "delete" -> {
// deleteLevering();
// subMenuLevering();
// }
// case "lijst levering" -> {
// lijstLevering();
// subMenuLevering();
// }
// case "update status" -> {
// updateStatus();
// subMenuLevering();
// }
// case "update chauffeur" -> {
// updateLeveringChauffeur();
// subMenuLevering();
// }
// case "zoek levering" -> {
// zoekLevering();
// subMenuLevering();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuLevering();
// }
// }
// }
//
// public void subMenuKlant() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Klant)");
// System.out.print(" (update Telefoon)");
// System.out.print(" (update naam)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek klant)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwKlant();
// subMenuKlant();
// }
// case "delete" -> {
// deleteKlant();
// subMenuKlant();
// }
// case "lijst klant" -> {
// lijstKlanten();
// subMenuKlant();
// }
// case "update telefoon" -> {
// updateKlantTelefoon();
// subMenuKlant();
// }
// case "update naam" -> {
// updateKlantNaam();
// subMenuKlant();
// }
// case "update adres" -> {
// updateKlantAdres();
// subMenuKlant();
// }
// case "zoek klant" -> {
// zoekOneKlant();
// subMenuKlant();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuKlant();
// }
// }
// }
//
// public void subMenuBestelling() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Bestelling)");
// System.out.print(" (lijst Bestelling producten)");
// System.out.print(" (update leveringsdatum)");
// System.out.print(" (zoek Bestelling)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwBestelling();
// subMenuBestelling();
// }
// case "delete" -> {
// deleteBestelling();
// subMenuBestelling();
// }
// case "lijst bestelling" -> {
// lijstBestelling();
// subMenuBestelling();
// }
// case "update leveringsdatum" -> {
// updateLeveringDatum();
// subMenuBestelling();
// }
// case "bestelling producten" -> {
// lijstBestellingProducten();
// subMenuBestelling();
// }
// case "zoek bestelling" -> {
// zoekOneBestelling();
// subMenuBestelling();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuBestelling();
// }
// }
// }
//
// public void subMenuChauffeur() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Chauffeur)");
// System.out.print(" (update naam)");
// System.out.print(" (update telefoon)");
// System.out.print(" (zoek chauffeur bij naam)");
// System.out.print(" (zoek chauffeur bij id)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwChauffeur();
// subMenuChauffeur();
// }
// case "delete" -> {
// deleteChauffeur();
// subMenuChauffeur();
// }
// case "lijst chauffeur" -> {
// lijstChauffeur();
// subMenuChauffeur();
// }
// case "update naam" -> {
// updateChauffeurNaam();
// subMenuChauffeur();
// }
// case "update telefoon" -> {
// updateChauffeurTelefoon();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij naam" -> {
// zoekChauffeurBijNaam();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij id" -> {
// zoekChauffeurBijId();
// subMenuChauffeur();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuChauffeur();
// }
// }
// }
//
// public void menu() {
// menuOptions();
// System.out.println();
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toUpperCase()) {
// case "K" -> subMenuKlant();
// case "B" -> subMenuBestelling();
// case "C" -> subMenuChauffeur();
// case "L" -> subMenuLevering();
// case "V" -> subMenuVoertuig();
// case "P" -> subMenuProduct();
// case "EXIT" -> System.out.println("End Of Program");
// default -> {
// System.out.println("Invalid input. Try again.");
// menu();
// }
// }
// }
//
//}
| MiguelSaffier/logistiekWebApp | src/main/java/sr/unasat/facade/AdminFacade.java | 7,335 | // String voorNaam = sr.unasat.Helper.scanstring(); | line_comment | nl | //package sr.unasat.facade;
//
//import sr.unasat.Helper.sr.unasat.Helper;
//import sr.unasat.entity.*;
//import sr.unasat.factory.Voertuig;
//import sr.unasat.service.*;
//
//import java.util.List;
//
//
//public class AdminFacade {
// KlantService ks = new KlantService();
// BestellingService bs = new BestellingService();
// ChauffeurService cs = new ChauffeurService();
// LeveringService ls = new LeveringService();
// ProductService ps = new ProductService();
// VoertuigService vs = new VoertuigService();
// BestellingProductService bps = new BestellingProductService();
//
//
// public void welcome() {
// System.out.println("Welcome to the logistics admin.");
// System.out.println();
// }
//
// public void menuOptions() {
// System.out.println("Menu: ");
//
// System.out.print("[Bestelling] (B)");
// System.out.print(" [Klant] (K)");
// System.out.print(" [Chauffeur] (C)");
// System.out.print(" [Product] (P)");
// System.out.print(" [Levering] (L)");
// System.out.print(" [Vrachtwagen] (V)");
// System.out.print(" (Exit)");
// }
//
// public void nieuwKlant() {
// System.out.println("voornaam: ");
// String voorNaam<SUF>
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// ks.createKlant(voorNaam, achterNaam, adres, telefoon);
// System.out.println("Klant succesvol toegevoegd");
// }
//
// public void lijstKlanten() {
// for (Klant k :
// ks.getKlant()) {
// System.out.println(k);
// }
// }
//
// public void zoekOneKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println(ks.findKlantByName(voorNaam, achterNaam));
// }
//
// public void deleteKlant() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ks.deleteKlant(id);
// System.out.println("klant met ID " + id + " verwijderd");
// }
//
// public void updateKlantNaam() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
//
// ks.updateNaam(id, voorNaam, achterNaam);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantAdres() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ks.updateAdres(id, adres);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantTelefoon() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
// ks.updateAdres(id, telefoon);
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void lijstBestelling() {
// for (Bestelling b : bs.getBestelling()
// ) {
// System.out.println(b);
// }
// }
//
// public void lijstBestellingProducten() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// for (BestellingProduct bp : bs.findBestellingById(id).getProducten()
// ) {
// System.out.println(bp);
// }
// }
//
//
// public void nieuwBestelling() {
// System.out.println("Klant voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("Klant achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
//
// List<String> p = sr.unasat.Helper.scanStringList();
// List<Integer> a = sr.unasat.Helper.scanIntList();
//
// bps.createBestellingProduct(bs.createBestelling(voornaam, achternaam, jaar, maand, dag), p, a);
//
// System.out.println("Bestelling succesvol toegevoegd");
// }
//
// public void zoekOneBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(bs.findBestellingById(id));
// }
//
//// public void updateLeveringKosten() {
//// System.out.println("Bestelling ID: ");
//// int id = sr.unasat.Helper.scanInt();
//// System.out.println("leveringskosten: ");
//// double leveringskosten = sr.unasat.Helper.scandouble();
//// bs.updateLeveringskosten(id, leveringskosten);
//// System.out.println("Bestelling met ID " + id + " updated");
//// }
//
// public void updateLeveringDatum() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
// bs.updateLeveringsDatum(id, jaar, maand, dag);
// System.out.println("Bestelling met ID " + id + " updated");
// }
//
// public void deleteBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// bs.deleteBestelling(id);
// System.out.println("Bestelling met ID " + id + " verwijderd");
// }
//
// public void lijstChauffeur() {
// for (Chauffeur c :
// cs.getChauffeur()) {
// System.out.println(c);
// }
// }
//
// public void nieuwChauffeur() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.createChauffeur(voornaam, achternaam, telefoon);
// System.out.println("Chauffeur succesvol toegevoegd");
// }
//
// public void zoekChauffeurBijNaam() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// System.out.println(cs.findChauffeurByName(voornaam, achternaam));
// }
//
// public void zoekChauffeurBijId() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(cs.findChauffeurById(id));
// }
//
// public void updateChauffeurNaam() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// cs.updateNaam(id, voornaam, achternaam);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void updateChauffeurTelefoon() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.updateTelefoon(id, telefoon);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void deleteChauffeur() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// cs.deleteChauffeur(id);
// System.out.println("Chauffeur met ID " + id + " verwijderd");
// }
//
// public void nieuwLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//// System.out.println("voornaam: ");
//// String voornaam = sr.unasat.Helper.scanstring();
//// System.out.println("achternaam: ");
//// String achternaam = sr.unasat.Helper.scanstring();
//
// ls.createLevering(id);
// System.out.println("Levering succesvol toegevoegd");
// }
//
// public void lijstLevering() {
// for (Levering l :
// ls.getLevering()) {
// System.out.println(l);
// }
// }
//
// public void deleteLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.deleteLevering(id);
// System.out.println("Levering met ID " + id + " verwijderd");
// }
//
// public void zoekLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.findLeveringById(id);
// }
//
// public void updateStatus() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("nieuw status: ");
// String status = sr.unasat.Helper.scanstring();
//
// ls.updateLeveringStatus(id, status);
// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void updateLeveringChauffeur() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println("error: function not ready");
//// ls.updateLeveringChauffeur();
//// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void nieuwProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.createProduct(naam, prijs, adres);
// System.out.println("Product succesvol toegevoegd");
// }
//
// public void deleteProduct() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ps.deleteProduct(id);
// System.out.println("Product met ID " + id + " verwijderd");
// }
//
// public void lijstProduct() {
// for (Product p :
// ps.getAllProducts()) {
// System.out.println(p);
// }
// }
//
// public void updatePrijs() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
//
// ps.updatePrijs(id, prijs);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void updateAdres() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.updateAdres(id, adres);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void zoekOneProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
//
// System.out.println(ps.findProductByName(naam));
// }
//
// public void nieuwVoertuig() {
// System.out.println("type (vrachtwagen of anders): ");
// String type = sr.unasat.Helper.scanstring();
// System.out.println("merk: ");
// String merk = sr.unasat.Helper.scanstring();
// System.out.println("capaciteit: ");
// int capaciteit = sr.unasat.Helper.scanInt();
// System.out.println("kenteken nummer: ");
// String kenteken = sr.unasat.Helper.scanstring();
//
// vs.createVoertuig(type, merk, capaciteit, kenteken);
// System.out.println("Voertuig succesvol toegevoegd");
// }
//
// public void deleteVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
// vs.deleteVoertuig(id);
// System.out.println("Voertuig met ID " + id + " verwijderd");
// }
//
// public void lijstVoertuig() {
// String type = sr.unasat.Helper.scanstring();
// for (Voertuig v :
// vs.getAllVoertuig(type)) {
// System.out.println(v);
// }
// }
//
// public void zoekOneVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(vs.findVoertuigById(id));
// }
//
//// public void subMenuVoertuig() {
//// System.out.println("Functies: ");
//// System.out.print("(add)");
//// System.out.print(" (delete)");
//// System.out.print(" (lijst voertuig)");
//// System.out.print(" (zoek voertuig)");
//// System.out.println(" (back)");
////
//// String menu = sr.unasat.Helper.scanstring();
//// switch (menu.toLowerCase()) {
//// case "add" -> {
//// nieuwVoertuig();
//// subMenuVoertuig();
//// }
//// case "delete" -> {
//// deleteVoertuig();
//// subMenuVoertuig();
//// }
//// case "lijst voertuig" -> {
//// lijstVoertuig();
//// subMenuVoertuig();
//// }
//// case "zoek voertuig" -> {
//// zoekOneVoertuig();
//// subMenuVoertuig();
//// }
//// case "back" -> menu();
//// default -> {
//// System.out.println("Invalid input. Try again.");
//// subMenuVoertuig();
//// }
//// }
//// }
//
// public void subMenuProduct() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst product)");
// System.out.print(" (update prijs)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek product)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwProduct();
// subMenuProduct();
// }
// case "delete" -> {
// deleteProduct();
// subMenuProduct();
// }
// case "lijst product" -> {
// lijstProduct();
// subMenuProduct();
// }
// case "update prijs" -> {
// updatePrijs();
// subMenuKlant();
// }
// case "update adres" -> {
// updateAdres();
// subMenuProduct();
// }
// case "zoek product" -> {
// zoekOneProduct();
// subMenuProduct();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuProduct();
// }
// }
// }
//
// public void subMenuLevering() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst levering)");
// System.out.print(" (update status)");
// System.out.print(" (update chauffeur)");
// System.out.print(" (zoek levering)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwLevering();
// subMenuLevering();
// }
// case "delete" -> {
// deleteLevering();
// subMenuLevering();
// }
// case "lijst levering" -> {
// lijstLevering();
// subMenuLevering();
// }
// case "update status" -> {
// updateStatus();
// subMenuLevering();
// }
// case "update chauffeur" -> {
// updateLeveringChauffeur();
// subMenuLevering();
// }
// case "zoek levering" -> {
// zoekLevering();
// subMenuLevering();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuLevering();
// }
// }
// }
//
// public void subMenuKlant() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Klant)");
// System.out.print(" (update Telefoon)");
// System.out.print(" (update naam)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek klant)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwKlant();
// subMenuKlant();
// }
// case "delete" -> {
// deleteKlant();
// subMenuKlant();
// }
// case "lijst klant" -> {
// lijstKlanten();
// subMenuKlant();
// }
// case "update telefoon" -> {
// updateKlantTelefoon();
// subMenuKlant();
// }
// case "update naam" -> {
// updateKlantNaam();
// subMenuKlant();
// }
// case "update adres" -> {
// updateKlantAdres();
// subMenuKlant();
// }
// case "zoek klant" -> {
// zoekOneKlant();
// subMenuKlant();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuKlant();
// }
// }
// }
//
// public void subMenuBestelling() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Bestelling)");
// System.out.print(" (lijst Bestelling producten)");
// System.out.print(" (update leveringsdatum)");
// System.out.print(" (zoek Bestelling)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwBestelling();
// subMenuBestelling();
// }
// case "delete" -> {
// deleteBestelling();
// subMenuBestelling();
// }
// case "lijst bestelling" -> {
// lijstBestelling();
// subMenuBestelling();
// }
// case "update leveringsdatum" -> {
// updateLeveringDatum();
// subMenuBestelling();
// }
// case "bestelling producten" -> {
// lijstBestellingProducten();
// subMenuBestelling();
// }
// case "zoek bestelling" -> {
// zoekOneBestelling();
// subMenuBestelling();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuBestelling();
// }
// }
// }
//
// public void subMenuChauffeur() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Chauffeur)");
// System.out.print(" (update naam)");
// System.out.print(" (update telefoon)");
// System.out.print(" (zoek chauffeur bij naam)");
// System.out.print(" (zoek chauffeur bij id)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwChauffeur();
// subMenuChauffeur();
// }
// case "delete" -> {
// deleteChauffeur();
// subMenuChauffeur();
// }
// case "lijst chauffeur" -> {
// lijstChauffeur();
// subMenuChauffeur();
// }
// case "update naam" -> {
// updateChauffeurNaam();
// subMenuChauffeur();
// }
// case "update telefoon" -> {
// updateChauffeurTelefoon();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij naam" -> {
// zoekChauffeurBijNaam();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij id" -> {
// zoekChauffeurBijId();
// subMenuChauffeur();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuChauffeur();
// }
// }
// }
//
// public void menu() {
// menuOptions();
// System.out.println();
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toUpperCase()) {
// case "K" -> subMenuKlant();
// case "B" -> subMenuBestelling();
// case "C" -> subMenuChauffeur();
// case "L" -> subMenuLevering();
// case "V" -> subMenuVoertuig();
// case "P" -> subMenuProduct();
// case "EXIT" -> System.out.println("End Of Program");
// default -> {
// System.out.println("Invalid input. Try again.");
// menu();
// }
// }
// }
//
//}
|
170675_13 | package com.tux.dto;
/**
*
* @author Mike
*/
public class ContpaqFolioDigital {
private java.math.BigDecimal cidfoldig;
private java.math.BigDecimal ciddoctode;
private java.math.BigDecimal cidcptodoc;
private java.math.BigDecimal ciddocto;
private java.math.BigDecimal ciddocaldi;
private java.math.BigDecimal cidfirmarl;
private java.math.BigDecimal cnoorden;
private java.lang.String cserie;
private java.math.BigDecimal cfolio;
private java.math.BigDecimal cnoaprob;
private java.sql.Date cfecaprob;
private java.math.BigDecimal cestado;
private java.math.BigDecimal centregado;
private java.sql.Date cfechaemi;
private java.lang.String choraemi;
private java.lang.String cemail;
private java.lang.String carchdidis;
private java.math.BigDecimal cidcptoori;
private java.sql.Date cfechacanc;
private java.lang.String choracanc;
private java.math.BigDecimal cestrad;
private java.lang.String ccadpedi;
private java.lang.String carchcbb;
private java.sql.Date cinivig;
private java.sql.Date cfinvig;
private java.lang.String ctipo;
private java.lang.String cserierec;
private java.math.BigDecimal cfoliorec;
private java.lang.String crfc;
private java.lang.String crazon;
private java.math.BigDecimal csisorigen;
private java.math.BigDecimal cejerpol;
private java.math.BigDecimal cperpol;
private java.math.BigDecimal ctipopol;
private java.math.BigDecimal cnumpol;
private java.lang.String ctipoldesc;
private java.lang.Double ctotal;
private java.lang.String caliasbdct;
private java.math.BigDecimal ccfdprueba;
private java.lang.String cdesestado;
private java.math.BigDecimal cpagadoban;
private java.lang.String cdespagban;
private java.lang.String creferen01;
private java.lang.String cobserva01;
private java.lang.String ccodconcba;
private java.lang.String cdesconcba;
private java.lang.String cnumctaban;
private java.lang.String cfolioban;
private java.math.BigDecimal ciddocdeba;
private java.lang.String cusuautban;
private java.lang.String cuuid;
private java.lang.String cusuban01;
private java.math.BigDecimal cautusba01;
private java.lang.String cusuban02;
private java.math.BigDecimal cautusba02;
private java.lang.String cusuban03;
private java.math.BigDecimal cautusba03;
private java.lang.String cdescaut01;
private java.lang.String cdescaut02;
private java.lang.String cdescaut03;
private java.math.BigDecimal cerrorval;
private java.lang.String cacusecan;
/**
* @return the cidfoldig
*/
public java.math.BigDecimal getCidfoldig() {
return cidfoldig;
}
/**
* @param cidfoldig the cidfoldig to set
*/
public void setCidfoldig(java.math.BigDecimal cidfoldig) {
this.cidfoldig = cidfoldig;
}
/**
* @return the ciddoctode
*/
public java.math.BigDecimal getCiddoctode() {
return ciddoctode;
}
/**
* @param ciddoctode the ciddoctode to set
*/
public void setCiddoctode(java.math.BigDecimal ciddoctode) {
this.ciddoctode = ciddoctode;
}
/**
* @return the cidcptodoc
*/
public java.math.BigDecimal getCidcptodoc() {
return cidcptodoc;
}
/**
* @param cidcptodoc the cidcptodoc to set
*/
public void setCidcptodoc(java.math.BigDecimal cidcptodoc) {
this.cidcptodoc = cidcptodoc;
}
/**
* @return the ciddocto
*/
public java.math.BigDecimal getCiddocto() {
return ciddocto;
}
/**
* @param ciddocto the ciddocto to set
*/
public void setCiddocto(java.math.BigDecimal ciddocto) {
this.ciddocto = ciddocto;
}
/**
* @return the ciddocaldi
*/
public java.math.BigDecimal getCiddocaldi() {
return ciddocaldi;
}
/**
* @param ciddocaldi the ciddocaldi to set
*/
public void setCiddocaldi(java.math.BigDecimal ciddocaldi) {
this.ciddocaldi = ciddocaldi;
}
/**
* @return the cidfirmarl
*/
public java.math.BigDecimal getCidfirmarl() {
return cidfirmarl;
}
/**
* @param cidfirmarl the cidfirmarl to set
*/
public void setCidfirmarl(java.math.BigDecimal cidfirmarl) {
this.cidfirmarl = cidfirmarl;
}
/**
* @return the cnoorden
*/
public java.math.BigDecimal getCnoorden() {
return cnoorden;
}
/**
* @param cnoorden the cnoorden to set
*/
public void setCnoorden(java.math.BigDecimal cnoorden) {
this.cnoorden = cnoorden;
}
/**
* @return the cserie
*/
public java.lang.String getCserie() {
return cserie;
}
/**
* @param cserie the cserie to set
*/
public void setCserie(java.lang.String cserie) {
this.cserie = cserie;
}
/**
* @return the cfolio
*/
public java.math.BigDecimal getCfolio() {
return cfolio;
}
/**
* @param cfolio the cfolio to set
*/
public void setCfolio(java.math.BigDecimal cfolio) {
this.cfolio = cfolio;
}
/**
* @return the cnoaprob
*/
public java.math.BigDecimal getCnoaprob() {
return cnoaprob;
}
/**
* @param cnoaprob the cnoaprob to set
*/
public void setCnoaprob(java.math.BigDecimal cnoaprob) {
this.cnoaprob = cnoaprob;
}
/**
* @return the cfecaprob
*/
public java.sql.Date getCfecaprob() {
return cfecaprob;
}
/**
* @param cfecaprob the cfecaprob to set
*/
public void setCfecaprob(java.sql.Date cfecaprob) {
this.cfecaprob = cfecaprob;
}
/**
* @return the cestado
*/
public java.math.BigDecimal getCestado() {
return cestado;
}
/**
* @param cestado the cestado to set
*/
public void setCestado(java.math.BigDecimal cestado) {
this.cestado = cestado;
}
/**
* @return the centregado
*/
public java.math.BigDecimal getCentregado() {
return centregado;
}
/**
* @param centregado the centregado to set
*/
public void setCentregado(java.math.BigDecimal centregado) {
this.centregado = centregado;
}
/**
* @return the cfechaemi
*/
public java.sql.Date getCfechaemi() {
return cfechaemi;
}
/**
* @param cfechaemi the cfechaemi to set
*/
public void setCfechaemi(java.sql.Date cfechaemi) {
this.cfechaemi = cfechaemi;
}
/**
* @return the choraemi
*/
public java.lang.String getChoraemi() {
return choraemi;
}
/**
* @param choraemi the choraemi to set
*/
public void setChoraemi(java.lang.String choraemi) {
this.choraemi = choraemi;
}
/**
* @return the cemail
*/
public java.lang.String getCemail() {
return cemail;
}
/**
* @param cemail the cemail to set
*/
public void setCemail(java.lang.String cemail) {
this.cemail = cemail;
}
/**
* @return the carchdidis
*/
public java.lang.String getCarchdidis() {
return carchdidis;
}
/**
* @param carchdidis the carchdidis to set
*/
public void setCarchdidis(java.lang.String carchdidis) {
this.carchdidis = carchdidis;
}
/**
* @return the cidcptoori
*/
public java.math.BigDecimal getCidcptoori() {
return cidcptoori;
}
/**
* @param cidcptoori the cidcptoori to set
*/
public void setCidcptoori(java.math.BigDecimal cidcptoori) {
this.cidcptoori = cidcptoori;
}
/**
* @return the cfechacanc
*/
public java.sql.Date getCfechacanc() {
return cfechacanc;
}
/**
* @param cfechacanc the cfechacanc to set
*/
public void setCfechacanc(java.sql.Date cfechacanc) {
this.cfechacanc = cfechacanc;
}
/**
* @return the choracanc
*/
public java.lang.String getChoracanc() {
return choracanc;
}
/**
* @param choracanc the choracanc to set
*/
public void setChoracanc(java.lang.String choracanc) {
this.choracanc = choracanc;
}
/**
* @return the cestrad
*/
public java.math.BigDecimal getCestrad() {
return cestrad;
}
/**
* @param cestrad the cestrad to set
*/
public void setCestrad(java.math.BigDecimal cestrad) {
this.cestrad = cestrad;
}
/**
* @return the ccadpedi
*/
public java.lang.String getCcadpedi() {
return ccadpedi;
}
/**
* @param ccadpedi the ccadpedi to set
*/
public void setCcadpedi(java.lang.String ccadpedi) {
this.ccadpedi = ccadpedi;
}
/**
* @return the carchcbb
*/
public java.lang.String getCarchcbb() {
return carchcbb;
}
/**
* @param carchcbb the carchcbb to set
*/
public void setCarchcbb(java.lang.String carchcbb) {
this.carchcbb = carchcbb;
}
/**
* @return the cinivig
*/
public java.sql.Date getCinivig() {
return cinivig;
}
/**
* @param cinivig the cinivig to set
*/
public void setCinivig(java.sql.Date cinivig) {
this.cinivig = cinivig;
}
/**
* @return the cfinvig
*/
public java.sql.Date getCfinvig() {
return cfinvig;
}
/**
* @param cfinvig the cfinvig to set
*/
public void setCfinvig(java.sql.Date cfinvig) {
this.cfinvig = cfinvig;
}
/**
* @return the ctipo
*/
public java.lang.String getCtipo() {
return ctipo;
}
/**
* @param ctipo the ctipo to set
*/
public void setCtipo(java.lang.String ctipo) {
this.ctipo = ctipo;
}
/**
* @return the cserierec
*/
public java.lang.String getCserierec() {
return cserierec;
}
/**
* @param cserierec the cserierec to set
*/
public void setCserierec(java.lang.String cserierec) {
this.cserierec = cserierec;
}
/**
* @return the cfoliorec
*/
public java.math.BigDecimal getCfoliorec() {
return cfoliorec;
}
/**
* @param cfoliorec the cfoliorec to set
*/
public void setCfoliorec(java.math.BigDecimal cfoliorec) {
this.cfoliorec = cfoliorec;
}
/**
* @return the crfc
*/
public java.lang.String getCrfc() {
return crfc;
}
/**
* @param crfc the crfc to set
*/
public void setCrfc(java.lang.String crfc) {
this.crfc = crfc;
}
/**
* @return the crazon
*/
public java.lang.String getCrazon() {
return crazon;
}
/**
* @param crazon the crazon to set
*/
public void setCrazon(java.lang.String crazon) {
this.crazon = crazon;
}
/**
* @return the csisorigen
*/
public java.math.BigDecimal getCsisorigen() {
return csisorigen;
}
/**
* @param csisorigen the csisorigen to set
*/
public void setCsisorigen(java.math.BigDecimal csisorigen) {
this.csisorigen = csisorigen;
}
/**
* @return the cejerpol
*/
public java.math.BigDecimal getCejerpol() {
return cejerpol;
}
/**
* @param cejerpol the cejerpol to set
*/
public void setCejerpol(java.math.BigDecimal cejerpol) {
this.cejerpol = cejerpol;
}
/**
* @return the cperpol
*/
public java.math.BigDecimal getCperpol() {
return cperpol;
}
/**
* @param cperpol the cperpol to set
*/
public void setCperpol(java.math.BigDecimal cperpol) {
this.cperpol = cperpol;
}
/**
* @return the ctipopol
*/
public java.math.BigDecimal getCtipopol() {
return ctipopol;
}
/**
* @param ctipopol the ctipopol to set
*/
public void setCtipopol(java.math.BigDecimal ctipopol) {
this.ctipopol = ctipopol;
}
/**
* @return the cnumpol
*/
public java.math.BigDecimal getCnumpol() {
return cnumpol;
}
/**
* @param cnumpol the cnumpol to set
*/
public void setCnumpol(java.math.BigDecimal cnumpol) {
this.cnumpol = cnumpol;
}
/**
* @return the ctipoldesc
*/
public java.lang.String getCtipoldesc() {
return ctipoldesc;
}
/**
* @param ctipoldesc the ctipoldesc to set
*/
public void setCtipoldesc(java.lang.String ctipoldesc) {
this.ctipoldesc = ctipoldesc;
}
/**
* @return the ctotal
*/
public java.lang.Double getCtotal() {
return ctotal;
}
/**
* @param ctotal the ctotal to set
*/
public void setCtotal(java.lang.Double ctotal) {
this.ctotal = ctotal;
}
/**
* @return the caliasbdct
*/
public java.lang.String getCaliasbdct() {
return caliasbdct;
}
/**
* @param caliasbdct the caliasbdct to set
*/
public void setCaliasbdct(java.lang.String caliasbdct) {
this.caliasbdct = caliasbdct;
}
/**
* @return the ccfdprueba
*/
public java.math.BigDecimal getCcfdprueba() {
return ccfdprueba;
}
/**
* @param ccfdprueba the ccfdprueba to set
*/
public void setCcfdprueba(java.math.BigDecimal ccfdprueba) {
this.ccfdprueba = ccfdprueba;
}
/**
* @return the cdesestado
*/
public java.lang.String getCdesestado() {
return cdesestado;
}
/**
* @param cdesestado the cdesestado to set
*/
public void setCdesestado(java.lang.String cdesestado) {
this.cdesestado = cdesestado;
}
/**
* @return the cpagadoban
*/
public java.math.BigDecimal getCpagadoban() {
return cpagadoban;
}
/**
* @param cpagadoban the cpagadoban to set
*/
public void setCpagadoban(java.math.BigDecimal cpagadoban) {
this.cpagadoban = cpagadoban;
}
/**
* @return the cdespagban
*/
public java.lang.String getCdespagban() {
return cdespagban;
}
/**
* @param cdespagban the cdespagban to set
*/
public void setCdespagban(java.lang.String cdespagban) {
this.cdespagban = cdespagban;
}
/**
* @return the creferen01
*/
public java.lang.String getCreferen01() {
return creferen01;
}
/**
* @param creferen01 the creferen01 to set
*/
public void setCreferen01(java.lang.String creferen01) {
this.creferen01 = creferen01;
}
/**
* @return the cobserva01
*/
public java.lang.String getCobserva01() {
return cobserva01;
}
/**
* @param cobserva01 the cobserva01 to set
*/
public void setCobserva01(java.lang.String cobserva01) {
this.cobserva01 = cobserva01;
}
/**
* @return the ccodconcba
*/
public java.lang.String getCcodconcba() {
return ccodconcba;
}
/**
* @param ccodconcba the ccodconcba to set
*/
public void setCcodconcba(java.lang.String ccodconcba) {
this.ccodconcba = ccodconcba;
}
/**
* @return the cdesconcba
*/
public java.lang.String getCdesconcba() {
return cdesconcba;
}
/**
* @param cdesconcba the cdesconcba to set
*/
public void setCdesconcba(java.lang.String cdesconcba) {
this.cdesconcba = cdesconcba;
}
/**
* @return the cnumctaban
*/
public java.lang.String getCnumctaban() {
return cnumctaban;
}
/**
* @param cnumctaban the cnumctaban to set
*/
public void setCnumctaban(java.lang.String cnumctaban) {
this.cnumctaban = cnumctaban;
}
/**
* @return the cfolioban
*/
public java.lang.String getCfolioban() {
return cfolioban;
}
/**
* @param cfolioban the cfolioban to set
*/
public void setCfolioban(java.lang.String cfolioban) {
this.cfolioban = cfolioban;
}
/**
* @return the ciddocdeba
*/
public java.math.BigDecimal getCiddocdeba() {
return ciddocdeba;
}
/**
* @param ciddocdeba the ciddocdeba to set
*/
public void setCiddocdeba(java.math.BigDecimal ciddocdeba) {
this.ciddocdeba = ciddocdeba;
}
/**
* @return the cusuautban
*/
public java.lang.String getCusuautban() {
return cusuautban;
}
/**
* @param cusuautban the cusuautban to set
*/
public void setCusuautban(java.lang.String cusuautban) {
this.cusuautban = cusuautban;
}
/**
* @return the cuuid
*/
public java.lang.String getCuuid() {
return cuuid;
}
/**
* @param cuuid the cuuid to set
*/
public void setCuuid(java.lang.String cuuid) {
this.cuuid = cuuid;
}
/**
* @return the cusuban01
*/
public java.lang.String getCusuban01() {
return cusuban01;
}
/**
* @param cusuban01 the cusuban01 to set
*/
public void setCusuban01(java.lang.String cusuban01) {
this.cusuban01 = cusuban01;
}
/**
* @return the cautusba01
*/
public java.math.BigDecimal getCautusba01() {
return cautusba01;
}
/**
* @param cautusba01 the cautusba01 to set
*/
public void setCautusba01(java.math.BigDecimal cautusba01) {
this.cautusba01 = cautusba01;
}
/**
* @return the cusuban02
*/
public java.lang.String getCusuban02() {
return cusuban02;
}
/**
* @param cusuban02 the cusuban02 to set
*/
public void setCusuban02(java.lang.String cusuban02) {
this.cusuban02 = cusuban02;
}
/**
* @return the cautusba02
*/
public java.math.BigDecimal getCautusba02() {
return cautusba02;
}
/**
* @param cautusba02 the cautusba02 to set
*/
public void setCautusba02(java.math.BigDecimal cautusba02) {
this.cautusba02 = cautusba02;
}
/**
* @return the cusuban03
*/
public java.lang.String getCusuban03() {
return cusuban03;
}
/**
* @param cusuban03 the cusuban03 to set
*/
public void setCusuban03(java.lang.String cusuban03) {
this.cusuban03 = cusuban03;
}
/**
* @return the cautusba03
*/
public java.math.BigDecimal getCautusba03() {
return cautusba03;
}
/**
* @param cautusba03 the cautusba03 to set
*/
public void setCautusba03(java.math.BigDecimal cautusba03) {
this.cautusba03 = cautusba03;
}
/**
* @return the cdescaut01
*/
public java.lang.String getCdescaut01() {
return cdescaut01;
}
/**
* @param cdescaut01 the cdescaut01 to set
*/
public void setCdescaut01(java.lang.String cdescaut01) {
this.cdescaut01 = cdescaut01;
}
/**
* @return the cdescaut02
*/
public java.lang.String getCdescaut02() {
return cdescaut02;
}
/**
* @param cdescaut02 the cdescaut02 to set
*/
public void setCdescaut02(java.lang.String cdescaut02) {
this.cdescaut02 = cdescaut02;
}
/**
* @return the cdescaut03
*/
public java.lang.String getCdescaut03() {
return cdescaut03;
}
/**
* @param cdescaut03 the cdescaut03 to set
*/
public void setCdescaut03(java.lang.String cdescaut03) {
this.cdescaut03 = cdescaut03;
}
/**
* @return the cerrorval
*/
public java.math.BigDecimal getCerrorval() {
return cerrorval;
}
/**
* @param cerrorval the cerrorval to set
*/
public void setCerrorval(java.math.BigDecimal cerrorval) {
this.cerrorval = cerrorval;
}
/**
* @return the cacusecan
*/
public java.lang.String getCacusecan() {
return cacusecan;
}
/**
* @param cacusecan the cacusecan to set
*/
public void setCacusecan(java.lang.String cacusecan) {
this.cacusecan = cacusecan;
}
}
| Miklex85/transportesTuxpanWS | src/java/com/tux/dto/ContpaqFolioDigital.java | 7,951 | /**
* @return the cnoorden
*/ | block_comment | nl | package com.tux.dto;
/**
*
* @author Mike
*/
public class ContpaqFolioDigital {
private java.math.BigDecimal cidfoldig;
private java.math.BigDecimal ciddoctode;
private java.math.BigDecimal cidcptodoc;
private java.math.BigDecimal ciddocto;
private java.math.BigDecimal ciddocaldi;
private java.math.BigDecimal cidfirmarl;
private java.math.BigDecimal cnoorden;
private java.lang.String cserie;
private java.math.BigDecimal cfolio;
private java.math.BigDecimal cnoaprob;
private java.sql.Date cfecaprob;
private java.math.BigDecimal cestado;
private java.math.BigDecimal centregado;
private java.sql.Date cfechaemi;
private java.lang.String choraemi;
private java.lang.String cemail;
private java.lang.String carchdidis;
private java.math.BigDecimal cidcptoori;
private java.sql.Date cfechacanc;
private java.lang.String choracanc;
private java.math.BigDecimal cestrad;
private java.lang.String ccadpedi;
private java.lang.String carchcbb;
private java.sql.Date cinivig;
private java.sql.Date cfinvig;
private java.lang.String ctipo;
private java.lang.String cserierec;
private java.math.BigDecimal cfoliorec;
private java.lang.String crfc;
private java.lang.String crazon;
private java.math.BigDecimal csisorigen;
private java.math.BigDecimal cejerpol;
private java.math.BigDecimal cperpol;
private java.math.BigDecimal ctipopol;
private java.math.BigDecimal cnumpol;
private java.lang.String ctipoldesc;
private java.lang.Double ctotal;
private java.lang.String caliasbdct;
private java.math.BigDecimal ccfdprueba;
private java.lang.String cdesestado;
private java.math.BigDecimal cpagadoban;
private java.lang.String cdespagban;
private java.lang.String creferen01;
private java.lang.String cobserva01;
private java.lang.String ccodconcba;
private java.lang.String cdesconcba;
private java.lang.String cnumctaban;
private java.lang.String cfolioban;
private java.math.BigDecimal ciddocdeba;
private java.lang.String cusuautban;
private java.lang.String cuuid;
private java.lang.String cusuban01;
private java.math.BigDecimal cautusba01;
private java.lang.String cusuban02;
private java.math.BigDecimal cautusba02;
private java.lang.String cusuban03;
private java.math.BigDecimal cautusba03;
private java.lang.String cdescaut01;
private java.lang.String cdescaut02;
private java.lang.String cdescaut03;
private java.math.BigDecimal cerrorval;
private java.lang.String cacusecan;
/**
* @return the cidfoldig
*/
public java.math.BigDecimal getCidfoldig() {
return cidfoldig;
}
/**
* @param cidfoldig the cidfoldig to set
*/
public void setCidfoldig(java.math.BigDecimal cidfoldig) {
this.cidfoldig = cidfoldig;
}
/**
* @return the ciddoctode
*/
public java.math.BigDecimal getCiddoctode() {
return ciddoctode;
}
/**
* @param ciddoctode the ciddoctode to set
*/
public void setCiddoctode(java.math.BigDecimal ciddoctode) {
this.ciddoctode = ciddoctode;
}
/**
* @return the cidcptodoc
*/
public java.math.BigDecimal getCidcptodoc() {
return cidcptodoc;
}
/**
* @param cidcptodoc the cidcptodoc to set
*/
public void setCidcptodoc(java.math.BigDecimal cidcptodoc) {
this.cidcptodoc = cidcptodoc;
}
/**
* @return the ciddocto
*/
public java.math.BigDecimal getCiddocto() {
return ciddocto;
}
/**
* @param ciddocto the ciddocto to set
*/
public void setCiddocto(java.math.BigDecimal ciddocto) {
this.ciddocto = ciddocto;
}
/**
* @return the ciddocaldi
*/
public java.math.BigDecimal getCiddocaldi() {
return ciddocaldi;
}
/**
* @param ciddocaldi the ciddocaldi to set
*/
public void setCiddocaldi(java.math.BigDecimal ciddocaldi) {
this.ciddocaldi = ciddocaldi;
}
/**
* @return the cidfirmarl
*/
public java.math.BigDecimal getCidfirmarl() {
return cidfirmarl;
}
/**
* @param cidfirmarl the cidfirmarl to set
*/
public void setCidfirmarl(java.math.BigDecimal cidfirmarl) {
this.cidfirmarl = cidfirmarl;
}
/**
* @return the cnoorden
<SUF>*/
public java.math.BigDecimal getCnoorden() {
return cnoorden;
}
/**
* @param cnoorden the cnoorden to set
*/
public void setCnoorden(java.math.BigDecimal cnoorden) {
this.cnoorden = cnoorden;
}
/**
* @return the cserie
*/
public java.lang.String getCserie() {
return cserie;
}
/**
* @param cserie the cserie to set
*/
public void setCserie(java.lang.String cserie) {
this.cserie = cserie;
}
/**
* @return the cfolio
*/
public java.math.BigDecimal getCfolio() {
return cfolio;
}
/**
* @param cfolio the cfolio to set
*/
public void setCfolio(java.math.BigDecimal cfolio) {
this.cfolio = cfolio;
}
/**
* @return the cnoaprob
*/
public java.math.BigDecimal getCnoaprob() {
return cnoaprob;
}
/**
* @param cnoaprob the cnoaprob to set
*/
public void setCnoaprob(java.math.BigDecimal cnoaprob) {
this.cnoaprob = cnoaprob;
}
/**
* @return the cfecaprob
*/
public java.sql.Date getCfecaprob() {
return cfecaprob;
}
/**
* @param cfecaprob the cfecaprob to set
*/
public void setCfecaprob(java.sql.Date cfecaprob) {
this.cfecaprob = cfecaprob;
}
/**
* @return the cestado
*/
public java.math.BigDecimal getCestado() {
return cestado;
}
/**
* @param cestado the cestado to set
*/
public void setCestado(java.math.BigDecimal cestado) {
this.cestado = cestado;
}
/**
* @return the centregado
*/
public java.math.BigDecimal getCentregado() {
return centregado;
}
/**
* @param centregado the centregado to set
*/
public void setCentregado(java.math.BigDecimal centregado) {
this.centregado = centregado;
}
/**
* @return the cfechaemi
*/
public java.sql.Date getCfechaemi() {
return cfechaemi;
}
/**
* @param cfechaemi the cfechaemi to set
*/
public void setCfechaemi(java.sql.Date cfechaemi) {
this.cfechaemi = cfechaemi;
}
/**
* @return the choraemi
*/
public java.lang.String getChoraemi() {
return choraemi;
}
/**
* @param choraemi the choraemi to set
*/
public void setChoraemi(java.lang.String choraemi) {
this.choraemi = choraemi;
}
/**
* @return the cemail
*/
public java.lang.String getCemail() {
return cemail;
}
/**
* @param cemail the cemail to set
*/
public void setCemail(java.lang.String cemail) {
this.cemail = cemail;
}
/**
* @return the carchdidis
*/
public java.lang.String getCarchdidis() {
return carchdidis;
}
/**
* @param carchdidis the carchdidis to set
*/
public void setCarchdidis(java.lang.String carchdidis) {
this.carchdidis = carchdidis;
}
/**
* @return the cidcptoori
*/
public java.math.BigDecimal getCidcptoori() {
return cidcptoori;
}
/**
* @param cidcptoori the cidcptoori to set
*/
public void setCidcptoori(java.math.BigDecimal cidcptoori) {
this.cidcptoori = cidcptoori;
}
/**
* @return the cfechacanc
*/
public java.sql.Date getCfechacanc() {
return cfechacanc;
}
/**
* @param cfechacanc the cfechacanc to set
*/
public void setCfechacanc(java.sql.Date cfechacanc) {
this.cfechacanc = cfechacanc;
}
/**
* @return the choracanc
*/
public java.lang.String getChoracanc() {
return choracanc;
}
/**
* @param choracanc the choracanc to set
*/
public void setChoracanc(java.lang.String choracanc) {
this.choracanc = choracanc;
}
/**
* @return the cestrad
*/
public java.math.BigDecimal getCestrad() {
return cestrad;
}
/**
* @param cestrad the cestrad to set
*/
public void setCestrad(java.math.BigDecimal cestrad) {
this.cestrad = cestrad;
}
/**
* @return the ccadpedi
*/
public java.lang.String getCcadpedi() {
return ccadpedi;
}
/**
* @param ccadpedi the ccadpedi to set
*/
public void setCcadpedi(java.lang.String ccadpedi) {
this.ccadpedi = ccadpedi;
}
/**
* @return the carchcbb
*/
public java.lang.String getCarchcbb() {
return carchcbb;
}
/**
* @param carchcbb the carchcbb to set
*/
public void setCarchcbb(java.lang.String carchcbb) {
this.carchcbb = carchcbb;
}
/**
* @return the cinivig
*/
public java.sql.Date getCinivig() {
return cinivig;
}
/**
* @param cinivig the cinivig to set
*/
public void setCinivig(java.sql.Date cinivig) {
this.cinivig = cinivig;
}
/**
* @return the cfinvig
*/
public java.sql.Date getCfinvig() {
return cfinvig;
}
/**
* @param cfinvig the cfinvig to set
*/
public void setCfinvig(java.sql.Date cfinvig) {
this.cfinvig = cfinvig;
}
/**
* @return the ctipo
*/
public java.lang.String getCtipo() {
return ctipo;
}
/**
* @param ctipo the ctipo to set
*/
public void setCtipo(java.lang.String ctipo) {
this.ctipo = ctipo;
}
/**
* @return the cserierec
*/
public java.lang.String getCserierec() {
return cserierec;
}
/**
* @param cserierec the cserierec to set
*/
public void setCserierec(java.lang.String cserierec) {
this.cserierec = cserierec;
}
/**
* @return the cfoliorec
*/
public java.math.BigDecimal getCfoliorec() {
return cfoliorec;
}
/**
* @param cfoliorec the cfoliorec to set
*/
public void setCfoliorec(java.math.BigDecimal cfoliorec) {
this.cfoliorec = cfoliorec;
}
/**
* @return the crfc
*/
public java.lang.String getCrfc() {
return crfc;
}
/**
* @param crfc the crfc to set
*/
public void setCrfc(java.lang.String crfc) {
this.crfc = crfc;
}
/**
* @return the crazon
*/
public java.lang.String getCrazon() {
return crazon;
}
/**
* @param crazon the crazon to set
*/
public void setCrazon(java.lang.String crazon) {
this.crazon = crazon;
}
/**
* @return the csisorigen
*/
public java.math.BigDecimal getCsisorigen() {
return csisorigen;
}
/**
* @param csisorigen the csisorigen to set
*/
public void setCsisorigen(java.math.BigDecimal csisorigen) {
this.csisorigen = csisorigen;
}
/**
* @return the cejerpol
*/
public java.math.BigDecimal getCejerpol() {
return cejerpol;
}
/**
* @param cejerpol the cejerpol to set
*/
public void setCejerpol(java.math.BigDecimal cejerpol) {
this.cejerpol = cejerpol;
}
/**
* @return the cperpol
*/
public java.math.BigDecimal getCperpol() {
return cperpol;
}
/**
* @param cperpol the cperpol to set
*/
public void setCperpol(java.math.BigDecimal cperpol) {
this.cperpol = cperpol;
}
/**
* @return the ctipopol
*/
public java.math.BigDecimal getCtipopol() {
return ctipopol;
}
/**
* @param ctipopol the ctipopol to set
*/
public void setCtipopol(java.math.BigDecimal ctipopol) {
this.ctipopol = ctipopol;
}
/**
* @return the cnumpol
*/
public java.math.BigDecimal getCnumpol() {
return cnumpol;
}
/**
* @param cnumpol the cnumpol to set
*/
public void setCnumpol(java.math.BigDecimal cnumpol) {
this.cnumpol = cnumpol;
}
/**
* @return the ctipoldesc
*/
public java.lang.String getCtipoldesc() {
return ctipoldesc;
}
/**
* @param ctipoldesc the ctipoldesc to set
*/
public void setCtipoldesc(java.lang.String ctipoldesc) {
this.ctipoldesc = ctipoldesc;
}
/**
* @return the ctotal
*/
public java.lang.Double getCtotal() {
return ctotal;
}
/**
* @param ctotal the ctotal to set
*/
public void setCtotal(java.lang.Double ctotal) {
this.ctotal = ctotal;
}
/**
* @return the caliasbdct
*/
public java.lang.String getCaliasbdct() {
return caliasbdct;
}
/**
* @param caliasbdct the caliasbdct to set
*/
public void setCaliasbdct(java.lang.String caliasbdct) {
this.caliasbdct = caliasbdct;
}
/**
* @return the ccfdprueba
*/
public java.math.BigDecimal getCcfdprueba() {
return ccfdprueba;
}
/**
* @param ccfdprueba the ccfdprueba to set
*/
public void setCcfdprueba(java.math.BigDecimal ccfdprueba) {
this.ccfdprueba = ccfdprueba;
}
/**
* @return the cdesestado
*/
public java.lang.String getCdesestado() {
return cdesestado;
}
/**
* @param cdesestado the cdesestado to set
*/
public void setCdesestado(java.lang.String cdesestado) {
this.cdesestado = cdesestado;
}
/**
* @return the cpagadoban
*/
public java.math.BigDecimal getCpagadoban() {
return cpagadoban;
}
/**
* @param cpagadoban the cpagadoban to set
*/
public void setCpagadoban(java.math.BigDecimal cpagadoban) {
this.cpagadoban = cpagadoban;
}
/**
* @return the cdespagban
*/
public java.lang.String getCdespagban() {
return cdespagban;
}
/**
* @param cdespagban the cdespagban to set
*/
public void setCdespagban(java.lang.String cdespagban) {
this.cdespagban = cdespagban;
}
/**
* @return the creferen01
*/
public java.lang.String getCreferen01() {
return creferen01;
}
/**
* @param creferen01 the creferen01 to set
*/
public void setCreferen01(java.lang.String creferen01) {
this.creferen01 = creferen01;
}
/**
* @return the cobserva01
*/
public java.lang.String getCobserva01() {
return cobserva01;
}
/**
* @param cobserva01 the cobserva01 to set
*/
public void setCobserva01(java.lang.String cobserva01) {
this.cobserva01 = cobserva01;
}
/**
* @return the ccodconcba
*/
public java.lang.String getCcodconcba() {
return ccodconcba;
}
/**
* @param ccodconcba the ccodconcba to set
*/
public void setCcodconcba(java.lang.String ccodconcba) {
this.ccodconcba = ccodconcba;
}
/**
* @return the cdesconcba
*/
public java.lang.String getCdesconcba() {
return cdesconcba;
}
/**
* @param cdesconcba the cdesconcba to set
*/
public void setCdesconcba(java.lang.String cdesconcba) {
this.cdesconcba = cdesconcba;
}
/**
* @return the cnumctaban
*/
public java.lang.String getCnumctaban() {
return cnumctaban;
}
/**
* @param cnumctaban the cnumctaban to set
*/
public void setCnumctaban(java.lang.String cnumctaban) {
this.cnumctaban = cnumctaban;
}
/**
* @return the cfolioban
*/
public java.lang.String getCfolioban() {
return cfolioban;
}
/**
* @param cfolioban the cfolioban to set
*/
public void setCfolioban(java.lang.String cfolioban) {
this.cfolioban = cfolioban;
}
/**
* @return the ciddocdeba
*/
public java.math.BigDecimal getCiddocdeba() {
return ciddocdeba;
}
/**
* @param ciddocdeba the ciddocdeba to set
*/
public void setCiddocdeba(java.math.BigDecimal ciddocdeba) {
this.ciddocdeba = ciddocdeba;
}
/**
* @return the cusuautban
*/
public java.lang.String getCusuautban() {
return cusuautban;
}
/**
* @param cusuautban the cusuautban to set
*/
public void setCusuautban(java.lang.String cusuautban) {
this.cusuautban = cusuautban;
}
/**
* @return the cuuid
*/
public java.lang.String getCuuid() {
return cuuid;
}
/**
* @param cuuid the cuuid to set
*/
public void setCuuid(java.lang.String cuuid) {
this.cuuid = cuuid;
}
/**
* @return the cusuban01
*/
public java.lang.String getCusuban01() {
return cusuban01;
}
/**
* @param cusuban01 the cusuban01 to set
*/
public void setCusuban01(java.lang.String cusuban01) {
this.cusuban01 = cusuban01;
}
/**
* @return the cautusba01
*/
public java.math.BigDecimal getCautusba01() {
return cautusba01;
}
/**
* @param cautusba01 the cautusba01 to set
*/
public void setCautusba01(java.math.BigDecimal cautusba01) {
this.cautusba01 = cautusba01;
}
/**
* @return the cusuban02
*/
public java.lang.String getCusuban02() {
return cusuban02;
}
/**
* @param cusuban02 the cusuban02 to set
*/
public void setCusuban02(java.lang.String cusuban02) {
this.cusuban02 = cusuban02;
}
/**
* @return the cautusba02
*/
public java.math.BigDecimal getCautusba02() {
return cautusba02;
}
/**
* @param cautusba02 the cautusba02 to set
*/
public void setCautusba02(java.math.BigDecimal cautusba02) {
this.cautusba02 = cautusba02;
}
/**
* @return the cusuban03
*/
public java.lang.String getCusuban03() {
return cusuban03;
}
/**
* @param cusuban03 the cusuban03 to set
*/
public void setCusuban03(java.lang.String cusuban03) {
this.cusuban03 = cusuban03;
}
/**
* @return the cautusba03
*/
public java.math.BigDecimal getCautusba03() {
return cautusba03;
}
/**
* @param cautusba03 the cautusba03 to set
*/
public void setCautusba03(java.math.BigDecimal cautusba03) {
this.cautusba03 = cautusba03;
}
/**
* @return the cdescaut01
*/
public java.lang.String getCdescaut01() {
return cdescaut01;
}
/**
* @param cdescaut01 the cdescaut01 to set
*/
public void setCdescaut01(java.lang.String cdescaut01) {
this.cdescaut01 = cdescaut01;
}
/**
* @return the cdescaut02
*/
public java.lang.String getCdescaut02() {
return cdescaut02;
}
/**
* @param cdescaut02 the cdescaut02 to set
*/
public void setCdescaut02(java.lang.String cdescaut02) {
this.cdescaut02 = cdescaut02;
}
/**
* @return the cdescaut03
*/
public java.lang.String getCdescaut03() {
return cdescaut03;
}
/**
* @param cdescaut03 the cdescaut03 to set
*/
public void setCdescaut03(java.lang.String cdescaut03) {
this.cdescaut03 = cdescaut03;
}
/**
* @return the cerrorval
*/
public java.math.BigDecimal getCerrorval() {
return cerrorval;
}
/**
* @param cerrorval the cerrorval to set
*/
public void setCerrorval(java.math.BigDecimal cerrorval) {
this.cerrorval = cerrorval;
}
/**
* @return the cacusecan
*/
public java.lang.String getCacusecan() {
return cacusecan;
}
/**
* @param cacusecan the cacusecan to set
*/
public void setCacusecan(java.lang.String cacusecan) {
this.cacusecan = cacusecan;
}
}
|
7486_0 | package InleverOpdrachten;
public class maincalcu {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 9)); // deze doet +
System.out.println(calc.subtract(8, 3)); // deze doet -
System.out.println(calc.multiply(4, 4)); // deze doet vermenigvuldigen dus x
System.out.println(calc.devide(25, 5)); // deze doet delen door :
System.out.println(calc.square(7)); // Dit vermenigvuldigd zichzelf meerdere keren zoals dus bijvoorbeeld als je 3.3 hebt doe je 3+3+3
System.out.println(calc.exponentiation(7, 7)); // machten woorden gebruikt
}
} | Milanvanderburgh/Rekenmachine-Opdracht | InleverOpdrachten/maincalcu.java | 249 | // deze doet +
| line_comment | nl | package InleverOpdrachten;
public class maincalcu {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 9)); // deze doet<SUF>
System.out.println(calc.subtract(8, 3)); // deze doet -
System.out.println(calc.multiply(4, 4)); // deze doet vermenigvuldigen dus x
System.out.println(calc.devide(25, 5)); // deze doet delen door :
System.out.println(calc.square(7)); // Dit vermenigvuldigd zichzelf meerdere keren zoals dus bijvoorbeeld als je 3.3 hebt doe je 3+3+3
System.out.println(calc.exponentiation(7, 7)); // machten woorden gebruikt
}
} |
19079_70 | package KBS_ICTM2n4;
//dit maakt de verbinding tussen de client en de servers
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
public class Serverconnection {
// Wanneer de makeConnectionWithServer-functie wordt aangeroepen, wordt de
// sessie die daarin tot stand komt in dit Session-object opgeslagen
// Dit object wordt weer op null gezet in de closeConnectionWithServer-functie.
public Session session;
// Deze functie poogt een session met het opgegeven IP-adres op te slaan in het
// bovenstaande Session-object "session",
// en geeft true terug als dit lukt, en false als dit niet lukt.
public boolean makeConnectionWithServer(String destinationIP, String username, String password) {
// Dit poortnummer wordt gebruikt om met SSH in te loggen.
int port = 3389;
try {
// We maken een nieuw Java Secure Channel-object aan (JSch), en starten hier vervolgens een sessie mee.
JSch jsch = new JSch();
session = jsch.getSession(username, destinationIP, port);
session.setPassword(password);
try {
session.setTimeout(1000);
} catch (JSchException e1) {
//
}
// (Momenteel controleren we de sleutel van de host niet. Als we een veiligere verbinding willen maken, kunnen StrictHostKeyChecking
// wel activeren, maar dan moeten we de host en sleutel eerst bekendmaken aan het systeem.)
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// Als "session" verbonden is, geven we true terug. Als er een error heeft plaatsgevonden of er geen verbinding is, geven we false terug.
if(session.isConnected()) {
System.out.println("Verbinding is geslaagd.");
return true;
} else {
System.out.println("Het is niet gelukt om een verbinding te maken.");
return false;
}
} catch(Exception e) {
System.out.println("Er is iets misgegaan bij verbinden met de server.");
System.out.println(e);
return false;
}
}
// Deze functie controleert of de sessie een verbinding met de server heeft.
public boolean serverConnected(int i) {
Serverconnection[] serverConnections = MonitoringDialog.getServerConnections();
Serverconnection serverConnection = serverConnections[i];
if(serverConnection.session.isConnected()) {
return true;
} else {
return false;
}
}
// Deze functie geeft een String terug waarin de uptime wordt weergegeven van de server waarmee.
// een SSH-connectie is gemaakt in het static Session-object "session" (in het format "X week(s), X day(s), X hour(s), X minute(s)").
// Als er geen session is geeft het een lege String terug.
public String serverUpTime() {
// Dit SSH-command zal de uptime weergeven.
String command = "uptime -p\nexit\n";
try {
// We maken een Channel-object aan van het type "shell",
// welke we kunnen gebruiken om het command op te geven, en de resulterende output te lezen.
Channel channel = session.openChannel("shell");
// We maken een inputStream aan met de gegevens die we van het command krijgen.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(byteArrayInputStream);
InputStream inputStream = channel.getInputStream();
// Er wordt verbonden met het shell-kanaal.
channel.connect();
// Met de volgende code wordt de inhoud van de inputStream overgeschreven naar een outputStream.
// Eerst maken we een outputStream waarin we de gegevens zullen schrijven,
// en een buffer waarmee we de gegevens van de inputStream overzetten naar de outputStream.
// De read-methode schrijft een deel van de inputStream over naar de buffer (met de lengte van de buffer).
// De lengte van deze overschrijving (een int) wordt vastgesteld als "length". Zolang length groter dan 0 is wordt de buffer overgeschreven
// naar de outputstream met de write-methode (de 0 in deze methode is het begin van het gedeelte in de buffer dat wordt overgeschreven,
// en de hoeveelheid bytes van dit gedeelte is de reeds vastgestelde length).
// Als read niet slaagt geeft deze methode -1 terug. In dat geval, of als het resterende gedeelte 0 is,
// hebben we het einde van de inputStream bereikt, en kunnen we stoppen.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
// Het kanaal wordt weer gesloten.
channel.disconnect();
// De inhoud van outputStream wordt in losse strings geknipt,
// waarbij elke nieuwe regel (na een enter: regex "\\r?\\n") een nieuwe string is in de array genaamd lines.
String[] lines = outputStream.toString("UTF-8").split("\\r?\\n");
String output = null;
// De inhoud die we willen teruggeven staat in de regel die begint met "up ".
for (String line : lines) {
if (line.startsWith("up ")) {
output = line;
}
}
// Als de uptime kleiner dan een minuut is, geeft de uptime -p command geen relevante gegevens.
// Voor het geval dat er "up" zonder spatie staat (en vervolgens niets) stellen we de output handmatig in.
if(output == null) {
output = "<1 minute";
}
// We willen slechts de uptime in woorden teruggeven.
output = output.replace("up ", "");
// Als er toch "up " en vervolgens niets staat, is de output nu gelijk aan "". Ook hier stellen we de output handmatig in.
if(output.equals("")) {
output = "<1 minute";
}
return output;
// Als er iets mis is gegaan, geven we een lege String terug.
} catch (Exception e) {
System.out.println("Er is iets misgegaan bij het achterhalen van de uptime.");
return "";
}
}
// Deze functie geeft een String terug, die het percentage van het CPU dat in gebruik is weergeeft.
public String serverCpuUsed() {
// Dit SSH-command zal informatie over het CPU-gebruik weergeven.
String command = "top\nq\nexit";
try {
// We maken een Channel-object aan van het type "shell",
// welke we kunnen gebruiken om het command op te geven, en de resulterende output te lezen.
Channel channel = session.openChannel("shell");
// We maken een inputStream aan met de gegevens die we van het command krijgen.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(byteArrayInputStream);
InputStream inputStream = channel.getInputStream();
// Er wordt verbonden met het shell-kanaal.
channel.connect();
// Met de volgende code wordt de inhoud van de inputStream overgeschreven naar een outputStream.
// Eerst maken we een outputStream waarin we de gegevens zullen schrijven,
// en een buffer waarmee we de gegevens van de inputStream overzetten naar de outputStream.
// De read-methode schrijft een deel van de inputStream over naar de buffer (met de lengte van de buffer).
// De lengte van deze overschrijving (een int) wordt vastgesteld als "length". Elke loop schrijven we deze lengte aan buffer over in de outputStream.
// Aangezien het "top"-command blijft updaten, wordt de inputstream steeds langer, en kunnen we niet bytes blijven bijschrijven tot het einde.
// Als we de outputStream de String "KiB Mem" bevat, hebben we de informatie die we nodig hebben,
// en gebruiken we "break" om de while-loop te stoppen.
// (Voor het geval dat kunnen we ook stoppen als de totale output een bepaalde lengte heeft bereikt, maar die controle
// levert misschien vertraging op.)
// (Kan waarschijnlijk efficiënter en netter).
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while (true) {
length = inputStream.read(buffer);
outputStream.write(buffer, 0, length);
if(outputStream.toString().contains("KiB Mem")) {
break;
}
}
// Het kanaal wordt weer gesloten.
channel.disconnect();
// De inhoud van outputStream wordt in losse strings geknipt,
// waarbij elke nieuwe regel (na een enter: regex "\\r?\\n") een nieuwe string is in de array genaamd lines.
String[] lines = outputStream.toString().split("\\r?\\n");
// De regel die begint met "%Cpu(s)" bevat de informatie die we nodig hebben.
String relevantLine = null;
for (String line : lines) {
if (line.startsWith("%Cpu(s)")) {
relevantLine = line;
}
}
// We splitsen deze regel vervolgens weer op bij elke komma.
String[] splitLine = relevantLine.split(",");
String idleString = null;
// Het stukje dat we willen gebruiken om het percentage van het CPU dat in gebruik is te berekenen, staat in het stukje
// met "id". (Dit stukje geeft het percentage aan dat juist niet in gebruik is.)
for (String lineContent : splitLine) {
if(lineContent.contains("id")) {
idleString = lineContent;
}
}
// De double met het percentage ongebruikte CPU staat tussen de twee spaties in dit stukje tekst als het percentage XX.X is, maar
// als het XXX.X is (100.0) dan heeft het de eerste spatie niet. (En misschien bij X.X juist twee spaties ervoor.)
// In plaats van de String op basis van spaties bij te snijden, kunnen we ook alle karakters die geen getal zijn weghalen.
// Er wordt dan een 1 aan de String toegevoegd om een of andere reden. Die verwijderen we, en we voegen de punt weer toe op de voorlaatste positie.
// (Misschien levert deze methode problemen op als het percentage X.X is, dit is niet getest. Het werkt wel met XXX.X en XX.X.)
idleString = idleString.replaceAll("[^0-9]", "");
idleString = idleString.substring(1);
idleString = idleString.substring(0, idleString.length()-1) + "." + idleString.substring(idleString.length()-1);
double idlePercentage = Double.parseDouble(idleString);
// Vervolgens achterhalen we hiermee het percentage van het CPU dat wel in gebruik is, en ronden we deze double af op één getal achter de komma.
double usedPercentage = (100 - idlePercentage);
if (!(usedPercentage == 0)) {
usedPercentage = Math.round(usedPercentage * 10) / 10.0;
}
// Hier plakken we nog een procentteken aan vast
String output = usedPercentage + "%";
return output;
// Als er iets mis is gegaan, geven we een lege String terug.
} catch (Exception e) {
System.out.println("Er is iets misgegaan bij het achterhalen van het CPU-gebruik.");
return "";
}
}
// Deze functie geeft een String terug die de hoeveelheid diskruimte die beschikbaar is in bytes aangeeft,
// alsook het percentage dat dit is van de gehele diskruimte in bytes.
public String serverDiskSpaceAvailable() {
// Dit SSH-command zal informatie over de diskruimte weergeven.
String command = "df -h\nexit\n";
try {
// We maken een Channel-object aan van het type "shell",
// welke we kunnen gebruiken om het command op te geven, en de resulterende output te lezen.
Channel channel = session.openChannel("shell");
// We maken een inputStream aan met de gegevens die we van het command krijgen.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(byteArrayInputStream);
InputStream inputStream = channel.getInputStream();
// Er wordt verbonden met het shell-kanaal.
channel.connect();
// Met de volgende code wordt de inhoud van de inputStream overgeschreven naar een outputStream.
// Eerst maken we een outputStream waarin we de gegevens zullen schrijven,
// en een buffer waarmee we de gegevens van de inputStream overzetten naar de outputStream.
// De read-methode schrijft een deel van de inputStream over naar de buffer (met de lengte van de buffer).
// De lengte van deze overschrijving (een int) wordt vastgesteld als "length". Zolang length groter dan 0 is wordt de buffer overgeschreven
// naar de outputstream met de write-methode (de 0 in deze methode is het begin van het gedeelte in de buffer dat wordt overgeschreven,
// en de hoeveelheid bytes van dit gedeelte is de reeds vastgestelde length).
// Als read niet slaagt geeft deze methode -1 terug. In dat geval, of als het resterende gedeelte 0 is,
// hebben we het einde van de inputStream bereikt, en kunnen we stoppen.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
// Het kanaal wordt weer gesloten.
channel.disconnect();
// De inhoud van outputStream wordt in losse strings geknipt,
// waarbij elke nieuwe regel (na een enter: regex "\\r?\\n") een nieuwe string is in de array genaamd lines.
String[] lines = outputStream.toString("UTF-8").split("\\r?\\n");
// De informatie die we nodig hebben staat in de regel die begint met "/dev/mapper/cl-root".
// (Dit kan dynamischer, maar het lijkt in ieder geval te werken voor de servers die we gebruiken in Skylab.
// Als het niet blijkt te werken moeten we de eerste regel na de regel die begint met "Filesystem" vinden.)
String relevantLine = null;
for (String line : lines) {
if (line.startsWith("/dev/mapper/cl-root")) {
relevantLine = line;
}
}
// Deze regel splitsen we weer op bij elke spatie.
String[] splitLine = relevantLine.split(" ");
ArrayList<String> lineContent = new ArrayList<>();
// Omdat er meerdere spaties na elkaar voorkomen, zitten er nu Strings in de lineContent-array die geen inhoud hebben.
// Daarom maken we een ArrayList met alle andere Strings.
for (int i = 0; i < splitLine.length; i++) {
if(!(splitLine[i].equals(""))) {
lineContent.add(splitLine[i]);
}
}
// De vierde van deze Strings bevat het percentage van de diskruimte dat gebruikt wordt,
// én een procentteken dat we weg moeten werken om de inhoud als integer te gebruiken
int percentageUsed = Integer.parseInt(lineContent.get(4).replace("%", ""));
// We gebruiken dit om de beschikbare ruimte te achterhalen.
int percentageAvailable = 100 - percentageUsed;
// In de vierde String staat het aantal bytes dat beschikbaar is,
// en in de tweede String staat het totale aantal bytes aan diskruimte in /dev/mapper/cl-root.
// We reigen deze gegevens aan elkaar in de vorm die willen teruggeven.
String output = lineContent.get(3) + " (" + percentageAvailable + "% of " + lineContent.get(1) + ")";
return output;
// Als er iets mis is gegaan, geven we een lege String terug.
} catch (Exception e) {
System.out.println("Er is iets misgegaan bij het achterhalen van de beschikbare diskruimte.");
return "";
}
}
// Deze functie sluit de connectie van het Sessie-object, en maakt dit object ook leeg voor de volgende keer dat er een verbinding wordt gemaakt.
public void closeConnectionWithServer() {
session.disconnect();
session = null;
}
}
| Milciwee/KBS_ICTM2n4 | src/main/java/KBS_ICTM2n4/Serverconnection.java | 4,525 | // Als er iets mis is gegaan, geven we een lege String terug. | line_comment | nl | package KBS_ICTM2n4;
//dit maakt de verbinding tussen de client en de servers
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
public class Serverconnection {
// Wanneer de makeConnectionWithServer-functie wordt aangeroepen, wordt de
// sessie die daarin tot stand komt in dit Session-object opgeslagen
// Dit object wordt weer op null gezet in de closeConnectionWithServer-functie.
public Session session;
// Deze functie poogt een session met het opgegeven IP-adres op te slaan in het
// bovenstaande Session-object "session",
// en geeft true terug als dit lukt, en false als dit niet lukt.
public boolean makeConnectionWithServer(String destinationIP, String username, String password) {
// Dit poortnummer wordt gebruikt om met SSH in te loggen.
int port = 3389;
try {
// We maken een nieuw Java Secure Channel-object aan (JSch), en starten hier vervolgens een sessie mee.
JSch jsch = new JSch();
session = jsch.getSession(username, destinationIP, port);
session.setPassword(password);
try {
session.setTimeout(1000);
} catch (JSchException e1) {
//
}
// (Momenteel controleren we de sleutel van de host niet. Als we een veiligere verbinding willen maken, kunnen StrictHostKeyChecking
// wel activeren, maar dan moeten we de host en sleutel eerst bekendmaken aan het systeem.)
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// Als "session" verbonden is, geven we true terug. Als er een error heeft plaatsgevonden of er geen verbinding is, geven we false terug.
if(session.isConnected()) {
System.out.println("Verbinding is geslaagd.");
return true;
} else {
System.out.println("Het is niet gelukt om een verbinding te maken.");
return false;
}
} catch(Exception e) {
System.out.println("Er is iets misgegaan bij verbinden met de server.");
System.out.println(e);
return false;
}
}
// Deze functie controleert of de sessie een verbinding met de server heeft.
public boolean serverConnected(int i) {
Serverconnection[] serverConnections = MonitoringDialog.getServerConnections();
Serverconnection serverConnection = serverConnections[i];
if(serverConnection.session.isConnected()) {
return true;
} else {
return false;
}
}
// Deze functie geeft een String terug waarin de uptime wordt weergegeven van de server waarmee.
// een SSH-connectie is gemaakt in het static Session-object "session" (in het format "X week(s), X day(s), X hour(s), X minute(s)").
// Als er geen session is geeft het een lege String terug.
public String serverUpTime() {
// Dit SSH-command zal de uptime weergeven.
String command = "uptime -p\nexit\n";
try {
// We maken een Channel-object aan van het type "shell",
// welke we kunnen gebruiken om het command op te geven, en de resulterende output te lezen.
Channel channel = session.openChannel("shell");
// We maken een inputStream aan met de gegevens die we van het command krijgen.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(byteArrayInputStream);
InputStream inputStream = channel.getInputStream();
// Er wordt verbonden met het shell-kanaal.
channel.connect();
// Met de volgende code wordt de inhoud van de inputStream overgeschreven naar een outputStream.
// Eerst maken we een outputStream waarin we de gegevens zullen schrijven,
// en een buffer waarmee we de gegevens van de inputStream overzetten naar de outputStream.
// De read-methode schrijft een deel van de inputStream over naar de buffer (met de lengte van de buffer).
// De lengte van deze overschrijving (een int) wordt vastgesteld als "length". Zolang length groter dan 0 is wordt de buffer overgeschreven
// naar de outputstream met de write-methode (de 0 in deze methode is het begin van het gedeelte in de buffer dat wordt overgeschreven,
// en de hoeveelheid bytes van dit gedeelte is de reeds vastgestelde length).
// Als read niet slaagt geeft deze methode -1 terug. In dat geval, of als het resterende gedeelte 0 is,
// hebben we het einde van de inputStream bereikt, en kunnen we stoppen.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
// Het kanaal wordt weer gesloten.
channel.disconnect();
// De inhoud van outputStream wordt in losse strings geknipt,
// waarbij elke nieuwe regel (na een enter: regex "\\r?\\n") een nieuwe string is in de array genaamd lines.
String[] lines = outputStream.toString("UTF-8").split("\\r?\\n");
String output = null;
// De inhoud die we willen teruggeven staat in de regel die begint met "up ".
for (String line : lines) {
if (line.startsWith("up ")) {
output = line;
}
}
// Als de uptime kleiner dan een minuut is, geeft de uptime -p command geen relevante gegevens.
// Voor het geval dat er "up" zonder spatie staat (en vervolgens niets) stellen we de output handmatig in.
if(output == null) {
output = "<1 minute";
}
// We willen slechts de uptime in woorden teruggeven.
output = output.replace("up ", "");
// Als er toch "up " en vervolgens niets staat, is de output nu gelijk aan "". Ook hier stellen we de output handmatig in.
if(output.equals("")) {
output = "<1 minute";
}
return output;
// Als er iets mis is gegaan, geven we een lege String terug.
} catch (Exception e) {
System.out.println("Er is iets misgegaan bij het achterhalen van de uptime.");
return "";
}
}
// Deze functie geeft een String terug, die het percentage van het CPU dat in gebruik is weergeeft.
public String serverCpuUsed() {
// Dit SSH-command zal informatie over het CPU-gebruik weergeven.
String command = "top\nq\nexit";
try {
// We maken een Channel-object aan van het type "shell",
// welke we kunnen gebruiken om het command op te geven, en de resulterende output te lezen.
Channel channel = session.openChannel("shell");
// We maken een inputStream aan met de gegevens die we van het command krijgen.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(byteArrayInputStream);
InputStream inputStream = channel.getInputStream();
// Er wordt verbonden met het shell-kanaal.
channel.connect();
// Met de volgende code wordt de inhoud van de inputStream overgeschreven naar een outputStream.
// Eerst maken we een outputStream waarin we de gegevens zullen schrijven,
// en een buffer waarmee we de gegevens van de inputStream overzetten naar de outputStream.
// De read-methode schrijft een deel van de inputStream over naar de buffer (met de lengte van de buffer).
// De lengte van deze overschrijving (een int) wordt vastgesteld als "length". Elke loop schrijven we deze lengte aan buffer over in de outputStream.
// Aangezien het "top"-command blijft updaten, wordt de inputstream steeds langer, en kunnen we niet bytes blijven bijschrijven tot het einde.
// Als we de outputStream de String "KiB Mem" bevat, hebben we de informatie die we nodig hebben,
// en gebruiken we "break" om de while-loop te stoppen.
// (Voor het geval dat kunnen we ook stoppen als de totale output een bepaalde lengte heeft bereikt, maar die controle
// levert misschien vertraging op.)
// (Kan waarschijnlijk efficiënter en netter).
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while (true) {
length = inputStream.read(buffer);
outputStream.write(buffer, 0, length);
if(outputStream.toString().contains("KiB Mem")) {
break;
}
}
// Het kanaal wordt weer gesloten.
channel.disconnect();
// De inhoud van outputStream wordt in losse strings geknipt,
// waarbij elke nieuwe regel (na een enter: regex "\\r?\\n") een nieuwe string is in de array genaamd lines.
String[] lines = outputStream.toString().split("\\r?\\n");
// De regel die begint met "%Cpu(s)" bevat de informatie die we nodig hebben.
String relevantLine = null;
for (String line : lines) {
if (line.startsWith("%Cpu(s)")) {
relevantLine = line;
}
}
// We splitsen deze regel vervolgens weer op bij elke komma.
String[] splitLine = relevantLine.split(",");
String idleString = null;
// Het stukje dat we willen gebruiken om het percentage van het CPU dat in gebruik is te berekenen, staat in het stukje
// met "id". (Dit stukje geeft het percentage aan dat juist niet in gebruik is.)
for (String lineContent : splitLine) {
if(lineContent.contains("id")) {
idleString = lineContent;
}
}
// De double met het percentage ongebruikte CPU staat tussen de twee spaties in dit stukje tekst als het percentage XX.X is, maar
// als het XXX.X is (100.0) dan heeft het de eerste spatie niet. (En misschien bij X.X juist twee spaties ervoor.)
// In plaats van de String op basis van spaties bij te snijden, kunnen we ook alle karakters die geen getal zijn weghalen.
// Er wordt dan een 1 aan de String toegevoegd om een of andere reden. Die verwijderen we, en we voegen de punt weer toe op de voorlaatste positie.
// (Misschien levert deze methode problemen op als het percentage X.X is, dit is niet getest. Het werkt wel met XXX.X en XX.X.)
idleString = idleString.replaceAll("[^0-9]", "");
idleString = idleString.substring(1);
idleString = idleString.substring(0, idleString.length()-1) + "." + idleString.substring(idleString.length()-1);
double idlePercentage = Double.parseDouble(idleString);
// Vervolgens achterhalen we hiermee het percentage van het CPU dat wel in gebruik is, en ronden we deze double af op één getal achter de komma.
double usedPercentage = (100 - idlePercentage);
if (!(usedPercentage == 0)) {
usedPercentage = Math.round(usedPercentage * 10) / 10.0;
}
// Hier plakken we nog een procentteken aan vast
String output = usedPercentage + "%";
return output;
// Als er<SUF>
} catch (Exception e) {
System.out.println("Er is iets misgegaan bij het achterhalen van het CPU-gebruik.");
return "";
}
}
// Deze functie geeft een String terug die de hoeveelheid diskruimte die beschikbaar is in bytes aangeeft,
// alsook het percentage dat dit is van de gehele diskruimte in bytes.
public String serverDiskSpaceAvailable() {
// Dit SSH-command zal informatie over de diskruimte weergeven.
String command = "df -h\nexit\n";
try {
// We maken een Channel-object aan van het type "shell",
// welke we kunnen gebruiken om het command op te geven, en de resulterende output te lezen.
Channel channel = session.openChannel("shell");
// We maken een inputStream aan met de gegevens die we van het command krijgen.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(byteArrayInputStream);
InputStream inputStream = channel.getInputStream();
// Er wordt verbonden met het shell-kanaal.
channel.connect();
// Met de volgende code wordt de inhoud van de inputStream overgeschreven naar een outputStream.
// Eerst maken we een outputStream waarin we de gegevens zullen schrijven,
// en een buffer waarmee we de gegevens van de inputStream overzetten naar de outputStream.
// De read-methode schrijft een deel van de inputStream over naar de buffer (met de lengte van de buffer).
// De lengte van deze overschrijving (een int) wordt vastgesteld als "length". Zolang length groter dan 0 is wordt de buffer overgeschreven
// naar de outputstream met de write-methode (de 0 in deze methode is het begin van het gedeelte in de buffer dat wordt overgeschreven,
// en de hoeveelheid bytes van dit gedeelte is de reeds vastgestelde length).
// Als read niet slaagt geeft deze methode -1 terug. In dat geval, of als het resterende gedeelte 0 is,
// hebben we het einde van de inputStream bereikt, en kunnen we stoppen.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
// Het kanaal wordt weer gesloten.
channel.disconnect();
// De inhoud van outputStream wordt in losse strings geknipt,
// waarbij elke nieuwe regel (na een enter: regex "\\r?\\n") een nieuwe string is in de array genaamd lines.
String[] lines = outputStream.toString("UTF-8").split("\\r?\\n");
// De informatie die we nodig hebben staat in de regel die begint met "/dev/mapper/cl-root".
// (Dit kan dynamischer, maar het lijkt in ieder geval te werken voor de servers die we gebruiken in Skylab.
// Als het niet blijkt te werken moeten we de eerste regel na de regel die begint met "Filesystem" vinden.)
String relevantLine = null;
for (String line : lines) {
if (line.startsWith("/dev/mapper/cl-root")) {
relevantLine = line;
}
}
// Deze regel splitsen we weer op bij elke spatie.
String[] splitLine = relevantLine.split(" ");
ArrayList<String> lineContent = new ArrayList<>();
// Omdat er meerdere spaties na elkaar voorkomen, zitten er nu Strings in de lineContent-array die geen inhoud hebben.
// Daarom maken we een ArrayList met alle andere Strings.
for (int i = 0; i < splitLine.length; i++) {
if(!(splitLine[i].equals(""))) {
lineContent.add(splitLine[i]);
}
}
// De vierde van deze Strings bevat het percentage van de diskruimte dat gebruikt wordt,
// én een procentteken dat we weg moeten werken om de inhoud als integer te gebruiken
int percentageUsed = Integer.parseInt(lineContent.get(4).replace("%", ""));
// We gebruiken dit om de beschikbare ruimte te achterhalen.
int percentageAvailable = 100 - percentageUsed;
// In de vierde String staat het aantal bytes dat beschikbaar is,
// en in de tweede String staat het totale aantal bytes aan diskruimte in /dev/mapper/cl-root.
// We reigen deze gegevens aan elkaar in de vorm die willen teruggeven.
String output = lineContent.get(3) + " (" + percentageAvailable + "% of " + lineContent.get(1) + ")";
return output;
// Als er iets mis is gegaan, geven we een lege String terug.
} catch (Exception e) {
System.out.println("Er is iets misgegaan bij het achterhalen van de beschikbare diskruimte.");
return "";
}
}
// Deze functie sluit de connectie van het Sessie-object, en maakt dit object ook leeg voor de volgende keer dat er een verbinding wordt gemaakt.
public void closeConnectionWithServer() {
session.disconnect();
session = null;
}
}
|
102200_12 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.expressietaal.lexical.tokens;
import nl.bzk.brp.expressietaal.parser.ParserFoutCode;
import nl.bzk.brp.expressietaal.symbols.Keywords;
/**
* Geordende collectie van tokens met een cursor, die het volgende te verwerken token aangeeft. TokenStack biedt
* methoden om o.a. het bereiken van het einde van de collectie te testen, de cursor te verschuiven en controles uit
* te voeren op het token dat wordt aangegeven door de cursor.
*/
public interface TokenStack {
/**
* Bepaalt of het einde van de token stack is bereikt.
*
* @return True als het einde van de stack is bereikt; anders false.
*/
boolean finished();
/**
* Geeft aan of de lexicale analyse succesvol is verlopen.
*
* @return True als de lexicale analyse succesvol is verlopen.
*/
boolean succes();
/**
* Geeft de gevonden fout terug.
*
* @return De gevonden fout.
*/
ParserFoutCode getFout();
/**
* Geeft de positie van de gevonden fout terug.
*
* @return Positie van de gevonden fout.
*/
int getFoutPositie();
/**
* Retourneert het totaal aantal tokens op de stack.
*
* @return Aantal tokens op de stack.
*/
int size();
/**
* Geef het huidige token aangewezen door cursor.
*
* @return Huidige token.
*/
Token currentToken();
/**
* Geef het huidige token aangewezen door cursor en schuif de cursor een token verder.
*
* @return Huidige token.
*/
Token shift();
/**
* Controleer of het huidige token van het opgegeven type is.
*
* @param tokenType Te controleren tokentype.
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als het huidige token van het opgegeven type is.
*/
boolean matchNextToken(final TokenType tokenType, final boolean shift);
/**
* Controleer of het huidige token van het opgegeven type en subtype is.
*
* @param tokenType Te controleren tokentype.
* @param tokenSubtype Te controleren tokensubtype.
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als het token van het opgegeven type en subtype is.
*/
boolean matchNextToken(final TokenType tokenType, final TokenSubtype tokenSubtype, final boolean shift);
/**
* Controleer of het huidige token een gelijkheidsoperator (gelijk-aan, niet-gelijk-aan) is.
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een gelijkheidsoperator is.
*/
boolean matchEqualityOperator(final boolean shift);
/**
* Controleer of het huidige token een optel- of aftrekoperator is.
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een optel- of aftrekoperator is.
*/
boolean matchAdditiveOperator(final boolean shift);
/**
* Controleer of het huidige token een vermenigvuldig- of deeloperator is.
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een vermenigvuldig- of deeloperator is.
*/
boolean matchMultiplicativeOperator(final boolean shift);
/**
* Controleer of het huidige token een vergelijkingsoperator is (kleiner, kleiner-of gelijk, groter,
* groter-of-gelijk, element-van-lijst).
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een vergelijkingsoperator is.
*/
boolean matchRelationalOperator(final boolean shift);
/**
* Controleer of het huidige token een bepaald keyword is.
*
* @param keyword Te controleren keyword.
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token het opgegeven keyword is.
*/
boolean matchKeyword(final Keywords keyword, final boolean shift);
}
| MinBZK/OperatieBRP | 2013/brp 2013-02-07/expressietaal/trunk/src/main/java/nl/bzk/brp/expressietaal/lexical/tokens/TokenStack.java | 1,328 | /**
* Controleer of het huidige token een optel- of aftrekoperator is.
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een optel- of aftrekoperator is.
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.expressietaal.lexical.tokens;
import nl.bzk.brp.expressietaal.parser.ParserFoutCode;
import nl.bzk.brp.expressietaal.symbols.Keywords;
/**
* Geordende collectie van tokens met een cursor, die het volgende te verwerken token aangeeft. TokenStack biedt
* methoden om o.a. het bereiken van het einde van de collectie te testen, de cursor te verschuiven en controles uit
* te voeren op het token dat wordt aangegeven door de cursor.
*/
public interface TokenStack {
/**
* Bepaalt of het einde van de token stack is bereikt.
*
* @return True als het einde van de stack is bereikt; anders false.
*/
boolean finished();
/**
* Geeft aan of de lexicale analyse succesvol is verlopen.
*
* @return True als de lexicale analyse succesvol is verlopen.
*/
boolean succes();
/**
* Geeft de gevonden fout terug.
*
* @return De gevonden fout.
*/
ParserFoutCode getFout();
/**
* Geeft de positie van de gevonden fout terug.
*
* @return Positie van de gevonden fout.
*/
int getFoutPositie();
/**
* Retourneert het totaal aantal tokens op de stack.
*
* @return Aantal tokens op de stack.
*/
int size();
/**
* Geef het huidige token aangewezen door cursor.
*
* @return Huidige token.
*/
Token currentToken();
/**
* Geef het huidige token aangewezen door cursor en schuif de cursor een token verder.
*
* @return Huidige token.
*/
Token shift();
/**
* Controleer of het huidige token van het opgegeven type is.
*
* @param tokenType Te controleren tokentype.
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als het huidige token van het opgegeven type is.
*/
boolean matchNextToken(final TokenType tokenType, final boolean shift);
/**
* Controleer of het huidige token van het opgegeven type en subtype is.
*
* @param tokenType Te controleren tokentype.
* @param tokenSubtype Te controleren tokensubtype.
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als het token van het opgegeven type en subtype is.
*/
boolean matchNextToken(final TokenType tokenType, final TokenSubtype tokenSubtype, final boolean shift);
/**
* Controleer of het huidige token een gelijkheidsoperator (gelijk-aan, niet-gelijk-aan) is.
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een gelijkheidsoperator is.
*/
boolean matchEqualityOperator(final boolean shift);
/**
* Controleer of het<SUF>*/
boolean matchAdditiveOperator(final boolean shift);
/**
* Controleer of het huidige token een vermenigvuldig- of deeloperator is.
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een vermenigvuldig- of deeloperator is.
*/
boolean matchMultiplicativeOperator(final boolean shift);
/**
* Controleer of het huidige token een vergelijkingsoperator is (kleiner, kleiner-of gelijk, groter,
* groter-of-gelijk, element-van-lijst).
*
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token een vergelijkingsoperator is.
*/
boolean matchRelationalOperator(final boolean shift);
/**
* Controleer of het huidige token een bepaald keyword is.
*
* @param keyword Te controleren keyword.
* @param shift Als TRUE dan wordt de cursor een teken opgeschoven bij een positieve match (shift).
* @return True als huidige token het opgegeven keyword is.
*/
boolean matchKeyword(final Keywords keyword, final boolean shift);
}
|
124819_13 | package nl.overheid.stelsel.gba.reva.bag.triemap;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
public class BagAdres implements Serializable {
private static final long serialVersionUID = -733312179296502981L;
/**
* Een categorisering van de gebruiksdoelen van het betreffende
* VERBLIJFSOBJECT, zoals dit formeel door de overheid als zodanig is
* toegestaan. Een VERBLIJFSOBJECT is de kleinste binnen één of meerdere
* panden gelegen en voor woon -, bedrijfsmatige - of recreatieve doeleinden
* geschikte eenheid van gebruik, die ontsloten wordt via een eigen toegang
* vanaf de openbare weg, een erf of een gedeelde verkeersruimte en die
* onderwerp kan zijn van rechtshandelingen.
*/
private String gebruiksdoel;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nummering.
*/
private String huisnummer;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nadere toevoeging aan een huisnummer of een combinatie
* van huisnummer en huisletter.
*/
private String huisnummertoevoeging;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende toevoeging aan een huisnummer in de vorm van een
* alfanumeriek teken.
*/
private String huisletter;
/**
* De unieke aanduiding van een NUMMERAANDUIDING. Een NUMMERAANDUIDING is een
* door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String nummeraanduidingId;
/**
* Een naam die aan een OPENBARE RUIMTE is toegekend in een daartoe strekkend
* formeel gemeentelijk besluit. Een OPENBARE RUIMTE is een door de
* gemeenteraad als zodanig aangewezen benaming van een binnen 1 woonplaats
* gelegen buitenruimte.
*
*/
private String openbareRuimteNaam;
/**
* De door TNT Post vastgestelde code behorende bij een bepaalde combinatie
* van een straatnaam en een huisnummer.
*/
private String postcode;
/**
* De aard van een als zodanig benoemde NUMMERAANDUIDING. Een NUMMERAANDUIDING
* is een door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String type;
/**
* De landelijk unieke aanduiding van een WOONPLAATS, zoals vastgesteld door
* de beheerder van de landelijke tabel voor woonplaatsen. Een WOONPLAATS is
* een door de gemeenteraad als zodanig aangewezen gedeelte van het
* gemeentelijk grondgebied.
*/
private String woonplaatsId;
/**
* De benaming van een door het gemeentebestuur aangewezen WOONPLAATS. Een
* WOONPLAATS is een door de gemeenteraad als zodanig aangewezen gedeelte van
* het gemeentelijk grondgebied.
*/
private String woonplaatsNaam;
public BagAdres() {
// Lege constructor.
}
public String getGebruiksdoel() {
return gebruiksdoel;
}
public void setGebruiksdoel( String gebruiksdoel ) {
this.gebruiksdoel = gebruiksdoel;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer( String huisnummer ) {
this.huisnummer = huisnummer;
}
public String getHuisnummertoevoeging() {
return huisnummertoevoeging;
}
public void setHuisnummertoevoeging( String huisnummertoevoeging ) {
this.huisnummertoevoeging = huisnummertoevoeging;
}
public String getHuisletter() {
return huisletter;
}
public void setHuisletter( String huisletter ) {
this.huisletter = huisletter;
}
public String getNummeraanduidingId() {
return nummeraanduidingId;
}
public void setNummeraanduidingId( String nummeraanduidingId ) {
this.nummeraanduidingId = nummeraanduidingId;
}
public String getOpenbareRuimteNaam() {
return openbareRuimteNaam;
}
public void setOpenbareRuimteNaam( String openbareRuimteNaam ) {
this.openbareRuimteNaam = openbareRuimteNaam;
}
public String getPostcode() {
return postcode;
}
public void setPostcode( String postcode ) {
this.postcode = postcode;
}
public String getType() {
return type;
}
public void setType( String type ) {
this.type = type;
}
public String getWoonplaatsId() {
return woonplaatsId;
}
public void setWoonplaatsId( String woonplaatsId ) {
this.woonplaatsId = woonplaatsId;
}
public String getWoonplaatsNaam() {
return woonplaatsNaam;
}
public void setWoonplaatsNaam( String woonplaatsNaam ) {
this.woonplaatsNaam = woonplaatsNaam;
}
/**
* Geeft de NUMMERAANDUIDING bestaande uit de samenvoeging van:
* (huisnummer)(huisletter)(huisnummertoevoeging)
*
* @return De samengestelde nummeraanduiding.
*/
public String getNummeraanduiding() {
StringBuffer nummeraanduiding = new StringBuffer();
if( huisnummer != null ) {
nummeraanduiding.append( huisnummer );
}
if( huisletter != null ) {
nummeraanduiding.append( huisletter );
}
if( huisnummertoevoeging != null ) {
nummeraanduiding.append( huisnummertoevoeging );
}
return nummeraanduiding.toString();
}
@Override
public boolean equals( Object obj ) {
// Vergelijking met niks.
if( obj == null ) {
return false;
}
// Vergelijking met zichzelf.
if( this == obj ) {
return true;
}
if( obj instanceof BagAdres ) {
BagAdres adres = (BagAdres) obj;
// We gaan ervan uit dat de objecten gelijk zijn, totdat we zeker
// weten dat dit niet zo is.
boolean isEqual = true;
isEqual &= StringUtils.equalsIgnoreCase( gebruiksdoel, adres.getGebruiksdoel() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummer, adres.getHuisnummer() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummertoevoeging, adres.getHuisnummertoevoeging() );
isEqual &= StringUtils.equalsIgnoreCase( huisletter, adres.getHuisletter() );
isEqual &= StringUtils.equalsIgnoreCase( nummeraanduidingId, adres.getNummeraanduidingId() );
isEqual &= StringUtils.equalsIgnoreCase( openbareRuimteNaam, adres.getOpenbareRuimteNaam() );
isEqual &= StringUtils.equalsIgnoreCase( postcode, adres.getPostcode() );
isEqual &= StringUtils.equalsIgnoreCase( type, adres.getType() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsId, adres.getWoonplaatsId() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsNaam, adres.getWoonplaatsNaam() );
return isEqual;
}
return false;
}
@Override
public int hashCode() {
StringBuffer string = new StringBuffer();
string.append( gebruiksdoel );
string.append( huisnummer );
string.append( huisnummertoevoeging );
string.append( huisletter );
string.append( nummeraanduidingId );
string.append( openbareRuimteNaam );
string.append( postcode );
string.append( type );
string.append( woonplaatsId );
string.append( woonplaatsNaam );
return string.toString().hashCode();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append( nummeraanduidingId ).append( "," );
string.append( woonplaatsNaam ).append( " " ).append( woonplaatsId ).append( "," );
string.append( openbareRuimteNaam ).append( "," );
if( huisnummer != null ) {
string.append( huisnummer ).append( "," );
}
if( huisletter != null ) {
string.append( huisletter ).append( "," );
}
if( huisnummertoevoeging != null ) {
string.append( huisnummertoevoeging ).append( "," );
}
string.append( postcode ).append( "," );
string.append( type ).append( "," );
string.append( gebruiksdoel );
return string.toString();
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-bag/reva-bag-triemap/src/main/java/nl/overheid/stelsel/gba/reva/bag/triemap/BagAdres.java | 2,670 | // We gaan ervan uit dat de objecten gelijk zijn, totdat we zeker | line_comment | nl | package nl.overheid.stelsel.gba.reva.bag.triemap;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
public class BagAdres implements Serializable {
private static final long serialVersionUID = -733312179296502981L;
/**
* Een categorisering van de gebruiksdoelen van het betreffende
* VERBLIJFSOBJECT, zoals dit formeel door de overheid als zodanig is
* toegestaan. Een VERBLIJFSOBJECT is de kleinste binnen één of meerdere
* panden gelegen en voor woon -, bedrijfsmatige - of recreatieve doeleinden
* geschikte eenheid van gebruik, die ontsloten wordt via een eigen toegang
* vanaf de openbare weg, een erf of een gedeelde verkeersruimte en die
* onderwerp kan zijn van rechtshandelingen.
*/
private String gebruiksdoel;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nummering.
*/
private String huisnummer;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nadere toevoeging aan een huisnummer of een combinatie
* van huisnummer en huisletter.
*/
private String huisnummertoevoeging;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende toevoeging aan een huisnummer in de vorm van een
* alfanumeriek teken.
*/
private String huisletter;
/**
* De unieke aanduiding van een NUMMERAANDUIDING. Een NUMMERAANDUIDING is een
* door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String nummeraanduidingId;
/**
* Een naam die aan een OPENBARE RUIMTE is toegekend in een daartoe strekkend
* formeel gemeentelijk besluit. Een OPENBARE RUIMTE is een door de
* gemeenteraad als zodanig aangewezen benaming van een binnen 1 woonplaats
* gelegen buitenruimte.
*
*/
private String openbareRuimteNaam;
/**
* De door TNT Post vastgestelde code behorende bij een bepaalde combinatie
* van een straatnaam en een huisnummer.
*/
private String postcode;
/**
* De aard van een als zodanig benoemde NUMMERAANDUIDING. Een NUMMERAANDUIDING
* is een door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String type;
/**
* De landelijk unieke aanduiding van een WOONPLAATS, zoals vastgesteld door
* de beheerder van de landelijke tabel voor woonplaatsen. Een WOONPLAATS is
* een door de gemeenteraad als zodanig aangewezen gedeelte van het
* gemeentelijk grondgebied.
*/
private String woonplaatsId;
/**
* De benaming van een door het gemeentebestuur aangewezen WOONPLAATS. Een
* WOONPLAATS is een door de gemeenteraad als zodanig aangewezen gedeelte van
* het gemeentelijk grondgebied.
*/
private String woonplaatsNaam;
public BagAdres() {
// Lege constructor.
}
public String getGebruiksdoel() {
return gebruiksdoel;
}
public void setGebruiksdoel( String gebruiksdoel ) {
this.gebruiksdoel = gebruiksdoel;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer( String huisnummer ) {
this.huisnummer = huisnummer;
}
public String getHuisnummertoevoeging() {
return huisnummertoevoeging;
}
public void setHuisnummertoevoeging( String huisnummertoevoeging ) {
this.huisnummertoevoeging = huisnummertoevoeging;
}
public String getHuisletter() {
return huisletter;
}
public void setHuisletter( String huisletter ) {
this.huisletter = huisletter;
}
public String getNummeraanduidingId() {
return nummeraanduidingId;
}
public void setNummeraanduidingId( String nummeraanduidingId ) {
this.nummeraanduidingId = nummeraanduidingId;
}
public String getOpenbareRuimteNaam() {
return openbareRuimteNaam;
}
public void setOpenbareRuimteNaam( String openbareRuimteNaam ) {
this.openbareRuimteNaam = openbareRuimteNaam;
}
public String getPostcode() {
return postcode;
}
public void setPostcode( String postcode ) {
this.postcode = postcode;
}
public String getType() {
return type;
}
public void setType( String type ) {
this.type = type;
}
public String getWoonplaatsId() {
return woonplaatsId;
}
public void setWoonplaatsId( String woonplaatsId ) {
this.woonplaatsId = woonplaatsId;
}
public String getWoonplaatsNaam() {
return woonplaatsNaam;
}
public void setWoonplaatsNaam( String woonplaatsNaam ) {
this.woonplaatsNaam = woonplaatsNaam;
}
/**
* Geeft de NUMMERAANDUIDING bestaande uit de samenvoeging van:
* (huisnummer)(huisletter)(huisnummertoevoeging)
*
* @return De samengestelde nummeraanduiding.
*/
public String getNummeraanduiding() {
StringBuffer nummeraanduiding = new StringBuffer();
if( huisnummer != null ) {
nummeraanduiding.append( huisnummer );
}
if( huisletter != null ) {
nummeraanduiding.append( huisletter );
}
if( huisnummertoevoeging != null ) {
nummeraanduiding.append( huisnummertoevoeging );
}
return nummeraanduiding.toString();
}
@Override
public boolean equals( Object obj ) {
// Vergelijking met niks.
if( obj == null ) {
return false;
}
// Vergelijking met zichzelf.
if( this == obj ) {
return true;
}
if( obj instanceof BagAdres ) {
BagAdres adres = (BagAdres) obj;
// We gaan<SUF>
// weten dat dit niet zo is.
boolean isEqual = true;
isEqual &= StringUtils.equalsIgnoreCase( gebruiksdoel, adres.getGebruiksdoel() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummer, adres.getHuisnummer() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummertoevoeging, adres.getHuisnummertoevoeging() );
isEqual &= StringUtils.equalsIgnoreCase( huisletter, adres.getHuisletter() );
isEqual &= StringUtils.equalsIgnoreCase( nummeraanduidingId, adres.getNummeraanduidingId() );
isEqual &= StringUtils.equalsIgnoreCase( openbareRuimteNaam, adres.getOpenbareRuimteNaam() );
isEqual &= StringUtils.equalsIgnoreCase( postcode, adres.getPostcode() );
isEqual &= StringUtils.equalsIgnoreCase( type, adres.getType() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsId, adres.getWoonplaatsId() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsNaam, adres.getWoonplaatsNaam() );
return isEqual;
}
return false;
}
@Override
public int hashCode() {
StringBuffer string = new StringBuffer();
string.append( gebruiksdoel );
string.append( huisnummer );
string.append( huisnummertoevoeging );
string.append( huisletter );
string.append( nummeraanduidingId );
string.append( openbareRuimteNaam );
string.append( postcode );
string.append( type );
string.append( woonplaatsId );
string.append( woonplaatsNaam );
return string.toString().hashCode();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append( nummeraanduidingId ).append( "," );
string.append( woonplaatsNaam ).append( " " ).append( woonplaatsId ).append( "," );
string.append( openbareRuimteNaam ).append( "," );
if( huisnummer != null ) {
string.append( huisnummer ).append( "," );
}
if( huisletter != null ) {
string.append( huisletter ).append( "," );
}
if( huisnummertoevoeging != null ) {
string.append( huisnummertoevoeging ).append( "," );
}
string.append( postcode ).append( "," );
string.append( type ).append( "," );
string.append( gebruiksdoel );
return string.toString();
}
}
|
114409_0 | package nl.overheid.koop.plooi.plooiiamservice.web;
import com.nimbusds.jose.JOSEException;
import lombok.RequiredArgsConstructor;
import lombok.val;
import nl.overheid.koop.plooi.plooiiamservice.domain.TokenService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
@RestController
@RequiredArgsConstructor
public class TokenIntrospectionEndpoint {
private final TokenService tokenService;
@GetMapping("/check_token")
public ResponseEntity<Void> checkToken(final HttpServletRequest request) {
val token = request.getHeader("x-access-token");
if (token == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
try {
if (!tokenService.validateToken(token))
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
} catch (ParseException | JOSEException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
return ResponseEntity.ok().build();
}
// Tijdelijk niet beschikbaar. Wordt opgepakt wanneer DPC via CA gaat aansluiten.
// @GetMapping("/check_ca_token")
// public ResponseEntity<Void> checkCaToken() {
// return ResponseEntity.ok().build();
// }
}
| MinBZK/woo-besluit-broncode-PLOOI | aanleveren/security/plooi-iam-service/src/main/java/nl/overheid/koop/plooi/plooiiamservice/web/TokenIntrospectionEndpoint.java | 418 | // Tijdelijk niet beschikbaar. Wordt opgepakt wanneer DPC via CA gaat aansluiten. | line_comment | nl | package nl.overheid.koop.plooi.plooiiamservice.web;
import com.nimbusds.jose.JOSEException;
import lombok.RequiredArgsConstructor;
import lombok.val;
import nl.overheid.koop.plooi.plooiiamservice.domain.TokenService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
@RestController
@RequiredArgsConstructor
public class TokenIntrospectionEndpoint {
private final TokenService tokenService;
@GetMapping("/check_token")
public ResponseEntity<Void> checkToken(final HttpServletRequest request) {
val token = request.getHeader("x-access-token");
if (token == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
try {
if (!tokenService.validateToken(token))
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
} catch (ParseException | JOSEException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
return ResponseEntity.ok().build();
}
// Tijdelijk niet<SUF>
// @GetMapping("/check_ca_token")
// public ResponseEntity<Void> checkCaToken() {
// return ResponseEntity.ok().build();
// }
}
|
212803_0 |
/*
Deze broncode is openbaar gemaakt vanwege een Woo-verzoek zodat deze
gericht is op transparantie en niet op hergebruik. Hergebruik van
de broncode is toegestaan onder de EUPL licentie, met uitzondering
van broncode waarvoor een andere licentie is aangegeven.
Het archief waar dit bestand deel van uitmaakt is te vinden op:
https://github.com/MinBZK/woo-besluit-broncode-digid
Eventuele kwetsbaarheden kunnen worden gemeld bij het NCSC via:
https://www.ncsc.nl/contact/kwetsbaarheid-melden
onder vermelding van "Logius, openbaar gemaakte broncode DigiD"
Voor overige vragen over dit Woo-besluit kunt u mailen met [email protected]
This code has been disclosed in response to a request under the Dutch
Open Government Act ("Wet open Overheid"). This implies that publication
is primarily driven by the need for transparence, not re-use.
Re-use is permitted under the EUPL-license, with the exception
of source files that contain a different license.
The archive that this file originates from can be found at:
https://github.com/MinBZK/woo-besluit-broncode-digid
Security vulnerabilities may be responsibly disclosed via the Dutch NCSC:
https://www.ncsc.nl/contact/kwetsbaarheid-melden
using the reference "Logius, publicly disclosed source code DigiD"
Other questions regarding this Open Goverment Act decision may be
directed via email to [email protected]
*/
package nl.logius.digid.app.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.tags.Tag;
import nl.logius.digid.sharedlib.config.AbstractSwaggerConfig;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class SwaggerConfig extends AbstractSwaggerConfig {
public static final String REQUEST_ACCOUNT_AND_APP = "DigiD app - Aanvragen DigiD account (en Digid app) via de app (zonder gn/ww)";
public static final String REQUEST_ACCOUNT_AND_APP_DESCRIPTION = "Startpunt -> geen DigiD account OF account in aanvraag. Actie -> Aanvragen DigiD account en app (via de app) zonder gebruikersnaam en wachtwoord. Optioneel om na het versturen van de brief (gebeurt op het endpoint /apps/pincode) de ID-check uit te voeren. Eindresultaat -> DigiD account en app aangevraagd en activatiebrief verstuurd. Indien ID-check uitgevoerd de aanvraag is op niveau Substantieel.";
public static final String ACTIVATE_LETTER = "DigiD app - Activeren met basis authenticatie en notificatie brief";
public static final String ACTIVATE_LETTER_DESCRIPTION = "Startpunt -> Een actief DigiD account, geen sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden. Eindresultaat -> Geactiveerde app op niveau Midden. Notificatiebrief ontvangen.";
public static final String ACTIVATE_SMS = "DigiD app - Activeren met basis authenticatie en sms verificatie";
public static final String ACTIVATE_SMS_DESCRIPTION = "Startpunt -> Een actief DigiD account, sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden met sms-controle. Eindresultaat -> Geactiveerde app op niveau Midden.";
public static final String ACTIVATE_RDA = "DigiD app - Activeren met basis authenticatie en ID-check";
public static final String ACTIVATE_RDA_DESCRIPTION = "Startpunt -> Een actief DigiD account op basis/midden niveau. Actie -> DigiD app activeren op Substantieel door het uitvoeren van de ID-check (indien ID-check negeren/niet mogelijk wordt een alternatief activatieproces gestart). Eindresultaat -> Geactiveerde app op niveau Substantieel.";
public static final String ACTIVATE_WITH_APP = "DigiD app - Activeren app met andere DigiD app";
public static final String ACTIVATE_WITH_APP_DESCRIPTION = "";
public static final String RS_ACTIVATE_WITH_APP = "DigiD app - Activeren app bij aanvraagstation";
public static final String RS_ACTIVATE_WITH_APP_DESCRIPTION = "";
public static final String ACTIVATE_WEBSITE = "DigiD app - Activeren account en app na aanvraag via de website";
public static final String ACTIVATE_WEBSITE_DESCRIPTION = "Startpunt -> aangevraagd account met gn/ww en eventueel sms (via de website). Actie -> Activeren van je account via een nieuwe app. Eindresultaat -> Actief account met een nieuwe app";
public static final String ACTIVATE_APP_WITH_CODE = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering";
public static final String ACTIVATE_APP_WITH_CODE_DESCRIPTION = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering";
public static final String UPGRADE_LOGIN_LEVEL = "DigiD app - Verhogen inlogniveau naar substantieel";
public static final String UPGRADE_LOGIN_LEVEL_DESCRIPTION = "DigiD app - Verhogen inlogniveau naar substantieel";
public static final String RE_APPLY_ACTIVATIONCODE = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)";
public static final String RE_APPLY_ACTIVATIONCODE_DESCRIPTION = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)";
public static final String AUTH_WITH_WID = "DigiD app - Authenticeren met identiteitsdocument (DigiD Hoog)";
public static final String AUTH_WITH_WID_DESCRIPTION = "Startpunt -> Een actief DigiD account met geactiveerd hoog middel. Actie -> Inloggen met identiteitsdocument op niveau hoog Eindresultaat -> Ingelogd bij webdienst op niveau hoog";
public static final String HEADER = "header";
public static final String MANAGE_ACCOUNT_SESSION = "DigiD app - Accounthandelingen Mijn DigiD";
public static final String PINCODE_RESET_OF_APP = "DigiD app - Reset pincode of app";
public static final String WIDCHECKER_RAISE_TO_SUB = "DigiD Wid Checker - Verhogen naar substantieel";
public static final String APP_LOGIN = "DigiD app - Starten app (inloggen met pincode)";
public static final String APP_LOGIN_DESCRIPTION = "Bij het openen van de app wordt je gelijk gevraagd om te authenticeren met pincode, voor andere flows die hierna komen hoeft niet meer te worden geauthenticeerd alleen eventueel bevestigd.";
public static final String CONFIRM_SESSION = "DigiD app - Bevestigen actie/login met geauthenticeerde sessie";
public static final String SHARED = "Shared endpoints";
public static final String SHARED_DESCRIPTION = "Bij het starten van de app haalt deze een aantal gegevens op via deze endpoints. Bijv of switches aan/of uit.";
@Value("${urls.external.app}")
private String appBaseUrl;
@Bean
public GroupedOpenApi publicOpenApi() {
var paths = new String[]{"/iapi/**", "/apps/**"};
return GroupedOpenApi.builder().group("Public-api").pathsToMatch(paths).build();
}
@Override
public OpenAPI IapiOpenAPI(){
return new OpenAPI().addServersItem(new Server().url(appBaseUrl))
.components(new Components()
.addParameters("API-V", apiVersionHeader())
.addParameters("OS-T", osTypeHeader())
.addParameters("APP-V", appVersionHeader())
.addParameters("OS-V", osVersionHeader())
.addParameters("REL-T", releaseTypeHeader())
.addParameters("X-Auth-Token", xAuthToken())
).tags(getFlowTags());
}
public List<Tag> getFlowTags(){
return List.of(
createTag(REQUEST_ACCOUNT_AND_APP, REQUEST_ACCOUNT_AND_APP_DESCRIPTION),
createTag(ACTIVATE_LETTER, ACTIVATE_LETTER_DESCRIPTION),
createTag(ACTIVATE_SMS, ACTIVATE_SMS_DESCRIPTION),
createTag(ACTIVATE_RDA, ACTIVATE_RDA_DESCRIPTION),
createTag(ACTIVATE_WITH_APP, ACTIVATE_WITH_APP_DESCRIPTION),
createTag(ACTIVATE_APP_WITH_CODE, ACTIVATE_APP_WITH_CODE_DESCRIPTION),
createTag(AUTH_WITH_WID, AUTH_WITH_WID_DESCRIPTION),
createTag(RE_APPLY_ACTIVATIONCODE, RE_APPLY_ACTIVATIONCODE_DESCRIPTION),
createTag(RS_ACTIVATE_WITH_APP, RS_ACTIVATE_WITH_APP_DESCRIPTION),
createTag(UPGRADE_LOGIN_LEVEL, UPGRADE_LOGIN_LEVEL_DESCRIPTION),
createTag(APP_LOGIN, APP_LOGIN_DESCRIPTION),
createTag(ACTIVATE_WEBSITE, ACTIVATE_WEBSITE_DESCRIPTION),
createTag(SHARED, SHARED_DESCRIPTION)
);
}
private Tag createTag(String name, String description) {
var tag = new Tag();
tag.setName(name);
tag.setDescription(description);
return tag;
}
protected static Parameter apiVersionHeader() {
return new Parameter()
.in(HEADER)
.name("API-Version")
.description("API-Version")
.example("1")
.required(true)
.schema(new StringSchema());
}
protected static Parameter osTypeHeader() {
return new Parameter()
.in(HEADER)
.name("OS-Type")
.description("OS-Type")
.example("Android")
.required(true)
.schema(new StringSchema());
}
protected static Parameter appVersionHeader() {
return new Parameter()
.in(HEADER)
.name("App-version")
.description("App-version")
.example("1.0.0")
.required(true)
.schema(new StringSchema());
}
protected static Parameter osVersionHeader() {
return new Parameter()
.in(HEADER)
.name("OS-Version")
.description("OS-Version")
.example("10")
.required(true)
.schema(new StringSchema());
}
protected static Parameter releaseTypeHeader() {
return new Parameter()
.in(HEADER)
.name("Release-Type")
.description("Release-Type")
.example("Productie")
.required(true)
.schema(new StringSchema());
}
protected static Parameter xAuthToken() {
return new Parameter()
.in("header")
.name("X-Auth-Token")
.description("X-Auth-Token")
.example("development")
.required(true)
.schema(new StringSchema());
}
}
| MinBZK/woo-besluit-broncode-digid | components/digid_app/src/main/java/nl/logius/digid/app/config/SwaggerConfig.java | 3,265 | /*
Deze broncode is openbaar gemaakt vanwege een Woo-verzoek zodat deze
gericht is op transparantie en niet op hergebruik. Hergebruik van
de broncode is toegestaan onder de EUPL licentie, met uitzondering
van broncode waarvoor een andere licentie is aangegeven.
Het archief waar dit bestand deel van uitmaakt is te vinden op:
https://github.com/MinBZK/woo-besluit-broncode-digid
Eventuele kwetsbaarheden kunnen worden gemeld bij het NCSC via:
https://www.ncsc.nl/contact/kwetsbaarheid-melden
onder vermelding van "Logius, openbaar gemaakte broncode DigiD"
Voor overige vragen over dit Woo-besluit kunt u mailen met [email protected]
This code has been disclosed in response to a request under the Dutch
Open Government Act ("Wet open Overheid"). This implies that publication
is primarily driven by the need for transparence, not re-use.
Re-use is permitted under the EUPL-license, with the exception
of source files that contain a different license.
The archive that this file originates from can be found at:
https://github.com/MinBZK/woo-besluit-broncode-digid
Security vulnerabilities may be responsibly disclosed via the Dutch NCSC:
https://www.ncsc.nl/contact/kwetsbaarheid-melden
using the reference "Logius, publicly disclosed source code DigiD"
Other questions regarding this Open Goverment Act decision may be
directed via email to [email protected]
*/ | block_comment | nl |
/*
Deze broncode is<SUF>*/
package nl.logius.digid.app.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.tags.Tag;
import nl.logius.digid.sharedlib.config.AbstractSwaggerConfig;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class SwaggerConfig extends AbstractSwaggerConfig {
public static final String REQUEST_ACCOUNT_AND_APP = "DigiD app - Aanvragen DigiD account (en Digid app) via de app (zonder gn/ww)";
public static final String REQUEST_ACCOUNT_AND_APP_DESCRIPTION = "Startpunt -> geen DigiD account OF account in aanvraag. Actie -> Aanvragen DigiD account en app (via de app) zonder gebruikersnaam en wachtwoord. Optioneel om na het versturen van de brief (gebeurt op het endpoint /apps/pincode) de ID-check uit te voeren. Eindresultaat -> DigiD account en app aangevraagd en activatiebrief verstuurd. Indien ID-check uitgevoerd de aanvraag is op niveau Substantieel.";
public static final String ACTIVATE_LETTER = "DigiD app - Activeren met basis authenticatie en notificatie brief";
public static final String ACTIVATE_LETTER_DESCRIPTION = "Startpunt -> Een actief DigiD account, geen sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden. Eindresultaat -> Geactiveerde app op niveau Midden. Notificatiebrief ontvangen.";
public static final String ACTIVATE_SMS = "DigiD app - Activeren met basis authenticatie en sms verificatie";
public static final String ACTIVATE_SMS_DESCRIPTION = "Startpunt -> Een actief DigiD account, sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden met sms-controle. Eindresultaat -> Geactiveerde app op niveau Midden.";
public static final String ACTIVATE_RDA = "DigiD app - Activeren met basis authenticatie en ID-check";
public static final String ACTIVATE_RDA_DESCRIPTION = "Startpunt -> Een actief DigiD account op basis/midden niveau. Actie -> DigiD app activeren op Substantieel door het uitvoeren van de ID-check (indien ID-check negeren/niet mogelijk wordt een alternatief activatieproces gestart). Eindresultaat -> Geactiveerde app op niveau Substantieel.";
public static final String ACTIVATE_WITH_APP = "DigiD app - Activeren app met andere DigiD app";
public static final String ACTIVATE_WITH_APP_DESCRIPTION = "";
public static final String RS_ACTIVATE_WITH_APP = "DigiD app - Activeren app bij aanvraagstation";
public static final String RS_ACTIVATE_WITH_APP_DESCRIPTION = "";
public static final String ACTIVATE_WEBSITE = "DigiD app - Activeren account en app na aanvraag via de website";
public static final String ACTIVATE_WEBSITE_DESCRIPTION = "Startpunt -> aangevraagd account met gn/ww en eventueel sms (via de website). Actie -> Activeren van je account via een nieuwe app. Eindresultaat -> Actief account met een nieuwe app";
public static final String ACTIVATE_APP_WITH_CODE = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering";
public static final String ACTIVATE_APP_WITH_CODE_DESCRIPTION = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering";
public static final String UPGRADE_LOGIN_LEVEL = "DigiD app - Verhogen inlogniveau naar substantieel";
public static final String UPGRADE_LOGIN_LEVEL_DESCRIPTION = "DigiD app - Verhogen inlogniveau naar substantieel";
public static final String RE_APPLY_ACTIVATIONCODE = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)";
public static final String RE_APPLY_ACTIVATIONCODE_DESCRIPTION = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)";
public static final String AUTH_WITH_WID = "DigiD app - Authenticeren met identiteitsdocument (DigiD Hoog)";
public static final String AUTH_WITH_WID_DESCRIPTION = "Startpunt -> Een actief DigiD account met geactiveerd hoog middel. Actie -> Inloggen met identiteitsdocument op niveau hoog Eindresultaat -> Ingelogd bij webdienst op niveau hoog";
public static final String HEADER = "header";
public static final String MANAGE_ACCOUNT_SESSION = "DigiD app - Accounthandelingen Mijn DigiD";
public static final String PINCODE_RESET_OF_APP = "DigiD app - Reset pincode of app";
public static final String WIDCHECKER_RAISE_TO_SUB = "DigiD Wid Checker - Verhogen naar substantieel";
public static final String APP_LOGIN = "DigiD app - Starten app (inloggen met pincode)";
public static final String APP_LOGIN_DESCRIPTION = "Bij het openen van de app wordt je gelijk gevraagd om te authenticeren met pincode, voor andere flows die hierna komen hoeft niet meer te worden geauthenticeerd alleen eventueel bevestigd.";
public static final String CONFIRM_SESSION = "DigiD app - Bevestigen actie/login met geauthenticeerde sessie";
public static final String SHARED = "Shared endpoints";
public static final String SHARED_DESCRIPTION = "Bij het starten van de app haalt deze een aantal gegevens op via deze endpoints. Bijv of switches aan/of uit.";
@Value("${urls.external.app}")
private String appBaseUrl;
@Bean
public GroupedOpenApi publicOpenApi() {
var paths = new String[]{"/iapi/**", "/apps/**"};
return GroupedOpenApi.builder().group("Public-api").pathsToMatch(paths).build();
}
@Override
public OpenAPI IapiOpenAPI(){
return new OpenAPI().addServersItem(new Server().url(appBaseUrl))
.components(new Components()
.addParameters("API-V", apiVersionHeader())
.addParameters("OS-T", osTypeHeader())
.addParameters("APP-V", appVersionHeader())
.addParameters("OS-V", osVersionHeader())
.addParameters("REL-T", releaseTypeHeader())
.addParameters("X-Auth-Token", xAuthToken())
).tags(getFlowTags());
}
public List<Tag> getFlowTags(){
return List.of(
createTag(REQUEST_ACCOUNT_AND_APP, REQUEST_ACCOUNT_AND_APP_DESCRIPTION),
createTag(ACTIVATE_LETTER, ACTIVATE_LETTER_DESCRIPTION),
createTag(ACTIVATE_SMS, ACTIVATE_SMS_DESCRIPTION),
createTag(ACTIVATE_RDA, ACTIVATE_RDA_DESCRIPTION),
createTag(ACTIVATE_WITH_APP, ACTIVATE_WITH_APP_DESCRIPTION),
createTag(ACTIVATE_APP_WITH_CODE, ACTIVATE_APP_WITH_CODE_DESCRIPTION),
createTag(AUTH_WITH_WID, AUTH_WITH_WID_DESCRIPTION),
createTag(RE_APPLY_ACTIVATIONCODE, RE_APPLY_ACTIVATIONCODE_DESCRIPTION),
createTag(RS_ACTIVATE_WITH_APP, RS_ACTIVATE_WITH_APP_DESCRIPTION),
createTag(UPGRADE_LOGIN_LEVEL, UPGRADE_LOGIN_LEVEL_DESCRIPTION),
createTag(APP_LOGIN, APP_LOGIN_DESCRIPTION),
createTag(ACTIVATE_WEBSITE, ACTIVATE_WEBSITE_DESCRIPTION),
createTag(SHARED, SHARED_DESCRIPTION)
);
}
private Tag createTag(String name, String description) {
var tag = new Tag();
tag.setName(name);
tag.setDescription(description);
return tag;
}
protected static Parameter apiVersionHeader() {
return new Parameter()
.in(HEADER)
.name("API-Version")
.description("API-Version")
.example("1")
.required(true)
.schema(new StringSchema());
}
protected static Parameter osTypeHeader() {
return new Parameter()
.in(HEADER)
.name("OS-Type")
.description("OS-Type")
.example("Android")
.required(true)
.schema(new StringSchema());
}
protected static Parameter appVersionHeader() {
return new Parameter()
.in(HEADER)
.name("App-version")
.description("App-version")
.example("1.0.0")
.required(true)
.schema(new StringSchema());
}
protected static Parameter osVersionHeader() {
return new Parameter()
.in(HEADER)
.name("OS-Version")
.description("OS-Version")
.example("10")
.required(true)
.schema(new StringSchema());
}
protected static Parameter releaseTypeHeader() {
return new Parameter()
.in(HEADER)
.name("Release-Type")
.description("Release-Type")
.example("Productie")
.required(true)
.schema(new StringSchema());
}
protected static Parameter xAuthToken() {
return new Parameter()
.in("header")
.name("X-Auth-Token")
.description("X-Auth-Token")
.example("development")
.required(true)
.schema(new StringSchema());
}
}
|
10277_0 | package ss.week7;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConcatThread extends Thread {
private static String text = ""; // global variable
private String toe; // niet static dus deze word nooit overschreven
private static Lock l = new ReentrantLock();
public ConcatThread(String toeArg) {
this.toe = toeArg;
}
public void run() {
l.lock();
text = text.concat(toe);
l.unlock();
}
public static void main(String[] args) {
(new ConcatThread("one;")).start();
(new ConcatThread("two;")).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.getMessage();
}
System.out.println(text);
}
}
| MinThaMie/Opdrachten | softwaresystems/src/ss/week7/ConcatThread.java | 253 | // niet static dus deze word nooit overschreven
| line_comment | nl | package ss.week7;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConcatThread extends Thread {
private static String text = ""; // global variable
private String toe; // niet static<SUF>
private static Lock l = new ReentrantLock();
public ConcatThread(String toeArg) {
this.toe = toeArg;
}
public void run() {
l.lock();
text = text.concat(toe);
l.unlock();
}
public static void main(String[] args) {
(new ConcatThread("one;")).start();
(new ConcatThread("two;")).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.getMessage();
}
System.out.println(text);
}
}
|
141800_4 | /**
* Author: Martin van Velsen <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 edu.cmu.cs.in.hoop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import com.sleepycat.collections.StoredMap;
import edu.cmu.cs.in.base.HoopLink;
import edu.cmu.cs.in.base.kv.HoopKVDocument;
import edu.cmu.cs.in.base.kv.HoopKVLong;
import edu.cmu.cs.in.controls.HoopButtonBox;
import edu.cmu.cs.in.controls.base.HoopEmbeddedJPanel;
import edu.cmu.cs.in.search.HoopDataSet;
/**
*
*/
public class HoopDocumentList extends HoopEmbeddedJPanel implements ActionListener, MouseListener
{
private static final long serialVersionUID = 2319368351656283482L;
private JList<HoopKVDocument> docList=null;
private JButton expandButton=null;
private JButton foldButton=null;
private JButton refreshButton=null;
private JButton configureButton=null;
private JButton prevButton=null;
private JTextField startIndex=null;
private JTextField windowSize=null;
private JButton nextButton=null;
private JButton searchButton=null;
private JButton sortButton=null;
private JLabel dbInfo=null;
private HoopButtonBox buttonBox=null;
private HoopButtonBox searchBox=null;
private Integer start=0;
private Integer maxShown=20;
private JTree threadTree=null;
private JButton treeExpandButton=null;
private JButton treeFoldButton=null;
private HoopDocumentListRenderer rendererObject=null;
/**
* Constructs a new frame that is initially invisible.
*/
public HoopDocumentList()
{
super (HoopLink.getImageByName("gtk-copy.png"));
setClassName ("HoopDocumentList");
debug ("HoopDocumentList ()");
Box holder = new Box (BoxLayout.Y_AXIS);
buttonBox=new HoopButtonBox ();
buttonBox.setMinimumSize(new Dimension (100,24));
buttonBox.setPreferredSize(new Dimension (200,24));
buttonBox.setMaximumSize(new Dimension (2000,24));
expandButton=new JButton ();
expandButton.setFont(new Font("Dialog", 1, 8));
expandButton.setPreferredSize(new Dimension (20,20));
expandButton.setMaximumSize(new Dimension (20,20));
expandButton.setIcon(HoopLink.getImageByName("tree-expand-icon.png"));
expandButton.addActionListener(this);
buttonBox.addComponent(expandButton);
foldButton=new JButton ();
foldButton.setFont(new Font("Dialog", 1, 8));
foldButton.setPreferredSize(new Dimension (20,20));
foldButton.setMaximumSize(new Dimension (20,20));
foldButton.setIcon(HoopLink.getImageByName("tree-fold-icon.png"));
foldButton.addActionListener(this);
buttonBox.addComponent(foldButton);
refreshButton=new JButton ();
refreshButton.setFont(new Font("Dialog", 1, 8));
refreshButton.setPreferredSize(new Dimension (20,20));
refreshButton.setMaximumSize(new Dimension (20,20));
refreshButton.setIcon(HoopLink.getImageByName("gtk-refresh.png"));
refreshButton.addActionListener(this);
buttonBox.addComponent(refreshButton);
configureButton=new JButton ();
configureButton.setFont(new Font("Dialog", 1, 8));
configureButton.setPreferredSize(new Dimension (20,20));
configureButton.setMaximumSize(new Dimension (20,20));
configureButton.setIcon(HoopLink.getImageByName("gtk-preferences.png"));
configureButton.addActionListener(this);
buttonBox.addComponent(configureButton);
prevButton=new JButton ();
prevButton.setPreferredSize(new Dimension (20,20));
prevButton.setMaximumSize(new Dimension (20,20));
prevButton.setIcon(HoopLink.getImageByName("gtk-go-back-ltr.png"));
prevButton.addActionListener(this);
buttonBox.addComponent(prevButton);
JLabel startLabel=new JLabel ();
startLabel.setFont(new Font("Dialog", 1, 8));
startLabel.setText("From: ");
buttonBox.addComponent(startLabel);
startIndex=new JTextField ();
startIndex.setText(start.toString());
startIndex.setFont(new Font("Dialog", 1, 8));
startIndex.setPreferredSize(new Dimension (50,20));
startIndex.setMaximumSize(new Dimension (50,20));
buttonBox.addComponent(startIndex);
JLabel withLabel=new JLabel ();
withLabel.setFont(new Font("Dialog", 1, 8));
withLabel.setText("show: ");
buttonBox.addComponent(withLabel);
windowSize=new JTextField ();
windowSize.setText(maxShown.toString());
windowSize.setFont(new Font("Dialog", 1, 8));
windowSize.setPreferredSize(new Dimension (50,20));
windowSize.setMaximumSize(new Dimension (50,20));
buttonBox.addComponent(windowSize);
nextButton=new JButton ();
nextButton.setPreferredSize(new Dimension (20,20));
nextButton.setMaximumSize(new Dimension (20,20));
nextButton.setIcon(HoopLink.getImageByName("gtk-go-forward-ltr.png"));
nextButton.addActionListener(this);
buttonBox.addComponent(nextButton);
dbInfo=new JLabel ();
dbInfo.setFont(new Font("Dialog", 1, 8));
buttonBox.addComponent(dbInfo);
searchBox=new HoopButtonBox ();
searchBox.setMinimumSize(new Dimension (100,24));
searchBox.setPreferredSize(new Dimension (200,24));
searchBox.setMaximumSize(new Dimension (2000,24));
searchButton=new JButton ();
searchButton.setPreferredSize(new Dimension (20,20));
searchButton.setMaximumSize(new Dimension (20,20));
searchButton.setIcon(HoopLink.getImageByName("gtk-find-and-replace.png"));
searchButton.addActionListener(this);
searchBox.addComponent(searchButton);
sortButton=new JButton ();
sortButton.setPreferredSize(new Dimension (20,20));
sortButton.setMaximumSize(new Dimension (20,20));
sortButton.setIcon(HoopLink.getImageByName("alphab_sort_icon.png"));
sortButton.addActionListener(this);
searchBox.addComponent(sortButton);
rendererObject=new HoopDocumentListRenderer ();
docList=new JList<HoopKVDocument> ();
docList.setCellRenderer (rendererObject);
docList.addMouseListener(this);
JScrollPane docScrollList = new JScrollPane (docList);
docScrollList.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
holder.add (buttonBox);
holder.add (searchBox);
holder.add (docScrollList);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab ("Document View",
HoopLink.getImageByName("text_icon.png"),
holder,
"Document View");
//>-------------------------------------------------------
threadTree=new JTree ();
threadTree.setFont(new Font("Dialog", 1, 10)); // overwritten by cellrenderer?
threadTree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
threadTree.setRootVisible(false);
threadTree.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
threadTree.setDragEnabled(false);
threadTree.addMouseListener (this);
JScrollPane treeScroller=new JScrollPane (threadTree);
Box treeButtonBox = new Box (BoxLayout.X_AXIS);
treeExpandButton=new JButton ();
treeExpandButton.setFont(new Font("Dialog", 1, 8));
treeExpandButton.setPreferredSize(new Dimension (20,20));
treeExpandButton.setMaximumSize(new Dimension (20,20));
//treeExpandButton.setText("All");
treeExpandButton.setIcon(HoopLink.getImageByName("tree-expand-icon.png"));
treeExpandButton.addActionListener(this);
treeButtonBox.add (treeExpandButton);
treeButtonBox.add (Box.createRigidArea(new Dimension(2,0)));
treeFoldButton=new JButton ();
treeFoldButton.setFont(new Font("Dialog", 1, 8));
treeFoldButton.setPreferredSize(new Dimension (20,20));
treeFoldButton.setMaximumSize(new Dimension (20,20));
treeFoldButton.setIcon(HoopLink.getImageByName("tree-fold-icon.png"));
//treeFoldButton.setText("None");
treeFoldButton.addActionListener(this);
treeButtonBox.add (treeFoldButton);
treeButtonBox.add (Box.createRigidArea(new Dimension(2,0)));
treeButtonBox.add(Box.createHorizontalGlue());
JPanel treePanel=new JPanel ();
treePanel.setLayout(new BoxLayout (treePanel,BoxLayout.Y_AXIS));
treePanel.add (treeButtonBox);
treePanel.add (treeScroller);
tabbedPane.addTab ("Thread View",
HoopLink.getImageByName("tree.gif"),
treePanel,
"Thread View");
//>-------------------------------------------------------
setContentPane (tabbedPane);
updateContents(); // Just in case we already have something
}
/**
*
*/
public void reset ()
{
debug ("reset ()");
DefaultListModel<HoopKVDocument> mdl=new DefaultListModel<HoopKVDocument> ();
docList.setModel (mdl);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Threads");
root.setUserObject("Threads");
DefaultTreeModel model = new DefaultTreeModel(root);
threadTree.setModel(model);
rendererObject.reset ();
}
/**
*
*/
public void updateContents()
{
debug ("updateContents ()");
if (HoopLink.dataSet==null)
HoopLink.dataSet=new HoopDataSet ();
HoopLink.dataSet.checkDB();
debug ("Dataset checked, showing first entries in document list ...");
StoredMap<Long,HoopKVDocument> map=HoopLink.dataSet.getData();
if (map==null)
{
return;
}
DefaultListModel<HoopKVDocument> mdl=new DefaultListModel<HoopKVDocument> ();
debug ("There are currently " + map.size() + " entries available");
Integer sizeTransformer=map.size();
dbInfo.setText(sizeTransformer.toString()+" Entries");
Iterator<HoopKVDocument> iterator = map.values().iterator();
int index=0;
int count=maxShown;
if (map.size()<maxShown)
count=map.size ();
if (map!=null)
{
while ((iterator.hasNext()) && (index<count))
{
HoopKVDocument aDoc=(HoopKVDocument) iterator.next();
debug ("Adding document ...");
mdl.addElement(aDoc);
index++;
}
}
docList.setModel (mdl);
showDocumentThreads ();
}
/**
*
*/
private void showDocumentThreads ()
{
debug ("showDocumentThreads ()");
if (HoopLink.dataSet==null)
{
return;
}
StoredMap<Long,HoopKVLong> threadData=HoopLink.dataSet.getThreads();
if (threadData==null)
{
debug ("Error: no thread data available");
return;
}
StoredMap<Long,HoopKVDocument> map=HoopLink.dataSet.getData();
if (map==null)
{
debug ("Error: no document data available");
return;
}
Integer totalShown=maxShown;
int dSize=threadData.size();
if (dSize<totalShown)
totalShown=dSize;
debug ("Thread data size: " + dSize + " adjusted: " + totalShown);
Iterator<HoopKVLong> iterator = threadData.values().iterator();
int index=0;
int count=maxShown;
if (threadData.size()<maxShown)
count=threadData.size ();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Threads");
root.setUserObject("Threads");
DefaultTreeModel model = new DefaultTreeModel(root);
int totalDocumentSize=0;
while ((iterator.hasNext()) && (index<count))
{
HoopKVLong aThread=(HoopKVLong) iterator.next();
DefaultMutableTreeNode aNode=new DefaultMutableTreeNode (aThread.getKeyString ());
root.add(aNode);
ArrayList <Object> threadContents=aThread.getValuesRaw();
debug ("Thread with id " +aThread.getKeyString() + " has " + aThread.getValuesRaw().size() + " entries");
totalDocumentSize+=aThread.getValuesRaw().size();
for (int j=0;j<threadContents.size();j++)
{
String docID=(String) threadContents.get(j);
DefaultMutableTreeNode threadNode=new DefaultMutableTreeNode (docID);
aNode.add(threadNode);
}
index++;
}
debug ("There are a total of " + totalDocumentSize + " documents in the database");
threadTree.setModel(model);
}
/**
*
*/
@Override
public void actionPerformed(ActionEvent event)
{
debug ("actionPerformed ()");
//String act=event.getActionCommand();
JButton button = (JButton)event.getSource();
if (button==expandButton)
{
//TreeNode root = (TreeNode) tree.getModel().getRoot();
//expandAll (tree, new TreePath(root));
}
if (button==foldButton)
{
//TreeNode root = (TreeNode) tree.getModel().getRoot();
//collapseAll (tree, new TreePath(root));
}
if (button==refreshButton)
{
updateContents();
}
if (button==configureButton)
{
//updateContents();
}
if (button==searchButton)
{
HoopSearch test=(HoopSearch) HoopLink.getWindow("Search");
if (test==null)
{
HoopLink.addView ("Search",new HoopSearch(),HoopLink.center);
test=(HoopSearch) HoopLink.getWindow("Search");
}
//test.showDocument(aDoc);
HoopLink.popWindow ("Search");
}
if (button==sortButton)
{
}
}
/**
*
*/
@Override
public void mouseClicked(MouseEvent event)
{
debug ("mouseClicked ()");
if (event.getSource()==threadTree)
{
debug ("Can't process thread tree double click yet");
}
else
{
if (event.getClickCount()==2)
{
int index = docList.locationToIndex(event.getPoint());
debug ("Double clicked on Item " + index);
HoopKVDocument aDoc=(HoopKVDocument) docList.getModel().getElementAt(index);
if (aDoc!=null)
{
HoopTextViewer test=(HoopTextViewer) HoopLink.getWindow("Text Viewer");
if (test==null)
{
HoopLink.addView ("Text Viewer",new HoopTextViewer(),HoopLink.center);
test=(HoopTextViewer) HoopLink.getWindow("Text Viewer");
}
test.showDocument(aDoc);
HoopLink.popWindow ("Text Viewer");
}
}
}
}
/**
*
*/
@Override
public void mouseEntered(MouseEvent arg0)
{
}
/**
*
*/
@Override
public void mouseExited(MouseEvent arg0)
{
}
/**
*
*/
@Override
public void mousePressed(MouseEvent arg0)
{
}
/**
*
*/
@Override
public void mouseReleased(MouseEvent arg0)
{
}
}
| Mindtoeye/Hoop | src/edu/cmu/cs/in/hoop/HoopDocumentList.java | 5,648 | //TreeNode root = (TreeNode) tree.getModel().getRoot(); | line_comment | nl | /**
* Author: Martin van Velsen <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 edu.cmu.cs.in.hoop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import com.sleepycat.collections.StoredMap;
import edu.cmu.cs.in.base.HoopLink;
import edu.cmu.cs.in.base.kv.HoopKVDocument;
import edu.cmu.cs.in.base.kv.HoopKVLong;
import edu.cmu.cs.in.controls.HoopButtonBox;
import edu.cmu.cs.in.controls.base.HoopEmbeddedJPanel;
import edu.cmu.cs.in.search.HoopDataSet;
/**
*
*/
public class HoopDocumentList extends HoopEmbeddedJPanel implements ActionListener, MouseListener
{
private static final long serialVersionUID = 2319368351656283482L;
private JList<HoopKVDocument> docList=null;
private JButton expandButton=null;
private JButton foldButton=null;
private JButton refreshButton=null;
private JButton configureButton=null;
private JButton prevButton=null;
private JTextField startIndex=null;
private JTextField windowSize=null;
private JButton nextButton=null;
private JButton searchButton=null;
private JButton sortButton=null;
private JLabel dbInfo=null;
private HoopButtonBox buttonBox=null;
private HoopButtonBox searchBox=null;
private Integer start=0;
private Integer maxShown=20;
private JTree threadTree=null;
private JButton treeExpandButton=null;
private JButton treeFoldButton=null;
private HoopDocumentListRenderer rendererObject=null;
/**
* Constructs a new frame that is initially invisible.
*/
public HoopDocumentList()
{
super (HoopLink.getImageByName("gtk-copy.png"));
setClassName ("HoopDocumentList");
debug ("HoopDocumentList ()");
Box holder = new Box (BoxLayout.Y_AXIS);
buttonBox=new HoopButtonBox ();
buttonBox.setMinimumSize(new Dimension (100,24));
buttonBox.setPreferredSize(new Dimension (200,24));
buttonBox.setMaximumSize(new Dimension (2000,24));
expandButton=new JButton ();
expandButton.setFont(new Font("Dialog", 1, 8));
expandButton.setPreferredSize(new Dimension (20,20));
expandButton.setMaximumSize(new Dimension (20,20));
expandButton.setIcon(HoopLink.getImageByName("tree-expand-icon.png"));
expandButton.addActionListener(this);
buttonBox.addComponent(expandButton);
foldButton=new JButton ();
foldButton.setFont(new Font("Dialog", 1, 8));
foldButton.setPreferredSize(new Dimension (20,20));
foldButton.setMaximumSize(new Dimension (20,20));
foldButton.setIcon(HoopLink.getImageByName("tree-fold-icon.png"));
foldButton.addActionListener(this);
buttonBox.addComponent(foldButton);
refreshButton=new JButton ();
refreshButton.setFont(new Font("Dialog", 1, 8));
refreshButton.setPreferredSize(new Dimension (20,20));
refreshButton.setMaximumSize(new Dimension (20,20));
refreshButton.setIcon(HoopLink.getImageByName("gtk-refresh.png"));
refreshButton.addActionListener(this);
buttonBox.addComponent(refreshButton);
configureButton=new JButton ();
configureButton.setFont(new Font("Dialog", 1, 8));
configureButton.setPreferredSize(new Dimension (20,20));
configureButton.setMaximumSize(new Dimension (20,20));
configureButton.setIcon(HoopLink.getImageByName("gtk-preferences.png"));
configureButton.addActionListener(this);
buttonBox.addComponent(configureButton);
prevButton=new JButton ();
prevButton.setPreferredSize(new Dimension (20,20));
prevButton.setMaximumSize(new Dimension (20,20));
prevButton.setIcon(HoopLink.getImageByName("gtk-go-back-ltr.png"));
prevButton.addActionListener(this);
buttonBox.addComponent(prevButton);
JLabel startLabel=new JLabel ();
startLabel.setFont(new Font("Dialog", 1, 8));
startLabel.setText("From: ");
buttonBox.addComponent(startLabel);
startIndex=new JTextField ();
startIndex.setText(start.toString());
startIndex.setFont(new Font("Dialog", 1, 8));
startIndex.setPreferredSize(new Dimension (50,20));
startIndex.setMaximumSize(new Dimension (50,20));
buttonBox.addComponent(startIndex);
JLabel withLabel=new JLabel ();
withLabel.setFont(new Font("Dialog", 1, 8));
withLabel.setText("show: ");
buttonBox.addComponent(withLabel);
windowSize=new JTextField ();
windowSize.setText(maxShown.toString());
windowSize.setFont(new Font("Dialog", 1, 8));
windowSize.setPreferredSize(new Dimension (50,20));
windowSize.setMaximumSize(new Dimension (50,20));
buttonBox.addComponent(windowSize);
nextButton=new JButton ();
nextButton.setPreferredSize(new Dimension (20,20));
nextButton.setMaximumSize(new Dimension (20,20));
nextButton.setIcon(HoopLink.getImageByName("gtk-go-forward-ltr.png"));
nextButton.addActionListener(this);
buttonBox.addComponent(nextButton);
dbInfo=new JLabel ();
dbInfo.setFont(new Font("Dialog", 1, 8));
buttonBox.addComponent(dbInfo);
searchBox=new HoopButtonBox ();
searchBox.setMinimumSize(new Dimension (100,24));
searchBox.setPreferredSize(new Dimension (200,24));
searchBox.setMaximumSize(new Dimension (2000,24));
searchButton=new JButton ();
searchButton.setPreferredSize(new Dimension (20,20));
searchButton.setMaximumSize(new Dimension (20,20));
searchButton.setIcon(HoopLink.getImageByName("gtk-find-and-replace.png"));
searchButton.addActionListener(this);
searchBox.addComponent(searchButton);
sortButton=new JButton ();
sortButton.setPreferredSize(new Dimension (20,20));
sortButton.setMaximumSize(new Dimension (20,20));
sortButton.setIcon(HoopLink.getImageByName("alphab_sort_icon.png"));
sortButton.addActionListener(this);
searchBox.addComponent(sortButton);
rendererObject=new HoopDocumentListRenderer ();
docList=new JList<HoopKVDocument> ();
docList.setCellRenderer (rendererObject);
docList.addMouseListener(this);
JScrollPane docScrollList = new JScrollPane (docList);
docScrollList.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
holder.add (buttonBox);
holder.add (searchBox);
holder.add (docScrollList);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab ("Document View",
HoopLink.getImageByName("text_icon.png"),
holder,
"Document View");
//>-------------------------------------------------------
threadTree=new JTree ();
threadTree.setFont(new Font("Dialog", 1, 10)); // overwritten by cellrenderer?
threadTree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
threadTree.setRootVisible(false);
threadTree.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
threadTree.setDragEnabled(false);
threadTree.addMouseListener (this);
JScrollPane treeScroller=new JScrollPane (threadTree);
Box treeButtonBox = new Box (BoxLayout.X_AXIS);
treeExpandButton=new JButton ();
treeExpandButton.setFont(new Font("Dialog", 1, 8));
treeExpandButton.setPreferredSize(new Dimension (20,20));
treeExpandButton.setMaximumSize(new Dimension (20,20));
//treeExpandButton.setText("All");
treeExpandButton.setIcon(HoopLink.getImageByName("tree-expand-icon.png"));
treeExpandButton.addActionListener(this);
treeButtonBox.add (treeExpandButton);
treeButtonBox.add (Box.createRigidArea(new Dimension(2,0)));
treeFoldButton=new JButton ();
treeFoldButton.setFont(new Font("Dialog", 1, 8));
treeFoldButton.setPreferredSize(new Dimension (20,20));
treeFoldButton.setMaximumSize(new Dimension (20,20));
treeFoldButton.setIcon(HoopLink.getImageByName("tree-fold-icon.png"));
//treeFoldButton.setText("None");
treeFoldButton.addActionListener(this);
treeButtonBox.add (treeFoldButton);
treeButtonBox.add (Box.createRigidArea(new Dimension(2,0)));
treeButtonBox.add(Box.createHorizontalGlue());
JPanel treePanel=new JPanel ();
treePanel.setLayout(new BoxLayout (treePanel,BoxLayout.Y_AXIS));
treePanel.add (treeButtonBox);
treePanel.add (treeScroller);
tabbedPane.addTab ("Thread View",
HoopLink.getImageByName("tree.gif"),
treePanel,
"Thread View");
//>-------------------------------------------------------
setContentPane (tabbedPane);
updateContents(); // Just in case we already have something
}
/**
*
*/
public void reset ()
{
debug ("reset ()");
DefaultListModel<HoopKVDocument> mdl=new DefaultListModel<HoopKVDocument> ();
docList.setModel (mdl);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Threads");
root.setUserObject("Threads");
DefaultTreeModel model = new DefaultTreeModel(root);
threadTree.setModel(model);
rendererObject.reset ();
}
/**
*
*/
public void updateContents()
{
debug ("updateContents ()");
if (HoopLink.dataSet==null)
HoopLink.dataSet=new HoopDataSet ();
HoopLink.dataSet.checkDB();
debug ("Dataset checked, showing first entries in document list ...");
StoredMap<Long,HoopKVDocument> map=HoopLink.dataSet.getData();
if (map==null)
{
return;
}
DefaultListModel<HoopKVDocument> mdl=new DefaultListModel<HoopKVDocument> ();
debug ("There are currently " + map.size() + " entries available");
Integer sizeTransformer=map.size();
dbInfo.setText(sizeTransformer.toString()+" Entries");
Iterator<HoopKVDocument> iterator = map.values().iterator();
int index=0;
int count=maxShown;
if (map.size()<maxShown)
count=map.size ();
if (map!=null)
{
while ((iterator.hasNext()) && (index<count))
{
HoopKVDocument aDoc=(HoopKVDocument) iterator.next();
debug ("Adding document ...");
mdl.addElement(aDoc);
index++;
}
}
docList.setModel (mdl);
showDocumentThreads ();
}
/**
*
*/
private void showDocumentThreads ()
{
debug ("showDocumentThreads ()");
if (HoopLink.dataSet==null)
{
return;
}
StoredMap<Long,HoopKVLong> threadData=HoopLink.dataSet.getThreads();
if (threadData==null)
{
debug ("Error: no thread data available");
return;
}
StoredMap<Long,HoopKVDocument> map=HoopLink.dataSet.getData();
if (map==null)
{
debug ("Error: no document data available");
return;
}
Integer totalShown=maxShown;
int dSize=threadData.size();
if (dSize<totalShown)
totalShown=dSize;
debug ("Thread data size: " + dSize + " adjusted: " + totalShown);
Iterator<HoopKVLong> iterator = threadData.values().iterator();
int index=0;
int count=maxShown;
if (threadData.size()<maxShown)
count=threadData.size ();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Threads");
root.setUserObject("Threads");
DefaultTreeModel model = new DefaultTreeModel(root);
int totalDocumentSize=0;
while ((iterator.hasNext()) && (index<count))
{
HoopKVLong aThread=(HoopKVLong) iterator.next();
DefaultMutableTreeNode aNode=new DefaultMutableTreeNode (aThread.getKeyString ());
root.add(aNode);
ArrayList <Object> threadContents=aThread.getValuesRaw();
debug ("Thread with id " +aThread.getKeyString() + " has " + aThread.getValuesRaw().size() + " entries");
totalDocumentSize+=aThread.getValuesRaw().size();
for (int j=0;j<threadContents.size();j++)
{
String docID=(String) threadContents.get(j);
DefaultMutableTreeNode threadNode=new DefaultMutableTreeNode (docID);
aNode.add(threadNode);
}
index++;
}
debug ("There are a total of " + totalDocumentSize + " documents in the database");
threadTree.setModel(model);
}
/**
*
*/
@Override
public void actionPerformed(ActionEvent event)
{
debug ("actionPerformed ()");
//String act=event.getActionCommand();
JButton button = (JButton)event.getSource();
if (button==expandButton)
{
//TreeNode root<SUF>
//expandAll (tree, new TreePath(root));
}
if (button==foldButton)
{
//TreeNode root = (TreeNode) tree.getModel().getRoot();
//collapseAll (tree, new TreePath(root));
}
if (button==refreshButton)
{
updateContents();
}
if (button==configureButton)
{
//updateContents();
}
if (button==searchButton)
{
HoopSearch test=(HoopSearch) HoopLink.getWindow("Search");
if (test==null)
{
HoopLink.addView ("Search",new HoopSearch(),HoopLink.center);
test=(HoopSearch) HoopLink.getWindow("Search");
}
//test.showDocument(aDoc);
HoopLink.popWindow ("Search");
}
if (button==sortButton)
{
}
}
/**
*
*/
@Override
public void mouseClicked(MouseEvent event)
{
debug ("mouseClicked ()");
if (event.getSource()==threadTree)
{
debug ("Can't process thread tree double click yet");
}
else
{
if (event.getClickCount()==2)
{
int index = docList.locationToIndex(event.getPoint());
debug ("Double clicked on Item " + index);
HoopKVDocument aDoc=(HoopKVDocument) docList.getModel().getElementAt(index);
if (aDoc!=null)
{
HoopTextViewer test=(HoopTextViewer) HoopLink.getWindow("Text Viewer");
if (test==null)
{
HoopLink.addView ("Text Viewer",new HoopTextViewer(),HoopLink.center);
test=(HoopTextViewer) HoopLink.getWindow("Text Viewer");
}
test.showDocument(aDoc);
HoopLink.popWindow ("Text Viewer");
}
}
}
}
/**
*
*/
@Override
public void mouseEntered(MouseEvent arg0)
{
}
/**
*
*/
@Override
public void mouseExited(MouseEvent arg0)
{
}
/**
*
*/
@Override
public void mousePressed(MouseEvent arg0)
{
}
/**
*
*/
@Override
public void mouseReleased(MouseEvent arg0)
{
}
}
|
6488_1 | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.util.text;
import com.intellij.util.containers.CollectionFactory;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Set;
import static com.intellij.openapi.util.text.StringUtil.isVowel;
/**
* @author Bas Leijdekkers
*/
public final class PastParticiple {
private static final int IRREGULAR_SIZE = 175;
private static final Map<String, String> IRREGULAR_VERBS = CollectionFactory.createCaseInsensitiveStringMap(IRREGULAR_SIZE);
private static final int DOUBLED_SIZE = 444;
private static final Set<String> DOUBLED_FINAL_CONSONANTS = CollectionFactory.createCaseInsensitiveStringSet(DOUBLED_SIZE);
private static final String[] PREFIXES = {"be", "co", "de", "dis", "for", "fore", "inter", "mis", "out", "over", "pre", "re", "un", "under", "up"};
/**
* Generates past participle form of an English verb.
* E.g. hang -> hung, resolve -> resolved, add -> added, open -> opened
*
* @param verb verb in first person present form
* @return the past participle conjugation of the verb
*/
public static String pastParticiple(String verb) {
if (ignore(verb)) return verb;
String irregularVerb = getIrregularPastParticiple(verb);
if (irregularVerb != null) return Pluralizer.restoreCase(verb, irregularVerb);
String pastParticiple = getDoubledFinalConsonantPastParticiple(verb);
if (pastParticiple != null) return Pluralizer.restoreCase(verb, pastParticiple);
return Pluralizer.restoreCase(verb, generateHeuristicPastParticiple(verb));
}
private static String getDoubledFinalConsonantPastParticiple(String verb) {
String pastParticiple = generateHeuristicDoubledFinalConsonantPastParticiple(verb);
if (pastParticiple != null) return pastParticiple;
if (DOUBLED_FINAL_CONSONANTS.contains(verb)) return verb + verb.charAt(verb.length() - 1) + "ed";
for (String prefix : PREFIXES) {
if (verb.startsWith(prefix) && DOUBLED_FINAL_CONSONANTS.contains(verb.substring(prefix.length()))) {
return verb + verb.charAt(verb.length() - 1) + "ed";
}
}
return null;
}
private static @Nullable String generateHeuristicDoubledFinalConsonantPastParticiple(String verb) {
int length = verb.length();
if (length < 3) return null;
char c1 = toLowerCase(verb.charAt(length - 1));
if (c1 != 'x' && c1 != 'y' && c1 != 'w') {
char c2 = toLowerCase(verb.charAt(length - 2));
if (!isVowel(c1) && isVowel(c2)) {
char c3 = toLowerCase(verb.charAt(length - 3));
if (!isVowel(c3) || c3 == 'y') {
if (length == 3 || length == 4 && !isVowel(toLowerCase(verb.charAt(0))) ||
length == 5 && !isVowel(toLowerCase(verb.charAt(0))) && !isVowel(toLowerCase(verb.charAt(1)))) {
return verb + c1 + "ed";
}
}
else if (length > 3 && c3 == 'u' && toLowerCase(verb.charAt(length - 4)) == 'q') {
return verb + c1 + "ed";
}
}
}
return null;
}
private static String getIrregularPastParticiple(String verb) {
String irregularVerb = IRREGULAR_VERBS.get(verb);
if (irregularVerb != null) return irregularVerb;
for (String prefix : PREFIXES) {
if (verb.startsWith(prefix)) {
irregularVerb = IRREGULAR_VERBS.get(verb.substring(prefix.length()));
if (irregularVerb != null) return prefix + irregularVerb;
}
}
return null;
}
/**
* Uses heuristics to generate the past participle form of the specified English verb.
*
* @param verb verb in first person present form
* @return the past participle conjugation of the verb
*/
private static String generateHeuristicPastParticiple(String verb) {
int length = verb.length();
char c1 = toLowerCase(verb.charAt(length - 1));
if (c1 == 'e') return verb + 'd';
char c2 = toLowerCase(verb.charAt(length - 2));
if (c1 == 'y' && !isVowel(c2)) return verb.substring(0, length - 1) + "ied";
return c1 == 'c' && isVowel(c2) ? verb + "ked" : verb + "ed";
}
private static boolean ignore(String verb) {
int length = verb.length();
if (length < 2) return true;
if (verb.equals("of")) return true;
char c1 = toLowerCase(verb.charAt(length - 1));
char c2 = toLowerCase(verb.charAt(length - 2));
if (c1 == 's' && (c2 == 'e' || c2 == 'l')) return true;
for (int i = 0; i < length; i++) {
if (!isAsciiLetter(verb.charAt(i))) return true;
}
return false;
}
private static boolean isAsciiLetter(char c) {
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
private static char toLowerCase(char c) {
return (char)(c | 0x20); // cheap hack
}
static {
String[] irregularVerbs = new String[] {
"abide", "abode",
"arise", "arisen",
"awake", "awoken",
"be", "been",
"bear", "borne",
"beat", "beaten",
"begin", "begun",
"bend", "bent",
"bet", "bet",
"bid", "bid", // can also be "bidden"
"bind", "bound",
"bite", "bitten",
"bleed", "bled",
"blow", "blown",
"break", "broken",
"breed", "bred",
"bring", "brought",
"broadcast", "broadcast",
"build", "built",
"burn", "burnt",
"burst", "burst",
"bust", "bust",
"buy", "bought",
"can", "could",
"cast", "cast",
"catch", "caught",
"chide", "chidden",
"choose", "chosen",
"cling", "clung",
//"clothe", "clad",
"come", "come",
"cost", "cost",
"creep", "crept",
"cut", "cut",
"deal", "dealt",
"dig", "dug",
//"dive", "dove",
"do", "done",
"draw", "drawn",
"dream", "dreamt",
"drink", "drunk",
"drive", "driven",
//"dwell", "dwelt",
"eat", "eaten",
"fall", "fallen",
"feed", "fed",
"feel", "felt",
"fight", "fought",
"find", "found",
"flee", "fled",
"fling", "flung",
"fly", "flown",
"forbid", "forbidden",
"forsake", "forsaken",
"freeze", "frozen",
"get", "gotten",
"give", "given",
"grind", "ground",
"go", "gone",
"grow", "grown",
"hang", "hung",
"have", "had",
"hear", "heard",
"hide", "hidden",
"hit", "hit",
"hold", "held",
"hurt", "hurt",
"keep", "kept",
"kneel", "knelt",
"know", "known",
"lay", "laid",
"lead", "led",
//"lean", "leant",
//"leap", "leapt",
//"learn", "learnt",
"leave", "left",
"lend", "lent",
"let", "let",
//"lie", "lain", // depends on meaning
"light", "lit",
"lose", "lost",
"make", "made",
"mean", "meant",
"meet", "met",
"misunderstand", "misunderstood", // two prefixes!
"mow", "mown",
"offset", "offset",
"partake", "partaken",
"pay", "paid",
//"plead", "pled",
"prove", "proven",
"proofread", "proofread",
"put", "put",
"quit", "quit",
"read", "read",
"rend", "rent",
"rid", "rid",
"ride", "ridden",
"ring", "rung",
"rise", "risen",
"roughcast", "roughcast",
"run", "run",
//"saw", "sawn",
"say", "said",
"see", "seen",
"seek", "sought",
"sell", "sold",
"send", "sent",
"set", "set",
"sew", "sewn",
"shake", "shaken",
"shave", "shaven",
"shear", "shorn",
"shed", "shed",
"shine", "shone",
"shoe", "shod",
"shoot", "shot",
"show", "shown",
"shrink", "shrunk",
"shut", "shut",
"sing", "sung",
"sink", "sunk",
"sit", "sat",
"slay", "slain",
"sleep", "slept",
"slide", "slid",
"sling", "slung",
"slink", "slunk",
"slit", "slit",
//"smell", "smelt", // archaic
"sneak", "snuck",
"sow", "sown",
"speak", "spoken",
"speed", "sped",
//"spell", "spelt", // archaic
"spend", "spent",
"spill", "spilt",
"spin", "spun",
"spit", "spat",
"split", "split",
"spoil", "spoilt",
"spread", "spread",
"spring", "sprung",
"stand", "stood",
"steal", "stolen",
"stick", "stuck",
"sting", "stung",
"stink", "stunk",
"strew", "strewn",
"stride", "stridden",
"strike", "stricken", // "struck" when meaning is "hit" as well.
"string", "strung",
"strive", "striven",
"sublet", "sublet",
"swear", "sworn",
"sweat", "sweat",
"sweep", "swept",
"swell", "swollen",
"swim", "swum",
"swing", "swung",
"take", "taken",
"teach", "taught",
"tear", "torn",
"telecast", "telecast",
"tell", "told",
"think", "thought",
//"thrive", "thriven",
"throw", "thrown",
"thrust", "thrust",
"tread", "trodden",
"typecast", "typecast",
"typeset", "typeset",
"typewrite", "typewritten",
"underlie", "underlain",
"wake", "woken",
"waylay", "waylaid",
"wear", "worn",
"weave", "woven",
"weep", "wept",
"wet", "wet",
"win", "won",
"wind", "wound",
"withdraw", "withdrawn",
"withhold", "withheld",
"withstand", "withstood",
"wring", "wrung",
"write", "written"
};
assert irregularVerbs.length / 2 == IRREGULAR_SIZE;
for (int i = 0, length = irregularVerbs.length; i < length; i += 2) {
String present = irregularVerbs[i];
String pastParticiple = irregularVerbs[i + 1];
if (pastParticiple.equals(generateHeuristicPastParticiple(present))) {
throw new IllegalStateException("unnecessary entry: " + present);
}
if (IRREGULAR_VERBS.containsKey(present)) {
throw new IllegalStateException("duplicated entry: " + present);
}
IRREGULAR_VERBS.put(present, pastParticiple);
}
for (String irregularVerb : IRREGULAR_VERBS.keySet()) {
for (String prefix : PREFIXES) {
if (IRREGULAR_VERBS.containsKey(prefix + irregularVerb) &&
IRREGULAR_VERBS.get(prefix + irregularVerb).equals(prefix + IRREGULAR_VERBS.get(irregularVerb))) {
throw new IllegalStateException("unnecessary prefix entry: " + prefix + irregularVerb);
}
}
}
String[] doubledFinalConsonants =
new String[]{"abet", "abhor", "abut", "adlib", "admit", "aerobat", "aerosol", "airdrop", "allot", "anagram", "annul", "appal",
"apparel", "armbar", "aver", "babysit", "backdrop", "backflip", "backlog", "backpedal", "backslap", "backstab", "ballot", "barbel",
"bareleg", "barrel", "bayonet", "befit", "befog", "benefit", "besot", "bestir", "bevel", "bewig", "billet", "bitmap", "blackleg",
"bloodlet", "bobsled", "bodypop", "boobytrap", "bootleg", "bowel", "bracket", "buffet", "bullshit", "cabal", "cancel", "caracol",
"caravan", "carburet", "carnap", "carol", "carpetbag", "castanet", "catnap", "cavil", "chanel", "channel", "chargecap", "chirrup",
"chisel", "clearcut", "clodhop", "closet", "cobweb", "coif", "combat", "commit", "compel", "concur", "confab", "confer", "control",
"coral", "corbel", "corral", "cosset", "costar", "councel", "council", "counsel", "counterplot", "courtmartial", "crossleg",
"cudgel", "daysit", "deadpan", "debag", "debar", "debug", "defer", "defog", "degas", "demit", "demob", "demur", "denet", "depig",
"depip", "depit", "derig", "deter", "devil", "diagram", "dial", "disbar", "disbud", "discomfit", "disembowel", "dishevel", "dispel",
"distil", "dognap", "doorstep", "dowel", "driftnet", "drivel", "duel", "dybbuk", "earwig", "eavesdrop", "ecolabel", "egotrip",
"electroblot", "embed", "emit", "empanel", "enamel", "enrol", "enthral", "entrammel", "entrap", "enwrap", "estop", "excel", "expel",
"extol", "farewel", "featherbed", "fingertip", "focus", "footslog", "format", "foxtrot", "fuel", "fulfil", "fullyfit", "funnel",
"gambol", "garrot", "giftwrap", "gimbal", "globetrot", "goldpan", "golliwog", "goosestep", "gossip", "gravel", "groundhop",
"grovel", "gunrun", "haircut", "handbag", "handicap", "handknit", "handset", "hareleg", "hedgehop", "hiccup", "hobnob", "horsewhip",
"hostel", "hotdog", "hovel", "humbug", "hushkit", "illfit", "imbed", "immunoblot", "impel", "imperil", "incur", "infer", "initial",
"input", "inset", "inspan", "instal", "instil", "inter", "interbed", "intercrop", "intermit", "interwar",
"japan", "jawdrop", "jetlag", "jewel", "jitterbug", "jogtrot", "kennel", "kidnap", "kissogram", "kneecap", "label", "lavel",
"leafcut", "leapfrog", "level", "libel", "lollop", "longleg", "mackerel", "mahom", "manumit", "marshal", "marvel", "matchwin",
"metal", "microplan", "microprogram", "milksop", "misclub", "model", "monogram", "multilevel", "nightclub", "nightsit", "nonplus",
"nutmeg", "occur", "offput", "omit", "onlap", "outcrop", "outfit", "outgas", "outgeneral", "outgun", "outjab", "outplan", "outship",
"outshop", "outsin", "outspan", "outstrip", "outwit", "overcrap", "overcrop", "overdub", "overfit", "overhat", "overlap", "overman",
"overpet", "overplot", "overshop", "overstep", "overtip", "overtop", "panel", "paperclip", "parallel", "parcel", "patrol", "pedal",
"peewit", "pencil", "permit", "petal", "pettifog", "photoset", "photostat", "phototypeset", "picket", "pilot", "pipefit", "pipet",
"plummet", "policyset", "ponytrek", "pouf", "prebag", "prefer", "preplan", "prizewin", "profer", "program", "propel", "pummel",
"pushfit", "quarrel", "quickskim", "quickstep", "quickwit", "quivertip", "rabbit", "radiolabel", "ramrod", "ratecap", "ravel",
"rebel", "rebin", "rebut", "recap", "recrop", "recur", "refer", "refit", "reflag", "refret", "regret", "rehab", "rejig", "rekit",
"reknot", "relap", "remap", "remit", "repastel", "repel", "repin", "replan", "replot", "replug", "repol", "repot", "rerig",
"reskin", "retop", "retrim", "retrofit", "revel", "revet", "rewrap", "ricochet", "ringlet", "rival", "rivet", "roadrun", "rocket",
"roset", "rosin", "rowel", "runnel", "sandbag", "scalpel", "schlep", "semicontrol", "semiskim", "sentinel", "shopfit", "shovel",
"shrinkwrap", "shrivel", "sideslip", "sidestep", "signal", "sinbin", "slowclap", "snivel", "snorkel", "softpedal", "spiderweb",
"spiral", "spraygun", "springtip", "squirrel", "stencil", "subcrop", "submit", "subset", "suedetrim", "sulfuret", "summit",
"suntan", "swivel", "tassel", "teleshop", "tendril", "thermal", "thermostat", "tightlip", "tinsel", "tittup", "toecap", "tomorrow",
"total", "towel", "traget", "trainspot", "trammel", "transfer", "transit", "transmit", "transship", "travel", "trendset", "trepan",
"tripod", "trousseaushop", "trowel", "tunnel", "unban", "unbar", "unbob", "uncap", "unclip", "undam", "underfit", "underman",
"underpin", "unfit", "unknot", "unlip", "unman", "unpad", "unpeg", "unpin", "unplug", "unrip", "unsnap", "unstep", "unstir",
"unstop", "untap", "unwrap", "unzip", "up", "verbal", "victual", "wainscot", "waterlog", "weasel", "whiteskin", "wildcat",
"wiretap", "woodchop", "woodcut", "worship", "yarnspin", "yodel", "zigzag"};
assert doubledFinalConsonants.length == DOUBLED_SIZE;
for (String verb : doubledFinalConsonants) {
int length = verb.length();
char lastLetter = verb.charAt(length - 1);
if (isVowel(lastLetter) || verb.charAt(length - 2) == lastLetter) {
throw new IllegalStateException("incorrect entry: " + verb);
}
if (getIrregularPastParticiple(verb) != null) {
throw new IllegalStateException("irregular verb: " + verb);
}
String pastParticiple = verb + lastLetter + "ed";
if (pastParticiple.equals(generateHeuristicPastParticiple(verb)) ||
pastParticiple.equals(getDoubledFinalConsonantPastParticiple(verb))) {
throw new IllegalStateException("unnecessary entry: " + verb);
}
if (pastParticiple(verb).equals(pastParticiple)) {
throw new IllegalStateException("duplicated entry: " + verb);
}
if (!DOUBLED_FINAL_CONSONANTS.add(verb)) {
throw new IllegalStateException("duplicate entry: " + verb);
}
}
for (String word : DOUBLED_FINAL_CONSONANTS) {
for (String prefix : PREFIXES) {
if (DOUBLED_FINAL_CONSONANTS.contains(prefix + word)) {
throw new IllegalStateException("unnecessary prefix entry: " + prefix + word);
}
}
}
}
}
| Mindula-Dilthushan/intellij-community | platform/util/src/com/intellij/openapi/util/text/PastParticiple.java | 6,449 | /**
* @author Bas Leijdekkers
*/ | block_comment | nl | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.util.text;
import com.intellij.util.containers.CollectionFactory;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Set;
import static com.intellij.openapi.util.text.StringUtil.isVowel;
/**
* @author Bas Leijdekkers<SUF>*/
public final class PastParticiple {
private static final int IRREGULAR_SIZE = 175;
private static final Map<String, String> IRREGULAR_VERBS = CollectionFactory.createCaseInsensitiveStringMap(IRREGULAR_SIZE);
private static final int DOUBLED_SIZE = 444;
private static final Set<String> DOUBLED_FINAL_CONSONANTS = CollectionFactory.createCaseInsensitiveStringSet(DOUBLED_SIZE);
private static final String[] PREFIXES = {"be", "co", "de", "dis", "for", "fore", "inter", "mis", "out", "over", "pre", "re", "un", "under", "up"};
/**
* Generates past participle form of an English verb.
* E.g. hang -> hung, resolve -> resolved, add -> added, open -> opened
*
* @param verb verb in first person present form
* @return the past participle conjugation of the verb
*/
public static String pastParticiple(String verb) {
if (ignore(verb)) return verb;
String irregularVerb = getIrregularPastParticiple(verb);
if (irregularVerb != null) return Pluralizer.restoreCase(verb, irregularVerb);
String pastParticiple = getDoubledFinalConsonantPastParticiple(verb);
if (pastParticiple != null) return Pluralizer.restoreCase(verb, pastParticiple);
return Pluralizer.restoreCase(verb, generateHeuristicPastParticiple(verb));
}
private static String getDoubledFinalConsonantPastParticiple(String verb) {
String pastParticiple = generateHeuristicDoubledFinalConsonantPastParticiple(verb);
if (pastParticiple != null) return pastParticiple;
if (DOUBLED_FINAL_CONSONANTS.contains(verb)) return verb + verb.charAt(verb.length() - 1) + "ed";
for (String prefix : PREFIXES) {
if (verb.startsWith(prefix) && DOUBLED_FINAL_CONSONANTS.contains(verb.substring(prefix.length()))) {
return verb + verb.charAt(verb.length() - 1) + "ed";
}
}
return null;
}
private static @Nullable String generateHeuristicDoubledFinalConsonantPastParticiple(String verb) {
int length = verb.length();
if (length < 3) return null;
char c1 = toLowerCase(verb.charAt(length - 1));
if (c1 != 'x' && c1 != 'y' && c1 != 'w') {
char c2 = toLowerCase(verb.charAt(length - 2));
if (!isVowel(c1) && isVowel(c2)) {
char c3 = toLowerCase(verb.charAt(length - 3));
if (!isVowel(c3) || c3 == 'y') {
if (length == 3 || length == 4 && !isVowel(toLowerCase(verb.charAt(0))) ||
length == 5 && !isVowel(toLowerCase(verb.charAt(0))) && !isVowel(toLowerCase(verb.charAt(1)))) {
return verb + c1 + "ed";
}
}
else if (length > 3 && c3 == 'u' && toLowerCase(verb.charAt(length - 4)) == 'q') {
return verb + c1 + "ed";
}
}
}
return null;
}
private static String getIrregularPastParticiple(String verb) {
String irregularVerb = IRREGULAR_VERBS.get(verb);
if (irregularVerb != null) return irregularVerb;
for (String prefix : PREFIXES) {
if (verb.startsWith(prefix)) {
irregularVerb = IRREGULAR_VERBS.get(verb.substring(prefix.length()));
if (irregularVerb != null) return prefix + irregularVerb;
}
}
return null;
}
/**
* Uses heuristics to generate the past participle form of the specified English verb.
*
* @param verb verb in first person present form
* @return the past participle conjugation of the verb
*/
private static String generateHeuristicPastParticiple(String verb) {
int length = verb.length();
char c1 = toLowerCase(verb.charAt(length - 1));
if (c1 == 'e') return verb + 'd';
char c2 = toLowerCase(verb.charAt(length - 2));
if (c1 == 'y' && !isVowel(c2)) return verb.substring(0, length - 1) + "ied";
return c1 == 'c' && isVowel(c2) ? verb + "ked" : verb + "ed";
}
private static boolean ignore(String verb) {
int length = verb.length();
if (length < 2) return true;
if (verb.equals("of")) return true;
char c1 = toLowerCase(verb.charAt(length - 1));
char c2 = toLowerCase(verb.charAt(length - 2));
if (c1 == 's' && (c2 == 'e' || c2 == 'l')) return true;
for (int i = 0; i < length; i++) {
if (!isAsciiLetter(verb.charAt(i))) return true;
}
return false;
}
private static boolean isAsciiLetter(char c) {
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
private static char toLowerCase(char c) {
return (char)(c | 0x20); // cheap hack
}
static {
String[] irregularVerbs = new String[] {
"abide", "abode",
"arise", "arisen",
"awake", "awoken",
"be", "been",
"bear", "borne",
"beat", "beaten",
"begin", "begun",
"bend", "bent",
"bet", "bet",
"bid", "bid", // can also be "bidden"
"bind", "bound",
"bite", "bitten",
"bleed", "bled",
"blow", "blown",
"break", "broken",
"breed", "bred",
"bring", "brought",
"broadcast", "broadcast",
"build", "built",
"burn", "burnt",
"burst", "burst",
"bust", "bust",
"buy", "bought",
"can", "could",
"cast", "cast",
"catch", "caught",
"chide", "chidden",
"choose", "chosen",
"cling", "clung",
//"clothe", "clad",
"come", "come",
"cost", "cost",
"creep", "crept",
"cut", "cut",
"deal", "dealt",
"dig", "dug",
//"dive", "dove",
"do", "done",
"draw", "drawn",
"dream", "dreamt",
"drink", "drunk",
"drive", "driven",
//"dwell", "dwelt",
"eat", "eaten",
"fall", "fallen",
"feed", "fed",
"feel", "felt",
"fight", "fought",
"find", "found",
"flee", "fled",
"fling", "flung",
"fly", "flown",
"forbid", "forbidden",
"forsake", "forsaken",
"freeze", "frozen",
"get", "gotten",
"give", "given",
"grind", "ground",
"go", "gone",
"grow", "grown",
"hang", "hung",
"have", "had",
"hear", "heard",
"hide", "hidden",
"hit", "hit",
"hold", "held",
"hurt", "hurt",
"keep", "kept",
"kneel", "knelt",
"know", "known",
"lay", "laid",
"lead", "led",
//"lean", "leant",
//"leap", "leapt",
//"learn", "learnt",
"leave", "left",
"lend", "lent",
"let", "let",
//"lie", "lain", // depends on meaning
"light", "lit",
"lose", "lost",
"make", "made",
"mean", "meant",
"meet", "met",
"misunderstand", "misunderstood", // two prefixes!
"mow", "mown",
"offset", "offset",
"partake", "partaken",
"pay", "paid",
//"plead", "pled",
"prove", "proven",
"proofread", "proofread",
"put", "put",
"quit", "quit",
"read", "read",
"rend", "rent",
"rid", "rid",
"ride", "ridden",
"ring", "rung",
"rise", "risen",
"roughcast", "roughcast",
"run", "run",
//"saw", "sawn",
"say", "said",
"see", "seen",
"seek", "sought",
"sell", "sold",
"send", "sent",
"set", "set",
"sew", "sewn",
"shake", "shaken",
"shave", "shaven",
"shear", "shorn",
"shed", "shed",
"shine", "shone",
"shoe", "shod",
"shoot", "shot",
"show", "shown",
"shrink", "shrunk",
"shut", "shut",
"sing", "sung",
"sink", "sunk",
"sit", "sat",
"slay", "slain",
"sleep", "slept",
"slide", "slid",
"sling", "slung",
"slink", "slunk",
"slit", "slit",
//"smell", "smelt", // archaic
"sneak", "snuck",
"sow", "sown",
"speak", "spoken",
"speed", "sped",
//"spell", "spelt", // archaic
"spend", "spent",
"spill", "spilt",
"spin", "spun",
"spit", "spat",
"split", "split",
"spoil", "spoilt",
"spread", "spread",
"spring", "sprung",
"stand", "stood",
"steal", "stolen",
"stick", "stuck",
"sting", "stung",
"stink", "stunk",
"strew", "strewn",
"stride", "stridden",
"strike", "stricken", // "struck" when meaning is "hit" as well.
"string", "strung",
"strive", "striven",
"sublet", "sublet",
"swear", "sworn",
"sweat", "sweat",
"sweep", "swept",
"swell", "swollen",
"swim", "swum",
"swing", "swung",
"take", "taken",
"teach", "taught",
"tear", "torn",
"telecast", "telecast",
"tell", "told",
"think", "thought",
//"thrive", "thriven",
"throw", "thrown",
"thrust", "thrust",
"tread", "trodden",
"typecast", "typecast",
"typeset", "typeset",
"typewrite", "typewritten",
"underlie", "underlain",
"wake", "woken",
"waylay", "waylaid",
"wear", "worn",
"weave", "woven",
"weep", "wept",
"wet", "wet",
"win", "won",
"wind", "wound",
"withdraw", "withdrawn",
"withhold", "withheld",
"withstand", "withstood",
"wring", "wrung",
"write", "written"
};
assert irregularVerbs.length / 2 == IRREGULAR_SIZE;
for (int i = 0, length = irregularVerbs.length; i < length; i += 2) {
String present = irregularVerbs[i];
String pastParticiple = irregularVerbs[i + 1];
if (pastParticiple.equals(generateHeuristicPastParticiple(present))) {
throw new IllegalStateException("unnecessary entry: " + present);
}
if (IRREGULAR_VERBS.containsKey(present)) {
throw new IllegalStateException("duplicated entry: " + present);
}
IRREGULAR_VERBS.put(present, pastParticiple);
}
for (String irregularVerb : IRREGULAR_VERBS.keySet()) {
for (String prefix : PREFIXES) {
if (IRREGULAR_VERBS.containsKey(prefix + irregularVerb) &&
IRREGULAR_VERBS.get(prefix + irregularVerb).equals(prefix + IRREGULAR_VERBS.get(irregularVerb))) {
throw new IllegalStateException("unnecessary prefix entry: " + prefix + irregularVerb);
}
}
}
String[] doubledFinalConsonants =
new String[]{"abet", "abhor", "abut", "adlib", "admit", "aerobat", "aerosol", "airdrop", "allot", "anagram", "annul", "appal",
"apparel", "armbar", "aver", "babysit", "backdrop", "backflip", "backlog", "backpedal", "backslap", "backstab", "ballot", "barbel",
"bareleg", "barrel", "bayonet", "befit", "befog", "benefit", "besot", "bestir", "bevel", "bewig", "billet", "bitmap", "blackleg",
"bloodlet", "bobsled", "bodypop", "boobytrap", "bootleg", "bowel", "bracket", "buffet", "bullshit", "cabal", "cancel", "caracol",
"caravan", "carburet", "carnap", "carol", "carpetbag", "castanet", "catnap", "cavil", "chanel", "channel", "chargecap", "chirrup",
"chisel", "clearcut", "clodhop", "closet", "cobweb", "coif", "combat", "commit", "compel", "concur", "confab", "confer", "control",
"coral", "corbel", "corral", "cosset", "costar", "councel", "council", "counsel", "counterplot", "courtmartial", "crossleg",
"cudgel", "daysit", "deadpan", "debag", "debar", "debug", "defer", "defog", "degas", "demit", "demob", "demur", "denet", "depig",
"depip", "depit", "derig", "deter", "devil", "diagram", "dial", "disbar", "disbud", "discomfit", "disembowel", "dishevel", "dispel",
"distil", "dognap", "doorstep", "dowel", "driftnet", "drivel", "duel", "dybbuk", "earwig", "eavesdrop", "ecolabel", "egotrip",
"electroblot", "embed", "emit", "empanel", "enamel", "enrol", "enthral", "entrammel", "entrap", "enwrap", "estop", "excel", "expel",
"extol", "farewel", "featherbed", "fingertip", "focus", "footslog", "format", "foxtrot", "fuel", "fulfil", "fullyfit", "funnel",
"gambol", "garrot", "giftwrap", "gimbal", "globetrot", "goldpan", "golliwog", "goosestep", "gossip", "gravel", "groundhop",
"grovel", "gunrun", "haircut", "handbag", "handicap", "handknit", "handset", "hareleg", "hedgehop", "hiccup", "hobnob", "horsewhip",
"hostel", "hotdog", "hovel", "humbug", "hushkit", "illfit", "imbed", "immunoblot", "impel", "imperil", "incur", "infer", "initial",
"input", "inset", "inspan", "instal", "instil", "inter", "interbed", "intercrop", "intermit", "interwar",
"japan", "jawdrop", "jetlag", "jewel", "jitterbug", "jogtrot", "kennel", "kidnap", "kissogram", "kneecap", "label", "lavel",
"leafcut", "leapfrog", "level", "libel", "lollop", "longleg", "mackerel", "mahom", "manumit", "marshal", "marvel", "matchwin",
"metal", "microplan", "microprogram", "milksop", "misclub", "model", "monogram", "multilevel", "nightclub", "nightsit", "nonplus",
"nutmeg", "occur", "offput", "omit", "onlap", "outcrop", "outfit", "outgas", "outgeneral", "outgun", "outjab", "outplan", "outship",
"outshop", "outsin", "outspan", "outstrip", "outwit", "overcrap", "overcrop", "overdub", "overfit", "overhat", "overlap", "overman",
"overpet", "overplot", "overshop", "overstep", "overtip", "overtop", "panel", "paperclip", "parallel", "parcel", "patrol", "pedal",
"peewit", "pencil", "permit", "petal", "pettifog", "photoset", "photostat", "phototypeset", "picket", "pilot", "pipefit", "pipet",
"plummet", "policyset", "ponytrek", "pouf", "prebag", "prefer", "preplan", "prizewin", "profer", "program", "propel", "pummel",
"pushfit", "quarrel", "quickskim", "quickstep", "quickwit", "quivertip", "rabbit", "radiolabel", "ramrod", "ratecap", "ravel",
"rebel", "rebin", "rebut", "recap", "recrop", "recur", "refer", "refit", "reflag", "refret", "regret", "rehab", "rejig", "rekit",
"reknot", "relap", "remap", "remit", "repastel", "repel", "repin", "replan", "replot", "replug", "repol", "repot", "rerig",
"reskin", "retop", "retrim", "retrofit", "revel", "revet", "rewrap", "ricochet", "ringlet", "rival", "rivet", "roadrun", "rocket",
"roset", "rosin", "rowel", "runnel", "sandbag", "scalpel", "schlep", "semicontrol", "semiskim", "sentinel", "shopfit", "shovel",
"shrinkwrap", "shrivel", "sideslip", "sidestep", "signal", "sinbin", "slowclap", "snivel", "snorkel", "softpedal", "spiderweb",
"spiral", "spraygun", "springtip", "squirrel", "stencil", "subcrop", "submit", "subset", "suedetrim", "sulfuret", "summit",
"suntan", "swivel", "tassel", "teleshop", "tendril", "thermal", "thermostat", "tightlip", "tinsel", "tittup", "toecap", "tomorrow",
"total", "towel", "traget", "trainspot", "trammel", "transfer", "transit", "transmit", "transship", "travel", "trendset", "trepan",
"tripod", "trousseaushop", "trowel", "tunnel", "unban", "unbar", "unbob", "uncap", "unclip", "undam", "underfit", "underman",
"underpin", "unfit", "unknot", "unlip", "unman", "unpad", "unpeg", "unpin", "unplug", "unrip", "unsnap", "unstep", "unstir",
"unstop", "untap", "unwrap", "unzip", "up", "verbal", "victual", "wainscot", "waterlog", "weasel", "whiteskin", "wildcat",
"wiretap", "woodchop", "woodcut", "worship", "yarnspin", "yodel", "zigzag"};
assert doubledFinalConsonants.length == DOUBLED_SIZE;
for (String verb : doubledFinalConsonants) {
int length = verb.length();
char lastLetter = verb.charAt(length - 1);
if (isVowel(lastLetter) || verb.charAt(length - 2) == lastLetter) {
throw new IllegalStateException("incorrect entry: " + verb);
}
if (getIrregularPastParticiple(verb) != null) {
throw new IllegalStateException("irregular verb: " + verb);
}
String pastParticiple = verb + lastLetter + "ed";
if (pastParticiple.equals(generateHeuristicPastParticiple(verb)) ||
pastParticiple.equals(getDoubledFinalConsonantPastParticiple(verb))) {
throw new IllegalStateException("unnecessary entry: " + verb);
}
if (pastParticiple(verb).equals(pastParticiple)) {
throw new IllegalStateException("duplicated entry: " + verb);
}
if (!DOUBLED_FINAL_CONSONANTS.add(verb)) {
throw new IllegalStateException("duplicate entry: " + verb);
}
}
for (String word : DOUBLED_FINAL_CONSONANTS) {
for (String prefix : PREFIXES) {
if (DOUBLED_FINAL_CONSONANTS.contains(prefix + word)) {
throw new IllegalStateException("unnecessary prefix entry: " + prefix + word);
}
}
}
}
}
|
48566_1 | /*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.*;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModDiscoverer;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModValidator;
import net.minecraftforge.accesstransformer.service.AccessTransformerService;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.loading.targets.CommonLaunchHandler;
import net.minecraftforge.forgespi.Environment;
import net.minecraftforge.forgespi.coremod.ICoreModProvider;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.BiFunction;
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
public class FMLLoader {
private static final Logger LOGGER = LogUtils.getLogger();
private static AccessTransformerService accessTransformer;
private static ModDiscoverer modDiscoverer;
private static ICoreModProvider coreModProvider;
private static LanguageLoadingProvider languageLoadingProvider;
private static Dist dist;
private static String naming;
private static LoadingModList loadingModList;
private static RuntimeDistCleaner runtimeDistCleaner;
private static Path gamePath;
private static final VersionInfo versionInfo = VersionInfo.detect();
private static String launchHandlerName;
private static CommonLaunchHandler commonLaunchHandler;
public static Runnable progressWindowTick;
private static ModValidator modValidator;
public static BackgroundScanHandler backgroundScanHandler;
private static boolean production;
private static IModuleLayerManager moduleLayerManager;
static void onInitialLoad(IEnvironment env, Set<String> otherServices) throws IncompatibleEnvironmentException {
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner");
coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod");
LOGGER.debug(CORE,"FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING"));
checkPackage(Environment.class, "2.0", "ForgeSPI");
try {
Class.forName("com.electronwill.nightconfig.core.Config", false, env.getClass().getClassLoader());
Class.forName("com.electronwill.nightconfig.toml.TomlFormat", false, env.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
LOGGER.error(CORE, "Failed to load NightConfig");
throw new IncompatibleEnvironmentException("Missing NightConfig");
}
}
private static <T> T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException {
@SuppressWarnings("unchecked")
var plugin = (T)env.findLaunchPlugin(id).orElseThrow(() -> {
LOGGER.error(CORE, "{} library is missing, we need this to run", name);
return new IncompatibleEnvironmentException("Missing " + name + ", cannot run");
});
checkPackage(plugin.getClass(), version, name);
return plugin;
}
private static void checkPackage(Class<?> cls, String version, String name) throws IncompatibleEnvironmentException {
var pkg = cls.getPackage();
var info = JarVersionLookupHandler.getInfo(pkg);
LOGGER.debug(CORE, "Found {} version: {}", name, info.impl().version().orElse("MISSING"));
if (!pkg.isCompatibleWith(version)) {
LOGGER.error(CORE, "Found incompatible {} specification: {}, version {} from {}", name,
info.spec().version().orElse("MISSING"),
info.impl().version().orElse("MISSING"),
info.impl().vendor().orElse("MISSING")
);
throw new IncompatibleEnvironmentException("Incompatible " + name + " found " + info.spec().version().orElse("MISSING"));
}
}
private static <T> T getSingleService(Class<T> clazz, String name) throws IncompatibleEnvironmentException {
var providers = new ArrayList<T>();
for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) {
try {
providers.add(itr.next());
} catch (ServiceConfigurationError e) {
LOGGER.error(CORE, "Failed to load a " + name + " library, expect problems", e);
}
}
if (providers.isEmpty()) {
LOGGER.error(CORE, "Found no {} provider. Cannot run", name);
throw new IncompatibleEnvironmentException("No " + name + " library found");
} else if (providers.size() > 1) {
LOGGER.error(CORE, "Found multiple {} providers: {}. Cannot run", name, providers.stream().map(p -> p.getClass().getName()).toList());
throw new IncompatibleEnvironmentException("Multiple " + name + " libraries found");
}
return providers.get(0);
}
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget);
final Optional<ILaunchHandlerService> launchHandler = environment.findLaunchHandler(launchTarget);
LOGGER.debug(CORE, "Using {} as launch service", launchTarget);
if (launchHandler.isEmpty()) {
LOGGER.error(CORE, "Missing LaunchHandler {}, cannot continue", launchTarget);
throw new RuntimeException("Missing launch handler: " + launchTarget);
}
// TODO: [FML][Loader] What the fuck is the point of using a service if you require a specific concrete class
if (!(launchHandler.get() instanceof CommonLaunchHandler)) {
LOGGER.error(CORE, "Incompatible Launch handler found - type {}, cannot continue", launchHandler.get().getClass().getName());
throw new RuntimeException("Incompatible launch handler found");
}
commonLaunchHandler = (CommonLaunchHandler)launchHandler.get();
launchHandlerName = launchHandler.get().name();
gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Paths.get(".").toAbsolutePath());
naming = commonLaunchHandler.getNaming();
dist = commonLaunchHandler.getDist();
production = commonLaunchHandler.isProduction();
accessTransformer.getExtension().accept(Pair.of(naming, "srg"));
runtimeDistCleaner.getExtension().accept(dist);
}
public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) {
LOGGER.debug(SCAN,"Scanning for Mod Locators");
modDiscoverer = new ModDiscoverer(arguments);
modValidator = modDiscoverer.discoverMods();
var pluginResources = modValidator.getPluginResources();
return List.of(pluginResources);
}
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
moduleLayerManager = layerManager;
languageLoadingProvider = new LanguageLoadingProvider();
backgroundScanHandler = modValidator.stage2Validation();
loadingModList = backgroundScanHandler.getLoadingModList();
return List.of(modValidator.getModResources());
}
public static ICoreModProvider getCoreModProvider() {
return coreModProvider;
}
public static LanguageLoadingProvider getLanguageLoadingProvider() {
return languageLoadingProvider;
}
static ModDiscoverer getModDiscoverer() {
return modDiscoverer;
}
public static CommonLaunchHandler getLaunchHandler() {
return commonLaunchHandler;
}
public static void addAccessTransformer(Path atPath, ModFile modName) {
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName());
}
public static Dist getDist() {
return dist;
}
public static void beforeStart(ModuleLayer gameLayer) {
ImmediateWindowHandler.acceptGameLayer(gameLayer);
ImmediateWindowHandler.updateProgress("Launching minecraft");
progressWindowTick.run();
}
public static LoadingModList getLoadingModList() {
return loadingModList;
}
public static Path getGamePath() {
return gamePath;
}
public static String getNaming() {
return naming;
}
public static Optional<BiFunction<INameMappingService.Domain, String, String>> getNameFunction(final String naming) {
return Launcher.INSTANCE.environment().findNameMapping(naming);
}
public static String getLauncherInfo() {
return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MLIMPL_VERSION.get()).orElse("MISSING");
}
public static List<Map<String, String>> modLauncherModList() {
return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MODLIST.get()).orElse(List.of());
}
public static String launcherHandlerName() {
return launchHandlerName;
}
public static boolean isProduction() {
return production;
}
public static boolean isSecureJarEnabled() {
return true;
}
public static ModuleLayer getGameLayer() {
return moduleLayerManager.getLayer(IModuleLayerManager.Layer.GAME).orElseThrow();
}
public static VersionInfo versionInfo() {
return versionInfo;
}
}
| MinecraftForge/MinecraftForge | fmlloader/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java | 2,910 | /*eventBus =*/ | block_comment | nl | /*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.*;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModDiscoverer;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModValidator;
import net.minecraftforge.accesstransformer.service.AccessTransformerService;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.loading.targets.CommonLaunchHandler;
import net.minecraftforge.forgespi.Environment;
import net.minecraftforge.forgespi.coremod.ICoreModProvider;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.BiFunction;
import static net.minecraftforge.fml.loading.LogMarkers.CORE;
import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
public class FMLLoader {
private static final Logger LOGGER = LogUtils.getLogger();
private static AccessTransformerService accessTransformer;
private static ModDiscoverer modDiscoverer;
private static ICoreModProvider coreModProvider;
private static LanguageLoadingProvider languageLoadingProvider;
private static Dist dist;
private static String naming;
private static LoadingModList loadingModList;
private static RuntimeDistCleaner runtimeDistCleaner;
private static Path gamePath;
private static final VersionInfo versionInfo = VersionInfo.detect();
private static String launchHandlerName;
private static CommonLaunchHandler commonLaunchHandler;
public static Runnable progressWindowTick;
private static ModValidator modValidator;
public static BackgroundScanHandler backgroundScanHandler;
private static boolean production;
private static IModuleLayerManager moduleLayerManager;
static void onInitialLoad(IEnvironment env, Set<String> otherServices) throws IncompatibleEnvironmentException {
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
/*eventBus <SUF>*/ getPlugin(env, "eventbus", "1.0", "EventBus");
runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner");
coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod");
LOGGER.debug(CORE,"FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING"));
checkPackage(Environment.class, "2.0", "ForgeSPI");
try {
Class.forName("com.electronwill.nightconfig.core.Config", false, env.getClass().getClassLoader());
Class.forName("com.electronwill.nightconfig.toml.TomlFormat", false, env.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
LOGGER.error(CORE, "Failed to load NightConfig");
throw new IncompatibleEnvironmentException("Missing NightConfig");
}
}
private static <T> T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException {
@SuppressWarnings("unchecked")
var plugin = (T)env.findLaunchPlugin(id).orElseThrow(() -> {
LOGGER.error(CORE, "{} library is missing, we need this to run", name);
return new IncompatibleEnvironmentException("Missing " + name + ", cannot run");
});
checkPackage(plugin.getClass(), version, name);
return plugin;
}
private static void checkPackage(Class<?> cls, String version, String name) throws IncompatibleEnvironmentException {
var pkg = cls.getPackage();
var info = JarVersionLookupHandler.getInfo(pkg);
LOGGER.debug(CORE, "Found {} version: {}", name, info.impl().version().orElse("MISSING"));
if (!pkg.isCompatibleWith(version)) {
LOGGER.error(CORE, "Found incompatible {} specification: {}, version {} from {}", name,
info.spec().version().orElse("MISSING"),
info.impl().version().orElse("MISSING"),
info.impl().vendor().orElse("MISSING")
);
throw new IncompatibleEnvironmentException("Incompatible " + name + " found " + info.spec().version().orElse("MISSING"));
}
}
private static <T> T getSingleService(Class<T> clazz, String name) throws IncompatibleEnvironmentException {
var providers = new ArrayList<T>();
for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) {
try {
providers.add(itr.next());
} catch (ServiceConfigurationError e) {
LOGGER.error(CORE, "Failed to load a " + name + " library, expect problems", e);
}
}
if (providers.isEmpty()) {
LOGGER.error(CORE, "Found no {} provider. Cannot run", name);
throw new IncompatibleEnvironmentException("No " + name + " library found");
} else if (providers.size() > 1) {
LOGGER.error(CORE, "Found multiple {} providers: {}. Cannot run", name, providers.stream().map(p -> p.getClass().getName()).toList());
throw new IncompatibleEnvironmentException("Multiple " + name + " libraries found");
}
return providers.get(0);
}
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
arguments.put("launchTarget", launchTarget);
final Optional<ILaunchHandlerService> launchHandler = environment.findLaunchHandler(launchTarget);
LOGGER.debug(CORE, "Using {} as launch service", launchTarget);
if (launchHandler.isEmpty()) {
LOGGER.error(CORE, "Missing LaunchHandler {}, cannot continue", launchTarget);
throw new RuntimeException("Missing launch handler: " + launchTarget);
}
// TODO: [FML][Loader] What the fuck is the point of using a service if you require a specific concrete class
if (!(launchHandler.get() instanceof CommonLaunchHandler)) {
LOGGER.error(CORE, "Incompatible Launch handler found - type {}, cannot continue", launchHandler.get().getClass().getName());
throw new RuntimeException("Incompatible launch handler found");
}
commonLaunchHandler = (CommonLaunchHandler)launchHandler.get();
launchHandlerName = launchHandler.get().name();
gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Paths.get(".").toAbsolutePath());
naming = commonLaunchHandler.getNaming();
dist = commonLaunchHandler.getDist();
production = commonLaunchHandler.isProduction();
accessTransformer.getExtension().accept(Pair.of(naming, "srg"));
runtimeDistCleaner.getExtension().accept(dist);
}
public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) {
LOGGER.debug(SCAN,"Scanning for Mod Locators");
modDiscoverer = new ModDiscoverer(arguments);
modValidator = modDiscoverer.discoverMods();
var pluginResources = modValidator.getPluginResources();
return List.of(pluginResources);
}
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
moduleLayerManager = layerManager;
languageLoadingProvider = new LanguageLoadingProvider();
backgroundScanHandler = modValidator.stage2Validation();
loadingModList = backgroundScanHandler.getLoadingModList();
return List.of(modValidator.getModResources());
}
public static ICoreModProvider getCoreModProvider() {
return coreModProvider;
}
public static LanguageLoadingProvider getLanguageLoadingProvider() {
return languageLoadingProvider;
}
static ModDiscoverer getModDiscoverer() {
return modDiscoverer;
}
public static CommonLaunchHandler getLaunchHandler() {
return commonLaunchHandler;
}
public static void addAccessTransformer(Path atPath, ModFile modName) {
LOGGER.debug(SCAN, "Adding Access Transformer in {}", modName.getFilePath());
accessTransformer.offerResource(atPath, modName.getFileName());
}
public static Dist getDist() {
return dist;
}
public static void beforeStart(ModuleLayer gameLayer) {
ImmediateWindowHandler.acceptGameLayer(gameLayer);
ImmediateWindowHandler.updateProgress("Launching minecraft");
progressWindowTick.run();
}
public static LoadingModList getLoadingModList() {
return loadingModList;
}
public static Path getGamePath() {
return gamePath;
}
public static String getNaming() {
return naming;
}
public static Optional<BiFunction<INameMappingService.Domain, String, String>> getNameFunction(final String naming) {
return Launcher.INSTANCE.environment().findNameMapping(naming);
}
public static String getLauncherInfo() {
return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MLIMPL_VERSION.get()).orElse("MISSING");
}
public static List<Map<String, String>> modLauncherModList() {
return Launcher.INSTANCE.environment().getProperty(IEnvironment.Keys.MODLIST.get()).orElse(List.of());
}
public static String launcherHandlerName() {
return launchHandlerName;
}
public static boolean isProduction() {
return production;
}
public static boolean isSecureJarEnabled() {
return true;
}
public static ModuleLayer getGameLayer() {
return moduleLayerManager.getLayer(IModuleLayerManager.Layer.GAME).orElseThrow();
}
public static VersionInfo versionInfo() {
return versionInfo;
}
}
|
141414_9 | /****************************************************************************
Copyright 2009, Colorado School of Mines and others.
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 edu.mines.jtk.sgl;
import java.awt.Color;
import edu.mines.jtk.dsp.*;
import static edu.mines.jtk.util.ArrayMath.*;
/**
* An axis-aligned panel that displays a slice of a 3D metric tensor field.
* The tensors correspond to symmetric positive-definite 3x3 matrices, and
* are rendered as ellipsoids.
* @author Chris Engelsma and Dave Hale, Colorado School of Mines.
* @version 2009.08.29
*/
public class TensorsPanel extends AxisAlignedPanel {
/**
* Constructs a tensors panel for the specified tensor field.
* Assumes default unit samplings.
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(EigenTensors3 et) {
this(new Sampling(et.getN1()),
new Sampling(et.getN2()),
new Sampling(et.getN3()),
et);
}
/**
* Constructs a tensors panel for the specified tensor field.
* @param s1 sampling of 1st dimension (Z axis).
* @param s2 sampling of 2nd dimension (Y axis).
* @param s3 sampling of 3rd dimension (X axis).
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(
Sampling s1, Sampling s2, Sampling s3, EigenTensors3 et)
{
_sx = s3;
_sy = s2;
_sz = s1;
_et = et;
_emax = findMaxEigenvalue();
setStates(StateSet.forTwoSidedShinySurface(Color.CYAN));
}
/**
* Updates the panel.
* This method should be called when the tensor field
* referenced by this tensors panel has been modified.
*/
public void update() {
dirtyDraw();
}
/**
* Sets the maximum size of the ellipsoids.
* As this size is increased, the number of ellipsoids decreases.
* @param size the maximum ellipsoid size, in samples.
*/
public void setEllipsoidSize(int size) {
_ellipsoidSize = size;
dirtyDraw();
}
/////////////////////////////////////////////////////////////////////////////
// protected
protected void draw(DrawContext dc) {
AxisAlignedFrame aaf = this.getFrame();
if (aaf==null)
return;
Axis axis = aaf.getAxis();
drawEllipsoids(axis);
}
/////////////////////////////////////////////////////////////////////////////
// private
private Sampling _sx,_sy,_sz;
private EigenTensors3 _et;
private float _emax;
private int _ellipsoidSize = 10;
private EllipsoidGlyph _eg = new EllipsoidGlyph();
/**
* Draws the tensors as ellipsoids.
*/
private void drawEllipsoids(Axis axis) {
// Tensor sampling.
int nx = _sx.getCount();
int ny = _sy.getCount();
int nz = _sz.getCount();
double dx = _sx.getDelta();
double dy = _sy.getDelta();
double dz = _sz.getDelta();
double fx = _sx.getFirst();
double fy = _sy.getFirst();
double fz = _sz.getFirst();
// Min/max (x,y,z) coordinates.
double xmin = _sx.getFirst();
double xmax = _sx.getLast();
double ymin = _sy.getFirst();
double ymax = _sy.getLast();
double zmin = _sz.getFirst();
double zmax = _sz.getLast();
// Maximum length of eigenvectors u, v and w.
float dmax = 0.5f*_ellipsoidSize;
float dxmax = (float)dx*dmax;
float dymax = (float)dy*dmax;
float dzmax = (float)dz*dmax;
// Distance between ellipsoid centers (in samples).
int kec = (int)(2.0*dmax);
// Scaling factor for the eigenvectors.
float scale = dmax/sqrt(_emax);
// Smallest eigenvalue permitted.
float etiny = 0.0001f*_emax;
// Current frame.
AxisAlignedFrame aaf = this.getFrame();
if (axis==Axis.X) {
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// X-Axis.
float xc = 0.5f*(float)(xmax+xmin);
int ix = _sx.indexOfNearest(xc);
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Y) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Y-Axis.
float yc = 0.5f*(float)(ymax+ymin);
int iy = _sy.indexOfNearest(yc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Z) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Z-Axis.
float zc = 0.5f*(float)(zmax+zmin);
int iz = _sz.indexOfNearest(zc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
}
}
/**
* Finds the largest eigenvalue to be used for scaling.
*/
private float findMaxEigenvalue() {
int n1 = _et.getN1();
int n2 = _et.getN2();
int n3 = _et.getN3();
float[] e = new float[3];
float emax = 0.0f;
for (int i3=0; i3<n3; ++i3) {
for (int i2=0; i2<n2; ++i2) {
for (int i1=0; i1<n1; ++i1) {
_et.getEigenvalues(i1,i2,i3,e);
float emaxi = max(e[0],e[1],e[2]);
if (emax<emaxi)
emax = emaxi;
}
}
}
return emax;
}
}
| MinesJTK/jtk | core/src/main/java/edu/mines/jtk/sgl/TensorsPanel.java | 4,182 | // Distance between ellipsoid centers (in samples). | line_comment | nl | /****************************************************************************
Copyright 2009, Colorado School of Mines and others.
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 edu.mines.jtk.sgl;
import java.awt.Color;
import edu.mines.jtk.dsp.*;
import static edu.mines.jtk.util.ArrayMath.*;
/**
* An axis-aligned panel that displays a slice of a 3D metric tensor field.
* The tensors correspond to symmetric positive-definite 3x3 matrices, and
* are rendered as ellipsoids.
* @author Chris Engelsma and Dave Hale, Colorado School of Mines.
* @version 2009.08.29
*/
public class TensorsPanel extends AxisAlignedPanel {
/**
* Constructs a tensors panel for the specified tensor field.
* Assumes default unit samplings.
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(EigenTensors3 et) {
this(new Sampling(et.getN1()),
new Sampling(et.getN2()),
new Sampling(et.getN3()),
et);
}
/**
* Constructs a tensors panel for the specified tensor field.
* @param s1 sampling of 1st dimension (Z axis).
* @param s2 sampling of 2nd dimension (Y axis).
* @param s3 sampling of 3rd dimension (X axis).
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(
Sampling s1, Sampling s2, Sampling s3, EigenTensors3 et)
{
_sx = s3;
_sy = s2;
_sz = s1;
_et = et;
_emax = findMaxEigenvalue();
setStates(StateSet.forTwoSidedShinySurface(Color.CYAN));
}
/**
* Updates the panel.
* This method should be called when the tensor field
* referenced by this tensors panel has been modified.
*/
public void update() {
dirtyDraw();
}
/**
* Sets the maximum size of the ellipsoids.
* As this size is increased, the number of ellipsoids decreases.
* @param size the maximum ellipsoid size, in samples.
*/
public void setEllipsoidSize(int size) {
_ellipsoidSize = size;
dirtyDraw();
}
/////////////////////////////////////////////////////////////////////////////
// protected
protected void draw(DrawContext dc) {
AxisAlignedFrame aaf = this.getFrame();
if (aaf==null)
return;
Axis axis = aaf.getAxis();
drawEllipsoids(axis);
}
/////////////////////////////////////////////////////////////////////////////
// private
private Sampling _sx,_sy,_sz;
private EigenTensors3 _et;
private float _emax;
private int _ellipsoidSize = 10;
private EllipsoidGlyph _eg = new EllipsoidGlyph();
/**
* Draws the tensors as ellipsoids.
*/
private void drawEllipsoids(Axis axis) {
// Tensor sampling.
int nx = _sx.getCount();
int ny = _sy.getCount();
int nz = _sz.getCount();
double dx = _sx.getDelta();
double dy = _sy.getDelta();
double dz = _sz.getDelta();
double fx = _sx.getFirst();
double fy = _sy.getFirst();
double fz = _sz.getFirst();
// Min/max (x,y,z) coordinates.
double xmin = _sx.getFirst();
double xmax = _sx.getLast();
double ymin = _sy.getFirst();
double ymax = _sy.getLast();
double zmin = _sz.getFirst();
double zmax = _sz.getLast();
// Maximum length of eigenvectors u, v and w.
float dmax = 0.5f*_ellipsoidSize;
float dxmax = (float)dx*dmax;
float dymax = (float)dy*dmax;
float dzmax = (float)dz*dmax;
// Distance between<SUF>
int kec = (int)(2.0*dmax);
// Scaling factor for the eigenvectors.
float scale = dmax/sqrt(_emax);
// Smallest eigenvalue permitted.
float etiny = 0.0001f*_emax;
// Current frame.
AxisAlignedFrame aaf = this.getFrame();
if (axis==Axis.X) {
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// X-Axis.
float xc = 0.5f*(float)(xmax+xmin);
int ix = _sx.indexOfNearest(xc);
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Y) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Y-Axis.
float yc = 0.5f*(float)(ymax+ymin);
int iy = _sy.indexOfNearest(yc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Z) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Z-Axis.
float zc = 0.5f*(float)(zmax+zmin);
int iz = _sz.indexOfNearest(zc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
}
}
/**
* Finds the largest eigenvalue to be used for scaling.
*/
private float findMaxEigenvalue() {
int n1 = _et.getN1();
int n2 = _et.getN2();
int n3 = _et.getN3();
float[] e = new float[3];
float emax = 0.0f;
for (int i3=0; i3<n3; ++i3) {
for (int i2=0; i2<n2; ++i2) {
for (int i1=0; i1<n1; ++i1) {
_et.getEigenvalues(i1,i2,i3,e);
float emaxi = max(e[0],e[1],e[2]);
if (emax<emaxi)
emax = emaxi;
}
}
}
return emax;
}
}
|
177895_17 | package com.carpentersblocks.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import com.carpentersblocks.tileentity.TEBase;
import com.carpentersblocks.util.BlockProperties;
import com.carpentersblocks.util.registry.BlockRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class GarageDoor extends AbstractMultiBlock implements ISided {
/**
* 16-bit data components:
*
* [000000] [0] [0] [0] [000] [0000]
* Unused Host Rigid State Dir Type
*/
public final static GarageDoor INSTANCE = new GarageDoor();
public static final int TYPE_DEFAULT = 0;
public static final int TYPE_GLASS_TOP = 1;
public static final int TYPE_GLASS = 2;
public static final int TYPE_SIDING = 3;
public static final int TYPE_HIDDEN = 4;
public final static int STATE_CLOSED = 0;
public final static int STATE_OPEN = 1;
public final static byte DOOR_NONRIGID = 0;
public final static byte DOOR_RIGID = 1;
/**
* Returns type.
*/
public int getType(TEBase TE)
{
return TE.getData() & 0xf;
}
/**
* Sets type.
*/
public void setType(TEBase TE, int type)
{
int temp = (TE.getData() & ~0xf) | type;
TE.setData(temp);
}
/**
* Returns direction.
*/
@Override
public ForgeDirection getDirection(TEBase TE)
{
int side = (TE.getData() & 0x70) >> 4;
return ForgeDirection.getOrientation(side);
}
/**
* Sets direction.
*/
@Override
public boolean setDirection(TEBase TE, ForgeDirection dir)
{
int temp = (TE.getData() & ~0x70) | (dir.ordinal() << 4);
return TE.setData(temp);
}
/**
* Returns state (open or closed).
*/
public int getState(TEBase TE)
{
return (TE.getData() & 0x80) >> 7;
}
/**
* Sets state (open or closed).
*/
public void setState(TEBase TE, int state)
{
int temp = (TE.getData() & ~0x80) | (state << 7);
TE.setData(temp);
}
/**
* Whether garage door is rigid (requires redstone).
*/
public boolean isRigid(TEBase TE)
{
return getRigidity(TE) == DOOR_RIGID;
}
/**
* Returns rigidity (requiring redstone).
*/
public int getRigidity(TEBase TE)
{
return (TE.getData() & 0x100) >> 8;
}
/**
* Sets rigidity (requiring redstone).
*/
public void setRigidity(TEBase TE, int rigidity)
{
int temp = (TE.getData() & ~0x100) | (rigidity << 8);
TE.setData(temp);
}
/**
* Sets host door (the topmost).
*/
public void setHost(TEBase TE)
{
int temp = TE.getData() | 0x200;
TE.setData(temp);
}
/**
* Returns true if door is host (the topmost).
*/
public boolean isHost(TEBase TE)
{
return (TE.getData() & 0x200) > 0;
}
/**
* Compares door pieces by distance from player.
*/
@SideOnly(Side.CLIENT)
class DoorPieceDistanceComparator implements Comparator<TEBase> {
@Override
public int compare(TEBase tileEntity1, TEBase tileEntity2) {
double dist1 = Minecraft.getMinecraft().thePlayer.getDistance(tileEntity1.xCoord, tileEntity1.yCoord, tileEntity1.zCoord);
double dist2 = Minecraft.getMinecraft().thePlayer.getDistance(tileEntity2.xCoord, tileEntity2.yCoord, tileEntity2.zCoord);
return dist1 < dist2 ? -1 : 1;
}
}
/**
* When passed a TEBase, will play state change sound
* if piece is nearest to player out of all connecting
* door pieces.
* <p>
* The server would normally handle this and send notification
* to all nearby players, but sound source will be dependent
* on each player's location.
*
* @param list an {@link ArrayList<TEBase>} of door pieces
* @param entityPlayer the source {@link EntityPlayer}
* @return the {@link TEBase} nearest to {@link EntityPlayer}
*/
@SideOnly(Side.CLIENT)
public void playStateChangeSound(TEBase TE)
{
Set<TEBase> set = getBlocks(TE, BlockRegistry.blockCarpentersGarageDoor);
List<TEBase> list = new ArrayList<TEBase>(set); // For sorting
// Only play sound if piece is nearest to player
Collections.sort(list, new DoorPieceDistanceComparator());
if (list.get(0).equals(TE)) {
TE.getWorldObj().playAuxSFXAtEntity((EntityPlayer)null, 1003, TE.xCoord, TE.yCoord, TE.zCoord, 0);
}
}
/**
* Helper function for determining properties based on a
* nearby garage door piece around the given coordinates.
*
* @param world the {@link World}
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @return a {@link TEBase} with relevant properties
*/
public TEBase findReferencePiece(World world, int x, int y, int z, ForgeDirection axis)
{
ForgeDirection dir = axis.getRotation(ForgeDirection.UP);
do {
TEBase temp1 = BlockProperties.getTileEntity(BlockRegistry.blockCarpentersGarageDoor, world, x + dir.offsetX, y, z + dir.offsetZ);
TEBase temp2 = BlockProperties.getTileEntity(BlockRegistry.blockCarpentersGarageDoor, world, x - dir.offsetX, y, z - dir.offsetZ);
if (temp1 != null && getDirection(temp1).equals(axis)) {
return temp1;
} else if (temp2 != null && getDirection(temp2).equals(axis)) {
return temp2;
}
} while (y > 1 && world.getBlock(x, --y, z).equals(Blocks.air));
return null;
}
/**
* Copies relevant properties and owner from source tile
* entity to destination tile entity.
*
* @param src the source {@link TEBase}
* @param dest the destination {@link TEBase}
*/
public void replicate(final TEBase src, TEBase dest)
{
setDirection(dest, getDirection(src));
setRigidity(dest, getRigidity(src));
setState(dest, getState(src));
setType(dest, getType(src));
dest.copyOwner(src);
}
/**
* Whether garage door is open.
*
* @param TE the {@link TEBase}
* @return <code>true</code> if garage door is open
*/
public boolean isOpen(TEBase TE)
{
return getState(TE) == STATE_OPEN;
}
/**
* Weather panel is the bottommost.
*
* @param TE the {@link TEBase}
* @return true if panel is the bottommost
*/
public boolean isBottommost(TEBase TE)
{
return !TE.getWorldObj().getBlock(TE.xCoord, TE.yCoord - 1, TE.zCoord).equals(BlockRegistry.blockCarpentersGarageDoor);
}
/**
* Gets the topmost garage door tile entity.
*
* @param TE the {@link TEBase}
* @return the {@link TEBase}
*/
public TEBase getTopmost(World world, int x, int y, int z)
{
do {
++y;
} while (world.getBlock(x, y, z).equals(BlockRegistry.blockCarpentersGarageDoor));
return (TEBase) world.getTileEntity(x, y - 1, z);
}
/**
* Gets the bottommost garage door tile entity.
*
* @param TE the {@link TEBase}
* @return the {@link TEBase}
*/
public TEBase getBottommost(World world, int x, int y, int z)
{
do {
--y;
} while (world.getBlock(x, y, z).equals(BlockRegistry.blockCarpentersGarageDoor));
return (TEBase) world.getTileEntity(x, y + 1, z);
}
/**
* Whether block is visible.
* <p>
* If a block is open and not in the topmost position,
* it cannot be selected or collided with.
*
* @param TE the {@link TEBase}
* @return true if visible
*/
public boolean isVisible(TEBase TE)
{
if (isOpen(TE)) {
return isHost(TE);
} else {
return true;
}
}
@Override
public int getMatchingDataPattern(TEBase TE)
{
return TE.getData() & 0x70;
}
@Override
public ForgeDirection[] getLocateDirs(TEBase TE)
{
ForgeDirection dirPlane = getDirection(TE).getRotation(ForgeDirection.UP);
ForgeDirection[] dirs = {
ForgeDirection.UP,
ForgeDirection.DOWN,
dirPlane,
dirPlane.getOpposite()
};
return dirs;
}
}
| Mineshopper/carpentersblocks | src/main/java/com/carpentersblocks/data/GarageDoor.java | 2,810 | /**
* Whether garage door is open.
*
* @param TE the {@link TEBase}
* @return <code>true</code> if garage door is open
*/ | block_comment | nl | package com.carpentersblocks.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import com.carpentersblocks.tileentity.TEBase;
import com.carpentersblocks.util.BlockProperties;
import com.carpentersblocks.util.registry.BlockRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class GarageDoor extends AbstractMultiBlock implements ISided {
/**
* 16-bit data components:
*
* [000000] [0] [0] [0] [000] [0000]
* Unused Host Rigid State Dir Type
*/
public final static GarageDoor INSTANCE = new GarageDoor();
public static final int TYPE_DEFAULT = 0;
public static final int TYPE_GLASS_TOP = 1;
public static final int TYPE_GLASS = 2;
public static final int TYPE_SIDING = 3;
public static final int TYPE_HIDDEN = 4;
public final static int STATE_CLOSED = 0;
public final static int STATE_OPEN = 1;
public final static byte DOOR_NONRIGID = 0;
public final static byte DOOR_RIGID = 1;
/**
* Returns type.
*/
public int getType(TEBase TE)
{
return TE.getData() & 0xf;
}
/**
* Sets type.
*/
public void setType(TEBase TE, int type)
{
int temp = (TE.getData() & ~0xf) | type;
TE.setData(temp);
}
/**
* Returns direction.
*/
@Override
public ForgeDirection getDirection(TEBase TE)
{
int side = (TE.getData() & 0x70) >> 4;
return ForgeDirection.getOrientation(side);
}
/**
* Sets direction.
*/
@Override
public boolean setDirection(TEBase TE, ForgeDirection dir)
{
int temp = (TE.getData() & ~0x70) | (dir.ordinal() << 4);
return TE.setData(temp);
}
/**
* Returns state (open or closed).
*/
public int getState(TEBase TE)
{
return (TE.getData() & 0x80) >> 7;
}
/**
* Sets state (open or closed).
*/
public void setState(TEBase TE, int state)
{
int temp = (TE.getData() & ~0x80) | (state << 7);
TE.setData(temp);
}
/**
* Whether garage door is rigid (requires redstone).
*/
public boolean isRigid(TEBase TE)
{
return getRigidity(TE) == DOOR_RIGID;
}
/**
* Returns rigidity (requiring redstone).
*/
public int getRigidity(TEBase TE)
{
return (TE.getData() & 0x100) >> 8;
}
/**
* Sets rigidity (requiring redstone).
*/
public void setRigidity(TEBase TE, int rigidity)
{
int temp = (TE.getData() & ~0x100) | (rigidity << 8);
TE.setData(temp);
}
/**
* Sets host door (the topmost).
*/
public void setHost(TEBase TE)
{
int temp = TE.getData() | 0x200;
TE.setData(temp);
}
/**
* Returns true if door is host (the topmost).
*/
public boolean isHost(TEBase TE)
{
return (TE.getData() & 0x200) > 0;
}
/**
* Compares door pieces by distance from player.
*/
@SideOnly(Side.CLIENT)
class DoorPieceDistanceComparator implements Comparator<TEBase> {
@Override
public int compare(TEBase tileEntity1, TEBase tileEntity2) {
double dist1 = Minecraft.getMinecraft().thePlayer.getDistance(tileEntity1.xCoord, tileEntity1.yCoord, tileEntity1.zCoord);
double dist2 = Minecraft.getMinecraft().thePlayer.getDistance(tileEntity2.xCoord, tileEntity2.yCoord, tileEntity2.zCoord);
return dist1 < dist2 ? -1 : 1;
}
}
/**
* When passed a TEBase, will play state change sound
* if piece is nearest to player out of all connecting
* door pieces.
* <p>
* The server would normally handle this and send notification
* to all nearby players, but sound source will be dependent
* on each player's location.
*
* @param list an {@link ArrayList<TEBase>} of door pieces
* @param entityPlayer the source {@link EntityPlayer}
* @return the {@link TEBase} nearest to {@link EntityPlayer}
*/
@SideOnly(Side.CLIENT)
public void playStateChangeSound(TEBase TE)
{
Set<TEBase> set = getBlocks(TE, BlockRegistry.blockCarpentersGarageDoor);
List<TEBase> list = new ArrayList<TEBase>(set); // For sorting
// Only play sound if piece is nearest to player
Collections.sort(list, new DoorPieceDistanceComparator());
if (list.get(0).equals(TE)) {
TE.getWorldObj().playAuxSFXAtEntity((EntityPlayer)null, 1003, TE.xCoord, TE.yCoord, TE.zCoord, 0);
}
}
/**
* Helper function for determining properties based on a
* nearby garage door piece around the given coordinates.
*
* @param world the {@link World}
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @return a {@link TEBase} with relevant properties
*/
public TEBase findReferencePiece(World world, int x, int y, int z, ForgeDirection axis)
{
ForgeDirection dir = axis.getRotation(ForgeDirection.UP);
do {
TEBase temp1 = BlockProperties.getTileEntity(BlockRegistry.blockCarpentersGarageDoor, world, x + dir.offsetX, y, z + dir.offsetZ);
TEBase temp2 = BlockProperties.getTileEntity(BlockRegistry.blockCarpentersGarageDoor, world, x - dir.offsetX, y, z - dir.offsetZ);
if (temp1 != null && getDirection(temp1).equals(axis)) {
return temp1;
} else if (temp2 != null && getDirection(temp2).equals(axis)) {
return temp2;
}
} while (y > 1 && world.getBlock(x, --y, z).equals(Blocks.air));
return null;
}
/**
* Copies relevant properties and owner from source tile
* entity to destination tile entity.
*
* @param src the source {@link TEBase}
* @param dest the destination {@link TEBase}
*/
public void replicate(final TEBase src, TEBase dest)
{
setDirection(dest, getDirection(src));
setRigidity(dest, getRigidity(src));
setState(dest, getState(src));
setType(dest, getType(src));
dest.copyOwner(src);
}
/**
* Whether garage door<SUF>*/
public boolean isOpen(TEBase TE)
{
return getState(TE) == STATE_OPEN;
}
/**
* Weather panel is the bottommost.
*
* @param TE the {@link TEBase}
* @return true if panel is the bottommost
*/
public boolean isBottommost(TEBase TE)
{
return !TE.getWorldObj().getBlock(TE.xCoord, TE.yCoord - 1, TE.zCoord).equals(BlockRegistry.blockCarpentersGarageDoor);
}
/**
* Gets the topmost garage door tile entity.
*
* @param TE the {@link TEBase}
* @return the {@link TEBase}
*/
public TEBase getTopmost(World world, int x, int y, int z)
{
do {
++y;
} while (world.getBlock(x, y, z).equals(BlockRegistry.blockCarpentersGarageDoor));
return (TEBase) world.getTileEntity(x, y - 1, z);
}
/**
* Gets the bottommost garage door tile entity.
*
* @param TE the {@link TEBase}
* @return the {@link TEBase}
*/
public TEBase getBottommost(World world, int x, int y, int z)
{
do {
--y;
} while (world.getBlock(x, y, z).equals(BlockRegistry.blockCarpentersGarageDoor));
return (TEBase) world.getTileEntity(x, y + 1, z);
}
/**
* Whether block is visible.
* <p>
* If a block is open and not in the topmost position,
* it cannot be selected or collided with.
*
* @param TE the {@link TEBase}
* @return true if visible
*/
public boolean isVisible(TEBase TE)
{
if (isOpen(TE)) {
return isHost(TE);
} else {
return true;
}
}
@Override
public int getMatchingDataPattern(TEBase TE)
{
return TE.getData() & 0x70;
}
@Override
public ForgeDirection[] getLocateDirs(TEBase TE)
{
ForgeDirection dirPlane = getDirection(TE).getRotation(ForgeDirection.UP);
ForgeDirection[] dirs = {
ForgeDirection.UP,
ForgeDirection.DOWN,
dirPlane,
dirPlane.getOpposite()
};
return dirs;
}
}
|
113808_4 | package com.iglens.地理;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
public class GeoUtils {
// 卫星椭球坐标投影到平面坐标系的投影因子
private static final double A = 6378245.0;
// 椭球的偏心率
private static final double EE = 0.00669342162296594323;
// 容差
private static final double PRECISION = 2e-10; // 默认2e-10
/**
* MAX_MERC = 20037508.3427892;<br>
* minMerc = -20037508.3427892;<br>
* 经纬度为[0,0]时墨卡托坐标为[0,0]<br>
* MAX_MERC对应纬度180<br>
* MIN_MERC对应纬度-180<br>
* 墨卡托投影图左上角,即[x:0,y:0]左上角,坐标为[minMerc,MAX_MERC]<br>
* 墨卡托投影图右上角,即[x:m,y:0]右上角,坐标为[MAX_MERC,MAX_MERC]<br>
* 墨卡托投影图左下角,即[x:0,y:m]左下角,坐标为[minMerc,minMerc]<br>
* 墨卡托投影图右下角,即[x:m,y:m]右下角,坐标为[MAX_MERC,minMerc]<br>
* [-20037508,20037508]----------------[20037508,20037508]<br>
* -------------------------------------------------------<br>
* -------------------------[0,0]-------------------------<br>
* -------------------------------------------------------<br>
* [-20037508,-20037508]--------------[20037508,-20037508]<br>
* 为了方便计算,算法中使用如下坐标系<br>
* [0,0]--------------------------------------[40075016,0]<br>
* -------------------------------------------------------<br>
* ------------------[20037508,20037508]------------------<br>
* -------------------------------------------------------<br>
* [0,40075016]------------------------[40075016,40075016]<br>
* 自定义坐标系转TSM坐标系方法:<br>
* Ty = MAX_MERC - y<br>
* Tx = x - MAX_MERC<br>
* TSM坐标系转自定义坐标系方法:<br>
* y = MAX_MERC - Ty<br>
* x = Tx + MAX_MERC<br>
*/
public static final double MAX_MERC = 20037508.3427892;
/** 经纬度转墨卡托 */
public static MercatorPoint LngLat2Mercator(LngLatPoint point) {
double x = point.getLng() * MAX_MERC / 180;
double y = Math.log(Math.tan((90 + point.getLat()) * Math.PI / 360)) / (Math.PI / 180);
y = y * MAX_MERC / 180;
return new MercatorPoint(x, y);
}
/** 墨卡托转经纬度 */
public static LngLatPoint Mercator2LngLat(MercatorPoint point) {
double x = point.getLng() / MAX_MERC * 180;
double y = point.getLat() / MAX_MERC * 180;
y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
return new LngLatPoint(x, y);
}
/** 通过XYZ获取Tile实例 */
public static Tile getTile(int z, int x, int y) {
Tile tile = new Tile();
tile.setZ(z);
tile.setX(x);
tile.setY(y);
int count = (int) Math.pow(2, z);
double each = MAX_MERC / ((double) count / 2);
double each_x = each * x;
double each_x_1 = each * (x + 1);
double each_y = each * y;
double each_y_1 = each * (y + 1);
tile.setTopLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y));
tile.setTopRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y));
tile.setBottomLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y_1));
tile.setBottomRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y_1));
return tile;
}
/** 通过墨卡托坐标获取Tile实例 */
public static Tile getTile(int zoom, MercatorPoint point) {
double cx = point.getLng() + MAX_MERC;
double cy = MAX_MERC - point.getLat();
int count = (int) Math.pow(2, zoom);
double each = MAX_MERC / ((double) count / 2);
int count_x = (int) Math.floor(cx / each);
int count_y = (int) Math.floor(cy / each);
Tile tile = getTile(zoom, count_x, count_y);
return tile;
}
/** 通过经纬度坐标获取Tile实例 */
public static Tile getTile(int zoom, LngLatPoint point) {
return getTile(zoom, LngLat2Mercator(point));
}
/** 获取多边形bounds */
public static Bound getPolygonBound(Polygon polygon) {
Bound bound = new Bound();
Double minX = null, minY = null, maxX = null, maxY = null;
for (MercatorPoint point : polygon.getPath()) {
minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng();
minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat();
maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng();
maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat();
}
bound.setTopLeft(new MercatorPoint(minX, maxY));
bound.setTopRight(new MercatorPoint(maxX, maxY));
bound.setBottomLeft(new MercatorPoint(minX, minY));
bound.setBottomRight(new MercatorPoint(maxX, minY));
return bound;
}
/** 获取多边形bounds(多个) */
public static Bound getPolygonsBound(List<Polygon> polygons) {
Bound bound = new Bound();
Double minX = null, minY = null, maxX = null, maxY = null;
for (Polygon polygon : polygons) {
for (MercatorPoint point : polygon.getPath()) {
minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng();
minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat();
maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng();
maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat();
}
}
bound.setTopLeft(new MercatorPoint(minX, maxY));
bound.setTopRight(new MercatorPoint(maxX, maxY));
bound.setBottomLeft(new MercatorPoint(minX, minY));
bound.setBottomRight(new MercatorPoint(maxX, minY));
return bound;
}
/** 判断瓦片图是否在多边形内 */
public static boolean isTileInPolygon(Tile tile, Polygon polygon) {
return isPointInPolygon(tile.getTopLeft(), polygon)
|| isPointInPolygon(tile.getTopRight(), polygon)
|| isPointInPolygon(tile.getBottomLeft(), polygon)
|| isPointInPolygon(tile.getBottomRight(), polygon);
}
/** 判断多边形是否在瓦片图区块内 */
public static boolean isPolygonInTile(Tile tile, Polygon polygon) {
ArrayList<MercatorPoint> path = new ArrayList<MercatorPoint>();
path.add(tile.getTopLeft());
path.add(tile.getTopRight());
path.add(tile.getBottomRight());
path.add(tile.getBottomLeft());
Polygon tilePolygon = new Polygon(path);
for (MercatorPoint point : polygon.getPath()) {
if (isPointInPolygon(point, tilePolygon)) {
return true;
}
}
return false;
}
/** 判断点是否在多边形内 */
/** 提取自百度地图API */
public static boolean isPointInPolygon(MercatorPoint markerPoint, Polygon polygon) {
// 下述代码来源:http://paulbourke.net/geometry/insidepoly/,进行了部分修改
// 基本思想是利用射线法,计算射线与多边形各边的交点,如果是偶数,则点在多边形外,否则
// 在多边形内。还会考虑一些特殊情况,如点在多边形顶点上,点在多边形边上等特殊情况。
int N = polygon.getPath().size();
boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0; // cross points count of x
double precision = PRECISION; // 浮点类型计算时候与0比较时候的容差
MercatorPoint p1, p2; // neighbour bound vertices
MercatorPoint p = markerPoint; // 测试点
p1 = polygon.getPath().get(0); // left vertex
for (int i = 1; i <= N; ++i) { // check all rays
if (p.equals(p1)) {
return boundOrVertex; // p is an vertex
}
p2 = polygon.getPath().get(i % N); // right vertex
// ray is outside of our interests
if (p.getLat() < Math.min(p1.getLat(), p2.getLat())
|| p.getLat() > Math.max(p1.getLat(), p2.getLat())) {
p1 = p2;
continue; // next ray left point
}
// ray is crossing over by the algorithm (common part of)
if (p.getLat() > Math.min(p1.getLat(), p2.getLat())
&& p.getLat() < Math.max(p1.getLat(), p2.getLat())) {
// x is before of ray
if (p.getLng() <= Math.max(p1.getLng(), p2.getLng())) {
// overlies on a horizontal ray
if (p1.getLat() == p2.getLat() && p.getLng() >= Math.min(p1.getLng(), p2.getLng())) {
return boundOrVertex;
}
if (p1.getLng() == p2.getLng()) { // ray is vertical
if (p1.getLng() == p.getLng()) { // overlies on a vertical ray
return boundOrVertex;
} else { // before ray
++intersectCount;
}
} else { // cross point on the left side
// cross point of lng
double xinters =
(p.getLat() - p1.getLat())
* (p2.getLng() - p1.getLng())
/ (p2.getLat() - p1.getLat())
+ p1.getLng();
// overlies on a ray
if (Math.abs(p.getLng() - xinters) < precision) {
return boundOrVertex;
}
if (p.getLng() < xinters) { // before ray
++intersectCount;
}
}
}
} else { // special case when ray is crossing through the vertex
if (p.getLat() == p2.getLat() && p.getLng() <= p2.getLng()) { // p crossing over p2
MercatorPoint p3 = polygon.getPath().get((i + 1) % N); // next vertex
if (p.getLat() >= Math.min(p1.getLat(), p3.getLat())
&& p.getLat() <= Math.max(p1.getLat(), p3.getLat())) {
// p.lat lies between p1.lat & p3.lat
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2; // next ray left point
}
// 偶数在多边形外
// 奇数在多边形内
return intersectCount % 2 != 0;
}
/** XYZ转必应坐标 */
public static String xyz2Bing(int _z, int _x, int _y) {
StringBuilder result = new StringBuilder();
double x = _x + 1;
double y = _y + 1;
int z_all = (int) Math.pow(2, _z);
for (int i = 1; i <= _z; i++) {
double z0 = z_all / Math.pow(2, i - 1);
// 左上
if (x / z0 <= 0.5 && y / z0 <= 0.5) {
result.append("0");
}
// 右上
if (x / z0 > 0.5 && y / z0 <= 0.5) {
result.append("1");
x = x - z0 / 2;
}
// 左下
if (x / z0 <= 0.5 && y / z0 > 0.5) {
result.append("2");
y = y - z0 / 2;
}
// 右下
if (x / z0 > 0.5 && y / z0 > 0.5) {
result.append("3");
x = x - z0 / 2;
y = y - z0 / 2;
}
}
return result.toString();
}
/** 是否超出中国范围 */
private static boolean outOfChina(LngLatPoint pt) {
double lat = +pt.getLat();
double lng = +pt.getLng();
// 纬度3.86~53.55,经度73.66~135.05
return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
}
/** WGS84坐标转GCJ02坐标 */
public static LngLatPoint wgs84_To_gcj02(LngLatPoint pt) {
double lng = pt.getLng();
double lat = pt.getLat();
if (outOfChina(pt)) {
return pt;
} else {
double dLat = transformLat(lng - 105.0, lat - 35.0);
double dLng = transformLng(lng - 105.0, lat - 35.0);
double radLat = lat / 180.0 * Math.PI;
double magic = Math.sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * Math.PI);
dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * Math.PI);
double mgLat = lat + dLat;
double mgLng = lng + dLng;
return new LngLatPoint(mgLng, mgLat);
}
}
/** GCJ02坐标转WGS84坐标 */
public static LngLatPoint gcj02_To_wgs84(LngLatPoint pt) {
double lng = pt.getLng();
double lat = pt.getLat();
if (outOfChina(pt)) {
return pt;
} else {
double dlat = transformLat(lng - 105.0, lat - 35.0);
double dlng = transformLng(lng - 105.0, lat - 35.0);
double radlat = lat / 180.0 * Math.PI;
double magic = Math.sin(radlat);
magic = 1 - EE * magic * magic;
double sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * Math.PI);
dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * Math.PI);
double mglat = lat + dlat;
double mglng = lng + dlng;
return new LngLatPoint(lng * 2 - mglng, lat * 2 - mglat);
}
}
private static double transformLat(double lat, double lng) {
double ret =
-100.0
+ 2.0 * lat
+ 3.0 * lng
+ 0.2 * lng * lng
+ 0.1 * lat * lng
+ 0.2 * Math.sqrt(Math.abs(lat));
ret +=
(20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0;
ret +=
(160.0 * Math.sin(lng / 12.0 * Math.PI) + 320 * Math.sin(lng * Math.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLng(double lat, double lng) {
double ret =
300.0
+ lat
+ 2.0 * lng
+ 0.1 * lat * lat
+ 0.1 * lat * lng
+ 0.1 * Math.sqrt(Math.abs(lat));
ret +=
(20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0;
ret +=
(150.0 * Math.sin(lat / 12.0 * Math.PI) + 300.0 * Math.sin(lat / 30.0 * Math.PI))
* 2.0
/ 3.0;
return ret;
}
}
@Data
class MercatorPoint implements Serializable {
private static final long serialVersionUID = 4066123199303085477L;
private Double lng;
private Double lat;
public MercatorPoint(double lng, double lat) {
this.lng = lng;
this.lat = lat;
}
public LngLatPoint convert2LngLat() {
return GeoUtils.Mercator2LngLat(this);
}
}
@Data
class LngLatPoint implements Serializable {
private static final long serialVersionUID = -3504030834818220866L;
private Double lng;
private Double lat;
public LngLatPoint(double lng, double lat) {
this.lng = lng;
this.lat = lat;
}
public MercatorPoint convert2Mercator() {
return GeoUtils.LngLat2Mercator(this);
}
}
@Data
class Polygon implements Serializable {
private static final long serialVersionUID = 8429062630741585169L;
ArrayList<MercatorPoint> path;
public Polygon(List<MercatorPoint> path) {
this.path = (ArrayList<MercatorPoint>) path;
}
}
@Data
class Tile implements Serializable {
private static final long serialVersionUID = -3598715656639420131L;
private Integer z;
private Integer x;
private Integer y;
private MercatorPoint topLeft;
private MercatorPoint topRight;
private MercatorPoint bottomLeft;
private MercatorPoint bottomRight;
public Tile() {}
public Tile(int z, int x, int y) {
this.z = z;
this.x = x;
this.y = y;
}
}
@Data
class Bound {
private MercatorPoint topLeft;
private MercatorPoint topRight;
private MercatorPoint bottomLeft;
private MercatorPoint bottomRight;
}
| Mingxiangyu/Demo | varietyOfTools/src/main/java/com/iglens/地理/GeoUtils.java | 5,618 | // p is an vertex | line_comment | nl | package com.iglens.地理;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
public class GeoUtils {
// 卫星椭球坐标投影到平面坐标系的投影因子
private static final double A = 6378245.0;
// 椭球的偏心率
private static final double EE = 0.00669342162296594323;
// 容差
private static final double PRECISION = 2e-10; // 默认2e-10
/**
* MAX_MERC = 20037508.3427892;<br>
* minMerc = -20037508.3427892;<br>
* 经纬度为[0,0]时墨卡托坐标为[0,0]<br>
* MAX_MERC对应纬度180<br>
* MIN_MERC对应纬度-180<br>
* 墨卡托投影图左上角,即[x:0,y:0]左上角,坐标为[minMerc,MAX_MERC]<br>
* 墨卡托投影图右上角,即[x:m,y:0]右上角,坐标为[MAX_MERC,MAX_MERC]<br>
* 墨卡托投影图左下角,即[x:0,y:m]左下角,坐标为[minMerc,minMerc]<br>
* 墨卡托投影图右下角,即[x:m,y:m]右下角,坐标为[MAX_MERC,minMerc]<br>
* [-20037508,20037508]----------------[20037508,20037508]<br>
* -------------------------------------------------------<br>
* -------------------------[0,0]-------------------------<br>
* -------------------------------------------------------<br>
* [-20037508,-20037508]--------------[20037508,-20037508]<br>
* 为了方便计算,算法中使用如下坐标系<br>
* [0,0]--------------------------------------[40075016,0]<br>
* -------------------------------------------------------<br>
* ------------------[20037508,20037508]------------------<br>
* -------------------------------------------------------<br>
* [0,40075016]------------------------[40075016,40075016]<br>
* 自定义坐标系转TSM坐标系方法:<br>
* Ty = MAX_MERC - y<br>
* Tx = x - MAX_MERC<br>
* TSM坐标系转自定义坐标系方法:<br>
* y = MAX_MERC - Ty<br>
* x = Tx + MAX_MERC<br>
*/
public static final double MAX_MERC = 20037508.3427892;
/** 经纬度转墨卡托 */
public static MercatorPoint LngLat2Mercator(LngLatPoint point) {
double x = point.getLng() * MAX_MERC / 180;
double y = Math.log(Math.tan((90 + point.getLat()) * Math.PI / 360)) / (Math.PI / 180);
y = y * MAX_MERC / 180;
return new MercatorPoint(x, y);
}
/** 墨卡托转经纬度 */
public static LngLatPoint Mercator2LngLat(MercatorPoint point) {
double x = point.getLng() / MAX_MERC * 180;
double y = point.getLat() / MAX_MERC * 180;
y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
return new LngLatPoint(x, y);
}
/** 通过XYZ获取Tile实例 */
public static Tile getTile(int z, int x, int y) {
Tile tile = new Tile();
tile.setZ(z);
tile.setX(x);
tile.setY(y);
int count = (int) Math.pow(2, z);
double each = MAX_MERC / ((double) count / 2);
double each_x = each * x;
double each_x_1 = each * (x + 1);
double each_y = each * y;
double each_y_1 = each * (y + 1);
tile.setTopLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y));
tile.setTopRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y));
tile.setBottomLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y_1));
tile.setBottomRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y_1));
return tile;
}
/** 通过墨卡托坐标获取Tile实例 */
public static Tile getTile(int zoom, MercatorPoint point) {
double cx = point.getLng() + MAX_MERC;
double cy = MAX_MERC - point.getLat();
int count = (int) Math.pow(2, zoom);
double each = MAX_MERC / ((double) count / 2);
int count_x = (int) Math.floor(cx / each);
int count_y = (int) Math.floor(cy / each);
Tile tile = getTile(zoom, count_x, count_y);
return tile;
}
/** 通过经纬度坐标获取Tile实例 */
public static Tile getTile(int zoom, LngLatPoint point) {
return getTile(zoom, LngLat2Mercator(point));
}
/** 获取多边形bounds */
public static Bound getPolygonBound(Polygon polygon) {
Bound bound = new Bound();
Double minX = null, minY = null, maxX = null, maxY = null;
for (MercatorPoint point : polygon.getPath()) {
minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng();
minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat();
maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng();
maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat();
}
bound.setTopLeft(new MercatorPoint(minX, maxY));
bound.setTopRight(new MercatorPoint(maxX, maxY));
bound.setBottomLeft(new MercatorPoint(minX, minY));
bound.setBottomRight(new MercatorPoint(maxX, minY));
return bound;
}
/** 获取多边形bounds(多个) */
public static Bound getPolygonsBound(List<Polygon> polygons) {
Bound bound = new Bound();
Double minX = null, minY = null, maxX = null, maxY = null;
for (Polygon polygon : polygons) {
for (MercatorPoint point : polygon.getPath()) {
minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng();
minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat();
maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng();
maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat();
}
}
bound.setTopLeft(new MercatorPoint(minX, maxY));
bound.setTopRight(new MercatorPoint(maxX, maxY));
bound.setBottomLeft(new MercatorPoint(minX, minY));
bound.setBottomRight(new MercatorPoint(maxX, minY));
return bound;
}
/** 判断瓦片图是否在多边形内 */
public static boolean isTileInPolygon(Tile tile, Polygon polygon) {
return isPointInPolygon(tile.getTopLeft(), polygon)
|| isPointInPolygon(tile.getTopRight(), polygon)
|| isPointInPolygon(tile.getBottomLeft(), polygon)
|| isPointInPolygon(tile.getBottomRight(), polygon);
}
/** 判断多边形是否在瓦片图区块内 */
public static boolean isPolygonInTile(Tile tile, Polygon polygon) {
ArrayList<MercatorPoint> path = new ArrayList<MercatorPoint>();
path.add(tile.getTopLeft());
path.add(tile.getTopRight());
path.add(tile.getBottomRight());
path.add(tile.getBottomLeft());
Polygon tilePolygon = new Polygon(path);
for (MercatorPoint point : polygon.getPath()) {
if (isPointInPolygon(point, tilePolygon)) {
return true;
}
}
return false;
}
/** 判断点是否在多边形内 */
/** 提取自百度地图API */
public static boolean isPointInPolygon(MercatorPoint markerPoint, Polygon polygon) {
// 下述代码来源:http://paulbourke.net/geometry/insidepoly/,进行了部分修改
// 基本思想是利用射线法,计算射线与多边形各边的交点,如果是偶数,则点在多边形外,否则
// 在多边形内。还会考虑一些特殊情况,如点在多边形顶点上,点在多边形边上等特殊情况。
int N = polygon.getPath().size();
boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0; // cross points count of x
double precision = PRECISION; // 浮点类型计算时候与0比较时候的容差
MercatorPoint p1, p2; // neighbour bound vertices
MercatorPoint p = markerPoint; // 测试点
p1 = polygon.getPath().get(0); // left vertex
for (int i = 1; i <= N; ++i) { // check all rays
if (p.equals(p1)) {
return boundOrVertex; // p is<SUF>
}
p2 = polygon.getPath().get(i % N); // right vertex
// ray is outside of our interests
if (p.getLat() < Math.min(p1.getLat(), p2.getLat())
|| p.getLat() > Math.max(p1.getLat(), p2.getLat())) {
p1 = p2;
continue; // next ray left point
}
// ray is crossing over by the algorithm (common part of)
if (p.getLat() > Math.min(p1.getLat(), p2.getLat())
&& p.getLat() < Math.max(p1.getLat(), p2.getLat())) {
// x is before of ray
if (p.getLng() <= Math.max(p1.getLng(), p2.getLng())) {
// overlies on a horizontal ray
if (p1.getLat() == p2.getLat() && p.getLng() >= Math.min(p1.getLng(), p2.getLng())) {
return boundOrVertex;
}
if (p1.getLng() == p2.getLng()) { // ray is vertical
if (p1.getLng() == p.getLng()) { // overlies on a vertical ray
return boundOrVertex;
} else { // before ray
++intersectCount;
}
} else { // cross point on the left side
// cross point of lng
double xinters =
(p.getLat() - p1.getLat())
* (p2.getLng() - p1.getLng())
/ (p2.getLat() - p1.getLat())
+ p1.getLng();
// overlies on a ray
if (Math.abs(p.getLng() - xinters) < precision) {
return boundOrVertex;
}
if (p.getLng() < xinters) { // before ray
++intersectCount;
}
}
}
} else { // special case when ray is crossing through the vertex
if (p.getLat() == p2.getLat() && p.getLng() <= p2.getLng()) { // p crossing over p2
MercatorPoint p3 = polygon.getPath().get((i + 1) % N); // next vertex
if (p.getLat() >= Math.min(p1.getLat(), p3.getLat())
&& p.getLat() <= Math.max(p1.getLat(), p3.getLat())) {
// p.lat lies between p1.lat & p3.lat
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2; // next ray left point
}
// 偶数在多边形外
// 奇数在多边形内
return intersectCount % 2 != 0;
}
/** XYZ转必应坐标 */
public static String xyz2Bing(int _z, int _x, int _y) {
StringBuilder result = new StringBuilder();
double x = _x + 1;
double y = _y + 1;
int z_all = (int) Math.pow(2, _z);
for (int i = 1; i <= _z; i++) {
double z0 = z_all / Math.pow(2, i - 1);
// 左上
if (x / z0 <= 0.5 && y / z0 <= 0.5) {
result.append("0");
}
// 右上
if (x / z0 > 0.5 && y / z0 <= 0.5) {
result.append("1");
x = x - z0 / 2;
}
// 左下
if (x / z0 <= 0.5 && y / z0 > 0.5) {
result.append("2");
y = y - z0 / 2;
}
// 右下
if (x / z0 > 0.5 && y / z0 > 0.5) {
result.append("3");
x = x - z0 / 2;
y = y - z0 / 2;
}
}
return result.toString();
}
/** 是否超出中国范围 */
private static boolean outOfChina(LngLatPoint pt) {
double lat = +pt.getLat();
double lng = +pt.getLng();
// 纬度3.86~53.55,经度73.66~135.05
return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
}
/** WGS84坐标转GCJ02坐标 */
public static LngLatPoint wgs84_To_gcj02(LngLatPoint pt) {
double lng = pt.getLng();
double lat = pt.getLat();
if (outOfChina(pt)) {
return pt;
} else {
double dLat = transformLat(lng - 105.0, lat - 35.0);
double dLng = transformLng(lng - 105.0, lat - 35.0);
double radLat = lat / 180.0 * Math.PI;
double magic = Math.sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * Math.PI);
dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * Math.PI);
double mgLat = lat + dLat;
double mgLng = lng + dLng;
return new LngLatPoint(mgLng, mgLat);
}
}
/** GCJ02坐标转WGS84坐标 */
public static LngLatPoint gcj02_To_wgs84(LngLatPoint pt) {
double lng = pt.getLng();
double lat = pt.getLat();
if (outOfChina(pt)) {
return pt;
} else {
double dlat = transformLat(lng - 105.0, lat - 35.0);
double dlng = transformLng(lng - 105.0, lat - 35.0);
double radlat = lat / 180.0 * Math.PI;
double magic = Math.sin(radlat);
magic = 1 - EE * magic * magic;
double sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * Math.PI);
dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * Math.PI);
double mglat = lat + dlat;
double mglng = lng + dlng;
return new LngLatPoint(lng * 2 - mglng, lat * 2 - mglat);
}
}
private static double transformLat(double lat, double lng) {
double ret =
-100.0
+ 2.0 * lat
+ 3.0 * lng
+ 0.2 * lng * lng
+ 0.1 * lat * lng
+ 0.2 * Math.sqrt(Math.abs(lat));
ret +=
(20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0;
ret +=
(160.0 * Math.sin(lng / 12.0 * Math.PI) + 320 * Math.sin(lng * Math.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLng(double lat, double lng) {
double ret =
300.0
+ lat
+ 2.0 * lng
+ 0.1 * lat * lat
+ 0.1 * lat * lng
+ 0.1 * Math.sqrt(Math.abs(lat));
ret +=
(20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0;
ret +=
(150.0 * Math.sin(lat / 12.0 * Math.PI) + 300.0 * Math.sin(lat / 30.0 * Math.PI))
* 2.0
/ 3.0;
return ret;
}
}
@Data
class MercatorPoint implements Serializable {
private static final long serialVersionUID = 4066123199303085477L;
private Double lng;
private Double lat;
public MercatorPoint(double lng, double lat) {
this.lng = lng;
this.lat = lat;
}
public LngLatPoint convert2LngLat() {
return GeoUtils.Mercator2LngLat(this);
}
}
@Data
class LngLatPoint implements Serializable {
private static final long serialVersionUID = -3504030834818220866L;
private Double lng;
private Double lat;
public LngLatPoint(double lng, double lat) {
this.lng = lng;
this.lat = lat;
}
public MercatorPoint convert2Mercator() {
return GeoUtils.LngLat2Mercator(this);
}
}
@Data
class Polygon implements Serializable {
private static final long serialVersionUID = 8429062630741585169L;
ArrayList<MercatorPoint> path;
public Polygon(List<MercatorPoint> path) {
this.path = (ArrayList<MercatorPoint>) path;
}
}
@Data
class Tile implements Serializable {
private static final long serialVersionUID = -3598715656639420131L;
private Integer z;
private Integer x;
private Integer y;
private MercatorPoint topLeft;
private MercatorPoint topRight;
private MercatorPoint bottomLeft;
private MercatorPoint bottomRight;
public Tile() {}
public Tile(int z, int x, int y) {
this.z = z;
this.x = x;
this.y = y;
}
}
@Data
class Bound {
private MercatorPoint topLeft;
private MercatorPoint topRight;
private MercatorPoint bottomLeft;
private MercatorPoint bottomRight;
}
|
48861_12 | /**
* Copyright CMW Mobile.com, 2010.
*/
package com.cmwmobile.android.samples;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import org.bspeice.minimalbible.R;
import org.jetbrains.annotations.NotNull;
/**
* The SeekBarDialogPreference class is a DialogPreference based and provides a
* seekbar preference.
*
* @author Casper Wakkers
*/
public class SeekBarDialogPreference extends
DialogPreference implements SeekBar.OnSeekBarChangeListener {
// Layout widgets.
private SeekBar seekBar = null;
private TextView valueText = null;
// Custom xml attributes.
private int maximumValue = 0;
private int minimumValue = 0;
private int stepSize = 0;
private String units = null;
private int value = 0;
/**
* The SeekBarDialogPreference constructor.
*
* @param context of this preference.
* @param attrs custom xml attributes.
*/
public SeekBarDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.SeekBarDialogPreference);
maximumValue = typedArray.getInteger(
R.styleable.SeekBarDialogPreference_maximumValue, 0);
minimumValue = typedArray.getInteger(
R.styleable.SeekBarDialogPreference_minimumValue, 0);
stepSize = typedArray.getInteger(
R.styleable.SeekBarDialogPreference_stepSize, 1);
units = typedArray.getString(
R.styleable.SeekBarDialogPreference_units);
typedArray.recycle();
}
/**
* {@inheritDoc}
*/
@Override
protected View onCreateDialogView() {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater.inflate(
R.layout.seekbardialogpreference_layout, null);
seekBar = (SeekBar) view.findViewById(R.id.preference_seekbar);
valueText = (TextView) view.findViewById(R.id.preference_text);
// Get the persistent value and correct it for the minimum value.
value = getPersistedInt(minimumValue) - minimumValue;
// You're never know...
if (value < 0) {
value = 0;
}
seekBar.setKeyProgressIncrement(stepSize);
seekBar.setMax(maximumValue - minimumValue);
// setProgress must come before we start listening to events, otherwise
// we may receive the initialization (i.e. 0) event destroying our value
seekBar.setProgress(value);
updateValueText(value);
seekBar.setOnSeekBarChangeListener(this);
return view;
}
/**
* {@inheritDoc}
*/
@Override
public void onProgressChanged(@NotNull SeekBar seek, int newValue,
boolean fromTouch) {
// Round the value to the closest integer value.
if (stepSize >= 1) {
value = Math.round(newValue / stepSize) * stepSize;
} else {
value = newValue;
}
updateValueText(value);
callChangeListener(value);
}
private void updateValueText(int value) {
valueText.setText(String.valueOf(value + minimumValue) +
(units == null ? "" : units));
}
@Override
public void onDialogClosed(boolean positiveResult) {
if (positiveResult && shouldPersist()) {
setSummary((value + minimumValue) + " " + units);
persistInt(value + minimumValue);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public CharSequence getSummary() {
// We have to use getPersistedInt over `value` since it will not have
// been set yet.
return getPersistedInt(minimumValue) + " " + units;
}
} | MinimalBible/MinimalBible | app/src/main/java/com/cmwmobile/android/samples/SeekBarDialogPreference.java | 1,178 | // been set yet. | line_comment | nl | /**
* Copyright CMW Mobile.com, 2010.
*/
package com.cmwmobile.android.samples;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import org.bspeice.minimalbible.R;
import org.jetbrains.annotations.NotNull;
/**
* The SeekBarDialogPreference class is a DialogPreference based and provides a
* seekbar preference.
*
* @author Casper Wakkers
*/
public class SeekBarDialogPreference extends
DialogPreference implements SeekBar.OnSeekBarChangeListener {
// Layout widgets.
private SeekBar seekBar = null;
private TextView valueText = null;
// Custom xml attributes.
private int maximumValue = 0;
private int minimumValue = 0;
private int stepSize = 0;
private String units = null;
private int value = 0;
/**
* The SeekBarDialogPreference constructor.
*
* @param context of this preference.
* @param attrs custom xml attributes.
*/
public SeekBarDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.SeekBarDialogPreference);
maximumValue = typedArray.getInteger(
R.styleable.SeekBarDialogPreference_maximumValue, 0);
minimumValue = typedArray.getInteger(
R.styleable.SeekBarDialogPreference_minimumValue, 0);
stepSize = typedArray.getInteger(
R.styleable.SeekBarDialogPreference_stepSize, 1);
units = typedArray.getString(
R.styleable.SeekBarDialogPreference_units);
typedArray.recycle();
}
/**
* {@inheritDoc}
*/
@Override
protected View onCreateDialogView() {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater.inflate(
R.layout.seekbardialogpreference_layout, null);
seekBar = (SeekBar) view.findViewById(R.id.preference_seekbar);
valueText = (TextView) view.findViewById(R.id.preference_text);
// Get the persistent value and correct it for the minimum value.
value = getPersistedInt(minimumValue) - minimumValue;
// You're never know...
if (value < 0) {
value = 0;
}
seekBar.setKeyProgressIncrement(stepSize);
seekBar.setMax(maximumValue - minimumValue);
// setProgress must come before we start listening to events, otherwise
// we may receive the initialization (i.e. 0) event destroying our value
seekBar.setProgress(value);
updateValueText(value);
seekBar.setOnSeekBarChangeListener(this);
return view;
}
/**
* {@inheritDoc}
*/
@Override
public void onProgressChanged(@NotNull SeekBar seek, int newValue,
boolean fromTouch) {
// Round the value to the closest integer value.
if (stepSize >= 1) {
value = Math.round(newValue / stepSize) * stepSize;
} else {
value = newValue;
}
updateValueText(value);
callChangeListener(value);
}
private void updateValueText(int value) {
valueText.setText(String.valueOf(value + minimumValue) +
(units == null ? "" : units));
}
@Override
public void onDialogClosed(boolean positiveResult) {
if (positiveResult && shouldPersist()) {
setSummary((value + minimumValue) + " " + units);
persistInt(value + minimumValue);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public CharSequence getSummary() {
// We have to use getPersistedInt over `value` since it will not have
// been set<SUF>
return getPersistedInt(minimumValue) + " " + units;
}
} |
191992_3 | package com.lilithsthrone.game.dialogue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.lilithsthrone.controller.xmlParsing.XMLUtil;
import com.lilithsthrone.game.Game;
import com.lilithsthrone.game.character.GameCharacter;
import com.lilithsthrone.game.character.npc.NPC;
import com.lilithsthrone.game.character.npc.dominion.Daddy;
import com.lilithsthrone.game.character.npc.dominion.Kalahari;
import com.lilithsthrone.game.character.npc.dominion.Ralph;
import com.lilithsthrone.game.dialogue.places.dominion.helenaHotel.HelenaConversationTopic;
import com.lilithsthrone.game.dialogue.places.submission.impFortress.ImpFortressDialogue;
import com.lilithsthrone.game.occupantManagement.slave.SlaveJob;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.utils.Util;
import com.lilithsthrone.utils.XMLSaving;
import com.lilithsthrone.utils.colours.Colour;
import com.lilithsthrone.utils.colours.PresetColour;
/**
* @since 0.1.0
* @version 0.4.4
* @author Innoxia
*/
public class DialogueFlags implements XMLSaving {
private int muggerDemand1 = 250; // Dominion
private int muggerDemand2 = 500; // Submission
private int muggerDemand3 = 750; // Elis
private int prostituteFine = 10_000;
public Set<AbstractDialogueFlagValue> values;
public int ralphDiscount;
public int scarlettPrice;
public int eponaStamps;
// Timers:
public Map<String, Long> savedLongs = new HashMap<>();
public int helenaSlaveOrderDay;
public int impCitadelImpWave;
// Amount of dialogue choices you can make before offspring interaction ends:
public int offspringDialogueTokens = 2;
// Murk transformation stage tracking:
private int murkPlayerTfStage;
private int murkCompanionTfStage;
private String slaveTrader;
private String managementCompanion;
private SlaveJob slaveryManagerJobSelected;
private Colour natalyaCollarColour;
private int natalyaPoints;
private String sadistNatalyaSlave;
// --- Sets: --- //
private Set<String> helenaConversationTopics = new HashSet<>();
// Reindeer event related flags:
private Set<String> reindeerEncounteredIDs = new HashSet<>();
private Set<String> reindeerWorkedForIDs = new HashSet<>();
private Set<String> reindeerFuckedIDs = new HashSet<>();
// Enforcer warehouse guards defeated:
public Set<String> warehouseDefeatedIDs = new HashSet<>();
// // Storage tiles checked:
// public Set<Vector2i> supplierStorageRoomsChecked = new HashSet<>();
public DialogueFlags() {
values = new HashSet<>();
slaveTrader = null;
managementCompanion = null;
slaveryManagerJobSelected = SlaveJob.IDLE;
// ralphDiscountStartTime = -1;
// kalahariBreakStartTime = -1;
// daddyResetTimer = -1;
// candiSexTimer = -1;
// ralphSexTimer = -1;
//
// impFortressAlphaDefeatedTime
// = impFortressDemonDefeatedTime
// = impFortressFemalesDefeatedTime
// = impFortressMalesDefeatedTime
// = -50000;
helenaSlaveOrderDay = -1;
ralphDiscount = 0;
eponaStamps = 0;
scarlettPrice = 15000;
impCitadelImpWave = 0;
murkPlayerTfStage = 0;
murkCompanionTfStage = 0;
natalyaCollarColour = PresetColour.CLOTHING_BRONZE;
natalyaPoints = 0;
sadistNatalyaSlave = "";
}
public Element saveAsXML(Element parentElement, Document doc) {
Element element = doc.createElement("dialogueFlags");
parentElement.appendChild(element);
// XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscountStartTime", String.valueOf(ralphDiscountStartTime));
// XMLUtil.createXMLElementWithValue(doc, element, "kalahariBreakStartTime", String.valueOf(kalahariBreakStartTime));
// XMLUtil.createXMLElementWithValue(doc, element, "daddyResetTimer", String.valueOf(daddyResetTimer));
//
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressAlphaDefeatedTime", String.valueOf(impFortressAlphaDefeatedTime));
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressDemonDefeatedTime", String.valueOf(impFortressDemonDefeatedTime));
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressFemalesDefeatedTime", String.valueOf(impFortressFemalesDefeatedTime));
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressMalesDefeatedTime", String.valueOf(impFortressMalesDefeatedTime));
XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscount", String.valueOf(ralphDiscount));
XMLUtil.createXMLElementWithValue(doc, element, "scarlettPrice", String.valueOf(scarlettPrice));
XMLUtil.createXMLElementWithValue(doc, element, "eponaStamps", String.valueOf(eponaStamps));
XMLUtil.createXMLElementWithValue(doc, element, "helenaSlaveOrderDay", String.valueOf(helenaSlaveOrderDay));
XMLUtil.createXMLElementWithValue(doc, element, "impCitadelImpWave", String.valueOf(impCitadelImpWave));
XMLUtil.createXMLElementWithValue(doc, element, "murkPlayerTfStage", String.valueOf(murkPlayerTfStage));
XMLUtil.createXMLElementWithValue(doc, element, "murkCompanionTfStage", String.valueOf(murkCompanionTfStage));
XMLUtil.createXMLElementWithValue(doc, element, "offspringDialogueTokens", String.valueOf(offspringDialogueTokens));
XMLUtil.createXMLElementWithValue(doc, element, "slaveTrader", slaveTrader);
XMLUtil.createXMLElementWithValue(doc, element, "slaveryManagerSlaveSelected", managementCompanion);
XMLUtil.createXMLElementWithValue(doc, element, "natalyaCollarColour", PresetColour.getIdFromColour(natalyaCollarColour));
XMLUtil.createXMLElementWithValue(doc, element, "natalyaPoints", String.valueOf(natalyaPoints));
XMLUtil.createXMLElementWithValue(doc, element, "sadistNatalyaSlave", sadistNatalyaSlave);
Element savedLongsElement = doc.createElement("savedLongs");
element.appendChild(savedLongsElement);
for(Entry<String, Long> savedLong : savedLongs.entrySet()) {
Element save = doc.createElement("save");
savedLongsElement.appendChild(save);
save.setAttribute("id", savedLong.getKey());
save.setTextContent(String.valueOf(savedLong.getValue()));
}
Element valuesElement = doc.createElement("dialogueValues");
element.appendChild(valuesElement);
for(AbstractDialogueFlagValue value : values) {
XMLUtil.createXMLElementWithValue(doc, valuesElement, "dialogueValue", DialogueFlagValue.getIdFromDialogueFlagValue(value));
}
saveSet(element, doc, helenaConversationTopics, "helenaConversationTopics");
saveSet(element, doc, reindeerEncounteredIDs, "reindeerEncounteredIDs");
saveSet(element, doc, reindeerWorkedForIDs, "reindeerWorkedForIDs");
saveSet(element, doc, reindeerFuckedIDs, "reindeerFuckedIDs");
saveSet(element, doc, warehouseDefeatedIDs, "warehouseDefeatedIDs");
// Element supplierStorageRoomsCheckedElement = doc.createElement("supplierStorageRoomsChecked");
// element.appendChild(supplierStorageRoomsCheckedElement);
// for(Vector2i value : supplierStorageRoomsChecked) {
// Element location = doc.createElement("location");
// supplierStorageRoomsCheckedElement.appendChild(location);
// XMLUtil.addAttribute(doc, location, "x", String.valueOf(value.getX()));
// XMLUtil.addAttribute(doc, location, "y", String.valueOf(value.getY()));
// }
return element;
}
public static DialogueFlags loadFromXML(Element parentElement, Document doc) {
DialogueFlags newFlags = new DialogueFlags();
newFlags.ralphDiscount = Integer.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscount").item(0)).getAttribute("value"));
newFlags.scarlettPrice = Integer.valueOf(((Element)parentElement.getElementsByTagName("scarlettPrice").item(0)).getAttribute("value"));
newFlags.offspringDialogueTokens = Integer.valueOf(((Element)parentElement.getElementsByTagName("offspringDialogueTokens").item(0)).getAttribute("value"));
newFlags.slaveTrader = ((Element)parentElement.getElementsByTagName("slaveTrader").item(0)).getAttribute("value");
newFlags.managementCompanion = ((Element)parentElement.getElementsByTagName("slaveryManagerSlaveSelected").item(0)).getAttribute("value");
try {
newFlags.eponaStamps = Integer.valueOf(((Element)parentElement.getElementsByTagName("eponaStamps").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.helenaSlaveOrderDay = Integer.valueOf(((Element)parentElement.getElementsByTagName("helenaSlaveOrderDay").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.impCitadelImpWave = Integer.valueOf(((Element)parentElement.getElementsByTagName("impCitadelImpWave").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.murkPlayerTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkPlayerTfStage").item(0)).getAttribute("value"));
newFlags.murkCompanionTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkCompanionTfStage").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.natalyaCollarColour = PresetColour.getColourFromId(((Element)parentElement.getElementsByTagName("natalyaCollarColour").item(0)).getAttribute("value"));
if(newFlags.natalyaCollarColour==PresetColour.CLOTHING_STEEL) {
newFlags.natalyaCollarColour = PresetColour.CLOTHING_BRONZE;
}
newFlags.natalyaPoints = Integer.valueOf(((Element)parentElement.getElementsByTagName("natalyaPoints").item(0)).getAttribute("value"));
newFlags.sadistNatalyaSlave = ((Element)parentElement.getElementsByTagName("sadistNatalyaSlave").item(0)).getAttribute("value");
} catch(Exception ex) {
}
// Load saved longs:
if(parentElement.getElementsByTagName("savedLongs").item(0)!=null) {
for(int i=0; i<((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").getLength(); i++){
Element e = (Element) ((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").item(i);
String id = e.getAttribute("id");
if(Main.isVersionOlderThan(Game.loadingVersion, "0.3.15")) {
if(id.equals("MACHINES")
|| id.equals("INTERCOM")
|| id.equals("BUSINESS")
|| id.equals("BOUNTY_HUNTERS")) {
id = "KAY_"+id;
}
}
newFlags.setSavedLong(id, Long.valueOf(e.getTextContent()));
}
} else { // Support for old timers (pre-version 0.3.9):
newFlags.setSavedLong(Ralph.RALPH_DISCOUNT_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscountStartTime").item(0)).getAttribute("value")));
try {
newFlags.setSavedLong(Kalahari.KALAHARI_BREAK_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("kalahariBreakStartTime").item(0)).getAttribute("value")));
} catch(Exception ex) {
}
try {
newFlags.setSavedLong(Daddy.DADDY_RESET_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("daddyResetTimer").item(0)).getAttribute("value")));
} catch(Exception ex) {
}
try {
if(!Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) {
newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_ALPHA_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressAlphaDefeatedTime").item(0)).getAttribute("value")));
newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_FEMALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressFemalesDefeatedTime").item(0)).getAttribute("value")));
newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_MALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressMalesDefeatedTime").item(0)).getAttribute("value")));
}
} catch(Exception ex) {
}
}
// Load flags:
for(int i=0; i<((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").getLength(); i++){
Element e = (Element) ((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").item(i);
try {
String flag = e.getAttribute("value");
if(flag.equalsIgnoreCase("punishedByAlexa")) {
newFlags.values.add(DialogueFlagValue.punishedByHelena);
} else {
AbstractDialogueFlagValue flagValue = DialogueFlagValue.getDialogueFlagValueFromId(flag);
if(flagValue!=null) {
newFlags.values.add(flagValue);
}
}
} catch(Exception ex) {
}
}
if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.6.1")) {
newFlags.values.remove(DialogueFlagValue.axelIntroduced);
newFlags.values.remove(DialogueFlagValue.roxyIntroduced);
newFlags.values.remove(DialogueFlagValue.eponaIntroduced);
}
if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) { // Add defeated flags so that the fortress will reset.
newFlags.values.add(DialogueFlagValue.impFortressAlphaDefeated);
newFlags.values.add(DialogueFlagValue.impFortressDemonDefeated);
newFlags.values.add(DialogueFlagValue.impFortressFemalesDefeated);
newFlags.values.add(DialogueFlagValue.impFortressMalesDefeated);
}
loadSet(parentElement, doc, newFlags.helenaConversationTopics, "helenaConversationTopics");
loadSet(parentElement, doc, newFlags.reindeerEncounteredIDs, "reindeerEncounteredIDs");
loadSet(parentElement, doc, newFlags.reindeerWorkedForIDs, "reindeerWorkedForIDs");
loadSet(parentElement, doc, newFlags.reindeerFuckedIDs, "reindeerFuckedIDs");
loadSet(parentElement, doc, newFlags.warehouseDefeatedIDs, "warehouseDefeatedIDs");
// if(parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)!=null) {
// for(int i=0; i<((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").getLength(); i++){
// Element e = (Element) ((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").item(i);
//
// newFlags.supplierStorageRoomsChecked.add(
// new Vector2i(
// Integer.valueOf(e.getAttribute("x")),
// Integer.valueOf(e.getAttribute("y"))));
// }
// }
return newFlags;
}
private static void saveSet(Element parentElement, Document doc, Set<String> set, String title) {
Element valuesElement = doc.createElement(title);
parentElement.appendChild(valuesElement);
for(String value : set) {
XMLUtil.createXMLElementWithValue(doc, valuesElement, "value", value.toString());
}
}
private static void loadSet(Element parentElement, Document doc, Set<String> set, String title) {
try {
if(parentElement.getElementsByTagName(title).item(0)!=null) {
for(int i=0; i<((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").getLength(); i++){
Element e = (Element) ((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").item(i);
set.add(e.getAttribute("value"));
}
}
} catch(Exception ex) {
}
}
public void applyTimePassingResets(int startHour, int hoursPassed) {
for(AbstractDialogueFlagValue flag : new HashSet<>(values)) {
if(flag.getResetHour()>-1) {
if((startHour<flag.getResetHour() && startHour+hoursPassed>=flag.getResetHour())
|| ((startHour-24)+hoursPassed>=flag.getResetHour())) {
values.remove(flag);
}
}
}
}
public boolean hasFlag(AbstractDialogueFlagValue flag) {
return values.contains(flag);
}
public boolean hasFlag(String flagId) {
return values.contains(DialogueFlagValue.getDialogueFlagValueFromId(flagId));
}
public void setFlag(String flagId, boolean flagMarker) {
if(flagMarker) {
values.add(DialogueFlagValue.getDialogueFlagValueFromId(flagId));
} else {
values.remove(DialogueFlagValue.getDialogueFlagValueFromId(flagId));
}
}
public void setFlag(AbstractDialogueFlagValue flag, boolean flagMarker) {
if(flagMarker) {
values.add(flag);
} else {
values.remove(flag);
}
}
public void setSavedLong(String id, long value) {
savedLongs.put(id, value);
}
public void setSavedLong(String id, String value) {
try {
long valueLong = Long.valueOf(value);
setSavedLong(id, valueLong);
} catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* @return Increments the long saved to this id. Sets to -1 before incrementing if there was no entry found.
*/
public void incrementSavedLong(String id, long increment) {
savedLongs.put(id, getSavedLong(id)+increment);
}
public boolean hasSavedLong(String id) {
return savedLongs.containsKey(id);
}
public void removeSavedLong(String id) {
savedLongs.remove(id);
}
/**
* @return The long saved to this id. Sets and returns -1 if there was no entry found.
*/
public long getSavedLong(String id) {
savedLongs.putIfAbsent(id, -1l);
return savedLongs.get(id);
}
public int getMuggerDemand1() {
return muggerDemand1;
}
public int getMuggerDemand2() {
return muggerDemand2;
}
public int getMuggerDemand3() {
return muggerDemand3;
}
public int getProstituteFine() {
return prostituteFine;
}
public NPC getSlaveTrader() {
if(slaveTrader==null || slaveTrader.isEmpty()) {
return null;
}
try {
return (NPC) Main.game.getNPCById(slaveTrader);
} catch (Exception e) {
Util.logGetNpcByIdError("getSlaveTrader()", slaveTrader);
return null;
}
}
public void setSlaveTrader(GameCharacter slaveTrader) {
if(slaveTrader==null) {
this.slaveTrader = null;
} else {
this.slaveTrader = slaveTrader.getId();
}
}
public String getSlaveTraderId() {
return slaveTrader;
}
public void setSlaveTraderId(String slaveTrader) {
this.slaveTrader = slaveTrader;
}
public NPC getManagementCompanion() {
if(managementCompanion==null || managementCompanion.isEmpty()) {
return null;
}
try {
return (NPC) Main.game.getNPCById(managementCompanion);
} catch (Exception e) {
Util.logGetNpcByIdError("getManagementCompanion()", managementCompanion);
//e.printStackTrace();
return null;
}
}
public void setManagementCompanion(GameCharacter managementCompanion) {
if(managementCompanion==null) {
this.managementCompanion = null;
} else {
this.managementCompanion = managementCompanion.getId();
}
}
public String getManagementCompanionId() {
return managementCompanion;
}
public void setManagementCompanionId(String managementCompanion) {
this.managementCompanion = managementCompanion;
}
// Reindeer event:
public SlaveJob getSlaveryManagerJobSelected() {
return slaveryManagerJobSelected;
}
public void setSlaveryManagerJobSelected(SlaveJob slaveryManagerJobSelected) {
this.slaveryManagerJobSelected = slaveryManagerJobSelected;
}
public void addHelenaConversationTopic(HelenaConversationTopic topic) {
helenaConversationTopics.add(topic.toString());
}
public boolean hasHelenaConversationTopic(HelenaConversationTopic topic) {
return helenaConversationTopics.contains(topic.toString());
}
public void addReindeerEncountered(String reindeerID) {
reindeerEncounteredIDs.add(reindeerID);
}
public boolean hasEncounteredReindeer(String reindeerID) {
return reindeerEncounteredIDs.contains(reindeerID);
}
public boolean hasEncounteredAnyReindeers() {
return !reindeerEncounteredIDs.isEmpty();
}
public void addReindeerDailyWorkedFor(String reindeerID) {
reindeerWorkedForIDs.add(reindeerID);
}
public boolean hasWorkedForReindeer(String reindeerID) {
return reindeerWorkedForIDs.contains(reindeerID);
}
public void addReindeerDailyFucked(String reindeerID) {
reindeerFuckedIDs.add(reindeerID);
}
public boolean hasFuckedReindeer(String reindeerID) {
return reindeerFuckedIDs.contains(reindeerID);
}
public void dailyReindeerReset(String reindeerID) {
reindeerWorkedForIDs.remove(reindeerID);
}
public int getMurkTfStage(GameCharacter target) {
if(target.isPlayer()) {
return murkPlayerTfStage;
}
return murkCompanionTfStage;
}
public void setMurkTfStage(GameCharacter target, int stage) {
if(target.isPlayer()) {
this.murkPlayerTfStage = stage;
} else {
this.murkCompanionTfStage = stage;
}
}
public Colour getNatalyaCollarColour() {
return natalyaCollarColour;
}
public void setNatalyaCollarColour(Colour natalyaCollarColour) {
this.natalyaCollarColour = natalyaCollarColour;
}
public int getNatalyaPoints() {
return natalyaPoints;
}
public void setNatalyaPoints(int natalyaPoints) {
this.natalyaPoints = natalyaPoints;
if(this.natalyaPoints<0) {
this.natalyaPoints = 0;
}
}
public String incrementNatalyaPoints(int increment) {
setNatalyaPoints(getNatalyaPoints()+increment);
boolean plural = increment!=1;
StringBuilder sb = new StringBuilder();
sb.append("<p style='text-align:center;'>");
if(increment>0) {
sb.append("You [style.colourGood(gained)] [style.boldPink("+increment+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!");
} else {
sb.append("You [style.colourBad(lost)] [style.boldPink("+(-increment)+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!");
}
sb.append("<br/>You now have [style.boldPink("+getNatalyaPoints()+")] [style.colourPinkLight(filly points)]!");
sb.append("</p>");
return sb.toString();
}
public String getSadistNatalyaSlave() {
return sadistNatalyaSlave;
}
public void setSadistNatalyaSlave(String sadistNatalyaSlave) {
this.sadistNatalyaSlave = sadistNatalyaSlave;
}
}
| MintyChip/liliths-throne-public | src/com/lilithsthrone/game/dialogue/DialogueFlags.java | 7,612 | // --- Sets: --- // | line_comment | nl | package com.lilithsthrone.game.dialogue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.lilithsthrone.controller.xmlParsing.XMLUtil;
import com.lilithsthrone.game.Game;
import com.lilithsthrone.game.character.GameCharacter;
import com.lilithsthrone.game.character.npc.NPC;
import com.lilithsthrone.game.character.npc.dominion.Daddy;
import com.lilithsthrone.game.character.npc.dominion.Kalahari;
import com.lilithsthrone.game.character.npc.dominion.Ralph;
import com.lilithsthrone.game.dialogue.places.dominion.helenaHotel.HelenaConversationTopic;
import com.lilithsthrone.game.dialogue.places.submission.impFortress.ImpFortressDialogue;
import com.lilithsthrone.game.occupantManagement.slave.SlaveJob;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.utils.Util;
import com.lilithsthrone.utils.XMLSaving;
import com.lilithsthrone.utils.colours.Colour;
import com.lilithsthrone.utils.colours.PresetColour;
/**
* @since 0.1.0
* @version 0.4.4
* @author Innoxia
*/
public class DialogueFlags implements XMLSaving {
private int muggerDemand1 = 250; // Dominion
private int muggerDemand2 = 500; // Submission
private int muggerDemand3 = 750; // Elis
private int prostituteFine = 10_000;
public Set<AbstractDialogueFlagValue> values;
public int ralphDiscount;
public int scarlettPrice;
public int eponaStamps;
// Timers:
public Map<String, Long> savedLongs = new HashMap<>();
public int helenaSlaveOrderDay;
public int impCitadelImpWave;
// Amount of dialogue choices you can make before offspring interaction ends:
public int offspringDialogueTokens = 2;
// Murk transformation stage tracking:
private int murkPlayerTfStage;
private int murkCompanionTfStage;
private String slaveTrader;
private String managementCompanion;
private SlaveJob slaveryManagerJobSelected;
private Colour natalyaCollarColour;
private int natalyaPoints;
private String sadistNatalyaSlave;
// --- Sets:<SUF>
private Set<String> helenaConversationTopics = new HashSet<>();
// Reindeer event related flags:
private Set<String> reindeerEncounteredIDs = new HashSet<>();
private Set<String> reindeerWorkedForIDs = new HashSet<>();
private Set<String> reindeerFuckedIDs = new HashSet<>();
// Enforcer warehouse guards defeated:
public Set<String> warehouseDefeatedIDs = new HashSet<>();
// // Storage tiles checked:
// public Set<Vector2i> supplierStorageRoomsChecked = new HashSet<>();
public DialogueFlags() {
values = new HashSet<>();
slaveTrader = null;
managementCompanion = null;
slaveryManagerJobSelected = SlaveJob.IDLE;
// ralphDiscountStartTime = -1;
// kalahariBreakStartTime = -1;
// daddyResetTimer = -1;
// candiSexTimer = -1;
// ralphSexTimer = -1;
//
// impFortressAlphaDefeatedTime
// = impFortressDemonDefeatedTime
// = impFortressFemalesDefeatedTime
// = impFortressMalesDefeatedTime
// = -50000;
helenaSlaveOrderDay = -1;
ralphDiscount = 0;
eponaStamps = 0;
scarlettPrice = 15000;
impCitadelImpWave = 0;
murkPlayerTfStage = 0;
murkCompanionTfStage = 0;
natalyaCollarColour = PresetColour.CLOTHING_BRONZE;
natalyaPoints = 0;
sadistNatalyaSlave = "";
}
public Element saveAsXML(Element parentElement, Document doc) {
Element element = doc.createElement("dialogueFlags");
parentElement.appendChild(element);
// XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscountStartTime", String.valueOf(ralphDiscountStartTime));
// XMLUtil.createXMLElementWithValue(doc, element, "kalahariBreakStartTime", String.valueOf(kalahariBreakStartTime));
// XMLUtil.createXMLElementWithValue(doc, element, "daddyResetTimer", String.valueOf(daddyResetTimer));
//
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressAlphaDefeatedTime", String.valueOf(impFortressAlphaDefeatedTime));
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressDemonDefeatedTime", String.valueOf(impFortressDemonDefeatedTime));
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressFemalesDefeatedTime", String.valueOf(impFortressFemalesDefeatedTime));
// XMLUtil.createXMLElementWithValue(doc, element, "impFortressMalesDefeatedTime", String.valueOf(impFortressMalesDefeatedTime));
XMLUtil.createXMLElementWithValue(doc, element, "ralphDiscount", String.valueOf(ralphDiscount));
XMLUtil.createXMLElementWithValue(doc, element, "scarlettPrice", String.valueOf(scarlettPrice));
XMLUtil.createXMLElementWithValue(doc, element, "eponaStamps", String.valueOf(eponaStamps));
XMLUtil.createXMLElementWithValue(doc, element, "helenaSlaveOrderDay", String.valueOf(helenaSlaveOrderDay));
XMLUtil.createXMLElementWithValue(doc, element, "impCitadelImpWave", String.valueOf(impCitadelImpWave));
XMLUtil.createXMLElementWithValue(doc, element, "murkPlayerTfStage", String.valueOf(murkPlayerTfStage));
XMLUtil.createXMLElementWithValue(doc, element, "murkCompanionTfStage", String.valueOf(murkCompanionTfStage));
XMLUtil.createXMLElementWithValue(doc, element, "offspringDialogueTokens", String.valueOf(offspringDialogueTokens));
XMLUtil.createXMLElementWithValue(doc, element, "slaveTrader", slaveTrader);
XMLUtil.createXMLElementWithValue(doc, element, "slaveryManagerSlaveSelected", managementCompanion);
XMLUtil.createXMLElementWithValue(doc, element, "natalyaCollarColour", PresetColour.getIdFromColour(natalyaCollarColour));
XMLUtil.createXMLElementWithValue(doc, element, "natalyaPoints", String.valueOf(natalyaPoints));
XMLUtil.createXMLElementWithValue(doc, element, "sadistNatalyaSlave", sadistNatalyaSlave);
Element savedLongsElement = doc.createElement("savedLongs");
element.appendChild(savedLongsElement);
for(Entry<String, Long> savedLong : savedLongs.entrySet()) {
Element save = doc.createElement("save");
savedLongsElement.appendChild(save);
save.setAttribute("id", savedLong.getKey());
save.setTextContent(String.valueOf(savedLong.getValue()));
}
Element valuesElement = doc.createElement("dialogueValues");
element.appendChild(valuesElement);
for(AbstractDialogueFlagValue value : values) {
XMLUtil.createXMLElementWithValue(doc, valuesElement, "dialogueValue", DialogueFlagValue.getIdFromDialogueFlagValue(value));
}
saveSet(element, doc, helenaConversationTopics, "helenaConversationTopics");
saveSet(element, doc, reindeerEncounteredIDs, "reindeerEncounteredIDs");
saveSet(element, doc, reindeerWorkedForIDs, "reindeerWorkedForIDs");
saveSet(element, doc, reindeerFuckedIDs, "reindeerFuckedIDs");
saveSet(element, doc, warehouseDefeatedIDs, "warehouseDefeatedIDs");
// Element supplierStorageRoomsCheckedElement = doc.createElement("supplierStorageRoomsChecked");
// element.appendChild(supplierStorageRoomsCheckedElement);
// for(Vector2i value : supplierStorageRoomsChecked) {
// Element location = doc.createElement("location");
// supplierStorageRoomsCheckedElement.appendChild(location);
// XMLUtil.addAttribute(doc, location, "x", String.valueOf(value.getX()));
// XMLUtil.addAttribute(doc, location, "y", String.valueOf(value.getY()));
// }
return element;
}
public static DialogueFlags loadFromXML(Element parentElement, Document doc) {
DialogueFlags newFlags = new DialogueFlags();
newFlags.ralphDiscount = Integer.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscount").item(0)).getAttribute("value"));
newFlags.scarlettPrice = Integer.valueOf(((Element)parentElement.getElementsByTagName("scarlettPrice").item(0)).getAttribute("value"));
newFlags.offspringDialogueTokens = Integer.valueOf(((Element)parentElement.getElementsByTagName("offspringDialogueTokens").item(0)).getAttribute("value"));
newFlags.slaveTrader = ((Element)parentElement.getElementsByTagName("slaveTrader").item(0)).getAttribute("value");
newFlags.managementCompanion = ((Element)parentElement.getElementsByTagName("slaveryManagerSlaveSelected").item(0)).getAttribute("value");
try {
newFlags.eponaStamps = Integer.valueOf(((Element)parentElement.getElementsByTagName("eponaStamps").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.helenaSlaveOrderDay = Integer.valueOf(((Element)parentElement.getElementsByTagName("helenaSlaveOrderDay").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.impCitadelImpWave = Integer.valueOf(((Element)parentElement.getElementsByTagName("impCitadelImpWave").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.murkPlayerTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkPlayerTfStage").item(0)).getAttribute("value"));
newFlags.murkCompanionTfStage = Integer.valueOf(((Element)parentElement.getElementsByTagName("murkCompanionTfStage").item(0)).getAttribute("value"));
} catch(Exception ex) {
}
try {
newFlags.natalyaCollarColour = PresetColour.getColourFromId(((Element)parentElement.getElementsByTagName("natalyaCollarColour").item(0)).getAttribute("value"));
if(newFlags.natalyaCollarColour==PresetColour.CLOTHING_STEEL) {
newFlags.natalyaCollarColour = PresetColour.CLOTHING_BRONZE;
}
newFlags.natalyaPoints = Integer.valueOf(((Element)parentElement.getElementsByTagName("natalyaPoints").item(0)).getAttribute("value"));
newFlags.sadistNatalyaSlave = ((Element)parentElement.getElementsByTagName("sadistNatalyaSlave").item(0)).getAttribute("value");
} catch(Exception ex) {
}
// Load saved longs:
if(parentElement.getElementsByTagName("savedLongs").item(0)!=null) {
for(int i=0; i<((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").getLength(); i++){
Element e = (Element) ((Element) parentElement.getElementsByTagName("savedLongs").item(0)).getElementsByTagName("save").item(i);
String id = e.getAttribute("id");
if(Main.isVersionOlderThan(Game.loadingVersion, "0.3.15")) {
if(id.equals("MACHINES")
|| id.equals("INTERCOM")
|| id.equals("BUSINESS")
|| id.equals("BOUNTY_HUNTERS")) {
id = "KAY_"+id;
}
}
newFlags.setSavedLong(id, Long.valueOf(e.getTextContent()));
}
} else { // Support for old timers (pre-version 0.3.9):
newFlags.setSavedLong(Ralph.RALPH_DISCOUNT_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("ralphDiscountStartTime").item(0)).getAttribute("value")));
try {
newFlags.setSavedLong(Kalahari.KALAHARI_BREAK_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("kalahariBreakStartTime").item(0)).getAttribute("value")));
} catch(Exception ex) {
}
try {
newFlags.setSavedLong(Daddy.DADDY_RESET_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("daddyResetTimer").item(0)).getAttribute("value")));
} catch(Exception ex) {
}
try {
if(!Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) {
newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_ALPHA_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressAlphaDefeatedTime").item(0)).getAttribute("value")));
newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_FEMALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressFemalesDefeatedTime").item(0)).getAttribute("value")));
newFlags.setSavedLong(ImpFortressDialogue.FORTRESS_MALES_CLEAR_TIMER_ID, Long.valueOf(((Element)parentElement.getElementsByTagName("impFortressMalesDefeatedTime").item(0)).getAttribute("value")));
}
} catch(Exception ex) {
}
}
// Load flags:
for(int i=0; i<((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").getLength(); i++){
Element e = (Element) ((Element) parentElement.getElementsByTagName("dialogueValues").item(0)).getElementsByTagName("dialogueValue").item(i);
try {
String flag = e.getAttribute("value");
if(flag.equalsIgnoreCase("punishedByAlexa")) {
newFlags.values.add(DialogueFlagValue.punishedByHelena);
} else {
AbstractDialogueFlagValue flagValue = DialogueFlagValue.getDialogueFlagValueFromId(flag);
if(flagValue!=null) {
newFlags.values.add(flagValue);
}
}
} catch(Exception ex) {
}
}
if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.6.1")) {
newFlags.values.remove(DialogueFlagValue.axelIntroduced);
newFlags.values.remove(DialogueFlagValue.roxyIntroduced);
newFlags.values.remove(DialogueFlagValue.eponaIntroduced);
}
if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.5")) { // Add defeated flags so that the fortress will reset.
newFlags.values.add(DialogueFlagValue.impFortressAlphaDefeated);
newFlags.values.add(DialogueFlagValue.impFortressDemonDefeated);
newFlags.values.add(DialogueFlagValue.impFortressFemalesDefeated);
newFlags.values.add(DialogueFlagValue.impFortressMalesDefeated);
}
loadSet(parentElement, doc, newFlags.helenaConversationTopics, "helenaConversationTopics");
loadSet(parentElement, doc, newFlags.reindeerEncounteredIDs, "reindeerEncounteredIDs");
loadSet(parentElement, doc, newFlags.reindeerWorkedForIDs, "reindeerWorkedForIDs");
loadSet(parentElement, doc, newFlags.reindeerFuckedIDs, "reindeerFuckedIDs");
loadSet(parentElement, doc, newFlags.warehouseDefeatedIDs, "warehouseDefeatedIDs");
// if(parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)!=null) {
// for(int i=0; i<((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").getLength(); i++){
// Element e = (Element) ((Element) parentElement.getElementsByTagName("supplierStorageRoomsChecked").item(0)).getElementsByTagName("location").item(i);
//
// newFlags.supplierStorageRoomsChecked.add(
// new Vector2i(
// Integer.valueOf(e.getAttribute("x")),
// Integer.valueOf(e.getAttribute("y"))));
// }
// }
return newFlags;
}
private static void saveSet(Element parentElement, Document doc, Set<String> set, String title) {
Element valuesElement = doc.createElement(title);
parentElement.appendChild(valuesElement);
for(String value : set) {
XMLUtil.createXMLElementWithValue(doc, valuesElement, "value", value.toString());
}
}
private static void loadSet(Element parentElement, Document doc, Set<String> set, String title) {
try {
if(parentElement.getElementsByTagName(title).item(0)!=null) {
for(int i=0; i<((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").getLength(); i++){
Element e = (Element) ((Element) parentElement.getElementsByTagName(title).item(0)).getElementsByTagName("value").item(i);
set.add(e.getAttribute("value"));
}
}
} catch(Exception ex) {
}
}
public void applyTimePassingResets(int startHour, int hoursPassed) {
for(AbstractDialogueFlagValue flag : new HashSet<>(values)) {
if(flag.getResetHour()>-1) {
if((startHour<flag.getResetHour() && startHour+hoursPassed>=flag.getResetHour())
|| ((startHour-24)+hoursPassed>=flag.getResetHour())) {
values.remove(flag);
}
}
}
}
public boolean hasFlag(AbstractDialogueFlagValue flag) {
return values.contains(flag);
}
public boolean hasFlag(String flagId) {
return values.contains(DialogueFlagValue.getDialogueFlagValueFromId(flagId));
}
public void setFlag(String flagId, boolean flagMarker) {
if(flagMarker) {
values.add(DialogueFlagValue.getDialogueFlagValueFromId(flagId));
} else {
values.remove(DialogueFlagValue.getDialogueFlagValueFromId(flagId));
}
}
public void setFlag(AbstractDialogueFlagValue flag, boolean flagMarker) {
if(flagMarker) {
values.add(flag);
} else {
values.remove(flag);
}
}
public void setSavedLong(String id, long value) {
savedLongs.put(id, value);
}
public void setSavedLong(String id, String value) {
try {
long valueLong = Long.valueOf(value);
setSavedLong(id, valueLong);
} catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* @return Increments the long saved to this id. Sets to -1 before incrementing if there was no entry found.
*/
public void incrementSavedLong(String id, long increment) {
savedLongs.put(id, getSavedLong(id)+increment);
}
public boolean hasSavedLong(String id) {
return savedLongs.containsKey(id);
}
public void removeSavedLong(String id) {
savedLongs.remove(id);
}
/**
* @return The long saved to this id. Sets and returns -1 if there was no entry found.
*/
public long getSavedLong(String id) {
savedLongs.putIfAbsent(id, -1l);
return savedLongs.get(id);
}
public int getMuggerDemand1() {
return muggerDemand1;
}
public int getMuggerDemand2() {
return muggerDemand2;
}
public int getMuggerDemand3() {
return muggerDemand3;
}
public int getProstituteFine() {
return prostituteFine;
}
public NPC getSlaveTrader() {
if(slaveTrader==null || slaveTrader.isEmpty()) {
return null;
}
try {
return (NPC) Main.game.getNPCById(slaveTrader);
} catch (Exception e) {
Util.logGetNpcByIdError("getSlaveTrader()", slaveTrader);
return null;
}
}
public void setSlaveTrader(GameCharacter slaveTrader) {
if(slaveTrader==null) {
this.slaveTrader = null;
} else {
this.slaveTrader = slaveTrader.getId();
}
}
public String getSlaveTraderId() {
return slaveTrader;
}
public void setSlaveTraderId(String slaveTrader) {
this.slaveTrader = slaveTrader;
}
public NPC getManagementCompanion() {
if(managementCompanion==null || managementCompanion.isEmpty()) {
return null;
}
try {
return (NPC) Main.game.getNPCById(managementCompanion);
} catch (Exception e) {
Util.logGetNpcByIdError("getManagementCompanion()", managementCompanion);
//e.printStackTrace();
return null;
}
}
public void setManagementCompanion(GameCharacter managementCompanion) {
if(managementCompanion==null) {
this.managementCompanion = null;
} else {
this.managementCompanion = managementCompanion.getId();
}
}
public String getManagementCompanionId() {
return managementCompanion;
}
public void setManagementCompanionId(String managementCompanion) {
this.managementCompanion = managementCompanion;
}
// Reindeer event:
public SlaveJob getSlaveryManagerJobSelected() {
return slaveryManagerJobSelected;
}
public void setSlaveryManagerJobSelected(SlaveJob slaveryManagerJobSelected) {
this.slaveryManagerJobSelected = slaveryManagerJobSelected;
}
public void addHelenaConversationTopic(HelenaConversationTopic topic) {
helenaConversationTopics.add(topic.toString());
}
public boolean hasHelenaConversationTopic(HelenaConversationTopic topic) {
return helenaConversationTopics.contains(topic.toString());
}
public void addReindeerEncountered(String reindeerID) {
reindeerEncounteredIDs.add(reindeerID);
}
public boolean hasEncounteredReindeer(String reindeerID) {
return reindeerEncounteredIDs.contains(reindeerID);
}
public boolean hasEncounteredAnyReindeers() {
return !reindeerEncounteredIDs.isEmpty();
}
public void addReindeerDailyWorkedFor(String reindeerID) {
reindeerWorkedForIDs.add(reindeerID);
}
public boolean hasWorkedForReindeer(String reindeerID) {
return reindeerWorkedForIDs.contains(reindeerID);
}
public void addReindeerDailyFucked(String reindeerID) {
reindeerFuckedIDs.add(reindeerID);
}
public boolean hasFuckedReindeer(String reindeerID) {
return reindeerFuckedIDs.contains(reindeerID);
}
public void dailyReindeerReset(String reindeerID) {
reindeerWorkedForIDs.remove(reindeerID);
}
public int getMurkTfStage(GameCharacter target) {
if(target.isPlayer()) {
return murkPlayerTfStage;
}
return murkCompanionTfStage;
}
public void setMurkTfStage(GameCharacter target, int stage) {
if(target.isPlayer()) {
this.murkPlayerTfStage = stage;
} else {
this.murkCompanionTfStage = stage;
}
}
public Colour getNatalyaCollarColour() {
return natalyaCollarColour;
}
public void setNatalyaCollarColour(Colour natalyaCollarColour) {
this.natalyaCollarColour = natalyaCollarColour;
}
public int getNatalyaPoints() {
return natalyaPoints;
}
public void setNatalyaPoints(int natalyaPoints) {
this.natalyaPoints = natalyaPoints;
if(this.natalyaPoints<0) {
this.natalyaPoints = 0;
}
}
public String incrementNatalyaPoints(int increment) {
setNatalyaPoints(getNatalyaPoints()+increment);
boolean plural = increment!=1;
StringBuilder sb = new StringBuilder();
sb.append("<p style='text-align:center;'>");
if(increment>0) {
sb.append("You [style.colourGood(gained)] [style.boldPink("+increment+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!");
} else {
sb.append("You [style.colourBad(lost)] [style.boldPink("+(-increment)+")] [style.colourPinkLight(filly point"+(plural?"s":"")+")]!");
}
sb.append("<br/>You now have [style.boldPink("+getNatalyaPoints()+")] [style.colourPinkLight(filly points)]!");
sb.append("</p>");
return sb.toString();
}
public String getSadistNatalyaSlave() {
return sadistNatalyaSlave;
}
public void setSadistNatalyaSlave(String sadistNatalyaSlave) {
this.sadistNatalyaSlave = sadistNatalyaSlave;
}
}
|
55100_3 | package com.example.blogit.blog;
import com.example.blogit.user.Users;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.Collections;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class BlogControllerTest {
@Autowired
private MockMvc mockMvc;
//Ik ben hier niet geintereseerd in de werking van de blogService.
//Normaal gesproken hoeven service lagen niet gemocked te worden (mits ze extern requests uitvoeren)
//Mock zo weinig mogelijk, maar krijg vooral vertrouwen in je code.
// (e.g. als je ook maar iets kleins veranderd moet dan zichtbaar zijn in falende tests)
@MockBean
private BlogService blogService;
//Dit is de standaard serialization engine van Spring, ik zag je eerder gson gebruiken.
//Jackson is meer de standaard, ik autowire hem hier omdat spring deze voor ons regelt.
@Autowired
ObjectMapper om;
//Elke test moet de @Test hebben
@Test
public void shouldGetABlog() throws Exception {
//given
var author = new Users("[email protected]", "mitchelwijt", "test123", "profilePic");
var blog = new Blog(author,1L, "Drunk", "Drunk on a Journey", "someBannerImg", 1L, LocalDateTime.now());
var blogListDTO = new BlogListDto(Collections.singletonList(blog), false, 1, 0);
when(blogService.getBlogs(1)).thenReturn(blogListDTO);
//when
var result = this.mockMvc
.perform(get("/api/blog/get-blogs").param("page", "1"))
.andDo(print());
//then
var expectedBlog = om.writeValueAsString(blogListDTO);
result
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json(expectedBlog))
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
} | MitchWijt/blogIt | src/test/java/com/example/blogit/blog/BlogControllerTest.java | 791 | // (e.g. als je ook maar iets kleins veranderd moet dan zichtbaar zijn in falende tests) | line_comment | nl | package com.example.blogit.blog;
import com.example.blogit.user.Users;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.Collections;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class BlogControllerTest {
@Autowired
private MockMvc mockMvc;
//Ik ben hier niet geintereseerd in de werking van de blogService.
//Normaal gesproken hoeven service lagen niet gemocked te worden (mits ze extern requests uitvoeren)
//Mock zo weinig mogelijk, maar krijg vooral vertrouwen in je code.
// (e.g. als<SUF>
@MockBean
private BlogService blogService;
//Dit is de standaard serialization engine van Spring, ik zag je eerder gson gebruiken.
//Jackson is meer de standaard, ik autowire hem hier omdat spring deze voor ons regelt.
@Autowired
ObjectMapper om;
//Elke test moet de @Test hebben
@Test
public void shouldGetABlog() throws Exception {
//given
var author = new Users("[email protected]", "mitchelwijt", "test123", "profilePic");
var blog = new Blog(author,1L, "Drunk", "Drunk on a Journey", "someBannerImg", 1L, LocalDateTime.now());
var blogListDTO = new BlogListDto(Collections.singletonList(blog), false, 1, 0);
when(blogService.getBlogs(1)).thenReturn(blogListDTO);
//when
var result = this.mockMvc
.perform(get("/api/blog/get-blogs").param("page", "1"))
.andDo(print());
//then
var expectedBlog = om.writeValueAsString(blogListDTO);
result
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json(expectedBlog))
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
} |
60692_0 | package nl.allergieradar;
/**
* Meer informatie over views:
* http://www.baeldung.com/jackson-json-view-annotation
*
* @author Peter van Vliet <[email protected]>
* @since 1.0
*/
public class View
{
public static class Internal extends Private {}
public static class Private extends Protected {}
public static class Protected extends Public {}
public static class Public {}
}
| MitchvanWijngaarden/Allergieradarserver | src/main/java/nl/allergieradar/View.java | 128 | /**
* Meer informatie over views:
* http://www.baeldung.com/jackson-json-view-annotation
*
* @author Peter van Vliet <[email protected]>
* @since 1.0
*/ | block_comment | nl | package nl.allergieradar;
/**
* Meer informatie over<SUF>*/
public class View
{
public static class Internal extends Private {}
public static class Private extends Protected {}
public static class Protected extends Public {}
public static class Public {}
}
|
40857_0 | import java.util.ArrayList;
import java.util.Random;
public class Ball {
//states
IState positive;
IState negative;
IState neutral;
IState currentState;
int timesRolled;
ArrayList<Integer> currentFortunes; //lijst van aantal gerolde fortunes
private static Ball instance = new Ball(); //instance
private Ball() {}
public static Ball getInstance() { //singleton
return instance;
}
public void init() { //init omdat we met een constructor werken
positive = new PositiveState(instance);
negative = new NegativeState(instance);
neutral = new NeutralState(instance);
setCurrentState(neutral);
timesRolled = 0;
currentFortunes = new ArrayList<Integer>();
}
public String makeFortune() {
Random r = new Random();
boolean duplicateFound;
int choice;
String result = "";
do {
duplicateFound = false; //we beginnen met false
choice = 1 + r.nextInt(20); //genereer
for(int value : currentFortunes) {
if (value == choice) { //hebben we de waarde al?
duplicateFound = true; //duplicate found dus repeat het generen
}
}
} while(duplicateFound);
if (choice >= 1 && choice <= 10) {
currentState = positive;
result = currentState.roll(choice);
} else if (choice > 10 && choice <= 15) {
currentState = neutral;
result = currentState.roll(choice);
} else {
currentState = negative;
result = currentState.roll(choice);
}
if (timesRolled % 10 == 0) {
currentFortunes.clear();
} else {
timesRolled++;
currentFortunes.add(choice);
}
return result + "\t --> [" + currentState.getClass().getName() + "]";
}
public IState getCurrentState() {
return currentState;
}
public void setCurrentState(IState currentState) {
this.currentState = currentState;
}
}
| Mocrosoft/ExamenArchitectuur | MagicBallExamen/src/Ball.java | 574 | //lijst van aantal gerolde fortunes | line_comment | nl | import java.util.ArrayList;
import java.util.Random;
public class Ball {
//states
IState positive;
IState negative;
IState neutral;
IState currentState;
int timesRolled;
ArrayList<Integer> currentFortunes; //lijst van<SUF>
private static Ball instance = new Ball(); //instance
private Ball() {}
public static Ball getInstance() { //singleton
return instance;
}
public void init() { //init omdat we met een constructor werken
positive = new PositiveState(instance);
negative = new NegativeState(instance);
neutral = new NeutralState(instance);
setCurrentState(neutral);
timesRolled = 0;
currentFortunes = new ArrayList<Integer>();
}
public String makeFortune() {
Random r = new Random();
boolean duplicateFound;
int choice;
String result = "";
do {
duplicateFound = false; //we beginnen met false
choice = 1 + r.nextInt(20); //genereer
for(int value : currentFortunes) {
if (value == choice) { //hebben we de waarde al?
duplicateFound = true; //duplicate found dus repeat het generen
}
}
} while(duplicateFound);
if (choice >= 1 && choice <= 10) {
currentState = positive;
result = currentState.roll(choice);
} else if (choice > 10 && choice <= 15) {
currentState = neutral;
result = currentState.roll(choice);
} else {
currentState = negative;
result = currentState.roll(choice);
}
if (timesRolled % 10 == 0) {
currentFortunes.clear();
} else {
timesRolled++;
currentFortunes.add(choice);
}
return result + "\t --> [" + currentState.getClass().getName() + "]";
}
public IState getCurrentState() {
return currentState;
}
public void setCurrentState(IState currentState) {
this.currentState = currentState;
}
}
|
202329_0 | package nl.Groep13.OrderHandler.model.v2;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Entity
@Getter
@Setter
@ToString
@Table(name = "article_order")
public class ArticleOrder {
//Eigenaar van het materiaal, oftewel de klant
//Ordernummer
//Aantal meter restant
//Stofnaam, -kleur en -samenstelling
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "articleID", referencedColumnName = "id")
private ArticleV2 articleID;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "customerID", referencedColumnName = "id")
private CustomerV2 customerID;
private boolean finished;
public ArticleOrder(Long id, ArticleV2 articleID, CustomerV2 customerID, boolean finished) {
this.id = id;
this.articleID = articleID;
this.customerID = customerID;
this.finished = finished;
}
public ArticleOrder() {
}
}
| Moemen02/IPSEN2-BE | src/main/java/nl/Groep13/OrderHandler/model/v2/ArticleOrder.java | 332 | //Eigenaar van het materiaal, oftewel de klant | line_comment | nl | package nl.Groep13.OrderHandler.model.v2;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Entity
@Getter
@Setter
@ToString
@Table(name = "article_order")
public class ArticleOrder {
//Eigenaar van<SUF>
//Ordernummer
//Aantal meter restant
//Stofnaam, -kleur en -samenstelling
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "articleID", referencedColumnName = "id")
private ArticleV2 articleID;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "customerID", referencedColumnName = "id")
private CustomerV2 customerID;
private boolean finished;
public ArticleOrder(Long id, ArticleV2 articleID, CustomerV2 customerID, boolean finished) {
this.id = id;
this.articleID = articleID;
this.customerID = customerID;
this.finished = finished;
}
public ArticleOrder() {
}
}
|
9622_3 |
public class Polynom{
public double[] koeffizienten;
public Polynom(double[] koeffizienten) {
this.koeffizienten = koeffizienten;
}
public double getKoeffizient(int stelle) {
return koeffizienten[stelle];
}
public int getDegree() {
return koeffizienten.length - 1;
}
public Complex getValue(Complex x){
Complex funktionsWert = Complex.zero();
for (int i = getDegree(); i >= 0; i--) {
funktionsWert = Complex.mult(funktionsWert, x);
funktionsWert = Complex.sum(funktionsWert, Complex.fromReal(getKoeffizient(i)));
}
return funktionsWert;
}
// @Override
// public String toString() {
// String result = "0";
// for (int i = 0; i < getDegree() + 1; i++) {
// result += " + " + koeffizienten[i] + " * x ^ " + (getDegree() - i);
// }
// return result;
// }
@Override
public String toString() {
System.out.print("f(x)=");
if (getDegree() < 0)
System.out.println("ERROR: Grad negativ!");
if (getDegree() == 0)
System.out.println(koeffizienten[0]);
if (getDegree() > 0) {
System.out.print(koeffizienten[getDegree()]);
if (getDegree() > 1) {
System.out.print("*x^");
System.out.print(getDegree());
} else
System.out.print("x");
for (int i = getDegree() - 1; i >= 0; i--) {
if (koeffizienten[i] > 0)
System.out.print(" +");
if (koeffizienten[i] < 0)
System.out.print(" ");
if (koeffizienten[i] != 0) {
System.out.print(koeffizienten[i]);
if (i > 1) {
System.out.print("*x^");
System.out.print(i);
} else if (i == 1)
System.out.print("x");
}
}
}
return "";
}
} | Mofty/Nummerik_Kripfganz_2015 | Polynom.java | 691 | // result += " + " + koeffizienten[i] + " * x ^ " + (getDegree() - i); | line_comment | nl |
public class Polynom{
public double[] koeffizienten;
public Polynom(double[] koeffizienten) {
this.koeffizienten = koeffizienten;
}
public double getKoeffizient(int stelle) {
return koeffizienten[stelle];
}
public int getDegree() {
return koeffizienten.length - 1;
}
public Complex getValue(Complex x){
Complex funktionsWert = Complex.zero();
for (int i = getDegree(); i >= 0; i--) {
funktionsWert = Complex.mult(funktionsWert, x);
funktionsWert = Complex.sum(funktionsWert, Complex.fromReal(getKoeffizient(i)));
}
return funktionsWert;
}
// @Override
// public String toString() {
// String result = "0";
// for (int i = 0; i < getDegree() + 1; i++) {
// result +=<SUF>
// }
// return result;
// }
@Override
public String toString() {
System.out.print("f(x)=");
if (getDegree() < 0)
System.out.println("ERROR: Grad negativ!");
if (getDegree() == 0)
System.out.println(koeffizienten[0]);
if (getDegree() > 0) {
System.out.print(koeffizienten[getDegree()]);
if (getDegree() > 1) {
System.out.print("*x^");
System.out.print(getDegree());
} else
System.out.print("x");
for (int i = getDegree() - 1; i >= 0; i--) {
if (koeffizienten[i] > 0)
System.out.print(" +");
if (koeffizienten[i] < 0)
System.out.print(" ");
if (koeffizienten[i] != 0) {
System.out.print(koeffizienten[i]);
if (i > 1) {
System.out.print("*x^");
System.out.print(i);
} else if (i == 1)
System.out.print("x");
}
}
}
return "";
}
} |
53620_43 | package com.mohistmc.paper.util;
public final class IntegerUtil {
public static final int HIGH_BIT_U32 = Integer.MIN_VALUE;
public static final long HIGH_BIT_U64 = Long.MIN_VALUE;
public static int ceilLog2(final int value) {
return Integer.SIZE - Integer.numberOfLeadingZeros(value - 1); // see doc of numberOfLeadingZeros
}
public static long ceilLog2(final long value) {
return Long.SIZE - Long.numberOfLeadingZeros(value - 1); // see doc of numberOfLeadingZeros
}
public static int floorLog2(final int value) {
// xor is optimized subtract for 2^n -1
// note that (2^n -1) - k = (2^n -1) ^ k for k <= (2^n - 1)
return (Integer.SIZE - 1) ^ Integer.numberOfLeadingZeros(value); // see doc of numberOfLeadingZeros
}
public static int floorLog2(final long value) {
// xor is optimized subtract for 2^n -1
// note that (2^n -1) - k = (2^n -1) ^ k for k <= (2^n - 1)
return (Long.SIZE - 1) ^ Long.numberOfLeadingZeros(value); // see doc of numberOfLeadingZeros
}
public static int roundCeilLog2(final int value) {
// optimized variant of 1 << (32 - leading(val - 1))
// given
// 1 << n = HIGH_BIT_32 >>> (31 - n) for n [0, 32)
// 1 << (32 - leading(val - 1)) = HIGH_BIT_32 >>> (31 - (32 - leading(val - 1)))
// HIGH_BIT_32 >>> (31 - (32 - leading(val - 1)))
// HIGH_BIT_32 >>> (31 - 32 + leading(val - 1))
// HIGH_BIT_32 >>> (-1 + leading(val - 1))
return HIGH_BIT_U32 >>> (Integer.numberOfLeadingZeros(value - 1) - 1);
}
public static long roundCeilLog2(final long value) {
// see logic documented above
return HIGH_BIT_U64 >>> (Long.numberOfLeadingZeros(value - 1) - 1);
}
public static int roundFloorLog2(final int value) {
// optimized variant of 1 << (31 - leading(val))
// given
// 1 << n = HIGH_BIT_32 >>> (31 - n) for n [0, 32)
// 1 << (31 - leading(val)) = HIGH_BIT_32 >> (31 - (31 - leading(val)))
// HIGH_BIT_32 >> (31 - (31 - leading(val)))
// HIGH_BIT_32 >> (31 - 31 + leading(val))
return HIGH_BIT_U32 >>> Integer.numberOfLeadingZeros(value);
}
public static long roundFloorLog2(final long value) {
// see logic documented above
return HIGH_BIT_U64 >>> Long.numberOfLeadingZeros(value);
}
public static boolean isPowerOfTwo(final int n) {
// 2^n has one bit
// note: this rets true for 0 still
return IntegerUtil.getTrailingBit(n) == n;
}
public static boolean isPowerOfTwo(final long n) {
// 2^n has one bit
// note: this rets true for 0 still
return IntegerUtil.getTrailingBit(n) == n;
}
public static int getTrailingBit(final int n) {
return -n & n;
}
public static long getTrailingBit(final long n) {
return -n & n;
}
public static int trailingZeros(final int n) {
return Integer.numberOfTrailingZeros(n);
}
public static int trailingZeros(final long n) {
return Long.numberOfTrailingZeros(n);
}
// from hacker's delight (signed division magic value)
public static int getDivisorMultiple(final long numbers) {
return (int)(numbers >>> 32);
}
// from hacker's delight (signed division magic value)
public static int getDivisorShift(final long numbers) {
return (int)numbers;
}
// copied from hacker's delight (signed division magic value)
// http://www.hackersdelight.org/hdcodetxt/magic.c.txt
public static long getDivisorNumbers(final int d) {
final int ad = branchlessAbs(d);
if (ad < 2) {
throw new IllegalArgumentException("|number| must be in [2, 2^31 -1], not: " + d);
}
final int two31 = 0x80000000;
final long mask = 0xFFFFFFFFL; // mask for enforcing unsigned behaviour
/*
Signed usage:
int number;
long magic = getDivisorNumbers(div);
long mul = magic >>> 32;
int sign = number >> 31;
int result = (int)(((long)number * mul) >>> magic) - sign;
*/
/*
Unsigned usage:
int number;
long magic = getDivisorNumbers(div);
long mul = magic >>> 32;
int result = (int)(((long)number * mul) >>> magic);
*/
int p = 31;
// all these variables are UNSIGNED!
int t = two31 + (d >>> 31);
int anc = t - 1 - (int)((t & mask)%ad);
int q1 = (int)((two31 & mask)/(anc & mask));
int r1 = two31 - q1*anc;
int q2 = (int)((two31 & mask)/(ad & mask));
int r2 = two31 - q2*ad;
int delta;
do {
p = p + 1;
q1 = 2*q1; // Update q1 = 2**p/|nc|.
r1 = 2*r1; // Update r1 = rem(2**p, |nc|).
if ((r1 & mask) >= (anc & mask)) {// (Must be an unsigned comparison here)
q1 = q1 + 1;
r1 = r1 - anc;
}
q2 = 2*q2; // Update q2 = 2**p/|d|.
r2 = 2*r2; // Update r2 = rem(2**p, |d|).
if ((r2 & mask) >= (ad & mask)) {// (Must be an unsigned comparison here)
q2 = q2 + 1;
r2 = r2 - ad;
}
delta = ad - r2;
} while ((q1 & mask) < (delta & mask) || (q1 == delta && r1 == 0));
int magicNum = q2 + 1;
if (d < 0) {
magicNum = -magicNum;
}
int shift = p;
return ((long)magicNum << 32) | shift;
}
public static int branchlessAbs(final int val) {
// -n = -1 ^ n + 1
final int mask = val >> (Integer.SIZE - 1); // -1 if < 0, 0 if >= 0
return (mask ^ val) - mask; // if val < 0, then (0 ^ val) - 0 else (-1 ^ val) + 1
}
public static long branchlessAbs(final long val) {
// -n = -1 ^ n + 1
final long mask = val >> (Long.SIZE - 1); // -1 if < 0, 0 if >= 0
return (mask ^ val) - mask; // if val < 0, then (0 ^ val) - 0 else (-1 ^ val) + 1
}
//https://github.com/skeeto/hash-prospector for hash functions
//score = ~590.47984224483832
public static int hash0(int x) {
x *= 0x36935555;
x ^= x >>> 16;
return x;
}
//score = ~310.01596637036749
public static int hash1(int x) {
x ^= x >>> 15;
x *= 0x356aaaad;
x ^= x >>> 17;
return x;
}
public static int hash2(int x) {
x ^= x >>> 16;
x *= 0x7feb352d;
x ^= x >>> 15;
x *= 0x846ca68b;
x ^= x >>> 16;
return x;
}
public static int hash3(int x) {
x ^= x >>> 17;
x *= 0xed5ad4bb;
x ^= x >>> 11;
x *= 0xac4c1b51;
x ^= x >>> 15;
x *= 0x31848bab;
x ^= x >>> 14;
return x;
}
//score = ~365.79959673201887
public static long hash1(long x) {
x ^= x >>> 27;
x *= 0xb24924b71d2d354bL;
x ^= x >>> 28;
return x;
}
//h2 hash
public static long hash2(long x) {
x ^= x >>> 32;
x *= 0xd6e8feb86659fd93L;
x ^= x >>> 32;
x *= 0xd6e8feb86659fd93L;
x ^= x >>> 32;
return x;
}
public static long hash3(long x) {
x ^= x >>> 45;
x *= 0xc161abe5704b6c79L;
x ^= x >>> 41;
x *= 0xe3e5389aedbc90f7L;
x ^= x >>> 56;
x *= 0x1f9aba75a52db073L;
x ^= x >>> 53;
return x;
}
private IntegerUtil() {
throw new RuntimeException();
}
}
| MohistMC/Mohist | src/main/java/com/mohistmc/paper/util/IntegerUtil.java | 2,729 | // if val < 0, then (0 ^ val) - 0 else (-1 ^ val) + 1 | line_comment | nl | package com.mohistmc.paper.util;
public final class IntegerUtil {
public static final int HIGH_BIT_U32 = Integer.MIN_VALUE;
public static final long HIGH_BIT_U64 = Long.MIN_VALUE;
public static int ceilLog2(final int value) {
return Integer.SIZE - Integer.numberOfLeadingZeros(value - 1); // see doc of numberOfLeadingZeros
}
public static long ceilLog2(final long value) {
return Long.SIZE - Long.numberOfLeadingZeros(value - 1); // see doc of numberOfLeadingZeros
}
public static int floorLog2(final int value) {
// xor is optimized subtract for 2^n -1
// note that (2^n -1) - k = (2^n -1) ^ k for k <= (2^n - 1)
return (Integer.SIZE - 1) ^ Integer.numberOfLeadingZeros(value); // see doc of numberOfLeadingZeros
}
public static int floorLog2(final long value) {
// xor is optimized subtract for 2^n -1
// note that (2^n -1) - k = (2^n -1) ^ k for k <= (2^n - 1)
return (Long.SIZE - 1) ^ Long.numberOfLeadingZeros(value); // see doc of numberOfLeadingZeros
}
public static int roundCeilLog2(final int value) {
// optimized variant of 1 << (32 - leading(val - 1))
// given
// 1 << n = HIGH_BIT_32 >>> (31 - n) for n [0, 32)
// 1 << (32 - leading(val - 1)) = HIGH_BIT_32 >>> (31 - (32 - leading(val - 1)))
// HIGH_BIT_32 >>> (31 - (32 - leading(val - 1)))
// HIGH_BIT_32 >>> (31 - 32 + leading(val - 1))
// HIGH_BIT_32 >>> (-1 + leading(val - 1))
return HIGH_BIT_U32 >>> (Integer.numberOfLeadingZeros(value - 1) - 1);
}
public static long roundCeilLog2(final long value) {
// see logic documented above
return HIGH_BIT_U64 >>> (Long.numberOfLeadingZeros(value - 1) - 1);
}
public static int roundFloorLog2(final int value) {
// optimized variant of 1 << (31 - leading(val))
// given
// 1 << n = HIGH_BIT_32 >>> (31 - n) for n [0, 32)
// 1 << (31 - leading(val)) = HIGH_BIT_32 >> (31 - (31 - leading(val)))
// HIGH_BIT_32 >> (31 - (31 - leading(val)))
// HIGH_BIT_32 >> (31 - 31 + leading(val))
return HIGH_BIT_U32 >>> Integer.numberOfLeadingZeros(value);
}
public static long roundFloorLog2(final long value) {
// see logic documented above
return HIGH_BIT_U64 >>> Long.numberOfLeadingZeros(value);
}
public static boolean isPowerOfTwo(final int n) {
// 2^n has one bit
// note: this rets true for 0 still
return IntegerUtil.getTrailingBit(n) == n;
}
public static boolean isPowerOfTwo(final long n) {
// 2^n has one bit
// note: this rets true for 0 still
return IntegerUtil.getTrailingBit(n) == n;
}
public static int getTrailingBit(final int n) {
return -n & n;
}
public static long getTrailingBit(final long n) {
return -n & n;
}
public static int trailingZeros(final int n) {
return Integer.numberOfTrailingZeros(n);
}
public static int trailingZeros(final long n) {
return Long.numberOfTrailingZeros(n);
}
// from hacker's delight (signed division magic value)
public static int getDivisorMultiple(final long numbers) {
return (int)(numbers >>> 32);
}
// from hacker's delight (signed division magic value)
public static int getDivisorShift(final long numbers) {
return (int)numbers;
}
// copied from hacker's delight (signed division magic value)
// http://www.hackersdelight.org/hdcodetxt/magic.c.txt
public static long getDivisorNumbers(final int d) {
final int ad = branchlessAbs(d);
if (ad < 2) {
throw new IllegalArgumentException("|number| must be in [2, 2^31 -1], not: " + d);
}
final int two31 = 0x80000000;
final long mask = 0xFFFFFFFFL; // mask for enforcing unsigned behaviour
/*
Signed usage:
int number;
long magic = getDivisorNumbers(div);
long mul = magic >>> 32;
int sign = number >> 31;
int result = (int)(((long)number * mul) >>> magic) - sign;
*/
/*
Unsigned usage:
int number;
long magic = getDivisorNumbers(div);
long mul = magic >>> 32;
int result = (int)(((long)number * mul) >>> magic);
*/
int p = 31;
// all these variables are UNSIGNED!
int t = two31 + (d >>> 31);
int anc = t - 1 - (int)((t & mask)%ad);
int q1 = (int)((two31 & mask)/(anc & mask));
int r1 = two31 - q1*anc;
int q2 = (int)((two31 & mask)/(ad & mask));
int r2 = two31 - q2*ad;
int delta;
do {
p = p + 1;
q1 = 2*q1; // Update q1 = 2**p/|nc|.
r1 = 2*r1; // Update r1 = rem(2**p, |nc|).
if ((r1 & mask) >= (anc & mask)) {// (Must be an unsigned comparison here)
q1 = q1 + 1;
r1 = r1 - anc;
}
q2 = 2*q2; // Update q2 = 2**p/|d|.
r2 = 2*r2; // Update r2 = rem(2**p, |d|).
if ((r2 & mask) >= (ad & mask)) {// (Must be an unsigned comparison here)
q2 = q2 + 1;
r2 = r2 - ad;
}
delta = ad - r2;
} while ((q1 & mask) < (delta & mask) || (q1 == delta && r1 == 0));
int magicNum = q2 + 1;
if (d < 0) {
magicNum = -magicNum;
}
int shift = p;
return ((long)magicNum << 32) | shift;
}
public static int branchlessAbs(final int val) {
// -n = -1 ^ n + 1
final int mask = val >> (Integer.SIZE - 1); // -1 if < 0, 0 if >= 0
return (mask ^ val) - mask; // if val < 0, then (0 ^ val) - 0 else (-1 ^ val) + 1
}
public static long branchlessAbs(final long val) {
// -n = -1 ^ n + 1
final long mask = val >> (Long.SIZE - 1); // -1 if < 0, 0 if >= 0
return (mask ^ val) - mask; // if val<SUF>
}
//https://github.com/skeeto/hash-prospector for hash functions
//score = ~590.47984224483832
public static int hash0(int x) {
x *= 0x36935555;
x ^= x >>> 16;
return x;
}
//score = ~310.01596637036749
public static int hash1(int x) {
x ^= x >>> 15;
x *= 0x356aaaad;
x ^= x >>> 17;
return x;
}
public static int hash2(int x) {
x ^= x >>> 16;
x *= 0x7feb352d;
x ^= x >>> 15;
x *= 0x846ca68b;
x ^= x >>> 16;
return x;
}
public static int hash3(int x) {
x ^= x >>> 17;
x *= 0xed5ad4bb;
x ^= x >>> 11;
x *= 0xac4c1b51;
x ^= x >>> 15;
x *= 0x31848bab;
x ^= x >>> 14;
return x;
}
//score = ~365.79959673201887
public static long hash1(long x) {
x ^= x >>> 27;
x *= 0xb24924b71d2d354bL;
x ^= x >>> 28;
return x;
}
//h2 hash
public static long hash2(long x) {
x ^= x >>> 32;
x *= 0xd6e8feb86659fd93L;
x ^= x >>> 32;
x *= 0xd6e8feb86659fd93L;
x ^= x >>> 32;
return x;
}
public static long hash3(long x) {
x ^= x >>> 45;
x *= 0xc161abe5704b6c79L;
x ^= x >>> 41;
x *= 0xe3e5389aedbc90f7L;
x ^= x >>> 56;
x *= 0x1f9aba75a52db073L;
x ^= x >>> 53;
return x;
}
private IntegerUtil() {
throw new RuntimeException();
}
}
|
32082_11 | /*
* Portions Copyright (C) 2003 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package com.sun.opengl.impl.tessellator;
class Geom {
private Geom() {
}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->t = 0 and
* let r be the negated result (this evaluates (uw)(v->s)), then
* r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->s = 0 and
* let r be the negated result (this evaluates (uw)(v->t)), then
* r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Returns a number whose sign matches TransEval(u,v,w) but which
* is cheaper to evaluate. Returns > 0, == 0 , or < 0
* as v is above, on, or below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results
* on some degenerate inputs, so the client must have some way to
* handle this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering,
* and interpolate the intersection s-value from these. Then repeat
* using the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
}
| MonALISA-CIT/Monalisa | doc/jsr-231/beta04/jogl-src/jogl/src/classes/com/sun/opengl/impl/tessellator/Geom.java | 3,641 | /* Interpolate between o2 and d1 */ | block_comment | nl | /*
* Portions Copyright (C) 2003 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package com.sun.opengl.impl.tessellator;
class Geom {
private Geom() {
}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->t = 0 and
* let r be the negated result (this evaluates (uw)(v->s)), then
* r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->s = 0 and
* let r be the negated result (this evaluates (uw)(v->t)), then
* r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Returns a number whose sign matches TransEval(u,v,w) but which
* is cheaper to evaluate. Returns > 0, == 0 , or < 0
* as v is above, on, or below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results
* on some degenerate inputs, so the client must have some way to
* handle this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering,
* and interpolate the intersection s-value from these. Then repeat
* using the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2<SUF>*/
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
}
|
30920_1 | package se.monstermannen.discordmonsterbot;
import com.arsenarsen.lavaplayerbridge.PlayerManager;
import com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory;
import com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException;
import com.arsenarsen.lavaplayerbridge.player.Player;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import se.monstermannen.discordmonsterbot.commands.Command;
import se.monstermannen.discordmonsterbot.commands.CommandType;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotAvatarCommand;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotGameCommand;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotNameCommand;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotPrefixCommand;
import se.monstermannen.discordmonsterbot.commands.general.*;
import se.monstermannen.discordmonsterbot.commands.music.*;
import se.monstermannen.discordmonsterbot.util.MonsterTimer;
import se.monstermannen.discordmonsterbot.util.PropertyHandler;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.RateLimitException;
import java.util.ArrayList;
/**
* Created by Viktor on 2017-01-12.
*
* main class
*/
public class DiscordMonsterBot {
// default values
public static String TOKEN = ""; // discord bot token
public static String YT_APIKEY = ""; // youtube api key
public static String PREFIX = "!"; // prefix for commands
public static boolean LOOPPLAYLIST = false; // loop music players playlist
// discord
private static IDiscordClient client;
private static MonsterTimer timer;
private static PlayerManager manager;
public static AddSongCommand addSong;
// variables
//public static Logger logger = LoggerFactory.getLogger(DiscordMonsterBot.class);
private static ArrayList<Command> commands = new ArrayList<>();
public static int readMessages;
public static int readCommands;
private static long startTime;
public static void main(String[] args){
try {
DiscordMonsterBot bot = new DiscordMonsterBot();
DiscordMonsterBot.startTime = System.currentTimeMillis();
PropertyHandler.readProperties();
timer = new MonsterTimer();
client = new ClientBuilder().withToken(TOKEN).build(); // builds client
manager = PlayerManager.getPlayerManager(LibraryFactory.getLibrary(client));
manager.getManager().registerSourceManager(new YoutubeAudioSourceManager()); // youtube
client.getDispatcher().registerListener(new Events()); // add listener
client.login(); // login :^)
// logger test
//BasicConfigurator.configure();
//logger.info("test log :D");
// general commands
commands.add(new HelpCommand());
commands.add(new StatsCommand());
commands.add(new SayCommand());
commands.add(new VirusCommand());
commands.add(new FlipCommand());
commands.add(new UserInfoCommand());
commands.add(new WhoSpamsCommand());
commands.add(new ImdbCommand());
commands.add(new SwagCommand());
commands.add(new WarningCommand());
// music commands
commands.add(new JoinCommand());
commands.add(new LeaveCommand());
commands.add(new AddSongCommand());
commands.add(new PlayCommand());
commands.add(new PauseCommand());
commands.add(new SkipCommand());
commands.add(new ClearCommand());
commands.add(new VolumeCommand());
commands.add(new SongCommand());
commands.add(new PlaylistCommand());
commands.add(new ShuffleCommand());
commands.add(new LoopCommand());
commands.add(new FwdCommand());
commands.add(new SavePlaylistCommand());
commands.add(new LoadPlaylistCommand());
// admin only commands (not listed when using help)
commands.add(new SetBotGameCommand());
commands.add(new SetBotNameCommand());
commands.add(new SetBotAvatarCommand());
commands.add(new SetBotPrefixCommand());
addSong = new AddSongCommand(); // used by !play command
} catch (DiscordException | RateLimitException | UnknownBindingException e) {
e.printStackTrace();
}
}
// todo logger
// todo fwd song
// todo random song list? + random song add
// todo rip (text on img)
// todo warn user
// todo aws amazon host? heroku?
// help -admin commands +music guide
// return time in seconds since program start
public static long getUptime(){
return (System.currentTimeMillis() - startTime) / 1000;
}
public static int getReadmessages(){
return readMessages;
}
public static int getReadCommands(){
return readCommands;
}
public static void increaseReadMessages(){
readMessages++;
}
public static void increaseReadCommands(){
readCommands++;
}
// return commandlist
public static ArrayList<Command> getCommands(){
return commands;
}
// return only commands of commandtype type
public static ArrayList<Command> getCommandsByType(CommandType type){
ArrayList<Command> ret = new ArrayList<>();
for(Command cmd : commands){
if(cmd.getCommandType() == type){
ret.add(cmd);
}
}
return ret;
}
// return lavaplayer
public static Player getPlayer(IGuild guild){
return manager.getPlayer(guild.getID());
}
}
| MonsterMannen/DiscordMonsterBot | src/main/java/se/monstermannen/discordmonsterbot/DiscordMonsterBot.java | 1,626 | // discord bot token | line_comment | nl | package se.monstermannen.discordmonsterbot;
import com.arsenarsen.lavaplayerbridge.PlayerManager;
import com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory;
import com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException;
import com.arsenarsen.lavaplayerbridge.player.Player;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import se.monstermannen.discordmonsterbot.commands.Command;
import se.monstermannen.discordmonsterbot.commands.CommandType;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotAvatarCommand;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotGameCommand;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotNameCommand;
import se.monstermannen.discordmonsterbot.commands.admin.SetBotPrefixCommand;
import se.monstermannen.discordmonsterbot.commands.general.*;
import se.monstermannen.discordmonsterbot.commands.music.*;
import se.monstermannen.discordmonsterbot.util.MonsterTimer;
import se.monstermannen.discordmonsterbot.util.PropertyHandler;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.RateLimitException;
import java.util.ArrayList;
/**
* Created by Viktor on 2017-01-12.
*
* main class
*/
public class DiscordMonsterBot {
// default values
public static String TOKEN = ""; // discord bot<SUF>
public static String YT_APIKEY = ""; // youtube api key
public static String PREFIX = "!"; // prefix for commands
public static boolean LOOPPLAYLIST = false; // loop music players playlist
// discord
private static IDiscordClient client;
private static MonsterTimer timer;
private static PlayerManager manager;
public static AddSongCommand addSong;
// variables
//public static Logger logger = LoggerFactory.getLogger(DiscordMonsterBot.class);
private static ArrayList<Command> commands = new ArrayList<>();
public static int readMessages;
public static int readCommands;
private static long startTime;
public static void main(String[] args){
try {
DiscordMonsterBot bot = new DiscordMonsterBot();
DiscordMonsterBot.startTime = System.currentTimeMillis();
PropertyHandler.readProperties();
timer = new MonsterTimer();
client = new ClientBuilder().withToken(TOKEN).build(); // builds client
manager = PlayerManager.getPlayerManager(LibraryFactory.getLibrary(client));
manager.getManager().registerSourceManager(new YoutubeAudioSourceManager()); // youtube
client.getDispatcher().registerListener(new Events()); // add listener
client.login(); // login :^)
// logger test
//BasicConfigurator.configure();
//logger.info("test log :D");
// general commands
commands.add(new HelpCommand());
commands.add(new StatsCommand());
commands.add(new SayCommand());
commands.add(new VirusCommand());
commands.add(new FlipCommand());
commands.add(new UserInfoCommand());
commands.add(new WhoSpamsCommand());
commands.add(new ImdbCommand());
commands.add(new SwagCommand());
commands.add(new WarningCommand());
// music commands
commands.add(new JoinCommand());
commands.add(new LeaveCommand());
commands.add(new AddSongCommand());
commands.add(new PlayCommand());
commands.add(new PauseCommand());
commands.add(new SkipCommand());
commands.add(new ClearCommand());
commands.add(new VolumeCommand());
commands.add(new SongCommand());
commands.add(new PlaylistCommand());
commands.add(new ShuffleCommand());
commands.add(new LoopCommand());
commands.add(new FwdCommand());
commands.add(new SavePlaylistCommand());
commands.add(new LoadPlaylistCommand());
// admin only commands (not listed when using help)
commands.add(new SetBotGameCommand());
commands.add(new SetBotNameCommand());
commands.add(new SetBotAvatarCommand());
commands.add(new SetBotPrefixCommand());
addSong = new AddSongCommand(); // used by !play command
} catch (DiscordException | RateLimitException | UnknownBindingException e) {
e.printStackTrace();
}
}
// todo logger
// todo fwd song
// todo random song list? + random song add
// todo rip (text on img)
// todo warn user
// todo aws amazon host? heroku?
// help -admin commands +music guide
// return time in seconds since program start
public static long getUptime(){
return (System.currentTimeMillis() - startTime) / 1000;
}
public static int getReadmessages(){
return readMessages;
}
public static int getReadCommands(){
return readCommands;
}
public static void increaseReadMessages(){
readMessages++;
}
public static void increaseReadCommands(){
readCommands++;
}
// return commandlist
public static ArrayList<Command> getCommands(){
return commands;
}
// return only commands of commandtype type
public static ArrayList<Command> getCommandsByType(CommandType type){
ArrayList<Command> ret = new ArrayList<>();
for(Command cmd : commands){
if(cmd.getCommandType() == type){
ret.add(cmd);
}
}
return ret;
}
// return lavaplayer
public static Player getPlayer(IGuild guild){
return manager.getPlayer(guild.getID());
}
}
|
32095_19 | /*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 2.0 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
** Processing integration: Andres Colubri, February 2012
*/
package processing.opengl.tess;
class Geom {
private Geom() {
}
/*
* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. If uw is
* vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v is very
* close to u or w. In particular if we set v->t = 0 and let r be the
* negated result (this evaluates (uw)(v->s)), then r is guaranteed to
* satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/*
* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. If
* uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v is very
* close to u or w. In particular if we set v->s = 0 and let r be the
* negated result (this evaluates (uw)(v->t)), then r is guaranteed to
* satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/*
* Returns a number whose sign matches TransEval(u,v,w) but which is
* cheaper to evaluate. Returns > 0, == 0 , or < 0 as v is above, on, or
* below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/*
* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results on
* some degenerate inputs, so the client must have some way to handle
* this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/*
* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), or (x+y)/2 if
* a==b==0. It requires that a,b >= 0, and enforces this in the rare case
* that one argument is slightly negative. The implementation is extremely
* stable numerically. In particular it guarantees that the result r
* satisfies MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v)
/*
* Given edges (o1,d1) and (o2,d2), compute their point of intersection. The
* computed point is guaranteed to lie in the intersection of the bounding
* rectangles defined by each edge.
*/{
double z1, z2;
/*
* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering, and
* interpolate the intersection s-value from these. Then repeat using
* the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
/***********************************************************************/
// Compute the cosine of the angle between the edges between o and
// v1 and between o and v2
static double EdgeCos(GLUvertex o, GLUvertex v1, GLUvertex v2) {
double ov1s = v1.s - o.s;
double ov1t = v1.t - o.t;
double ov2s = v2.s - o.s;
double ov2t = v2.t - o.t;
double dotp = ov1s * ov2s + ov1t * ov2t;
double len = Math.sqrt(ov1s * ov1s + ov1t * ov1t) * Math.sqrt(ov2s * ov2s + ov2t * ov2t);
if (len > 0.0) {
dotp /= len;
}
return dotp;
}
static final double EPSILON = 1.0e-5;
static final double ONE_MINUS_EPSILON = 1.0 - EPSILON;
}
| MoradaDigital/protocoder | AndroidApp/protocoder/src/processing/opengl/tess/Geom.java | 4,099 | // v1 and between o and v2 | line_comment | nl | /*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 2.0 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
** Processing integration: Andres Colubri, February 2012
*/
package processing.opengl.tess;
class Geom {
private Geom() {
}
/*
* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. If uw is
* vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v is very
* close to u or w. In particular if we set v->t = 0 and let r be the
* negated result (this evaluates (uw)(v->s)), then r is guaranteed to
* satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/*
* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. If
* uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v is very
* close to u or w. In particular if we set v->s = 0 and let r be the
* negated result (this evaluates (uw)(v->t)), then r is guaranteed to
* satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/*
* Returns a number whose sign matches TransEval(u,v,w) but which is
* cheaper to evaluate. Returns > 0, == 0 , or < 0 as v is above, on, or
* below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/*
* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results on
* some degenerate inputs, so the client must have some way to handle
* this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/*
* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), or (x+y)/2 if
* a==b==0. It requires that a,b >= 0, and enforces this in the rare case
* that one argument is slightly negative. The implementation is extremely
* stable numerically. In particular it guarantees that the result r
* satisfies MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v)
/*
* Given edges (o1,d1) and (o2,d2), compute their point of intersection. The
* computed point is guaranteed to lie in the intersection of the bounding
* rectangles defined by each edge.
*/{
double z1, z2;
/*
* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering, and
* interpolate the intersection s-value from these. Then repeat using
* the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
/***********************************************************************/
// Compute the cosine of the angle between the edges between o and
// v1 and<SUF>
static double EdgeCos(GLUvertex o, GLUvertex v1, GLUvertex v2) {
double ov1s = v1.s - o.s;
double ov1t = v1.t - o.t;
double ov2s = v2.s - o.s;
double ov2t = v2.t - o.t;
double dotp = ov1s * ov2s + ov1t * ov2t;
double len = Math.sqrt(ov1s * ov1s + ov1t * ov1t) * Math.sqrt(ov2s * ov2s + ov2t * ov2t);
if (len > 0.0) {
dotp /= len;
}
return dotp;
}
static final double EPSILON = 1.0e-5;
static final double ONE_MINUS_EPSILON = 1.0 - EPSILON;
}
|
88010_7 | package de.morrisbr.language.user.propety.registry;
import de.morrisbr.language.LanguagePlugin;
import de.morrisbr.language.database.LiteSQL;
import de.morrisbr.language.user.User;
import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.UUID;
public class UserRegistry {
private final Registry registry;
private final HashMap<String, User> users = new HashMap<String, User>();
public UserRegistry(Registry registry) {
this.registry = registry;
}
/**
* Add user to Memory.
* Add user to DataBase.
* <p>
* (User Register)
*
* @param user
*/
public void addUser(User user) {
LiteSQL databank = getRegistry().getPlugin().getDataBase();
LanguagePlugin plugin = registry.getPlugin();
ConsoleCommandSender consoleSender = plugin.getServer().getConsoleSender();
Player player = plugin.getServer().getPlayer(UUID.fromString(user.getUuid()));
users.put(user.getUuid(), user);
if (!isUserExistInDataBase(user.getUuid())) {
databank.execute("INSERT OR IGNORE INTO Users " + "VALUES ('" + user.getUuid() + "', '" + user.getProfile().getLanguage().getName() + "')");
} else
consoleSender.sendMessage(ChatColor.YELLOW + "LanguageAPI: The User(" + player.getName() + ", " + user.getUuid() + ") is already registered!");
}
/**
*
* Get a User from uuid.
* Not stable, can return NULL
*
* @param uuid
* @return User
*/
public User getUser(String uuid) {
return users.get(uuid);
}
/**
*
* Check is User in Memory registed.
* User is Registed, when his Joined.
*
* Returnt: True - when is in Memory.
*
* Returnt: False - when is not in Memory.
*
* @param uuid
* @return boolean
*/
public boolean isUserExistInMemory(String uuid) {
return getUser(uuid) != null;
}
/**
*
* Check is User in DataBase registed.
* User is Registed, when his Joined.
*
* Returnt: True - when is in DataBase.
*
* Returnt: False - when is not in DataBase.
*
* @param uuid
* @return boolean
*/
public boolean isUserExistInDataBase(String uuid) {
LiteSQL database = getRegistry().getPlugin().getDataBase();
try {
ResultSet resultSet = database.executeQuery("SELECT * FROM Users WHERE player_uuid='" + uuid + "'");
if (resultSet.next())
resultSet.close();
return true;
} catch (SQLException exception) {
exception.printStackTrace();
}
return false;
}
// public boolean isUserExistInDataBase(String uuid) {
//
// LiteSQL database = getRegistry().getPlugin().getDataBase();
//
// try {
//
// boolean isExist;
//
// ResultSet resultSet = database.executeQuery("SELECT count(spreek),spreek FROM Users WHERE player_uuid = " + uuid);
// resultSet.next();
//
// isExist = resultSet.getInt("count(spreek)") == 1;
// resultSet.close();
//
// return isExist;
//
// } catch (SQLException e) {
// e.printStackTrace();
// return false;
// }
//}
/**
*
* Get the Registry.
*
* @return Registry
*/
public Registry getRegistry() {
return registry;
}
}
| MorrisBrProjects/LanguageAPI | src/de/morrisbr/language/user/propety/registry/UserRegistry.java | 1,077 | // isExist = resultSet.getInt("count(spreek)") == 1; | line_comment | nl | package de.morrisbr.language.user.propety.registry;
import de.morrisbr.language.LanguagePlugin;
import de.morrisbr.language.database.LiteSQL;
import de.morrisbr.language.user.User;
import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.UUID;
public class UserRegistry {
private final Registry registry;
private final HashMap<String, User> users = new HashMap<String, User>();
public UserRegistry(Registry registry) {
this.registry = registry;
}
/**
* Add user to Memory.
* Add user to DataBase.
* <p>
* (User Register)
*
* @param user
*/
public void addUser(User user) {
LiteSQL databank = getRegistry().getPlugin().getDataBase();
LanguagePlugin plugin = registry.getPlugin();
ConsoleCommandSender consoleSender = plugin.getServer().getConsoleSender();
Player player = plugin.getServer().getPlayer(UUID.fromString(user.getUuid()));
users.put(user.getUuid(), user);
if (!isUserExistInDataBase(user.getUuid())) {
databank.execute("INSERT OR IGNORE INTO Users " + "VALUES ('" + user.getUuid() + "', '" + user.getProfile().getLanguage().getName() + "')");
} else
consoleSender.sendMessage(ChatColor.YELLOW + "LanguageAPI: The User(" + player.getName() + ", " + user.getUuid() + ") is already registered!");
}
/**
*
* Get a User from uuid.
* Not stable, can return NULL
*
* @param uuid
* @return User
*/
public User getUser(String uuid) {
return users.get(uuid);
}
/**
*
* Check is User in Memory registed.
* User is Registed, when his Joined.
*
* Returnt: True - when is in Memory.
*
* Returnt: False - when is not in Memory.
*
* @param uuid
* @return boolean
*/
public boolean isUserExistInMemory(String uuid) {
return getUser(uuid) != null;
}
/**
*
* Check is User in DataBase registed.
* User is Registed, when his Joined.
*
* Returnt: True - when is in DataBase.
*
* Returnt: False - when is not in DataBase.
*
* @param uuid
* @return boolean
*/
public boolean isUserExistInDataBase(String uuid) {
LiteSQL database = getRegistry().getPlugin().getDataBase();
try {
ResultSet resultSet = database.executeQuery("SELECT * FROM Users WHERE player_uuid='" + uuid + "'");
if (resultSet.next())
resultSet.close();
return true;
} catch (SQLException exception) {
exception.printStackTrace();
}
return false;
}
// public boolean isUserExistInDataBase(String uuid) {
//
// LiteSQL database = getRegistry().getPlugin().getDataBase();
//
// try {
//
// boolean isExist;
//
// ResultSet resultSet = database.executeQuery("SELECT count(spreek),spreek FROM Users WHERE player_uuid = " + uuid);
// resultSet.next();
//
// isExist =<SUF>
// resultSet.close();
//
// return isExist;
//
// } catch (SQLException e) {
// e.printStackTrace();
// return false;
// }
//}
/**
*
* Get the Registry.
*
* @return Registry
*/
public Registry getRegistry() {
return registry;
}
}
|
190865_4 | package LES1.P5;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class ProductDAOPsql implements ProductDAO {
private Connection conn;
private OVChipkaartDAOPsql ovcdao;
public ProductDAOPsql(Connection conn) {
this.conn = conn;
}
public ProductDAOPsql(Connection conn, OVChipkaartDAOPsql ovcdao) {
this.conn = conn;
this.ovcdao = ovcdao;
}
public void setOvcdao(OVChipkaartDAOPsql ovcdao) {
this.ovcdao = ovcdao;
}
@Override
public boolean save(Product product) {
String SQL = "INSERT INTO product VALUES (?, ?, ?, ?)";
String SQL2 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
prestat.setInt(1, product.getProduct_nummer());
prestat.setString(2, product.getNaam());
prestat.setString(3, product.getBeschrijving());
prestat.setFloat(4, product.getPrijs());
prestat.executeUpdate();
for (OVChipkaart o : product.getOVChipkaarten()) {
PreparedStatement prestat2 = conn.prepareStatement(SQL2);
prestat2.setInt(1, o.getKaart_nummer());
prestat2.setInt(2, product.getProduct_nummer());
prestat2.setString(3, "actief");
prestat2.setDate(4, Date.valueOf(LocalDate.now()));
prestat2.executeUpdate();
}
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
@Override
public boolean update(Product product) {
// De update functie is niet heel erg uitgebreid of complex, maar als standaard heb ik genomen dat de prijs van het product met 5 word verhoogd
String SQL = "UPDATE product SET prijs = prijs + 5 WHERE product_nummer = ?";
// Ik nam aan dat "last update" in de koppel tabel stond voor wanneer een product of ovchipkaart voor het laatst is veranderd/geupdate
// En ik verander de prijs van een product, dus dan moet in de koppel tabel de "last update" upgedate worden op de plekken met dat zelfde product nummer
String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?";
String SQL3 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
PreparedStatement prestat2 = conn.prepareStatement(SQL2);
prestat.setInt(1, product.getProduct_nummer());
prestat2.setInt(1, product.getProduct_nummer());
prestat.executeUpdate();
prestat2.executeUpdate();
for (OVChipkaart o : product.getOVChipkaarten()) {
PreparedStatement prestat3 = conn.prepareStatement(SQL3);
prestat3.setInt(1, o.getKaart_nummer());
prestat3.setInt(2, product.getProduct_nummer());
prestat3.setString(3, "actief");
prestat3.setDate(4, Date.valueOf(LocalDate.now()));
prestat3.executeUpdate();
}
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
@Override
public boolean delete(Product product) {
String SQL = "DELETE FROM product WHERE product_nummer = ?";
String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
PreparedStatement prestat2 = conn.prepareStatement(SQL2);
prestat.setInt(1, product.getProduct_nummer());
prestat2.setInt(1, product.getProduct_nummer());
prestat2.executeUpdate();
prestat.executeUpdate();
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
public List<Product> findByOVChipkaart(OVChipkaart ovChipkaart) {
String SQL = "SELECT ov_chipkaart_product.kaart_nummer, product.product_nummer, product.naam, product.beschrijving, product.prijs " +
"FROM product " +
"JOIN ov_chipkaart_product " +
"ON ov_chipkaart_product.product_nummer = product.product_nummer " +
"WHERE ov_chipkaart_product.kaart_nummer = ? " +
"ORDER BY kaart_nummer, product_nummer";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
prestat.setInt(1, ovChipkaart.getKaart_nummer());
ResultSet rs = prestat.executeQuery();
List<Product> producten = new ArrayList<>();
while (rs.next()) {
int prnr = rs.getInt("product_nummer");
String nm = rs.getString("naam");
String besch = rs.getString("beschrijving");
Float prijs = rs.getFloat("prijs");
Product pr = new Product(prnr, nm, besch, prijs);
pr.addOVChipkaart(ovChipkaart);
producten.add(pr);
}
return producten;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public List<Product> findAll(){
// Hier veranderd van "SELECT * FROM product;" naar deze query met JOIN zodat je ook de ovchipkaarten ook op haalt en toevoegd aan de producten
// Hetzelfde in OVChipkaartDAOPsql
String SQL = "SELECT ov_chipkaart_product.kaart_nummer, ov_chipkaart.geldig_tot, ov_chipkaart.klasse, ov_chipkaart.saldo, ov_chipkaart.reiziger_id, product.product_nummer, product.naam, product.beschrijving, product.prijs " +
"FROM product " +
"JOIN ov_chipkaart_product " +
"ON ov_chipkaart_product.product_nummer = product.product_nummer " +
"JOIN ov_chipkaart " +
"ON ov_chipkaart_product.kaart_nummer = ov_chipkaart.kaart_nummer " +
"ORDER BY kaart_nummer, product_nummer;";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
ResultSet rs = prestat.executeQuery();
List<Product> producten = new ArrayList<>();
while(rs.next()) {
int prnr = rs.getInt("product_nummer");
String nm = rs.getString("naam");
String besch = rs.getString("beschrijving");
Float prijs = rs.getFloat("prijs");
int knm = rs.getInt("kaart_nummer");
Date geldigTot = rs.getDate("geldig_tot");
int klasse = rs.getInt("klasse");
float saldo = rs.getFloat("saldo");
int rid = rs.getInt("reiziger_id");
OVChipkaart ov = new OVChipkaart(knm, geldigTot, klasse, saldo, rid);
Product pr = new Product(prnr, nm, besch, prijs);
for(Product p : producten){
if(p.getProduct_nummer() == pr.getProduct_nummer()){
p.addOVChipkaart(ov);
break;
}
}
pr.addOVChipkaart(ov);
producten.add(pr);
}
return producten;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
| MorrisT011/DP_OV-Chipkaart2 | src/LES1/P5/ProductDAOPsql.java | 2,247 | // Hetzelfde in OVChipkaartDAOPsql | line_comment | nl | package LES1.P5;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class ProductDAOPsql implements ProductDAO {
private Connection conn;
private OVChipkaartDAOPsql ovcdao;
public ProductDAOPsql(Connection conn) {
this.conn = conn;
}
public ProductDAOPsql(Connection conn, OVChipkaartDAOPsql ovcdao) {
this.conn = conn;
this.ovcdao = ovcdao;
}
public void setOvcdao(OVChipkaartDAOPsql ovcdao) {
this.ovcdao = ovcdao;
}
@Override
public boolean save(Product product) {
String SQL = "INSERT INTO product VALUES (?, ?, ?, ?)";
String SQL2 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
prestat.setInt(1, product.getProduct_nummer());
prestat.setString(2, product.getNaam());
prestat.setString(3, product.getBeschrijving());
prestat.setFloat(4, product.getPrijs());
prestat.executeUpdate();
for (OVChipkaart o : product.getOVChipkaarten()) {
PreparedStatement prestat2 = conn.prepareStatement(SQL2);
prestat2.setInt(1, o.getKaart_nummer());
prestat2.setInt(2, product.getProduct_nummer());
prestat2.setString(3, "actief");
prestat2.setDate(4, Date.valueOf(LocalDate.now()));
prestat2.executeUpdate();
}
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
@Override
public boolean update(Product product) {
// De update functie is niet heel erg uitgebreid of complex, maar als standaard heb ik genomen dat de prijs van het product met 5 word verhoogd
String SQL = "UPDATE product SET prijs = prijs + 5 WHERE product_nummer = ?";
// Ik nam aan dat "last update" in de koppel tabel stond voor wanneer een product of ovchipkaart voor het laatst is veranderd/geupdate
// En ik verander de prijs van een product, dus dan moet in de koppel tabel de "last update" upgedate worden op de plekken met dat zelfde product nummer
String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?";
String SQL3 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
PreparedStatement prestat2 = conn.prepareStatement(SQL2);
prestat.setInt(1, product.getProduct_nummer());
prestat2.setInt(1, product.getProduct_nummer());
prestat.executeUpdate();
prestat2.executeUpdate();
for (OVChipkaart o : product.getOVChipkaarten()) {
PreparedStatement prestat3 = conn.prepareStatement(SQL3);
prestat3.setInt(1, o.getKaart_nummer());
prestat3.setInt(2, product.getProduct_nummer());
prestat3.setString(3, "actief");
prestat3.setDate(4, Date.valueOf(LocalDate.now()));
prestat3.executeUpdate();
}
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
@Override
public boolean delete(Product product) {
String SQL = "DELETE FROM product WHERE product_nummer = ?";
String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
PreparedStatement prestat2 = conn.prepareStatement(SQL2);
prestat.setInt(1, product.getProduct_nummer());
prestat2.setInt(1, product.getProduct_nummer());
prestat2.executeUpdate();
prestat.executeUpdate();
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return false;
}
public List<Product> findByOVChipkaart(OVChipkaart ovChipkaart) {
String SQL = "SELECT ov_chipkaart_product.kaart_nummer, product.product_nummer, product.naam, product.beschrijving, product.prijs " +
"FROM product " +
"JOIN ov_chipkaart_product " +
"ON ov_chipkaart_product.product_nummer = product.product_nummer " +
"WHERE ov_chipkaart_product.kaart_nummer = ? " +
"ORDER BY kaart_nummer, product_nummer";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
prestat.setInt(1, ovChipkaart.getKaart_nummer());
ResultSet rs = prestat.executeQuery();
List<Product> producten = new ArrayList<>();
while (rs.next()) {
int prnr = rs.getInt("product_nummer");
String nm = rs.getString("naam");
String besch = rs.getString("beschrijving");
Float prijs = rs.getFloat("prijs");
Product pr = new Product(prnr, nm, besch, prijs);
pr.addOVChipkaart(ovChipkaart);
producten.add(pr);
}
return producten;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public List<Product> findAll(){
// Hier veranderd van "SELECT * FROM product;" naar deze query met JOIN zodat je ook de ovchipkaarten ook op haalt en toevoegd aan de producten
// Hetzelfde in<SUF>
String SQL = "SELECT ov_chipkaart_product.kaart_nummer, ov_chipkaart.geldig_tot, ov_chipkaart.klasse, ov_chipkaart.saldo, ov_chipkaart.reiziger_id, product.product_nummer, product.naam, product.beschrijving, product.prijs " +
"FROM product " +
"JOIN ov_chipkaart_product " +
"ON ov_chipkaart_product.product_nummer = product.product_nummer " +
"JOIN ov_chipkaart " +
"ON ov_chipkaart_product.kaart_nummer = ov_chipkaart.kaart_nummer " +
"ORDER BY kaart_nummer, product_nummer;";
try {
PreparedStatement prestat = conn.prepareStatement(SQL);
ResultSet rs = prestat.executeQuery();
List<Product> producten = new ArrayList<>();
while(rs.next()) {
int prnr = rs.getInt("product_nummer");
String nm = rs.getString("naam");
String besch = rs.getString("beschrijving");
Float prijs = rs.getFloat("prijs");
int knm = rs.getInt("kaart_nummer");
Date geldigTot = rs.getDate("geldig_tot");
int klasse = rs.getInt("klasse");
float saldo = rs.getFloat("saldo");
int rid = rs.getInt("reiziger_id");
OVChipkaart ov = new OVChipkaart(knm, geldigTot, klasse, saldo, rid);
Product pr = new Product(prnr, nm, besch, prijs);
for(Product p : producten){
if(p.getProduct_nummer() == pr.getProduct_nummer()){
p.addOVChipkaart(ov);
break;
}
}
pr.addOVChipkaart(ov);
producten.add(pr);
}
return producten;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
|
153347_28 | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.entitySystem.entity.internal;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.set.TLongSet;
import gnu.trove.set.hash.TLongHashSet;
import org.joml.Quaternionfc;
import org.joml.Vector3fc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.engine.core.TerasologyConstants;
import org.terasology.engine.entitySystem.entity.EntityBuilder;
import org.terasology.engine.entitySystem.entity.EntityRef;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.BeforeRemoveComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.OnActivatedComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.OnAddedComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.OnChangedComponent;
import org.terasology.engine.entitySystem.event.internal.EventSystem;
import org.terasology.engine.entitySystem.metadata.ComponentLibrary;
import org.terasology.engine.entitySystem.prefab.Prefab;
import org.terasology.engine.entitySystem.prefab.PrefabManager;
import org.terasology.engine.entitySystem.sectors.SectorSimulationComponent;
import org.terasology.engine.game.GameManifest;
import org.terasology.engine.world.internal.WorldInfo;
import org.terasology.gestalt.entitysystem.component.Component;
import org.terasology.persistence.typeHandling.TypeHandlerLibrary;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.terasology.engine.entitySystem.entity.internal.EntityScope.SECTOR;
public class PojoEntityManager implements EngineEntityManager {
public static final long NULL_ID = 0;
private static final Logger logger = LoggerFactory.getLogger(PojoEntityManager.class);
private long nextEntityId = 1;
private TLongSet loadedIds = new TLongHashSet();
private EngineEntityPool globalPool = new PojoEntityPool(this);
private PojoSectorManager sectorManager = new PojoSectorManager(this);
private Map<Long, EngineEntityPool> poolMap = new MapMaker().initialCapacity(1000).makeMap();
private List<EngineEntityPool> worldPools = Lists.newArrayList();
private Map<EngineEntityPool, Long> poolCounts = new HashMap<EngineEntityPool, Long>();
private Set<EntityChangeSubscriber> subscribers = Sets.newLinkedHashSet();
private Set<EntityDestroySubscriber> destroySubscribers = Sets.newLinkedHashSet();
private EventSystem eventSystem;
private PrefabManager prefabManager;
private ComponentLibrary componentLibrary;
private WorldManager worldManager;
private GameManifest gameManifest;
private RefStrategy refStrategy = new DefaultRefStrategy();
private TypeHandlerLibrary typeSerializerLibrary;
@Override
public RefStrategy getEntityRefStrategy() {
return refStrategy;
}
@Override
public void setEntityRefStrategy(RefStrategy strategy) {
this.refStrategy = strategy;
}
@Override
public EngineEntityPool getGlobalPool() {
return globalPool;
}
/**
* Check if world pools have been created and returns them such that subsequent entities are put in them. The global pool
* is returned if no world pools have been created.
*
* @return the pool under consideration.
*/
public EngineEntityPool getCurrentWorldPool() {
if (worldManager == null || worldManager.getCurrentWorldPool() == null) {
return globalPool;
} else {
return worldManager.getCurrentWorldPool();
}
}
/**
* Not all entities are present in the world pools. The world pools are created only
* in the {@link org.terasology.engine.core.modes.loadProcesses.CreateWorldEntity} process, but much before
* that some blocks are loaded. Hence those are by default put into the global pool.
*
* @return if world pools have been formed or not
*/
private boolean isWorldPoolGlobalPool() {
return getCurrentWorldPool() == globalPool;
}
@Override
public void clear() {
globalPool.clear();
sectorManager.clear();
nextEntityId = 1;
loadedIds.clear();
}
@Override
public EntityBuilder newBuilder() {
return getCurrentWorldPool().newBuilder();
}
@Override
public EntityBuilder newBuilder(String prefabName) {
return getCurrentWorldPool().newBuilder(prefabName);
}
@Override
public EntityBuilder newBuilder(Prefab prefab) {
return getCurrentWorldPool().newBuilder(prefab);
}
@Override
public EntityRef create() {
return getCurrentWorldPool().create();
}
@Override
public void createWorldPools(GameManifest game) {
this.gameManifest = game;
Map<String, WorldInfo> worldInfoMap = gameManifest.getWorldInfoMap();
worldManager = new WorldManager(gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD));
for (Map.Entry<String, WorldInfo> worldInfoEntry : worldInfoMap.entrySet()) {
EngineEntityPool pool = new PojoEntityPool(this);
//pool.create();
worldPools.add(pool);
worldManager.addWorldPool(worldInfoEntry.getValue(), pool);
}
}
@Override
public EntityRef createSectorEntity(long maxDelta) {
return createSectorEntity(maxDelta, maxDelta);
}
@Override
public EntityRef createSectorEntity(long unloadedMaxDelta, long loadedMaxDelta) {
EntityRef entity = sectorManager.create();
entity.setScope(SECTOR);
SectorSimulationComponent simulationComponent = entity.getComponent(SectorSimulationComponent.class);
simulationComponent.unloadedMaxDelta = unloadedMaxDelta;
simulationComponent.loadedMaxDelta = loadedMaxDelta;
entity.saveComponent(simulationComponent);
return entity;
}
@Override
public long createEntity() {
if (nextEntityId == NULL_ID) {
nextEntityId++;
}
loadedIds.add(nextEntityId);
return nextEntityId++;
}
@Override
public EntityRef create(Component... components) {
return getCurrentWorldPool().create(components);
}
@Override
public EntityRef create(Iterable<Component> components) {
return getCurrentWorldPool().create(components);
}
@Override
public EntityRef create(Iterable<Component> components, boolean sendLifecycleEvents) {
return getCurrentWorldPool().create(components, sendLifecycleEvents);
}
@Override
public EntityRef create(String prefabName) {
return getCurrentWorldPool().create(prefabName);
}
@Override
public EntityRef create(Prefab prefab, Vector3fc position, Quaternionfc rotation) {
return getCurrentWorldPool().create(prefab, position, rotation);
}
@Override
public EntityRef create(Prefab prefab, Vector3fc position) {
return getCurrentWorldPool().create(prefab, position);
}
@Override
public EntityRef create(String prefab, Vector3fc position) {
return getCurrentWorldPool().create(prefab, position);
}
@Override
public EntityRef create(Prefab prefab) {
return getCurrentWorldPool().create(prefab);
}
@Override
//Todo: Depreciated, maybe remove? Not many uses
public EntityRef copy(EntityRef other) {
if (!other.exists()) {
return EntityRef.NULL;
}
List<Component> newEntityComponents = Lists.newArrayList();
for (Component c : other.iterateComponents()) {
newEntityComponents.add(componentLibrary.copy(c));
}
return getCurrentWorldPool().create(newEntityComponents);
}
@Override
public Map<Class<? extends Component>, Component> copyComponents(EntityRef other) {
Map<Class<? extends Component>, Component> result = Maps.newHashMap();
for (Component c : other.iterateComponents()) {
result.put(c.getClass(), componentLibrary.copyWithOwnedEntities(c));
}
return result;
}
@Override
public Iterable<EntityRef> getAllEntities() {
if (isWorldPoolGlobalPool()) {
return Iterables.concat(globalPool.getAllEntities(), sectorManager.getAllEntities());
}
return Iterables.concat(globalPool.getAllEntities(), getCurrentWorldPool().getAllEntities(), sectorManager.getAllEntities());
}
@SafeVarargs
@Override
public final Iterable<EntityRef> getEntitiesWith(Class<? extends Component>... componentClasses) {
if (isWorldPoolGlobalPool()) {
return Iterables.concat(globalPool.getEntitiesWith(componentClasses),
sectorManager.getEntitiesWith(componentClasses));
}
return Iterables.concat(globalPool.getEntitiesWith(componentClasses),
getCurrentWorldPool().getEntitiesWith(componentClasses), sectorManager.getEntitiesWith(componentClasses));
}
@Override
public int getActiveEntityCount() {
if (isWorldPoolGlobalPool()) {
return globalPool.getActiveEntityCount() + sectorManager.getActiveEntityCount();
}
return globalPool.getActiveEntityCount() + getCurrentWorldPool().getActiveEntityCount()
+ sectorManager.getActiveEntityCount();
}
@Override
public ComponentLibrary getComponentLibrary() {
return componentLibrary;
}
public void setComponentLibrary(ComponentLibrary componentLibrary) {
this.componentLibrary = componentLibrary;
}
@Override
public EventSystem getEventSystem() {
return eventSystem;
}
@Override
public void setEventSystem(EventSystem eventSystem) {
this.eventSystem = eventSystem;
}
@Override
public PrefabManager getPrefabManager() {
return prefabManager;
}
public void setPrefabManager(PrefabManager prefabManager) {
this.prefabManager = prefabManager;
}
/*
* Engine features
*/
@Override
public EntityRef getEntity(long id) {
return getPool(id)
.map(pool -> pool.getEntity(id))
.orElse(EntityRef.NULL);
}
@Override
public List<EngineEntityPool> getWorldPools() {
return worldPools;
}
@Override
public Map<WorldInfo, EngineEntityPool> getWorldPoolsMap() {
return worldManager.getWorldPoolMap();
}
@Override
public Map<Long, EngineEntityPool> getPoolMap() {
return poolMap;
}
@Override
public Map<EngineEntityPool, Long> getPoolCounts() {
return poolCounts;
}
/**
* Creates the entity without sending any events. The entity life cycle subscriber will however be informed.
*/
@Override
public EntityRef createEntityWithoutLifecycleEvents(Iterable<Component> components) {
return getCurrentWorldPool().createEntityWithoutLifecycleEvents(components);
}
/**
* Creates the entity without sending any events. The entity life cycle subscriber will however be informed.
*/
@Override
public EntityRef createEntityWithoutLifecycleEvents(String prefabName) {
return getCurrentWorldPool().createEntityWithoutLifecycleEvents(prefabName);
}
/**
* Creates the entity without sending any events. The entity life cycle subscriber will however be informed.
*/
@Override
public EntityRef createEntityWithoutLifecycleEvents(Prefab prefab) {
return getCurrentWorldPool().createEntityWithoutLifecycleEvents(prefab);
}
@Override
public void putEntity(long entityId, BaseEntityRef ref) {
getCurrentWorldPool().putEntity(entityId, ref);
}
@Override
public ComponentTable getComponentStore() {
return getCurrentWorldPool().getComponentStore();
}
@Override
public void destroyEntityWithoutEvents(EntityRef entity) {
getCurrentWorldPool().destroyEntityWithoutEvents(entity);
}
@Override
public EntityRef createEntityWithId(long id, Iterable<Component> components) {
EntityBuilder builder = newBuilder();
builder.setId(id);
builder.addComponents(components);
return builder.build();
}
@Override
public void subscribeForChanges(EntityChangeSubscriber subscriber) {
subscribers.add(subscriber);
}
@Override
public void subscribeForDestruction(EntityDestroySubscriber subscriber) {
destroySubscribers.add(subscriber);
}
@Override
public void unsubscribe(EntityChangeSubscriber subscriber) {
subscribers.remove(subscriber);
}
@Override
public TypeHandlerLibrary getTypeSerializerLibrary() {
return typeSerializerLibrary;
}
public void setTypeSerializerLibrary(TypeHandlerLibrary serializerLibrary) {
this.typeSerializerLibrary = serializerLibrary;
}
@Override
public EngineSectorManager getSectorManager() {
return sectorManager;
}
@Override
public void deactivateForStorage(EntityRef entity) {
if (!entity.exists()) {
return;
}
long entityId = entity.getId();
if (eventSystem != null) {
eventSystem.send(entity, BeforeDeactivateComponent.newInstance());
}
List<Component> components = Collections.unmodifiableList(
getPool(entityId)
.map(pool -> pool.getComponentStore().getComponentsInNewList(entityId))
.orElse(Collections.emptyList()));
notifyBeforeDeactivation(entity, components);
for (Component component : components) {
getPool(entityId).ifPresent(pool -> pool.getComponentStore().remove(entityId, component.getClass()));
}
loadedIds.remove(entityId);
}
@Override
public long getNextId() {
return nextEntityId;
}
@Override
public void setNextId(long id) {
nextEntityId = id;
}
/*
* For use by Entity Refs
*/
/**
* @param entityId
* @param componentClass
* @return Whether the entity has a component of the given type
*/
@Override
public boolean hasComponent(long entityId, Class<? extends Component> componentClass) {
return globalPool.getComponentStore().get(entityId, componentClass) != null
|| getCurrentWorldPool().getComponentStore().get(entityId, componentClass) != null
|| sectorManager.hasComponent(entityId, componentClass);
}
@Override
public boolean isExistingEntity(long id) {
return nextEntityId > id;
}
/**
* @param id
* @return Whether the entity is currently active
*/
@Override
public boolean isActiveEntity(long id) {
return loadedIds.contains(id);
}
/**
* @param entityId
* @return An iterable over the components of the given entity
*/
@Override
public Iterable<Component> iterateComponents(long entityId) {
return getPool(entityId)
.map(pool -> pool.getComponentStore().iterateComponents(entityId))
.orElse(Collections.emptyList());
}
@Override
public void destroy(long entityId) {
getPool(entityId).ifPresent(pool -> pool.destroy(entityId));
}
protected void notifyComponentRemovalAndEntityDestruction(long entityId, EntityRef ref) {
getPool(entityId)
.map(pool -> pool.getComponentStore().iterateComponents(entityId))
.orElse(Collections.emptyList())
.forEach(comp -> notifyComponentRemoved(ref, comp.getClass()));
for (EntityDestroySubscriber destroySubscriber : destroySubscribers) {
destroySubscriber.onEntityDestroyed(ref);
}
}
/**
* @param entityId
* @param componentClass
* @param <T>
* @return The component of that type owned by the given entity, or null if it doesn't have that component
*/
@Override
public <T extends Component> T getComponent(long entityId, Class<T> componentClass) {
return getPool(entityId)
.map(pool -> pool.getComponentStore().get(entityId, componentClass))
.orElse(null);
}
/**
* Adds (or replaces) a component to an entity
*
* @param entityId
* @param component
* @param <T>
* @return The added component
*/
@Override
public <T extends Component> T addComponent(long entityId, T component) {
Preconditions.checkNotNull(component);
Optional<Component> oldComponent = getPool(entityId).map(pool -> pool.getComponentStore().put(entityId, component));
// notify internal users first to get the unobstructed views on the entity as it is at this moment.
if (!oldComponent.isPresent()) {
notifyComponentAdded(getEntity(entityId), component.getClass());
} else {
logger.error("Adding a component ({}) over an existing component for entity {}", component.getClass(), entityId);
notifyComponentChanged(getEntity(entityId), component.getClass());
}
// Send life cycle events for arbitrary systems to react on.
// Note: systems are free to remove the component that was just added, which might cause some trouble here...
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);
if (!oldComponent.isPresent()) {
eventSystem.send(entityRef, OnAddedComponent.newInstance(), component);
eventSystem.send(entityRef, OnActivatedComponent.newInstance(), component);
} else {
eventSystem.send(entityRef, OnChangedComponent.newInstance(), component);
}
}
return component;
}
/**
* Removes a component from an entity
*
* @param entityId
* @param componentClass
*/
@Override
public <T extends Component> T removeComponent(long entityId, Class<T> componentClass) {
Optional<ComponentTable> maybeStore = getPool(entityId).map(EngineEntityPool::getComponentStore);
Optional<T> component = maybeStore.map(store -> store.get(entityId, componentClass));
if (component.isPresent()) {
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);
eventSystem.send(entityRef, BeforeDeactivateComponent.newInstance(), component.get());
eventSystem.send(entityRef, BeforeRemoveComponent.newInstance(), component.get());
}
notifyComponentRemoved(getEntity(entityId), componentClass);
maybeStore.ifPresent(store -> store.remove(entityId, componentClass));
}
return component.orElse(null);
}
/**
* Saves a component to an entity
*
* @param entityId
* @param component
*/
@Override
public void saveComponent(long entityId, Component component) {
Optional<Component> oldComponent = getPool(entityId)
.map(pool -> pool.getComponentStore().put(entityId, component));
if (!oldComponent.isPresent()) {
logger.error("Saving a component ({}) that doesn't belong to this entity {}", component.getClass(), entityId);
}
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);
if (!oldComponent.isPresent()) {
eventSystem.send(entityRef, OnAddedComponent.newInstance(), component);
eventSystem.send(entityRef, OnActivatedComponent.newInstance(), component);
} else {
eventSystem.send(entityRef, OnChangedComponent.newInstance(), component);
}
}
if (!oldComponent.isPresent()) {
notifyComponentAdded(getEntity(entityId), component.getClass());
} else {
notifyComponentChanged(getEntity(entityId), component.getClass());
}
}
/*
* Implementation
*/
public Optional<EngineEntityPool> getPool(long id) {
Optional<EngineEntityPool> pool = Optional.ofNullable(poolMap.get(id));
if (!pool.isPresent()) {
if (id != NULL_ID) {
// TODO: Entity pools assignment is not needed as of now, can be enabled later on when necessary.
if (!isExistingEntity(id)) {
logger.error("Entity {} doesn't exist", id);
}
}
}
return pool;
}
/**
* Assign the given entity to the given pool.
* <p>
* If the entity is already assigned to a pool, it will be re-assigned to the given pool.
* This does not actually move the entity or any of its components.
* If you want to move an entity to a different pool, {@link #moveToPool(long, EngineEntityPool)} should be used
* instead.
*
* @param entityId the id of the entity to assign
* @param pool the pool to assign the entity to
*/
@Override
public void assignToPool(long entityId, EngineEntityPool pool) {
if (poolMap.get(entityId) != pool) {
poolMap.put(entityId, pool);
if (!poolCounts.containsKey(pool)) {
poolCounts.put(pool, 1L);
} else {
poolCounts.put(pool, poolCounts.get(pool) + 1L);
}
}
}
/**
* Remove the assignment of an entity to a pool.
* <p>
* This does not affect anything else related to the entity, but may lead to the entity or its components being
* unable to be found.
* <p>
* When using this method, be sure to properly re-assign the entity to its correct pool afterwards.
*
* @param id the id of the entity to remove the assignment for
*/
protected void unassignPool(long id) {
poolMap.remove(id);
}
@Override
public boolean moveToPool(long id, EngineEntityPool pool) {
if (getPool(id).isPresent() && getPool(id).get().equals(pool)) {
//The entity is already in the correct pool
return true;
}
//Save the current entity and components
Optional<EngineEntityPool> maybePool = getPool(id);
EngineEntityPool oldPool;
if (!maybePool.isPresent()) {
return false;
} else {
oldPool = maybePool.get();
}
Map<Class<? extends Component>, Component> savedComponents = copyComponents(oldPool.getEntity(id));
//Remove from the existing pool
Optional<BaseEntityRef> maybeRef = oldPool.remove(id);
//Decrease the count of entities in that pool
poolCounts.put(oldPool, poolCounts.get(oldPool) - 1);
if (!maybeRef.isPresent()) {
return false;
}
BaseEntityRef ref = maybeRef.get();
//Create in new pool
pool.insertRef(ref, savedComponents.values());
//TODO: send events?
return true;
}
@Override
public void notifyComponentAdded(EntityRef changedEntity, Class<? extends Component> component) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onEntityComponentAdded(changedEntity, component);
}
}
protected void notifyComponentRemoved(EntityRef changedEntity, Class<? extends Component> component) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onEntityComponentRemoved(changedEntity, component);
}
}
protected void notifyComponentChanged(EntityRef changedEntity, Class<? extends Component> component) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onEntityComponentChange(changedEntity, component);
}
}
/**
* This method gets called when the entity gets reactivated. e.g. after storage an entity needs to be reactivated.
*/
private void notifyReactivation(EntityRef entity, Collection<Component> components) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onReactivation(entity, components);
}
}
/**
* This method gets called before an entity gets deactivated (e.g. for storage).
*/
private void notifyBeforeDeactivation(EntityRef entity, Collection<Component> components) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onBeforeDeactivation(entity, components);
}
}
@Override
@SafeVarargs
public final int getCountOfEntitiesWith(Class<? extends Component>... componentClasses) {
if (isWorldPoolGlobalPool()) {
return globalPool.getCountOfEntitiesWith(componentClasses) +
sectorManager.getCountOfEntitiesWith(componentClasses);
}
return sectorManager.getCountOfEntitiesWith(componentClasses) +
getCurrentWorldPool().getCountOfEntitiesWith(componentClasses) +
globalPool.getCountOfEntitiesWith(componentClasses);
}
public <T extends Component> Iterable<Map.Entry<EntityRef, T>> listComponents(Class<T> componentClass) {
List<TLongObjectIterator<T>> iterators = new ArrayList<>();
if (isWorldPoolGlobalPool()) {
iterators.add(globalPool.getComponentStore().componentIterator(componentClass));
} else {
iterators.add(globalPool.getComponentStore().componentIterator(componentClass));
iterators.add(getCurrentWorldPool().getComponentStore().componentIterator(componentClass));
}
iterators.add(sectorManager.getComponentStore().componentIterator(componentClass));
List<Map.Entry<EntityRef, T>> list = new ArrayList<>();
for (TLongObjectIterator<T> iterator : iterators) {
if (iterator != null) {
while (iterator.hasNext()) {
iterator.advance();
list.add(new EntityEntry<>(getEntity(iterator.key()), iterator.value()));
}
}
}
return list;
}
@Override
public boolean registerId(long entityId) {
if (entityId >= nextEntityId) {
logger.error("Prevented attempt to create entity with an invalid id.");
return false;
}
loadedIds.add(entityId);
return true;
}
protected boolean idLoaded(long entityId) {
return loadedIds.contains(entityId);
}
@Override
public Optional<BaseEntityRef> remove(long id) {
return getPool(id)
.flatMap(pool -> pool.remove(id));
}
@Override
public void insertRef(BaseEntityRef ref, Iterable<Component> components) {
globalPool.insertRef(ref, components);
}
@Override
public boolean contains(long id) {
return globalPool.contains(id) || sectorManager.contains(id);
}
/**
* Remove this id from the entity manager's list of loaded ids.
*
* @param id the id to remove
*/
protected void unregister(long id) {
loadedIds.remove(id);
}
private static class EntityEntry<T> implements Map.Entry<EntityRef, T> {
private EntityRef key;
private T value;
EntityEntry(EntityRef ref, T value) {
this.key = ref;
this.value = value;
}
@Override
public EntityRef getKey() {
return key;
}
@Override
public T getValue() {
return value;
}
@Override
public T setValue(T newValue) {
throw new UnsupportedOperationException();
}
}
}
| MovingBlocks/Terasology | engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java | 7,351 | //TODO: send events? | line_comment | nl | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.entitySystem.entity.internal;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.set.TLongSet;
import gnu.trove.set.hash.TLongHashSet;
import org.joml.Quaternionfc;
import org.joml.Vector3fc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.engine.core.TerasologyConstants;
import org.terasology.engine.entitySystem.entity.EntityBuilder;
import org.terasology.engine.entitySystem.entity.EntityRef;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.BeforeRemoveComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.OnActivatedComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.OnAddedComponent;
import org.terasology.engine.entitySystem.entity.lifecycleEvents.OnChangedComponent;
import org.terasology.engine.entitySystem.event.internal.EventSystem;
import org.terasology.engine.entitySystem.metadata.ComponentLibrary;
import org.terasology.engine.entitySystem.prefab.Prefab;
import org.terasology.engine.entitySystem.prefab.PrefabManager;
import org.terasology.engine.entitySystem.sectors.SectorSimulationComponent;
import org.terasology.engine.game.GameManifest;
import org.terasology.engine.world.internal.WorldInfo;
import org.terasology.gestalt.entitysystem.component.Component;
import org.terasology.persistence.typeHandling.TypeHandlerLibrary;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.terasology.engine.entitySystem.entity.internal.EntityScope.SECTOR;
public class PojoEntityManager implements EngineEntityManager {
public static final long NULL_ID = 0;
private static final Logger logger = LoggerFactory.getLogger(PojoEntityManager.class);
private long nextEntityId = 1;
private TLongSet loadedIds = new TLongHashSet();
private EngineEntityPool globalPool = new PojoEntityPool(this);
private PojoSectorManager sectorManager = new PojoSectorManager(this);
private Map<Long, EngineEntityPool> poolMap = new MapMaker().initialCapacity(1000).makeMap();
private List<EngineEntityPool> worldPools = Lists.newArrayList();
private Map<EngineEntityPool, Long> poolCounts = new HashMap<EngineEntityPool, Long>();
private Set<EntityChangeSubscriber> subscribers = Sets.newLinkedHashSet();
private Set<EntityDestroySubscriber> destroySubscribers = Sets.newLinkedHashSet();
private EventSystem eventSystem;
private PrefabManager prefabManager;
private ComponentLibrary componentLibrary;
private WorldManager worldManager;
private GameManifest gameManifest;
private RefStrategy refStrategy = new DefaultRefStrategy();
private TypeHandlerLibrary typeSerializerLibrary;
@Override
public RefStrategy getEntityRefStrategy() {
return refStrategy;
}
@Override
public void setEntityRefStrategy(RefStrategy strategy) {
this.refStrategy = strategy;
}
@Override
public EngineEntityPool getGlobalPool() {
return globalPool;
}
/**
* Check if world pools have been created and returns them such that subsequent entities are put in them. The global pool
* is returned if no world pools have been created.
*
* @return the pool under consideration.
*/
public EngineEntityPool getCurrentWorldPool() {
if (worldManager == null || worldManager.getCurrentWorldPool() == null) {
return globalPool;
} else {
return worldManager.getCurrentWorldPool();
}
}
/**
* Not all entities are present in the world pools. The world pools are created only
* in the {@link org.terasology.engine.core.modes.loadProcesses.CreateWorldEntity} process, but much before
* that some blocks are loaded. Hence those are by default put into the global pool.
*
* @return if world pools have been formed or not
*/
private boolean isWorldPoolGlobalPool() {
return getCurrentWorldPool() == globalPool;
}
@Override
public void clear() {
globalPool.clear();
sectorManager.clear();
nextEntityId = 1;
loadedIds.clear();
}
@Override
public EntityBuilder newBuilder() {
return getCurrentWorldPool().newBuilder();
}
@Override
public EntityBuilder newBuilder(String prefabName) {
return getCurrentWorldPool().newBuilder(prefabName);
}
@Override
public EntityBuilder newBuilder(Prefab prefab) {
return getCurrentWorldPool().newBuilder(prefab);
}
@Override
public EntityRef create() {
return getCurrentWorldPool().create();
}
@Override
public void createWorldPools(GameManifest game) {
this.gameManifest = game;
Map<String, WorldInfo> worldInfoMap = gameManifest.getWorldInfoMap();
worldManager = new WorldManager(gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD));
for (Map.Entry<String, WorldInfo> worldInfoEntry : worldInfoMap.entrySet()) {
EngineEntityPool pool = new PojoEntityPool(this);
//pool.create();
worldPools.add(pool);
worldManager.addWorldPool(worldInfoEntry.getValue(), pool);
}
}
@Override
public EntityRef createSectorEntity(long maxDelta) {
return createSectorEntity(maxDelta, maxDelta);
}
@Override
public EntityRef createSectorEntity(long unloadedMaxDelta, long loadedMaxDelta) {
EntityRef entity = sectorManager.create();
entity.setScope(SECTOR);
SectorSimulationComponent simulationComponent = entity.getComponent(SectorSimulationComponent.class);
simulationComponent.unloadedMaxDelta = unloadedMaxDelta;
simulationComponent.loadedMaxDelta = loadedMaxDelta;
entity.saveComponent(simulationComponent);
return entity;
}
@Override
public long createEntity() {
if (nextEntityId == NULL_ID) {
nextEntityId++;
}
loadedIds.add(nextEntityId);
return nextEntityId++;
}
@Override
public EntityRef create(Component... components) {
return getCurrentWorldPool().create(components);
}
@Override
public EntityRef create(Iterable<Component> components) {
return getCurrentWorldPool().create(components);
}
@Override
public EntityRef create(Iterable<Component> components, boolean sendLifecycleEvents) {
return getCurrentWorldPool().create(components, sendLifecycleEvents);
}
@Override
public EntityRef create(String prefabName) {
return getCurrentWorldPool().create(prefabName);
}
@Override
public EntityRef create(Prefab prefab, Vector3fc position, Quaternionfc rotation) {
return getCurrentWorldPool().create(prefab, position, rotation);
}
@Override
public EntityRef create(Prefab prefab, Vector3fc position) {
return getCurrentWorldPool().create(prefab, position);
}
@Override
public EntityRef create(String prefab, Vector3fc position) {
return getCurrentWorldPool().create(prefab, position);
}
@Override
public EntityRef create(Prefab prefab) {
return getCurrentWorldPool().create(prefab);
}
@Override
//Todo: Depreciated, maybe remove? Not many uses
public EntityRef copy(EntityRef other) {
if (!other.exists()) {
return EntityRef.NULL;
}
List<Component> newEntityComponents = Lists.newArrayList();
for (Component c : other.iterateComponents()) {
newEntityComponents.add(componentLibrary.copy(c));
}
return getCurrentWorldPool().create(newEntityComponents);
}
@Override
public Map<Class<? extends Component>, Component> copyComponents(EntityRef other) {
Map<Class<? extends Component>, Component> result = Maps.newHashMap();
for (Component c : other.iterateComponents()) {
result.put(c.getClass(), componentLibrary.copyWithOwnedEntities(c));
}
return result;
}
@Override
public Iterable<EntityRef> getAllEntities() {
if (isWorldPoolGlobalPool()) {
return Iterables.concat(globalPool.getAllEntities(), sectorManager.getAllEntities());
}
return Iterables.concat(globalPool.getAllEntities(), getCurrentWorldPool().getAllEntities(), sectorManager.getAllEntities());
}
@SafeVarargs
@Override
public final Iterable<EntityRef> getEntitiesWith(Class<? extends Component>... componentClasses) {
if (isWorldPoolGlobalPool()) {
return Iterables.concat(globalPool.getEntitiesWith(componentClasses),
sectorManager.getEntitiesWith(componentClasses));
}
return Iterables.concat(globalPool.getEntitiesWith(componentClasses),
getCurrentWorldPool().getEntitiesWith(componentClasses), sectorManager.getEntitiesWith(componentClasses));
}
@Override
public int getActiveEntityCount() {
if (isWorldPoolGlobalPool()) {
return globalPool.getActiveEntityCount() + sectorManager.getActiveEntityCount();
}
return globalPool.getActiveEntityCount() + getCurrentWorldPool().getActiveEntityCount()
+ sectorManager.getActiveEntityCount();
}
@Override
public ComponentLibrary getComponentLibrary() {
return componentLibrary;
}
public void setComponentLibrary(ComponentLibrary componentLibrary) {
this.componentLibrary = componentLibrary;
}
@Override
public EventSystem getEventSystem() {
return eventSystem;
}
@Override
public void setEventSystem(EventSystem eventSystem) {
this.eventSystem = eventSystem;
}
@Override
public PrefabManager getPrefabManager() {
return prefabManager;
}
public void setPrefabManager(PrefabManager prefabManager) {
this.prefabManager = prefabManager;
}
/*
* Engine features
*/
@Override
public EntityRef getEntity(long id) {
return getPool(id)
.map(pool -> pool.getEntity(id))
.orElse(EntityRef.NULL);
}
@Override
public List<EngineEntityPool> getWorldPools() {
return worldPools;
}
@Override
public Map<WorldInfo, EngineEntityPool> getWorldPoolsMap() {
return worldManager.getWorldPoolMap();
}
@Override
public Map<Long, EngineEntityPool> getPoolMap() {
return poolMap;
}
@Override
public Map<EngineEntityPool, Long> getPoolCounts() {
return poolCounts;
}
/**
* Creates the entity without sending any events. The entity life cycle subscriber will however be informed.
*/
@Override
public EntityRef createEntityWithoutLifecycleEvents(Iterable<Component> components) {
return getCurrentWorldPool().createEntityWithoutLifecycleEvents(components);
}
/**
* Creates the entity without sending any events. The entity life cycle subscriber will however be informed.
*/
@Override
public EntityRef createEntityWithoutLifecycleEvents(String prefabName) {
return getCurrentWorldPool().createEntityWithoutLifecycleEvents(prefabName);
}
/**
* Creates the entity without sending any events. The entity life cycle subscriber will however be informed.
*/
@Override
public EntityRef createEntityWithoutLifecycleEvents(Prefab prefab) {
return getCurrentWorldPool().createEntityWithoutLifecycleEvents(prefab);
}
@Override
public void putEntity(long entityId, BaseEntityRef ref) {
getCurrentWorldPool().putEntity(entityId, ref);
}
@Override
public ComponentTable getComponentStore() {
return getCurrentWorldPool().getComponentStore();
}
@Override
public void destroyEntityWithoutEvents(EntityRef entity) {
getCurrentWorldPool().destroyEntityWithoutEvents(entity);
}
@Override
public EntityRef createEntityWithId(long id, Iterable<Component> components) {
EntityBuilder builder = newBuilder();
builder.setId(id);
builder.addComponents(components);
return builder.build();
}
@Override
public void subscribeForChanges(EntityChangeSubscriber subscriber) {
subscribers.add(subscriber);
}
@Override
public void subscribeForDestruction(EntityDestroySubscriber subscriber) {
destroySubscribers.add(subscriber);
}
@Override
public void unsubscribe(EntityChangeSubscriber subscriber) {
subscribers.remove(subscriber);
}
@Override
public TypeHandlerLibrary getTypeSerializerLibrary() {
return typeSerializerLibrary;
}
public void setTypeSerializerLibrary(TypeHandlerLibrary serializerLibrary) {
this.typeSerializerLibrary = serializerLibrary;
}
@Override
public EngineSectorManager getSectorManager() {
return sectorManager;
}
@Override
public void deactivateForStorage(EntityRef entity) {
if (!entity.exists()) {
return;
}
long entityId = entity.getId();
if (eventSystem != null) {
eventSystem.send(entity, BeforeDeactivateComponent.newInstance());
}
List<Component> components = Collections.unmodifiableList(
getPool(entityId)
.map(pool -> pool.getComponentStore().getComponentsInNewList(entityId))
.orElse(Collections.emptyList()));
notifyBeforeDeactivation(entity, components);
for (Component component : components) {
getPool(entityId).ifPresent(pool -> pool.getComponentStore().remove(entityId, component.getClass()));
}
loadedIds.remove(entityId);
}
@Override
public long getNextId() {
return nextEntityId;
}
@Override
public void setNextId(long id) {
nextEntityId = id;
}
/*
* For use by Entity Refs
*/
/**
* @param entityId
* @param componentClass
* @return Whether the entity has a component of the given type
*/
@Override
public boolean hasComponent(long entityId, Class<? extends Component> componentClass) {
return globalPool.getComponentStore().get(entityId, componentClass) != null
|| getCurrentWorldPool().getComponentStore().get(entityId, componentClass) != null
|| sectorManager.hasComponent(entityId, componentClass);
}
@Override
public boolean isExistingEntity(long id) {
return nextEntityId > id;
}
/**
* @param id
* @return Whether the entity is currently active
*/
@Override
public boolean isActiveEntity(long id) {
return loadedIds.contains(id);
}
/**
* @param entityId
* @return An iterable over the components of the given entity
*/
@Override
public Iterable<Component> iterateComponents(long entityId) {
return getPool(entityId)
.map(pool -> pool.getComponentStore().iterateComponents(entityId))
.orElse(Collections.emptyList());
}
@Override
public void destroy(long entityId) {
getPool(entityId).ifPresent(pool -> pool.destroy(entityId));
}
protected void notifyComponentRemovalAndEntityDestruction(long entityId, EntityRef ref) {
getPool(entityId)
.map(pool -> pool.getComponentStore().iterateComponents(entityId))
.orElse(Collections.emptyList())
.forEach(comp -> notifyComponentRemoved(ref, comp.getClass()));
for (EntityDestroySubscriber destroySubscriber : destroySubscribers) {
destroySubscriber.onEntityDestroyed(ref);
}
}
/**
* @param entityId
* @param componentClass
* @param <T>
* @return The component of that type owned by the given entity, or null if it doesn't have that component
*/
@Override
public <T extends Component> T getComponent(long entityId, Class<T> componentClass) {
return getPool(entityId)
.map(pool -> pool.getComponentStore().get(entityId, componentClass))
.orElse(null);
}
/**
* Adds (or replaces) a component to an entity
*
* @param entityId
* @param component
* @param <T>
* @return The added component
*/
@Override
public <T extends Component> T addComponent(long entityId, T component) {
Preconditions.checkNotNull(component);
Optional<Component> oldComponent = getPool(entityId).map(pool -> pool.getComponentStore().put(entityId, component));
// notify internal users first to get the unobstructed views on the entity as it is at this moment.
if (!oldComponent.isPresent()) {
notifyComponentAdded(getEntity(entityId), component.getClass());
} else {
logger.error("Adding a component ({}) over an existing component for entity {}", component.getClass(), entityId);
notifyComponentChanged(getEntity(entityId), component.getClass());
}
// Send life cycle events for arbitrary systems to react on.
// Note: systems are free to remove the component that was just added, which might cause some trouble here...
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);
if (!oldComponent.isPresent()) {
eventSystem.send(entityRef, OnAddedComponent.newInstance(), component);
eventSystem.send(entityRef, OnActivatedComponent.newInstance(), component);
} else {
eventSystem.send(entityRef, OnChangedComponent.newInstance(), component);
}
}
return component;
}
/**
* Removes a component from an entity
*
* @param entityId
* @param componentClass
*/
@Override
public <T extends Component> T removeComponent(long entityId, Class<T> componentClass) {
Optional<ComponentTable> maybeStore = getPool(entityId).map(EngineEntityPool::getComponentStore);
Optional<T> component = maybeStore.map(store -> store.get(entityId, componentClass));
if (component.isPresent()) {
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);
eventSystem.send(entityRef, BeforeDeactivateComponent.newInstance(), component.get());
eventSystem.send(entityRef, BeforeRemoveComponent.newInstance(), component.get());
}
notifyComponentRemoved(getEntity(entityId), componentClass);
maybeStore.ifPresent(store -> store.remove(entityId, componentClass));
}
return component.orElse(null);
}
/**
* Saves a component to an entity
*
* @param entityId
* @param component
*/
@Override
public void saveComponent(long entityId, Component component) {
Optional<Component> oldComponent = getPool(entityId)
.map(pool -> pool.getComponentStore().put(entityId, component));
if (!oldComponent.isPresent()) {
logger.error("Saving a component ({}) that doesn't belong to this entity {}", component.getClass(), entityId);
}
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);
if (!oldComponent.isPresent()) {
eventSystem.send(entityRef, OnAddedComponent.newInstance(), component);
eventSystem.send(entityRef, OnActivatedComponent.newInstance(), component);
} else {
eventSystem.send(entityRef, OnChangedComponent.newInstance(), component);
}
}
if (!oldComponent.isPresent()) {
notifyComponentAdded(getEntity(entityId), component.getClass());
} else {
notifyComponentChanged(getEntity(entityId), component.getClass());
}
}
/*
* Implementation
*/
public Optional<EngineEntityPool> getPool(long id) {
Optional<EngineEntityPool> pool = Optional.ofNullable(poolMap.get(id));
if (!pool.isPresent()) {
if (id != NULL_ID) {
// TODO: Entity pools assignment is not needed as of now, can be enabled later on when necessary.
if (!isExistingEntity(id)) {
logger.error("Entity {} doesn't exist", id);
}
}
}
return pool;
}
/**
* Assign the given entity to the given pool.
* <p>
* If the entity is already assigned to a pool, it will be re-assigned to the given pool.
* This does not actually move the entity or any of its components.
* If you want to move an entity to a different pool, {@link #moveToPool(long, EngineEntityPool)} should be used
* instead.
*
* @param entityId the id of the entity to assign
* @param pool the pool to assign the entity to
*/
@Override
public void assignToPool(long entityId, EngineEntityPool pool) {
if (poolMap.get(entityId) != pool) {
poolMap.put(entityId, pool);
if (!poolCounts.containsKey(pool)) {
poolCounts.put(pool, 1L);
} else {
poolCounts.put(pool, poolCounts.get(pool) + 1L);
}
}
}
/**
* Remove the assignment of an entity to a pool.
* <p>
* This does not affect anything else related to the entity, but may lead to the entity or its components being
* unable to be found.
* <p>
* When using this method, be sure to properly re-assign the entity to its correct pool afterwards.
*
* @param id the id of the entity to remove the assignment for
*/
protected void unassignPool(long id) {
poolMap.remove(id);
}
@Override
public boolean moveToPool(long id, EngineEntityPool pool) {
if (getPool(id).isPresent() && getPool(id).get().equals(pool)) {
//The entity is already in the correct pool
return true;
}
//Save the current entity and components
Optional<EngineEntityPool> maybePool = getPool(id);
EngineEntityPool oldPool;
if (!maybePool.isPresent()) {
return false;
} else {
oldPool = maybePool.get();
}
Map<Class<? extends Component>, Component> savedComponents = copyComponents(oldPool.getEntity(id));
//Remove from the existing pool
Optional<BaseEntityRef> maybeRef = oldPool.remove(id);
//Decrease the count of entities in that pool
poolCounts.put(oldPool, poolCounts.get(oldPool) - 1);
if (!maybeRef.isPresent()) {
return false;
}
BaseEntityRef ref = maybeRef.get();
//Create in new pool
pool.insertRef(ref, savedComponents.values());
//TODO: send<SUF>
return true;
}
@Override
public void notifyComponentAdded(EntityRef changedEntity, Class<? extends Component> component) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onEntityComponentAdded(changedEntity, component);
}
}
protected void notifyComponentRemoved(EntityRef changedEntity, Class<? extends Component> component) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onEntityComponentRemoved(changedEntity, component);
}
}
protected void notifyComponentChanged(EntityRef changedEntity, Class<? extends Component> component) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onEntityComponentChange(changedEntity, component);
}
}
/**
* This method gets called when the entity gets reactivated. e.g. after storage an entity needs to be reactivated.
*/
private void notifyReactivation(EntityRef entity, Collection<Component> components) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onReactivation(entity, components);
}
}
/**
* This method gets called before an entity gets deactivated (e.g. for storage).
*/
private void notifyBeforeDeactivation(EntityRef entity, Collection<Component> components) {
for (EntityChangeSubscriber subscriber : subscribers) {
subscriber.onBeforeDeactivation(entity, components);
}
}
@Override
@SafeVarargs
public final int getCountOfEntitiesWith(Class<? extends Component>... componentClasses) {
if (isWorldPoolGlobalPool()) {
return globalPool.getCountOfEntitiesWith(componentClasses) +
sectorManager.getCountOfEntitiesWith(componentClasses);
}
return sectorManager.getCountOfEntitiesWith(componentClasses) +
getCurrentWorldPool().getCountOfEntitiesWith(componentClasses) +
globalPool.getCountOfEntitiesWith(componentClasses);
}
public <T extends Component> Iterable<Map.Entry<EntityRef, T>> listComponents(Class<T> componentClass) {
List<TLongObjectIterator<T>> iterators = new ArrayList<>();
if (isWorldPoolGlobalPool()) {
iterators.add(globalPool.getComponentStore().componentIterator(componentClass));
} else {
iterators.add(globalPool.getComponentStore().componentIterator(componentClass));
iterators.add(getCurrentWorldPool().getComponentStore().componentIterator(componentClass));
}
iterators.add(sectorManager.getComponentStore().componentIterator(componentClass));
List<Map.Entry<EntityRef, T>> list = new ArrayList<>();
for (TLongObjectIterator<T> iterator : iterators) {
if (iterator != null) {
while (iterator.hasNext()) {
iterator.advance();
list.add(new EntityEntry<>(getEntity(iterator.key()), iterator.value()));
}
}
}
return list;
}
@Override
public boolean registerId(long entityId) {
if (entityId >= nextEntityId) {
logger.error("Prevented attempt to create entity with an invalid id.");
return false;
}
loadedIds.add(entityId);
return true;
}
protected boolean idLoaded(long entityId) {
return loadedIds.contains(entityId);
}
@Override
public Optional<BaseEntityRef> remove(long id) {
return getPool(id)
.flatMap(pool -> pool.remove(id));
}
@Override
public void insertRef(BaseEntityRef ref, Iterable<Component> components) {
globalPool.insertRef(ref, components);
}
@Override
public boolean contains(long id) {
return globalPool.contains(id) || sectorManager.contains(id);
}
/**
* Remove this id from the entity manager's list of loaded ids.
*
* @param id the id to remove
*/
protected void unregister(long id) {
loadedIds.remove(id);
}
private static class EntityEntry<T> implements Map.Entry<EntityRef, T> {
private EntityRef key;
private T value;
EntityEntry(EntityRef ref, T value) {
this.key = ref;
this.value = value;
}
@Override
public EntityRef getKey() {
return key;
}
@Override
public T getValue() {
return value;
}
@Override
public T setValue(T newValue) {
throw new UnsupportedOperationException();
}
}
}
|
136852_11 | /*
* Copyright 2003-2004 The Apache Software Foundation
*
* 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 org.apache.commons.collections.set;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.collection.CompositeCollection;
/**
* Decorates a set of other sets to provide a single unified view.
* <p>
* Changes made to this set will actually be made on the decorated set.
* Add and remove operations require the use of a pluggable strategy. If no
* strategy is provided then add and remove are unsupported.
*
* @since Commons Collections 3.0
* @version $Revision: 1.3 $ $Date: 2004/02/18 01:14:27 $
*
* @author Brian McCallister
*/
public class CompositeSet extends CompositeCollection implements Set {
/**
* Create an empty CompositeSet
*/
public CompositeSet() {
super();
}
/**
* Create a CompositeSet with just <code>set</code> composited
* @param set The initial set in the composite
*/
public CompositeSet(Set set) {
super(set);
}
/**
* Create a composite set with sets as the initial set of composited Sets
*/
public CompositeSet(Set[] sets) {
super(sets);
}
/**
* Add a Set to this composite
*
* @param c Must implement Set
* @throws IllegalArgumentException if c does not implement java.util.Set
* or if a SetMutator is set, but fails to resolve a collision
* @throws UnsupportedOperationException if there is no SetMutator set, or
* a CollectionMutator is set instead of a SetMutator
* @see org.apache.commons.collections.collection.CompositeCollection.CollectionMutator
* @see SetMutator
*/
public synchronized void addComposited(Collection c) {
if (!(c instanceof Set)) {
throw new IllegalArgumentException("Collections added must implement java.util.Set");
}
for (Iterator i = this.getCollections().iterator(); i.hasNext();) {
Set set = (Set) i.next();
Collection intersects = CollectionUtils.intersection(set, c);
if (intersects.size() > 0) {
if (this.mutator == null) {
throw new UnsupportedOperationException(
"Collision adding composited collection with no SetMutator set");
}
else if (!(this.mutator instanceof SetMutator)) {
throw new UnsupportedOperationException(
"Collision adding composited collection to a CompositeSet with a CollectionMutator instead of a SetMutator");
}
((SetMutator) this.mutator).resolveCollision(this, set, (Set) c, intersects);
if (CollectionUtils.intersection(set, c).size() > 0) {
throw new IllegalArgumentException(
"Attempt to add illegal entry unresolved by SetMutator.resolveCollision()");
}
}
}
super.addComposited(new Collection[]{c});
}
/**
* Add two sets to this composite
*
* @throws IllegalArgumentException if c or d does not implement java.util.Set
*/
public synchronized void addComposited(Collection c, Collection d) {
if (!(c instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set");
if (!(d instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set");
this.addComposited(new Set[]{(Set) c, (Set) d});
}
/**
* Add an array of sets to this composite
* @param comps
* @throws IllegalArgumentException if any of the collections in comps do not implement Set
*/
public synchronized void addComposited(Collection[] comps) {
for (int i = comps.length - 1; i >= 0; --i) {
this.addComposited(comps[i]);
}
}
/**
* This can receive either a <code>CompositeCollection.CollectionMutator</code>
* or a <code>CompositeSet.SetMutator</code>. If a
* <code>CompositeCollection.CollectionMutator</code> is used than conflicts when adding
* composited sets will throw IllegalArgumentException
* <p>
*/
public void setMutator(CollectionMutator mutator) {
super.setMutator(mutator);
}
/* Set operations */
/**
* If a <code>CollectionMutator</code> is defined for this CompositeSet then this
* method will be called anyway.
*
* @param obj Object to be removed
* @return true if the object is removed, false otherwise
*/
public boolean remove(Object obj) {
for (Iterator i = this.getCollections().iterator(); i.hasNext();) {
Set set = (Set) i.next();
if (set.contains(obj)) return set.remove(obj);
}
return false;
}
/**
* @see Set#equals
*/
public boolean equals(Object obj) {
if (obj instanceof Set) {
Set set = (Set) obj;
if (set.containsAll(this) && set.size() == this.size()) {
return true;
}
}
return false;
}
/**
* @see Set#hashCode
*/
public int hashCode() {
int code = 0;
for (Iterator i = this.iterator(); i.hasNext();) {
Object next = i.next();
code += (next != null ? next.hashCode() : 0);
}
return code;
}
/**
* Define callbacks for mutation operations.
* <p>
* Defining remove() on implementations of SetMutator is pointless
* as they are never called by CompositeSet.
*/
public static interface SetMutator extends CompositeCollection.CollectionMutator {
/**
* <p>
* Called when a Set is added to the CompositeSet and there is a
* collision between existing and added sets.
* </p>
* <p>
* If <code>added</code> and <code>existing</code> still have any intersects
* after this method returns an IllegalArgumentException will be thrown.
* </p>
* @param comp The CompositeSet being modified
* @param existing The Set already existing in the composite
* @param added the Set being added to the composite
* @param intersects the intersection of th existing and added sets
*/
public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects);
}
}
| Mr-xn/Penetration_Testing_POC | jboss_CVE-2017-12149/src/org/apache/commons/collections/set/CompositeSet.java | 2,000 | /**
* @see Set#hashCode
*/ | block_comment | nl | /*
* Copyright 2003-2004 The Apache Software Foundation
*
* 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 org.apache.commons.collections.set;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.collection.CompositeCollection;
/**
* Decorates a set of other sets to provide a single unified view.
* <p>
* Changes made to this set will actually be made on the decorated set.
* Add and remove operations require the use of a pluggable strategy. If no
* strategy is provided then add and remove are unsupported.
*
* @since Commons Collections 3.0
* @version $Revision: 1.3 $ $Date: 2004/02/18 01:14:27 $
*
* @author Brian McCallister
*/
public class CompositeSet extends CompositeCollection implements Set {
/**
* Create an empty CompositeSet
*/
public CompositeSet() {
super();
}
/**
* Create a CompositeSet with just <code>set</code> composited
* @param set The initial set in the composite
*/
public CompositeSet(Set set) {
super(set);
}
/**
* Create a composite set with sets as the initial set of composited Sets
*/
public CompositeSet(Set[] sets) {
super(sets);
}
/**
* Add a Set to this composite
*
* @param c Must implement Set
* @throws IllegalArgumentException if c does not implement java.util.Set
* or if a SetMutator is set, but fails to resolve a collision
* @throws UnsupportedOperationException if there is no SetMutator set, or
* a CollectionMutator is set instead of a SetMutator
* @see org.apache.commons.collections.collection.CompositeCollection.CollectionMutator
* @see SetMutator
*/
public synchronized void addComposited(Collection c) {
if (!(c instanceof Set)) {
throw new IllegalArgumentException("Collections added must implement java.util.Set");
}
for (Iterator i = this.getCollections().iterator(); i.hasNext();) {
Set set = (Set) i.next();
Collection intersects = CollectionUtils.intersection(set, c);
if (intersects.size() > 0) {
if (this.mutator == null) {
throw new UnsupportedOperationException(
"Collision adding composited collection with no SetMutator set");
}
else if (!(this.mutator instanceof SetMutator)) {
throw new UnsupportedOperationException(
"Collision adding composited collection to a CompositeSet with a CollectionMutator instead of a SetMutator");
}
((SetMutator) this.mutator).resolveCollision(this, set, (Set) c, intersects);
if (CollectionUtils.intersection(set, c).size() > 0) {
throw new IllegalArgumentException(
"Attempt to add illegal entry unresolved by SetMutator.resolveCollision()");
}
}
}
super.addComposited(new Collection[]{c});
}
/**
* Add two sets to this composite
*
* @throws IllegalArgumentException if c or d does not implement java.util.Set
*/
public synchronized void addComposited(Collection c, Collection d) {
if (!(c instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set");
if (!(d instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set");
this.addComposited(new Set[]{(Set) c, (Set) d});
}
/**
* Add an array of sets to this composite
* @param comps
* @throws IllegalArgumentException if any of the collections in comps do not implement Set
*/
public synchronized void addComposited(Collection[] comps) {
for (int i = comps.length - 1; i >= 0; --i) {
this.addComposited(comps[i]);
}
}
/**
* This can receive either a <code>CompositeCollection.CollectionMutator</code>
* or a <code>CompositeSet.SetMutator</code>. If a
* <code>CompositeCollection.CollectionMutator</code> is used than conflicts when adding
* composited sets will throw IllegalArgumentException
* <p>
*/
public void setMutator(CollectionMutator mutator) {
super.setMutator(mutator);
}
/* Set operations */
/**
* If a <code>CollectionMutator</code> is defined for this CompositeSet then this
* method will be called anyway.
*
* @param obj Object to be removed
* @return true if the object is removed, false otherwise
*/
public boolean remove(Object obj) {
for (Iterator i = this.getCollections().iterator(); i.hasNext();) {
Set set = (Set) i.next();
if (set.contains(obj)) return set.remove(obj);
}
return false;
}
/**
* @see Set#equals
*/
public boolean equals(Object obj) {
if (obj instanceof Set) {
Set set = (Set) obj;
if (set.containsAll(this) && set.size() == this.size()) {
return true;
}
}
return false;
}
/**
* @see Set#hashCode
<SUF>*/
public int hashCode() {
int code = 0;
for (Iterator i = this.iterator(); i.hasNext();) {
Object next = i.next();
code += (next != null ? next.hashCode() : 0);
}
return code;
}
/**
* Define callbacks for mutation operations.
* <p>
* Defining remove() on implementations of SetMutator is pointless
* as they are never called by CompositeSet.
*/
public static interface SetMutator extends CompositeCollection.CollectionMutator {
/**
* <p>
* Called when a Set is added to the CompositeSet and there is a
* collision between existing and added sets.
* </p>
* <p>
* If <code>added</code> and <code>existing</code> still have any intersects
* after this method returns an IllegalArgumentException will be thrown.
* </p>
* @param comp The CompositeSet being modified
* @param existing The Set already existing in the composite
* @param added the Set being added to the composite
* @param intersects the intersection of th existing and added sets
*/
public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects);
}
}
|
98135_2 | package BTClib3001;
import java.util.Arrays;
/****************************************************************************************************************
* Version 1.0 Autor: Mr. Maxwell vom 22.02.2023 *
* HMAC SHA256 *
* Es wird ein HMAC mit SHA256 berechnet: "https://de.wikipedia.org/wiki/HMAC" *
* Statische Klasse die nur eine statische Methode hat. *
* Es gibt nur eine Abhängigkeit zur SHA256 Hash Klasse *
* Getestet durch Referenzimplementierung von "javax.crypto.Mac;" mit 10000000 rand. Vektoren, rand. Längen. *
****************************************************************************************************************/
public class HMAC
{
/** HMAC Funktion die SHA256 verwendet **/
public static byte[] getHMAC_SHA256(byte[] data, byte[] key) throws Exception
{
byte[] k;
if(key.length>64) k = Arrays.copyOf(SHA256.getHash(key),64);
else k = Arrays.copyOf(key, 64);
byte[] opad = new byte[64];
byte[] ipad = new byte[64];
for(int i=0; i<64;i++) opad[i]=0x5c;
for(int i=0; i<64;i++) ipad[i]=0x36;
byte[] b = SHA256.getHash(add(xor(k,ipad), data));
byte[] out = SHA256.getHash(add(xor(k,opad), b));
return out;
}
// ------------------------------------------------- private Methoden -------------------------------------------
// verbindet die beiden Arrays hintereinander
private static byte[] add(byte[] a, byte[] b)
{
byte[] out = new byte[a.length + b.length];
System.arraycopy(a, 0, out, 0, a.length);
System.arraycopy(b, 0, out, a.length, b.length);
return out;
}
// XOR von a und b. a unb b müssen gleich lang sein!
private static byte[] xor(byte[] a, byte[] b) throws Exception
{
if(a.length != b.length) throw new Exception("a and b are not the same length");
byte[] out = new byte[a.length];
for(int i=0;i<a.length;i++)
{
out[i] = (byte) (a[i] ^ b[i]);
}
return out;
}
} | MrMaxweII/Bitcoin-Address-Generator | src/BTClib3001/HMAC.java | 756 | // ------------------------------------------------- private Methoden -------------------------------------------
| line_comment | nl | package BTClib3001;
import java.util.Arrays;
/****************************************************************************************************************
* Version 1.0 Autor: Mr. Maxwell vom 22.02.2023 *
* HMAC SHA256 *
* Es wird ein HMAC mit SHA256 berechnet: "https://de.wikipedia.org/wiki/HMAC" *
* Statische Klasse die nur eine statische Methode hat. *
* Es gibt nur eine Abhängigkeit zur SHA256 Hash Klasse *
* Getestet durch Referenzimplementierung von "javax.crypto.Mac;" mit 10000000 rand. Vektoren, rand. Längen. *
****************************************************************************************************************/
public class HMAC
{
/** HMAC Funktion die SHA256 verwendet **/
public static byte[] getHMAC_SHA256(byte[] data, byte[] key) throws Exception
{
byte[] k;
if(key.length>64) k = Arrays.copyOf(SHA256.getHash(key),64);
else k = Arrays.copyOf(key, 64);
byte[] opad = new byte[64];
byte[] ipad = new byte[64];
for(int i=0; i<64;i++) opad[i]=0x5c;
for(int i=0; i<64;i++) ipad[i]=0x36;
byte[] b = SHA256.getHash(add(xor(k,ipad), data));
byte[] out = SHA256.getHash(add(xor(k,opad), b));
return out;
}
// ------------------------------------------------- private<SUF>
// verbindet die beiden Arrays hintereinander
private static byte[] add(byte[] a, byte[] b)
{
byte[] out = new byte[a.length + b.length];
System.arraycopy(a, 0, out, 0, a.length);
System.arraycopy(b, 0, out, a.length, b.length);
return out;
}
// XOR von a und b. a unb b müssen gleich lang sein!
private static byte[] xor(byte[] a, byte[] b) throws Exception
{
if(a.length != b.length) throw new Exception("a and b are not the same length");
byte[] out = new byte[a.length];
for(int i=0;i<a.length;i++)
{
out[i] = (byte) (a[i] ^ b[i]);
}
return out;
}
} |
31806_4 |
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.math.BigInteger;
import javax.swing.JComponent;
/************************************************************************
* *
* Kleiner Secp256k1 Calculatur für Testzwecke *
* Hier werden alle Berechnungen durchgeführt *
* *
************************************************************************/
public class Calculator
{
private static int color = 0; // Farbe der doppelten Elemente
private static Color[] txt_color = new Color[19]; // Zugeordnete Hintergrundfarbe jeden Textfeldes
public static boolean run_findEquals = true; // Zum Beenden des Thread´s "FindEquals"
public static boolean run_calc = false; // Verhindert das doppelte starten von Calc.
// Hier wird die richtige Rechenoperation anhand der ausgweählten Eingabefelder bestimmt
// Die Informations-Meldungen werden entspechend auf der GUI platziert
// Rückgabe ist Integer was wie folgt identifiziert wird:
// 0 = ungültige Operation
// 1 = scalare Addition ( 2 Zahlen werden normal addiert)
// 2 = scalare Subtraktion ( 2 Zahlen werden normal Subrahier)
// 3 = scalare Multiplikation ( 2 Zahlen werden normal Multipliziert)
// 4 = scalare Division ( 2 Zahlen werden normal Dividiert)
// 5 = Addition auf der elliptischen Kurve ( Vektor + Vektor)
// 6 = Subtraktion auf der elliptischen Kurve ( Vektor - Vektor)
// 7 = Multiplikation auf der elliptischen Kurve ( Skalar * Vektor)
// 8 = Divison auf der elliptischen Kurve ( Vektor / Skalar)
public static int parseOP()
{
int a = GUI.comboBox_1.getSelectedIndex();
int b = GUI.comboBox_2.getSelectedIndex();
int op = GUI.comboBox_op.getSelectedIndex();
GUI.lbl_op.setForeground(new Color(100, 149, 237));
GUI.txt_opBeschreibung.setForeground(new Color(100, 149, 237));
GUI.txt[4].setVisible(true);
GUI.btn_calc.setEnabled(true);
GUI.txt_opBeschreibung.setText("");
String a_txt = (String) GUI.comboBox_1.getSelectedItem();
String b_txt = (String) GUI.comboBox_2.getSelectedItem();
String op_txt="";
if(op==0) op_txt = "addition";
if(op==1) op_txt = "subtraction";
if(op==2) op_txt = "multiplication";
if(op==3) op_txt = "division";
if(op==4) op_txt = "signature";
if(op==5) op_txt = "verify";
String txt_0 = " The "+op_txt+" of a "+a_txt+" with a "+b_txt+"\n is not possible!\n\n Adjust the input fields\n for the "+op_txt+" correctly";
String txt_1 = " scalar "+op_txt+"\n\n "+op_txt+" of a number with a number modulo n\n f(x) = (A "+GUI.comboBox_op.getSelectedItem()+" B)mod(n)";
String txt_2 = " elliptic curve "+op_txt+"\n\n "+op_txt+" of a "+a_txt+" with a "+b_txt+"\n on the elliptic curve Secp256k1\n f(x) = (A "+GUI.comboBox_op.getSelectedItem()+" B)";
String txt_3 = " ECDSA Signatur\n\n h = hash of the document to be signed\n k = random number\n B = the private key with which you want to sign \n G = generator point \n\n Signature r,s\n\n f(r) = k \u2022 G \n f(s) = (h + r \u2022 B)/k";
String txt_4 = " ECDSA verification\n\n h = hash of the document to be verified\n r,s = the signature\n B = the public key with which you want to verified \n G = generator point \n\n h/s \u2022 G + r/s \u2022 B = r(x)";
if(a==1 && b==1 && op==0) { GUI.lbl_op.setText("scalar addition"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 1;}
if(a==1 && b==1 && op==1) { GUI.lbl_op.setText("scalar subtraction"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 2;}
if(a==1 && b==1 && op==2) { GUI.lbl_op.setText("scalar multiplication");GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 3;}
if(a==1 && b==1 && op==3) { GUI.lbl_op.setText("scalar division"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 4;}
if(a==0 && b==0 && op==0) { GUI.lbl_op.setText("ECC addition"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 5;}
if(a==0 && b==0 && op==1) { GUI.lbl_op.setText("ECC subtraktion"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 6;}
if(a==1 && b==0 && op==2) { GUI.lbl_op.setText("ECC multiplication"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 7;}
if(a==0 && b==1 && op==2) { GUI.lbl_op.setText("ECC multiplikation"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 7;}
if(a==0 && b==1 && op==3) { GUI.lbl_op.setText("ECC division"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 8;}
if(a==0 && b==1 && op==4) { GUI.lbl_op.setText("signature"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_3); return 9;}
if(a==0 && b==0 && op==5) { GUI.lbl_op.setText("verify"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_4); return 10;}
GUI.lbl_op.setText("No possible operation!");
{
GUI.lbl_op.setForeground(Color.RED); GUI.btn_calc.setEnabled(false);
GUI.txt_opBeschreibung.setText(txt_0);
GUI.txt_opBeschreibung.setForeground(Color.red);
return 0;
}
}
// subtrahiert a-b
private static BigInteger sub(BigInteger a, BigInteger b)
{
return a.add(Secp256k1.ORDNUNG.subtract(b)).mod(Secp256k1.ORDNUNG);
}
// dividiert a / b
public static BigInteger div(BigInteger a, BigInteger b)
{
return a.multiply(b.modInverse(Secp256k1.ORDNUNG)).mod(Secp256k1.ORDNUNG);
}
// Hauptmethode die bei Betätigung des "=" Symbols, die Berechnung ausführt.
public static void calc() throws Exception
{
if(run_calc==true) return;
else run_calc = true;
int op = parseOP();
BigInteger[] po1 = new BigInteger[2];
BigInteger[] po2 = new BigInteger[2];
switch(op)
{
case 1: GUI.txt[4].setText( new BigInteger(GUI.txt[0].getText(),16).add (new BigInteger(GUI.txt[2].getText(),16)).mod(Secp256k1.ORDNUNG).toString(16)); break;
case 2: GUI.txt[4].setText(sub( new BigInteger(GUI.txt[0].getText(),16), new BigInteger(GUI.txt[2].getText(),16)).toString(16)); break;
case 3: GUI.txt[4].setText( new BigInteger(GUI.txt[0].getText(),16).multiply(new BigInteger(GUI.txt[2].getText(),16)).mod(Secp256k1.ORDNUNG).toString(16)); break;
case 4: GUI.txt[4].setText(div( new BigInteger(GUI.txt[0].getText(),16), new BigInteger(GUI.txt[2].getText(),16)).toString(16)); break;
case 5: // Addition elliptic curve
{
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
po2[0] = new BigInteger(GUI.txt[2].getText(),16);
po2[1] = new BigInteger(GUI.txt[3].getText(),16);
BigInteger[] erg = Secp256k1.addition(po1, po2);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 6: // Suptraktion elliptic curve
{
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
po2[0] = new BigInteger(GUI.txt[2].getText(),16);
po2[1] = new BigInteger(GUI.txt[3].getText(),16);
BigInteger[] erg = Secp256k1.subtraktion(po1, po2);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 7: // Multiplikation elliptic curve
{
BigInteger fac;
if(GUI.comboBox_1.getSelectedIndex()==1)
{
fac = new BigInteger(GUI.txt[0].getText(),16);
po1[0] = new BigInteger(GUI.txt[2].getText(),16);
po1[1] = new BigInteger(GUI.txt[3].getText(),16);
}
else
{
fac = new BigInteger(GUI.txt[2].getText(),16);
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
}
BigInteger[] erg = Secp256k1.multiply_Point(po1, fac);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 8: // Division elliptic curve
{
BigInteger div = new BigInteger(GUI.txt[2].getText(),16);
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
BigInteger[] erg = Secp256k1.div(po1, div);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 9: // Signature
{
BigInteger h = new BigInteger(GUI.txt[0].getText(),16);
BigInteger k = new BigInteger(GUI.txt[1].getText(),16);
BigInteger prv = new BigInteger(GUI.txt[2].getText(),16);
Secp256k1 sec = new Secp256k1();
BigInteger[] erg = sec.sig(h.toByteArray(), prv.toByteArray(), k.toByteArray());
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 10: // Verify
{
BigInteger h = new BigInteger(GUI.txt[0].getText(),16);
po1[0] = new BigInteger(GUI.txt[1].getText(),16);
po1[1] = new BigInteger(GUI.txt[18].getText(),16);
po2[0] = new BigInteger(GUI.txt[2].getText(),16);
po2[1] = new BigInteger(GUI.txt[3].getText(),16);
Secp256k1 sec = new Secp256k1();
Boolean erg = sec.verify(h.toByteArray(), po1, po2);
GUI.txt[4].setText(erg.toString());
break;
}
default:
}
run_calc=false;
GUI.animation.close();
}
// Speichert den übergebenen Vektor im nächsten freien Merker
// Ist kein Merker mehr frei, wird nichts gespeichert
public static void saveToNextMerker(String a, String b)
{
for(int i=6;i<18;i=i+2)
{
if(isEmty(i)==true && isEmty(i+1)==true)
{
GUI.txt[i].setText(a);
GUI.txt[i+1].setText(b);
break;
}
}
}
// Speichert den Merker zurück in den Eingabebereich.
// nr = die Button Nummer die leider nur auf diesem Umständlichem Weg übergeben werden kann.
public static void saveFromMerkerTo(ActionEvent e)
{
int nr = (int) ((JComponent) e.getSource()).getClientProperty("int");
if(nr%2==0) // die Merker auf der linken Seite
{
if(GUI.comboBox_op.getSelectedIndex()!=5)
{
GUI.txt[0].setText(GUI.txt[nr+6].getText());
GUI.txt[1].setText(GUI.txt[nr+7].getText());
if(isEmty(nr+7)) GUI.comboBox_1.setSelectedIndex(1);
else GUI.comboBox_1.setSelectedIndex(0);
}
else // Bei Auswahl von Verify
{
GUI.txt[1].setText(GUI.txt[nr+6].getText());
GUI.txt[18].setText(GUI.txt[nr+7].getText());
}
}
else // die Merker auf der rechten Seite
{
GUI.txt[2].setText(GUI.txt[nr+5].getText());
GUI.txt[3].setText(GUI.txt[nr+6].getText());
if(isEmty(nr+6)) GUI.comboBox_2.setSelectedIndex(1);
else GUI.comboBox_2.setSelectedIndex(0);
}
}
// Prüft ob das Feld leer ist
private static boolean isEmty(int m)
{
if(GUI.txt[m].getText().equals("")) return true;
else return false;
}
// Startet einen eigenen Thread der zyklich alle eingabe Felder mit einander vergleicht
// und doppelte Elemente farblich markiert
// Die Hintergrundfarbe wird zwichengespeichert und erst am Ende auf das Textfeld geschrieben, damit es nicht zum Flackern kommt.
public static void findEquals()
{
Thread t = new Thread(new Runnable()
{
public void run()
{
while(run_findEquals)
{
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
color =0;
for(int i=0;i<19;i++) txt_color[i] = Color.white;
txt_color[4] = new Color(245, 245, 245);
txt_color[5] = new Color(245, 245, 245);
String[] text = new String[19];
for(int i=0;i<19;i++) {text[i] = GUI.txt[i].getText();}
for(int i=0;i<19;i++)
{
for(int j=0;j<19;j++)
{
if(text[i].equals(text[j]) && i!=j && text[i].equals("")==false)
{
txt_color[i] = nextColor();
txt_color[j] = nextColor();
}
}
color++;
}
for(int i=0;i<19;i++) {GUI.txt[i].setBackground(txt_color[i]);}
if(GUI.txt[0].getText().equals("color")) printAllColor();
}
System.out.println("Thread findEquals beendet");
}
});
t.start();
}
// Vergibt die nächste Farbe für die Hintergrundfarbe der gleichen Elemente
private static Color nextColor()
{
Color[] c = new Color[19];
c[3] = Color.decode("#fbeeee");
c[6] = Color.decode("#F8ECE0");
c[9] = Color.decode("#F7F8E0");
c[12] = Color.decode("#ECF8E0");
c[15] = Color.decode("#E0F8E0");
c[1] = Color.decode("#E0F2F7");
c[4] = Color.decode("#E0E6F8");
c[7] = Color.decode("#E6E0F8");
c[10] = Color.decode("#ffd6cc");
c[13] = Color.decode("#ebe0cc");
c[16] = Color.decode("#F8E0E6");
c[2] = Color.decode("#cce0ff");
c[5] = Color.decode("#F5A9A9");
c[8] = Color.decode("#F5D0A9");
c[11] = Color.decode("#F2F5A9");
c[14] = Color.decode("#D0F5A9");
c[17] = Color.decode("#A9F5A9");
c[0] = Color.decode("#A9F5D0");
c[18] = Color.decode("#ffcccc");
return c[color];
}
//Testmethode die bei der Eingabe von "color" im ersten Feld alle Farben anzeigt.
private static void printAllColor()
{
color = 0;
for(int i=0;i<19;i++)
{
GUI.txt[i].setBackground(nextColor());
color++;
}
}
// ------------------------------------------------------- Signature & Verify --------------------------------------------
// der Eingabebereich der GUI wird für die Berechnung der Sigantur angepasst
public static void setOP_Sig()
{
GUI.comboBox_op.setFont(new Font("Tahoma", Font.PLAIN, 18));
GUI.comboBox_1.setSelectedIndex(0);
GUI.comboBox_2.setSelectedIndex(1);
GUI.lbl_X.setText("h");
GUI.lbl_Y.setText("k");
GUI.lbl_Z.setVisible(false);
GUI.lbl_privKey.setVisible(true);
GUI.lbl_privKey.setText("Private Key");
GUI.lbl_privKey.setForeground(Color.RED);
GUI.btn_G1.setVisible(false);
GUI.btn_rand1.setVisible(true);
GUI.btn_m1.setBounds(300, 135, 50, 20);
GUI.btn_y1a.setVisible(false);
GUI.btn_y1b.setVisible(false);
GUI.lbl_r.setVisible(true);
GUI.lbl_s.setVisible(true);
GUI.txt[18].setVisible(false);
GUI.txt[18].setText("");
GUI.txt[1].setBounds(20, 110, 330, 20);
GUI.lbl_Y.setBounds(10, 113, 23, 14);
GUI.btn_m4.setVisible(false);
GUI.lbl_D.setVisible(false);
for(int i=0; i<12 ;i++) if(i%2==0) {GUI.btn_m[i].setText("<--A"); GUI.btn_m[i].setToolTipText("Save this memory field back to input A");}
}
// der Eingabebereich der GUI wird für die Berechnung der Verifikation angepasst
public static void setOP_ver()
{
GUI.comboBox_op.setFont(new Font("Tahoma", Font.PLAIN, 18));
GUI.comboBox_1.setSelectedIndex(0);
GUI.comboBox_2.setSelectedIndex(0);
GUI.lbl_X.setText("h");
GUI.lbl_Y.setText("r");
GUI.lbl_Z.setText("s");
GUI.lbl_Z.setVisible(true);
GUI.lbl_privKey.setVisible(true);
GUI.lbl_privKey.setText("Public Key");
GUI.lbl_privKey.setForeground(Color.blue);
GUI.btn_G1.setVisible(false);
GUI.btn_rand1.setVisible(false);
GUI.btn_m1.setBounds(300, 102, 49, 15);
GUI.btn_y1a.setVisible(false);
GUI.btn_y1b.setVisible(false);
GUI.lbl_r.setVisible(false);
GUI.lbl_s.setVisible(false);
GUI.txt[18].setVisible(true);
GUI.txt[1].setBounds(20, 130, 330, 20);
GUI.lbl_Y.setBounds(10, 133, 23, 14);
GUI.txt[1].setText("");
GUI.txt[2].setText("");
GUI.txt[3].setText("");
GUI.btn_m4.setVisible(true);
GUI.lbl_D.setVisible(true);
for(int i=0; i<12 ;i++) if(i%2==0) {GUI.btn_m[i].setText("<--D"); GUI.btn_m[i].setToolTipText("Save this memory field back to input D");}
}
// der Eingabebereich der GUI wird für die Berechnung zurück auf Calculator gesetzt
public static void setOP_calc()
{
GUI.comboBox_op.setFont(new Font("Tahoma", Font.PLAIN, 30));
GUI.lbl_X.setText("X");
GUI.lbl_Y.setText("Y");
GUI.lbl_privKey.setVisible(false);
GUI.btn_G1.setVisible(true);
GUI.btn_rand1.setVisible(true);
GUI.btn_m1.setBounds(300, 135, 50, 20);
GUI.btn_y1a.setVisible(true);
GUI.btn_y1b.setVisible(true);
GUI.lbl_r.setVisible(false);
GUI.lbl_s.setVisible(false);
GUI.txt[18].setVisible(false);
GUI.txt[18].setText("");
GUI.lbl_Z.setVisible(false);
GUI.txt[1].setBounds(20, 110, 330, 20);
GUI.lbl_Y.setBounds(10, 113, 23, 14);
GUI.btn_m4.setVisible(false);
GUI.lbl_D.setVisible(false);
for(int i=0; i<12 ;i++) if(i%2==0) {GUI.btn_m[i].setText("<--A"); GUI.btn_m[i].setToolTipText("Save this memory field back to input A");}
}
}
| MrMaxweII/Secp256k1-Calculator | Calculator.java | 6,965 | // Verhindert das doppelte starten von Calc.
| line_comment | nl |
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.math.BigInteger;
import javax.swing.JComponent;
/************************************************************************
* *
* Kleiner Secp256k1 Calculatur für Testzwecke *
* Hier werden alle Berechnungen durchgeführt *
* *
************************************************************************/
public class Calculator
{
private static int color = 0; // Farbe der doppelten Elemente
private static Color[] txt_color = new Color[19]; // Zugeordnete Hintergrundfarbe jeden Textfeldes
public static boolean run_findEquals = true; // Zum Beenden des Thread´s "FindEquals"
public static boolean run_calc = false; // Verhindert das<SUF>
// Hier wird die richtige Rechenoperation anhand der ausgweählten Eingabefelder bestimmt
// Die Informations-Meldungen werden entspechend auf der GUI platziert
// Rückgabe ist Integer was wie folgt identifiziert wird:
// 0 = ungültige Operation
// 1 = scalare Addition ( 2 Zahlen werden normal addiert)
// 2 = scalare Subtraktion ( 2 Zahlen werden normal Subrahier)
// 3 = scalare Multiplikation ( 2 Zahlen werden normal Multipliziert)
// 4 = scalare Division ( 2 Zahlen werden normal Dividiert)
// 5 = Addition auf der elliptischen Kurve ( Vektor + Vektor)
// 6 = Subtraktion auf der elliptischen Kurve ( Vektor - Vektor)
// 7 = Multiplikation auf der elliptischen Kurve ( Skalar * Vektor)
// 8 = Divison auf der elliptischen Kurve ( Vektor / Skalar)
public static int parseOP()
{
int a = GUI.comboBox_1.getSelectedIndex();
int b = GUI.comboBox_2.getSelectedIndex();
int op = GUI.comboBox_op.getSelectedIndex();
GUI.lbl_op.setForeground(new Color(100, 149, 237));
GUI.txt_opBeschreibung.setForeground(new Color(100, 149, 237));
GUI.txt[4].setVisible(true);
GUI.btn_calc.setEnabled(true);
GUI.txt_opBeschreibung.setText("");
String a_txt = (String) GUI.comboBox_1.getSelectedItem();
String b_txt = (String) GUI.comboBox_2.getSelectedItem();
String op_txt="";
if(op==0) op_txt = "addition";
if(op==1) op_txt = "subtraction";
if(op==2) op_txt = "multiplication";
if(op==3) op_txt = "division";
if(op==4) op_txt = "signature";
if(op==5) op_txt = "verify";
String txt_0 = " The "+op_txt+" of a "+a_txt+" with a "+b_txt+"\n is not possible!\n\n Adjust the input fields\n for the "+op_txt+" correctly";
String txt_1 = " scalar "+op_txt+"\n\n "+op_txt+" of a number with a number modulo n\n f(x) = (A "+GUI.comboBox_op.getSelectedItem()+" B)mod(n)";
String txt_2 = " elliptic curve "+op_txt+"\n\n "+op_txt+" of a "+a_txt+" with a "+b_txt+"\n on the elliptic curve Secp256k1\n f(x) = (A "+GUI.comboBox_op.getSelectedItem()+" B)";
String txt_3 = " ECDSA Signatur\n\n h = hash of the document to be signed\n k = random number\n B = the private key with which you want to sign \n G = generator point \n\n Signature r,s\n\n f(r) = k \u2022 G \n f(s) = (h + r \u2022 B)/k";
String txt_4 = " ECDSA verification\n\n h = hash of the document to be verified\n r,s = the signature\n B = the public key with which you want to verified \n G = generator point \n\n h/s \u2022 G + r/s \u2022 B = r(x)";
if(a==1 && b==1 && op==0) { GUI.lbl_op.setText("scalar addition"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 1;}
if(a==1 && b==1 && op==1) { GUI.lbl_op.setText("scalar subtraction"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 2;}
if(a==1 && b==1 && op==2) { GUI.lbl_op.setText("scalar multiplication");GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 3;}
if(a==1 && b==1 && op==3) { GUI.lbl_op.setText("scalar division"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_1); return 4;}
if(a==0 && b==0 && op==0) { GUI.lbl_op.setText("ECC addition"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 5;}
if(a==0 && b==0 && op==1) { GUI.lbl_op.setText("ECC subtraktion"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 6;}
if(a==1 && b==0 && op==2) { GUI.lbl_op.setText("ECC multiplication"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 7;}
if(a==0 && b==1 && op==2) { GUI.lbl_op.setText("ECC multiplikation"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 7;}
if(a==0 && b==1 && op==3) { GUI.lbl_op.setText("ECC division"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_2); return 8;}
if(a==0 && b==1 && op==4) { GUI.lbl_op.setText("signature"); GUI.txt[5].setVisible(true); GUI.txt_opBeschreibung.setText(txt_3); return 9;}
if(a==0 && b==0 && op==5) { GUI.lbl_op.setText("verify"); GUI.txt[5].setVisible(false); GUI.txt_opBeschreibung.setText(txt_4); return 10;}
GUI.lbl_op.setText("No possible operation!");
{
GUI.lbl_op.setForeground(Color.RED); GUI.btn_calc.setEnabled(false);
GUI.txt_opBeschreibung.setText(txt_0);
GUI.txt_opBeschreibung.setForeground(Color.red);
return 0;
}
}
// subtrahiert a-b
private static BigInteger sub(BigInteger a, BigInteger b)
{
return a.add(Secp256k1.ORDNUNG.subtract(b)).mod(Secp256k1.ORDNUNG);
}
// dividiert a / b
public static BigInteger div(BigInteger a, BigInteger b)
{
return a.multiply(b.modInverse(Secp256k1.ORDNUNG)).mod(Secp256k1.ORDNUNG);
}
// Hauptmethode die bei Betätigung des "=" Symbols, die Berechnung ausführt.
public static void calc() throws Exception
{
if(run_calc==true) return;
else run_calc = true;
int op = parseOP();
BigInteger[] po1 = new BigInteger[2];
BigInteger[] po2 = new BigInteger[2];
switch(op)
{
case 1: GUI.txt[4].setText( new BigInteger(GUI.txt[0].getText(),16).add (new BigInteger(GUI.txt[2].getText(),16)).mod(Secp256k1.ORDNUNG).toString(16)); break;
case 2: GUI.txt[4].setText(sub( new BigInteger(GUI.txt[0].getText(),16), new BigInteger(GUI.txt[2].getText(),16)).toString(16)); break;
case 3: GUI.txt[4].setText( new BigInteger(GUI.txt[0].getText(),16).multiply(new BigInteger(GUI.txt[2].getText(),16)).mod(Secp256k1.ORDNUNG).toString(16)); break;
case 4: GUI.txt[4].setText(div( new BigInteger(GUI.txt[0].getText(),16), new BigInteger(GUI.txt[2].getText(),16)).toString(16)); break;
case 5: // Addition elliptic curve
{
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
po2[0] = new BigInteger(GUI.txt[2].getText(),16);
po2[1] = new BigInteger(GUI.txt[3].getText(),16);
BigInteger[] erg = Secp256k1.addition(po1, po2);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 6: // Suptraktion elliptic curve
{
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
po2[0] = new BigInteger(GUI.txt[2].getText(),16);
po2[1] = new BigInteger(GUI.txt[3].getText(),16);
BigInteger[] erg = Secp256k1.subtraktion(po1, po2);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 7: // Multiplikation elliptic curve
{
BigInteger fac;
if(GUI.comboBox_1.getSelectedIndex()==1)
{
fac = new BigInteger(GUI.txt[0].getText(),16);
po1[0] = new BigInteger(GUI.txt[2].getText(),16);
po1[1] = new BigInteger(GUI.txt[3].getText(),16);
}
else
{
fac = new BigInteger(GUI.txt[2].getText(),16);
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
}
BigInteger[] erg = Secp256k1.multiply_Point(po1, fac);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 8: // Division elliptic curve
{
BigInteger div = new BigInteger(GUI.txt[2].getText(),16);
po1[0] = new BigInteger(GUI.txt[0].getText(),16);
po1[1] = new BigInteger(GUI.txt[1].getText(),16);
BigInteger[] erg = Secp256k1.div(po1, div);
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 9: // Signature
{
BigInteger h = new BigInteger(GUI.txt[0].getText(),16);
BigInteger k = new BigInteger(GUI.txt[1].getText(),16);
BigInteger prv = new BigInteger(GUI.txt[2].getText(),16);
Secp256k1 sec = new Secp256k1();
BigInteger[] erg = sec.sig(h.toByteArray(), prv.toByteArray(), k.toByteArray());
GUI.txt[4].setText(erg[0].toString(16));
GUI.txt[5].setText(erg[1].toString(16));
break;
}
case 10: // Verify
{
BigInteger h = new BigInteger(GUI.txt[0].getText(),16);
po1[0] = new BigInteger(GUI.txt[1].getText(),16);
po1[1] = new BigInteger(GUI.txt[18].getText(),16);
po2[0] = new BigInteger(GUI.txt[2].getText(),16);
po2[1] = new BigInteger(GUI.txt[3].getText(),16);
Secp256k1 sec = new Secp256k1();
Boolean erg = sec.verify(h.toByteArray(), po1, po2);
GUI.txt[4].setText(erg.toString());
break;
}
default:
}
run_calc=false;
GUI.animation.close();
}
// Speichert den übergebenen Vektor im nächsten freien Merker
// Ist kein Merker mehr frei, wird nichts gespeichert
public static void saveToNextMerker(String a, String b)
{
for(int i=6;i<18;i=i+2)
{
if(isEmty(i)==true && isEmty(i+1)==true)
{
GUI.txt[i].setText(a);
GUI.txt[i+1].setText(b);
break;
}
}
}
// Speichert den Merker zurück in den Eingabebereich.
// nr = die Button Nummer die leider nur auf diesem Umständlichem Weg übergeben werden kann.
public static void saveFromMerkerTo(ActionEvent e)
{
int nr = (int) ((JComponent) e.getSource()).getClientProperty("int");
if(nr%2==0) // die Merker auf der linken Seite
{
if(GUI.comboBox_op.getSelectedIndex()!=5)
{
GUI.txt[0].setText(GUI.txt[nr+6].getText());
GUI.txt[1].setText(GUI.txt[nr+7].getText());
if(isEmty(nr+7)) GUI.comboBox_1.setSelectedIndex(1);
else GUI.comboBox_1.setSelectedIndex(0);
}
else // Bei Auswahl von Verify
{
GUI.txt[1].setText(GUI.txt[nr+6].getText());
GUI.txt[18].setText(GUI.txt[nr+7].getText());
}
}
else // die Merker auf der rechten Seite
{
GUI.txt[2].setText(GUI.txt[nr+5].getText());
GUI.txt[3].setText(GUI.txt[nr+6].getText());
if(isEmty(nr+6)) GUI.comboBox_2.setSelectedIndex(1);
else GUI.comboBox_2.setSelectedIndex(0);
}
}
// Prüft ob das Feld leer ist
private static boolean isEmty(int m)
{
if(GUI.txt[m].getText().equals("")) return true;
else return false;
}
// Startet einen eigenen Thread der zyklich alle eingabe Felder mit einander vergleicht
// und doppelte Elemente farblich markiert
// Die Hintergrundfarbe wird zwichengespeichert und erst am Ende auf das Textfeld geschrieben, damit es nicht zum Flackern kommt.
public static void findEquals()
{
Thread t = new Thread(new Runnable()
{
public void run()
{
while(run_findEquals)
{
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
color =0;
for(int i=0;i<19;i++) txt_color[i] = Color.white;
txt_color[4] = new Color(245, 245, 245);
txt_color[5] = new Color(245, 245, 245);
String[] text = new String[19];
for(int i=0;i<19;i++) {text[i] = GUI.txt[i].getText();}
for(int i=0;i<19;i++)
{
for(int j=0;j<19;j++)
{
if(text[i].equals(text[j]) && i!=j && text[i].equals("")==false)
{
txt_color[i] = nextColor();
txt_color[j] = nextColor();
}
}
color++;
}
for(int i=0;i<19;i++) {GUI.txt[i].setBackground(txt_color[i]);}
if(GUI.txt[0].getText().equals("color")) printAllColor();
}
System.out.println("Thread findEquals beendet");
}
});
t.start();
}
// Vergibt die nächste Farbe für die Hintergrundfarbe der gleichen Elemente
private static Color nextColor()
{
Color[] c = new Color[19];
c[3] = Color.decode("#fbeeee");
c[6] = Color.decode("#F8ECE0");
c[9] = Color.decode("#F7F8E0");
c[12] = Color.decode("#ECF8E0");
c[15] = Color.decode("#E0F8E0");
c[1] = Color.decode("#E0F2F7");
c[4] = Color.decode("#E0E6F8");
c[7] = Color.decode("#E6E0F8");
c[10] = Color.decode("#ffd6cc");
c[13] = Color.decode("#ebe0cc");
c[16] = Color.decode("#F8E0E6");
c[2] = Color.decode("#cce0ff");
c[5] = Color.decode("#F5A9A9");
c[8] = Color.decode("#F5D0A9");
c[11] = Color.decode("#F2F5A9");
c[14] = Color.decode("#D0F5A9");
c[17] = Color.decode("#A9F5A9");
c[0] = Color.decode("#A9F5D0");
c[18] = Color.decode("#ffcccc");
return c[color];
}
//Testmethode die bei der Eingabe von "color" im ersten Feld alle Farben anzeigt.
private static void printAllColor()
{
color = 0;
for(int i=0;i<19;i++)
{
GUI.txt[i].setBackground(nextColor());
color++;
}
}
// ------------------------------------------------------- Signature & Verify --------------------------------------------
// der Eingabebereich der GUI wird für die Berechnung der Sigantur angepasst
public static void setOP_Sig()
{
GUI.comboBox_op.setFont(new Font("Tahoma", Font.PLAIN, 18));
GUI.comboBox_1.setSelectedIndex(0);
GUI.comboBox_2.setSelectedIndex(1);
GUI.lbl_X.setText("h");
GUI.lbl_Y.setText("k");
GUI.lbl_Z.setVisible(false);
GUI.lbl_privKey.setVisible(true);
GUI.lbl_privKey.setText("Private Key");
GUI.lbl_privKey.setForeground(Color.RED);
GUI.btn_G1.setVisible(false);
GUI.btn_rand1.setVisible(true);
GUI.btn_m1.setBounds(300, 135, 50, 20);
GUI.btn_y1a.setVisible(false);
GUI.btn_y1b.setVisible(false);
GUI.lbl_r.setVisible(true);
GUI.lbl_s.setVisible(true);
GUI.txt[18].setVisible(false);
GUI.txt[18].setText("");
GUI.txt[1].setBounds(20, 110, 330, 20);
GUI.lbl_Y.setBounds(10, 113, 23, 14);
GUI.btn_m4.setVisible(false);
GUI.lbl_D.setVisible(false);
for(int i=0; i<12 ;i++) if(i%2==0) {GUI.btn_m[i].setText("<--A"); GUI.btn_m[i].setToolTipText("Save this memory field back to input A");}
}
// der Eingabebereich der GUI wird für die Berechnung der Verifikation angepasst
public static void setOP_ver()
{
GUI.comboBox_op.setFont(new Font("Tahoma", Font.PLAIN, 18));
GUI.comboBox_1.setSelectedIndex(0);
GUI.comboBox_2.setSelectedIndex(0);
GUI.lbl_X.setText("h");
GUI.lbl_Y.setText("r");
GUI.lbl_Z.setText("s");
GUI.lbl_Z.setVisible(true);
GUI.lbl_privKey.setVisible(true);
GUI.lbl_privKey.setText("Public Key");
GUI.lbl_privKey.setForeground(Color.blue);
GUI.btn_G1.setVisible(false);
GUI.btn_rand1.setVisible(false);
GUI.btn_m1.setBounds(300, 102, 49, 15);
GUI.btn_y1a.setVisible(false);
GUI.btn_y1b.setVisible(false);
GUI.lbl_r.setVisible(false);
GUI.lbl_s.setVisible(false);
GUI.txt[18].setVisible(true);
GUI.txt[1].setBounds(20, 130, 330, 20);
GUI.lbl_Y.setBounds(10, 133, 23, 14);
GUI.txt[1].setText("");
GUI.txt[2].setText("");
GUI.txt[3].setText("");
GUI.btn_m4.setVisible(true);
GUI.lbl_D.setVisible(true);
for(int i=0; i<12 ;i++) if(i%2==0) {GUI.btn_m[i].setText("<--D"); GUI.btn_m[i].setToolTipText("Save this memory field back to input D");}
}
// der Eingabebereich der GUI wird für die Berechnung zurück auf Calculator gesetzt
public static void setOP_calc()
{
GUI.comboBox_op.setFont(new Font("Tahoma", Font.PLAIN, 30));
GUI.lbl_X.setText("X");
GUI.lbl_Y.setText("Y");
GUI.lbl_privKey.setVisible(false);
GUI.btn_G1.setVisible(true);
GUI.btn_rand1.setVisible(true);
GUI.btn_m1.setBounds(300, 135, 50, 20);
GUI.btn_y1a.setVisible(true);
GUI.btn_y1b.setVisible(true);
GUI.lbl_r.setVisible(false);
GUI.lbl_s.setVisible(false);
GUI.txt[18].setVisible(false);
GUI.txt[18].setText("");
GUI.lbl_Z.setVisible(false);
GUI.txt[1].setBounds(20, 110, 330, 20);
GUI.lbl_Y.setBounds(10, 113, 23, 14);
GUI.btn_m4.setVisible(false);
GUI.lbl_D.setVisible(false);
for(int i=0; i<12 ;i++) if(i%2==0) {GUI.btn_m[i].setText("<--A"); GUI.btn_m[i].setToolTipText("Save this memory field back to input A");}
}
}
|
189035_17 | package TxBuild;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Scanner;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.OverlayLayout;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import RPC.ConnectRPC;
/********************************************************************************************************************
* Autor: Mr. Maxwell vom 29.01.2024 *
* Die GUI (JDialog). Importiert die csv Datei mit den eigenen kontrollieten Bitcoin-Adressen. *
* Zeigt alle Adressen an, die Beträge enthalten und zeigt die gesamt-Summe an *
********************************************************************************************************************/
public class GUI_ImportCSV extends JDialog
{
private JTable table; // Die Tabelle mit den Bitcon-Adressen
private JScrollPane scrollPane = new JScrollPane();
private JTextPane txt_meld = new JTextPane(); // Ausgabe-Fenster mit allen Meldungen
private JProgressBar progressBar = new JProgressBar(); // Wartebalklen unten, wenn der Core die Transaktionen sucht.
private JTextField txt_totalValue = new JTextField(); // Gesamter Ausgangs-Betrag
private JButton btn_open = new JButton("open csv file"); // öffnet den FileCooser zum laden der csv-Datei
private JButton btn_cancel = new JButton("cancel"); // Abbruch Load
private JButton btn_input = new JButton("As source address"); // Button: Als Eingabe setzten
private JButton btn_output = new JButton("As destination address"); // Button: Als Ausgabe setzten
private JLabel lbl_progress = new JLabel(new ImageIcon("icons/load.gif")); // Animiertes progress gif. drehendes Bitcoin-Symbol
public GUI_ImportCSV(int x, int y)
{
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Import Bitcoin Address csv file");
setBounds(x, y, 800, 450);
setModal(true);
JMenuBar menuBar = new JMenuBar();
JPanel pnl_menu = new JPanel();
JPanel pnl_2 = new JPanel();
JPanel pnl_3 = new JPanel();
JLayeredPane pnl_lp = new JLayeredPane();
JLabel lbl_file = new JLabel("user.dir"); // Speicherort der csv.Datei
JTextPane lbl_info = new JTextPane(); // Beschreibung
lbl_info .setForeground(GUI.color4);
txt_meld .setForeground(Color.RED);
lbl_file .setBackground(GUI.color1);
progressBar .setForeground(GUI.color4);
lbl_info .setBackground(GUI.color1);
txt_meld .setBackground(GUI.color1);
progressBar .setBackground(GUI.color1);
txt_totalValue .setBackground(GUI.color1);
lbl_info .setFont(GUI.font3);
txt_totalValue .setFont(GUI.font4);
btn_input .setFont(new Font("Century Gothic", Font.PLAIN, 12));
btn_output .setFont(new Font("Century Gothic", Font.PLAIN, 12));
btn_open .setFont(new Font("Century Gothic", Font.PLAIN, 12));
btn_cancel .setFont(new Font("Century Gothic", Font.PLAIN, 12));
lbl_file .setFont(new Font("Century Gothic", Font.PLAIN, 12));
lbl_info .setText(" This is where the csv file is imported, which contains your own Bitcoin addresses.\r\n Once imported, the total amount of all controlled Bitcoin addresses will be displayed.\r\n They can directly choose from which addresses they want to send or receive.");
lbl_file .setText("user.dir");
txt_totalValue .setBorder(new TitledBorder(new LineBorder(GUI.color4), "Total Value", TitledBorder.LEADING, TitledBorder.TOP, GUI.font2, GUI.color3));
menuBar .setBorder(new LineBorder(GUI.color1));
scrollPane .setBorder(new LineBorder(GUI.color1, 7));
progressBar .setBorder(null);
btn_input .setPreferredSize(new Dimension(160, 22));
btn_output .setPreferredSize(new Dimension(160, 22));
progressBar .setPreferredSize(new Dimension(146, 13));
btn_open .setPreferredSize(new Dimension(110, 20));
btn_cancel .setPreferredSize(new Dimension(110, 20));
btn_input .setMargin(new Insets(0, 0, 0, 0));
btn_output .setMargin(new Insets(0, 0, 0, 0));
btn_open .setMargin(new Insets(0, 0, 0, 0));
btn_cancel .setMargin(new Insets(0, 0, 0, 0));
lbl_info .setEditable(false);
txt_totalValue .setEditable(false);
btn_input .setEnabled(false);
btn_output .setEnabled(false);
progressBar .setVisible(false);
btn_cancel .setVisible(false);
lbl_progress .setVisible(false);
progressBar .setStringPainted(true);
txt_totalValue .setColumns(19);
scrollPane .setOpaque(false);
scrollPane .setFocusable(false);
scrollPane .setFocusTraversalKeysEnabled(false);
scrollPane .getViewport().setOpaque(false);
pnl_lp .setLayout(new OverlayLayout(pnl_lp));
pnl_2 .setLayout(new BorderLayout(0, 0));
pnl_menu .setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
pnl_3 .setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
txt_totalValue .setHorizontalAlignment(SwingConstants.RIGHT);
setJMenuBar(menuBar);
menuBar .add(pnl_menu);
pnl_menu .add(btn_open);
pnl_menu .add(btn_cancel);
pnl_menu .add(lbl_file);
pnl_lp .add(lbl_progress);
pnl_lp .add(scrollPane);
pnl_2 .add(pnl_3, BorderLayout.NORTH);
pnl_2 .add(txt_meld, BorderLayout.CENTER);
pnl_2 .add(progressBar, BorderLayout.SOUTH);
pnl_3 .add(btn_input);
pnl_3 .add(Box.createHorizontalStrut(50));
pnl_3 .add(btn_output);
pnl_3 .add(Box.createHorizontalStrut(165));
pnl_3 .add(txt_totalValue);
getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().add(lbl_info, BorderLayout.NORTH);
getContentPane().add(pnl_lp, BorderLayout.CENTER);
getContentPane().add(pnl_2, BorderLayout.SOUTH);
// ----------------------------------------------------------- Actions --------------------------------------------------------------------------
// Öffnet mit dem JFileChooser die sig.Tx.
btn_open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
txt_meld.setText("");
String userDir = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser(userDir +"/Desktop");
chooser.setFileFilter(new FileNameExtensionFilter("BTCAddressList.csv", "csv"));
chooser.setCurrentDirectory(new File(lbl_file.getText()));
int button = chooser.showOpenDialog(scrollPane);
if(button==0)
{
lbl_file.setText(chooser.getSelectedFile().getAbsolutePath());
try
{
ArrayList<String> list = new ArrayList<String>();
Scanner scanner = new Scanner(new File(lbl_file.getText()));
scanner.useDelimiter(",");
while(scanner.hasNext())
{
String str = ((scanner.next().replaceAll("\n", "")));
if(str.length()>8) list.add(str);
}
scanner.close();
String[] addr = list.toArray(new String[0]);
loadTxfromCore(addr);
}
catch (Exception e1)
{
txt_meld.setText(e1.getMessage());
e1.printStackTrace();
}
}
}
});
// Bricht den "scantxoutset-Befehl" des Cores (Laden der TX) ab.
btn_cancel.addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
// Steuert die Process-Bar
Thread thread3 = new Thread(new Runnable()
{
@Override
public void run()
{
ConnectRPC core = new ConnectRPC(TxBuildAction.ip,TxBuildAction.port,TxBuildAction.name,TxBuildAction.pw);
core.setTimeOut(Integer.valueOf(GUI_CoreSettings.txt_timeOut.getText()));
try
{
core.get_scantxoutset("abort", new String[] {""}, new String[] {""});
}
catch(Exception ex)
{
ex.printStackTrace();
txt_meld.setText(ex.getMessage());
}
}
});
thread3.start();
}
}
});
// Übernimmt markierte Zeilen und schreibt sie in den Input der Haupt-GUI
btn_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
txt_meld.setText("");
int[] auswahl = table.getSelectedRows();
if(auswahl.length<=0) JOptionPane.showMessageDialog(scrollPane, "No marked addresses.\nMark the desired addresses!\nUse the keyboard shortcuts: <Ctrl+a> or <Ctrl+select> or<Shift+select> etc.", "Info", 1);
else
{
GUI.cBox_inCount.setSelectedIndex(auswahl.length-1);
if(auswahl.length == GUI.txt_inAdr.length) // Prüft ob die Anzahl Inputs richtig aktuallisiert wurde. Ist Notwendig, der Benutzer es ablehen kann.
{
for(int i=0; i<auswahl.length;i++)
{
String addr = (String) table.getModel().getValueAt(auswahl[i], 0);
GUI.txt_inAdr[i].setText(addr);
}
GUI.dialogImport.dispose();
}
}
}
catch (Exception e1)
{
txt_meld.setText(e1.getMessage());
e1.printStackTrace();
}
}
});
// Übernimmt markierte Zeilen und schreibt sie in den Output der Haupt-GUI
btn_output.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
txt_meld.setText("");
int[] auswahl = table.getSelectedRows();
if(auswahl.length<=0) JOptionPane.showMessageDialog(scrollPane, "No marked addresses.\nMark the desired addresses!\nUse the keyboard shortcuts: <Ctrl+a> or <Ctrl+select> or<Shift+select> etc.", "Info", 1);
else
{
GUI.cBox_outCount.setSelectedIndex(auswahl.length-1);
if(auswahl.length == GUI.txt_outAdr.length) // Prüft ob die Anzahl Outputs richtig aktuallisiert wurde. Ist Notwendig, der Benutzer es ablehen kann.
{
for(int i=0; i<auswahl.length;i++)
{
String addr = (String) table.getModel().getValueAt(auswahl[i], 0);
GUI.txt_outAdr[i].setText(addr);
}
GUI.dialogImport.dispose();
}
}
}
catch (Exception e1)
{
txt_meld.setText(e1.getMessage());
e1.printStackTrace();
}
}
});
}
// --------------------------------------------------------------- private Methoden ----------------------------------------------------------
// Hier wird die Tabelle erstellt und in die GUI gesetzt
private void setTable(String[][] str_tab) throws Exception
{
String[] ueberschrift= new String[] { "BTC Addrress", "Value"};
table = new JTable();
table.setEnabled(true);
table.setFont(GUI.font4);
table.setForeground(GUI.color3);
table.setSelectionForeground(new Color(120,0,0));
// table.setSelectionBackground(Color.MAGENTA); // Geht nicht, Kann nicht verändert werden!
table.getTableHeader().setBackground(GUI.color3);
table.getTableHeader().setForeground(GUI.color1);
table.setSurrendersFocusOnKeystroke(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
table.setDefaultEditor(Object.class, null);
table.setModel(new DefaultTableModel(str_tab, ueberschrift));
table.getColumnModel().getColumn(0).setPreferredWidth(400);
table.getColumnModel().getColumn(1).setPreferredWidth(50);
table.setGridColor(GUI.color4);
table.setRowHeight(20);
table.setOpaque(false);
table.setCellSelectionEnabled(true);
((JComponent) table.getDefaultRenderer(Object.class)).setOpaque(false);
scrollPane .setViewportView(table);
}
// Lädt die Transaktionen vom Bitcoin-Core
private void loadTxfromCore(String[] addr)
{
txt_totalValue.setText("");
btn_open.setVisible(false);
btn_cancel.setVisible(true);
txt_meld.setText("");
TxBuildAction.ip = GUI_CoreSettings.txt_ip.getText();
TxBuildAction.port = Integer.valueOf(GUI_CoreSettings.txt_port.getText());
TxBuildAction.name = GUI_CoreSettings.txt_uName.getText();
TxBuildAction.pw = GUI_CoreSettings.txt_pw.getText();
Thread thread1 = new Thread(new Runnable()
{
@Override
public void run()
{
ConnectRPC core = new ConnectRPC(TxBuildAction.ip,TxBuildAction.port,TxBuildAction.name,TxBuildAction.pw);
core.setTimeOut(Integer.valueOf(GUI_CoreSettings.txt_timeOut.getText()));
try
{
String[] adrFormat = new String[addr.length];
for(int i=0; i<addr.length;i++){adrFormat[i] = "addr";}
JSONObject coreTxOutSet = core.get_scantxoutset("start", adrFormat, addr);
scantxoutsetResult(coreTxOutSet);
}
catch(Exception ex)
{
ex.printStackTrace();
txt_meld.setText(ex.getMessage());
}
btn_open.setVisible(true);
btn_cancel.setVisible(false);
}
});
// Steuert die Process-Bar
Thread thread2 = new Thread(new Runnable()
{
@Override
public void run()
{
ConnectRPC core = new ConnectRPC(TxBuildAction.ip,TxBuildAction.port,TxBuildAction.name,TxBuildAction.pw);
core.setTimeOut(Integer.valueOf(GUI_CoreSettings.txt_timeOut.getText()));
lbl_progress.setVisible(true);
progressBar.setVisible(true);
for(int i=0; i<600; i++ )
{
try
{
Thread.sleep(1000);
JSONObject jo = core.get_scantxoutset("status", new String[] {""}, new String[] {""});
progressBar.setValue(jo.getJSONObject("result").getInt("progress"));
}
catch(Exception ex)
{
lbl_progress.setVisible(false);
progressBar.setVisible(false);
break;
}
}
}
});
thread1.start();
thread2.start();
}
// Wertet das Ergebnis vom Core aus und und schreibt die Daten in die GUI
private void scantxoutsetResult(JSONObject jo) throws JSONException
{
try{txt_meld.setText("BitcoinCore Error:\n"+ jo.getJSONObject("error").getString("message"));} // Gibt Fehler-Meldungen vom Core aus
catch(Exception e) {};
try
{
JSONObject jo_result = jo.getJSONObject("result"); // Das Ergebnis von Core, als JSON-Object
if(jo_result.getBoolean("success") == true) // Wenn Ergebnis fehlerfrei abgeschlossen ist.
{
LinkedHashMap<String,Double>hm = new LinkedHashMap<String,Double>(); // In die HashMap werden die Adressen und zugehörigen Beträge gespeichert. "LinkedHashMap" bedeutet, dass die Reihenfolge der Elemente bei behalten wird.
txt_totalValue.setText(String.format("%.8f", jo_result.getDouble("total_amount"))); // Gesamtbetrag aller Adressen
JSONArray unspents = jo_result.getJSONArray("unspents"); // Nicht ausgegebene Inputs als JSONArray
for(int i=0;i<unspents.length();i++)
{
JSONObject jo_el = unspents.getJSONObject(i);
String addr = jo_el.getString("desc"); // Die Bitcoin Adresse, mit angehängten Daten
addr = addr.substring(addr.indexOf("(")+1, addr.indexOf(")")); // Die reine Bitcoin Adresse. (Angehängte Daten werden entfernt)
hm.put(addr, hm.getOrDefault(addr, 0.0) + jo_el.getDouble("amount")); // Speichert Addresse mit Betrag in die HashMap und addiert dabei die Beträge bei mehrfachen gleichen Adressen.
} // In der LinkedHashMap (hm) befinden sich nun alle Adressen mit den zugehörigen Beträgen. Mehrfache Adressen wurden zusammen-verrechnet.
String[][] tab = new String[hm.size()][2]; // 2Dim String-Array wird hier angelegt und später der Tabelle übergeben. Entspricht im Prinzip der Tabelle.
Object[] keys = hm.keySet().toArray(); // Mit "keys" sind die BTC-Adressen gemeint, die als Schlüssel in der HashMap fungieren. Die Schlüssel müssen aufgelistet werden um sie anschließend in der Schleife durchlaufen zu können.
for(int i=0; i<keys.length;i++) // Damit wird die HashMap in die Tabelle übertragen.
{
tab[i][0] = (String) keys[i]; // Schreibt die BTC-Adressen (keys) in die Tabelle
tab[i][1] = String.format("%.8f",(Math.round(hm.get(tab[i][0])*100000000.0)/100000000.0)); // Schreibt die Beträge in die Tabelle, die Beträge werden noch richtig formatiert.
}
setTable(tab);
if(keys.length>0)
{
btn_input .setEnabled(true);
btn_output .setEnabled(true);
}
else
{
btn_input .setEnabled(false);
btn_output .setEnabled(false);
txt_meld.setText("No address with an available amount found.");
}
}
}
catch(Exception e) {e.printStackTrace();};
}
} | MrMaxweII/TxBuilder | src/TxBuild/GUI_ImportCSV.java | 6,412 | // --------------------------------------------------------------- private Methoden ----------------------------------------------------------
| line_comment | nl | package TxBuild;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Scanner;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.OverlayLayout;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import RPC.ConnectRPC;
/********************************************************************************************************************
* Autor: Mr. Maxwell vom 29.01.2024 *
* Die GUI (JDialog). Importiert die csv Datei mit den eigenen kontrollieten Bitcoin-Adressen. *
* Zeigt alle Adressen an, die Beträge enthalten und zeigt die gesamt-Summe an *
********************************************************************************************************************/
public class GUI_ImportCSV extends JDialog
{
private JTable table; // Die Tabelle mit den Bitcon-Adressen
private JScrollPane scrollPane = new JScrollPane();
private JTextPane txt_meld = new JTextPane(); // Ausgabe-Fenster mit allen Meldungen
private JProgressBar progressBar = new JProgressBar(); // Wartebalklen unten, wenn der Core die Transaktionen sucht.
private JTextField txt_totalValue = new JTextField(); // Gesamter Ausgangs-Betrag
private JButton btn_open = new JButton("open csv file"); // öffnet den FileCooser zum laden der csv-Datei
private JButton btn_cancel = new JButton("cancel"); // Abbruch Load
private JButton btn_input = new JButton("As source address"); // Button: Als Eingabe setzten
private JButton btn_output = new JButton("As destination address"); // Button: Als Ausgabe setzten
private JLabel lbl_progress = new JLabel(new ImageIcon("icons/load.gif")); // Animiertes progress gif. drehendes Bitcoin-Symbol
public GUI_ImportCSV(int x, int y)
{
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Import Bitcoin Address csv file");
setBounds(x, y, 800, 450);
setModal(true);
JMenuBar menuBar = new JMenuBar();
JPanel pnl_menu = new JPanel();
JPanel pnl_2 = new JPanel();
JPanel pnl_3 = new JPanel();
JLayeredPane pnl_lp = new JLayeredPane();
JLabel lbl_file = new JLabel("user.dir"); // Speicherort der csv.Datei
JTextPane lbl_info = new JTextPane(); // Beschreibung
lbl_info .setForeground(GUI.color4);
txt_meld .setForeground(Color.RED);
lbl_file .setBackground(GUI.color1);
progressBar .setForeground(GUI.color4);
lbl_info .setBackground(GUI.color1);
txt_meld .setBackground(GUI.color1);
progressBar .setBackground(GUI.color1);
txt_totalValue .setBackground(GUI.color1);
lbl_info .setFont(GUI.font3);
txt_totalValue .setFont(GUI.font4);
btn_input .setFont(new Font("Century Gothic", Font.PLAIN, 12));
btn_output .setFont(new Font("Century Gothic", Font.PLAIN, 12));
btn_open .setFont(new Font("Century Gothic", Font.PLAIN, 12));
btn_cancel .setFont(new Font("Century Gothic", Font.PLAIN, 12));
lbl_file .setFont(new Font("Century Gothic", Font.PLAIN, 12));
lbl_info .setText(" This is where the csv file is imported, which contains your own Bitcoin addresses.\r\n Once imported, the total amount of all controlled Bitcoin addresses will be displayed.\r\n They can directly choose from which addresses they want to send or receive.");
lbl_file .setText("user.dir");
txt_totalValue .setBorder(new TitledBorder(new LineBorder(GUI.color4), "Total Value", TitledBorder.LEADING, TitledBorder.TOP, GUI.font2, GUI.color3));
menuBar .setBorder(new LineBorder(GUI.color1));
scrollPane .setBorder(new LineBorder(GUI.color1, 7));
progressBar .setBorder(null);
btn_input .setPreferredSize(new Dimension(160, 22));
btn_output .setPreferredSize(new Dimension(160, 22));
progressBar .setPreferredSize(new Dimension(146, 13));
btn_open .setPreferredSize(new Dimension(110, 20));
btn_cancel .setPreferredSize(new Dimension(110, 20));
btn_input .setMargin(new Insets(0, 0, 0, 0));
btn_output .setMargin(new Insets(0, 0, 0, 0));
btn_open .setMargin(new Insets(0, 0, 0, 0));
btn_cancel .setMargin(new Insets(0, 0, 0, 0));
lbl_info .setEditable(false);
txt_totalValue .setEditable(false);
btn_input .setEnabled(false);
btn_output .setEnabled(false);
progressBar .setVisible(false);
btn_cancel .setVisible(false);
lbl_progress .setVisible(false);
progressBar .setStringPainted(true);
txt_totalValue .setColumns(19);
scrollPane .setOpaque(false);
scrollPane .setFocusable(false);
scrollPane .setFocusTraversalKeysEnabled(false);
scrollPane .getViewport().setOpaque(false);
pnl_lp .setLayout(new OverlayLayout(pnl_lp));
pnl_2 .setLayout(new BorderLayout(0, 0));
pnl_menu .setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
pnl_3 .setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
txt_totalValue .setHorizontalAlignment(SwingConstants.RIGHT);
setJMenuBar(menuBar);
menuBar .add(pnl_menu);
pnl_menu .add(btn_open);
pnl_menu .add(btn_cancel);
pnl_menu .add(lbl_file);
pnl_lp .add(lbl_progress);
pnl_lp .add(scrollPane);
pnl_2 .add(pnl_3, BorderLayout.NORTH);
pnl_2 .add(txt_meld, BorderLayout.CENTER);
pnl_2 .add(progressBar, BorderLayout.SOUTH);
pnl_3 .add(btn_input);
pnl_3 .add(Box.createHorizontalStrut(50));
pnl_3 .add(btn_output);
pnl_3 .add(Box.createHorizontalStrut(165));
pnl_3 .add(txt_totalValue);
getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().add(lbl_info, BorderLayout.NORTH);
getContentPane().add(pnl_lp, BorderLayout.CENTER);
getContentPane().add(pnl_2, BorderLayout.SOUTH);
// ----------------------------------------------------------- Actions --------------------------------------------------------------------------
// Öffnet mit dem JFileChooser die sig.Tx.
btn_open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
txt_meld.setText("");
String userDir = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser(userDir +"/Desktop");
chooser.setFileFilter(new FileNameExtensionFilter("BTCAddressList.csv", "csv"));
chooser.setCurrentDirectory(new File(lbl_file.getText()));
int button = chooser.showOpenDialog(scrollPane);
if(button==0)
{
lbl_file.setText(chooser.getSelectedFile().getAbsolutePath());
try
{
ArrayList<String> list = new ArrayList<String>();
Scanner scanner = new Scanner(new File(lbl_file.getText()));
scanner.useDelimiter(",");
while(scanner.hasNext())
{
String str = ((scanner.next().replaceAll("\n", "")));
if(str.length()>8) list.add(str);
}
scanner.close();
String[] addr = list.toArray(new String[0]);
loadTxfromCore(addr);
}
catch (Exception e1)
{
txt_meld.setText(e1.getMessage());
e1.printStackTrace();
}
}
}
});
// Bricht den "scantxoutset-Befehl" des Cores (Laden der TX) ab.
btn_cancel.addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
// Steuert die Process-Bar
Thread thread3 = new Thread(new Runnable()
{
@Override
public void run()
{
ConnectRPC core = new ConnectRPC(TxBuildAction.ip,TxBuildAction.port,TxBuildAction.name,TxBuildAction.pw);
core.setTimeOut(Integer.valueOf(GUI_CoreSettings.txt_timeOut.getText()));
try
{
core.get_scantxoutset("abort", new String[] {""}, new String[] {""});
}
catch(Exception ex)
{
ex.printStackTrace();
txt_meld.setText(ex.getMessage());
}
}
});
thread3.start();
}
}
});
// Übernimmt markierte Zeilen und schreibt sie in den Input der Haupt-GUI
btn_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
txt_meld.setText("");
int[] auswahl = table.getSelectedRows();
if(auswahl.length<=0) JOptionPane.showMessageDialog(scrollPane, "No marked addresses.\nMark the desired addresses!\nUse the keyboard shortcuts: <Ctrl+a> or <Ctrl+select> or<Shift+select> etc.", "Info", 1);
else
{
GUI.cBox_inCount.setSelectedIndex(auswahl.length-1);
if(auswahl.length == GUI.txt_inAdr.length) // Prüft ob die Anzahl Inputs richtig aktuallisiert wurde. Ist Notwendig, der Benutzer es ablehen kann.
{
for(int i=0; i<auswahl.length;i++)
{
String addr = (String) table.getModel().getValueAt(auswahl[i], 0);
GUI.txt_inAdr[i].setText(addr);
}
GUI.dialogImport.dispose();
}
}
}
catch (Exception e1)
{
txt_meld.setText(e1.getMessage());
e1.printStackTrace();
}
}
});
// Übernimmt markierte Zeilen und schreibt sie in den Output der Haupt-GUI
btn_output.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
txt_meld.setText("");
int[] auswahl = table.getSelectedRows();
if(auswahl.length<=0) JOptionPane.showMessageDialog(scrollPane, "No marked addresses.\nMark the desired addresses!\nUse the keyboard shortcuts: <Ctrl+a> or <Ctrl+select> or<Shift+select> etc.", "Info", 1);
else
{
GUI.cBox_outCount.setSelectedIndex(auswahl.length-1);
if(auswahl.length == GUI.txt_outAdr.length) // Prüft ob die Anzahl Outputs richtig aktuallisiert wurde. Ist Notwendig, der Benutzer es ablehen kann.
{
for(int i=0; i<auswahl.length;i++)
{
String addr = (String) table.getModel().getValueAt(auswahl[i], 0);
GUI.txt_outAdr[i].setText(addr);
}
GUI.dialogImport.dispose();
}
}
}
catch (Exception e1)
{
txt_meld.setText(e1.getMessage());
e1.printStackTrace();
}
}
});
}
// --------------------------------------------------------------- private<SUF>
// Hier wird die Tabelle erstellt und in die GUI gesetzt
private void setTable(String[][] str_tab) throws Exception
{
String[] ueberschrift= new String[] { "BTC Addrress", "Value"};
table = new JTable();
table.setEnabled(true);
table.setFont(GUI.font4);
table.setForeground(GUI.color3);
table.setSelectionForeground(new Color(120,0,0));
// table.setSelectionBackground(Color.MAGENTA); // Geht nicht, Kann nicht verändert werden!
table.getTableHeader().setBackground(GUI.color3);
table.getTableHeader().setForeground(GUI.color1);
table.setSurrendersFocusOnKeystroke(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
table.setDefaultEditor(Object.class, null);
table.setModel(new DefaultTableModel(str_tab, ueberschrift));
table.getColumnModel().getColumn(0).setPreferredWidth(400);
table.getColumnModel().getColumn(1).setPreferredWidth(50);
table.setGridColor(GUI.color4);
table.setRowHeight(20);
table.setOpaque(false);
table.setCellSelectionEnabled(true);
((JComponent) table.getDefaultRenderer(Object.class)).setOpaque(false);
scrollPane .setViewportView(table);
}
// Lädt die Transaktionen vom Bitcoin-Core
private void loadTxfromCore(String[] addr)
{
txt_totalValue.setText("");
btn_open.setVisible(false);
btn_cancel.setVisible(true);
txt_meld.setText("");
TxBuildAction.ip = GUI_CoreSettings.txt_ip.getText();
TxBuildAction.port = Integer.valueOf(GUI_CoreSettings.txt_port.getText());
TxBuildAction.name = GUI_CoreSettings.txt_uName.getText();
TxBuildAction.pw = GUI_CoreSettings.txt_pw.getText();
Thread thread1 = new Thread(new Runnable()
{
@Override
public void run()
{
ConnectRPC core = new ConnectRPC(TxBuildAction.ip,TxBuildAction.port,TxBuildAction.name,TxBuildAction.pw);
core.setTimeOut(Integer.valueOf(GUI_CoreSettings.txt_timeOut.getText()));
try
{
String[] adrFormat = new String[addr.length];
for(int i=0; i<addr.length;i++){adrFormat[i] = "addr";}
JSONObject coreTxOutSet = core.get_scantxoutset("start", adrFormat, addr);
scantxoutsetResult(coreTxOutSet);
}
catch(Exception ex)
{
ex.printStackTrace();
txt_meld.setText(ex.getMessage());
}
btn_open.setVisible(true);
btn_cancel.setVisible(false);
}
});
// Steuert die Process-Bar
Thread thread2 = new Thread(new Runnable()
{
@Override
public void run()
{
ConnectRPC core = new ConnectRPC(TxBuildAction.ip,TxBuildAction.port,TxBuildAction.name,TxBuildAction.pw);
core.setTimeOut(Integer.valueOf(GUI_CoreSettings.txt_timeOut.getText()));
lbl_progress.setVisible(true);
progressBar.setVisible(true);
for(int i=0; i<600; i++ )
{
try
{
Thread.sleep(1000);
JSONObject jo = core.get_scantxoutset("status", new String[] {""}, new String[] {""});
progressBar.setValue(jo.getJSONObject("result").getInt("progress"));
}
catch(Exception ex)
{
lbl_progress.setVisible(false);
progressBar.setVisible(false);
break;
}
}
}
});
thread1.start();
thread2.start();
}
// Wertet das Ergebnis vom Core aus und und schreibt die Daten in die GUI
private void scantxoutsetResult(JSONObject jo) throws JSONException
{
try{txt_meld.setText("BitcoinCore Error:\n"+ jo.getJSONObject("error").getString("message"));} // Gibt Fehler-Meldungen vom Core aus
catch(Exception e) {};
try
{
JSONObject jo_result = jo.getJSONObject("result"); // Das Ergebnis von Core, als JSON-Object
if(jo_result.getBoolean("success") == true) // Wenn Ergebnis fehlerfrei abgeschlossen ist.
{
LinkedHashMap<String,Double>hm = new LinkedHashMap<String,Double>(); // In die HashMap werden die Adressen und zugehörigen Beträge gespeichert. "LinkedHashMap" bedeutet, dass die Reihenfolge der Elemente bei behalten wird.
txt_totalValue.setText(String.format("%.8f", jo_result.getDouble("total_amount"))); // Gesamtbetrag aller Adressen
JSONArray unspents = jo_result.getJSONArray("unspents"); // Nicht ausgegebene Inputs als JSONArray
for(int i=0;i<unspents.length();i++)
{
JSONObject jo_el = unspents.getJSONObject(i);
String addr = jo_el.getString("desc"); // Die Bitcoin Adresse, mit angehängten Daten
addr = addr.substring(addr.indexOf("(")+1, addr.indexOf(")")); // Die reine Bitcoin Adresse. (Angehängte Daten werden entfernt)
hm.put(addr, hm.getOrDefault(addr, 0.0) + jo_el.getDouble("amount")); // Speichert Addresse mit Betrag in die HashMap und addiert dabei die Beträge bei mehrfachen gleichen Adressen.
} // In der LinkedHashMap (hm) befinden sich nun alle Adressen mit den zugehörigen Beträgen. Mehrfache Adressen wurden zusammen-verrechnet.
String[][] tab = new String[hm.size()][2]; // 2Dim String-Array wird hier angelegt und später der Tabelle übergeben. Entspricht im Prinzip der Tabelle.
Object[] keys = hm.keySet().toArray(); // Mit "keys" sind die BTC-Adressen gemeint, die als Schlüssel in der HashMap fungieren. Die Schlüssel müssen aufgelistet werden um sie anschließend in der Schleife durchlaufen zu können.
for(int i=0; i<keys.length;i++) // Damit wird die HashMap in die Tabelle übertragen.
{
tab[i][0] = (String) keys[i]; // Schreibt die BTC-Adressen (keys) in die Tabelle
tab[i][1] = String.format("%.8f",(Math.round(hm.get(tab[i][0])*100000000.0)/100000000.0)); // Schreibt die Beträge in die Tabelle, die Beträge werden noch richtig formatiert.
}
setTable(tab);
if(keys.length>0)
{
btn_input .setEnabled(true);
btn_output .setEnabled(true);
}
else
{
btn_input .setEnabled(false);
btn_output .setEnabled(false);
txt_meld.setText("No address with an available amount found.");
}
}
}
catch(Exception e) {e.printStackTrace();};
}
} |
14991_9 | package com.novi.gymmanagementapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GymManagementApiApplication {
public static void main(String[] args) {
SpringApplication.run(GymManagementApiApplication.class, args);
}
//todo • 1. Technisch ontwerp schrijven ============================================================================
//Bevat een titelblad, inleiding en inhoudsopgave. In het documenten zitten geen verwijzingen naar afbeeldingen en informatie buiten het document zelf.
//Beschrijft het probleem en de manier waarop deze applicatie dat probleem oplost.
//Beschrijft wat de applicatie moet kunnen middels een sommering van 25 functionele en niet functionele eisen.
//Bevat één klassendiagram van alle entiteiten. Dit klassendiagram is taal- en platformafhankelijk en hoeft geen methodes te bevatten.
//todo • Bevat minimaal twee volledig uitgewerkte sequentiediagrammen waarin alle architecturale lagen (controller, service, repository) voorkomen. Zorg ervoor dat deze diagrammen klasse- en methodenamen bevatten.
//==================================================================================================================
//2. Verantwoordingsdocument in PDF ================================================================================
//Minimaal 5 beargumenteerde technische keuzes.
//Een beschrijving van minimaal 5 limitaties van de applicatie en beargumentatie van de mogelijke doorontwikkelingen.
//Een link naar jouw project op Github.
//==================================================================================================================
//todo • 3. Broncode Spring Boot ===================================================================================
//Het is een REST-ful webservice die data beheert via endpoints.
//De applicatie is beveiligd en bevat minimaal 2 en maximaal 3 user-rollen met verschillende mogelijkheden.
//De applicatie en database zijn onafhankelijk van elkaar waardoor het mogelijk is om eventueel naar een ander database systeem te wisselen (zoals MySQL, PostgreSQL, SQLite).
//Communicatie met de database vindt plaats door middel van repositories. De database kan in de vorm van CRUD operaties of complexere, samengestelde, queries bevraagd worden.
//De database is relationeel en bevat minimaal een 1 one-to-one relatie en 1 one-to-many relatie.
//De applicatie maakt het mogelijk om bestanden (zoals muziek, PDF’s of afbeeldingen) te uploaden en te downloaden. (huiswerk les van 1 november)
//todo • De application context van de applicatie wordt getest met Spring Boot test, WebMvc en JUnit.
//todo • Het systeem wordt geleverd met een valide set aan data en unit-tests worden voorzien van eigen test data.
//==================================================================================================================
//todo • 4. Installatie handleiding ================================================================================
//Een inhoudsopgave en inleiding, met daarin een korte beschrijving van de functionaliteit van de applicatie en de gebruikte technieken.
//Een lijst van benodigdheden om de applicatie te kunnen runnen (zoals applicaties, runtime environments of andere benodigdheden.
//Een stappenplan met installatie instructies.
//Een lijst met (test)gebruikers en user-rollen.
//Een Postman collectie, die gebruikt kan worden om jouw applicatie te testen.
//todo • Een lijst van REST-endpoints, inclusief voorbeelden van de JSON-requests. Deze voorbeelden moeten uitgeschreven zijn zoals in Postman, zodat je ze gemakkelijk kunt selecteren, kopiëren en plakken. Hierin leg je ook uit hoe de endpoints beveiligd zijn.
}
| MrPeanutButterz/GymManagementApi | src/main/java/com/novi/gymmanagementapi/GymManagementApiApplication.java | 999 | //Een link naar jouw project op Github. | line_comment | nl | package com.novi.gymmanagementapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GymManagementApiApplication {
public static void main(String[] args) {
SpringApplication.run(GymManagementApiApplication.class, args);
}
//todo • 1. Technisch ontwerp schrijven ============================================================================
//Bevat een titelblad, inleiding en inhoudsopgave. In het documenten zitten geen verwijzingen naar afbeeldingen en informatie buiten het document zelf.
//Beschrijft het probleem en de manier waarop deze applicatie dat probleem oplost.
//Beschrijft wat de applicatie moet kunnen middels een sommering van 25 functionele en niet functionele eisen.
//Bevat één klassendiagram van alle entiteiten. Dit klassendiagram is taal- en platformafhankelijk en hoeft geen methodes te bevatten.
//todo • Bevat minimaal twee volledig uitgewerkte sequentiediagrammen waarin alle architecturale lagen (controller, service, repository) voorkomen. Zorg ervoor dat deze diagrammen klasse- en methodenamen bevatten.
//==================================================================================================================
//2. Verantwoordingsdocument in PDF ================================================================================
//Minimaal 5 beargumenteerde technische keuzes.
//Een beschrijving van minimaal 5 limitaties van de applicatie en beargumentatie van de mogelijke doorontwikkelingen.
//Een link<SUF>
//==================================================================================================================
//todo • 3. Broncode Spring Boot ===================================================================================
//Het is een REST-ful webservice die data beheert via endpoints.
//De applicatie is beveiligd en bevat minimaal 2 en maximaal 3 user-rollen met verschillende mogelijkheden.
//De applicatie en database zijn onafhankelijk van elkaar waardoor het mogelijk is om eventueel naar een ander database systeem te wisselen (zoals MySQL, PostgreSQL, SQLite).
//Communicatie met de database vindt plaats door middel van repositories. De database kan in de vorm van CRUD operaties of complexere, samengestelde, queries bevraagd worden.
//De database is relationeel en bevat minimaal een 1 one-to-one relatie en 1 one-to-many relatie.
//De applicatie maakt het mogelijk om bestanden (zoals muziek, PDF’s of afbeeldingen) te uploaden en te downloaden. (huiswerk les van 1 november)
//todo • De application context van de applicatie wordt getest met Spring Boot test, WebMvc en JUnit.
//todo • Het systeem wordt geleverd met een valide set aan data en unit-tests worden voorzien van eigen test data.
//==================================================================================================================
//todo • 4. Installatie handleiding ================================================================================
//Een inhoudsopgave en inleiding, met daarin een korte beschrijving van de functionaliteit van de applicatie en de gebruikte technieken.
//Een lijst van benodigdheden om de applicatie te kunnen runnen (zoals applicaties, runtime environments of andere benodigdheden.
//Een stappenplan met installatie instructies.
//Een lijst met (test)gebruikers en user-rollen.
//Een Postman collectie, die gebruikt kan worden om jouw applicatie te testen.
//todo • Een lijst van REST-endpoints, inclusief voorbeelden van de JSON-requests. Deze voorbeelden moeten uitgeschreven zijn zoals in Postman, zodat je ze gemakkelijk kunt selecteren, kopiëren en plakken. Hierin leg je ook uit hoe de endpoints beveiligd zijn.
}
|
27994_8 | package de.golfgl.lightblocks;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.pay.PurchaseManager;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.I18NBundle;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import de.golfgl.gdxgameanalytics.GameAnalytics;
import de.golfgl.gdxgamesvcs.IGameServiceClient;
import de.golfgl.gdxgamesvcs.IGameServiceListener;
import de.golfgl.gdxgamesvcs.gamestate.ILoadGameStateResponseListener;
import de.golfgl.gdxpushmessages.IPushMessageListener;
import de.golfgl.gdxpushmessages.IPushMessageProvider;
import de.golfgl.lightblocks.backend.BackendManager;
import de.golfgl.lightblocks.gpgs.GaHelper;
import de.golfgl.lightblocks.gpgs.IMultiplayerGsClient;
import de.golfgl.lightblocks.menu.MultiplayerMenuScreen;
import de.golfgl.lightblocks.model.Mission;
import de.golfgl.lightblocks.model.TutorialModel;
import de.golfgl.lightblocks.multiplayer.AbstractMultiplayerRoom;
import de.golfgl.lightblocks.multiplayer.INsdHelper;
import de.golfgl.lightblocks.screen.AbstractScreen;
import de.golfgl.lightblocks.screen.MainMenuScreen;
import de.golfgl.lightblocks.screen.PlayScreen;
import de.golfgl.lightblocks.input.PlayScreenInput;
import de.golfgl.lightblocks.screen.VetoException;
import de.golfgl.lightblocks.state.GameStateHandler;
import de.golfgl.lightblocks.state.LocalPrefs;
import de.golfgl.lightblocks.state.MyControllerMapping;
import de.golfgl.lightblocks.state.Player;
import de.golfgl.lightblocks.state.Theme;
import static com.badlogic.gdx.Gdx.app;
public class LightBlocksGame extends Game implements IGameServiceListener, IPushMessageListener {
public static final int nativeGameWidth = 480;
public static final int nativeGameHeight = 800;
public static final float menuLandscapeHeight = nativeGameHeight * .8f;
public static final String GAME_URL_SHORT = "http://bit.ly/2lrP1zq";
public static final String GAME_EMAIL = "[email protected]";
public static final String GAME_URL = "https://www.golfgl.de/lightblocks/";
public static final String SOURCECODE_URL = "https://github.com/MrStahlfelge/lightblocks/";
public static final String CONTROLLER_RECOMMENDATION_URL = "https://www.golfgl.de/lightblocks/#controller";
// An den gleichen Eintrag im AndroidManifest und robovm.properties denken!!!
public static final int GAME_VERSIONNUMBER = 2112;
public static final String GAME_VERSIONSTRING = "1.5." + GAME_VERSIONNUMBER;
// Abstand für Git
// auch dran denken das data-Verzeichnis beim release wegzunehmen!
public static final boolean GAME_DEVMODE = true;
public static final String SKIN_DEFAULT = "default";
public static final String SKIN_FONT_TITLE = "bigbigoutline";
public static final String SKIN_EDIT_BIG = "editbig";
public static final String SKIN_FONT_BIG = "big";
public static final String SKIN_FONT_REG = "qs25";
public static final String SKIN_WINDOW_FRAMELESS = "frameless";
public static final String SKIN_WINDOW_OVERLAY = "overlay";
public static final String SKIN_WINDOW_ALLBLACK = "fullsize";
public static final String SKIN_BUTTON_ROUND = "round";
public static final String SKIN_BUTTON_CHECKBOX = "checkbox";
public static final String SKIN_BUTTON_SMOKE = "smoke";
public static final String SKIN_BUTTON_WELCOME = "welcome";
public static final String SKIN_BUTTON_GAMEPAD = "gamepad";
public static final String SKIN_TOUCHPAD_DPAD = "dpad";
public static final String SKIN_STYLE_PAGER = "pager";
public static final String SKIN_LIST = "list";
public static final float LABEL_SCALING = .65f;
public static final float ICON_SCALE_MENU = 1f;
public static String gameStoreUrl;
public static Color EMPHASIZE_COLOR;
public static Color COLOR_DISABLED;
public static Color COLOR_UNSELECTED;
public static Color COLOR_FOCUSSED_ACTOR;
// Android Modellname des Geräts
public static String modelNameRunningOn;
public Skin skin;
public Theme theme;
public AssetManager assetManager;
public I18NBundle TEXTS;
public LocalPrefs localPrefs;
public GameStateHandler savegame;
public BackendManager backendManager;
// these resources are used in the whole game... so we are loading them here
public TextureRegion trBlock;
public TextureRegion trGhostBlock;
public TextureRegion trBlockEnlightened;
public TextureRegion trGlowingLine;
public TextureRegion trPreviewOsb;
public TextureRegion trPreviewOsg;
public Sound dropSound;
public Sound rotateSound;
public Sound removeSound;
public Sound gameOverSound;
public Sound cleanSpecialSound;
public Sound cleanFreezedSound;
public Sound freezeBeginSound;
public Sound unlockedSound;
public Sound swoshSound;
public Sound garbageSound;
public ShareHandler share;
public AbstractMultiplayerRoom multiRoom;
public Player player;
public IGameServiceClient gpgsClient;
public MainMenuScreen mainMenuScreen;
public INsdHelper nsdHelper;
public MyControllerMapping controllerMappings;
public GameAnalytics gameAnalytics;
public PurchaseManager purchaseManager;
public IPushMessageProvider pushMessageProvider;
private FPSLogger fpsLogger;
private List<Mission> missionList;
private HashMap<String, Mission> missionMap;
private boolean openWeblinks = true;
/**
* @return true wenn das ganze auf einem Smartphone/Tablet im Webbrowser läuft
*/
public static boolean isWebAppOnMobileDevice() {
return Gdx.app.getType().equals(Application.ApplicationType.WebGL) &&
!Gdx.input.isPeripheralAvailable(Input.Peripheral.HardwareKeyboard);
}
/**
* @return true wenn (wahrscheinlich) auf FireTV/AndroidTV
*/
public static boolean isOnAndroidTV() {
return Gdx.app.getType().equals(Application.ApplicationType.Android) &&
!Gdx.input.isPeripheralAvailable(Input.Peripheral.MultitouchScreen);
}
/**
* @return true wenn auf Amazon FireTV
*/
public static boolean isOnFireTv() {
return isOnAndroidTV() && modelNameRunningOn != null && modelNameRunningOn.startsWith("AFT");
}
@Override
public void create() {
if (GAME_DEVMODE) {
fpsLogger = new FPSLogger();
Gdx.app.setLogLevel(Application.LOG_INFO);
} else {
Gdx.app.setLogLevel(Application.LOG_ERROR);
}
Preferences lbPrefs = app.getPreferences("lightblocks");
localPrefs = new LocalPrefs(lbPrefs);
// bevor gpgs angemeldet wird (wegen Cloud save)
backendManager = new BackendManager(localPrefs);
if (pushMessageProvider != null && backendManager.hasUserId())
pushMessageProvider.initService(this);
if (share == null)
share = new ShareHandler();
initGameAnalytics(lbPrefs);
player = new MyOwnPlayer();
savegame = new GameStateHandler(this, lbPrefs);
// GPGS: Wenn beim letzten Mal angemeldet, dann wieder anmelden
if (gpgsClient != null) {
gpgsClient.setListener(this);
if (localPrefs.getGpgsAutoLogin())
gpgsClient.resumeSession();
}
I18NBundle.setSimpleFormatter(true);
loadAndInitAssets();
try {
controllerMappings = new MyControllerMapping(this);
Controllers.addListener(controllerMappings.controllerToInputAdapter);
} catch (Throwable t) {
Gdx.app.error("Application", "Controllers not instantiated", t);
}
mainMenuScreen = new MainMenuScreen(this);
// Replay-Modus wurde gestartet => hier dann nix weiter tun
if (shouldGoToReplay())
return;
// In Tutorial, wenn Spiel das erste Mal gestartet, Touchscreen und keine Tastatur/Controller vorhanden
if (savegame.hasGameState() || !TutorialModel.tutorialAvailable() ||
PlayScreenInput.isInputTypeAvailable(PlayScreenInput.KEY_KEYSORGAMEPAD))
this.setScreen(mainMenuScreen);
else {
// beim ersten Mal ins Tutorial (nur für Touchinput)!
try {
PlayScreen ps = PlayScreen.gotoPlayScreen(this, TutorialModel.getTutorialInitParams());
ps.setShowScoresWhenGameOver(false);
ps.setBackScreen(mainMenuScreen);
} catch (VetoException e) {
this.setScreen(mainMenuScreen);
}
}
}
protected boolean shouldGoToReplay() {
return false;
}
protected void initGameAnalytics(Preferences lbPrefs) {
if (gameAnalytics == null) {
gameAnalytics = new GameAnalytics();
gameAnalytics.setPlatformVersionString("1");
}
gameAnalytics.setGameBuildNumber(GAME_DEVMODE ? "debug" : String.valueOf(GAME_VERSIONNUMBER));
gameAnalytics.setCustom1(Gdx.input.isPeripheralAvailable(Input.Peripheral.MultitouchScreen) ?
"withTouch" : "noTouch");
gameAnalytics.setPrefs(lbPrefs);
gameAnalytics.setGameKey(GaHelper.GA_APP_KEY);
gameAnalytics.setGameSecretKey(GaHelper.GA_SECRET_KEY);
gameAnalytics.startSession();
}
public String getSoundAssetFilename(String name) {
//overriden for iOS
return "sound/" + name + ".ogg";
}
private void loadAndInitAssets() {
assetManager = new AssetManager();
// den Sound als erstes und danach finish, damit er möglichst auf allen Geräten rechtzeitig zur Verfügung steht
assetManager.load(getSoundAssetFilename("cleanspecial"), Sound.class);
assetManager.finishLoading();
assetManager.load(getSoundAssetFilename("cleanfreeze"), Sound.class);
assetManager.load(getSoundAssetFilename("swosh"), Sound.class);
assetManager.load("i18n/strings", I18NBundle.class);
assetManager.load(getSoundAssetFilename("switchon"), Sound.class);
assetManager.load(getSoundAssetFilename("switchflip"), Sound.class);
assetManager.load(getSoundAssetFilename("glow05"), Sound.class);
assetManager.load(getSoundAssetFilename("gameover"), Sound.class);
assetManager.load(getSoundAssetFilename("unlocked"), Sound.class);
assetManager.load(getSoundAssetFilename("garbage"), Sound.class);
assetManager.load(getSoundAssetFilename("freezestart"), Sound.class);
assetManager.load("skin/lb.json", Skin.class);
assetManager.finishLoading();
skin = assetManager.get("skin/lb.json", Skin.class);
TEXTS = assetManager.get("i18n/strings", I18NBundle.class);
trBlock = skin.getRegion("block-deactivated");
trGhostBlock = skin.getRegion("block-ghost");
trBlockEnlightened = skin.getRegion("block-light");
trGlowingLine = skin.getRegion("lineglow");
dropSound = assetManager.get(getSoundAssetFilename("switchon"), Sound.class);
rotateSound = assetManager.get(getSoundAssetFilename("switchflip"), Sound.class);
removeSound = assetManager.get(getSoundAssetFilename("glow05"), Sound.class);
gameOverSound = assetManager.get(getSoundAssetFilename("gameover"), Sound.class);
unlockedSound = assetManager.get(getSoundAssetFilename("unlocked"), Sound.class);
garbageSound = assetManager.get(getSoundAssetFilename("garbage"), Sound.class);
cleanSpecialSound = assetManager.get(getSoundAssetFilename("cleanspecial"), Sound.class);
cleanFreezedSound = assetManager.get(getSoundAssetFilename("cleanfreeze"), Sound.class);
freezeBeginSound = assetManager.get(getSoundAssetFilename("freezestart"), Sound.class);
swoshSound = assetManager.get(getSoundAssetFilename("swosh"), Sound.class);
trPreviewOsb = skin.getRegion("playscreen-osb");
trPreviewOsg = skin.getRegion("playscreen-osg");
COLOR_DISABLED = skin.getColor("disabled");
COLOR_FOCUSSED_ACTOR = skin.getColor("lightselection");
COLOR_UNSELECTED = skin.getColor("unselected");
EMPHASIZE_COLOR = skin.getColor("emphasize");
skin.get(SKIN_FONT_TITLE, Label.LabelStyle.class).font.setFixedWidthGlyphs("0123456789-+X");
skin.get(SKIN_FONT_TITLE, Label.LabelStyle.class).font.setUseIntegerPositions(false);
// Theme aktiviert?
theme = new Theme(this);
}
@Override
public void render() {
super.render(); //important!
if (GAME_DEVMODE && fpsLogger != null)
fpsLogger.log();
}
@Override
public void pause() {
super.pause();
if (gpgsClient != null)
gpgsClient.pauseSession();
if (gameAnalytics != null)
gameAnalytics.closeSession();
}
@Override
public void resume() {
super.resume();
if (localPrefs.getGpgsAutoLogin() && gpgsClient != null && !gpgsClient.isSessionActive())
gpgsClient.resumeSession();
if (gameAnalytics != null)
gameAnalytics.startSession();
backendManager.sendEnqueuedScores();
}
@Override
public void dispose() {
if (multiRoom != null)
try {
multiRoom.leaveRoom(true);
} catch (VetoException e) {
e.printStackTrace();
}
mainMenuScreen.dispose();
skin.dispose();
if (purchaseManager != null) {
purchaseManager.dispose();
}
}
@Override
public void gsOnSessionActive() {
localPrefs.setGpgsAutoLogin(true);
handleAccountChanged();
}
private void handleAccountChanged() {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
mainMenuScreen.refreshAccountInfo();
//beim ersten Connect Spielstand laden (wenn vorhanden)
// War zuerst in GpgsConnect, es wurde aber der allerste Login nicht mehr automatisch gesetzt.
// (obwohl das Willkommen... Schild kam)
// Nun in UI Thread verlagert
if (!savegame.isAlreadyLoadedFromCloud() && gpgsClient.isSessionActive())
gpgsClient.loadGameState(IMultiplayerGsClient.NAME_SAVE_GAMESTATE,
new ILoadGameStateResponseListener() {
@Override
public void gsGameStateLoaded(byte[] gameState) {
savegame.mergeGameServiceSaveData(gameState);
}
});
}
});
}
@Override
public void gsOnSessionInactive() {
handleAccountChanged();
}
@Override
public void gsShowErrorToUser(GsErrorType errType, final String msg, Throwable t) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
Screen currentScreen = getScreen();
if (currentScreen instanceof AbstractScreen)
((AbstractScreen) currentScreen).showDialog(msg);
}
});
}
public List<Mission> getMissionList() {
if (missionList == null) {
missionList = Mission.getMissionList();
// Hashmap aufbauen
missionMap = new HashMap<String, Mission>(missionList.size());
for (Mission mission : missionList)
missionMap.put(mission.getUniqueId(), mission);
}
return missionList;
}
public Mission getMissionFromUid(String uid) {
if (missionMap == null)
getMissionList();
return missionMap.get(uid);
}
/**
* locks the orientation on Android/IOS to portrait, landscape or current
*
* @param orientation, oder null um auf den aktuellen zu sperren
* @return true, wenn gleichzeitig auch eine Drehung erzwungen wurde.
* false, wenn noch auf falscher Orientation steht
*/
public boolean lockOrientation(Input.Orientation orientation) {
return Gdx.input.getNativeOrientation().equals(orientation);
}
/**
* unlocks the orientation
*/
public void unlockOrientation() {
}
/**
* @return ob es erlaubt ist, Weblinks zu öffnen (=> Android TV)
*/
public boolean allowOpenWeblinks() {
return openWeblinks;
}
public void setOpenWeblinks(boolean openWeblinks) {
this.openWeblinks = openWeblinks;
}
public boolean canDonate() {
return purchaseManager != null;
}
public MultiplayerMenuScreen getNewMultiplayerMenu(Group actorToHide) {
return new MultiplayerMenuScreen(this, actorToHide);
}
/**
* URI öffnen, wenn möglich. Falls nicht möglich, Hinweisdialog zeigen
*
* @param uri
*/
public void openOrShowUri(String uri) {
boolean success = false;
if (allowOpenWeblinks())
success = Gdx.net.openURI(uri);
if (!success) {
((AbstractScreen) getScreen()).showDialog(TEXTS.format("errorOpenUri", uri));
}
}
public float getDisplayDensityRatio() {
return 1f;
}
public boolean supportsRealTimeMultiplayer() {
return false;
}
@Override
public void onRegistrationTokenRetrieved(String token) {
localPrefs.setPushToken(token);
}
@Override
public void onPushMessageArrived(String payload) {
if (backendManager.hasUserId() && payload != null
&& payload.startsWith(BackendManager.PUSH_PAYLOAD_MULTIPLAYER)) {
backendManager.invalidateCachedMatches();
backendManager.setCompetitionNewsAvailableFlag(true);
}
}
public boolean canInstallTheme() {
return false;
}
public void doInstallTheme(InputStream zipFile) {
}
private class MyOwnPlayer extends Player {
@Override
public String getGamerId() {
if (backendManager.hasUserId() && localPrefs.getBackendNickname() != null)
return localPrefs.getBackendNickname();
else if (gpgsClient != null && gpgsClient.getPlayerDisplayName() != null)
return gpgsClient.getPlayerDisplayName();
else
return modelNameRunningOn;
}
}
}
| MrStahlfelge/lightblocks | core/src/de/golfgl/lightblocks/LightBlocksGame.java | 5,601 | // bevor gpgs angemeldet wird (wegen Cloud save) | line_comment | nl | package de.golfgl.lightblocks;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.pay.PurchaseManager;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.I18NBundle;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import de.golfgl.gdxgameanalytics.GameAnalytics;
import de.golfgl.gdxgamesvcs.IGameServiceClient;
import de.golfgl.gdxgamesvcs.IGameServiceListener;
import de.golfgl.gdxgamesvcs.gamestate.ILoadGameStateResponseListener;
import de.golfgl.gdxpushmessages.IPushMessageListener;
import de.golfgl.gdxpushmessages.IPushMessageProvider;
import de.golfgl.lightblocks.backend.BackendManager;
import de.golfgl.lightblocks.gpgs.GaHelper;
import de.golfgl.lightblocks.gpgs.IMultiplayerGsClient;
import de.golfgl.lightblocks.menu.MultiplayerMenuScreen;
import de.golfgl.lightblocks.model.Mission;
import de.golfgl.lightblocks.model.TutorialModel;
import de.golfgl.lightblocks.multiplayer.AbstractMultiplayerRoom;
import de.golfgl.lightblocks.multiplayer.INsdHelper;
import de.golfgl.lightblocks.screen.AbstractScreen;
import de.golfgl.lightblocks.screen.MainMenuScreen;
import de.golfgl.lightblocks.screen.PlayScreen;
import de.golfgl.lightblocks.input.PlayScreenInput;
import de.golfgl.lightblocks.screen.VetoException;
import de.golfgl.lightblocks.state.GameStateHandler;
import de.golfgl.lightblocks.state.LocalPrefs;
import de.golfgl.lightblocks.state.MyControllerMapping;
import de.golfgl.lightblocks.state.Player;
import de.golfgl.lightblocks.state.Theme;
import static com.badlogic.gdx.Gdx.app;
public class LightBlocksGame extends Game implements IGameServiceListener, IPushMessageListener {
public static final int nativeGameWidth = 480;
public static final int nativeGameHeight = 800;
public static final float menuLandscapeHeight = nativeGameHeight * .8f;
public static final String GAME_URL_SHORT = "http://bit.ly/2lrP1zq";
public static final String GAME_EMAIL = "[email protected]";
public static final String GAME_URL = "https://www.golfgl.de/lightblocks/";
public static final String SOURCECODE_URL = "https://github.com/MrStahlfelge/lightblocks/";
public static final String CONTROLLER_RECOMMENDATION_URL = "https://www.golfgl.de/lightblocks/#controller";
// An den gleichen Eintrag im AndroidManifest und robovm.properties denken!!!
public static final int GAME_VERSIONNUMBER = 2112;
public static final String GAME_VERSIONSTRING = "1.5." + GAME_VERSIONNUMBER;
// Abstand für Git
// auch dran denken das data-Verzeichnis beim release wegzunehmen!
public static final boolean GAME_DEVMODE = true;
public static final String SKIN_DEFAULT = "default";
public static final String SKIN_FONT_TITLE = "bigbigoutline";
public static final String SKIN_EDIT_BIG = "editbig";
public static final String SKIN_FONT_BIG = "big";
public static final String SKIN_FONT_REG = "qs25";
public static final String SKIN_WINDOW_FRAMELESS = "frameless";
public static final String SKIN_WINDOW_OVERLAY = "overlay";
public static final String SKIN_WINDOW_ALLBLACK = "fullsize";
public static final String SKIN_BUTTON_ROUND = "round";
public static final String SKIN_BUTTON_CHECKBOX = "checkbox";
public static final String SKIN_BUTTON_SMOKE = "smoke";
public static final String SKIN_BUTTON_WELCOME = "welcome";
public static final String SKIN_BUTTON_GAMEPAD = "gamepad";
public static final String SKIN_TOUCHPAD_DPAD = "dpad";
public static final String SKIN_STYLE_PAGER = "pager";
public static final String SKIN_LIST = "list";
public static final float LABEL_SCALING = .65f;
public static final float ICON_SCALE_MENU = 1f;
public static String gameStoreUrl;
public static Color EMPHASIZE_COLOR;
public static Color COLOR_DISABLED;
public static Color COLOR_UNSELECTED;
public static Color COLOR_FOCUSSED_ACTOR;
// Android Modellname des Geräts
public static String modelNameRunningOn;
public Skin skin;
public Theme theme;
public AssetManager assetManager;
public I18NBundle TEXTS;
public LocalPrefs localPrefs;
public GameStateHandler savegame;
public BackendManager backendManager;
// these resources are used in the whole game... so we are loading them here
public TextureRegion trBlock;
public TextureRegion trGhostBlock;
public TextureRegion trBlockEnlightened;
public TextureRegion trGlowingLine;
public TextureRegion trPreviewOsb;
public TextureRegion trPreviewOsg;
public Sound dropSound;
public Sound rotateSound;
public Sound removeSound;
public Sound gameOverSound;
public Sound cleanSpecialSound;
public Sound cleanFreezedSound;
public Sound freezeBeginSound;
public Sound unlockedSound;
public Sound swoshSound;
public Sound garbageSound;
public ShareHandler share;
public AbstractMultiplayerRoom multiRoom;
public Player player;
public IGameServiceClient gpgsClient;
public MainMenuScreen mainMenuScreen;
public INsdHelper nsdHelper;
public MyControllerMapping controllerMappings;
public GameAnalytics gameAnalytics;
public PurchaseManager purchaseManager;
public IPushMessageProvider pushMessageProvider;
private FPSLogger fpsLogger;
private List<Mission> missionList;
private HashMap<String, Mission> missionMap;
private boolean openWeblinks = true;
/**
* @return true wenn das ganze auf einem Smartphone/Tablet im Webbrowser läuft
*/
public static boolean isWebAppOnMobileDevice() {
return Gdx.app.getType().equals(Application.ApplicationType.WebGL) &&
!Gdx.input.isPeripheralAvailable(Input.Peripheral.HardwareKeyboard);
}
/**
* @return true wenn (wahrscheinlich) auf FireTV/AndroidTV
*/
public static boolean isOnAndroidTV() {
return Gdx.app.getType().equals(Application.ApplicationType.Android) &&
!Gdx.input.isPeripheralAvailable(Input.Peripheral.MultitouchScreen);
}
/**
* @return true wenn auf Amazon FireTV
*/
public static boolean isOnFireTv() {
return isOnAndroidTV() && modelNameRunningOn != null && modelNameRunningOn.startsWith("AFT");
}
@Override
public void create() {
if (GAME_DEVMODE) {
fpsLogger = new FPSLogger();
Gdx.app.setLogLevel(Application.LOG_INFO);
} else {
Gdx.app.setLogLevel(Application.LOG_ERROR);
}
Preferences lbPrefs = app.getPreferences("lightblocks");
localPrefs = new LocalPrefs(lbPrefs);
// bevor gpgs<SUF>
backendManager = new BackendManager(localPrefs);
if (pushMessageProvider != null && backendManager.hasUserId())
pushMessageProvider.initService(this);
if (share == null)
share = new ShareHandler();
initGameAnalytics(lbPrefs);
player = new MyOwnPlayer();
savegame = new GameStateHandler(this, lbPrefs);
// GPGS: Wenn beim letzten Mal angemeldet, dann wieder anmelden
if (gpgsClient != null) {
gpgsClient.setListener(this);
if (localPrefs.getGpgsAutoLogin())
gpgsClient.resumeSession();
}
I18NBundle.setSimpleFormatter(true);
loadAndInitAssets();
try {
controllerMappings = new MyControllerMapping(this);
Controllers.addListener(controllerMappings.controllerToInputAdapter);
} catch (Throwable t) {
Gdx.app.error("Application", "Controllers not instantiated", t);
}
mainMenuScreen = new MainMenuScreen(this);
// Replay-Modus wurde gestartet => hier dann nix weiter tun
if (shouldGoToReplay())
return;
// In Tutorial, wenn Spiel das erste Mal gestartet, Touchscreen und keine Tastatur/Controller vorhanden
if (savegame.hasGameState() || !TutorialModel.tutorialAvailable() ||
PlayScreenInput.isInputTypeAvailable(PlayScreenInput.KEY_KEYSORGAMEPAD))
this.setScreen(mainMenuScreen);
else {
// beim ersten Mal ins Tutorial (nur für Touchinput)!
try {
PlayScreen ps = PlayScreen.gotoPlayScreen(this, TutorialModel.getTutorialInitParams());
ps.setShowScoresWhenGameOver(false);
ps.setBackScreen(mainMenuScreen);
} catch (VetoException e) {
this.setScreen(mainMenuScreen);
}
}
}
protected boolean shouldGoToReplay() {
return false;
}
protected void initGameAnalytics(Preferences lbPrefs) {
if (gameAnalytics == null) {
gameAnalytics = new GameAnalytics();
gameAnalytics.setPlatformVersionString("1");
}
gameAnalytics.setGameBuildNumber(GAME_DEVMODE ? "debug" : String.valueOf(GAME_VERSIONNUMBER));
gameAnalytics.setCustom1(Gdx.input.isPeripheralAvailable(Input.Peripheral.MultitouchScreen) ?
"withTouch" : "noTouch");
gameAnalytics.setPrefs(lbPrefs);
gameAnalytics.setGameKey(GaHelper.GA_APP_KEY);
gameAnalytics.setGameSecretKey(GaHelper.GA_SECRET_KEY);
gameAnalytics.startSession();
}
public String getSoundAssetFilename(String name) {
//overriden for iOS
return "sound/" + name + ".ogg";
}
private void loadAndInitAssets() {
assetManager = new AssetManager();
// den Sound als erstes und danach finish, damit er möglichst auf allen Geräten rechtzeitig zur Verfügung steht
assetManager.load(getSoundAssetFilename("cleanspecial"), Sound.class);
assetManager.finishLoading();
assetManager.load(getSoundAssetFilename("cleanfreeze"), Sound.class);
assetManager.load(getSoundAssetFilename("swosh"), Sound.class);
assetManager.load("i18n/strings", I18NBundle.class);
assetManager.load(getSoundAssetFilename("switchon"), Sound.class);
assetManager.load(getSoundAssetFilename("switchflip"), Sound.class);
assetManager.load(getSoundAssetFilename("glow05"), Sound.class);
assetManager.load(getSoundAssetFilename("gameover"), Sound.class);
assetManager.load(getSoundAssetFilename("unlocked"), Sound.class);
assetManager.load(getSoundAssetFilename("garbage"), Sound.class);
assetManager.load(getSoundAssetFilename("freezestart"), Sound.class);
assetManager.load("skin/lb.json", Skin.class);
assetManager.finishLoading();
skin = assetManager.get("skin/lb.json", Skin.class);
TEXTS = assetManager.get("i18n/strings", I18NBundle.class);
trBlock = skin.getRegion("block-deactivated");
trGhostBlock = skin.getRegion("block-ghost");
trBlockEnlightened = skin.getRegion("block-light");
trGlowingLine = skin.getRegion("lineglow");
dropSound = assetManager.get(getSoundAssetFilename("switchon"), Sound.class);
rotateSound = assetManager.get(getSoundAssetFilename("switchflip"), Sound.class);
removeSound = assetManager.get(getSoundAssetFilename("glow05"), Sound.class);
gameOverSound = assetManager.get(getSoundAssetFilename("gameover"), Sound.class);
unlockedSound = assetManager.get(getSoundAssetFilename("unlocked"), Sound.class);
garbageSound = assetManager.get(getSoundAssetFilename("garbage"), Sound.class);
cleanSpecialSound = assetManager.get(getSoundAssetFilename("cleanspecial"), Sound.class);
cleanFreezedSound = assetManager.get(getSoundAssetFilename("cleanfreeze"), Sound.class);
freezeBeginSound = assetManager.get(getSoundAssetFilename("freezestart"), Sound.class);
swoshSound = assetManager.get(getSoundAssetFilename("swosh"), Sound.class);
trPreviewOsb = skin.getRegion("playscreen-osb");
trPreviewOsg = skin.getRegion("playscreen-osg");
COLOR_DISABLED = skin.getColor("disabled");
COLOR_FOCUSSED_ACTOR = skin.getColor("lightselection");
COLOR_UNSELECTED = skin.getColor("unselected");
EMPHASIZE_COLOR = skin.getColor("emphasize");
skin.get(SKIN_FONT_TITLE, Label.LabelStyle.class).font.setFixedWidthGlyphs("0123456789-+X");
skin.get(SKIN_FONT_TITLE, Label.LabelStyle.class).font.setUseIntegerPositions(false);
// Theme aktiviert?
theme = new Theme(this);
}
@Override
public void render() {
super.render(); //important!
if (GAME_DEVMODE && fpsLogger != null)
fpsLogger.log();
}
@Override
public void pause() {
super.pause();
if (gpgsClient != null)
gpgsClient.pauseSession();
if (gameAnalytics != null)
gameAnalytics.closeSession();
}
@Override
public void resume() {
super.resume();
if (localPrefs.getGpgsAutoLogin() && gpgsClient != null && !gpgsClient.isSessionActive())
gpgsClient.resumeSession();
if (gameAnalytics != null)
gameAnalytics.startSession();
backendManager.sendEnqueuedScores();
}
@Override
public void dispose() {
if (multiRoom != null)
try {
multiRoom.leaveRoom(true);
} catch (VetoException e) {
e.printStackTrace();
}
mainMenuScreen.dispose();
skin.dispose();
if (purchaseManager != null) {
purchaseManager.dispose();
}
}
@Override
public void gsOnSessionActive() {
localPrefs.setGpgsAutoLogin(true);
handleAccountChanged();
}
private void handleAccountChanged() {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
mainMenuScreen.refreshAccountInfo();
//beim ersten Connect Spielstand laden (wenn vorhanden)
// War zuerst in GpgsConnect, es wurde aber der allerste Login nicht mehr automatisch gesetzt.
// (obwohl das Willkommen... Schild kam)
// Nun in UI Thread verlagert
if (!savegame.isAlreadyLoadedFromCloud() && gpgsClient.isSessionActive())
gpgsClient.loadGameState(IMultiplayerGsClient.NAME_SAVE_GAMESTATE,
new ILoadGameStateResponseListener() {
@Override
public void gsGameStateLoaded(byte[] gameState) {
savegame.mergeGameServiceSaveData(gameState);
}
});
}
});
}
@Override
public void gsOnSessionInactive() {
handleAccountChanged();
}
@Override
public void gsShowErrorToUser(GsErrorType errType, final String msg, Throwable t) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
Screen currentScreen = getScreen();
if (currentScreen instanceof AbstractScreen)
((AbstractScreen) currentScreen).showDialog(msg);
}
});
}
public List<Mission> getMissionList() {
if (missionList == null) {
missionList = Mission.getMissionList();
// Hashmap aufbauen
missionMap = new HashMap<String, Mission>(missionList.size());
for (Mission mission : missionList)
missionMap.put(mission.getUniqueId(), mission);
}
return missionList;
}
public Mission getMissionFromUid(String uid) {
if (missionMap == null)
getMissionList();
return missionMap.get(uid);
}
/**
* locks the orientation on Android/IOS to portrait, landscape or current
*
* @param orientation, oder null um auf den aktuellen zu sperren
* @return true, wenn gleichzeitig auch eine Drehung erzwungen wurde.
* false, wenn noch auf falscher Orientation steht
*/
public boolean lockOrientation(Input.Orientation orientation) {
return Gdx.input.getNativeOrientation().equals(orientation);
}
/**
* unlocks the orientation
*/
public void unlockOrientation() {
}
/**
* @return ob es erlaubt ist, Weblinks zu öffnen (=> Android TV)
*/
public boolean allowOpenWeblinks() {
return openWeblinks;
}
public void setOpenWeblinks(boolean openWeblinks) {
this.openWeblinks = openWeblinks;
}
public boolean canDonate() {
return purchaseManager != null;
}
public MultiplayerMenuScreen getNewMultiplayerMenu(Group actorToHide) {
return new MultiplayerMenuScreen(this, actorToHide);
}
/**
* URI öffnen, wenn möglich. Falls nicht möglich, Hinweisdialog zeigen
*
* @param uri
*/
public void openOrShowUri(String uri) {
boolean success = false;
if (allowOpenWeblinks())
success = Gdx.net.openURI(uri);
if (!success) {
((AbstractScreen) getScreen()).showDialog(TEXTS.format("errorOpenUri", uri));
}
}
public float getDisplayDensityRatio() {
return 1f;
}
public boolean supportsRealTimeMultiplayer() {
return false;
}
@Override
public void onRegistrationTokenRetrieved(String token) {
localPrefs.setPushToken(token);
}
@Override
public void onPushMessageArrived(String payload) {
if (backendManager.hasUserId() && payload != null
&& payload.startsWith(BackendManager.PUSH_PAYLOAD_MULTIPLAYER)) {
backendManager.invalidateCachedMatches();
backendManager.setCompetitionNewsAvailableFlag(true);
}
}
public boolean canInstallTheme() {
return false;
}
public void doInstallTheme(InputStream zipFile) {
}
private class MyOwnPlayer extends Player {
@Override
public String getGamerId() {
if (backendManager.hasUserId() && localPrefs.getBackendNickname() != null)
return localPrefs.getBackendNickname();
else if (gpgsClient != null && gpgsClient.getPlayerDisplayName() != null)
return gpgsClient.getPlayerDisplayName();
else
return modelNameRunningOn;
}
}
}
|
89830_3 | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Dateiname : Mergesort.java
* Beschreibung : Einsendeaufgabe 2 für den Kurs Algorithmen
*
* @author Tobias Wagner ([email protected])
* @version 1.00, 02.12.2019
*/
// Klasse Mergesort zum Sortieren von Arrays und zum Testen der gegebenen Dateien Rand... und Sort...
// Jeweils mit Anfangs- und Endzeit
public class Mergesort
{
private static String[] testDaten = {"Rand10_1", "Rand10_2", "Rand20_1", "Rand20_2",
"Rand50_1", "Rand50_2", "Rand100_1", "Rand100_2",
"Rand200_1", "Rand200_2", "Rand500_1", "Rand500_1",
"Rand1000_1", "Rand1000_2", "Rand10000_1", "Rand10000_2",
"Rand100000_1", "Rand100000_2", "Sort10_1", "Sort20_1", "Sort50_1", "Sort100_1", "Sort200_1",
"Sort500_1", "Sort1000_1", "Sort10000_1", "Sort100000_1"};
//Deklaration der main Methode
public static void main(String[] args) throws IOException
{
ArrayList<TestErgebnis> ergebnisListe = new ArrayList<>();
for (String testFilename : testDaten) {
// Einlesen des zu bearbeitenden Arrays - Auswahl der Datei mit dem Array
int[] testDatensatz = FileIntArray.FileToIntArray(testFilename);
// Ausgeben des unsortierten Arrays
System.out.println(Arrays.toString(testDatensatz));
// Erfassen der Anfangszeit
double anfangszeit = System.nanoTime();
// Ausführen von mergeSort
mergeSort(testDatensatz, 0, testDatensatz.length - 1);
// Erfassen der Endzeit
double endzeit = System.nanoTime();
// Ausgabe des sortierten Arrays
System.out.println(Arrays.toString(testDatensatz));
// Ausgabe der benötigten Dauer für den Durchlauf von mergeSort
double dauer = endzeit - anfangszeit;
System.out.println("Die benötigte Zeit betraegt: " + dauer + " Nanosekunden");
// Speichern des Testergebnisses in unsere ergebnissliste
TestErgebnis testErgebnis = new TestErgebnis(testFilename, dauer);
ergebnisListe.add(testErgebnis);
}
File datei = new File("Testlaufergebnis.csv");
FileWriter schreiber = new FileWriter(datei);
// CSV Kopzeile
schreiber.write("Testlauf;Zeit\n");
for (TestErgebnis testErg : ergebnisListe) {
schreiber.write(testErg.getTestDataname() + ";" + testErg.getTime() + "\n");
}
schreiber.close();
}
// Rekursive Funktion Mergesort
// Initialisierung Mergesort mit dem eingelesenen Array, dem linken Index, dem rechten Index
private static void mergeSort(int[] datensatz, int indexLinks, int indexRechts)
{
if (indexLinks < indexRechts) {
int mitte = (indexLinks + indexRechts) / 2;
mergeSort(datensatz, indexLinks, mitte);
mergeSort(datensatz, mitte + 1, indexRechts);
merge(datensatz, indexLinks, mitte, indexRechts);
}
}
//Merge - Methode, die in Mergesort aufgerufen wird
private static void merge(int[] datensatz, int l, int m, int r)
{
// H = Hilfsarray, zum Zwischenspeichern, mit der Länge des Arrays A
int hilfsArray[] = new int[datensatz.length];
// definiere i = linker Index, solange i kleiner gleich rechter Index, führe aus und erhöhe i
for (int i = l; i <= r; i++) {
// Zwischenspeichern von Array datensatz[i] nach hilfsarray[i]
hilfsArray[i] = datensatz[i];
}
// Laufzeitvariablen i, j und k für die while - Schleifendurchläufe
int i = l;
int j = m + 1;
int k = l;
// solange i kleiner gleich mittlerer Index UND j kleiner gleich rechter Index,
while (i <= m && j <= r) {
// Kopiere kleineren aktuellen Wert hilfsArray[j] -> datensatz[k] bzw. hilfsArray[i] -> datensatz[k]
// Erhöhe aktuellen Index von Teilarray mit kleinerem Wert
// Erhöhe aktuellen Index von H
// Wenn H an der Stelle i kleiner gleich H an der Stelle J, dann setze H[i] auf A[k] erhöhe i um eins
if (hilfsArray[i] <= hilfsArray[j]) {
datensatz[k] = hilfsArray[i];
i++;
// ansonsten setze H an der Stelle j auf A[k] und erhöhe j um 1
} else {
datensatz[k] = hilfsArray[j];
j++;
}
// Erhöhe k, die Zählvariable des Arrays A um eins,
// um die nächste Position im Array A im kommenden Durchlauf einzufügen
k++;
}
// übertrage Werte des noch nicht vollständig durchlaufenen Teilarrays nach H
// Kopiere H nach A (von Index l bis Index r)
while (i <= m) {
datensatz[k] = hilfsArray[i];
k++;
i++;
}
while (j <= r) {
datensatz[k] = hilfsArray[j];
k++;
j++;
}
}
// Hilfsklasse zum speichern von Testergebnissen
private static class TestErgebnis
{
private final String testDataname;
private final Double time;
public TestErgebnis(String testDataname, Double time)
{
this.testDataname = testDataname;
this.time = time;
}
public String getTestDataname()
{
return testDataname;
}
public Double getTime()
{
return time;
}
}
}
| MrTobiasWagner/s79080ESA010 | Mergesort.java | 1,896 | //Deklaration der main Methode
| line_comment | nl | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Dateiname : Mergesort.java
* Beschreibung : Einsendeaufgabe 2 für den Kurs Algorithmen
*
* @author Tobias Wagner ([email protected])
* @version 1.00, 02.12.2019
*/
// Klasse Mergesort zum Sortieren von Arrays und zum Testen der gegebenen Dateien Rand... und Sort...
// Jeweils mit Anfangs- und Endzeit
public class Mergesort
{
private static String[] testDaten = {"Rand10_1", "Rand10_2", "Rand20_1", "Rand20_2",
"Rand50_1", "Rand50_2", "Rand100_1", "Rand100_2",
"Rand200_1", "Rand200_2", "Rand500_1", "Rand500_1",
"Rand1000_1", "Rand1000_2", "Rand10000_1", "Rand10000_2",
"Rand100000_1", "Rand100000_2", "Sort10_1", "Sort20_1", "Sort50_1", "Sort100_1", "Sort200_1",
"Sort500_1", "Sort1000_1", "Sort10000_1", "Sort100000_1"};
//Deklaration der<SUF>
public static void main(String[] args) throws IOException
{
ArrayList<TestErgebnis> ergebnisListe = new ArrayList<>();
for (String testFilename : testDaten) {
// Einlesen des zu bearbeitenden Arrays - Auswahl der Datei mit dem Array
int[] testDatensatz = FileIntArray.FileToIntArray(testFilename);
// Ausgeben des unsortierten Arrays
System.out.println(Arrays.toString(testDatensatz));
// Erfassen der Anfangszeit
double anfangszeit = System.nanoTime();
// Ausführen von mergeSort
mergeSort(testDatensatz, 0, testDatensatz.length - 1);
// Erfassen der Endzeit
double endzeit = System.nanoTime();
// Ausgabe des sortierten Arrays
System.out.println(Arrays.toString(testDatensatz));
// Ausgabe der benötigten Dauer für den Durchlauf von mergeSort
double dauer = endzeit - anfangszeit;
System.out.println("Die benötigte Zeit betraegt: " + dauer + " Nanosekunden");
// Speichern des Testergebnisses in unsere ergebnissliste
TestErgebnis testErgebnis = new TestErgebnis(testFilename, dauer);
ergebnisListe.add(testErgebnis);
}
File datei = new File("Testlaufergebnis.csv");
FileWriter schreiber = new FileWriter(datei);
// CSV Kopzeile
schreiber.write("Testlauf;Zeit\n");
for (TestErgebnis testErg : ergebnisListe) {
schreiber.write(testErg.getTestDataname() + ";" + testErg.getTime() + "\n");
}
schreiber.close();
}
// Rekursive Funktion Mergesort
// Initialisierung Mergesort mit dem eingelesenen Array, dem linken Index, dem rechten Index
private static void mergeSort(int[] datensatz, int indexLinks, int indexRechts)
{
if (indexLinks < indexRechts) {
int mitte = (indexLinks + indexRechts) / 2;
mergeSort(datensatz, indexLinks, mitte);
mergeSort(datensatz, mitte + 1, indexRechts);
merge(datensatz, indexLinks, mitte, indexRechts);
}
}
//Merge - Methode, die in Mergesort aufgerufen wird
private static void merge(int[] datensatz, int l, int m, int r)
{
// H = Hilfsarray, zum Zwischenspeichern, mit der Länge des Arrays A
int hilfsArray[] = new int[datensatz.length];
// definiere i = linker Index, solange i kleiner gleich rechter Index, führe aus und erhöhe i
for (int i = l; i <= r; i++) {
// Zwischenspeichern von Array datensatz[i] nach hilfsarray[i]
hilfsArray[i] = datensatz[i];
}
// Laufzeitvariablen i, j und k für die while - Schleifendurchläufe
int i = l;
int j = m + 1;
int k = l;
// solange i kleiner gleich mittlerer Index UND j kleiner gleich rechter Index,
while (i <= m && j <= r) {
// Kopiere kleineren aktuellen Wert hilfsArray[j] -> datensatz[k] bzw. hilfsArray[i] -> datensatz[k]
// Erhöhe aktuellen Index von Teilarray mit kleinerem Wert
// Erhöhe aktuellen Index von H
// Wenn H an der Stelle i kleiner gleich H an der Stelle J, dann setze H[i] auf A[k] erhöhe i um eins
if (hilfsArray[i] <= hilfsArray[j]) {
datensatz[k] = hilfsArray[i];
i++;
// ansonsten setze H an der Stelle j auf A[k] und erhöhe j um 1
} else {
datensatz[k] = hilfsArray[j];
j++;
}
// Erhöhe k, die Zählvariable des Arrays A um eins,
// um die nächste Position im Array A im kommenden Durchlauf einzufügen
k++;
}
// übertrage Werte des noch nicht vollständig durchlaufenen Teilarrays nach H
// Kopiere H nach A (von Index l bis Index r)
while (i <= m) {
datensatz[k] = hilfsArray[i];
k++;
i++;
}
while (j <= r) {
datensatz[k] = hilfsArray[j];
k++;
j++;
}
}
// Hilfsklasse zum speichern von Testergebnissen
private static class TestErgebnis
{
private final String testDataname;
private final Double time;
public TestErgebnis(String testDataname, Double time)
{
this.testDataname = testDataname;
this.time = time;
}
public String getTestDataname()
{
return testDataname;
}
public Double getTime()
{
return time;
}
}
}
|
137612_1 | package com.mran.cardpage;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import static android.support.v4.widget.ViewDragHelper.STATE_DRAGGING;
import static android.support.v4.widget.ViewDragHelper.STATE_IDLE;
/**
* Created by M on 2017/9/15.
*/
public class CardPage extends ViewGroup {
private final static int CARDMAXSIZE = 5;
private final static int CARD_SPACING = 30;
private int width;//整个宽度
private int height;//整个高度
private int middleWidthPostion;//中间位置
private int percentage10;//百分之10的宽度
private float suofangxish = 0.9f;
private int jianju = 100;
private Paint mPaint;
private Context mContext;
private AttributeSet mAttributeSet;
private int[] cardWidth = {0, 0, 0, 0, 0};//card的宽度
private int[] cardHeight = {0, 0, 0, 0, 0};//card的高度
private int[] cardLeftPostion = {0, 0, 0, 0, 0};//card左边坐标
private int[] cardTopPostion = {0, 0, 0, 0, 0};//card上部坐标
private int[] cardColor = {0xc8ffeff4, 0xd8ffeff4, 0xe8ffeff4, 0xf8ffeff4};
private int pageSize = 0;
private int pageInTop = 0;
private int pageInBottom = 0;
private int pageLast = 0;
private float mMoveDetal = 0;//全局移动变量
boolean changedSuccess = false;//用来判断是否移动成功
boolean forcelayout = false;
private int topPosition = jianju * 4;
private int leftPsotion;
float firstTouchPosition = 0;
float alpha;
private int dragState = -1;
private ViewDragHelper mViewDragHelper;
private List<CardItem> mViewList = new ArrayList<>();
public CardPage(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CardPage(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attributeSet) {
this.mContext = context;
this.mAttributeSet = attributeSet;
mPaint = new Paint();
setWillNotDraw(false);
mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return child == getChildAt(getChildCount() - 1);/*只有处于最顶层的view才可以被拖动,否则在顶层拖动未结束时拖动其他view,顶层view会被释放*/
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
super.onEdgeDragStarted(edgeFlags, pointerId);
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return left;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return jianju * 4;
}
@Override
public void onViewDragStateChanged(int state) {
dragState = state;
switch (state) {
case STATE_DRAGGING:
break;
case STATE_IDLE:
forcelayout = false;
xx = 0;
cx = 0;
if (changedSuccess) {
// removeView(getChildAt(getChildCount() - 1));
removeViewInLayout(getChildAt(getChildCount() - 1));
if (pageInBottom < pageSize)
addView(mViewList.get(pageInBottom++).getView(), 0);
}
break;
}
super.onViewDragStateChanged(state);
}
int xx = 0;
float cx = 0;
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
alpha = (float) ((float) Math.abs(left - leftPsotion) / (0.95 * width));//更新即将出来的Card的透明度
mMoveDetal = (float) ((float) Math.abs(left - leftPsotion) / (0.95 * width));
Log.d("CardPage", "onViewPositionChanged: left" + left + "mMoveDeta" + mMoveDetal + "leftPsotion" + leftPsotion + "width" + width);
forcelayout = true;
xx += dx;
cx += (int) (dx * jianju / (0.90 * width));
int size=getChildCount();
int addx=0;
if (size<CARDMAXSIZE)
addx=CARDMAXSIZE-size;
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
if (view == changedView)
continue;
Log.d("CardPage", "onViewPositionChanged: xx" + (xx) + "dx" + dx + "cx" + cx + "jianju" + jianju + "width" + width + "alpha" + alpha);
view.setTop((int) (jianju * (i+addx) + mMoveDetal * jianju));
view.setScaleX((float) (1+0.11*mMoveDetal));
view.setScaleY((float) (1+0.11*mMoveDetal));
}
Log.d("CardPage", "onViewPositionChanged: view.width"+getChildAt(getChildCount()-1).getWidth());
invalidate();
super.onViewPositionChanged(changedView, left, top, dx, dy);
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
Log.d("CardPage", "onViewReleased: releasedChildtag" + releasedChild.getTag());
/*惯性滑动*/
if (Math.abs(releasedChild.getLeft() - leftPsotion) <= 0.3 * 0.9 * width) {
mViewDragHelper.settleCapturedViewAt(leftPsotion, topPosition);
changedSuccess = false;
} else if (releasedChild.getLeft() - leftPsotion < 0) {/*向左划*/
changedSuccess = true;
mViewDragHelper.settleCapturedViewAt(-width, topPosition);
} else {/*向右划*/
changedSuccess = true;
mViewDragHelper.settleCapturedViewAt(width, topPosition);
}
invalidate();
}
});
mViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT | ViewDragHelper.EDGE_RIGHT);
}
private int index = 0;
public CardPage addPage(View pageView) {
mViewList.add(new CardItem(pageView, index++));
return this;
}
int tags = 0;
public void build() {
int firstSize = Math.min(CARDMAXSIZE, mViewList.size());
for (int i = 0; i < firstSize; i++) {
CardItem cardItem = mViewList.get(i);
cardItem.mIndexInCards = i;
addView(cardItem.getView(), 0);
pageInBottom++;
Log.d("CardPage", "build: tags" + tags++);
}
pageInBottom++;
pageSize = mViewList.size();
childSize = Math.min(pageSize, CARDMAXSIZE);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("CardPage", "onDraw: ");
mPaint.setColor(0xff303F9F);
mPaint.setTextSize(45);
for (int i = 0; i < getChildCount(); i++) {
canvas.drawText(String.valueOf(mViewList.get((Integer) getChildAt(i).getTag()).cardWidth), i * 100, 100, mPaint);
canvas.drawText(String.valueOf(mViewList.get((Integer) getChildAt(i).getTag()).cardTop), i * 100, 200, mPaint);
}
mPaint.setStrokeWidth(15);
canvas.drawLine(0, jianju * 4, width, jianju * 4, mPaint);
canvas.save();
}
boolean firstMeasure = true;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d("CardPage", "onMeasure: tags" + tags++);
if (leftPsotion == 0) {/*避免多次计算*/
width = getSize(400, widthMeasureSpec);
height = getSize(400, heightMeasureSpec);
percentage10 = (int) (width * 0.1);
middleWidthPostion = width / 2;
leftPsotion = 0;
topPosition = jianju * 4;
}
firstMeasure = false;
}
int childSize;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d("CardPage", "onLayout: ");
childSize = getChildCount();
int size=getChildCount();
int addx=0;
if (size<CARDMAXSIZE)
addx=CARDMAXSIZE-size;
for (int i = 0; i < childSize; i++) {
View view = getChildAt(i);
int cardWidth = (int) (Math.pow(suofangxish, childSize-i-addx) * width);
Log.d("CardPage", "onLayout: cardWidth" + cardWidth);
Log.d("CardPage", "onLayout: i_" + i + "jianju * i" + jianju * i);
view.layout(middleWidthPostion - cardWidth / 2, jianju * (i+addx), middleWidthPostion + cardWidth / 2, jianju * (i+addx) + cardWidth);
}
}
private int getSize(int defaultSize, int measureSpec) {
int mySize = defaultSize;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
switch (mode) {
case MeasureSpec.UNSPECIFIED:
mySize = defaultSize;
break;
case MeasureSpec.AT_MOST:
mySize = size;
break;
case MeasureSpec.EXACTLY:
mySize = size;
break;
}
return mySize;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
firstTouchPosition = ev.getX();
break;
case MotionEvent.ACTION_MOVE:
break;
}
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public void computeScroll() {
if (mViewDragHelper.continueSettling(true)) {
invalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event);
return true;
}
}
| Mran/ViewPageTransformer | cardpage/src/main/java/com/mran/cardpage/CardPage.java | 3,234 | // removeView(getChildAt(getChildCount() - 1)); | line_comment | nl | package com.mran.cardpage;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import static android.support.v4.widget.ViewDragHelper.STATE_DRAGGING;
import static android.support.v4.widget.ViewDragHelper.STATE_IDLE;
/**
* Created by M on 2017/9/15.
*/
public class CardPage extends ViewGroup {
private final static int CARDMAXSIZE = 5;
private final static int CARD_SPACING = 30;
private int width;//整个宽度
private int height;//整个高度
private int middleWidthPostion;//中间位置
private int percentage10;//百分之10的宽度
private float suofangxish = 0.9f;
private int jianju = 100;
private Paint mPaint;
private Context mContext;
private AttributeSet mAttributeSet;
private int[] cardWidth = {0, 0, 0, 0, 0};//card的宽度
private int[] cardHeight = {0, 0, 0, 0, 0};//card的高度
private int[] cardLeftPostion = {0, 0, 0, 0, 0};//card左边坐标
private int[] cardTopPostion = {0, 0, 0, 0, 0};//card上部坐标
private int[] cardColor = {0xc8ffeff4, 0xd8ffeff4, 0xe8ffeff4, 0xf8ffeff4};
private int pageSize = 0;
private int pageInTop = 0;
private int pageInBottom = 0;
private int pageLast = 0;
private float mMoveDetal = 0;//全局移动变量
boolean changedSuccess = false;//用来判断是否移动成功
boolean forcelayout = false;
private int topPosition = jianju * 4;
private int leftPsotion;
float firstTouchPosition = 0;
float alpha;
private int dragState = -1;
private ViewDragHelper mViewDragHelper;
private List<CardItem> mViewList = new ArrayList<>();
public CardPage(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CardPage(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attributeSet) {
this.mContext = context;
this.mAttributeSet = attributeSet;
mPaint = new Paint();
setWillNotDraw(false);
mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return child == getChildAt(getChildCount() - 1);/*只有处于最顶层的view才可以被拖动,否则在顶层拖动未结束时拖动其他view,顶层view会被释放*/
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
super.onEdgeDragStarted(edgeFlags, pointerId);
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return left;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return jianju * 4;
}
@Override
public void onViewDragStateChanged(int state) {
dragState = state;
switch (state) {
case STATE_DRAGGING:
break;
case STATE_IDLE:
forcelayout = false;
xx = 0;
cx = 0;
if (changedSuccess) {
// removeView(getChildAt(getChildCount() -<SUF>
removeViewInLayout(getChildAt(getChildCount() - 1));
if (pageInBottom < pageSize)
addView(mViewList.get(pageInBottom++).getView(), 0);
}
break;
}
super.onViewDragStateChanged(state);
}
int xx = 0;
float cx = 0;
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
alpha = (float) ((float) Math.abs(left - leftPsotion) / (0.95 * width));//更新即将出来的Card的透明度
mMoveDetal = (float) ((float) Math.abs(left - leftPsotion) / (0.95 * width));
Log.d("CardPage", "onViewPositionChanged: left" + left + "mMoveDeta" + mMoveDetal + "leftPsotion" + leftPsotion + "width" + width);
forcelayout = true;
xx += dx;
cx += (int) (dx * jianju / (0.90 * width));
int size=getChildCount();
int addx=0;
if (size<CARDMAXSIZE)
addx=CARDMAXSIZE-size;
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
if (view == changedView)
continue;
Log.d("CardPage", "onViewPositionChanged: xx" + (xx) + "dx" + dx + "cx" + cx + "jianju" + jianju + "width" + width + "alpha" + alpha);
view.setTop((int) (jianju * (i+addx) + mMoveDetal * jianju));
view.setScaleX((float) (1+0.11*mMoveDetal));
view.setScaleY((float) (1+0.11*mMoveDetal));
}
Log.d("CardPage", "onViewPositionChanged: view.width"+getChildAt(getChildCount()-1).getWidth());
invalidate();
super.onViewPositionChanged(changedView, left, top, dx, dy);
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
Log.d("CardPage", "onViewReleased: releasedChildtag" + releasedChild.getTag());
/*惯性滑动*/
if (Math.abs(releasedChild.getLeft() - leftPsotion) <= 0.3 * 0.9 * width) {
mViewDragHelper.settleCapturedViewAt(leftPsotion, topPosition);
changedSuccess = false;
} else if (releasedChild.getLeft() - leftPsotion < 0) {/*向左划*/
changedSuccess = true;
mViewDragHelper.settleCapturedViewAt(-width, topPosition);
} else {/*向右划*/
changedSuccess = true;
mViewDragHelper.settleCapturedViewAt(width, topPosition);
}
invalidate();
}
});
mViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT | ViewDragHelper.EDGE_RIGHT);
}
private int index = 0;
public CardPage addPage(View pageView) {
mViewList.add(new CardItem(pageView, index++));
return this;
}
int tags = 0;
public void build() {
int firstSize = Math.min(CARDMAXSIZE, mViewList.size());
for (int i = 0; i < firstSize; i++) {
CardItem cardItem = mViewList.get(i);
cardItem.mIndexInCards = i;
addView(cardItem.getView(), 0);
pageInBottom++;
Log.d("CardPage", "build: tags" + tags++);
}
pageInBottom++;
pageSize = mViewList.size();
childSize = Math.min(pageSize, CARDMAXSIZE);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("CardPage", "onDraw: ");
mPaint.setColor(0xff303F9F);
mPaint.setTextSize(45);
for (int i = 0; i < getChildCount(); i++) {
canvas.drawText(String.valueOf(mViewList.get((Integer) getChildAt(i).getTag()).cardWidth), i * 100, 100, mPaint);
canvas.drawText(String.valueOf(mViewList.get((Integer) getChildAt(i).getTag()).cardTop), i * 100, 200, mPaint);
}
mPaint.setStrokeWidth(15);
canvas.drawLine(0, jianju * 4, width, jianju * 4, mPaint);
canvas.save();
}
boolean firstMeasure = true;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d("CardPage", "onMeasure: tags" + tags++);
if (leftPsotion == 0) {/*避免多次计算*/
width = getSize(400, widthMeasureSpec);
height = getSize(400, heightMeasureSpec);
percentage10 = (int) (width * 0.1);
middleWidthPostion = width / 2;
leftPsotion = 0;
topPosition = jianju * 4;
}
firstMeasure = false;
}
int childSize;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d("CardPage", "onLayout: ");
childSize = getChildCount();
int size=getChildCount();
int addx=0;
if (size<CARDMAXSIZE)
addx=CARDMAXSIZE-size;
for (int i = 0; i < childSize; i++) {
View view = getChildAt(i);
int cardWidth = (int) (Math.pow(suofangxish, childSize-i-addx) * width);
Log.d("CardPage", "onLayout: cardWidth" + cardWidth);
Log.d("CardPage", "onLayout: i_" + i + "jianju * i" + jianju * i);
view.layout(middleWidthPostion - cardWidth / 2, jianju * (i+addx), middleWidthPostion + cardWidth / 2, jianju * (i+addx) + cardWidth);
}
}
private int getSize(int defaultSize, int measureSpec) {
int mySize = defaultSize;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
switch (mode) {
case MeasureSpec.UNSPECIFIED:
mySize = defaultSize;
break;
case MeasureSpec.AT_MOST:
mySize = size;
break;
case MeasureSpec.EXACTLY:
mySize = size;
break;
}
return mySize;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
firstTouchPosition = ev.getX();
break;
case MotionEvent.ACTION_MOVE:
break;
}
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public void computeScroll() {
if (mViewDragHelper.continueSettling(true)) {
invalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event);
return true;
}
}
|
66503_3 | package scenes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.mt4j.MTApplication;
import org.mt4j.components.TransformSpace;
import org.mt4j.components.visibleComponents.shapes.MTRectangle;
import org.mt4j.components.visibleComponents.widgets.MTBackgroundImage;
import org.mt4j.components.visibleComponents.widgets.buttons.MTImageButton;
import org.mt4j.input.inputProcessors.componentProcessors.tapProcessor.TapEvent;
import org.mt4j.sceneManagement.AbstractScene;
import org.mt4j.sceneManagement.Iscene;
import org.mt4j.util.MT4jSettings;
import org.mt4j.util.MTColor;
import org.mt4j.util.math.Vector3D;
import processing.core.PImage;
public class NinjaMainMenu extends AbstractScene {
//Applicatie variabelen
private MTApplication mtApp;
private String category;
//Verschillende scenes waar deze scene naartoe kan gaan(nog niet geinitialiseerd)
//Exit knop is geen scene maar rechtstreekse sluiting van het window
private Iscene newScene;
public NinjaMainMenu(MTApplication mtApplication, String name, String _category) {
//Setup van het scherm.
super(mtApplication, name);
this.category = _category;
this.mtApp = mtApplication;
this.setClearColor(new MTColor(0, 0, 0, 255));
PImage bg_img = mtApplication.loadImage("../data/ninja_bg.jpg");
MTBackgroundImage bg = new MTBackgroundImage(mtApp, bg_img, false);
//Aanmaken van het logo dat dienst doet als menu opener
PImage logo = mtApplication.loadImage("../data/menu/ninjaLogo.png");
MTImageButton logoMenu = new MTImageButton(logo, mtApp);
//Laadt de images in
PImage ribbon = mtApplication.loadImage("../data/menu/menuRibbon.png");
PImage theme = mtApplication.loadImage("../data/menu/theme.png");
PImage settings = mtApplication.loadImage("../data/menu/settings.png");
PImage exit = mtApplication.loadImage("../data/menu/exit.png");
PImage catImg = mtApplication.loadImage("../data/menu/hot.png");
if(this.category == "Binnenland") {
catImg = mtApplication.loadImage("../data/menu/binnenland.png");
}
else if(this.category == "Buitenland") {
catImg = mtApplication.loadImage("../data/menu/buitenland.png");
}
else if(this.category == "Sport") {
catImg = mtApplication.loadImage("../data/menu/sport.png");
}
else if(this.category == "Cultuur") {
catImg = mtApplication.loadImage("../data/menu/cultuur.png");
}
else if(this.category == "Economie") {
catImg = mtApplication.loadImage("../data/menu/economie.png");
}
//Aanmaken van het de imageButtons en de menuRibbon
MTRectangle menuRibbon = new MTRectangle(ribbon, mtApp);
MTImageButton categoryButton = new MTImageButton(catImg, mtApp);
MTImageButton themeButton = new MTImageButton(theme, mtApp);
MTImageButton settingsButton = new MTImageButton(settings, mtApp);
MTImageButton exitButton = new MTImageButton(exit, mtApp);
//Verwijder de strokes rondom de imageButton
logoMenu.setNoStroke(true);
menuRibbon.setNoStroke(true);
categoryButton.setNoStroke(true);
themeButton.setNoStroke(true);
settingsButton.setNoStroke(true);
exitButton.setNoStroke(true);
//Als OpenGL aanwezig is, gebruik maken van OpenGL om de graphics te tonen
if (MT4jSettings.getInstance().isOpenGlMode()) {
bg.setUseDirectGL(true);
logoMenu.setUseDirectGL(true);
menuRibbon.setUseDirectGL(true);
categoryButton.setUseDirectGL(true);
themeButton.setUseDirectGL(true);
settingsButton.setUseDirectGL(true);
exitButton.setUseDirectGL(true);
}
//Alle events van de verschillende menu-onderdelen worden hieronder gedefinieerd
logoMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eLogo) {
switch(eLogo.getID()) {
case TapEvent.BUTTON_CLICKED:
//Ga terug naar mainNinjaScene
//Deze keer wordt de category ook meegestuurd zodoende dat deze niet verloren gaat
//bij het afbreken van de scene
mtApp.popScene();
break;
default:
break;
}
}
});
categoryButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eCategory) {
switch(eCategory.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor categoryselectie
mtApp.pushScene();
newScene = new NinjaSelectCategory(mtApp, "Ninjanieuws", category);
mtApp.addScene(newScene);
mtApp.changeScene(newScene);
break;
default:
break;
}
}
});
themeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eTheme) {
switch(eTheme.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor naar thema selectie te gaan komt hier
break;
default:
break;
}
}
});
settingsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eSettings) {
switch(eSettings.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor naar settingsscherm te gaan komt hier
break;
default:
break;
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent exit) {
switch(exit.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor de app af te sluiten (WIP want nog veel problemen)
break;
default:
break;
}
}
});
//Alle elementen toevoegen op het canvas.
this.getCanvas().addChild(bg);
this.getCanvas().addChild(menuRibbon);
this.getCanvas().addChild(logoMenu);
this.getCanvas().addChild(categoryButton);
this.getCanvas().addChild(themeButton);
this.getCanvas().addChild(settingsButton);
this.getCanvas().addChild(exitButton);
//Plaats van de elementen op het canvas instellen
logoMenu.setPositionGlobal(new Vector3D(mtApp.width - logoMenu.getWidthXY(TransformSpace.GLOBAL) / 2, logoMenu.getHeightXY(TransformSpace.GLOBAL) / 2));
menuRibbon.setPositionGlobal(new Vector3D(mtApp.width - menuRibbon.getWidthXY(TransformSpace.GLOBAL) / 2 + 22, menuRibbon.getHeightXY(TransformSpace.GLOBAL) / 2 - 23));
categoryButton.setPositionGlobal(new Vector3D(mtApp.width - categoryButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 205, categoryButton.getHeightXY(TransformSpace.GLOBAL) / 2));
themeButton.setPositionGlobal(new Vector3D(mtApp.width - themeButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 180, themeButton.getHeightXY(TransformSpace.GLOBAL) / 2 + 90));
settingsButton.setPositionGlobal(new Vector3D(mtApp.width - settingsButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 115, settingsButton.getHeightXY(TransformSpace.GLOBAL) / 2 + 160));
exitButton.setPositionGlobal(new Vector3D(mtApp.width - exitButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 20, exitButton.getHeightXY(TransformSpace.GLOBAL) / 2 + 210));
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public void shutDown() {
// TODO Auto-generated method stub
}
}
| Multec/Multec_IM_13_1 | src/scenes/NinjaMainMenu.java | 2,318 | //Aanmaken van het logo dat dienst doet als menu opener | line_comment | nl | package scenes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.mt4j.MTApplication;
import org.mt4j.components.TransformSpace;
import org.mt4j.components.visibleComponents.shapes.MTRectangle;
import org.mt4j.components.visibleComponents.widgets.MTBackgroundImage;
import org.mt4j.components.visibleComponents.widgets.buttons.MTImageButton;
import org.mt4j.input.inputProcessors.componentProcessors.tapProcessor.TapEvent;
import org.mt4j.sceneManagement.AbstractScene;
import org.mt4j.sceneManagement.Iscene;
import org.mt4j.util.MT4jSettings;
import org.mt4j.util.MTColor;
import org.mt4j.util.math.Vector3D;
import processing.core.PImage;
public class NinjaMainMenu extends AbstractScene {
//Applicatie variabelen
private MTApplication mtApp;
private String category;
//Verschillende scenes waar deze scene naartoe kan gaan(nog niet geinitialiseerd)
//Exit knop is geen scene maar rechtstreekse sluiting van het window
private Iscene newScene;
public NinjaMainMenu(MTApplication mtApplication, String name, String _category) {
//Setup van het scherm.
super(mtApplication, name);
this.category = _category;
this.mtApp = mtApplication;
this.setClearColor(new MTColor(0, 0, 0, 255));
PImage bg_img = mtApplication.loadImage("../data/ninja_bg.jpg");
MTBackgroundImage bg = new MTBackgroundImage(mtApp, bg_img, false);
//Aanmaken van<SUF>
PImage logo = mtApplication.loadImage("../data/menu/ninjaLogo.png");
MTImageButton logoMenu = new MTImageButton(logo, mtApp);
//Laadt de images in
PImage ribbon = mtApplication.loadImage("../data/menu/menuRibbon.png");
PImage theme = mtApplication.loadImage("../data/menu/theme.png");
PImage settings = mtApplication.loadImage("../data/menu/settings.png");
PImage exit = mtApplication.loadImage("../data/menu/exit.png");
PImage catImg = mtApplication.loadImage("../data/menu/hot.png");
if(this.category == "Binnenland") {
catImg = mtApplication.loadImage("../data/menu/binnenland.png");
}
else if(this.category == "Buitenland") {
catImg = mtApplication.loadImage("../data/menu/buitenland.png");
}
else if(this.category == "Sport") {
catImg = mtApplication.loadImage("../data/menu/sport.png");
}
else if(this.category == "Cultuur") {
catImg = mtApplication.loadImage("../data/menu/cultuur.png");
}
else if(this.category == "Economie") {
catImg = mtApplication.loadImage("../data/menu/economie.png");
}
//Aanmaken van het de imageButtons en de menuRibbon
MTRectangle menuRibbon = new MTRectangle(ribbon, mtApp);
MTImageButton categoryButton = new MTImageButton(catImg, mtApp);
MTImageButton themeButton = new MTImageButton(theme, mtApp);
MTImageButton settingsButton = new MTImageButton(settings, mtApp);
MTImageButton exitButton = new MTImageButton(exit, mtApp);
//Verwijder de strokes rondom de imageButton
logoMenu.setNoStroke(true);
menuRibbon.setNoStroke(true);
categoryButton.setNoStroke(true);
themeButton.setNoStroke(true);
settingsButton.setNoStroke(true);
exitButton.setNoStroke(true);
//Als OpenGL aanwezig is, gebruik maken van OpenGL om de graphics te tonen
if (MT4jSettings.getInstance().isOpenGlMode()) {
bg.setUseDirectGL(true);
logoMenu.setUseDirectGL(true);
menuRibbon.setUseDirectGL(true);
categoryButton.setUseDirectGL(true);
themeButton.setUseDirectGL(true);
settingsButton.setUseDirectGL(true);
exitButton.setUseDirectGL(true);
}
//Alle events van de verschillende menu-onderdelen worden hieronder gedefinieerd
logoMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eLogo) {
switch(eLogo.getID()) {
case TapEvent.BUTTON_CLICKED:
//Ga terug naar mainNinjaScene
//Deze keer wordt de category ook meegestuurd zodoende dat deze niet verloren gaat
//bij het afbreken van de scene
mtApp.popScene();
break;
default:
break;
}
}
});
categoryButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eCategory) {
switch(eCategory.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor categoryselectie
mtApp.pushScene();
newScene = new NinjaSelectCategory(mtApp, "Ninjanieuws", category);
mtApp.addScene(newScene);
mtApp.changeScene(newScene);
break;
default:
break;
}
}
});
themeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eTheme) {
switch(eTheme.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor naar thema selectie te gaan komt hier
break;
default:
break;
}
}
});
settingsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eSettings) {
switch(eSettings.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor naar settingsscherm te gaan komt hier
break;
default:
break;
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent exit) {
switch(exit.getID()) {
case TapEvent.BUTTON_CLICKED:
//Code voor de app af te sluiten (WIP want nog veel problemen)
break;
default:
break;
}
}
});
//Alle elementen toevoegen op het canvas.
this.getCanvas().addChild(bg);
this.getCanvas().addChild(menuRibbon);
this.getCanvas().addChild(logoMenu);
this.getCanvas().addChild(categoryButton);
this.getCanvas().addChild(themeButton);
this.getCanvas().addChild(settingsButton);
this.getCanvas().addChild(exitButton);
//Plaats van de elementen op het canvas instellen
logoMenu.setPositionGlobal(new Vector3D(mtApp.width - logoMenu.getWidthXY(TransformSpace.GLOBAL) / 2, logoMenu.getHeightXY(TransformSpace.GLOBAL) / 2));
menuRibbon.setPositionGlobal(new Vector3D(mtApp.width - menuRibbon.getWidthXY(TransformSpace.GLOBAL) / 2 + 22, menuRibbon.getHeightXY(TransformSpace.GLOBAL) / 2 - 23));
categoryButton.setPositionGlobal(new Vector3D(mtApp.width - categoryButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 205, categoryButton.getHeightXY(TransformSpace.GLOBAL) / 2));
themeButton.setPositionGlobal(new Vector3D(mtApp.width - themeButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 180, themeButton.getHeightXY(TransformSpace.GLOBAL) / 2 + 90));
settingsButton.setPositionGlobal(new Vector3D(mtApp.width - settingsButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 115, settingsButton.getHeightXY(TransformSpace.GLOBAL) / 2 + 160));
exitButton.setPositionGlobal(new Vector3D(mtApp.width - exitButton.getWidthXY(TransformSpace.GLOBAL) / 2 - 20, exitButton.getHeightXY(TransformSpace.GLOBAL) / 2 + 210));
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public void shutDown() {
// TODO Auto-generated method stub
}
}
|
102902_2 | package day_065_mrt;
public class C072 {
}
class Test{
public static void main(String[] args) {
Test ts=new Test();
System.out.println(isAvaiable + " ");// isAvaiable basinca asagidan false degeri gelecek.// False basacak
isAvaiable=ts.doStuff();// True basacak
System.out.println(isAvaiable);
}
public static boolean doStuff(){
return ! isAvaiable;// isavaiable tersi return edecek yani :True dönecek
}
static boolean isAvaiable=false;// sout olan bu variable dir.Boolean in default degeri zaten fals
}
// fallse true=B | MuratTokar/Java | day_065_mrt/C072.java | 200 | // sout olan bu variable dir.Boolean in default degeri zaten fals | line_comment | nl | package day_065_mrt;
public class C072 {
}
class Test{
public static void main(String[] args) {
Test ts=new Test();
System.out.println(isAvaiable + " ");// isAvaiable basinca asagidan false degeri gelecek.// False basacak
isAvaiable=ts.doStuff();// True basacak
System.out.println(isAvaiable);
}
public static boolean doStuff(){
return ! isAvaiable;// isavaiable tersi return edecek yani :True dönecek
}
static boolean isAvaiable=false;// sout olan<SUF>
}
// fallse true=B |
180433_6 | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en power zijn altijd gehele getallen dan is er geen afronding
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| Murrx/EWDC | ws-parent/ws-producer/src/main/java/nl/hu/fnt/gsos/wsproducer/PowerserviceImpl.java | 343 | //// // x en power zijn altijd gehele getallen dan is er geen afronding | line_comment | nl | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en<SUF>
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
|
191913_0 | /*
* Developer : Joris Rijkes ([email protected])
* Date : 7 okt. 2013
* All code (c)2013 Joris Rijkes inc. all rights reserved
*/
package com.th5.domain.model.validators;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.th5.domain.model.Person;
public class UserPersonValidator implements ValidatorInterface<Person> {
private List<AttributeError> errorList = new ArrayList<AttributeError>();
private static String NAME_PATTERN = "[a-zA-Z-\\s]{3,20}";
@Override
public List<AttributeError> validate(Person person) {
isValidBirthDate(person.getBirthdate());
isValidFirstName(person.getFirstName());
isValidGender(person.getGender());
isValidLastName(person.getLastName());
return errorList;
}
public void isValidFirstName(String firstName) {
if (firstName == null) {
errorList
.add(new AttributeError("firstName", "first name is null"));
} else if (firstName.trim().length() == 0) {
errorList.add(new AttributeError("firstName",
"first name is required"));
} else {
if (!firstName.matches(NAME_PATTERN)) {
errorList.add(new AttributeError("firstName",
"Invalid first name"));
}
}
}
public void isValidLastName(String lastName) {
if (lastName == null) {
errorList.add(new AttributeError("lastName", "last name is null"));
} else if (lastName.trim().length() == 0) {
errorList.add(new AttributeError("lastName",
"last name is required"));
} else {
if (!lastName.matches(NAME_PATTERN)) {
errorList.add(new AttributeError("lastName",
"Invalid last name"));
}
}
}
public void isValidGender(int gender) {
if (!((gender == 0) || (gender == 1))) {
errorList.add(new AttributeError("gender",
"gender is required/invalid"));
}
}
public void isValidBirthDate(Date birthdate) {
if (birthdate == null) {
errorList.add(new AttributeError("birthdate",
"birthdate is required"));
} else if (!birthdate.before(Calendar.getInstance().getTime())) {
errorList.add(new AttributeError("birthdate",
"birthdate cannot be in the future"));
}
}
public void clearArray() {
errorList.clear();
}
}
| Murrx/themaopdracht-5-hu | src/com/th5/domain/model/validators/UserPersonValidator.java | 732 | /*
* Developer : Joris Rijkes ([email protected])
* Date : 7 okt. 2013
* All code (c)2013 Joris Rijkes inc. all rights reserved
*/ | block_comment | nl | /*
* Developer : Joris<SUF>*/
package com.th5.domain.model.validators;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.th5.domain.model.Person;
public class UserPersonValidator implements ValidatorInterface<Person> {
private List<AttributeError> errorList = new ArrayList<AttributeError>();
private static String NAME_PATTERN = "[a-zA-Z-\\s]{3,20}";
@Override
public List<AttributeError> validate(Person person) {
isValidBirthDate(person.getBirthdate());
isValidFirstName(person.getFirstName());
isValidGender(person.getGender());
isValidLastName(person.getLastName());
return errorList;
}
public void isValidFirstName(String firstName) {
if (firstName == null) {
errorList
.add(new AttributeError("firstName", "first name is null"));
} else if (firstName.trim().length() == 0) {
errorList.add(new AttributeError("firstName",
"first name is required"));
} else {
if (!firstName.matches(NAME_PATTERN)) {
errorList.add(new AttributeError("firstName",
"Invalid first name"));
}
}
}
public void isValidLastName(String lastName) {
if (lastName == null) {
errorList.add(new AttributeError("lastName", "last name is null"));
} else if (lastName.trim().length() == 0) {
errorList.add(new AttributeError("lastName",
"last name is required"));
} else {
if (!lastName.matches(NAME_PATTERN)) {
errorList.add(new AttributeError("lastName",
"Invalid last name"));
}
}
}
public void isValidGender(int gender) {
if (!((gender == 0) || (gender == 1))) {
errorList.add(new AttributeError("gender",
"gender is required/invalid"));
}
}
public void isValidBirthDate(Date birthdate) {
if (birthdate == null) {
errorList.add(new AttributeError("birthdate",
"birthdate is required"));
} else if (!birthdate.before(Calendar.getInstance().getTime())) {
errorList.add(new AttributeError("birthdate",
"birthdate cannot be in the future"));
}
}
public void clearArray() {
errorList.clear();
}
}
|
43885_1 | package com.example.cuisin;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.cuisin.Adapters.TopRecipesAdapter;
import com.example.cuisin.Api.RecipeInformation;
import com.example.cuisin.Api.Result;
import com.example.cuisin.Api.ResultsList;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements TextView.OnEditorActionListener {
ApiCaller apiCaller;
ArrayList<Result> list;
TopRecipesAdapter topRecipesAdapter;
RecyclerView recyclerView;
EditText recipeInput;
TextView recipesText;
private Integer recipeAmount;
private SharedPreferences savedValues;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// override van dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
savedValues = PreferenceManager.getDefaultSharedPreferences(this);
recipeAmount = Integer.parseInt(savedValues.getString("recipe_numbers", "5"));
// de query van de api gaat standaard op Top Recipes staan. Dan krijgen we onmiddelijk recepten wanneer de app opstart
apiCaller = new ApiCaller();
apiCaller.getTopRecipes(apiListener, "Top Recipes", recipeAmount);
// edit box in activity_main.xml
recipeInput = (EditText) findViewById(R.id.recipeInput);
recipeInput.setOnEditorActionListener(this);
// hier gaan we uitvoeren wat er gaat gebeuren als je op een recept klikt. Openen van detailsactivity
topRecipesAdapter = new TopRecipesAdapter(MainActivity.this, list, new TopRecipesAdapter.ItemClickListener() {
@Override
public void onItemClick(String recipeId) {
startActivity(new Intent(MainActivity.this, DetailsActivity.class)
.putExtra("recipeId", recipeId));
}
});
}
private final ApiListener apiListener = new ApiListener() {
@Override
public void getResponse(ResultsList resultsList) {
GridLayoutManager manager = new GridLayoutManager(MainActivity.this, 1);
recyclerView = findViewById(R.id.tr_recycler);
recyclerView.setHasFixedSize(true);
manager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
topRecipesAdapter = new TopRecipesAdapter(MainActivity.this, resultsList.results, topRecipesAdapter.itemClickListener);
recyclerView.setAdapter(topRecipesAdapter);
}
@Override
public void getError(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
@Override
public void getResponse(RecipeInformation recipeInformation){}
};
///////////////////////////////////////searchbar/////////////////////////////////////////////////
// als we iets ingeven in de edit box en op enter drukken gaan we de ingegeven text meegeven met inputText en de APi oproepen met de meegeven input.
// zo krijgen we resultaten te zien met de ingegeven query.
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEARCH) {
String inputText = recipeInput.getText().toString();
apiCaller.getTopRecipes(apiListener, inputText, recipeAmount);
recipesText = (TextView) findViewById(R.id.textViewRecipe);
recipesText.setText(inputText + " recipes");
}
return true;
}
///////////////////////////////////////settings activity/////////////////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recipes_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
// get preferences
recipeAmount = Integer.parseInt(savedValues.getString("recipe_numbers", "5"));
apiCaller.getTopRecipes(apiListener, recipeInput.getText().toString(), recipeAmount);
}
} | Mustafa0142/CuisinV2 | app/src/main/java/com/example/cuisin/MainActivity.java | 1,392 | // de query van de api gaat standaard op Top Recipes staan. Dan krijgen we onmiddelijk recepten wanneer de app opstart | line_comment | nl | package com.example.cuisin;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.cuisin.Adapters.TopRecipesAdapter;
import com.example.cuisin.Api.RecipeInformation;
import com.example.cuisin.Api.Result;
import com.example.cuisin.Api.ResultsList;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements TextView.OnEditorActionListener {
ApiCaller apiCaller;
ArrayList<Result> list;
TopRecipesAdapter topRecipesAdapter;
RecyclerView recyclerView;
EditText recipeInput;
TextView recipesText;
private Integer recipeAmount;
private SharedPreferences savedValues;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// override van dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
savedValues = PreferenceManager.getDefaultSharedPreferences(this);
recipeAmount = Integer.parseInt(savedValues.getString("recipe_numbers", "5"));
// de query<SUF>
apiCaller = new ApiCaller();
apiCaller.getTopRecipes(apiListener, "Top Recipes", recipeAmount);
// edit box in activity_main.xml
recipeInput = (EditText) findViewById(R.id.recipeInput);
recipeInput.setOnEditorActionListener(this);
// hier gaan we uitvoeren wat er gaat gebeuren als je op een recept klikt. Openen van detailsactivity
topRecipesAdapter = new TopRecipesAdapter(MainActivity.this, list, new TopRecipesAdapter.ItemClickListener() {
@Override
public void onItemClick(String recipeId) {
startActivity(new Intent(MainActivity.this, DetailsActivity.class)
.putExtra("recipeId", recipeId));
}
});
}
private final ApiListener apiListener = new ApiListener() {
@Override
public void getResponse(ResultsList resultsList) {
GridLayoutManager manager = new GridLayoutManager(MainActivity.this, 1);
recyclerView = findViewById(R.id.tr_recycler);
recyclerView.setHasFixedSize(true);
manager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
topRecipesAdapter = new TopRecipesAdapter(MainActivity.this, resultsList.results, topRecipesAdapter.itemClickListener);
recyclerView.setAdapter(topRecipesAdapter);
}
@Override
public void getError(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
@Override
public void getResponse(RecipeInformation recipeInformation){}
};
///////////////////////////////////////searchbar/////////////////////////////////////////////////
// als we iets ingeven in de edit box en op enter drukken gaan we de ingegeven text meegeven met inputText en de APi oproepen met de meegeven input.
// zo krijgen we resultaten te zien met de ingegeven query.
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEARCH) {
String inputText = recipeInput.getText().toString();
apiCaller.getTopRecipes(apiListener, inputText, recipeAmount);
recipesText = (TextView) findViewById(R.id.textViewRecipe);
recipesText.setText(inputText + " recipes");
}
return true;
}
///////////////////////////////////////settings activity/////////////////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recipes_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
// get preferences
recipeAmount = Integer.parseInt(savedValues.getString("recipe_numbers", "5"));
apiCaller.getTopRecipes(apiListener, recipeInput.getText().toString(), recipeAmount);
}
} |
164532_2 | /**
* Copyright (C) <2021> <chen junwen>
* <p>
* 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.
* <p>
* 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.
* <p>
* 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 io.mycat.config;
/**
* cjw
* [email protected]
*/
public class MySQLServerCapabilityFlags {
/**
* server value
*
*
* server: 11110111 11111111
* client_cmd: 11 10100110 10000101
* client_jdbc:10 10100010 10001111
*
* see 'http://dev.mysql.com/doc/refman/5.1/en/mysql-real-connect.html'
*
*/
// new more secure passwords
public static final int CLIENT_LONG_PASSWORD = 1;
// Found instead of affected rows
// 返回找到(匹配)的行数,而不是改变了的行数。
public static final int CLIENT_FOUND_ROWS = 2;
// Get all column flags
public static final int CLIENT_LONG_FLAG = 4;
// One can specify db on connect
public static final int CLIENT_CONNECT_WITH_DB = 8;
// Don't allow database.table.column
// 不允许“数据库名.表名.列名”这样的语法。这是对于ODBC的设置。
// 当使用这样的语法时解析器会产生一个错误,这对于一些ODBC的程序限制bug来说是有用的。
public static final int CLIENT_NO_SCHEMA = 16;
// Can use compression protocol
// 使用压缩协议
public static final int CLIENT_COMPRESS = 32;
// Odbc client
public static final int CLIENT_ODBC = 64;
// Can use LOAD DATA LOCAL
public static final int CLIENT_LOCAL_FILES = 128;
// Ignore spaces before '('
// 允许在函数名后使用空格。所有函数名可以预留字。
public static final int CLIENT_IGNORE_SPACE = 256;
// New 4.1 protocol This is an interactive client
public static final int CLIENT_PROTOCOL_41 = 512;
// This is an interactive client
// 允许使用关闭连接之前的不活动交互超时的描述,而不是等待超时秒数。
// 客户端的会话等待超时变量变为交互超时变量。
public static final int CLIENT_INTERACTIVE = 1024;
// Switch to SSL after handshake
// 使用SSL。这个设置不应该被应用程序设置,他应该是在客户端库内部是设置的。
// 可以在调用mysql_real_connect()之前调用mysql_ssl_set()来代替设置。
public static final int CLIENT_SSL = 2048;
// IGNORE sigpipes
// 阻止客户端库安装一个SIGPIPE信号处理器。
// 这个可以用于当应用程序已经安装该处理器的时候避免与其发生冲突。
public static final int CLIENT_IGNORE_SIGPIPE = 4096;
// Client knows about transactions
public static final int CLIENT_TRANSACTIONS = 8192;
// Old flag for 4.1 protocol
public static final int CLIENT_RESERVED = 16384;
// New 4.1 authentication
public static final int CLIENT_SECURE_CONNECTION = 32768;
// Enable/disable multi-stmt support
// 通知服务器客户端可以发送多条语句(由分号分隔)。如果该标志为没有被设置,多条语句执行。
public static final int CLIENT_MULTI_STATEMENTS = 1 << 16;
// Enable/disable multi-results
// 通知服务器客户端可以处理由多语句或者存储过程执行生成的多结果集。
// 当打开CLIENT_MULTI_STATEMENTS时,这个标志自动的被打开。
public static final int CLIENT_MULTI_RESULTS = 1 << 1 << 16;
/**
ServerCan send multiple resultsets for COM_STMT_EXECUTE.
Client
Can handle multiple resultsets for COM_STMT_EXECUTE.
Value
0x00040000
Requires
CLIENT_PROTOCOL_41
*/
public static final int CLIENT_PS_MULTI_RESULTS = 1 << 2 << 16;
/**
Server
Sends extra data in Initial Handshake Packet and supports the pluggable authentication protocol.
Client
Supports authentication plugins.
Requires
CLIENT_PROTOCOL_41
*/
public static final int CLIENT_PLUGIN_AUTH = 1 << 3 << 16;
/**
Value
0x00100000
Server
Permits connection attributes in Protocol::HandshakeResponse41.
Client
Sends connection attributes in Protocol::HandshakeResponse41.
*/
public static final int CLIENT_CONNECT_ATTRS = 1 << 4 << 16;
/**
Value
0x00200000
Server
Understands length-encoded integer for auth response data in Protocol::HandshakeResponse41.
Client
Length of auth response data in Protocol::HandshakeResponse41 is a length-encoded integer.
The flag was introduced in 5.6.6, but had the wrong value.
*/
public static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 1 << 5 << 16;
/**
*Value
* 0x00400000
*
* Server
* Announces support for expired password extension.
*
* Client
* Can handle expired passwords.
*/
public static final int CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 1 << 6 << 16;
/**
* Value
* 0x00800000
*
* Server
* Can set SERVER_SESSION_STATE_CHANGED in the Status Flags and send session-state change data after a OK packet.
*
* Client
* Expects the server to send sesson-state changes after a OK packet.
*/
public static final int CLIENT_SESSION_TRACK = 1 << 7 << 16;
/**
Value
0x01000000
Server
Can send OK after a Text Resultset.
Client
Expects an OK (instead of EOF) after the resultset rows of a Text Resultset.
Background
To support CLIENT_SESSION_TRACK, additional information must be sent after all successful commands. Although the OK packet is extensible, the EOF packet is not due to the overlap of its bytes with the content of the Text Resultset Row.
Therefore, the EOF packet in the Text Resultset is replaced with an OK packet. EOF packets are deprecated as of MySQL 5.7.5.
*/
public static final int CLIENT_DEPRECATE_EOF = 1 << 8 << 16;
public int value = 0;
public MySQLServerCapabilityFlags(int capabilities) {
this.value = capabilities;
}
public MySQLServerCapabilityFlags() {
}
public static int getDefaultServerCapabilities() {
int flag = 0;
flag |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD;
flag |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS;
flag |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG;
flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB;
// flag |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA;
// boolean usingCompress = MycatServer.getInstance().getConfig()
// .getSystem().getUseCompression() == 1;
// if (usingCompress) {
// flag |= MySQLServerCapabilityFlags.CLIENT_COMPRESS;
// }
// flag |= MySQLServerCapabilityFlags.CLIENT_ODBC;
flag |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES;
flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE;
flag |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41;
flag |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE;
// flag |= MySQLServerCapabilityFlags.CLIENT_SSL;
flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE;
flag |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS;
// flag |= ServerDefs.CLIENT_RESERVED;
flag |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION;
flag |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH;
// flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS;
// flag |= (MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK);
flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS;
flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS;
return flag;
}
public static boolean isLongPassword(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD) != 0;
}
public static boolean isFoundRows(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS) != 0;
}
public static boolean isConnectionWithDatabase(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB) != 0;
}
public static boolean isDoNotAllowDatabaseDotTableDotColumn(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA) != 0;
}
public static boolean isCanUseCompressionProtocol(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_COMPRESS) != 0;
}
public static boolean isODBCClient(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_ODBC) != 0;
}
public static boolean isCanUseLoadDataLocal(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES) != 0;
}
public static boolean isIgnoreSpacesBeforeLeftBracket(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE) != 0;
}
public static boolean isClientProtocol41(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41) != 0;
}
public static boolean isSwitchToSSLAfterHandshake(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_SSL) != 0;
}
public static boolean isIgnoreSigpipes(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE) != 0;
}
public static boolean isKnowsAboutTransactions(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS) != 0;
}
public static boolean isInteractive(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_INTERACTIVE) != 0;
}
public static boolean isSpeak41Protocol(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_RESERVED) != 0;
}
public static boolean isCanDo41Anthentication(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION) != 0;
}
public static boolean isMultipleStatements(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS) != 0;
}
public static boolean isPSMultipleResults(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS) != 0;
}
public static boolean isPluginAuth(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH) != 0;
}
public static boolean isConnectAttrs(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS) != 0;
}
public static boolean isPluginAuthLenencClientData(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0;
}
public static boolean isSessionVariableTracking(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK) != 0;
}
public static boolean isDeprecateEOF(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF) != 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("MySQLServerCapabilityFlags{");
sb.append("value=").append(Integer.toBinaryString(value << 7));
sb.append('}');
return sb.toString();
}
public int getLower2Bytes() {
return value & 0x0000ffff;
}
public int getUpper2Bytes() {
return value >>> 16;
}
public boolean isLongPassword() {
return isLongPassword(value);
}
public void setLongPassword() {
value |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD;
}
public boolean isFoundRows() {
return isFoundRows(value);
}
public void setFoundRows() {
value |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS;
}
public boolean isLongColumnWithFLags() {
return isLongColumnWithFLags(value);
}
public boolean isLongColumnWithFLags(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_LONG_FLAG) != 0;
}
public void setLongColumnWithFLags() {
value |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG;
}
public boolean isConnectionWithDatabase() {
return isConnectionWithDatabase(value);
}
public void setConnectionWithDatabase() {
value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB;
}
public boolean isDoNotAllowDatabaseDotTableDotColumn() {
return isDoNotAllowDatabaseDotTableDotColumn(value);
}
public void setDoNotAllowDatabaseDotTableDotColumn() {
value |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA;
}
public boolean isCanUseCompressionProtocol() {
return isCanUseCompressionProtocol(value);
}
public void setCanUseCompressionProtocol() {
value |= MySQLServerCapabilityFlags.CLIENT_COMPRESS;
}
public boolean isODBCClient() {
return isODBCClient(value);
}
public void setODBCClient() {
value |= MySQLServerCapabilityFlags.CLIENT_ODBC;
}
public boolean isCanUseLoadDataLocal() {
return isCanUseLoadDataLocal(value);
}
public void setCanUseLoadDataLocal() {
value |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES;
}
public boolean isIgnoreSpacesBeforeLeftBracket() {
return isIgnoreSpacesBeforeLeftBracket(value);
}
public void setIgnoreSpacesBeforeLeftBracket() {
value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE;
}
public boolean isClientProtocol41() {
return isClientProtocol41(value);
}
public void setClientProtocol41() {
value |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41;
}
public boolean isSwitchToSSLAfterHandshake() {
return isSwitchToSSLAfterHandshake(value);
}
public void setSwitchToSSLAfterHandshake() {
value |= MySQLServerCapabilityFlags.CLIENT_SSL;
}
public boolean isIgnoreSigpipes() {
return isIgnoreSigpipes(value);
}
public void setIgnoreSigpipes() {
value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE;
}
public boolean isKnowsAboutTransactions() {
return isKnowsAboutTransactions(value);
}
public void setKnowsAboutTransactions() {
value |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS;
}
public void setInteractive() {
value |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE;
}
public boolean isInteractive() {
return isInteractive(value);
}
public boolean isSpeak41Protocol() {
return isSpeak41Protocol(value);
}
public void setSpeak41Protocol() {
value |= MySQLServerCapabilityFlags.CLIENT_RESERVED;
}
public boolean isCanDo41Anthentication() {
return isCanDo41Anthentication(value);
}
public void setCanDo41Anthentication() {
value |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION;
}
public boolean isMultipleStatements() {
return isMultipleStatements(value);
}
public void setMultipleStatements() {
value |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS;
}
public boolean isMultipleResults() {
return isMultipleResults(value);
}
public boolean isMultipleResults(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS) != 0;
}
public void setMultipleResults() {
value |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS;
}
public boolean isPSMultipleResults() {
return isPSMultipleResults(value);
}
public void setPSMultipleResults() {
value |= MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS;
}
public boolean isPluginAuth() {
return isPluginAuth(value);
}
public void setPluginAuth() {
value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH;
}
public boolean isConnectAttrs() {
return isConnectAttrs(value);
}
public void setConnectAttrs() {
value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS;
}
public boolean isPluginAuthLenencClientData() {
return isPluginAuthLenencClientData(value);
}
public void setPluginAuthLenencClientData() {
value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA;
}
public boolean isClientCanHandleExpiredPasswords() {
return isClientCanHandleExpiredPasswords(value);
}
public boolean isClientCanHandleExpiredPasswords(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) != 0;
}
public void setClientCanHandleExpiredPasswords() {
value |= MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS;
}
public boolean isSessionVariableTracking() {
return isSessionVariableTracking(value);
}
public void setSessionVariableTracking() {
value |= MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK;
}
public boolean isDeprecateEOF() {
return isDeprecateEOF(value);
}
public void setDeprecateEOF() {
value |= MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MySQLServerCapabilityFlags)) return false;
MySQLServerCapabilityFlags that = (MySQLServerCapabilityFlags) o;
return hashCode() == that.hashCode();
}
@Override
public int hashCode() {
return value << 7;
}
}
| MyCATApache/Mycat2 | config/src/main/java/io/mycat/config/MySQLServerCapabilityFlags.java | 5,366 | /**
* server value
*
*
* server: 11110111 11111111
* client_cmd: 11 10100110 10000101
* client_jdbc:10 10100010 10001111
*
* see 'http://dev.mysql.com/doc/refman/5.1/en/mysql-real-connect.html'
*
*/ | block_comment | nl | /**
* Copyright (C) <2021> <chen junwen>
* <p>
* 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.
* <p>
* 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.
* <p>
* 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 io.mycat.config;
/**
* cjw
* [email protected]
*/
public class MySQLServerCapabilityFlags {
/**
* server value
<SUF>*/
// new more secure passwords
public static final int CLIENT_LONG_PASSWORD = 1;
// Found instead of affected rows
// 返回找到(匹配)的行数,而不是改变了的行数。
public static final int CLIENT_FOUND_ROWS = 2;
// Get all column flags
public static final int CLIENT_LONG_FLAG = 4;
// One can specify db on connect
public static final int CLIENT_CONNECT_WITH_DB = 8;
// Don't allow database.table.column
// 不允许“数据库名.表名.列名”这样的语法。这是对于ODBC的设置。
// 当使用这样的语法时解析器会产生一个错误,这对于一些ODBC的程序限制bug来说是有用的。
public static final int CLIENT_NO_SCHEMA = 16;
// Can use compression protocol
// 使用压缩协议
public static final int CLIENT_COMPRESS = 32;
// Odbc client
public static final int CLIENT_ODBC = 64;
// Can use LOAD DATA LOCAL
public static final int CLIENT_LOCAL_FILES = 128;
// Ignore spaces before '('
// 允许在函数名后使用空格。所有函数名可以预留字。
public static final int CLIENT_IGNORE_SPACE = 256;
// New 4.1 protocol This is an interactive client
public static final int CLIENT_PROTOCOL_41 = 512;
// This is an interactive client
// 允许使用关闭连接之前的不活动交互超时的描述,而不是等待超时秒数。
// 客户端的会话等待超时变量变为交互超时变量。
public static final int CLIENT_INTERACTIVE = 1024;
// Switch to SSL after handshake
// 使用SSL。这个设置不应该被应用程序设置,他应该是在客户端库内部是设置的。
// 可以在调用mysql_real_connect()之前调用mysql_ssl_set()来代替设置。
public static final int CLIENT_SSL = 2048;
// IGNORE sigpipes
// 阻止客户端库安装一个SIGPIPE信号处理器。
// 这个可以用于当应用程序已经安装该处理器的时候避免与其发生冲突。
public static final int CLIENT_IGNORE_SIGPIPE = 4096;
// Client knows about transactions
public static final int CLIENT_TRANSACTIONS = 8192;
// Old flag for 4.1 protocol
public static final int CLIENT_RESERVED = 16384;
// New 4.1 authentication
public static final int CLIENT_SECURE_CONNECTION = 32768;
// Enable/disable multi-stmt support
// 通知服务器客户端可以发送多条语句(由分号分隔)。如果该标志为没有被设置,多条语句执行。
public static final int CLIENT_MULTI_STATEMENTS = 1 << 16;
// Enable/disable multi-results
// 通知服务器客户端可以处理由多语句或者存储过程执行生成的多结果集。
// 当打开CLIENT_MULTI_STATEMENTS时,这个标志自动的被打开。
public static final int CLIENT_MULTI_RESULTS = 1 << 1 << 16;
/**
ServerCan send multiple resultsets for COM_STMT_EXECUTE.
Client
Can handle multiple resultsets for COM_STMT_EXECUTE.
Value
0x00040000
Requires
CLIENT_PROTOCOL_41
*/
public static final int CLIENT_PS_MULTI_RESULTS = 1 << 2 << 16;
/**
Server
Sends extra data in Initial Handshake Packet and supports the pluggable authentication protocol.
Client
Supports authentication plugins.
Requires
CLIENT_PROTOCOL_41
*/
public static final int CLIENT_PLUGIN_AUTH = 1 << 3 << 16;
/**
Value
0x00100000
Server
Permits connection attributes in Protocol::HandshakeResponse41.
Client
Sends connection attributes in Protocol::HandshakeResponse41.
*/
public static final int CLIENT_CONNECT_ATTRS = 1 << 4 << 16;
/**
Value
0x00200000
Server
Understands length-encoded integer for auth response data in Protocol::HandshakeResponse41.
Client
Length of auth response data in Protocol::HandshakeResponse41 is a length-encoded integer.
The flag was introduced in 5.6.6, but had the wrong value.
*/
public static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 1 << 5 << 16;
/**
*Value
* 0x00400000
*
* Server
* Announces support for expired password extension.
*
* Client
* Can handle expired passwords.
*/
public static final int CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 1 << 6 << 16;
/**
* Value
* 0x00800000
*
* Server
* Can set SERVER_SESSION_STATE_CHANGED in the Status Flags and send session-state change data after a OK packet.
*
* Client
* Expects the server to send sesson-state changes after a OK packet.
*/
public static final int CLIENT_SESSION_TRACK = 1 << 7 << 16;
/**
Value
0x01000000
Server
Can send OK after a Text Resultset.
Client
Expects an OK (instead of EOF) after the resultset rows of a Text Resultset.
Background
To support CLIENT_SESSION_TRACK, additional information must be sent after all successful commands. Although the OK packet is extensible, the EOF packet is not due to the overlap of its bytes with the content of the Text Resultset Row.
Therefore, the EOF packet in the Text Resultset is replaced with an OK packet. EOF packets are deprecated as of MySQL 5.7.5.
*/
public static final int CLIENT_DEPRECATE_EOF = 1 << 8 << 16;
public int value = 0;
public MySQLServerCapabilityFlags(int capabilities) {
this.value = capabilities;
}
public MySQLServerCapabilityFlags() {
}
public static int getDefaultServerCapabilities() {
int flag = 0;
flag |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD;
flag |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS;
flag |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG;
flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB;
// flag |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA;
// boolean usingCompress = MycatServer.getInstance().getConfig()
// .getSystem().getUseCompression() == 1;
// if (usingCompress) {
// flag |= MySQLServerCapabilityFlags.CLIENT_COMPRESS;
// }
// flag |= MySQLServerCapabilityFlags.CLIENT_ODBC;
flag |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES;
flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE;
flag |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41;
flag |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE;
// flag |= MySQLServerCapabilityFlags.CLIENT_SSL;
flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE;
flag |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS;
// flag |= ServerDefs.CLIENT_RESERVED;
flag |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION;
flag |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH;
// flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS;
// flag |= (MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK);
flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS;
flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS;
return flag;
}
public static boolean isLongPassword(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD) != 0;
}
public static boolean isFoundRows(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS) != 0;
}
public static boolean isConnectionWithDatabase(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB) != 0;
}
public static boolean isDoNotAllowDatabaseDotTableDotColumn(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA) != 0;
}
public static boolean isCanUseCompressionProtocol(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_COMPRESS) != 0;
}
public static boolean isODBCClient(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_ODBC) != 0;
}
public static boolean isCanUseLoadDataLocal(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES) != 0;
}
public static boolean isIgnoreSpacesBeforeLeftBracket(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE) != 0;
}
public static boolean isClientProtocol41(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41) != 0;
}
public static boolean isSwitchToSSLAfterHandshake(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_SSL) != 0;
}
public static boolean isIgnoreSigpipes(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE) != 0;
}
public static boolean isKnowsAboutTransactions(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS) != 0;
}
public static boolean isInteractive(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_INTERACTIVE) != 0;
}
public static boolean isSpeak41Protocol(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_RESERVED) != 0;
}
public static boolean isCanDo41Anthentication(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION) != 0;
}
public static boolean isMultipleStatements(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS) != 0;
}
public static boolean isPSMultipleResults(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS) != 0;
}
public static boolean isPluginAuth(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH) != 0;
}
public static boolean isConnectAttrs(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS) != 0;
}
public static boolean isPluginAuthLenencClientData(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0;
}
public static boolean isSessionVariableTracking(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK) != 0;
}
public static boolean isDeprecateEOF(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF) != 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("MySQLServerCapabilityFlags{");
sb.append("value=").append(Integer.toBinaryString(value << 7));
sb.append('}');
return sb.toString();
}
public int getLower2Bytes() {
return value & 0x0000ffff;
}
public int getUpper2Bytes() {
return value >>> 16;
}
public boolean isLongPassword() {
return isLongPassword(value);
}
public void setLongPassword() {
value |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD;
}
public boolean isFoundRows() {
return isFoundRows(value);
}
public void setFoundRows() {
value |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS;
}
public boolean isLongColumnWithFLags() {
return isLongColumnWithFLags(value);
}
public boolean isLongColumnWithFLags(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_LONG_FLAG) != 0;
}
public void setLongColumnWithFLags() {
value |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG;
}
public boolean isConnectionWithDatabase() {
return isConnectionWithDatabase(value);
}
public void setConnectionWithDatabase() {
value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB;
}
public boolean isDoNotAllowDatabaseDotTableDotColumn() {
return isDoNotAllowDatabaseDotTableDotColumn(value);
}
public void setDoNotAllowDatabaseDotTableDotColumn() {
value |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA;
}
public boolean isCanUseCompressionProtocol() {
return isCanUseCompressionProtocol(value);
}
public void setCanUseCompressionProtocol() {
value |= MySQLServerCapabilityFlags.CLIENT_COMPRESS;
}
public boolean isODBCClient() {
return isODBCClient(value);
}
public void setODBCClient() {
value |= MySQLServerCapabilityFlags.CLIENT_ODBC;
}
public boolean isCanUseLoadDataLocal() {
return isCanUseLoadDataLocal(value);
}
public void setCanUseLoadDataLocal() {
value |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES;
}
public boolean isIgnoreSpacesBeforeLeftBracket() {
return isIgnoreSpacesBeforeLeftBracket(value);
}
public void setIgnoreSpacesBeforeLeftBracket() {
value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE;
}
public boolean isClientProtocol41() {
return isClientProtocol41(value);
}
public void setClientProtocol41() {
value |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41;
}
public boolean isSwitchToSSLAfterHandshake() {
return isSwitchToSSLAfterHandshake(value);
}
public void setSwitchToSSLAfterHandshake() {
value |= MySQLServerCapabilityFlags.CLIENT_SSL;
}
public boolean isIgnoreSigpipes() {
return isIgnoreSigpipes(value);
}
public void setIgnoreSigpipes() {
value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE;
}
public boolean isKnowsAboutTransactions() {
return isKnowsAboutTransactions(value);
}
public void setKnowsAboutTransactions() {
value |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS;
}
public void setInteractive() {
value |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE;
}
public boolean isInteractive() {
return isInteractive(value);
}
public boolean isSpeak41Protocol() {
return isSpeak41Protocol(value);
}
public void setSpeak41Protocol() {
value |= MySQLServerCapabilityFlags.CLIENT_RESERVED;
}
public boolean isCanDo41Anthentication() {
return isCanDo41Anthentication(value);
}
public void setCanDo41Anthentication() {
value |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION;
}
public boolean isMultipleStatements() {
return isMultipleStatements(value);
}
public void setMultipleStatements() {
value |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS;
}
public boolean isMultipleResults() {
return isMultipleResults(value);
}
public boolean isMultipleResults(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS) != 0;
}
public void setMultipleResults() {
value |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS;
}
public boolean isPSMultipleResults() {
return isPSMultipleResults(value);
}
public void setPSMultipleResults() {
value |= MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS;
}
public boolean isPluginAuth() {
return isPluginAuth(value);
}
public void setPluginAuth() {
value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH;
}
public boolean isConnectAttrs() {
return isConnectAttrs(value);
}
public void setConnectAttrs() {
value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS;
}
public boolean isPluginAuthLenencClientData() {
return isPluginAuthLenencClientData(value);
}
public void setPluginAuthLenencClientData() {
value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA;
}
public boolean isClientCanHandleExpiredPasswords() {
return isClientCanHandleExpiredPasswords(value);
}
public boolean isClientCanHandleExpiredPasswords(int value) {
return (value & MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) != 0;
}
public void setClientCanHandleExpiredPasswords() {
value |= MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS;
}
public boolean isSessionVariableTracking() {
return isSessionVariableTracking(value);
}
public void setSessionVariableTracking() {
value |= MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK;
}
public boolean isDeprecateEOF() {
return isDeprecateEOF(value);
}
public void setDeprecateEOF() {
value |= MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MySQLServerCapabilityFlags)) return false;
MySQLServerCapabilityFlags that = (MySQLServerCapabilityFlags) o;
return hashCode() == that.hashCode();
}
@Override
public int hashCode() {
return value << 7;
}
}
|
101698_16 | //*****************************************************************************
//* Element of MyOpenLab Library *
//* *
//* Copyright (C) 2004 Carmelo Salafia ([email protected]) *
//* *
//* This library is free software; you can redistribute it and/or modify *
//* it under the terms of the GNU Lesser General Public License as published *
//* by the Free Software Foundation; either version 2.1 of the License, *
//* or (at your option) any later version. *
//* http://www.gnu.org/licenses/lgpl.html *
//* *
//* This library is distributed in the hope that it will be useful, *
//* but WITHOUTANY WARRANTY; without even the implied warranty of *
//* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
//* See the GNU Lesser General Public License for more details. *
//* *
//* You should have received a copy of the GNU Lesser General Public License *
//* along with this library; if not, write to the Free Software Foundation, *
//* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA *
//*****************************************************************************
import VisualLogic.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import tools.*;
import VisualLogic.variables.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.*;
import java.util.*;
import java.awt.image.MemoryImageSource;
import java3drobot.*;
public class Panel extends JVSMain implements PanelIF
{
private boolean on=false;
private VSBoolean interpolation = new VSBoolean(false);
private VSGroup in;
private ExternalIF circuitElement;
private Font font=new Font("Monospaced",0,13);
private double aktuellerWinkel=0;// grad!
private double stepAngle=10; // grad!
private CanvasRobot3D panelX=null;
private int posX=0;
private int posY=0;
//Properties
private VSBoolean drawLine = new VSBoolean(true);
private VSColor backColor = new VSColor(Color.WHITE);
private VSBoolean gridVisible = new VSBoolean(true);
private VSColor gridColor = new VSColor(Color.LIGHT_GRAY);
private VSInteger gridDX = new VSInteger(20);
private VSInteger gridDY = new VSInteger(20);
private int oldWidth=0;
private int oldHeight=0;
public void onDispose()
{
JPanel panel=element.getFrontPanel();
panel.remove(panelX);
}
public void processPanel(int pinIndex, double value, Object obj)
{
if (panelX!=null)
{
if (pinIndex==0 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setBasisAngle(tmp.getValue());
}else
if (pinIndex==1 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setZ1Angle(tmp.getValue());
}else
if (pinIndex==2 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setZ2Angle(tmp.getValue());
}else
if (pinIndex==3 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setZ3Angle(tmp.getValue());
}else
if (pinIndex==4 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setHandAngle(tmp.getValue());
}else
if (pinIndex==5 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
panelX.setOpenHand(tmp.getValue());
}
}
/*
if (pinIndex==1 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.goBack();
}
if (pinIndex==2 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.stop();
}
if (pinIndex==3 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setAngle(tmp.getValue());
aktuellerWinkel=tmp.getValue();
}
if (pinIndex==4 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue())
{
aktuellerWinkel+=stepAngle;
panelX.setAngle(aktuellerWinkel);
}
}
if (pinIndex==5 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue())
{
aktuellerWinkel-=stepAngle;
panelX.setAngle(aktuellerWinkel);
}
}
if (pinIndex==6 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
stepAngle=tmp.getValue();
}
if (pinIndex==7 && obj instanceof VSInteger)
{
VSInteger tmp = (VSInteger)obj;
posX=tmp.getValue();
}
if (pinIndex==8 && obj instanceof VSInteger)
{
VSInteger tmp = (VSInteger)obj;
posY=tmp.getValue();
}
if (pinIndex==9 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.gotoCoordinated(posX,posY);
}
if (pinIndex==10 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.setPosition(posX,posY);
}
if (pinIndex==11 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
panelX.setGreiferStatus(tmp.getValue());
}
if (pinIndex==12 && obj instanceof VSGroup)
{
VSGroup group = (VSGroup)obj;
panelX.clearImages();
for (int i=0;i<group.list.size();i++)
{
VSObject o = (VSObject)group.list.get(i);
if (o instanceof VSGroup)
{
VSGroup tmp =(VSGroup)o;
if (tmp.list.size()==3)
{
Image imgX=null;
int pX=0;
int pY=0;
if (tmp.list.get(0) instanceof VSImage24)
{
VSImage24 vsimg=(VSImage24)tmp.list.get(0);
imgX= Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(vsimg.getWidth(),vsimg.getHeight(),vsimg.getPixels(), 0, vsimg.getWidth()) );
}
if (tmp.list.get(1) instanceof VSInteger)
{
VSInteger posX=(VSInteger)tmp.list.get(1);
pX=posX.getValue();
}
if (tmp.list.get(2) instanceof VSInteger)
{
VSInteger posY=(VSInteger)tmp.list.get(2);
pY=posY.getValue();
}
panelX.addImage(imgX,pX,pY);
}
}
}
panelX.handle();
}
if (pinIndex==13 && obj instanceof VSGroup)
{
VSGroup group = (VSGroup)obj;
panelX.clearPickableObjects();
for (int i=0;i<group.list.size();i++)
{
VSObject o = (VSObject)group.list.get(i);
if (o instanceof VSGroup)
{
VSGroup tmp =(VSGroup)o;
if (tmp.list.size()==2)
{
Image imgX=null;
int pX=0;
int pY=0;
if (tmp.list.get(0) instanceof VSInteger)
{
VSInteger posX=(VSInteger)tmp.list.get(0);
pX=posX.getValue();
}
if (tmp.list.get(1) instanceof VSInteger)
{
VSInteger posY=(VSInteger)tmp.list.get(1);
pY=posY.getValue();
}
panelX.addPickableObject(pX,pY);
}
}
}
panelX.handle();
}
if (pinIndex==14 && obj instanceof VSBoolean)
{
VSBoolean tmp=(VSBoolean)obj;
panelX.setRecordWay(tmp.getValue());
}
if (pinIndex==15 && obj instanceof VSInteger)
{
VSInteger tmp=(VSInteger)obj;
panelX.setDelay(tmp.getValue());
}
if (pinIndex==16 && obj instanceof VSBoolean)
{
VSBoolean tmp=(VSBoolean)obj;
if (tmp.getValue())
{
panelX.clearWeg();
}
//panelX.setDelay(tmp.getValue());
}
if (pinIndex==17 && obj instanceof VSImage24)
{
VSImage24 vsimg=(VSImage24)obj;
Image img= Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(vsimg.getWidth(),vsimg.getHeight(),vsimg.getPixels(), 0, vsimg.getWidth()) );
panelX.setRobotImage(img);
panelX.updateUI();
} */
}
public void paint(java.awt.Graphics g)
{
if (element!=null && panelX!=null)
{
Rectangle rec=element.jGetBounds();
if (rec.width>50 | rec.height>50)
{
if (rec.width!=oldWidth || rec.height!=oldHeight)
{
panelX.setLocation(10,10);
panelX.setSize(rec.width-10-10,rec.height-10-10);
oldWidth=rec.width;
oldHeight=rec.height;
}
} else
{
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString("Resize", 7,30);
panelX.setSize(0,0);
}
}else
{
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString("Please install Java 3D", 7,30);
g.drawString("from https://java3d.dev.java.net/binary-builds.html", 7,45);
g.drawString("!* Attention: if you have updated your Java Version ", 7,60);
g.drawString("!* you have to reinstall java 3d.", 7,75);
}
}
public void propertyChanged(Object o)
{
/*panelX.setDrawLine(drawLine.getValue());
panelX.setBackgroundColor(backColor.getValue());
panelX.setGridVisible(gridVisible.getValue());
panelX.setGridColor(gridColor.getValue());
panelX.setGridDX(gridDX.getValue());
panelX.setGridDY(gridDY.getValue());
panelX.handle();*/
}
public void setPropertyEditor()
{
/*element.jAddPEItem("Weg zeichnen",drawLine, 0,0);
element.jAddPEItem("Background Color",backColor, 0,0);
element.jAddPEItem("Grid Visible",gridVisible, 0,0);
element.jAddPEItem("Grid Color",gridColor, 0,0);
element.jAddPEItem("Grid DX",gridDX, 2,500);
element.jAddPEItem("Grid DY",gridDY, 2,500);
localize();*/
}
private void localize()
{
int d=6;
String language;
language="en_US";
element.jSetPEItemLocale(d+0,language,"Draw path");
element.jSetPEItemLocale(d+1,language,"Background Color");
element.jSetPEItemLocale(d+2,language,"Grid Visible");
element.jSetPEItemLocale(d+3,language,"Grid Color");
element.jSetPEItemLocale(d+4,language,"Grid DX");
element.jSetPEItemLocale(d+5,language,"Grid DY");
language="es_ES";
element.jSetPEItemLocale(d+0,language,"Draw path");
element.jSetPEItemLocale(d+1,language,"Background Color");
element.jSetPEItemLocale(d+2,language,"Grid Visible");
element.jSetPEItemLocale(d+3,language,"Grid Color");
element.jSetPEItemLocale(d+4,language,"Grid DX");
element.jSetPEItemLocale(d+5,language,"Grid DY");
}
public void start()
{
circuitElement=element.getCircuitElement();
stepAngle=10;
aktuellerWinkel=0;
if (panelX!=null) panelX.resetView();
}
public void stop()
{
}
public void init()
{
initPins(0,0,0,0);
initPinVisibility(false,false,false,false);
setSize(150,150);
element.jSetInnerBorderVisibility(false);
element.jSetBorderVisibility(true);
//element.jSetResizeSynchron(true);
element.jSetResizable(true);
setName("RobotArmSim v 1.0");
try
{
panelX=new CanvasRobot3D();
} catch(Exception ex)
{
}
}
public void xOnInit()
{
JPanel panel=element.getFrontPanel();
panel.setLayout(null);
//graph.setOpaque(false);
if (panelX!=null)
{
panel.add(panelX);
panelX.setLocation(30,30);
panelX.setSize(0,0);
}
//graph.graph.init();
element.setAlwaysOnTop(true);
//propertyChanged(null);
}
public void loadFromStream(java.io.FileInputStream fis)
{
/*drawLine.loadFromStream(fis);
backColor.loadFromStream(fis);
gridVisible.loadFromStream(fis);
gridColor.loadFromStream(fis);
gridDX.loadFromStream(fis);
gridDY.loadFromStream(fis);*/
}
public void saveToStream(java.io.FileOutputStream fos)
{
/* drawLine.saveToStream(fos);
backColor.saveToStream(fos);
gridVisible.saveToStream(fos);
gridColor.saveToStream(fos);
gridDX.saveToStream(fos);
gridDY.saveToStream(fos);*/
}
}
| MyLibreLab/MyLibreLab | elements/FrontElements/2Robotics/RobotArm3D_1_0/src/Panel.java | 4,239 | /*element.jAddPEItem("Weg zeichnen",drawLine, 0,0);
element.jAddPEItem("Background Color",backColor, 0,0);
element.jAddPEItem("Grid Visible",gridVisible, 0,0);
element.jAddPEItem("Grid Color",gridColor, 0,0);
element.jAddPEItem("Grid DX",gridDX, 2,500);
element.jAddPEItem("Grid DY",gridDY, 2,500);
localize();*/ | block_comment | nl | //*****************************************************************************
//* Element of MyOpenLab Library *
//* *
//* Copyright (C) 2004 Carmelo Salafia ([email protected]) *
//* *
//* This library is free software; you can redistribute it and/or modify *
//* it under the terms of the GNU Lesser General Public License as published *
//* by the Free Software Foundation; either version 2.1 of the License, *
//* or (at your option) any later version. *
//* http://www.gnu.org/licenses/lgpl.html *
//* *
//* This library is distributed in the hope that it will be useful, *
//* but WITHOUTANY WARRANTY; without even the implied warranty of *
//* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
//* See the GNU Lesser General Public License for more details. *
//* *
//* You should have received a copy of the GNU Lesser General Public License *
//* along with this library; if not, write to the Free Software Foundation, *
//* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA *
//*****************************************************************************
import VisualLogic.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import tools.*;
import VisualLogic.variables.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.*;
import java.util.*;
import java.awt.image.MemoryImageSource;
import java3drobot.*;
public class Panel extends JVSMain implements PanelIF
{
private boolean on=false;
private VSBoolean interpolation = new VSBoolean(false);
private VSGroup in;
private ExternalIF circuitElement;
private Font font=new Font("Monospaced",0,13);
private double aktuellerWinkel=0;// grad!
private double stepAngle=10; // grad!
private CanvasRobot3D panelX=null;
private int posX=0;
private int posY=0;
//Properties
private VSBoolean drawLine = new VSBoolean(true);
private VSColor backColor = new VSColor(Color.WHITE);
private VSBoolean gridVisible = new VSBoolean(true);
private VSColor gridColor = new VSColor(Color.LIGHT_GRAY);
private VSInteger gridDX = new VSInteger(20);
private VSInteger gridDY = new VSInteger(20);
private int oldWidth=0;
private int oldHeight=0;
public void onDispose()
{
JPanel panel=element.getFrontPanel();
panel.remove(panelX);
}
public void processPanel(int pinIndex, double value, Object obj)
{
if (panelX!=null)
{
if (pinIndex==0 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setBasisAngle(tmp.getValue());
}else
if (pinIndex==1 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setZ1Angle(tmp.getValue());
}else
if (pinIndex==2 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setZ2Angle(tmp.getValue());
}else
if (pinIndex==3 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setZ3Angle(tmp.getValue());
}else
if (pinIndex==4 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setHandAngle(tmp.getValue());
}else
if (pinIndex==5 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
panelX.setOpenHand(tmp.getValue());
}
}
/*
if (pinIndex==1 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.goBack();
}
if (pinIndex==2 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.stop();
}
if (pinIndex==3 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
panelX.setAngle(tmp.getValue());
aktuellerWinkel=tmp.getValue();
}
if (pinIndex==4 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue())
{
aktuellerWinkel+=stepAngle;
panelX.setAngle(aktuellerWinkel);
}
}
if (pinIndex==5 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue())
{
aktuellerWinkel-=stepAngle;
panelX.setAngle(aktuellerWinkel);
}
}
if (pinIndex==6 && obj instanceof VSDouble)
{
VSDouble tmp = (VSDouble)obj;
stepAngle=tmp.getValue();
}
if (pinIndex==7 && obj instanceof VSInteger)
{
VSInteger tmp = (VSInteger)obj;
posX=tmp.getValue();
}
if (pinIndex==8 && obj instanceof VSInteger)
{
VSInteger tmp = (VSInteger)obj;
posY=tmp.getValue();
}
if (pinIndex==9 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.gotoCoordinated(posX,posY);
}
if (pinIndex==10 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
if (tmp.getValue()) panelX.setPosition(posX,posY);
}
if (pinIndex==11 && obj instanceof VSBoolean)
{
VSBoolean tmp = (VSBoolean)obj;
panelX.setGreiferStatus(tmp.getValue());
}
if (pinIndex==12 && obj instanceof VSGroup)
{
VSGroup group = (VSGroup)obj;
panelX.clearImages();
for (int i=0;i<group.list.size();i++)
{
VSObject o = (VSObject)group.list.get(i);
if (o instanceof VSGroup)
{
VSGroup tmp =(VSGroup)o;
if (tmp.list.size()==3)
{
Image imgX=null;
int pX=0;
int pY=0;
if (tmp.list.get(0) instanceof VSImage24)
{
VSImage24 vsimg=(VSImage24)tmp.list.get(0);
imgX= Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(vsimg.getWidth(),vsimg.getHeight(),vsimg.getPixels(), 0, vsimg.getWidth()) );
}
if (tmp.list.get(1) instanceof VSInteger)
{
VSInteger posX=(VSInteger)tmp.list.get(1);
pX=posX.getValue();
}
if (tmp.list.get(2) instanceof VSInteger)
{
VSInteger posY=(VSInteger)tmp.list.get(2);
pY=posY.getValue();
}
panelX.addImage(imgX,pX,pY);
}
}
}
panelX.handle();
}
if (pinIndex==13 && obj instanceof VSGroup)
{
VSGroup group = (VSGroup)obj;
panelX.clearPickableObjects();
for (int i=0;i<group.list.size();i++)
{
VSObject o = (VSObject)group.list.get(i);
if (o instanceof VSGroup)
{
VSGroup tmp =(VSGroup)o;
if (tmp.list.size()==2)
{
Image imgX=null;
int pX=0;
int pY=0;
if (tmp.list.get(0) instanceof VSInteger)
{
VSInteger posX=(VSInteger)tmp.list.get(0);
pX=posX.getValue();
}
if (tmp.list.get(1) instanceof VSInteger)
{
VSInteger posY=(VSInteger)tmp.list.get(1);
pY=posY.getValue();
}
panelX.addPickableObject(pX,pY);
}
}
}
panelX.handle();
}
if (pinIndex==14 && obj instanceof VSBoolean)
{
VSBoolean tmp=(VSBoolean)obj;
panelX.setRecordWay(tmp.getValue());
}
if (pinIndex==15 && obj instanceof VSInteger)
{
VSInteger tmp=(VSInteger)obj;
panelX.setDelay(tmp.getValue());
}
if (pinIndex==16 && obj instanceof VSBoolean)
{
VSBoolean tmp=(VSBoolean)obj;
if (tmp.getValue())
{
panelX.clearWeg();
}
//panelX.setDelay(tmp.getValue());
}
if (pinIndex==17 && obj instanceof VSImage24)
{
VSImage24 vsimg=(VSImage24)obj;
Image img= Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(vsimg.getWidth(),vsimg.getHeight(),vsimg.getPixels(), 0, vsimg.getWidth()) );
panelX.setRobotImage(img);
panelX.updateUI();
} */
}
public void paint(java.awt.Graphics g)
{
if (element!=null && panelX!=null)
{
Rectangle rec=element.jGetBounds();
if (rec.width>50 | rec.height>50)
{
if (rec.width!=oldWidth || rec.height!=oldHeight)
{
panelX.setLocation(10,10);
panelX.setSize(rec.width-10-10,rec.height-10-10);
oldWidth=rec.width;
oldHeight=rec.height;
}
} else
{
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString("Resize", 7,30);
panelX.setSize(0,0);
}
}else
{
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString("Please install Java 3D", 7,30);
g.drawString("from https://java3d.dev.java.net/binary-builds.html", 7,45);
g.drawString("!* Attention: if you have updated your Java Version ", 7,60);
g.drawString("!* you have to reinstall java 3d.", 7,75);
}
}
public void propertyChanged(Object o)
{
/*panelX.setDrawLine(drawLine.getValue());
panelX.setBackgroundColor(backColor.getValue());
panelX.setGridVisible(gridVisible.getValue());
panelX.setGridColor(gridColor.getValue());
panelX.setGridDX(gridDX.getValue());
panelX.setGridDY(gridDY.getValue());
panelX.handle();*/
}
public void setPropertyEditor()
{
/*element.jAddPEItem("Weg zeichnen",drawLine, 0,0);<SUF>*/
}
private void localize()
{
int d=6;
String language;
language="en_US";
element.jSetPEItemLocale(d+0,language,"Draw path");
element.jSetPEItemLocale(d+1,language,"Background Color");
element.jSetPEItemLocale(d+2,language,"Grid Visible");
element.jSetPEItemLocale(d+3,language,"Grid Color");
element.jSetPEItemLocale(d+4,language,"Grid DX");
element.jSetPEItemLocale(d+5,language,"Grid DY");
language="es_ES";
element.jSetPEItemLocale(d+0,language,"Draw path");
element.jSetPEItemLocale(d+1,language,"Background Color");
element.jSetPEItemLocale(d+2,language,"Grid Visible");
element.jSetPEItemLocale(d+3,language,"Grid Color");
element.jSetPEItemLocale(d+4,language,"Grid DX");
element.jSetPEItemLocale(d+5,language,"Grid DY");
}
public void start()
{
circuitElement=element.getCircuitElement();
stepAngle=10;
aktuellerWinkel=0;
if (panelX!=null) panelX.resetView();
}
public void stop()
{
}
public void init()
{
initPins(0,0,0,0);
initPinVisibility(false,false,false,false);
setSize(150,150);
element.jSetInnerBorderVisibility(false);
element.jSetBorderVisibility(true);
//element.jSetResizeSynchron(true);
element.jSetResizable(true);
setName("RobotArmSim v 1.0");
try
{
panelX=new CanvasRobot3D();
} catch(Exception ex)
{
}
}
public void xOnInit()
{
JPanel panel=element.getFrontPanel();
panel.setLayout(null);
//graph.setOpaque(false);
if (panelX!=null)
{
panel.add(panelX);
panelX.setLocation(30,30);
panelX.setSize(0,0);
}
//graph.graph.init();
element.setAlwaysOnTop(true);
//propertyChanged(null);
}
public void loadFromStream(java.io.FileInputStream fis)
{
/*drawLine.loadFromStream(fis);
backColor.loadFromStream(fis);
gridVisible.loadFromStream(fis);
gridColor.loadFromStream(fis);
gridDX.loadFromStream(fis);
gridDY.loadFromStream(fis);*/
}
public void saveToStream(java.io.FileOutputStream fos)
{
/* drawLine.saveToStream(fos);
backColor.saveToStream(fos);
gridVisible.saveToStream(fos);
gridColor.saveToStream(fos);
gridDX.saveToStream(fos);
gridDY.saveToStream(fos);*/
}
}
|
208631_13 | /*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.ibiosim.gui.verificationView;
import javax.swing.*;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.AbstractRunnableNamedButton;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyList;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.Runnable;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
/**
* This class creates a GUI front end for the Verification tool. It provides the
* necessary options to run an atacs simulation of the circuit and manage the
* results from the BioSim GUI.
*
* @author Kevin Jones
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ParameterEditor extends JPanel implements ActionListener {
private static final long serialVersionUID = -5806315070287184299L;
//private JButton save, run, viewCircuit, viewTrace, viewLog, addComponent, removeComponent;
private JLabel algorithm, timingMethod, timingOptions, otherOptions, otherOptions2,
compilation, bddSizeLabel, advTiming, abstractLabel;
private JRadioButton untimed, geometric, posets, bag, bap, baptdc, verify, vergate, orbits,
search, trace, bdd, dbm, smt, lhpn, view, none, simplify, abstractLhpn;
private JCheckBox abst, partialOrder, dot, verbose, graph, genrg, timsubset, superset, infopt,
orbmatch, interleav, prune, disabling, nofail, keepgoing, explpn, nochecks, reduction,
newTab, postProc, redCheck, xForm2, expandRate;
private JTextField bddSize;
//private JTextField backgroundField, componentField;
private ButtonGroup timingMethodGroup, algorithmGroup, abstractionGroup;
private PropertyList variables;
private String root;
//private String directory, verFile, oldBdd, sourceFileNoPath;
public String verifyFile;
//private boolean change, atacs;
//private JTabbedPane bigTab;
//private PropertyList componentList;
//private AbstPane abstPane;
//private Log log;
//private BioSim biosim;
/**
* This is the constructor for the Verification class. It initializes all
* the input fields, puts them on panels, adds the panels to the frame, and
* then displays the frame.
*/
public ParameterEditor(String directory, boolean lema, boolean atacs) {
String[] tempDir = GlobalConstants.splitPath(directory);
root = tempDir[0];
for (int i = 1; i < tempDir.length - 1; i++) {
root = root + File.separator + tempDir[i];
}
JPanel abstractionPanel = new JPanel();
abstractionPanel.setMaximumSize(new Dimension(1000, 35));
JPanel timingRadioPanel = new JPanel();
timingRadioPanel.setMaximumSize(new Dimension(1000, 35));
JPanel timingCheckBoxPanel = new JPanel();
timingCheckBoxPanel.setMaximumSize(new Dimension(1000, 30));
JPanel otherPanel = new JPanel();
otherPanel.setMaximumSize(new Dimension(1000, 35));
JPanel algorithmPanel = new JPanel();
algorithmPanel.setMaximumSize(new Dimension(1000, 35));
//JPanel buttonPanel = new JPanel();
JPanel compilationPanel = new JPanel();
compilationPanel.setMaximumSize(new Dimension(1000, 35));
JPanel advancedPanel = new JPanel();
advancedPanel.setMaximumSize(new Dimension(1000, 35));
JPanel bddPanel = new JPanel();
bddPanel.setMaximumSize(new Dimension(1000, 35));
JPanel pruningPanel = new JPanel();
pruningPanel.setMaximumSize(new Dimension(1000, 35));
JPanel advTimingPanel = new JPanel();
advTimingPanel.setMaximumSize(new Dimension(1000, 62));
advTimingPanel.setPreferredSize(new Dimension(1000, 62));
bddSize = new JTextField("");
bddSize.setPreferredSize(new Dimension(40, 18));
//oldBdd = bddSize.getText();
//componentField = new JTextField("");
//componentList = new PropertyList("");
abstractLabel = new JLabel("Abstraction:");
algorithm = new JLabel("Verification Algorithm:");
timingMethod = new JLabel("Timing Method:");
timingOptions = new JLabel("Timing Options:");
otherOptions = new JLabel("Other Options:");
otherOptions2 = new JLabel("Other Options:");
compilation = new JLabel("Compilation Options:");
bddSizeLabel = new JLabel("BDD Linkspace Size:");
advTiming = new JLabel("Timing Options:");
// Initializes the radio buttons and check boxes
// Abstraction Options
none = new JRadioButton("None");
simplify = new JRadioButton("Simplification");
abstractLhpn = new JRadioButton("Abstraction");
// Timing Methods
if (atacs) {
untimed = new JRadioButton("Untimed");
geometric = new JRadioButton("Geometric");
posets = new JRadioButton("POSETs");
bag = new JRadioButton("BAG");
bap = new JRadioButton("BAP");
baptdc = new JRadioButton("BAPTDC");
}
else {
bdd = new JRadioButton("BDD");
dbm = new JRadioButton("DBM");
smt = new JRadioButton("SMT");
}
lhpn = new JRadioButton("LPN");
view = new JRadioButton("View");
// Basic Timing Options
abst = new JCheckBox("Abstract");
partialOrder = new JCheckBox("Partial Order");
// Other Basic Options
dot = new JCheckBox("Dot");
verbose = new JCheckBox("Verbose");
graph = new JCheckBox("Show State Graph");
// Verification Algorithms
verify = new JRadioButton("Verify");
vergate = new JRadioButton("Verify Gates");
orbits = new JRadioButton("Orbits");
search = new JRadioButton("Search");
trace = new JRadioButton("Trace");
verify.addActionListener(this);
vergate.addActionListener(this);
orbits.addActionListener(this);
search.addActionListener(this);
trace.addActionListener(this);
// Compilations Options
newTab = new JCheckBox("New Tab");
postProc = new JCheckBox("Post Processing");
redCheck = new JCheckBox("Redundancy Check");
xForm2 = new JCheckBox("Don't Use Transform 2");
expandRate = new JCheckBox("Expand Rate");
newTab.addActionListener(this);
postProc.addActionListener(this);
redCheck.addActionListener(this);
xForm2.addActionListener(this);
expandRate.addActionListener(this);
// Advanced Timing Options
genrg = new JCheckBox("Generate RG");
timsubset = new JCheckBox("Subsets");
superset = new JCheckBox("Supersets");
infopt = new JCheckBox("Infinity Optimization");
orbmatch = new JCheckBox("Orbits Match");
interleav = new JCheckBox("Interleave");
prune = new JCheckBox("Prune");
disabling = new JCheckBox("Disabling");
nofail = new JCheckBox("No fail");
keepgoing = new JCheckBox("Keep going");
explpn = new JCheckBox("Expand LPN");
genrg.addActionListener(this);
timsubset.addActionListener(this);
superset.addActionListener(this);
infopt.addActionListener(this);
orbmatch.addActionListener(this);
interleav.addActionListener(this);
prune.addActionListener(this);
disabling.addActionListener(this);
nofail.addActionListener(this);
keepgoing.addActionListener(this);
explpn.addActionListener(this);
// Other Advanced Options
nochecks = new JCheckBox("No checks");
reduction = new JCheckBox("Reduction");
nochecks.addActionListener(this);
reduction.addActionListener(this);
// Component List
//addComponent = new JButton("Add Component");
//removeComponent = new JButton("Remove Component");
// addComponent.addActionListener(this);
// removeComponent.addActionListener(this);
GridBagConstraints constraints = new GridBagConstraints();
variables = new PropertyList("Variable List");
EditButton editVar = new EditButton("Edit Variable");
JPanel varPanel = Utility.createPanel(this, "Variables", variables, null, null, editVar);
constraints.gridx = 0;
constraints.gridy = 1;
abstractionGroup = new ButtonGroup();
timingMethodGroup = new ButtonGroup();
algorithmGroup = new ButtonGroup();
abstractLhpn.setSelected(true);
if (lema) {
dbm.setSelected(true);
}
else {
untimed.setSelected(true);
}
verify.setSelected(true);
// Groups the radio buttons
abstractionGroup.add(none);
abstractionGroup.add(simplify);
abstractionGroup.add(abstractLhpn);
if (lema) {
timingMethodGroup.add(bdd);
timingMethodGroup.add(dbm);
timingMethodGroup.add(smt);
}
else {
timingMethodGroup.add(untimed);
timingMethodGroup.add(geometric);
timingMethodGroup.add(posets);
timingMethodGroup.add(bag);
timingMethodGroup.add(bap);
timingMethodGroup.add(baptdc);
}
timingMethodGroup.add(lhpn);
timingMethodGroup.add(view);
algorithmGroup.add(verify);
algorithmGroup.add(vergate);
algorithmGroup.add(orbits);
algorithmGroup.add(search);
algorithmGroup.add(trace);
JPanel basicOptions = new JPanel();
// Adds the buttons to their panels
abstractionPanel.add(abstractLabel);
abstractionPanel.add(none);
abstractionPanel.add(simplify);
abstractionPanel.add(abstractLhpn);
timingRadioPanel.add(timingMethod);
if (lema) {
timingRadioPanel.add(bdd);
timingRadioPanel.add(dbm);
timingRadioPanel.add(smt);
}
else {
timingRadioPanel.add(untimed);
timingRadioPanel.add(geometric);
timingRadioPanel.add(posets);
timingRadioPanel.add(bag);
timingRadioPanel.add(bap);
timingRadioPanel.add(baptdc);
}
timingRadioPanel.add(lhpn);
timingRadioPanel.add(view);
timingCheckBoxPanel.add(timingOptions);
timingCheckBoxPanel.add(abst);
timingCheckBoxPanel.add(partialOrder);
otherPanel.add(otherOptions);
otherPanel.add(dot);
otherPanel.add(verbose);
otherPanel.add(graph);
algorithmPanel.add(algorithm);
algorithmPanel.add(verify);
algorithmPanel.add(vergate);
algorithmPanel.add(orbits);
algorithmPanel.add(search);
algorithmPanel.add(trace);
compilationPanel.add(compilation);
compilationPanel.add(newTab);
compilationPanel.add(postProc);
compilationPanel.add(redCheck);
compilationPanel.add(xForm2);
compilationPanel.add(expandRate);
advTimingPanel.add(advTiming);
advTimingPanel.add(genrg);
advTimingPanel.add(timsubset);
advTimingPanel.add(superset);
advTimingPanel.add(infopt);
advTimingPanel.add(orbmatch);
advTimingPanel.add(interleav);
advTimingPanel.add(prune);
advTimingPanel.add(disabling);
advTimingPanel.add(nofail);
advTimingPanel.add(keepgoing);
advTimingPanel.add(explpn);
advancedPanel.add(otherOptions2);
advancedPanel.add(nochecks);
advancedPanel.add(reduction);
bddPanel.add(bddSizeLabel);
bddPanel.add(bddSize);
basicOptions.add(varPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
}
public class EditButton extends AbstractRunnableNamedButton {
/**
*
*/
private static final long serialVersionUID = 1L;
public EditButton(String name) {
super(name);
}
@Override
public void run() {
new EditCommand().run();
}
}
private class EditCommand implements Runnable {
public EditCommand() {
// this.name = name;
//this.list = list;
}
@Override
public void run() {
}
/*
public String getName() {
return name;
}
private String name = null;
*/
//private PropertyList list = null;
}
} | MyersResearchGroup/iBioSim | gui/src/main/java/edu/utah/ece/async/ibiosim/gui/verificationView/ParameterEditor.java | 3,858 | //oldBdd = bddSize.getText(); | line_comment | nl | /*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.ibiosim.gui.verificationView;
import javax.swing.*;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.AbstractRunnableNamedButton;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyList;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.Runnable;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
/**
* This class creates a GUI front end for the Verification tool. It provides the
* necessary options to run an atacs simulation of the circuit and manage the
* results from the BioSim GUI.
*
* @author Kevin Jones
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ParameterEditor extends JPanel implements ActionListener {
private static final long serialVersionUID = -5806315070287184299L;
//private JButton save, run, viewCircuit, viewTrace, viewLog, addComponent, removeComponent;
private JLabel algorithm, timingMethod, timingOptions, otherOptions, otherOptions2,
compilation, bddSizeLabel, advTiming, abstractLabel;
private JRadioButton untimed, geometric, posets, bag, bap, baptdc, verify, vergate, orbits,
search, trace, bdd, dbm, smt, lhpn, view, none, simplify, abstractLhpn;
private JCheckBox abst, partialOrder, dot, verbose, graph, genrg, timsubset, superset, infopt,
orbmatch, interleav, prune, disabling, nofail, keepgoing, explpn, nochecks, reduction,
newTab, postProc, redCheck, xForm2, expandRate;
private JTextField bddSize;
//private JTextField backgroundField, componentField;
private ButtonGroup timingMethodGroup, algorithmGroup, abstractionGroup;
private PropertyList variables;
private String root;
//private String directory, verFile, oldBdd, sourceFileNoPath;
public String verifyFile;
//private boolean change, atacs;
//private JTabbedPane bigTab;
//private PropertyList componentList;
//private AbstPane abstPane;
//private Log log;
//private BioSim biosim;
/**
* This is the constructor for the Verification class. It initializes all
* the input fields, puts them on panels, adds the panels to the frame, and
* then displays the frame.
*/
public ParameterEditor(String directory, boolean lema, boolean atacs) {
String[] tempDir = GlobalConstants.splitPath(directory);
root = tempDir[0];
for (int i = 1; i < tempDir.length - 1; i++) {
root = root + File.separator + tempDir[i];
}
JPanel abstractionPanel = new JPanel();
abstractionPanel.setMaximumSize(new Dimension(1000, 35));
JPanel timingRadioPanel = new JPanel();
timingRadioPanel.setMaximumSize(new Dimension(1000, 35));
JPanel timingCheckBoxPanel = new JPanel();
timingCheckBoxPanel.setMaximumSize(new Dimension(1000, 30));
JPanel otherPanel = new JPanel();
otherPanel.setMaximumSize(new Dimension(1000, 35));
JPanel algorithmPanel = new JPanel();
algorithmPanel.setMaximumSize(new Dimension(1000, 35));
//JPanel buttonPanel = new JPanel();
JPanel compilationPanel = new JPanel();
compilationPanel.setMaximumSize(new Dimension(1000, 35));
JPanel advancedPanel = new JPanel();
advancedPanel.setMaximumSize(new Dimension(1000, 35));
JPanel bddPanel = new JPanel();
bddPanel.setMaximumSize(new Dimension(1000, 35));
JPanel pruningPanel = new JPanel();
pruningPanel.setMaximumSize(new Dimension(1000, 35));
JPanel advTimingPanel = new JPanel();
advTimingPanel.setMaximumSize(new Dimension(1000, 62));
advTimingPanel.setPreferredSize(new Dimension(1000, 62));
bddSize = new JTextField("");
bddSize.setPreferredSize(new Dimension(40, 18));
//oldBdd =<SUF>
//componentField = new JTextField("");
//componentList = new PropertyList("");
abstractLabel = new JLabel("Abstraction:");
algorithm = new JLabel("Verification Algorithm:");
timingMethod = new JLabel("Timing Method:");
timingOptions = new JLabel("Timing Options:");
otherOptions = new JLabel("Other Options:");
otherOptions2 = new JLabel("Other Options:");
compilation = new JLabel("Compilation Options:");
bddSizeLabel = new JLabel("BDD Linkspace Size:");
advTiming = new JLabel("Timing Options:");
// Initializes the radio buttons and check boxes
// Abstraction Options
none = new JRadioButton("None");
simplify = new JRadioButton("Simplification");
abstractLhpn = new JRadioButton("Abstraction");
// Timing Methods
if (atacs) {
untimed = new JRadioButton("Untimed");
geometric = new JRadioButton("Geometric");
posets = new JRadioButton("POSETs");
bag = new JRadioButton("BAG");
bap = new JRadioButton("BAP");
baptdc = new JRadioButton("BAPTDC");
}
else {
bdd = new JRadioButton("BDD");
dbm = new JRadioButton("DBM");
smt = new JRadioButton("SMT");
}
lhpn = new JRadioButton("LPN");
view = new JRadioButton("View");
// Basic Timing Options
abst = new JCheckBox("Abstract");
partialOrder = new JCheckBox("Partial Order");
// Other Basic Options
dot = new JCheckBox("Dot");
verbose = new JCheckBox("Verbose");
graph = new JCheckBox("Show State Graph");
// Verification Algorithms
verify = new JRadioButton("Verify");
vergate = new JRadioButton("Verify Gates");
orbits = new JRadioButton("Orbits");
search = new JRadioButton("Search");
trace = new JRadioButton("Trace");
verify.addActionListener(this);
vergate.addActionListener(this);
orbits.addActionListener(this);
search.addActionListener(this);
trace.addActionListener(this);
// Compilations Options
newTab = new JCheckBox("New Tab");
postProc = new JCheckBox("Post Processing");
redCheck = new JCheckBox("Redundancy Check");
xForm2 = new JCheckBox("Don't Use Transform 2");
expandRate = new JCheckBox("Expand Rate");
newTab.addActionListener(this);
postProc.addActionListener(this);
redCheck.addActionListener(this);
xForm2.addActionListener(this);
expandRate.addActionListener(this);
// Advanced Timing Options
genrg = new JCheckBox("Generate RG");
timsubset = new JCheckBox("Subsets");
superset = new JCheckBox("Supersets");
infopt = new JCheckBox("Infinity Optimization");
orbmatch = new JCheckBox("Orbits Match");
interleav = new JCheckBox("Interleave");
prune = new JCheckBox("Prune");
disabling = new JCheckBox("Disabling");
nofail = new JCheckBox("No fail");
keepgoing = new JCheckBox("Keep going");
explpn = new JCheckBox("Expand LPN");
genrg.addActionListener(this);
timsubset.addActionListener(this);
superset.addActionListener(this);
infopt.addActionListener(this);
orbmatch.addActionListener(this);
interleav.addActionListener(this);
prune.addActionListener(this);
disabling.addActionListener(this);
nofail.addActionListener(this);
keepgoing.addActionListener(this);
explpn.addActionListener(this);
// Other Advanced Options
nochecks = new JCheckBox("No checks");
reduction = new JCheckBox("Reduction");
nochecks.addActionListener(this);
reduction.addActionListener(this);
// Component List
//addComponent = new JButton("Add Component");
//removeComponent = new JButton("Remove Component");
// addComponent.addActionListener(this);
// removeComponent.addActionListener(this);
GridBagConstraints constraints = new GridBagConstraints();
variables = new PropertyList("Variable List");
EditButton editVar = new EditButton("Edit Variable");
JPanel varPanel = Utility.createPanel(this, "Variables", variables, null, null, editVar);
constraints.gridx = 0;
constraints.gridy = 1;
abstractionGroup = new ButtonGroup();
timingMethodGroup = new ButtonGroup();
algorithmGroup = new ButtonGroup();
abstractLhpn.setSelected(true);
if (lema) {
dbm.setSelected(true);
}
else {
untimed.setSelected(true);
}
verify.setSelected(true);
// Groups the radio buttons
abstractionGroup.add(none);
abstractionGroup.add(simplify);
abstractionGroup.add(abstractLhpn);
if (lema) {
timingMethodGroup.add(bdd);
timingMethodGroup.add(dbm);
timingMethodGroup.add(smt);
}
else {
timingMethodGroup.add(untimed);
timingMethodGroup.add(geometric);
timingMethodGroup.add(posets);
timingMethodGroup.add(bag);
timingMethodGroup.add(bap);
timingMethodGroup.add(baptdc);
}
timingMethodGroup.add(lhpn);
timingMethodGroup.add(view);
algorithmGroup.add(verify);
algorithmGroup.add(vergate);
algorithmGroup.add(orbits);
algorithmGroup.add(search);
algorithmGroup.add(trace);
JPanel basicOptions = new JPanel();
// Adds the buttons to their panels
abstractionPanel.add(abstractLabel);
abstractionPanel.add(none);
abstractionPanel.add(simplify);
abstractionPanel.add(abstractLhpn);
timingRadioPanel.add(timingMethod);
if (lema) {
timingRadioPanel.add(bdd);
timingRadioPanel.add(dbm);
timingRadioPanel.add(smt);
}
else {
timingRadioPanel.add(untimed);
timingRadioPanel.add(geometric);
timingRadioPanel.add(posets);
timingRadioPanel.add(bag);
timingRadioPanel.add(bap);
timingRadioPanel.add(baptdc);
}
timingRadioPanel.add(lhpn);
timingRadioPanel.add(view);
timingCheckBoxPanel.add(timingOptions);
timingCheckBoxPanel.add(abst);
timingCheckBoxPanel.add(partialOrder);
otherPanel.add(otherOptions);
otherPanel.add(dot);
otherPanel.add(verbose);
otherPanel.add(graph);
algorithmPanel.add(algorithm);
algorithmPanel.add(verify);
algorithmPanel.add(vergate);
algorithmPanel.add(orbits);
algorithmPanel.add(search);
algorithmPanel.add(trace);
compilationPanel.add(compilation);
compilationPanel.add(newTab);
compilationPanel.add(postProc);
compilationPanel.add(redCheck);
compilationPanel.add(xForm2);
compilationPanel.add(expandRate);
advTimingPanel.add(advTiming);
advTimingPanel.add(genrg);
advTimingPanel.add(timsubset);
advTimingPanel.add(superset);
advTimingPanel.add(infopt);
advTimingPanel.add(orbmatch);
advTimingPanel.add(interleav);
advTimingPanel.add(prune);
advTimingPanel.add(disabling);
advTimingPanel.add(nofail);
advTimingPanel.add(keepgoing);
advTimingPanel.add(explpn);
advancedPanel.add(otherOptions2);
advancedPanel.add(nochecks);
advancedPanel.add(reduction);
bddPanel.add(bddSizeLabel);
bddPanel.add(bddSize);
basicOptions.add(varPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
}
public class EditButton extends AbstractRunnableNamedButton {
/**
*
*/
private static final long serialVersionUID = 1L;
public EditButton(String name) {
super(name);
}
@Override
public void run() {
new EditCommand().run();
}
}
private class EditCommand implements Runnable {
public EditCommand() {
// this.name = name;
//this.list = list;
}
@Override
public void run() {
}
/*
public String getName() {
return name;
}
private String name = null;
*/
//private PropertyList list = null;
}
} |
208252_4 | /* Copyright (C) 2010 - 2011 Fabian Neundorf, Philip Caroli,
* Maximilian Madlung, Usman Ghani Ahmed, Jeremias Mechler
*
* 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 org.ojim.rmi.server;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class StartNetOjim {
/**
* Klasse verwaltet eine Instanz des Remote Objektes , welches unter einem
* festgelegten Namen über das Netzwerk erreichbar ist
* Netzwerk Objekt wird bei dem lokalen Namendienst registriert, portReg und
* portStub müssen von der lokalen Firewall und der Hardware Firewall
* (Router) freigegeben werden. Bitte Achten Sie auch darauf, dass
* Ports die schon von ihrem Betriebssystem benutzt werden, nicht für ihren Server
* benutzt werden können. Eine Liste mit den Standardports die von ihrem Betriebssystem
* verwendet werden, finden Sie auf http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers.
*
*
* @param portReg Port für die lokale Registry
*
* @param portStub Port für das exportieren des Objekts
*
* @param ip ip Adresse unter welcher der Namendienst erreichbar ist
*/
public void startServer(int portReg,String ip,ImplNetOjim ojimServer){
System.out.println("\n"+"Server wird eingerichtet...");
try {
Registry registry = LocateRegistry.createRegistry(portReg);
//registry.list();
String registryURL = "rmi://"+ip+":" + portReg + "/myServer";
Naming.rebind(registryURL, ojimServer);
System.err.println("Server ist bereit");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
/**
* Beendet die gestartete Registry
*/
public void endRegistry(ImplNetOjim ojimServer){
try {
Registry registry = LocateRegistry.getRegistry();
registry.unbind("myServer");
UnicastRemoteObject.unexportObject(ojimServer, true);
UnicastRemoteObject.unexportObject(registry, true);
registry = null;
} catch (RemoteException e) {
System.out.println("Es wurde keine Registry gestartet!");
} catch (NotBoundException e) {
System.out.println("Es ist kein Objekt in der Registry registriert,"+"\n"+
"somit kann auch kein Remote Objekt von der Registry abgemeldet werden!");
}
}
}
| N0T3P4D/PSE | src/org/ojim/rmi/server/StartNetOjim.java | 1,006 | /**
* Beendet die gestartete Registry
*/ | block_comment | nl | /* Copyright (C) 2010 - 2011 Fabian Neundorf, Philip Caroli,
* Maximilian Madlung, Usman Ghani Ahmed, Jeremias Mechler
*
* 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 org.ojim.rmi.server;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class StartNetOjim {
/**
* Klasse verwaltet eine Instanz des Remote Objektes , welches unter einem
* festgelegten Namen über das Netzwerk erreichbar ist
* Netzwerk Objekt wird bei dem lokalen Namendienst registriert, portReg und
* portStub müssen von der lokalen Firewall und der Hardware Firewall
* (Router) freigegeben werden. Bitte Achten Sie auch darauf, dass
* Ports die schon von ihrem Betriebssystem benutzt werden, nicht für ihren Server
* benutzt werden können. Eine Liste mit den Standardports die von ihrem Betriebssystem
* verwendet werden, finden Sie auf http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers.
*
*
* @param portReg Port für die lokale Registry
*
* @param portStub Port für das exportieren des Objekts
*
* @param ip ip Adresse unter welcher der Namendienst erreichbar ist
*/
public void startServer(int portReg,String ip,ImplNetOjim ojimServer){
System.out.println("\n"+"Server wird eingerichtet...");
try {
Registry registry = LocateRegistry.createRegistry(portReg);
//registry.list();
String registryURL = "rmi://"+ip+":" + portReg + "/myServer";
Naming.rebind(registryURL, ojimServer);
System.err.println("Server ist bereit");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
/**
* Beendet die gestartete<SUF>*/
public void endRegistry(ImplNetOjim ojimServer){
try {
Registry registry = LocateRegistry.getRegistry();
registry.unbind("myServer");
UnicastRemoteObject.unexportObject(ojimServer, true);
UnicastRemoteObject.unexportObject(registry, true);
registry = null;
} catch (RemoteException e) {
System.out.println("Es wurde keine Registry gestartet!");
} catch (NotBoundException e) {
System.out.println("Es ist kein Objekt in der Registry registriert,"+"\n"+
"somit kann auch kein Remote Objekt von der Registry abgemeldet werden!");
}
}
}
|
52446_0 | package battleship.placementsStrategy;
import battleship.Boat;
import java.util.ArrayList;
/*
stap 1:
new classe BattleshipPlacementStrategy
stap 2:
in BattleshipPlayerType new playertype aanmaken (vergeet niet ook de naam te veranderen),
en in getplayertypes the naam bij zetten
voor placement strategien kiezen we de slechste shooting ai "BattleshipSequentialShootingAi::new"
stap 3:
nieuwe else if statement met player type toevoegen.
*/
public interface BattleshipPlacementStrategy {
ArrayList<Boat> getShips();
}
| N1cknamed/isy-project | src/main/java/battleship/placementsStrategy/BattleshipPlacementStrategy.java | 164 | /*
stap 1:
new classe BattleshipPlacementStrategy
stap 2:
in BattleshipPlayerType new playertype aanmaken (vergeet niet ook de naam te veranderen),
en in getplayertypes the naam bij zetten
voor placement strategien kiezen we de slechste shooting ai "BattleshipSequentialShootingAi::new"
stap 3:
nieuwe else if statement met player type toevoegen.
*/ | block_comment | nl | package battleship.placementsStrategy;
import battleship.Boat;
import java.util.ArrayList;
/*
stap 1:
new<SUF>*/
public interface BattleshipPlacementStrategy {
ArrayList<Boat> getShips();
}
|
158661_1 | public class mian {
public static void main(String[] args) {
Vrachtschip S = new Vrachtschip("SuperMaramiu", 10, 7500);
System.out.println(S.toString());
S.loods();
Haven H = new Haven(0,150);
H.voegSchipToe(S);
System.out.println("______________________________________________________________");
Haven haven = new Haven();
Schip zeilboot = new Zeilboot("smalleSally", 15, 1);
Schip vrachtschip = new Vrachtschip("SuperMaramiu", 300, 7500);
System.out.println("______________________________________________________________");
System.out.println(haven.aanmeren(zeilboot));
System.out.println("______________________________________________________________");
System.out.println(haven.aanmeren(vrachtschip));
Vrachtschip groteFrans = new Vrachtschip("GroteFrans", 100, 2500);
Vrachtschip superMaramiu = new Vrachtschip("SuperMaramiu", 400, 7500);
Zeilboot smalleSally = new Zeilboot("SmalleSally", 15, 1);
System.out.println("================================================");
// 2. Maak een Haven "Wally-Kiwi"
Haven wallyKiwi = new Haven();
System.out.println("================================================");
// Laat GroteFrans en SmalleSally aanmeren in de haven
wallyKiwi.aanmeren(groteFrans);
wallyKiwi.aanmeren(smalleSally);
System.out.println("================================================");
System.out.println("================================================");
// 3. Laat SuperMaramiu aanmeren, dit mag niet lukken omdat er geen plaats meer is.
wallyKiwi.aanmeren(superMaramiu);
System.out.println("================================================");
}
}
| NAJJAT/Javaexams | untitled/src/mian.java | 536 | // Laat GroteFrans en SmalleSally aanmeren in de haven | line_comment | nl | public class mian {
public static void main(String[] args) {
Vrachtschip S = new Vrachtschip("SuperMaramiu", 10, 7500);
System.out.println(S.toString());
S.loods();
Haven H = new Haven(0,150);
H.voegSchipToe(S);
System.out.println("______________________________________________________________");
Haven haven = new Haven();
Schip zeilboot = new Zeilboot("smalleSally", 15, 1);
Schip vrachtschip = new Vrachtschip("SuperMaramiu", 300, 7500);
System.out.println("______________________________________________________________");
System.out.println(haven.aanmeren(zeilboot));
System.out.println("______________________________________________________________");
System.out.println(haven.aanmeren(vrachtschip));
Vrachtschip groteFrans = new Vrachtschip("GroteFrans", 100, 2500);
Vrachtschip superMaramiu = new Vrachtschip("SuperMaramiu", 400, 7500);
Zeilboot smalleSally = new Zeilboot("SmalleSally", 15, 1);
System.out.println("================================================");
// 2. Maak een Haven "Wally-Kiwi"
Haven wallyKiwi = new Haven();
System.out.println("================================================");
// Laat GroteFrans<SUF>
wallyKiwi.aanmeren(groteFrans);
wallyKiwi.aanmeren(smalleSally);
System.out.println("================================================");
System.out.println("================================================");
// 3. Laat SuperMaramiu aanmeren, dit mag niet lukken omdat er geen plaats meer is.
wallyKiwi.aanmeren(superMaramiu);
System.out.println("================================================");
}
}
|
79421_0 |
public class Volmachthouder extends Persoon {
public Volmachthouder(String voornaam, String achternaam) {
super(voornaam, achternaam);
}
@Override
public boolean equals(Object obj) {
// De klasse Persoon zijn equals methode kijkt al of Personen gelijk zijn op basis van hun achternaam
// Hierdoor kunnen we de methode van de klasse Persoon oproepen via super!
return super.equals(obj);
}
}
| NAJJAT/hoogschoolExecption | Volmachthouder.java | 127 | // De klasse Persoon zijn equals methode kijkt al of Personen gelijk zijn op basis van hun achternaam | line_comment | nl |
public class Volmachthouder extends Persoon {
public Volmachthouder(String voornaam, String achternaam) {
super(voornaam, achternaam);
}
@Override
public boolean equals(Object obj) {
// De klasse<SUF>
// Hierdoor kunnen we de methode van de klasse Persoon oproepen via super!
return super.equals(obj);
}
}
|
36399_11 | /*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package gov.nasa.worldwind.util.glu.tessellator;
class Geom {
private Geom() {
}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->t = 0 and
* let r be the negated result (this evaluates (uw)(v->s)), then
* r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->s = 0 and
* let r be the negated result (this evaluates (uw)(v->t)), then
* r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Returns a number whose sign matches TransEval(u,v,w) but which
* is cheaper to evaluate. Returns > 0, == 0 , or < 0
* as v is above, on, or below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results
* on some degenerate inputs, so the client must have some way to
* handle this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering,
* and interpolate the intersection s-value from these. Then repeat
* using the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
}
| NASAWorldWind/WorldWindAndroid | worldwind/src/main/java/gov/nasa/worldwind/util/glu/tessellator/Geom.java | 3,807 | /* Interpolate between o2 and d1 */ | block_comment | nl | /*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package gov.nasa.worldwind.util.glu.tessellator;
class Geom {
private Geom() {
}
/* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->t - (uw)(v->s), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->t = 0 and
* let r be the negated result (this evaluates (uw)(v->s)), then
* r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t).
*/
static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR));
} else {
return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) {
double gapL, gapR;
assert (VertLeq(u, v) && VertLeq(v, w));
gapL = v.s - u.s;
gapR = w.s - v.s;
if (gapL + gapR > 0) {
return (v.t - w.t) * gapL + (v.t - u.t) * gapR;
}
/* vertical line */
return 0;
}
/***********************************************************************
* Define versions of EdgeSign, EdgeEval with s and t transposed.
*/
static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w),
* evaluates the t-coord of the edge uw at the s-coord of the vertex v.
* Returns v->s - (uw)(v->t), ie. the signed distance from uw to v.
* If uw is vertical (and thus passes thru v), the result is zero.
*
* The calculation is extremely accurate and stable, even when v
* is very close to u or w. In particular if we set v->s = 0 and
* let r be the negated result (this evaluates (uw)(v->t)), then
* r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s).
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
if (gapL < gapR) {
return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR));
} else {
return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR));
}
}
/* vertical line */
return 0;
}
static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) {
/* Returns a number whose sign matches TransEval(u,v,w) but which
* is cheaper to evaluate. Returns > 0, == 0 , or < 0
* as v is above, on, or below the edge uw.
*/
double gapL, gapR;
assert (TransLeq(u, v) && TransLeq(v, w));
gapL = v.t - u.t;
gapR = w.t - v.t;
if (gapL + gapR > 0) {
return (v.s - w.s) * gapL + (v.s - u.s) * gapR;
}
/* vertical line */
return 0;
}
static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) {
/* For almost-degenerate situations, the results are not reliable.
* Unless the floating-point arithmetic can be performed without
* rounding errors, *any* implementation will give incorrect results
* on some degenerate inputs, so the client must have some way to
* handle this situation.
*/
return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0;
}
/* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b),
* or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces
* this in the rare case that one argument is slightly negative.
* The implementation is extremely stable numerically.
* In particular it guarantees that the result r satisfies
* MIN(x,y) <= r <= MAX(x,y), and the results are very accurate
* even when a and b differ greatly in magnitude.
*/
static double Interpolate(double a, double x, double b, double y) {
a = (a < 0) ? 0 : a;
b = (b < 0) ? 0 : b;
if (a <= b) {
if (b == 0) {
return (x + y) / 2.0;
} else {
return (x + (y - x) * (a / (a + b)));
}
} else {
return (y + (x - y) * (b / (a + b)));
}
}
static void EdgeIntersect(GLUvertex o1, GLUvertex d1,
GLUvertex o2, GLUvertex d2,
GLUvertex v)
/* Given edges (o1,d1) and (o2,d2), compute their point of intersection.
* The computed point is guaranteed to lie in the intersection of the
* bounding rectangles defined by each edge.
*/ {
double z1, z2;
/* This is certainly not the most efficient way to find the intersection
* of two line segments, but it is very numerically stable.
*
* Strategy: find the two middle vertices in the VertLeq ordering,
* and interpolate the intersection s-value from these. Then repeat
* using the TransLeq ordering to find the intersection t-value.
*/
if (!VertLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!VertLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!VertLeq(o1, o2)) {
GLUvertex temp = o1;
o1 = o2;
o2 = temp;
temp = d1;
d1 = d2;
d2 = temp;
}
if (!VertLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.s = (o2.s + d1.s) / 2.0;
} else if (VertLeq(d1, d2)) {
/* Interpolate between o2<SUF>*/
z1 = EdgeEval(o1, o2, d1);
z2 = EdgeEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d1.s);
} else {
/* Interpolate between o2 and d2 */
z1 = EdgeSign(o1, o2, d1);
z2 = -EdgeSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.s = Interpolate(z1, o2.s, z2, d2.s);
}
/* Now repeat the process for t */
if (!TransLeq(o1, d1)) {
GLUvertex temp = o1;
o1 = d1;
d1 = temp;
}
if (!TransLeq(o2, d2)) {
GLUvertex temp = o2;
o2 = d2;
d2 = temp;
}
if (!TransLeq(o1, o2)) {
GLUvertex temp = o2;
o2 = o1;
o1 = temp;
temp = d2;
d2 = d1;
d1 = temp;
}
if (!TransLeq(o2, d1)) {
/* Technically, no intersection -- do our best */
v.t = (o2.t + d1.t) / 2.0;
} else if (TransLeq(d1, d2)) {
/* Interpolate between o2 and d1 */
z1 = TransEval(o1, o2, d1);
z2 = TransEval(o2, d1, d2);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d1.t);
} else {
/* Interpolate between o2 and d2 */
z1 = TransSign(o1, o2, d1);
z2 = -TransSign(o1, d2, d1);
if (z1 + z2 < 0) {
z1 = -z1;
z2 = -z2;
}
v.t = Interpolate(z1, o2.t, z2, d2.t);
}
}
static boolean VertEq(GLUvertex u, GLUvertex v) {
return u.s == v.s && u.t == v.t;
}
static boolean VertLeq(GLUvertex u, GLUvertex v) {
return u.s < v.s || (u.s == v.s && u.t <= v.t);
}
/* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */
static boolean TransLeq(GLUvertex u, GLUvertex v) {
return u.t < v.t || (u.t == v.t && u.s <= v.s);
}
static boolean EdgeGoesLeft(GLUhalfEdge e) {
return VertLeq(e.Sym.Org, e.Org);
}
static boolean EdgeGoesRight(GLUhalfEdge e) {
return VertLeq(e.Org, e.Sym.Org);
}
static double VertL1dist(GLUvertex u, GLUvertex v) {
return Math.abs(u.s - v.s) + Math.abs(u.t - v.t);
}
}
|
14122_0 | package Formulas;
import java.util.ArrayList;
public class JuliantiFormules {
//TODO: JAVADOCCEN
// Input is een arraylist van objecten (doubles en strings enzo)...
public static String intFunction(ArrayList<Object> input)
{
if(input.size() >= 2)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(input.get(0) instanceof Double)
{
double inputdouble = (double) input.get(0);
double outputdouble = Math.floor(inputdouble);
//Math.floor rond het altijd af naar een lager geheel getal
//Dus moet je nu nog kijken of je hem naar boven moet afronden:
if((outputdouble + 0.5) < inputdouble)
{
outputdouble++;
}
String outputstring = Double.toString(outputdouble);
return outputstring;
}
else
{
throw new IllegalArgumentException("Please select a cell containing a number.");
}
}
public static String islogical(ArrayList<Object> input)
{
if(input.size() > 1)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(input.get(0) instanceof String)
{
String inputstring = (String) input.get(0);
if(inputstring.matches("true")|| inputstring.matches("TRUE") || inputstring.matches("True") || inputstring.matches("false") || inputstring.matches("False") || inputstring.matches("FALSE"))
{
return "true";
}
}
return "false";
}
public static String iseven(ArrayList<Object> input)
{
if(input.size() > 1)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(!(input.get(0) instanceof Double))
{
throw new IllegalArgumentException("Please select a cell containing a number.");
}
if(input.get(0) instanceof Double)
{
double inputdouble = (double) input.get(0);
if(inputdouble%2 == 0)
{
return "true";
}
}
return "false";
}
public static String isnumber(ArrayList<Object> input)
{
if(input.size() > 1)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(input.get(0) instanceof Double)
{
return "true";
}
return "false";
}
} | NBroekhuijsen/V2OOP | src/Formulas/JuliantiFormules.java | 692 | // Input is een arraylist van objecten (doubles en strings enzo)... | line_comment | nl | package Formulas;
import java.util.ArrayList;
public class JuliantiFormules {
//TODO: JAVADOCCEN
// Input is<SUF>
public static String intFunction(ArrayList<Object> input)
{
if(input.size() >= 2)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(input.get(0) instanceof Double)
{
double inputdouble = (double) input.get(0);
double outputdouble = Math.floor(inputdouble);
//Math.floor rond het altijd af naar een lager geheel getal
//Dus moet je nu nog kijken of je hem naar boven moet afronden:
if((outputdouble + 0.5) < inputdouble)
{
outputdouble++;
}
String outputstring = Double.toString(outputdouble);
return outputstring;
}
else
{
throw new IllegalArgumentException("Please select a cell containing a number.");
}
}
public static String islogical(ArrayList<Object> input)
{
if(input.size() > 1)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(input.get(0) instanceof String)
{
String inputstring = (String) input.get(0);
if(inputstring.matches("true")|| inputstring.matches("TRUE") || inputstring.matches("True") || inputstring.matches("false") || inputstring.matches("False") || inputstring.matches("FALSE"))
{
return "true";
}
}
return "false";
}
public static String iseven(ArrayList<Object> input)
{
if(input.size() > 1)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(!(input.get(0) instanceof Double))
{
throw new IllegalArgumentException("Please select a cell containing a number.");
}
if(input.get(0) instanceof Double)
{
double inputdouble = (double) input.get(0);
if(inputdouble%2 == 0)
{
return "true";
}
}
return "false";
}
public static String isnumber(ArrayList<Object> input)
{
if(input.size() > 1)
{
throw new IllegalArgumentException("Please select only one cell.");
}
if(input.get(0) instanceof Double)
{
return "true";
}
return "false";
}
} |
79179_2 | /*
* Phylontal FrontEnd - a GUI frontend for Phylontal
* Copyright 2009-2011 Peter E. Midford
* This file is part of Phylontal Frontend
*
* Phylontal Frontend 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.
*
* Phylontal Frontend 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 Phylontal Frontend. If not, see <http://www.gnu.org/licenses/>.
*
* Created on Oct 8, 2009
* Last updated on April 27, 2011
*
*/
package org.ethontos.phylontal.fe.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Observable;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
import org.ethontos.phylontal.project.Alignment;
import org.ethontos.phylontal.project.OntTerm;
import org.ethontos.phylontal.project.OntologyWrapper;
import org.ethontos.phylontal.project.Project;
import org.ethontos.phylontal.project.impl.DataFactory;
import org.ethontos.phylontal.project.impl.ExtendableStringMetric;
import org.ethontos.phylontal.project.phylo.GraphTree;
import org.ethontos.phylontal.fe.UserFrontEnd;
public class MatcherTab extends TabView {
private final String SAVEOPENERROR = "Error opening file for output: ";
public enum Config {SETONTOLOGY, TWOONTOLOGY, TWOSET, UNDEFINED};
OntTerm selectedLeft = null;
OntTerm selectedRight = null;
//Menus
final private JMenuBar tabMenus = new JMenuBar();
// Match Menu Items
private JMenuItem suggestMatchItem;
private JMenuItem suggestMatchFromNiece;
//Help Menu Items
private JMenuItem showLicenseItem;
private JMenuItem matchHelpItem;
private SetListPane resultsPane;
private SetListPane setsPane1;
private SetListPane setsPane2;
private TermListPane termsPane1;
private TermListPane termsPane2;
private SimpleTreePane treePane;
private JPanel resultNamesPanel = new JPanel(); // should always be a setsPane
private JPanel leftNamesPanel = new JPanel();
private JPanel rightNamesPanel = new JPanel();
private JPanel treePanel = new JPanel();
private JLabel resultTitle = new JLabel();
private JLabel leftTitle = new JLabel();
private JLabel rightTitle = new JLabel();
private JLabel treeTitle = new JLabel();
private Config paneConfig = Config.UNDEFINED; //default for new projects
static Logger logger = Logger.getLogger(MatcherTab.class.getName());
public MatcherTab(UserFrontEnd app) {
super(app);
initializeAreas();
setConfiguration(Config.TWOONTOLOGY);
this.setVisible(true);
}
@Override
public boolean useable() {
Project p = theApp.getProject();
if (p == null)
return false;
GraphTree t = p.showTree();
if (t == null)
return false;
if (p.listOntologies().size()<2){
logger.debug("Ontologies count is " + p.listOntologies().size());
return false;
}
return true;
}
@Override
protected void showHelp() {
// TODO Auto-generated method stub
}
@Override
protected void showPreferences() {
// TODO Auto-generated method stub
}
@Override
public JMenuBar initializeMenus() {
if (tabMenus.getComponentCount() == 0){
final JMenu fileMenu = new JMenu("File");
final JMenu editMenu = new JMenu("Edit");
final JMenu matchMenu = new JMenu("Match");
final JMenu helpMenu = new JMenu("Help");
//submenus
final JMenu saveAlignmentAsMenu = new JMenu("Save Alignment As...");
tabMenus.add(fileMenu);
tabMenus.add(editMenu);
tabMenus.add(matchMenu);
if (theApp.runningOSX()){
JMenu windowMenu = new JMenu("Window");
tabMenus.add(windowMenu);
}
tabMenus.add(helpMenu);
fileMenu.add(makeSaveProjectAsItem());
fileMenu.add(saveAlignmentAsMenu);
saveAlignmentAsMenu.add(makeSaveAlignmentAsTuplesItem());
saveAlignmentAsMenu.add(makeSaveAlignmentAsOntologyItem());
matchMenu.add(makeUnGuidedMatchItem());
matchMenu.add(makeSuggestMatchItem());
matchMenu.add(makeSuggestMatchFromNieceItem());
helpMenu.add(makeShowLicenseItem(theApp));
}
return tabMenus;
}
private void initializeAreas(){
resultsPane = new SetListPane();
resultsPane.setBorder(BorderFactory.createLineBorder(Color.RED));
resultsPane.setMinimumSize(new Dimension(200,200));
resultNamesPanel.add(resultTitle);
resultNamesPanel.add(resultsPane);
termsPane1 = new TermListPane();
termsPane1.setBorder(BorderFactory.createLineBorder(Color.YELLOW));
termsPane2 = new TermListPane();
termsPane2.setBorder(BorderFactory.createLineBorder(Color.GREEN));
treePane = new SimpleTreePane();
treePane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
treeTitle.setText("Current Tree");
treePanel.setMinimumSize(new Dimension(200,200));
treePanel.add(treeTitle);
treePanel.add(treePane);
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
resultNamesPanel.setMinimumSize(new Dimension(200,200));
resultNamesPanel.setLayout(new BoxLayout(resultNamesPanel,BoxLayout.Y_AXIS));
leftNamesPanel.setLayout(new BoxLayout(leftNamesPanel,BoxLayout.Y_AXIS));
rightNamesPanel.setLayout(new BoxLayout(rightNamesPanel,BoxLayout.Y_AXIS));
treePanel.setLayout(new BoxLayout(treePanel,BoxLayout.Y_AXIS));
this.add(resultNamesPanel);
leftNamesPanel.setMinimumSize(new Dimension(200,200));
this.add(leftNamesPanel);
rightNamesPanel.setMinimumSize(new Dimension(200,200));
this.add(rightNamesPanel);
treePanel.setMinimumSize(new Dimension(200,200));
this.add(treePanel);
}
public void setConfiguration(MatcherTab.Config c){
switch (c){
case SETONTOLOGY:
configureSetOntology();
break;
case TWOSET:
configureTwoSet();
break;
case TWOONTOLOGY:
default:
configureTwoOntology();
}
}
private void configureTwoSet(){
if (!paneConfig.equals(Config.TWOSET)){
leftNamesPanel.removeAll();
leftNamesPanel.add(leftTitle);
leftNamesPanel.add(setsPane1);
rightNamesPanel.removeAll();
rightNamesPanel.add(rightTitle);
rightNamesPanel.add(setsPane2);
paneConfig = Config.TWOSET;
}
}
private void configureSetOntology(){
if (!paneConfig.equals(Config.SETONTOLOGY)){
leftNamesPanel.removeAll();
leftNamesPanel.add(leftTitle);
leftNamesPanel.add(setsPane1);
rightNamesPanel.removeAll();
rightNamesPanel.add(rightTitle);
rightNamesPanel.add(setsPane1);
paneConfig = Config.SETONTOLOGY;
}
}
private void configureTwoOntology(){
if (!paneConfig.equals(Config.TWOONTOLOGY)){
leftNamesPanel.removeAll();
leftNamesPanel.add(leftTitle);
leftNamesPanel.add(termsPane1);
rightNamesPanel.removeAll();
rightNamesPanel.add(rightTitle);
rightNamesPanel.add(termsPane2);
paneConfig = Config.TWOONTOLOGY;
}
}
private void updatePanels(){
GraphTree selectedTree = theApp.getProject().selectTree(0);
treePane.setTree(selectedTree);
// cheating here
List <URI> onts = getProject().listOntologies();
if (onts.size()>1){
OntologyWrapper w1 = getProject().showOntology(onts.get(0));
OntologyWrapper w2 = getProject().showOntology(onts.get(1));
termsPane1.setTerms(w1);
termsPane2.setTerms(w2);
}
else {
JOptionPane.showMessageDialog(this, "Ontologies haven't been loaded yet", "No Ontologies", JOptionPane.ERROR_MESSAGE);
}
treePane.setVisible(true);
}
public void update(Observable o, Object arg){
// super.update(o,arg); //tabview is currently abstract, so nothing to do here
if (o.equals(getProject())){
if (useable()){
theApp.getMainFrame().enableTab(this, "Construct alignment");
updatePanels();
}
}
if (arg != null && arg instanceof GraphTree){
// if another tree is selected, something should happen in the tree pane
}
if (selectedLeft != null && selectedRight != null){
switch(paneConfig){
case TWOONTOLOGY:{
logger.debug("Ready to match terms from right and left");
int userChoice = JOptionPane.showConfirmDialog(this,"Join "+ selectedLeft.getURI() + " and " + selectedRight.getURI() + "?");
if (userChoice == JOptionPane.YES_OPTION){
final Project project = getProject();
// TipMapping theMapping = project.getTipMapping();
// theMapping.addPair(selectedTaxon, project.showOntology(selectedOntology));
// mapPane.refreshPairs();
// finally select both selections (we should grey them out at some point...
termsPane1.clearSelected();
termsPane2.clearSelected();
selectedLeft = null;
selectedRight = null;
}
else { // assume last selection was mistaken, clear only it
if (arg.equals(selectedLeft)) { //last selection from the left panel (ontology term)
termsPane1.clearSelected();
selectedLeft = null;
}
else if (arg.equals(selectedRight)){ //last selection was from the right panel (ontology term)
termsPane2.clearSelected();
selectedRight = null;
}
}
break;
}
case SETONTOLOGY:{
break;
}
case TWOSET:{
break;
}
case UNDEFINED:
default:{
}
}
}
}
//Menu handlers
//saveProjectItem = addMenuItem(fileMenu,"SaveProject", new saveProjectListener());
private JMenuItem makeSaveProjectAsItem(){
final JMenuItem item = new JMenuItem("Save Project As...");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
final Project project = theApp.getProject();
final JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(project.projectExtensions());
final int returnVal = chooser.showSaveDialog(theApp.getMainFrame());
if(returnVal == JFileChooser.APPROVE_OPTION) {
project.saveProjectAs(chooser.getSelectedFile());
}
}
catch(Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(theApp.getMainFrame(),"Error opening file for output: " + ex.toString(),"",JOptionPane.ERROR_MESSAGE);
}
}
});
return item;
}
private JMenuItem makeSaveAlignmentAsTuplesItem(){
final JMenuItem item = new JMenuItem("Tuples...");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
return item;
}
private JMenuItem makeSaveAlignmentAsOntologyItem(){
final JMenuItem item = new JMenuItem("Ontology...");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
return item;
}
private JMenuItem makeUnGuidedMatchItem(){
final JMenuItem item = new JMenuItem("Run UnGuided Match");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
final Project project = getProject();
final DataFactory factory = project.getDataFactory();
List <URI> onts = project.listOntologies(); //need to get this pair from somewhere
if (onts.size()>1){
JOptionPane.showMessageDialog(theApp.getMainFrame(), "About to start unguided match");
Alignment newAlignment = factory.getAlignment();
ExtendableStringMetric m = factory.getExtendableStringMetric(ExtendableStringMetric.Metric.MongeElkan);
OntologyWrapper w1 = project.showOntology(onts.get(0));
OntologyWrapper w2 = project.showOntology(onts.get(1));
List <OntTerm> names1 = w1.getPreOrderedTermList(new HashSet<OntTerm>());
List <OntTerm> names2 = w2.getPreOrderedTermList(new HashSet<OntTerm>());
project.unguidedMatch(newAlignment, w1, names1, w2, names2,m);
JOptionPane.showMessageDialog(theApp.getMainFrame(), "Unguided match completed - top 30 pairs on console");
}
else {
JOptionPane.showMessageDialog(theApp.getMainFrame(), "Ontologies haven't been loaded yet", "No Ontologies", JOptionPane.ERROR_MESSAGE);
}
}
});
return item;
}
private JMenuItem makeSuggestMatchItem(){
final JMenuItem item = new JMenuItem("Suggest Match");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO stub
}
});
return item;
}
private JMenuItem makeSuggestMatchFromNieceItem(){
final JMenuItem item = new JMenuItem("Suggest Match from daughter of other set");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO stub
}
});
return item;
}
}
| NESCent/Phylontal | src/fesource/org/ethontos/phylontal/fe/view/MatcherTab.java | 4,247 | //Help Menu Items | line_comment | nl | /*
* Phylontal FrontEnd - a GUI frontend for Phylontal
* Copyright 2009-2011 Peter E. Midford
* This file is part of Phylontal Frontend
*
* Phylontal Frontend 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.
*
* Phylontal Frontend 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 Phylontal Frontend. If not, see <http://www.gnu.org/licenses/>.
*
* Created on Oct 8, 2009
* Last updated on April 27, 2011
*
*/
package org.ethontos.phylontal.fe.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Observable;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
import org.ethontos.phylontal.project.Alignment;
import org.ethontos.phylontal.project.OntTerm;
import org.ethontos.phylontal.project.OntologyWrapper;
import org.ethontos.phylontal.project.Project;
import org.ethontos.phylontal.project.impl.DataFactory;
import org.ethontos.phylontal.project.impl.ExtendableStringMetric;
import org.ethontos.phylontal.project.phylo.GraphTree;
import org.ethontos.phylontal.fe.UserFrontEnd;
public class MatcherTab extends TabView {
private final String SAVEOPENERROR = "Error opening file for output: ";
public enum Config {SETONTOLOGY, TWOONTOLOGY, TWOSET, UNDEFINED};
OntTerm selectedLeft = null;
OntTerm selectedRight = null;
//Menus
final private JMenuBar tabMenus = new JMenuBar();
// Match Menu Items
private JMenuItem suggestMatchItem;
private JMenuItem suggestMatchFromNiece;
//Help Menu<SUF>
private JMenuItem showLicenseItem;
private JMenuItem matchHelpItem;
private SetListPane resultsPane;
private SetListPane setsPane1;
private SetListPane setsPane2;
private TermListPane termsPane1;
private TermListPane termsPane2;
private SimpleTreePane treePane;
private JPanel resultNamesPanel = new JPanel(); // should always be a setsPane
private JPanel leftNamesPanel = new JPanel();
private JPanel rightNamesPanel = new JPanel();
private JPanel treePanel = new JPanel();
private JLabel resultTitle = new JLabel();
private JLabel leftTitle = new JLabel();
private JLabel rightTitle = new JLabel();
private JLabel treeTitle = new JLabel();
private Config paneConfig = Config.UNDEFINED; //default for new projects
static Logger logger = Logger.getLogger(MatcherTab.class.getName());
public MatcherTab(UserFrontEnd app) {
super(app);
initializeAreas();
setConfiguration(Config.TWOONTOLOGY);
this.setVisible(true);
}
@Override
public boolean useable() {
Project p = theApp.getProject();
if (p == null)
return false;
GraphTree t = p.showTree();
if (t == null)
return false;
if (p.listOntologies().size()<2){
logger.debug("Ontologies count is " + p.listOntologies().size());
return false;
}
return true;
}
@Override
protected void showHelp() {
// TODO Auto-generated method stub
}
@Override
protected void showPreferences() {
// TODO Auto-generated method stub
}
@Override
public JMenuBar initializeMenus() {
if (tabMenus.getComponentCount() == 0){
final JMenu fileMenu = new JMenu("File");
final JMenu editMenu = new JMenu("Edit");
final JMenu matchMenu = new JMenu("Match");
final JMenu helpMenu = new JMenu("Help");
//submenus
final JMenu saveAlignmentAsMenu = new JMenu("Save Alignment As...");
tabMenus.add(fileMenu);
tabMenus.add(editMenu);
tabMenus.add(matchMenu);
if (theApp.runningOSX()){
JMenu windowMenu = new JMenu("Window");
tabMenus.add(windowMenu);
}
tabMenus.add(helpMenu);
fileMenu.add(makeSaveProjectAsItem());
fileMenu.add(saveAlignmentAsMenu);
saveAlignmentAsMenu.add(makeSaveAlignmentAsTuplesItem());
saveAlignmentAsMenu.add(makeSaveAlignmentAsOntologyItem());
matchMenu.add(makeUnGuidedMatchItem());
matchMenu.add(makeSuggestMatchItem());
matchMenu.add(makeSuggestMatchFromNieceItem());
helpMenu.add(makeShowLicenseItem(theApp));
}
return tabMenus;
}
private void initializeAreas(){
resultsPane = new SetListPane();
resultsPane.setBorder(BorderFactory.createLineBorder(Color.RED));
resultsPane.setMinimumSize(new Dimension(200,200));
resultNamesPanel.add(resultTitle);
resultNamesPanel.add(resultsPane);
termsPane1 = new TermListPane();
termsPane1.setBorder(BorderFactory.createLineBorder(Color.YELLOW));
termsPane2 = new TermListPane();
termsPane2.setBorder(BorderFactory.createLineBorder(Color.GREEN));
treePane = new SimpleTreePane();
treePane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
treeTitle.setText("Current Tree");
treePanel.setMinimumSize(new Dimension(200,200));
treePanel.add(treeTitle);
treePanel.add(treePane);
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
resultNamesPanel.setMinimumSize(new Dimension(200,200));
resultNamesPanel.setLayout(new BoxLayout(resultNamesPanel,BoxLayout.Y_AXIS));
leftNamesPanel.setLayout(new BoxLayout(leftNamesPanel,BoxLayout.Y_AXIS));
rightNamesPanel.setLayout(new BoxLayout(rightNamesPanel,BoxLayout.Y_AXIS));
treePanel.setLayout(new BoxLayout(treePanel,BoxLayout.Y_AXIS));
this.add(resultNamesPanel);
leftNamesPanel.setMinimumSize(new Dimension(200,200));
this.add(leftNamesPanel);
rightNamesPanel.setMinimumSize(new Dimension(200,200));
this.add(rightNamesPanel);
treePanel.setMinimumSize(new Dimension(200,200));
this.add(treePanel);
}
public void setConfiguration(MatcherTab.Config c){
switch (c){
case SETONTOLOGY:
configureSetOntology();
break;
case TWOSET:
configureTwoSet();
break;
case TWOONTOLOGY:
default:
configureTwoOntology();
}
}
private void configureTwoSet(){
if (!paneConfig.equals(Config.TWOSET)){
leftNamesPanel.removeAll();
leftNamesPanel.add(leftTitle);
leftNamesPanel.add(setsPane1);
rightNamesPanel.removeAll();
rightNamesPanel.add(rightTitle);
rightNamesPanel.add(setsPane2);
paneConfig = Config.TWOSET;
}
}
private void configureSetOntology(){
if (!paneConfig.equals(Config.SETONTOLOGY)){
leftNamesPanel.removeAll();
leftNamesPanel.add(leftTitle);
leftNamesPanel.add(setsPane1);
rightNamesPanel.removeAll();
rightNamesPanel.add(rightTitle);
rightNamesPanel.add(setsPane1);
paneConfig = Config.SETONTOLOGY;
}
}
private void configureTwoOntology(){
if (!paneConfig.equals(Config.TWOONTOLOGY)){
leftNamesPanel.removeAll();
leftNamesPanel.add(leftTitle);
leftNamesPanel.add(termsPane1);
rightNamesPanel.removeAll();
rightNamesPanel.add(rightTitle);
rightNamesPanel.add(termsPane2);
paneConfig = Config.TWOONTOLOGY;
}
}
private void updatePanels(){
GraphTree selectedTree = theApp.getProject().selectTree(0);
treePane.setTree(selectedTree);
// cheating here
List <URI> onts = getProject().listOntologies();
if (onts.size()>1){
OntologyWrapper w1 = getProject().showOntology(onts.get(0));
OntologyWrapper w2 = getProject().showOntology(onts.get(1));
termsPane1.setTerms(w1);
termsPane2.setTerms(w2);
}
else {
JOptionPane.showMessageDialog(this, "Ontologies haven't been loaded yet", "No Ontologies", JOptionPane.ERROR_MESSAGE);
}
treePane.setVisible(true);
}
public void update(Observable o, Object arg){
// super.update(o,arg); //tabview is currently abstract, so nothing to do here
if (o.equals(getProject())){
if (useable()){
theApp.getMainFrame().enableTab(this, "Construct alignment");
updatePanels();
}
}
if (arg != null && arg instanceof GraphTree){
// if another tree is selected, something should happen in the tree pane
}
if (selectedLeft != null && selectedRight != null){
switch(paneConfig){
case TWOONTOLOGY:{
logger.debug("Ready to match terms from right and left");
int userChoice = JOptionPane.showConfirmDialog(this,"Join "+ selectedLeft.getURI() + " and " + selectedRight.getURI() + "?");
if (userChoice == JOptionPane.YES_OPTION){
final Project project = getProject();
// TipMapping theMapping = project.getTipMapping();
// theMapping.addPair(selectedTaxon, project.showOntology(selectedOntology));
// mapPane.refreshPairs();
// finally select both selections (we should grey them out at some point...
termsPane1.clearSelected();
termsPane2.clearSelected();
selectedLeft = null;
selectedRight = null;
}
else { // assume last selection was mistaken, clear only it
if (arg.equals(selectedLeft)) { //last selection from the left panel (ontology term)
termsPane1.clearSelected();
selectedLeft = null;
}
else if (arg.equals(selectedRight)){ //last selection was from the right panel (ontology term)
termsPane2.clearSelected();
selectedRight = null;
}
}
break;
}
case SETONTOLOGY:{
break;
}
case TWOSET:{
break;
}
case UNDEFINED:
default:{
}
}
}
}
//Menu handlers
//saveProjectItem = addMenuItem(fileMenu,"SaveProject", new saveProjectListener());
private JMenuItem makeSaveProjectAsItem(){
final JMenuItem item = new JMenuItem("Save Project As...");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
final Project project = theApp.getProject();
final JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(project.projectExtensions());
final int returnVal = chooser.showSaveDialog(theApp.getMainFrame());
if(returnVal == JFileChooser.APPROVE_OPTION) {
project.saveProjectAs(chooser.getSelectedFile());
}
}
catch(Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(theApp.getMainFrame(),"Error opening file for output: " + ex.toString(),"",JOptionPane.ERROR_MESSAGE);
}
}
});
return item;
}
private JMenuItem makeSaveAlignmentAsTuplesItem(){
final JMenuItem item = new JMenuItem("Tuples...");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
return item;
}
private JMenuItem makeSaveAlignmentAsOntologyItem(){
final JMenuItem item = new JMenuItem("Ontology...");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
return item;
}
private JMenuItem makeUnGuidedMatchItem(){
final JMenuItem item = new JMenuItem("Run UnGuided Match");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
final Project project = getProject();
final DataFactory factory = project.getDataFactory();
List <URI> onts = project.listOntologies(); //need to get this pair from somewhere
if (onts.size()>1){
JOptionPane.showMessageDialog(theApp.getMainFrame(), "About to start unguided match");
Alignment newAlignment = factory.getAlignment();
ExtendableStringMetric m = factory.getExtendableStringMetric(ExtendableStringMetric.Metric.MongeElkan);
OntologyWrapper w1 = project.showOntology(onts.get(0));
OntologyWrapper w2 = project.showOntology(onts.get(1));
List <OntTerm> names1 = w1.getPreOrderedTermList(new HashSet<OntTerm>());
List <OntTerm> names2 = w2.getPreOrderedTermList(new HashSet<OntTerm>());
project.unguidedMatch(newAlignment, w1, names1, w2, names2,m);
JOptionPane.showMessageDialog(theApp.getMainFrame(), "Unguided match completed - top 30 pairs on console");
}
else {
JOptionPane.showMessageDialog(theApp.getMainFrame(), "Ontologies haven't been loaded yet", "No Ontologies", JOptionPane.ERROR_MESSAGE);
}
}
});
return item;
}
private JMenuItem makeSuggestMatchItem(){
final JMenuItem item = new JMenuItem("Suggest Match");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO stub
}
});
return item;
}
private JMenuItem makeSuggestMatchFromNieceItem(){
final JMenuItem item = new JMenuItem("Suggest Match from daughter of other set");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO stub
}
});
return item;
}
}
|
82002_14 | package javax.rtcbench;
import javax.rtc.RTC;
import javax.rtc.Lightweight;
/*
Author : Shay Gal-On, EEMBC
This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009
All rights reserved.
EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the
CoreMark License that is distributed with the official EEMBC COREMARK Software release.
If you received this EEMBC CoreMark Software without the accompanying CoreMark License,
you must discontinue use and download the official release from www.coremark.org.
Also, if you are publicly displaying scores generated from the EEMBC CoreMark software,
make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file.
EEMBC
4354 Town Center Blvd. Suite 114-200
El Dorado Hills, CA, 95762
*/
/*
Topic: Description
Simple state machines like this one are used in many embedded products.
For more complex state machines, sometimes a state transition table implementation is used instead,
trading speed of direct coding for ease of maintenance.
Since the main goal of using a state machine in CoreMark is to excercise the switch/if behaviour,
we are using a small moore machine.
In particular, this machine tests type of string input,
trying to determine whether the input is a number or something else.
(see core_state.png).
*/
public class CoreState {
public static final byte CORE_STATE_START = 0;
public static final byte CORE_STATE_INVALID = 1;
public static final byte CORE_STATE_S1 = 2;
public static final byte CORE_STATE_S2 = 3;
public static final byte CORE_STATE_INT = 4;
public static final byte CORE_STATE_FLOAT = 5;
public static final byte CORE_STATE_EXPONENT = 6;
public static final byte CORE_STATE_SCIENTIFIC = 7;
public static final byte NUM_CORE_STATES = 8;
/* Function: core_bench_state
Benchmark function
Go over the input twice, once direct, and once after introducing some corruption.
*/
static short core_bench_state(int blksize, byte[] memblock,
short seed1, short seed2, short step, short crc, CoreMain.TmpData tmpData)
{
int[] final_counts = tmpData.final_counts;
int[] track_counts = tmpData.track_counts;
ShortWrapper p = tmpData.p;
short pValue; // Within this method we use this so the local variable can be pinned by markloop.
p.value=0; // We use this to pass to core_state_transition since it needs to be able to modify the index (it's a double pointer in C).
int i;
for (i=0; i<NUM_CORE_STATES; i++) {
final_counts[i]=track_counts[i]=0;
}
/* run the state machine over the input */
while (memblock[p.value]!=0) {
byte fstate=core_state_transition(p,memblock,track_counts);
final_counts[fstate]++;
}
// p=memblock;
pValue=0; // Stays within this method, so use pValue
while (pValue < blksize) { /* insert some corruption */
if (memblock[pValue]!=',')
memblock[pValue]^=(byte)seed1;
pValue+=step;
}
// p=memblock;
p.value=0;
/* run the state machine over the input again */
while (memblock[p.value]!=0) {
byte fstate=core_state_transition(p,memblock,track_counts);
final_counts[fstate]++;
}
// p=memblock;
pValue=0; // Stays within this method, so use pValue
while (pValue < blksize) { /* undo corruption if seed1 and seed2 are equal */
if (memblock[pValue]!=',')
memblock[pValue]^=(byte)seed2;
pValue+=step;
}
/* end timing */
for (i=0; i<NUM_CORE_STATES; i++) {
crc=CoreUtil.crcu32(final_counts[i],crc);
crc=CoreUtil.crcu32(track_counts[i],crc);
}
return crc;
}
// NOT STANDARD COREMARK CODE: make this into functions to prevent them taking up memory at runtime.
// not used during the benchmark so this won't influence the results.
/* Default initialization patterns */
// private static Object[] intpat ={ "5012".getBytes(), "1234".getBytes(), "-874".getBytes(), "+122".getBytes()};
// private static Object[] floatpat={"35.54400".getBytes(),".1234500".getBytes(),"-110.700".getBytes(),"+0.64400".getBytes()};
// private static Object[] scipat ={"5.500e+3".getBytes(),"-.123e-2".getBytes(),"-87e+832".getBytes(),"+0.6e-12".getBytes()};
// private static Object[] errpat ={"T0.3e-1F".getBytes(),"-T.T++Tq".getBytes(),"1T3.4e4z".getBytes(),"34.0e-T^".getBytes()};
private static byte[] intpat(int i) {
if (i==0) return "5012".getBytes();
else if (i==1) return "1234".getBytes();
else if (i==2) return "-874".getBytes();
else return "+122".getBytes();
}
private static byte[] floatpat(int i) {
if (i==0) return "35.54400".getBytes();
else if (i==1) return ".1234500".getBytes();
else if (i==2) return "-110.700".getBytes();
else return "+0.64400".getBytes();
}
private static byte[] scipat(int i) {
if (i==0) return "5.500e+3".getBytes();
else if (i==1) return "-.123e-2".getBytes();
else if (i==2) return "-87e+832".getBytes();
else return "+0.6e-12".getBytes();
}
private static byte[] errpat(int i) {
if (i==0) return "T0.3e-1F".getBytes();
else if (i==1) return "-T.T++Tq".getBytes();
else if (i==2) return "1T3.4e4z".getBytes();
else return "34.0e-T^".getBytes();
}
// TODO: This is a very ugly hack to prevent ProGuard from inlining core_bench_state, which causes other problems when it happens.
// It would be nice to have more direct control over what gets inlined or not.
private static byte vliegtuig = 1;
/* Function: core_init_state
Initialize the input data for the state machine.
Populate the input with several predetermined strings, interspersed.
Actual patterns chosen depend on the seed parameter.
Note:
The seed parameter MUST be supplied from a source that cannot be determined at compile time
*/
static byte[] core_init_state(int size, short seed) {
byte[] p=new byte[size];
int total=0,next=0,i;
byte[] buf=null;
size--;
next=0;
while ((total+next+1)<size) {
if (next>0) {
for(i=0;i<next;i++)
p[total+i]=buf[i];
p[total+i]=',';
total+=next+1;
}
seed++;
switch (seed & 0x7) {
case 0: /* int */
case 1: /* int */
case 2: /* int */
buf=intpat((seed>>3) & 0x3);
next=4;
break;
case 3: /* float */
case 4: /* float */
buf=floatpat((seed>>3) & 0x3);
next=8;
break;
case 5: /* scientific */
case 6: /* scientific */
buf=scipat((seed>>3) & 0x3);
next=8;
break;
case 7: /* invalid */
buf=errpat((seed>>3) & 0x3);
next=8;
break;
default: /* Never happen, just to make some compilers happy */
break;
}
}
size++;
while (total<size) { /* fill the rest with 0 */
p[total]=0;
total++;
}
return p;
}
// Shouldn't use the manually written version here because we're evaluating the effect of optimising Java compilers,
// and the advantage of manually writing the bytecode is exactly what's missing without an optimising compiler.
@Lightweight
static boolean ee_isdigit(byte c) {
boolean retval;
retval = ((c>='0') & (c<='9')) ? true : false;
return retval;
}
/* Function: core_state_transition
Actual state machine.
The state machine will continue scanning until either:
1 - an invalid input is detected.
2 - a valid number has been detected.
The input pointer is updated to point to the end of the token, and the end state is returned (either specific format determined or invalid).
*/
private static class CoreStateTransitionParam {
public byte[] instr;
public short index;
}
// State core_state_transition( ee_u8 **instr , int[] transition_count) {
@Lightweight
static byte core_state_transition(ShortWrapper indexWrapper, byte[] str, int[] transition_count) {
short index = indexWrapper.value;
byte NEXT_SYMBOL;
byte state=CORE_STATE_START;
// for( ; *str && state != CORE_INVALID; str++ ) {
for( ; (NEXT_SYMBOL = str[index])!=0 && state != CORE_STATE_INVALID; index++ ) {
if (NEXT_SYMBOL==',') /* end of this input */ {
index++;
break;
}
switch(state) {
case CORE_STATE_START:
if(ee_isdigit(NEXT_SYMBOL)) {
state = CORE_STATE_INT;
}
else if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) {
state = CORE_STATE_S1;
}
else if( NEXT_SYMBOL == '.' ) {
state = CORE_STATE_FLOAT;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_INVALID]++;
}
transition_count[CORE_STATE_START]++;
break;
case CORE_STATE_S1:
if(ee_isdigit(NEXT_SYMBOL)) {
state = CORE_STATE_INT;
transition_count[CORE_STATE_S1]++;
}
else if( NEXT_SYMBOL == '.' ) {
state = CORE_STATE_FLOAT;
transition_count[CORE_STATE_S1]++;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_S1]++;
}
break;
case CORE_STATE_INT:
if( NEXT_SYMBOL == '.' ) {
state = CORE_STATE_FLOAT;
transition_count[CORE_STATE_INT]++;
}
else if(!(ee_isdigit(NEXT_SYMBOL))) {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_INT]++;
}
break;
case CORE_STATE_FLOAT:
if( NEXT_SYMBOL == 'E' || NEXT_SYMBOL == 'e' ) {
state = CORE_STATE_S2;
transition_count[CORE_STATE_FLOAT]++;
}
else if(!(ee_isdigit(NEXT_SYMBOL))) {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_FLOAT]++;
}
break;
case CORE_STATE_S2:
if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) {
state = CORE_STATE_EXPONENT;
transition_count[CORE_STATE_S2]++;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_S2]++;
}
break;
case CORE_STATE_EXPONENT:
if(ee_isdigit(NEXT_SYMBOL)) {
state = CORE_STATE_SCIENTIFIC;
transition_count[CORE_STATE_EXPONENT]++;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_EXPONENT]++;
}
break;
case CORE_STATE_SCIENTIFIC:
if(!(ee_isdigit(NEXT_SYMBOL))) {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_INVALID]++;
}
break;
default:
break;
}
}
// *instr=str;
indexWrapper.value = index;
return state;
}
}
| NEWSLabNTU/capevm | src/lib/bm_coremk_noinl/java/javax/rtcbench/CoreState.java | 3,723 | // private static Object[] intpat ={ "5012".getBytes(), "1234".getBytes(), "-874".getBytes(), "+122".getBytes()}; | line_comment | nl | package javax.rtcbench;
import javax.rtc.RTC;
import javax.rtc.Lightweight;
/*
Author : Shay Gal-On, EEMBC
This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009
All rights reserved.
EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the
CoreMark License that is distributed with the official EEMBC COREMARK Software release.
If you received this EEMBC CoreMark Software without the accompanying CoreMark License,
you must discontinue use and download the official release from www.coremark.org.
Also, if you are publicly displaying scores generated from the EEMBC CoreMark software,
make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file.
EEMBC
4354 Town Center Blvd. Suite 114-200
El Dorado Hills, CA, 95762
*/
/*
Topic: Description
Simple state machines like this one are used in many embedded products.
For more complex state machines, sometimes a state transition table implementation is used instead,
trading speed of direct coding for ease of maintenance.
Since the main goal of using a state machine in CoreMark is to excercise the switch/if behaviour,
we are using a small moore machine.
In particular, this machine tests type of string input,
trying to determine whether the input is a number or something else.
(see core_state.png).
*/
public class CoreState {
public static final byte CORE_STATE_START = 0;
public static final byte CORE_STATE_INVALID = 1;
public static final byte CORE_STATE_S1 = 2;
public static final byte CORE_STATE_S2 = 3;
public static final byte CORE_STATE_INT = 4;
public static final byte CORE_STATE_FLOAT = 5;
public static final byte CORE_STATE_EXPONENT = 6;
public static final byte CORE_STATE_SCIENTIFIC = 7;
public static final byte NUM_CORE_STATES = 8;
/* Function: core_bench_state
Benchmark function
Go over the input twice, once direct, and once after introducing some corruption.
*/
static short core_bench_state(int blksize, byte[] memblock,
short seed1, short seed2, short step, short crc, CoreMain.TmpData tmpData)
{
int[] final_counts = tmpData.final_counts;
int[] track_counts = tmpData.track_counts;
ShortWrapper p = tmpData.p;
short pValue; // Within this method we use this so the local variable can be pinned by markloop.
p.value=0; // We use this to pass to core_state_transition since it needs to be able to modify the index (it's a double pointer in C).
int i;
for (i=0; i<NUM_CORE_STATES; i++) {
final_counts[i]=track_counts[i]=0;
}
/* run the state machine over the input */
while (memblock[p.value]!=0) {
byte fstate=core_state_transition(p,memblock,track_counts);
final_counts[fstate]++;
}
// p=memblock;
pValue=0; // Stays within this method, so use pValue
while (pValue < blksize) { /* insert some corruption */
if (memblock[pValue]!=',')
memblock[pValue]^=(byte)seed1;
pValue+=step;
}
// p=memblock;
p.value=0;
/* run the state machine over the input again */
while (memblock[p.value]!=0) {
byte fstate=core_state_transition(p,memblock,track_counts);
final_counts[fstate]++;
}
// p=memblock;
pValue=0; // Stays within this method, so use pValue
while (pValue < blksize) { /* undo corruption if seed1 and seed2 are equal */
if (memblock[pValue]!=',')
memblock[pValue]^=(byte)seed2;
pValue+=step;
}
/* end timing */
for (i=0; i<NUM_CORE_STATES; i++) {
crc=CoreUtil.crcu32(final_counts[i],crc);
crc=CoreUtil.crcu32(track_counts[i],crc);
}
return crc;
}
// NOT STANDARD COREMARK CODE: make this into functions to prevent them taking up memory at runtime.
// not used during the benchmark so this won't influence the results.
/* Default initialization patterns */
// private static<SUF>
// private static Object[] floatpat={"35.54400".getBytes(),".1234500".getBytes(),"-110.700".getBytes(),"+0.64400".getBytes()};
// private static Object[] scipat ={"5.500e+3".getBytes(),"-.123e-2".getBytes(),"-87e+832".getBytes(),"+0.6e-12".getBytes()};
// private static Object[] errpat ={"T0.3e-1F".getBytes(),"-T.T++Tq".getBytes(),"1T3.4e4z".getBytes(),"34.0e-T^".getBytes()};
private static byte[] intpat(int i) {
if (i==0) return "5012".getBytes();
else if (i==1) return "1234".getBytes();
else if (i==2) return "-874".getBytes();
else return "+122".getBytes();
}
private static byte[] floatpat(int i) {
if (i==0) return "35.54400".getBytes();
else if (i==1) return ".1234500".getBytes();
else if (i==2) return "-110.700".getBytes();
else return "+0.64400".getBytes();
}
private static byte[] scipat(int i) {
if (i==0) return "5.500e+3".getBytes();
else if (i==1) return "-.123e-2".getBytes();
else if (i==2) return "-87e+832".getBytes();
else return "+0.6e-12".getBytes();
}
private static byte[] errpat(int i) {
if (i==0) return "T0.3e-1F".getBytes();
else if (i==1) return "-T.T++Tq".getBytes();
else if (i==2) return "1T3.4e4z".getBytes();
else return "34.0e-T^".getBytes();
}
// TODO: This is a very ugly hack to prevent ProGuard from inlining core_bench_state, which causes other problems when it happens.
// It would be nice to have more direct control over what gets inlined or not.
private static byte vliegtuig = 1;
/* Function: core_init_state
Initialize the input data for the state machine.
Populate the input with several predetermined strings, interspersed.
Actual patterns chosen depend on the seed parameter.
Note:
The seed parameter MUST be supplied from a source that cannot be determined at compile time
*/
static byte[] core_init_state(int size, short seed) {
byte[] p=new byte[size];
int total=0,next=0,i;
byte[] buf=null;
size--;
next=0;
while ((total+next+1)<size) {
if (next>0) {
for(i=0;i<next;i++)
p[total+i]=buf[i];
p[total+i]=',';
total+=next+1;
}
seed++;
switch (seed & 0x7) {
case 0: /* int */
case 1: /* int */
case 2: /* int */
buf=intpat((seed>>3) & 0x3);
next=4;
break;
case 3: /* float */
case 4: /* float */
buf=floatpat((seed>>3) & 0x3);
next=8;
break;
case 5: /* scientific */
case 6: /* scientific */
buf=scipat((seed>>3) & 0x3);
next=8;
break;
case 7: /* invalid */
buf=errpat((seed>>3) & 0x3);
next=8;
break;
default: /* Never happen, just to make some compilers happy */
break;
}
}
size++;
while (total<size) { /* fill the rest with 0 */
p[total]=0;
total++;
}
return p;
}
// Shouldn't use the manually written version here because we're evaluating the effect of optimising Java compilers,
// and the advantage of manually writing the bytecode is exactly what's missing without an optimising compiler.
@Lightweight
static boolean ee_isdigit(byte c) {
boolean retval;
retval = ((c>='0') & (c<='9')) ? true : false;
return retval;
}
/* Function: core_state_transition
Actual state machine.
The state machine will continue scanning until either:
1 - an invalid input is detected.
2 - a valid number has been detected.
The input pointer is updated to point to the end of the token, and the end state is returned (either specific format determined or invalid).
*/
private static class CoreStateTransitionParam {
public byte[] instr;
public short index;
}
// State core_state_transition( ee_u8 **instr , int[] transition_count) {
@Lightweight
static byte core_state_transition(ShortWrapper indexWrapper, byte[] str, int[] transition_count) {
short index = indexWrapper.value;
byte NEXT_SYMBOL;
byte state=CORE_STATE_START;
// for( ; *str && state != CORE_INVALID; str++ ) {
for( ; (NEXT_SYMBOL = str[index])!=0 && state != CORE_STATE_INVALID; index++ ) {
if (NEXT_SYMBOL==',') /* end of this input */ {
index++;
break;
}
switch(state) {
case CORE_STATE_START:
if(ee_isdigit(NEXT_SYMBOL)) {
state = CORE_STATE_INT;
}
else if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) {
state = CORE_STATE_S1;
}
else if( NEXT_SYMBOL == '.' ) {
state = CORE_STATE_FLOAT;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_INVALID]++;
}
transition_count[CORE_STATE_START]++;
break;
case CORE_STATE_S1:
if(ee_isdigit(NEXT_SYMBOL)) {
state = CORE_STATE_INT;
transition_count[CORE_STATE_S1]++;
}
else if( NEXT_SYMBOL == '.' ) {
state = CORE_STATE_FLOAT;
transition_count[CORE_STATE_S1]++;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_S1]++;
}
break;
case CORE_STATE_INT:
if( NEXT_SYMBOL == '.' ) {
state = CORE_STATE_FLOAT;
transition_count[CORE_STATE_INT]++;
}
else if(!(ee_isdigit(NEXT_SYMBOL))) {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_INT]++;
}
break;
case CORE_STATE_FLOAT:
if( NEXT_SYMBOL == 'E' || NEXT_SYMBOL == 'e' ) {
state = CORE_STATE_S2;
transition_count[CORE_STATE_FLOAT]++;
}
else if(!(ee_isdigit(NEXT_SYMBOL))) {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_FLOAT]++;
}
break;
case CORE_STATE_S2:
if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) {
state = CORE_STATE_EXPONENT;
transition_count[CORE_STATE_S2]++;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_S2]++;
}
break;
case CORE_STATE_EXPONENT:
if(ee_isdigit(NEXT_SYMBOL)) {
state = CORE_STATE_SCIENTIFIC;
transition_count[CORE_STATE_EXPONENT]++;
}
else {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_EXPONENT]++;
}
break;
case CORE_STATE_SCIENTIFIC:
if(!(ee_isdigit(NEXT_SYMBOL))) {
state = CORE_STATE_INVALID;
transition_count[CORE_STATE_INVALID]++;
}
break;
default:
break;
}
}
// *instr=str;
indexWrapper.value = index;
return state;
}
}
|
180503_1 | package org.raytracer.classes.objects;
import org.raytracer.Main;
public class Color {
private float red = 1;
private float green = 1;
private float blue = 1;
/**
* Standard color is white
*/
public Color() {
setColor(Color.White);
}
/**
* @param red number between 0 and 1
* @param green number between 0 and 1
* @param blue number between 0 and 1
*/
public Color(float red, float green, float blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public float getRed() {
return red;
}
public float getBlue() {
return blue;
}
public float getGreen() {
return green;
}
public void setColor(float red, float green, float blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public void setColor(Color color) {
this.red = color.red;
this.green = color.green;
this.blue = color.blue;
}
/**
* Gets rgb values and converts it to a hex number
*
* @return hex code
*/
public int getRGB() {
int redPart = (int) (red * 255);
int greenPart = (int) (green * 255);
int bluePart = (int) (blue * 255);
// Shift bits to right place
//redPart = (redPart << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
//greenPart = (greenPart << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
//bluePart = bluePart & 0x000000FF; //Mask out anything not blue.
//return 0xFF000000 | redPart | greenPart | bluePart; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
int rgb = redPart;
rgb = (rgb << 8) + greenPart;
rgb = (rgb << 8) + bluePart;
return rgb;
}
public int getRGBBitshifted(){
int redPart = (int) (red * 255);
int greenPart = (int) (green * 255);
int bluePart = (int) (blue * 255);
// Shift bits to right place
redPart = (redPart << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
greenPart = (greenPart << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
bluePart = bluePart & 0x000000FF; //Mask out anything not blue.
return 0xFF000000 | redPart | greenPart | bluePart; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}
public void nerfColor() {
/*
red = Math.max(0, Math.min(1, red));
blue = Math.max(0, Math.min(1, blue));
green = Math.max(0, Math.min(1, green));
*/
if (red > 1)
red = 1;
if (blue > 1)
blue = 1;
if (green > 1)
green = 1;
if (red < 0)
red = 0;
if (blue < 0)
blue = 0;
if (green < 0)
green = 0;
}
public static Color fromInt(int argb) {
int b = (argb) & 0xFF;
int g = (argb >> 8) & 0xFF;
int r = (argb >> 16) & 0xFF;
return new Color(r / 255F, g / 255F, b / 255F);
}
public java.awt.Color toAWTColor() {
return new java.awt.Color(red, green, blue);
}
public static final Color White = new Color(1f, 1f, 1f);
public static final Color Black = new Color(0, 0, 0);
public static final Color Blue = new Color(0, 0, 1f);
//public static final Color
public Color multiply(float value) {
return new Color(this.red * value, this.green * value, this.blue * value);
}
/**
* Berekenen lichtintensiteit
*/
// calculate the reflection
//reflectie = kleurlicht * kleurobject
public Color lightReflection(Color lightColor, float lightDistance) {
lightColor.lightIntensityColorOverDistance(lightDistance);
float red = this.red * lightColor.getRed();
float blue = this.blue * lightColor.getBlue();
float green = this.green * lightColor.getGreen();
return new Color(red, green, blue);
}
/**
* Berekenen lichtintensiteit
*/
public Color lightIntensityColorOverDistance(float objectDistance) {
double distance = Math.pow(objectDistance, 2);
double lightIntensity = 1 / distance;
float red = this.red * (float) lightIntensity;
float green = this.green * (float) lightIntensity;
float blue = this.blue * (float) lightIntensity;
return new Color(red, green, blue);
}
}
| NHLStenden-HBO-ICT/Raytracer-groep_14 | Raytracer-groep_14/src/main/java/org/raytracer/classes/objects/Color.java | 1,497 | /**
* @param red number between 0 and 1
* @param green number between 0 and 1
* @param blue number between 0 and 1
*/ | block_comment | nl | package org.raytracer.classes.objects;
import org.raytracer.Main;
public class Color {
private float red = 1;
private float green = 1;
private float blue = 1;
/**
* Standard color is white
*/
public Color() {
setColor(Color.White);
}
/**
* @param red <SUF>*/
public Color(float red, float green, float blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public float getRed() {
return red;
}
public float getBlue() {
return blue;
}
public float getGreen() {
return green;
}
public void setColor(float red, float green, float blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public void setColor(Color color) {
this.red = color.red;
this.green = color.green;
this.blue = color.blue;
}
/**
* Gets rgb values and converts it to a hex number
*
* @return hex code
*/
public int getRGB() {
int redPart = (int) (red * 255);
int greenPart = (int) (green * 255);
int bluePart = (int) (blue * 255);
// Shift bits to right place
//redPart = (redPart << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
//greenPart = (greenPart << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
//bluePart = bluePart & 0x000000FF; //Mask out anything not blue.
//return 0xFF000000 | redPart | greenPart | bluePart; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
int rgb = redPart;
rgb = (rgb << 8) + greenPart;
rgb = (rgb << 8) + bluePart;
return rgb;
}
public int getRGBBitshifted(){
int redPart = (int) (red * 255);
int greenPart = (int) (green * 255);
int bluePart = (int) (blue * 255);
// Shift bits to right place
redPart = (redPart << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
greenPart = (greenPart << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
bluePart = bluePart & 0x000000FF; //Mask out anything not blue.
return 0xFF000000 | redPart | greenPart | bluePart; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}
public void nerfColor() {
/*
red = Math.max(0, Math.min(1, red));
blue = Math.max(0, Math.min(1, blue));
green = Math.max(0, Math.min(1, green));
*/
if (red > 1)
red = 1;
if (blue > 1)
blue = 1;
if (green > 1)
green = 1;
if (red < 0)
red = 0;
if (blue < 0)
blue = 0;
if (green < 0)
green = 0;
}
public static Color fromInt(int argb) {
int b = (argb) & 0xFF;
int g = (argb >> 8) & 0xFF;
int r = (argb >> 16) & 0xFF;
return new Color(r / 255F, g / 255F, b / 255F);
}
public java.awt.Color toAWTColor() {
return new java.awt.Color(red, green, blue);
}
public static final Color White = new Color(1f, 1f, 1f);
public static final Color Black = new Color(0, 0, 0);
public static final Color Blue = new Color(0, 0, 1f);
//public static final Color
public Color multiply(float value) {
return new Color(this.red * value, this.green * value, this.blue * value);
}
/**
* Berekenen lichtintensiteit
*/
// calculate the reflection
//reflectie = kleurlicht * kleurobject
public Color lightReflection(Color lightColor, float lightDistance) {
lightColor.lightIntensityColorOverDistance(lightDistance);
float red = this.red * lightColor.getRed();
float blue = this.blue * lightColor.getBlue();
float green = this.green * lightColor.getGreen();
return new Color(red, green, blue);
}
/**
* Berekenen lichtintensiteit
*/
public Color lightIntensityColorOverDistance(float objectDistance) {
double distance = Math.pow(objectDistance, 2);
double lightIntensity = 1 / distance;
float red = this.red * (float) lightIntensity;
float green = this.green * (float) lightIntensity;
float blue = this.blue * (float) lightIntensity;
return new Color(red, green, blue);
}
}
|
61977_8 | package proeend.material;
import proeend.math.FastRandom;
import proeend.records.ScatterRecord;
import proeend.math.Ray;
import proeend.math.Vector;
import proeend.records.HitRecord;
/**
* Maakt een dielectric materiaal aan.
*/
public class Dielectric extends Material {
private final double refractionIndex; // Index of Refraction
private Vector color = new Vector(1,1,1);
/**
* Construeert een dielectric materiaal met de gegeven hoeveelheid lichtbreking
* @param indexOfRefraction De hoeveelheid lichtbreking.
*/
public Dielectric(double indexOfRefraction) {
refractionIndex = indexOfRefraction;
}
public Dielectric(double indexOfRefraction, Vector color) {
refractionIndex = indexOfRefraction;
this.color = color;
}
@Override
public boolean scatter(Ray rayIn, HitRecord rec, ScatterRecord scRecord) {
scRecord.attenuation = color;
scRecord.pdf = null;
scRecord.skipPDF = true;
double refractionRatio = rec.isFrontFace() ? (1.0 / refractionIndex) : refractionIndex;
Vector unitDirection = rayIn.getDirection().toUnitVector();
double cosTheta = Math.min(Vector.dot(unitDirection.invert(),rec.getNormal()),1.0);
double sinTheta = Math.sqrt(1.0-cosTheta*cosTheta);
boolean cannotRefract = refractionRatio * sinTheta > 1.0;
Vector direction;
if (cannotRefract || reflectance(cosTheta, refractionRatio) > FastRandom.random())
direction = Vector.reflect(unitDirection, rec.getNormal());
else
direction = refract(unitDirection,rec.normal,refractionRatio);
//Vector refracted = refract(unitDirection, rec.getNormal(), refractionRatio);
scRecord.skipRay.updateRay((rec.getP()), direction);
return true;
}
/**
* Reflecteert een vector.
* @param cos De cosinus.
* @param refInd De reflectance index.
* @return De gereflecteerde vector.
*/
private static double reflectance(double cos, double refInd) {
double r0 = (1-refInd) / (1+refInd);
r0 = r0*r0;
return r0 + (1-r0)* Math.pow((1-cos),5);
}
/**
* Bereken de gebroken lichtstraal (refractie) wanneer een straal invalt op een oppervlak.
* @param uv De richting van de invallende straal.
* @param normal De normaalvector van het oppervlak.
* @param etai_over_etat De verhouding van de brekingsindices.
* @return De richting van de gebroken lichtstraal.
*/
public Vector refract(Vector uv, Vector normal, double etai_over_etat) {
// Bereken de cosinus van de hoek tussen de invallende straal en de normaal.
double cos_theta = Math.min(- Vector.dot(uv, normal), 1.0);
// Bereken het loodrechte deel van de gebroken lichtstraal.
Vector r_out_perp = uv.add(normal.scale(cos_theta)).scale(etai_over_etat);
// Bereken het evenwijdige deel van de gebroken lichtstraal.
double discriminant = 1.0 - Vector.lengthSquared(r_out_perp);
if (discriminant > 0) {
Vector r_out_parallel = normal.scale(-Math.sqrt(discriminant));
// Voeg de loodrechte en evenwijdige delen samen om de gebroken lichtstraal te verkrijgen.
return r_out_perp.add(r_out_parallel);
} else {
// Als de discriminant negatief is, is er totale interne reflectie.
return new Vector(0, 0, 0); // Geen breking, de straal wordt volledig gereflecteerd.
}
}
}
| NHLStenden-HBO-ICT/graphics-2023-2024-groep-3-eend | project_eend/src/main/java/proeend/material/Dielectric.java | 1,083 | // Bereken het evenwijdige deel van de gebroken lichtstraal. | line_comment | nl | package proeend.material;
import proeend.math.FastRandom;
import proeend.records.ScatterRecord;
import proeend.math.Ray;
import proeend.math.Vector;
import proeend.records.HitRecord;
/**
* Maakt een dielectric materiaal aan.
*/
public class Dielectric extends Material {
private final double refractionIndex; // Index of Refraction
private Vector color = new Vector(1,1,1);
/**
* Construeert een dielectric materiaal met de gegeven hoeveelheid lichtbreking
* @param indexOfRefraction De hoeveelheid lichtbreking.
*/
public Dielectric(double indexOfRefraction) {
refractionIndex = indexOfRefraction;
}
public Dielectric(double indexOfRefraction, Vector color) {
refractionIndex = indexOfRefraction;
this.color = color;
}
@Override
public boolean scatter(Ray rayIn, HitRecord rec, ScatterRecord scRecord) {
scRecord.attenuation = color;
scRecord.pdf = null;
scRecord.skipPDF = true;
double refractionRatio = rec.isFrontFace() ? (1.0 / refractionIndex) : refractionIndex;
Vector unitDirection = rayIn.getDirection().toUnitVector();
double cosTheta = Math.min(Vector.dot(unitDirection.invert(),rec.getNormal()),1.0);
double sinTheta = Math.sqrt(1.0-cosTheta*cosTheta);
boolean cannotRefract = refractionRatio * sinTheta > 1.0;
Vector direction;
if (cannotRefract || reflectance(cosTheta, refractionRatio) > FastRandom.random())
direction = Vector.reflect(unitDirection, rec.getNormal());
else
direction = refract(unitDirection,rec.normal,refractionRatio);
//Vector refracted = refract(unitDirection, rec.getNormal(), refractionRatio);
scRecord.skipRay.updateRay((rec.getP()), direction);
return true;
}
/**
* Reflecteert een vector.
* @param cos De cosinus.
* @param refInd De reflectance index.
* @return De gereflecteerde vector.
*/
private static double reflectance(double cos, double refInd) {
double r0 = (1-refInd) / (1+refInd);
r0 = r0*r0;
return r0 + (1-r0)* Math.pow((1-cos),5);
}
/**
* Bereken de gebroken lichtstraal (refractie) wanneer een straal invalt op een oppervlak.
* @param uv De richting van de invallende straal.
* @param normal De normaalvector van het oppervlak.
* @param etai_over_etat De verhouding van de brekingsindices.
* @return De richting van de gebroken lichtstraal.
*/
public Vector refract(Vector uv, Vector normal, double etai_over_etat) {
// Bereken de cosinus van de hoek tussen de invallende straal en de normaal.
double cos_theta = Math.min(- Vector.dot(uv, normal), 1.0);
// Bereken het loodrechte deel van de gebroken lichtstraal.
Vector r_out_perp = uv.add(normal.scale(cos_theta)).scale(etai_over_etat);
// Bereken het<SUF>
double discriminant = 1.0 - Vector.lengthSquared(r_out_perp);
if (discriminant > 0) {
Vector r_out_parallel = normal.scale(-Math.sqrt(discriminant));
// Voeg de loodrechte en evenwijdige delen samen om de gebroken lichtstraal te verkrijgen.
return r_out_perp.add(r_out_parallel);
} else {
// Als de discriminant negatief is, is er totale interne reflectie.
return new Vector(0, 0, 0); // Geen breking, de straal wordt volledig gereflecteerd.
}
}
}
|
87833_5 | /*
* SPDX-FileCopyrightText: 2023 Atos
* SPDX-License-Identifier: EUPL-1.2+
*/
/**
* IMBAG API - van de LVBAG
* Dit is de [BAG API](https://zakelijk.kadaster.nl/-/bag-api) Individuele Bevragingen van de Landelijke Voorziening Basisregistratie Adressen en Gebouwen (LVBAG). Meer informatie over de Basisregistratie Adressen en Gebouwen is te vinden op de website van het [Ministerie van Binnenlandse Zaken en Koninkrijksrelaties](https://www.geobasisregistraties.nl/basisregistraties/adressen-en-gebouwen) en [Kadaster](https://zakelijk.kadaster.nl/bag). De BAG API levert informatie conform de [BAG Catalogus 2018](https://www.geobasisregistraties.nl/documenten/publicatie/2018/03/12/catalogus-2018) en het informatiemodel IMBAG 2.0. De API specificatie volgt de [Nederlandse API-Strategie](https://docs.geostandaarden.nl/api/API-Strategie) specificatie versie van 20200204 en is opgesteld in [OpenAPI Specificatie](https://www.forumstandaardisatie.nl/standaard/openapi-specification) (OAS) v3. Het standaard mediatype HAL (`application/hal+json`) wordt gebruikt. Dit is een mediatype voor het weergeven van resources en hun relaties via hyperlinks. Deze API is vooral gericht op individuele bevragingen (op basis van de identificerende gegevens van een object). Om gebruik te kunnen maken van de BAG API is een API key nodig, deze kan verkregen worden door het [aanvraagformulier](https://formulieren.kadaster.nl/aanvraag_bag_api_individuele_bevragingen_productie) in te vullen. Voor vragen, neem contact op met de LVBAG beheerder o.v.v. BAG API 2.0. We zijn aan het kijken naar een geschikt medium hiervoor, mede ook om de API iteratief te kunnen opstellen of doorontwikkelen samen met de community. Als de API iets (nog) niet kan, wat u wel graag wilt, neem dan contact op.
* <p>
* The version of the OpenAPI document: 2.6.0
* <p>
* <p>
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package net.atos.client.bag.api;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import org.eclipse.microprofile.faulttolerance.Timeout;
import org.eclipse.microprofile.rest.client.annotation.RegisterClientHeaders;
import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
import org.eclipse.microprofile.rest.client.annotation.RegisterProviders;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import net.atos.client.bag.model.OpenbareRuimteIOHal;
import net.atos.client.bag.model.OpenbareRuimteIOHalCollection;
import net.atos.client.bag.model.OpenbareRuimteIOLvcHalCollection;
import net.atos.client.bag.util.BAGClientHeadersFactory;
import net.atos.client.bag.util.JsonbConfiguration;
import net.atos.client.brp.exception.RuntimeExceptionMapper;
/**
* IMBAG API - van de LVBAG
*
* <p>Dit is de [BAG API](https://zakelijk.kadaster.nl/-/bag-api) Individuele Bevragingen van de Landelijke Voorziening Basisregistratie Adressen en Gebouwen (LVBAG). Meer informatie over de Basisregistratie Adressen en Gebouwen is te vinden op de website van het [Ministerie van Binnenlandse Zaken en Koninkrijksrelaties](https://www.geobasisregistraties.nl/basisregistraties/adressen-en-gebouwen) en [Kadaster](https://zakelijk.kadaster.nl/bag). De BAG API levert informatie conform de [BAG Catalogus 2018](https://www.geobasisregistraties.nl/documenten/publicatie/2018/03/12/catalogus-2018) en het informatiemodel IMBAG 2.0. De API specificatie volgt de [Nederlandse API-Strategie](https://docs.geostandaarden.nl/api/API-Strategie) specificatie versie van 20200204 en is opgesteld in [OpenAPI Specificatie](https://www.forumstandaardisatie.nl/standaard/openapi-specification) (OAS) v3. Het standaard mediatype HAL (`application/hal+json`) wordt gebruikt. Dit is een mediatype voor het weergeven van resources en hun relaties via hyperlinks. Deze API is vooral gericht op individuele bevragingen (op basis van de identificerende gegevens van een object). Om gebruik te kunnen maken van de BAG API is een API key nodig, deze kan verkregen worden door het [aanvraagformulier](https://formulieren.kadaster.nl/aanvraag_bag_api_individuele_bevragingen_productie) in te vullen. Voor vragen, neem contact op met de LVBAG beheerder o.v.v. BAG API 2.0. We zijn aan het kijken naar een geschikt medium hiervoor, mede ook om de API iteratief te kunnen opstellen of doorontwikkelen samen met de community. Als de API iets (nog) niet kan, wat u wel graag wilt, neem dan contact op.
*/
@RegisterRestClient(configKey = "BAG-API-Client")
@RegisterClientHeaders(BAGClientHeadersFactory.class)
@RegisterProviders({
@RegisterProvider(RuntimeExceptionMapper.class),
@RegisterProvider(JsonbConfiguration.class)})
@Timeout(unit = ChronoUnit.SECONDS, value = 5)
@Path("/openbareruimten")
public interface OpenbareRuimteApi {
/**
* bevragen van een openbare ruimte met de identificatie van een openbare ruimte.
* <p>
* Bevragen/raadplegen van een openbare ruimte met de identificatie van een openbare ruimte. Parameter huidig kan worden toegepast, zie [functionele specificatie huidig](https://github.com/lvbag/BAG-API/blob/master/Features/huidig.feature). De geldigOp en beschikbaarOp parameters kunnen gebruikt worden voor tijdreis vragen, zie [functionele specificatie tijdreizen](https://github.com/lvbag/BAG-API/blob/master/Features/tijdreizen.feature). Als expand=ligtInWoonplaats of true dan wordt de woonplaats als geneste resource geleverd, zie [functionele specificatie expand](https://github.com/lvbag/BAG-API/blob/master/Features/expand.feature).
*/
@GET
@Path("/{openbareRuimteIdentificatie}")
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOHal openbareruimteIdentificatie(
@PathParam("openbareRuimteIdentificatie") String openbareRuimteIdentificatie,
@QueryParam("geldigOp") LocalDate geldigOp, @QueryParam("beschikbaarOp") OffsetDateTime beschikbaarOp,
@QueryParam("expand") String expand,
@QueryParam("huidig") @DefaultValue("false") Boolean huidig) throws ProcessingException;
/**
* bevragen van een voorkomen van een openbare ruimte met de identificatie van een openbare ruimte en de identificatie van een voorkomen, bestaande uit een versie en een timestamp van het tijdstip van registratie in de LV BAG.
* <p>
* Bevragen/raadplegen van een voorkomen van een openbare ruimte met de identificatie van een openbare ruimte en de identificatie van een voorkomen, bestaande uit een versie en een timestamp van het tijdstip van registratie in de LV BAG.
*/
@GET
@Path("/{openbareRuimteIdentificatie}/{versie}/{timestampRegistratieLv}")
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOHal openbareruimteIdentificatieVoorkomen(
@PathParam("openbareRuimteIdentificatie") String openbareRuimteIdentificatie,
@PathParam("versie") Integer versie,
@PathParam("timestampRegistratieLv") String timestampRegistratieLv) throws ProcessingException;
/**
* bevragen levenscyclus van een openbare ruimte met de identificatie van een openbare ruimte.
* <p>
* Bevragen/raadplegen van de levenscyclus van één openbare ruimte, via de identificatie van een openbare ruimte.
*/
@GET
@Path("/{openbareRuimteIdentificatie}/lvc")
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOLvcHalCollection openbareruimteLvcIdentificatie(
@PathParam("openbareRuimteIdentificatie") String openbareRuimteIdentificatie,
@QueryParam("geheleLvc") @DefaultValue("false") Boolean geheleLvc) throws ProcessingException;
/**
* bevragen openbare ruimte(n) op basis van de verschillende combinaties van parameters.
* <p>
* De volgende (combinaties van) parameters worden ondersteund: 1. Bevragen/raadplegen van een openbare ruimte met een woonplaats naam en een openbare ruimte naam. Als expand=ligtInWoonplaats of true dan wordt de woonplaats als geneste resource geleverd, zie [functionele specificatie expand](https://github.com/lvbag/BAG-API/blob/master/Features/expand.feature). 2. Bevragen/raadplegen van een openbare ruimte met een woonplaats identificatie en een openbare ruimte naam. Als expand=ligtInWoonplaats of true dan wordt de woonplaats als geneste resource geleverd, zie [functionele specificatie expand](https://github.com/lvbag/BAG-API/blob/master/Features/expand.feature). 3. Bevragen/zoeken van alle aan een woonplaats gerelateerde openbare ruimten met de woonplaats identificatie. Parameter huidig kan worden toegepast, zie [functionele specificatie huidig](https://github.com/lvbag/BAG-API/blob/master/Features/huidig.feature). Expand wordt niet ondersteund. Bij alle bovenstaande combinaties wordt paginering ondersteund en kunnen de parameters geldigOp en beschikbaarOp worden gebruikt. Voor paginering, zie: [functionele specificatie paginering](https://github.com/lvbag/BAG-API/blob/master/Features/paginering.feature). De geldigOp en beschikbaarOp parameters kunnen gebruikt worden voor tijdreis vragen, zie [functionele specificatie tijdreizen](https://github.com/lvbag/BAG-API/blob/master/Features/tijdreizen.feature).
*/
@GET
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOHalCollection zoekOpenbareRuimten(@QueryParam("woonplaatsNaam") String woonplaatsNaam,
@QueryParam("openbareRuimteNaam") String openbareRuimteNaam,
@QueryParam("woonplaatsIdentificatie") String woonplaatsIdentificatie,
@QueryParam("huidig") @DefaultValue("false") Boolean huidig, @QueryParam("geldigOp") LocalDate geldigOp,
@QueryParam("beschikbaarOp") OffsetDateTime beschikbaarOp,
@QueryParam("page") @DefaultValue("1") Integer page,
@QueryParam("pageSize") @DefaultValue("20") Integer pageSize,
@QueryParam("expand") String expand) throws ProcessingException;
}
| NL-AMS-LOCGOV/zaakafhandelcomponent | src/main/java/net/atos/client/bag/api/OpenbareRuimteApi.java | 3,285 | /**
* bevragen levenscyclus van een openbare ruimte met de identificatie van een openbare ruimte.
* <p>
* Bevragen/raadplegen van de levenscyclus van één openbare ruimte, via de identificatie van een openbare ruimte.
*/ | block_comment | nl | /*
* SPDX-FileCopyrightText: 2023 Atos
* SPDX-License-Identifier: EUPL-1.2+
*/
/**
* IMBAG API - van de LVBAG
* Dit is de [BAG API](https://zakelijk.kadaster.nl/-/bag-api) Individuele Bevragingen van de Landelijke Voorziening Basisregistratie Adressen en Gebouwen (LVBAG). Meer informatie over de Basisregistratie Adressen en Gebouwen is te vinden op de website van het [Ministerie van Binnenlandse Zaken en Koninkrijksrelaties](https://www.geobasisregistraties.nl/basisregistraties/adressen-en-gebouwen) en [Kadaster](https://zakelijk.kadaster.nl/bag). De BAG API levert informatie conform de [BAG Catalogus 2018](https://www.geobasisregistraties.nl/documenten/publicatie/2018/03/12/catalogus-2018) en het informatiemodel IMBAG 2.0. De API specificatie volgt de [Nederlandse API-Strategie](https://docs.geostandaarden.nl/api/API-Strategie) specificatie versie van 20200204 en is opgesteld in [OpenAPI Specificatie](https://www.forumstandaardisatie.nl/standaard/openapi-specification) (OAS) v3. Het standaard mediatype HAL (`application/hal+json`) wordt gebruikt. Dit is een mediatype voor het weergeven van resources en hun relaties via hyperlinks. Deze API is vooral gericht op individuele bevragingen (op basis van de identificerende gegevens van een object). Om gebruik te kunnen maken van de BAG API is een API key nodig, deze kan verkregen worden door het [aanvraagformulier](https://formulieren.kadaster.nl/aanvraag_bag_api_individuele_bevragingen_productie) in te vullen. Voor vragen, neem contact op met de LVBAG beheerder o.v.v. BAG API 2.0. We zijn aan het kijken naar een geschikt medium hiervoor, mede ook om de API iteratief te kunnen opstellen of doorontwikkelen samen met de community. Als de API iets (nog) niet kan, wat u wel graag wilt, neem dan contact op.
* <p>
* The version of the OpenAPI document: 2.6.0
* <p>
* <p>
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package net.atos.client.bag.api;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import org.eclipse.microprofile.faulttolerance.Timeout;
import org.eclipse.microprofile.rest.client.annotation.RegisterClientHeaders;
import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
import org.eclipse.microprofile.rest.client.annotation.RegisterProviders;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import net.atos.client.bag.model.OpenbareRuimteIOHal;
import net.atos.client.bag.model.OpenbareRuimteIOHalCollection;
import net.atos.client.bag.model.OpenbareRuimteIOLvcHalCollection;
import net.atos.client.bag.util.BAGClientHeadersFactory;
import net.atos.client.bag.util.JsonbConfiguration;
import net.atos.client.brp.exception.RuntimeExceptionMapper;
/**
* IMBAG API - van de LVBAG
*
* <p>Dit is de [BAG API](https://zakelijk.kadaster.nl/-/bag-api) Individuele Bevragingen van de Landelijke Voorziening Basisregistratie Adressen en Gebouwen (LVBAG). Meer informatie over de Basisregistratie Adressen en Gebouwen is te vinden op de website van het [Ministerie van Binnenlandse Zaken en Koninkrijksrelaties](https://www.geobasisregistraties.nl/basisregistraties/adressen-en-gebouwen) en [Kadaster](https://zakelijk.kadaster.nl/bag). De BAG API levert informatie conform de [BAG Catalogus 2018](https://www.geobasisregistraties.nl/documenten/publicatie/2018/03/12/catalogus-2018) en het informatiemodel IMBAG 2.0. De API specificatie volgt de [Nederlandse API-Strategie](https://docs.geostandaarden.nl/api/API-Strategie) specificatie versie van 20200204 en is opgesteld in [OpenAPI Specificatie](https://www.forumstandaardisatie.nl/standaard/openapi-specification) (OAS) v3. Het standaard mediatype HAL (`application/hal+json`) wordt gebruikt. Dit is een mediatype voor het weergeven van resources en hun relaties via hyperlinks. Deze API is vooral gericht op individuele bevragingen (op basis van de identificerende gegevens van een object). Om gebruik te kunnen maken van de BAG API is een API key nodig, deze kan verkregen worden door het [aanvraagformulier](https://formulieren.kadaster.nl/aanvraag_bag_api_individuele_bevragingen_productie) in te vullen. Voor vragen, neem contact op met de LVBAG beheerder o.v.v. BAG API 2.0. We zijn aan het kijken naar een geschikt medium hiervoor, mede ook om de API iteratief te kunnen opstellen of doorontwikkelen samen met de community. Als de API iets (nog) niet kan, wat u wel graag wilt, neem dan contact op.
*/
@RegisterRestClient(configKey = "BAG-API-Client")
@RegisterClientHeaders(BAGClientHeadersFactory.class)
@RegisterProviders({
@RegisterProvider(RuntimeExceptionMapper.class),
@RegisterProvider(JsonbConfiguration.class)})
@Timeout(unit = ChronoUnit.SECONDS, value = 5)
@Path("/openbareruimten")
public interface OpenbareRuimteApi {
/**
* bevragen van een openbare ruimte met de identificatie van een openbare ruimte.
* <p>
* Bevragen/raadplegen van een openbare ruimte met de identificatie van een openbare ruimte. Parameter huidig kan worden toegepast, zie [functionele specificatie huidig](https://github.com/lvbag/BAG-API/blob/master/Features/huidig.feature). De geldigOp en beschikbaarOp parameters kunnen gebruikt worden voor tijdreis vragen, zie [functionele specificatie tijdreizen](https://github.com/lvbag/BAG-API/blob/master/Features/tijdreizen.feature). Als expand=ligtInWoonplaats of true dan wordt de woonplaats als geneste resource geleverd, zie [functionele specificatie expand](https://github.com/lvbag/BAG-API/blob/master/Features/expand.feature).
*/
@GET
@Path("/{openbareRuimteIdentificatie}")
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOHal openbareruimteIdentificatie(
@PathParam("openbareRuimteIdentificatie") String openbareRuimteIdentificatie,
@QueryParam("geldigOp") LocalDate geldigOp, @QueryParam("beschikbaarOp") OffsetDateTime beschikbaarOp,
@QueryParam("expand") String expand,
@QueryParam("huidig") @DefaultValue("false") Boolean huidig) throws ProcessingException;
/**
* bevragen van een voorkomen van een openbare ruimte met de identificatie van een openbare ruimte en de identificatie van een voorkomen, bestaande uit een versie en een timestamp van het tijdstip van registratie in de LV BAG.
* <p>
* Bevragen/raadplegen van een voorkomen van een openbare ruimte met de identificatie van een openbare ruimte en de identificatie van een voorkomen, bestaande uit een versie en een timestamp van het tijdstip van registratie in de LV BAG.
*/
@GET
@Path("/{openbareRuimteIdentificatie}/{versie}/{timestampRegistratieLv}")
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOHal openbareruimteIdentificatieVoorkomen(
@PathParam("openbareRuimteIdentificatie") String openbareRuimteIdentificatie,
@PathParam("versie") Integer versie,
@PathParam("timestampRegistratieLv") String timestampRegistratieLv) throws ProcessingException;
/**
* bevragen levenscyclus van<SUF>*/
@GET
@Path("/{openbareRuimteIdentificatie}/lvc")
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOLvcHalCollection openbareruimteLvcIdentificatie(
@PathParam("openbareRuimteIdentificatie") String openbareRuimteIdentificatie,
@QueryParam("geheleLvc") @DefaultValue("false") Boolean geheleLvc) throws ProcessingException;
/**
* bevragen openbare ruimte(n) op basis van de verschillende combinaties van parameters.
* <p>
* De volgende (combinaties van) parameters worden ondersteund: 1. Bevragen/raadplegen van een openbare ruimte met een woonplaats naam en een openbare ruimte naam. Als expand=ligtInWoonplaats of true dan wordt de woonplaats als geneste resource geleverd, zie [functionele specificatie expand](https://github.com/lvbag/BAG-API/blob/master/Features/expand.feature). 2. Bevragen/raadplegen van een openbare ruimte met een woonplaats identificatie en een openbare ruimte naam. Als expand=ligtInWoonplaats of true dan wordt de woonplaats als geneste resource geleverd, zie [functionele specificatie expand](https://github.com/lvbag/BAG-API/blob/master/Features/expand.feature). 3. Bevragen/zoeken van alle aan een woonplaats gerelateerde openbare ruimten met de woonplaats identificatie. Parameter huidig kan worden toegepast, zie [functionele specificatie huidig](https://github.com/lvbag/BAG-API/blob/master/Features/huidig.feature). Expand wordt niet ondersteund. Bij alle bovenstaande combinaties wordt paginering ondersteund en kunnen de parameters geldigOp en beschikbaarOp worden gebruikt. Voor paginering, zie: [functionele specificatie paginering](https://github.com/lvbag/BAG-API/blob/master/Features/paginering.feature). De geldigOp en beschikbaarOp parameters kunnen gebruikt worden voor tijdreis vragen, zie [functionele specificatie tijdreizen](https://github.com/lvbag/BAG-API/blob/master/Features/tijdreizen.feature).
*/
@GET
@Produces({"application/hal+json", "application/problem+json"})
public OpenbareRuimteIOHalCollection zoekOpenbareRuimten(@QueryParam("woonplaatsNaam") String woonplaatsNaam,
@QueryParam("openbareRuimteNaam") String openbareRuimteNaam,
@QueryParam("woonplaatsIdentificatie") String woonplaatsIdentificatie,
@QueryParam("huidig") @DefaultValue("false") Boolean huidig, @QueryParam("geldigOp") LocalDate geldigOp,
@QueryParam("beschikbaarOp") OffsetDateTime beschikbaarOp,
@QueryParam("page") @DefaultValue("1") Integer page,
@QueryParam("pageSize") @DefaultValue("20") Integer pageSize,
@QueryParam("expand") String expand) throws ProcessingException;
}
|
20905_1 | /*
* Copyright 2013 Netherlands eScience Center
*
* 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.esciencecenter.eastroviz.flaggers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
Wanneer je informatie hebt in frequentierichting zou je ook kunnen
overwegen om (iteratief?) te "smoothen" in die richting: dus eerst een
eerste ongevoelige (sum)threshold om de grootste pieken eruit te halen,
dan een lowpass filter (e.g. 1d Gaussian convolution) op de
frequentierichting uitvoeren, thresholden+smoothen nogmaals herhalen op
het verschil en dan een laatste keer sumthresholden. Daardoor
"vergelijk" je kanalen onderling en wordt je ook gevoeliger voor
veranderingen niet-broadband RFI. Wanneer je een "absolute" sumthreshold
"broadband" detector + de gesmoothde spectrale detector combineert is
dit is erg effectief, denk ik. Dit is natuurlijk een geavanceerdere
thresholder en vast niet het eerste algoritme wat je wilt implementeren
-- ik weet uberhaubt niet of het technisch mogelijk is op de blue gene,
maar het is een idee. Het is niet zoo zwaar om dit te doen.
*/
public class PostCorrelationSmoothedSumThresholdFlagger extends PostCorrelationSumThresholdFlagger {
private static final Logger logger = LoggerFactory.getLogger(PostCorrelationSumThresholdFlagger.class);
public PostCorrelationSmoothedSumThresholdFlagger(final int nrChannels, final float baseSensitivity, final float SIREtaValue) {
super(nrChannels, baseSensitivity, SIREtaValue);
}
// we have the data for one second, all frequencies in a subband.
// if one of the polarizations exceeds the threshold, flag them all.
@Override
protected void flag(final float[] powers, final boolean[] flagged, final int pol) {
calculateStatistics(powers, flagged); // sets mean, median, stdDev
logger.trace("mean = " + getMean() + ", median = " + getMedian() + ", stdDev = " + getStdDev());
// first do an insensitive sumthreshold
final float originalSensitivity = getBaseSensitivity();
setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive!
sumThreshold1D(powers, flagged); // sets flags, and replaces flagged samples with threshold
// smooth
final float[] smoothedPower = oneDimensionalGausConvolution(powers, 0.5f); // 2nd param is sigma, heigth of the gauss curve
// calculate difference
final float[] diff = new float[getNrChannels()];
for (int i = 0; i < getNrChannels(); i++) {
diff[i] = powers[i] - smoothedPower[i];
}
// flag based on difference
calculateStatistics(diff, flagged); // sets mean, median, stdDev
setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive!
sumThreshold1D(diff, flagged);
// and one final pass on the flagged power
calculateStatistics(powers, flagged); // sets mean, median, stdDev
setBaseSensitivity(originalSensitivity * 0.80f); // higher number is less sensitive!
sumThreshold1D(powers, flagged);
setBaseSensitivity(originalSensitivity);
}
}
| NLeSC/eAstroViz | src/nl/esciencecenter/eastroviz/flaggers/PostCorrelationSmoothedSumThresholdFlagger.java | 1,038 | /*
Wanneer je informatie hebt in frequentierichting zou je ook kunnen
overwegen om (iteratief?) te "smoothen" in die richting: dus eerst een
eerste ongevoelige (sum)threshold om de grootste pieken eruit te halen,
dan een lowpass filter (e.g. 1d Gaussian convolution) op de
frequentierichting uitvoeren, thresholden+smoothen nogmaals herhalen op
het verschil en dan een laatste keer sumthresholden. Daardoor
"vergelijk" je kanalen onderling en wordt je ook gevoeliger voor
veranderingen niet-broadband RFI. Wanneer je een "absolute" sumthreshold
"broadband" detector + de gesmoothde spectrale detector combineert is
dit is erg effectief, denk ik. Dit is natuurlijk een geavanceerdere
thresholder en vast niet het eerste algoritme wat je wilt implementeren
-- ik weet uberhaubt niet of het technisch mogelijk is op de blue gene,
maar het is een idee. Het is niet zoo zwaar om dit te doen.
*/ | block_comment | nl | /*
* Copyright 2013 Netherlands eScience Center
*
* 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.esciencecenter.eastroviz.flaggers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
Wanneer je informatie<SUF>*/
public class PostCorrelationSmoothedSumThresholdFlagger extends PostCorrelationSumThresholdFlagger {
private static final Logger logger = LoggerFactory.getLogger(PostCorrelationSumThresholdFlagger.class);
public PostCorrelationSmoothedSumThresholdFlagger(final int nrChannels, final float baseSensitivity, final float SIREtaValue) {
super(nrChannels, baseSensitivity, SIREtaValue);
}
// we have the data for one second, all frequencies in a subband.
// if one of the polarizations exceeds the threshold, flag them all.
@Override
protected void flag(final float[] powers, final boolean[] flagged, final int pol) {
calculateStatistics(powers, flagged); // sets mean, median, stdDev
logger.trace("mean = " + getMean() + ", median = " + getMedian() + ", stdDev = " + getStdDev());
// first do an insensitive sumthreshold
final float originalSensitivity = getBaseSensitivity();
setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive!
sumThreshold1D(powers, flagged); // sets flags, and replaces flagged samples with threshold
// smooth
final float[] smoothedPower = oneDimensionalGausConvolution(powers, 0.5f); // 2nd param is sigma, heigth of the gauss curve
// calculate difference
final float[] diff = new float[getNrChannels()];
for (int i = 0; i < getNrChannels(); i++) {
diff[i] = powers[i] - smoothedPower[i];
}
// flag based on difference
calculateStatistics(diff, flagged); // sets mean, median, stdDev
setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive!
sumThreshold1D(diff, flagged);
// and one final pass on the flagged power
calculateStatistics(powers, flagged); // sets mean, median, stdDev
setBaseSensitivity(originalSensitivity * 0.80f); // higher number is less sensitive!
sumThreshold1D(powers, flagged);
setBaseSensitivity(originalSensitivity);
}
}
|
84025_2 | package nl.pvanassen.ns.model.prijzen;
import nl.pvanassen.ns.handle.Handle;
import nl.pvanassen.ns.xml.Xml;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Handle for parsing 'producten' xml, as defined in <a
* href="http://www.ns.nl/api/api#api-documentatie-prijzen">documentatie prijzen</a>
*
* @author Paul van Assen
*
*/
public class PrijsHandle implements Handle<Prijzen> {
/**
* {@inheritDoc}
*
* @see nl.pvanassen.ns.handle.Handle#getModel(java.io.InputStream)
*/
@Override
public Prijzen getModel(InputStream stream) {
Map<String, VervoerderKeuze> vervoerderKeuzes = new HashMap<>();
Xml xml = Xml.getXml(stream, "VervoerderKeuzes");
for (Xml vervoerderKeuze : xml.children("VervoerderKeuze")) {
String vervoerderKeuzeNaam = vervoerderKeuze.attr("naam");
int tariefEenheden = Integer.parseInt(vervoerderKeuze.child("Tariefeenheden").content());
Map<String, ReisType> reisTypes = new HashMap<>();
for (Xml reisTypeXml : vervoerderKeuze.children("ReisType")) {
String reisTypeNaam = reisTypeXml.attr("name");
Map<Integer, ReisKlasse> reisKlassen = new HashMap<>();
for (Xml reisKlasseXml : reisTypeXml.children("ReisKlasse")) {
int klasse = Integer.parseInt(reisKlasseXml.attr("klasse"));
// <Prijsdeel vervoerder="NS" prijs="47.20" naar="GDM" van="RTD"/>
List<Prijsdeel> prijsdelen = new LinkedList<>();
for (Xml prijsdeelXml : reisKlasseXml.children("Prijsdeel")) {
prijsdelen.add(new Prijsdeel(prijsdeelXml.attr("vervoerder"), new BigDecimal(prijsdeelXml.attr("prijs")), prijsdeelXml.attr("van"), prijsdeelXml.attr("naar")));
}
BigDecimal totaal = new BigDecimal(reisKlasseXml.child("Totaal").content());
Map<String, BigDecimal> kortingprijzen = new HashMap<>();
for (Xml kortingsPrijsXml : reisKlasseXml.child("Korting").children("Kortingsprijs")) {
kortingprijzen.put(kortingsPrijsXml.attr("name"), new BigDecimal(kortingsPrijsXml.attr("prijs")));
}
reisKlassen.put(klasse, new ReisKlasse(klasse, prijsdelen, totaal, Collections.unmodifiableMap(kortingprijzen)));
}
reisTypes.put(reisTypeNaam, new ReisType(reisTypeNaam, Collections.unmodifiableMap(reisKlassen)));
}
vervoerderKeuzes.put(vervoerderKeuzeNaam, new VervoerderKeuze(vervoerderKeuzeNaam, tariefEenheden, Collections.unmodifiableMap(reisTypes)));
}
return new Prijzen(Collections.unmodifiableMap(vervoerderKeuzes));
}
}
| NS-API/ns-api | src/main/java/nl/pvanassen/ns/model/prijzen/PrijsHandle.java | 1,004 | // <Prijsdeel vervoerder="NS" prijs="47.20" naar="GDM" van="RTD"/> | line_comment | nl | package nl.pvanassen.ns.model.prijzen;
import nl.pvanassen.ns.handle.Handle;
import nl.pvanassen.ns.xml.Xml;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Handle for parsing 'producten' xml, as defined in <a
* href="http://www.ns.nl/api/api#api-documentatie-prijzen">documentatie prijzen</a>
*
* @author Paul van Assen
*
*/
public class PrijsHandle implements Handle<Prijzen> {
/**
* {@inheritDoc}
*
* @see nl.pvanassen.ns.handle.Handle#getModel(java.io.InputStream)
*/
@Override
public Prijzen getModel(InputStream stream) {
Map<String, VervoerderKeuze> vervoerderKeuzes = new HashMap<>();
Xml xml = Xml.getXml(stream, "VervoerderKeuzes");
for (Xml vervoerderKeuze : xml.children("VervoerderKeuze")) {
String vervoerderKeuzeNaam = vervoerderKeuze.attr("naam");
int tariefEenheden = Integer.parseInt(vervoerderKeuze.child("Tariefeenheden").content());
Map<String, ReisType> reisTypes = new HashMap<>();
for (Xml reisTypeXml : vervoerderKeuze.children("ReisType")) {
String reisTypeNaam = reisTypeXml.attr("name");
Map<Integer, ReisKlasse> reisKlassen = new HashMap<>();
for (Xml reisKlasseXml : reisTypeXml.children("ReisKlasse")) {
int klasse = Integer.parseInt(reisKlasseXml.attr("klasse"));
// <Prijsdeel vervoerder="NS"<SUF>
List<Prijsdeel> prijsdelen = new LinkedList<>();
for (Xml prijsdeelXml : reisKlasseXml.children("Prijsdeel")) {
prijsdelen.add(new Prijsdeel(prijsdeelXml.attr("vervoerder"), new BigDecimal(prijsdeelXml.attr("prijs")), prijsdeelXml.attr("van"), prijsdeelXml.attr("naar")));
}
BigDecimal totaal = new BigDecimal(reisKlasseXml.child("Totaal").content());
Map<String, BigDecimal> kortingprijzen = new HashMap<>();
for (Xml kortingsPrijsXml : reisKlasseXml.child("Korting").children("Kortingsprijs")) {
kortingprijzen.put(kortingsPrijsXml.attr("name"), new BigDecimal(kortingsPrijsXml.attr("prijs")));
}
reisKlassen.put(klasse, new ReisKlasse(klasse, prijsdelen, totaal, Collections.unmodifiableMap(kortingprijzen)));
}
reisTypes.put(reisTypeNaam, new ReisType(reisTypeNaam, Collections.unmodifiableMap(reisKlassen)));
}
vervoerderKeuzes.put(vervoerderKeuzeNaam, new VervoerderKeuze(vervoerderKeuzeNaam, tariefEenheden, Collections.unmodifiableMap(reisTypes)));
}
return new Prijzen(Collections.unmodifiableMap(vervoerderKeuzes));
}
}
|
183327_36 | /*NSRCOPYRIGHT
Copyright (C) 1999-2011 University of Washington
Developed by the National Simulation Resource
Department of Bioengineering, Box 355061
University of Washington, Seattle, WA 98195-5061.
Dr. J. B. Bassingthwaighte, Director
END_NSRCOPYRIGHT*/
// n-dimensional sampled data
package JSim.data;
import JSim.util.*;
import JSim.expr.*;
public class RealNData extends Data {
private GridData[] grids; // grid domains for data
private int ngrids; // # grids
private int nsamples; // # samples
private double[] samples; // samples
private double min, minpos, max; // min, min positive, max samples
private double close; // grid closeness criterion
private int interp; // Interp method, see below
public final static int NEAREST_INTERP = 0;
public final static int OLDLINEAR_INTERP = 1;
public final static int VELDHUIZEN_INTERP = 2;
public final static int MULTILINEAR_INTERP = 3;
public final static int MULTILINEARNAN_INTERP = 4;
// constructors
public RealNData(String d, Unit u, GridData[] g)
throws Xcept {
super(d, u);
grids = g;
ngrids = (grids == null) ? 0 : grids.length;
nsamples = 1;
close = 1;
for (int i=0; i<ndim(); i++) {
GridData x = grids[i];
if (x == null) throw new Xcept(d +
" data grid undefined");
nsamples *= x.ct();
double xclose = (x.max()-x.min())/ (x.ct()-1);
if (i==0 || xclose<close) close=xclose;
}
close = close * 1e-7; // single-precision accuracy
samples = new double[nsamples];
for (int i=0; i<nsamples; i++)
samples[i] = Double.NaN;
interp = MULTILINEARNAN_INTERP;
}
public RealNData(String d, Unit u,
GridData[] g, double[] samp) throws Xcept {
this(d, u, g);
set(samp);
}
// convert grid to sampled
public RealNData(GridData g) throws Xcept {
this(g.desc, g.unit, new GridData[] { g });
set(g.samples());
}
// resample grid
public RealNData(RealNData base, GridData[] g,
boolean nanOutOfRange) throws Xcept {
this(base.desc, base.unit, g);
if (ndim() != base.ndim()) throw new Xcept(
"Data resampling dimesion conflict");
// fill in data
double[] gval = new double[ndim()];
for (int i=0; i<nsamples(); i++) {
int[] gpos = gridPos(i);
for (int j=0; j<ndim(); j++)
gval[j] = grid(j).realVal(gpos[j]);
samples[i] = base.realVal(gval);
if (nanOutOfRange && base.outOfRange(gval))
samples[i] = Double.NaN;
}
}
// set data values
public void set(int inx, double dat) {
samples[inx] = dat;
}
public void set(int[] gpos, double dat) throws Xcept {
int inx = inx(gpos);
samples[inx] = dat;
}
public void set(double dat) throws Xcept {
if (ndim() != 0) throw new Xcept(this,
"set() invalid for ndim()>0");
set(0, dat);
}
public void set(double[] dat) throws Xcept {
if (dat.length != nsamples) throw new Xcept(this,
"Mismatched array length in set()");
for (int i=0; i<nsamples; i++)
samples[i] = dat[i];
}
public void setSome(double[] dat) throws Xcept {
int n = Math.min(nsamples, dat.length);
for (int i=0; i<n; i++)
samples[i] = dat[i];
}
// subset import
public void set(Subset sset, double[] dat) throws Xcept {
if (sset == null || ndim() != 1) {
set(dat);
return;
}
// 1D reduction
int hix = Math.min(sset.hix, samples.length-1);
for (int i=sset.lox; i<=hix; i++)
samples[i] = dat[i-sset.lox];
}
// subset export
public double[] samples(Subset sset) throws Xcept {
if (sset == null || ndim() != 1) return samples;
if (sset.lox > sset.hix) return samples; // ???
// 1D reduction
double[] dat = new double[sset.hix-sset.lox+1];
for (int i=sset.lox; i<=sset.hix; i++)
dat[i-sset.lox] = (i>=samples.length) ?
Double.NaN : samples[i];
return dat;
}
// interp
public void setInterp(int i) throws Xcept {
switch (i) {
case NEAREST_INTERP:
case OLDLINEAR_INTERP:
case VELDHUIZEN_INTERP:
case MULTILINEAR_INTERP:
case MULTILINEARNAN_INTERP:
interp = i;
return;
}
throw new Xcept(this, "Unknown interpolation method");
}
// query
public DataInfo info(Subset sset) throws Xcept {
return new Info(this, sset);
}
public int ndim() { return ngrids; }
public GridData grid(int i) { return grids[i]; }
public int nsamples() { return nsamples; }
public double realVal(int[] gpos) throws Xcept {
return samples[inx(gpos)];
}
public double realVal(int i) { return samples[i]; }
public double realVal() throws Xcept {
if (ndim() != 0) throw new Xcept(this,
"realVal() invalid for ndim()>0");
return realVal(0);
}
public double[] samples() { return samples; }
public void calcExtrema() {
min = minpos = max = Double.NaN;
for (int i=0; i<samples.length; i++) {
double d = samples[i];
if (Double.isNaN(d)) continue;
if (Double.isInfinite(d)) continue;
if (Double.isNaN(min) || d<min) min = d;
if (d>0 && (Double.isNaN(minpos) || d<minpos))
minpos = d;
if (Double.isNaN(max) || d>max) max = d;
}
}
public double min() { return min; }
public double minpos() { return minpos; }
public double max() { return max; }
// legend grids
public String legendGrids() {
if (ndim() == 0) return "";
String s = "(";
for (int i=0; i<ndim(); i++) {
if (i>0) s = s + ",";
GridData grid = grid(i);
String gs = grid.name;
if (Util.isBlank(gs)) gs = grid.desc;
if (Util.isBlank(gs)) gs = "*";
s = s + gs;
}
return s + ")";
}
// which interpolated algorithm?
public double realVal(double[] vals) throws Xcept {
if (ndim() != vals.length) throw new Xcept(this,
"incorrect #args for RealNData interpolation");
switch (interp) {
case OLDLINEAR_INTERP:
return realValOld(vals);
case VELDHUIZEN_INTERP:
return realValVeldhuizen(vals);
case MULTILINEAR_INTERP:
return realValMulti(vals);
case MULTILINEARNAN_INTERP:
return realValMultiNaN(vals);
default:
throw new Xcept(this,
"Unsupported interpolation method=" + interp);
}
}
// original (flawed) interpolated query
public double realValOld(double[] vals) throws Xcept {
int[] loarr = new int[ndim()];
int[] hiarr = new int[ndim()];
double frac = 0;
for (int i=0; i<ndim(); i++) {
GridData x = grid(i);
double val = vals[i];
// j = low side index
int j = x.nearestInx(val);
double jval = x.realVal(j);
if (j>0 && jval>val && val>x.min() && val<x.max())
jval = x.realVal(--j);
// k = high side index
int k = (j<x.ct()-1) ? j+1 : j;
double kval = x.realVal(k);
double xfrac = (j==k) ?
0 : (val-jval)/(kval - jval);
if (xfrac <= 0) {
xfrac = 0;
k=j;
} else if (xfrac >= 1) {
xfrac = 0;
j=k;
}
// store
loarr[i] = j;
hiarr[i] = k;
frac += xfrac*xfrac;
}
frac = Math.sqrt(frac);
double ret = 0;
if (frac < 1) ret += (1-frac)*realVal(loarr);
if (frac > close) ret += frac*realVal(hiarr);
return ret;
}
// Multilinear interpolation
public double realValMulti(double[] vals) throws Xcept {
if (ndim() > 32)
throw new Xcept(this,"Interpolation: more than 32 dimensions");
int[] loarr = new int[ndim()];
int[] hiarr = new int[ndim()];
int[] coord = new int[ndim()];
double[] frac = new double[ndim()];
for (int i=0; i<ndim(); i++) {
//get grid coordinate
GridData x = grid(i);
double val = vals[i];
// j = low side index
int j = x.nearestInx(val);
double jval = x.realVal(j);
if (j>0 && jval>val && val>x.min() && val<x.max())
jval = x.realVal(--j);
// k = high side index
int k = (j<x.ct()-1) ? j+1 : j;
double kval = x.realVal(k);
// relative distance from lower node
double xfrac = (j==k) ?
0 : (val-jval)/(kval - jval);
// val is close to node
if (xfrac <= close) {
xfrac = 0;
k=j;
} else if (xfrac >= 1 - close) {
xfrac = 0;
j=k;
}
// store
loarr[i] = j;
hiarr[i] = k;
frac[i] = xfrac;
}
double w;
double ret = 0.0;
// loop over all edges of enclosing hypercube
for (long i=0; i<(1 << ndim()); i++) {
w = 1.0; // basis function associated with grid point i
// loop over edge coordinates
for (int j=0; j<ndim(); j++) {
if ((1 << j & i) == 0 ){
// the edge i is lower
// if the corresponding bit in i is not set
coord[j] = loarr[j];
w *= 1 - frac[j];
} else {
// the edge i is higher
// if the corresponding bit in i is set
coord[j] = hiarr[j];
w *= frac[j];
}
}
ret += w*realVal(coord);
}
return ret;
}
// NaN protectected Multilinear interpolation/extrapolation
public double realValMultiNaN(double[] ovals) throws Xcept {
int ndim = ndim();
if (ndim > 30)
throw new Xcept(this,"Interpolation does not support more than 30 dimensions");
// load bounding hypercube indexes: loarr, hiarr
double[] nvals = new double[ndim];
int[] loarr = new int[ndim];
int[] hiarr = new int[ndim];
for (int i=0; i<ndim; i++) {
GridData x = grid(i);
double val = ovals[i];
double xdelta = 1e-7* (x.max() - x.min());
if (val < x.min())
val = x.min();
else if (val > x.max())
val = x.max();
nvals[i] = val;
int j = x.nearestInx(val);
//System.err.println(x.desc() + ": nearestInx(" + val + ")=" + j + " realVal(" + j + ")=" + x.realVal(j));
if (j>0 && x.realVal(j) + xdelta >= val)
j--;
else if (j == x.ct()-1)
j--;
loarr[i] = j;
hiarr[i] = j+1;
}
// back off if realVal(hiarr) is NaN
if (Double.isNaN(realVal(hiarr))) {
for (int i=0; i<ndim; i++) {
if (hiarr[i] <2) continue;
hiarr[i]--;
if (Double.isNaN(realVal(hiarr)))
hiarr[i]++;
else
loarr[i]--;
}
}
// calculate fractions
double[] frac = new double[ndim];
for (int i=0; i<ndim; i++) {
GridData x = grid(i);
double jval = x.realVal(loarr[i]);
double kval = x.realVal(hiarr[i]);
frac[i] = (nvals[i] - jval) / (kval - jval);
//System.err.println(x.desc() + " val=" + nvals[i] + " j=" + loarr[i] +
//" k=" + hiarr[i] + " frac=" + frac[i]);
}
// sum frac weighted vals (vtot) and weights (wtot)
// over all edges(vertices?) of hypercube
double wtot = 0;
double vtot = 0;
double vsave = Double.NaN; // save a non-NaN value, if any
int[] coord = new int[ndim];
long npts = 1 << ndim;
for (long i=0; i<npts; i++) {
double w = 1.0; // basis function associated with grid point i
// loop over edge coordinates
for (int j=0; j<ndim(); j++) {
if ((1 << j & i) == 0 ){
// the edge i is lower
// if the corresponding bit in i is not set
coord[j] = loarr[j];
w *= 1 - frac[j];
} else {
// the edge i is higher
// if the corresponding bit in i is set
coord[j] = hiarr[j];
w *= frac[j];
}
}
double v = realVal(coord);
//System.err.println(desc() + ".realVal(" + Util.pretty(coord) + ")=" + v + " w=" + w);
if(!Double.isNaN(v)) {
vtot += v*w;
wtot += w;
vsave = v;
}
//System.err.println(" vtot=" + vtot + " wtot=" + wtot);
}
double ret = (wtot == 0) ? vsave : vtot/wtot;
//System.err.println("ret=" + ret);
return ret;
}
// interpolated query
// stepwise linear interpolation
// adapted from Todd Veldhuizen,
// Master's Theseis, Univ Waterloo MAY 1998
// http://osl.iu.edu/~tveldhui/papers/MAScThesis/node33.html
public double realValVeldhuizen(double[] vals) throws Xcept {
int[] loarr = new int[ndim()];
int[] hiarr = new int[ndim()];
IntDoub permu[] = new IntDoub[ndim()];
double frac = 0;
for (int i=0; i<ndim(); i++) {
//get grid coordinate
GridData x = grid(i);
double val = vals[i];
// j = low side index
int j = x.nearestInx(val);
double jval = x.realVal(j);
if (j>0 && jval>val && val>x.min() && val<x.max())
jval = x.realVal(--j);
// k = high side index
int k = (j<x.ct()-1) ? j+1 : j;
double kval = x.realVal(k);
// relative distance from lower node
double xfrac = (j==k) ?
0 : (val-jval)/(kval - jval);
// val is close to node
if (xfrac <= close) {
xfrac = 0;
k=j;
} else if (xfrac >= 1 - close) {
xfrac = 0;
j=k;
}
// store
loarr[i] = j;
hiarr[i] = k;
permu[i] = new IntDoub();
permu[i].i = i;
permu[i].a = xfrac;
}
java.util.Arrays.sort(permu);
int[] coord = loarr;
double coeff = 1.0;
double ret = 0.0;
for (int i=0; i<ndim(); i++) {
int j;
coeff -= permu[i].a;
ret += coeff*realVal(coord);
coeff = permu[i].a;
j = permu[i].i;
coord[j] = hiarr[j];
}
ret += coeff*realVal(coord);
return ret;
}
// sum over entire range
public double sum() {
double tot = 0;
for (int i=0; i<nsamples; i++) {
if (! Double.isNaN(samples[i]))
tot += samples[i];
}
return tot;
}
// 1D sum over restricted range
public double sum(double xmin, double xmax) throws Xcept {
if (ndim() != 1) throw new Xcept(
"sum(min,max) supports only 1D data: " + this);
GridData xgrid = grid(0);
double tot = 0;
for (int i=0; i<nsamples; i++) {
double x = xgrid.realVal(i);
if (x < xmin || x > xmax) continue;
double s = samples[i];
if (! Double.isNaN(s))
tot += s;
}
return tot;
}
// integral (RegularGridData only, for now)
public double integral() throws Xcept {
double tot = 0;
for (int i=0; i<nsamples; i++) {
int[] gpos = gridPos(i);
int wgt = 1;
for (int j=0; j<ndim(); j++) {
if (gpos[j] == 0) continue;
if (gpos[j] == grid(j).ct()-1) continue;
wgt *= 2;
}
tot += realVal(i)*wgt;
}
for (int i=0; i<ndim(); i++) {
if (! (grid(i) instanceof RegularGridData))
throw new Xcept(this,
"integral() currently supports only equal-spaced grids");
double xdelta = ((RegularGridData) grid(i)).delta();
tot *= (xdelta/2);
}
return tot;
}
// 1D integral over restricted range
public double integral(double xmin, double xmax) throws Xcept {
if (ndim() != 1) throw new Xcept(
"integral(min,max) supports only 1D data: " + this);
if (! (grid(0) instanceof RegularGridData)) throw new Xcept(
"integral(min,max) supports only regular grids: " + this);
RegularGridData xgrid = (RegularGridData) grid(0);
double delta2 = xgrid.delta() / 2;
if (xgrid.min() > xmin) xmin = xgrid.min();
if (xgrid.max() < xmax) xmax = xgrid.max();
double tot = 0;
for (int i=0; i<nsamples; i++) {
double s = samples[i];
if (Double.isNaN(s)) continue;
double x = xgrid.realVal(i);
double xlo = Math.max(xmin, x - delta2);
double xhi = Math.min(xmax, x + delta2);
if (xhi <= xlo) continue;
tot += s * (xhi - xlo);
}
return tot;
}
// serializable info
public static class Info extends DataInfo {
public DataInfo[] grids;
public double[] samples;
// constructors
public Info() { }
public Info(RealNData data, Subset sset) throws Xcept {
super(data);
int n = data.ndim();
if (n>0) {
grids = new DataInfo[n];
for (int i=0; i<n; i++)
grids[i] = data.grid(i).info();
}
samples = data.samples(sset);
subset = sset;
}
}
// test program
public static void main(String[] args) throws Exception{
int ndim = args.length/2;
GridData[] grids = new GridData[ndim];
int[] gpos = new int[ndim];
for (int i=0; i<ndim; i++) {
grids[i] = new RegularGridData("x", null,
0.0, 1.1, Util.toInt(args[i]));
gpos[i] = Util.toInt(args[i+ndim]);
}
RealNData data = new RealNData("u", null, grids);
int inx = data.inx(gpos);
int[] gpos1 = data.gridPos(inx);
System.out.print("" + inx);
for (int i=0; i<gpos1.length; i++)
System.out.print(" " + gpos1[i]);
System.out.println("");
}
// Auxiliary class for permuting sort
static class IntDoub implements Comparable {
public double a;
public int i;
public int compareTo(Object o)
{
return Double.compare(((IntDoub) o).a,a);
}
}
}
| NSR-Physiome/JSim | SRC2.0/JSim/data/RealNData.java | 6,685 | // loop over edge coordinates | line_comment | nl | /*NSRCOPYRIGHT
Copyright (C) 1999-2011 University of Washington
Developed by the National Simulation Resource
Department of Bioengineering, Box 355061
University of Washington, Seattle, WA 98195-5061.
Dr. J. B. Bassingthwaighte, Director
END_NSRCOPYRIGHT*/
// n-dimensional sampled data
package JSim.data;
import JSim.util.*;
import JSim.expr.*;
public class RealNData extends Data {
private GridData[] grids; // grid domains for data
private int ngrids; // # grids
private int nsamples; // # samples
private double[] samples; // samples
private double min, minpos, max; // min, min positive, max samples
private double close; // grid closeness criterion
private int interp; // Interp method, see below
public final static int NEAREST_INTERP = 0;
public final static int OLDLINEAR_INTERP = 1;
public final static int VELDHUIZEN_INTERP = 2;
public final static int MULTILINEAR_INTERP = 3;
public final static int MULTILINEARNAN_INTERP = 4;
// constructors
public RealNData(String d, Unit u, GridData[] g)
throws Xcept {
super(d, u);
grids = g;
ngrids = (grids == null) ? 0 : grids.length;
nsamples = 1;
close = 1;
for (int i=0; i<ndim(); i++) {
GridData x = grids[i];
if (x == null) throw new Xcept(d +
" data grid undefined");
nsamples *= x.ct();
double xclose = (x.max()-x.min())/ (x.ct()-1);
if (i==0 || xclose<close) close=xclose;
}
close = close * 1e-7; // single-precision accuracy
samples = new double[nsamples];
for (int i=0; i<nsamples; i++)
samples[i] = Double.NaN;
interp = MULTILINEARNAN_INTERP;
}
public RealNData(String d, Unit u,
GridData[] g, double[] samp) throws Xcept {
this(d, u, g);
set(samp);
}
// convert grid to sampled
public RealNData(GridData g) throws Xcept {
this(g.desc, g.unit, new GridData[] { g });
set(g.samples());
}
// resample grid
public RealNData(RealNData base, GridData[] g,
boolean nanOutOfRange) throws Xcept {
this(base.desc, base.unit, g);
if (ndim() != base.ndim()) throw new Xcept(
"Data resampling dimesion conflict");
// fill in data
double[] gval = new double[ndim()];
for (int i=0; i<nsamples(); i++) {
int[] gpos = gridPos(i);
for (int j=0; j<ndim(); j++)
gval[j] = grid(j).realVal(gpos[j]);
samples[i] = base.realVal(gval);
if (nanOutOfRange && base.outOfRange(gval))
samples[i] = Double.NaN;
}
}
// set data values
public void set(int inx, double dat) {
samples[inx] = dat;
}
public void set(int[] gpos, double dat) throws Xcept {
int inx = inx(gpos);
samples[inx] = dat;
}
public void set(double dat) throws Xcept {
if (ndim() != 0) throw new Xcept(this,
"set() invalid for ndim()>0");
set(0, dat);
}
public void set(double[] dat) throws Xcept {
if (dat.length != nsamples) throw new Xcept(this,
"Mismatched array length in set()");
for (int i=0; i<nsamples; i++)
samples[i] = dat[i];
}
public void setSome(double[] dat) throws Xcept {
int n = Math.min(nsamples, dat.length);
for (int i=0; i<n; i++)
samples[i] = dat[i];
}
// subset import
public void set(Subset sset, double[] dat) throws Xcept {
if (sset == null || ndim() != 1) {
set(dat);
return;
}
// 1D reduction
int hix = Math.min(sset.hix, samples.length-1);
for (int i=sset.lox; i<=hix; i++)
samples[i] = dat[i-sset.lox];
}
// subset export
public double[] samples(Subset sset) throws Xcept {
if (sset == null || ndim() != 1) return samples;
if (sset.lox > sset.hix) return samples; // ???
// 1D reduction
double[] dat = new double[sset.hix-sset.lox+1];
for (int i=sset.lox; i<=sset.hix; i++)
dat[i-sset.lox] = (i>=samples.length) ?
Double.NaN : samples[i];
return dat;
}
// interp
public void setInterp(int i) throws Xcept {
switch (i) {
case NEAREST_INTERP:
case OLDLINEAR_INTERP:
case VELDHUIZEN_INTERP:
case MULTILINEAR_INTERP:
case MULTILINEARNAN_INTERP:
interp = i;
return;
}
throw new Xcept(this, "Unknown interpolation method");
}
// query
public DataInfo info(Subset sset) throws Xcept {
return new Info(this, sset);
}
public int ndim() { return ngrids; }
public GridData grid(int i) { return grids[i]; }
public int nsamples() { return nsamples; }
public double realVal(int[] gpos) throws Xcept {
return samples[inx(gpos)];
}
public double realVal(int i) { return samples[i]; }
public double realVal() throws Xcept {
if (ndim() != 0) throw new Xcept(this,
"realVal() invalid for ndim()>0");
return realVal(0);
}
public double[] samples() { return samples; }
public void calcExtrema() {
min = minpos = max = Double.NaN;
for (int i=0; i<samples.length; i++) {
double d = samples[i];
if (Double.isNaN(d)) continue;
if (Double.isInfinite(d)) continue;
if (Double.isNaN(min) || d<min) min = d;
if (d>0 && (Double.isNaN(minpos) || d<minpos))
minpos = d;
if (Double.isNaN(max) || d>max) max = d;
}
}
public double min() { return min; }
public double minpos() { return minpos; }
public double max() { return max; }
// legend grids
public String legendGrids() {
if (ndim() == 0) return "";
String s = "(";
for (int i=0; i<ndim(); i++) {
if (i>0) s = s + ",";
GridData grid = grid(i);
String gs = grid.name;
if (Util.isBlank(gs)) gs = grid.desc;
if (Util.isBlank(gs)) gs = "*";
s = s + gs;
}
return s + ")";
}
// which interpolated algorithm?
public double realVal(double[] vals) throws Xcept {
if (ndim() != vals.length) throw new Xcept(this,
"incorrect #args for RealNData interpolation");
switch (interp) {
case OLDLINEAR_INTERP:
return realValOld(vals);
case VELDHUIZEN_INTERP:
return realValVeldhuizen(vals);
case MULTILINEAR_INTERP:
return realValMulti(vals);
case MULTILINEARNAN_INTERP:
return realValMultiNaN(vals);
default:
throw new Xcept(this,
"Unsupported interpolation method=" + interp);
}
}
// original (flawed) interpolated query
public double realValOld(double[] vals) throws Xcept {
int[] loarr = new int[ndim()];
int[] hiarr = new int[ndim()];
double frac = 0;
for (int i=0; i<ndim(); i++) {
GridData x = grid(i);
double val = vals[i];
// j = low side index
int j = x.nearestInx(val);
double jval = x.realVal(j);
if (j>0 && jval>val && val>x.min() && val<x.max())
jval = x.realVal(--j);
// k = high side index
int k = (j<x.ct()-1) ? j+1 : j;
double kval = x.realVal(k);
double xfrac = (j==k) ?
0 : (val-jval)/(kval - jval);
if (xfrac <= 0) {
xfrac = 0;
k=j;
} else if (xfrac >= 1) {
xfrac = 0;
j=k;
}
// store
loarr[i] = j;
hiarr[i] = k;
frac += xfrac*xfrac;
}
frac = Math.sqrt(frac);
double ret = 0;
if (frac < 1) ret += (1-frac)*realVal(loarr);
if (frac > close) ret += frac*realVal(hiarr);
return ret;
}
// Multilinear interpolation
public double realValMulti(double[] vals) throws Xcept {
if (ndim() > 32)
throw new Xcept(this,"Interpolation: more than 32 dimensions");
int[] loarr = new int[ndim()];
int[] hiarr = new int[ndim()];
int[] coord = new int[ndim()];
double[] frac = new double[ndim()];
for (int i=0; i<ndim(); i++) {
//get grid coordinate
GridData x = grid(i);
double val = vals[i];
// j = low side index
int j = x.nearestInx(val);
double jval = x.realVal(j);
if (j>0 && jval>val && val>x.min() && val<x.max())
jval = x.realVal(--j);
// k = high side index
int k = (j<x.ct()-1) ? j+1 : j;
double kval = x.realVal(k);
// relative distance from lower node
double xfrac = (j==k) ?
0 : (val-jval)/(kval - jval);
// val is close to node
if (xfrac <= close) {
xfrac = 0;
k=j;
} else if (xfrac >= 1 - close) {
xfrac = 0;
j=k;
}
// store
loarr[i] = j;
hiarr[i] = k;
frac[i] = xfrac;
}
double w;
double ret = 0.0;
// loop over all edges of enclosing hypercube
for (long i=0; i<(1 << ndim()); i++) {
w = 1.0; // basis function associated with grid point i
// loop over edge coordinates
for (int j=0; j<ndim(); j++) {
if ((1 << j & i) == 0 ){
// the edge i is lower
// if the corresponding bit in i is not set
coord[j] = loarr[j];
w *= 1 - frac[j];
} else {
// the edge i is higher
// if the corresponding bit in i is set
coord[j] = hiarr[j];
w *= frac[j];
}
}
ret += w*realVal(coord);
}
return ret;
}
// NaN protectected Multilinear interpolation/extrapolation
public double realValMultiNaN(double[] ovals) throws Xcept {
int ndim = ndim();
if (ndim > 30)
throw new Xcept(this,"Interpolation does not support more than 30 dimensions");
// load bounding hypercube indexes: loarr, hiarr
double[] nvals = new double[ndim];
int[] loarr = new int[ndim];
int[] hiarr = new int[ndim];
for (int i=0; i<ndim; i++) {
GridData x = grid(i);
double val = ovals[i];
double xdelta = 1e-7* (x.max() - x.min());
if (val < x.min())
val = x.min();
else if (val > x.max())
val = x.max();
nvals[i] = val;
int j = x.nearestInx(val);
//System.err.println(x.desc() + ": nearestInx(" + val + ")=" + j + " realVal(" + j + ")=" + x.realVal(j));
if (j>0 && x.realVal(j) + xdelta >= val)
j--;
else if (j == x.ct()-1)
j--;
loarr[i] = j;
hiarr[i] = j+1;
}
// back off if realVal(hiarr) is NaN
if (Double.isNaN(realVal(hiarr))) {
for (int i=0; i<ndim; i++) {
if (hiarr[i] <2) continue;
hiarr[i]--;
if (Double.isNaN(realVal(hiarr)))
hiarr[i]++;
else
loarr[i]--;
}
}
// calculate fractions
double[] frac = new double[ndim];
for (int i=0; i<ndim; i++) {
GridData x = grid(i);
double jval = x.realVal(loarr[i]);
double kval = x.realVal(hiarr[i]);
frac[i] = (nvals[i] - jval) / (kval - jval);
//System.err.println(x.desc() + " val=" + nvals[i] + " j=" + loarr[i] +
//" k=" + hiarr[i] + " frac=" + frac[i]);
}
// sum frac weighted vals (vtot) and weights (wtot)
// over all edges(vertices?) of hypercube
double wtot = 0;
double vtot = 0;
double vsave = Double.NaN; // save a non-NaN value, if any
int[] coord = new int[ndim];
long npts = 1 << ndim;
for (long i=0; i<npts; i++) {
double w = 1.0; // basis function associated with grid point i
// loop over<SUF>
for (int j=0; j<ndim(); j++) {
if ((1 << j & i) == 0 ){
// the edge i is lower
// if the corresponding bit in i is not set
coord[j] = loarr[j];
w *= 1 - frac[j];
} else {
// the edge i is higher
// if the corresponding bit in i is set
coord[j] = hiarr[j];
w *= frac[j];
}
}
double v = realVal(coord);
//System.err.println(desc() + ".realVal(" + Util.pretty(coord) + ")=" + v + " w=" + w);
if(!Double.isNaN(v)) {
vtot += v*w;
wtot += w;
vsave = v;
}
//System.err.println(" vtot=" + vtot + " wtot=" + wtot);
}
double ret = (wtot == 0) ? vsave : vtot/wtot;
//System.err.println("ret=" + ret);
return ret;
}
// interpolated query
// stepwise linear interpolation
// adapted from Todd Veldhuizen,
// Master's Theseis, Univ Waterloo MAY 1998
// http://osl.iu.edu/~tveldhui/papers/MAScThesis/node33.html
public double realValVeldhuizen(double[] vals) throws Xcept {
int[] loarr = new int[ndim()];
int[] hiarr = new int[ndim()];
IntDoub permu[] = new IntDoub[ndim()];
double frac = 0;
for (int i=0; i<ndim(); i++) {
//get grid coordinate
GridData x = grid(i);
double val = vals[i];
// j = low side index
int j = x.nearestInx(val);
double jval = x.realVal(j);
if (j>0 && jval>val && val>x.min() && val<x.max())
jval = x.realVal(--j);
// k = high side index
int k = (j<x.ct()-1) ? j+1 : j;
double kval = x.realVal(k);
// relative distance from lower node
double xfrac = (j==k) ?
0 : (val-jval)/(kval - jval);
// val is close to node
if (xfrac <= close) {
xfrac = 0;
k=j;
} else if (xfrac >= 1 - close) {
xfrac = 0;
j=k;
}
// store
loarr[i] = j;
hiarr[i] = k;
permu[i] = new IntDoub();
permu[i].i = i;
permu[i].a = xfrac;
}
java.util.Arrays.sort(permu);
int[] coord = loarr;
double coeff = 1.0;
double ret = 0.0;
for (int i=0; i<ndim(); i++) {
int j;
coeff -= permu[i].a;
ret += coeff*realVal(coord);
coeff = permu[i].a;
j = permu[i].i;
coord[j] = hiarr[j];
}
ret += coeff*realVal(coord);
return ret;
}
// sum over entire range
public double sum() {
double tot = 0;
for (int i=0; i<nsamples; i++) {
if (! Double.isNaN(samples[i]))
tot += samples[i];
}
return tot;
}
// 1D sum over restricted range
public double sum(double xmin, double xmax) throws Xcept {
if (ndim() != 1) throw new Xcept(
"sum(min,max) supports only 1D data: " + this);
GridData xgrid = grid(0);
double tot = 0;
for (int i=0; i<nsamples; i++) {
double x = xgrid.realVal(i);
if (x < xmin || x > xmax) continue;
double s = samples[i];
if (! Double.isNaN(s))
tot += s;
}
return tot;
}
// integral (RegularGridData only, for now)
public double integral() throws Xcept {
double tot = 0;
for (int i=0; i<nsamples; i++) {
int[] gpos = gridPos(i);
int wgt = 1;
for (int j=0; j<ndim(); j++) {
if (gpos[j] == 0) continue;
if (gpos[j] == grid(j).ct()-1) continue;
wgt *= 2;
}
tot += realVal(i)*wgt;
}
for (int i=0; i<ndim(); i++) {
if (! (grid(i) instanceof RegularGridData))
throw new Xcept(this,
"integral() currently supports only equal-spaced grids");
double xdelta = ((RegularGridData) grid(i)).delta();
tot *= (xdelta/2);
}
return tot;
}
// 1D integral over restricted range
public double integral(double xmin, double xmax) throws Xcept {
if (ndim() != 1) throw new Xcept(
"integral(min,max) supports only 1D data: " + this);
if (! (grid(0) instanceof RegularGridData)) throw new Xcept(
"integral(min,max) supports only regular grids: " + this);
RegularGridData xgrid = (RegularGridData) grid(0);
double delta2 = xgrid.delta() / 2;
if (xgrid.min() > xmin) xmin = xgrid.min();
if (xgrid.max() < xmax) xmax = xgrid.max();
double tot = 0;
for (int i=0; i<nsamples; i++) {
double s = samples[i];
if (Double.isNaN(s)) continue;
double x = xgrid.realVal(i);
double xlo = Math.max(xmin, x - delta2);
double xhi = Math.min(xmax, x + delta2);
if (xhi <= xlo) continue;
tot += s * (xhi - xlo);
}
return tot;
}
// serializable info
public static class Info extends DataInfo {
public DataInfo[] grids;
public double[] samples;
// constructors
public Info() { }
public Info(RealNData data, Subset sset) throws Xcept {
super(data);
int n = data.ndim();
if (n>0) {
grids = new DataInfo[n];
for (int i=0; i<n; i++)
grids[i] = data.grid(i).info();
}
samples = data.samples(sset);
subset = sset;
}
}
// test program
public static void main(String[] args) throws Exception{
int ndim = args.length/2;
GridData[] grids = new GridData[ndim];
int[] gpos = new int[ndim];
for (int i=0; i<ndim; i++) {
grids[i] = new RegularGridData("x", null,
0.0, 1.1, Util.toInt(args[i]));
gpos[i] = Util.toInt(args[i+ndim]);
}
RealNData data = new RealNData("u", null, grids);
int inx = data.inx(gpos);
int[] gpos1 = data.gridPos(inx);
System.out.print("" + inx);
for (int i=0; i<gpos1.length; i++)
System.out.print(" " + gpos1[i]);
System.out.println("");
}
// Auxiliary class for permuting sort
static class IntDoub implements Comparable {
public double a;
public int i;
public int compareTo(Object o)
{
return Double.compare(((IntDoub) o).a,a);
}
}
}
|
200193_11 | /*
* @author Holger Vogelsang
*/
package de.hska.iwii.gui.drawing;
import java.util.EventListener;
import javafx.scene.Node;
/**
* Ein konkreter Beobachter der Zeichenereignisse muss diese
* Schnittstelle implementieren.
* @author H. Vogelsang
*/
public interface DrawingListener extends EventListener {
/**
* Reaktion auf einen Mausklick in die Zeichenflaeche. Dabei wird eine neue
* Figur erzeugt.
* @param figureType Zu erzeugende Figur:
* <ul>
* <li><code>"circle"</code> Es soll ein neuer Kreis erzeugt werden.
* <li><code>"rect"</code> Es soll ein neues Rechteck erzeugt werden.
* <li><code>"line"</code> Es soll eine neue Linie erzeugt werden.
* </ul>
* @param xPos X-Position des Mauszeigers waehrend des Klicks.
* @param yPos y-Position des Mauszeigers waehrend des Klicks.
*/
void startCreateFigure(String figureType, double xPos, double yPos);
/**
* Die Figur an der mit <code>pos</code> gekennzeichneten Stelle
* soll verschoben werden.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers waehrend des Klicks.
* @param yPos y-Position des Mauszeigers waehrend des Klicks.
*/
void startMoveFigure(Node node, double xPos, double yPos);
/**
* Der Mauszeiger wird mit gedrueckter Maustaste ueber die
* Zeichenflaeche bewegt. Dabei wird die neu mit
* <code>startCreateFigure</code> erzeugte Figur in der Groesse
* veraendert.
* @param xPos X-Position des Mauszeigers waehrend des Verschiebens.
* @param yPos y-Position des Mauszeigers waehrend des Verschiebens.
*/
void workCreateFigure(double xPos, double yPos);
/**
* Der Mauszeiger wird mit gedrueckter Maustaste ueber die
* Zeichenflaeche bewegt. Dabei wird eine mit
* <code>startMoveFigure</code> gewaehlte Figur verschoben.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers waehrend des Verschiebens.
* @param yPos y-Position des Mauszeigers waehrend des Verschiebens.
*/
void workMoveFigure(Node node, double xPos, double yPos);
/**
* Der Mauszeiger wird wieder losgelassen. Das Erzeugen
* der Figur ist somit beendet.
* @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste.
* @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste.
*/
void endCreateFigure(double xPos, double yPos);
/**
* Der Mauszeiger wird wieder losgelassen. Das Verschieben
* der Figur ist somit beendet.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste.
* @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste.
*/
void endMoveFigure(Node node, double xPos, double yPos);
/**
* Selektionsereignis: Die Maustaste wurde auf einer Figur
* gedrueckt und wieder losgelassen.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers waehrend des Klicks.
* @param yPos y-Position des Mauszeigers waehrend des Klicks.
* @param shiftPressed <code>true</code>: Die Shift-Taste wurde waehrend des
* Mausklicks gedrueckt.
*/
void selectFigure(Node node, double xPos, double yPos, boolean shiftPressed);
/**
* Gestenereignis: Figur soll gedreht werden.
* @param node Zu drehende Figure.
* @param angle Winkel, um den die Figur weitergedreht werden soll.
*/
void rotate(Node node, double angle);
/**
* Gestenereignis: Figur soll verschoben werden.
* @param node Zu verschiebende Figure.
* @param deltaX Abstand in x-Richtung, um den die Figur weitergeschoben werden soll.
* @param deltaY Abstand in y-Richtung, um den die Figur weitergeschoben werden soll.
*/
void translate(Node node, double deltaX, double deltaY);
/**
* Gestenereignis: Groesse der Figur soll veraendert werden.
* @param node Zu verandernde Figure.
* @param zoomFactor Faktor, um den die Figur vergroessert oder verkleinert werden soll.
*/
void zoom(Node node, double zoomFactor);
/**
* Aufforderung zum Loeschen der selektierten Figur.
*/
void deleteFigures();
/**
* Aufforderung zum Kopieren der selektierten Figuren.
*/
void copyFigures();
/**
* Aufforderung zum Einfuegen einer kopierten Figuren.
*/
void pasteFigures();
/**
* Selektierte Figuren in die oberste Ebene verschieben.
*/
void moveSelectedFiguresToTop();
/**
* Selektierte Figuren in die unterste Ebene verschieben.
*/
void moveSelectedFiguresToBottom();
/**
* Selektierte Figuren eine Ebene nach unten verschieben.
*/
void moveSelectedFiguresDown();
/**
* Selektierte Figuren um eine Ebene nach oben verschieben.
*/
void moveSelectedFiguresUp();
/**
* Alle selektierten Figuren zu einer Gruppe zusammenfassen.
*/
void groupFigures();
/**
* Alle selektierten Gruppen aufloesen.
*/
void ungroupFigures();
/**
* Anzahl selektierter Figuren ermitteln.
* @return Anzahl selektierter Figuren.
*/
int getSelectedFiguresCount();
/**
* Anzahl Figuren im Clipboard ermitteln.
* @return Anzahl Figuren im Clipboard.
*/
int getFiguresInClipboardCount();
/**
* Ist eine Gruppe momentan selektiert?
* @return <code>true</code> Ja, es ist mindestens eine Gruppe selektiert.
*/
boolean isGroupSelected();
}
| Nad707/Zeichenprogramm | src/de/hska/iwii/gui/drawing/DrawingListener.java | 1,812 | /**
* Gestenereignis: Groesse der Figur soll veraendert werden.
* @param node Zu verandernde Figure.
* @param zoomFactor Faktor, um den die Figur vergroessert oder verkleinert werden soll.
*/ | block_comment | nl | /*
* @author Holger Vogelsang
*/
package de.hska.iwii.gui.drawing;
import java.util.EventListener;
import javafx.scene.Node;
/**
* Ein konkreter Beobachter der Zeichenereignisse muss diese
* Schnittstelle implementieren.
* @author H. Vogelsang
*/
public interface DrawingListener extends EventListener {
/**
* Reaktion auf einen Mausklick in die Zeichenflaeche. Dabei wird eine neue
* Figur erzeugt.
* @param figureType Zu erzeugende Figur:
* <ul>
* <li><code>"circle"</code> Es soll ein neuer Kreis erzeugt werden.
* <li><code>"rect"</code> Es soll ein neues Rechteck erzeugt werden.
* <li><code>"line"</code> Es soll eine neue Linie erzeugt werden.
* </ul>
* @param xPos X-Position des Mauszeigers waehrend des Klicks.
* @param yPos y-Position des Mauszeigers waehrend des Klicks.
*/
void startCreateFigure(String figureType, double xPos, double yPos);
/**
* Die Figur an der mit <code>pos</code> gekennzeichneten Stelle
* soll verschoben werden.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers waehrend des Klicks.
* @param yPos y-Position des Mauszeigers waehrend des Klicks.
*/
void startMoveFigure(Node node, double xPos, double yPos);
/**
* Der Mauszeiger wird mit gedrueckter Maustaste ueber die
* Zeichenflaeche bewegt. Dabei wird die neu mit
* <code>startCreateFigure</code> erzeugte Figur in der Groesse
* veraendert.
* @param xPos X-Position des Mauszeigers waehrend des Verschiebens.
* @param yPos y-Position des Mauszeigers waehrend des Verschiebens.
*/
void workCreateFigure(double xPos, double yPos);
/**
* Der Mauszeiger wird mit gedrueckter Maustaste ueber die
* Zeichenflaeche bewegt. Dabei wird eine mit
* <code>startMoveFigure</code> gewaehlte Figur verschoben.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers waehrend des Verschiebens.
* @param yPos y-Position des Mauszeigers waehrend des Verschiebens.
*/
void workMoveFigure(Node node, double xPos, double yPos);
/**
* Der Mauszeiger wird wieder losgelassen. Das Erzeugen
* der Figur ist somit beendet.
* @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste.
* @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste.
*/
void endCreateFigure(double xPos, double yPos);
/**
* Der Mauszeiger wird wieder losgelassen. Das Verschieben
* der Figur ist somit beendet.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste.
* @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste.
*/
void endMoveFigure(Node node, double xPos, double yPos);
/**
* Selektionsereignis: Die Maustaste wurde auf einer Figur
* gedrueckt und wieder losgelassen.
* @param node Zu verschiebende Figure.
* @param xPos X-Position des Mauszeigers waehrend des Klicks.
* @param yPos y-Position des Mauszeigers waehrend des Klicks.
* @param shiftPressed <code>true</code>: Die Shift-Taste wurde waehrend des
* Mausklicks gedrueckt.
*/
void selectFigure(Node node, double xPos, double yPos, boolean shiftPressed);
/**
* Gestenereignis: Figur soll gedreht werden.
* @param node Zu drehende Figure.
* @param angle Winkel, um den die Figur weitergedreht werden soll.
*/
void rotate(Node node, double angle);
/**
* Gestenereignis: Figur soll verschoben werden.
* @param node Zu verschiebende Figure.
* @param deltaX Abstand in x-Richtung, um den die Figur weitergeschoben werden soll.
* @param deltaY Abstand in y-Richtung, um den die Figur weitergeschoben werden soll.
*/
void translate(Node node, double deltaX, double deltaY);
/**
* Gestenereignis: Groesse der<SUF>*/
void zoom(Node node, double zoomFactor);
/**
* Aufforderung zum Loeschen der selektierten Figur.
*/
void deleteFigures();
/**
* Aufforderung zum Kopieren der selektierten Figuren.
*/
void copyFigures();
/**
* Aufforderung zum Einfuegen einer kopierten Figuren.
*/
void pasteFigures();
/**
* Selektierte Figuren in die oberste Ebene verschieben.
*/
void moveSelectedFiguresToTop();
/**
* Selektierte Figuren in die unterste Ebene verschieben.
*/
void moveSelectedFiguresToBottom();
/**
* Selektierte Figuren eine Ebene nach unten verschieben.
*/
void moveSelectedFiguresDown();
/**
* Selektierte Figuren um eine Ebene nach oben verschieben.
*/
void moveSelectedFiguresUp();
/**
* Alle selektierten Figuren zu einer Gruppe zusammenfassen.
*/
void groupFigures();
/**
* Alle selektierten Gruppen aufloesen.
*/
void ungroupFigures();
/**
* Anzahl selektierter Figuren ermitteln.
* @return Anzahl selektierter Figuren.
*/
int getSelectedFiguresCount();
/**
* Anzahl Figuren im Clipboard ermitteln.
* @return Anzahl Figuren im Clipboard.
*/
int getFiguresInClipboardCount();
/**
* Ist eine Gruppe momentan selektiert?
* @return <code>true</code> Ja, es ist mindestens eine Gruppe selektiert.
*/
boolean isGroupSelected();
}
|
100944_3 | package nl.huiges.blipapi;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.os.Bundle;
import com.huiges.AndroBlip.R;
import nl.huiges.apicaller.APICaller;
/**
* Wrapper class to communicate with the blipfoto api.
* Combines all API calls as static functions.
* It might need some splitting in the end.
*
* Results get their own DAO-like objects (WAO: Web Access Objects)
* These objects are probably going to go grow in time, so sorry about that as well..
*
* Uses separate 'apicaller' for HTTP connection.
*
* This all should probably be a separate library?
*
* @author Nanne Huiges
* @see APICaller
* @version 0.1.1
*/
public class BlipAPI {
public static final String VIEW_ALL = "everything";
public static final String VIEW_SPOT = "spotlight";
public static final String VIEW_RATED = "rated";
public static final String VIEW_RAND = "random";
public static final String VIEW_SUBS = "subscribed";
public static final String VIEW_ME = "me";
public static final String VIEW_FAV = "favourites";
public static final String VIEW_MYFAV = "myfavourites";
public static final int SIZE_SMALL = 0;
public static final int SIZE_BIG = 1;
public static final int THUMB_COLOR = 0;
public static final int THUMB_GREY = 1;
public static final String server = "api.blipfoto.com";
/**
* API code (iApiResultReceiver) makes the result
* go straight to the receiver's signal function
*
* This is unfortunate as we want to parse it first
* and have the parsing be done by this object.
*
* Quick fix was below static function
* @todo call receivers signal function with parsed bundle
*
* @param extras result bundle as received from API call
* @return parsed bundle
*/
public static Bundle parseResult(Bundle extras, Resources res){
String resultS = extras.getString(APICaller.RESULT);
JSONObject entryO=null;
Bundle result = new Bundle();
try {
entryO = new JSONObject(resultS);
// } catch (JSONException | NullPointerException e1) { java 7 says hi
} catch (JSONException e1) {
result.putBoolean("error", true);
result.putString("resultText",res.getString(R.string.error_upload_unknown));
return result;
} catch ( NullPointerException e1) {
result.putBoolean("error", true);
result.putString("resultText",res.getString(R.string.error_upload_network));
return result;
}
String resultText = "";
boolean error = false;
if(entryO != null){
JSONObject jso = null;
try {
jso = (JSONObject) entryO.getJSONObject("error");
} catch (JSONException e1) {}
if (jso != null){
try {
resultText = jso.getString("message");
} catch (JSONException e) {
resultText = res.getString(R.string.error_blipfoto_empty);
}
result.putBoolean("error", true);
result.putString("resultText",resultText);
return result;
}else{
//geen error. hopelijk wel data dan.
try {
JSONObject data = (JSONObject) entryO.getJSONObject("data");
resultText = data.getString("message");
} catch (JSONException e) {
error = true;
resultText = res.getString(R.string.error_blipfoto_unsure);
}
}
}
result.putBoolean("error", error);
result.putString("resultText",resultText);
return result;
}
}
| NanneHuiges/androblip | src/nl/huiges/blipapi/BlipAPI.java | 1,090 | //geen error. hopelijk wel data dan. | line_comment | nl | package nl.huiges.blipapi;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.os.Bundle;
import com.huiges.AndroBlip.R;
import nl.huiges.apicaller.APICaller;
/**
* Wrapper class to communicate with the blipfoto api.
* Combines all API calls as static functions.
* It might need some splitting in the end.
*
* Results get their own DAO-like objects (WAO: Web Access Objects)
* These objects are probably going to go grow in time, so sorry about that as well..
*
* Uses separate 'apicaller' for HTTP connection.
*
* This all should probably be a separate library?
*
* @author Nanne Huiges
* @see APICaller
* @version 0.1.1
*/
public class BlipAPI {
public static final String VIEW_ALL = "everything";
public static final String VIEW_SPOT = "spotlight";
public static final String VIEW_RATED = "rated";
public static final String VIEW_RAND = "random";
public static final String VIEW_SUBS = "subscribed";
public static final String VIEW_ME = "me";
public static final String VIEW_FAV = "favourites";
public static final String VIEW_MYFAV = "myfavourites";
public static final int SIZE_SMALL = 0;
public static final int SIZE_BIG = 1;
public static final int THUMB_COLOR = 0;
public static final int THUMB_GREY = 1;
public static final String server = "api.blipfoto.com";
/**
* API code (iApiResultReceiver) makes the result
* go straight to the receiver's signal function
*
* This is unfortunate as we want to parse it first
* and have the parsing be done by this object.
*
* Quick fix was below static function
* @todo call receivers signal function with parsed bundle
*
* @param extras result bundle as received from API call
* @return parsed bundle
*/
public static Bundle parseResult(Bundle extras, Resources res){
String resultS = extras.getString(APICaller.RESULT);
JSONObject entryO=null;
Bundle result = new Bundle();
try {
entryO = new JSONObject(resultS);
// } catch (JSONException | NullPointerException e1) { java 7 says hi
} catch (JSONException e1) {
result.putBoolean("error", true);
result.putString("resultText",res.getString(R.string.error_upload_unknown));
return result;
} catch ( NullPointerException e1) {
result.putBoolean("error", true);
result.putString("resultText",res.getString(R.string.error_upload_network));
return result;
}
String resultText = "";
boolean error = false;
if(entryO != null){
JSONObject jso = null;
try {
jso = (JSONObject) entryO.getJSONObject("error");
} catch (JSONException e1) {}
if (jso != null){
try {
resultText = jso.getString("message");
} catch (JSONException e) {
resultText = res.getString(R.string.error_blipfoto_empty);
}
result.putBoolean("error", true);
result.putString("resultText",resultText);
return result;
}else{
//geen error.<SUF>
try {
JSONObject data = (JSONObject) entryO.getJSONObject("data");
resultText = data.getString("message");
} catch (JSONException e) {
error = true;
resultText = res.getString(R.string.error_blipfoto_unsure);
}
}
}
result.putBoolean("error", error);
result.putString("resultText",resultText);
return result;
}
}
|
191011_0 | package com.example.backen_kleding_bieb.controller;
import com.example.backen_kleding_bieb.dto.AuthenticationRequest;
import com.example.backen_kleding_bieb.dto.AuthenticationResponse;
import com.example.backen_kleding_bieb.service.CustomUserDetailsService;
import com.example.backen_kleding_bieb.utils.JwtUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@CrossOrigin
@RestController
public class AuthenticationController {
private final AuthenticationManager authenticationManager;
private final CustomUserDetailsService userDetailsService;
private final JwtUtil jwtUtl;
public AuthenticationController(AuthenticationManager authenticationManager, CustomUserDetailsService userDetailsService, JwtUtil jwtUtl) {
this.authenticationManager = authenticationManager;
this.userDetailsService = userDetailsService;
this.jwtUtl = jwtUtl;
}
@GetMapping(value = "/authenticated")
public ResponseEntity<Object> authenticated(Authentication authentication, Principal principal) {
return ResponseEntity.ok().body(principal);
}
/*
Deze methode geeft het JWT token terug wanneer de gebruiker de juiste inloggegevens op geeft.
*/
@PostMapping(value = "/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
throws Exception {
String username = authenticationRequest.getUsername();
String password = authenticationRequest.getPassword();
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password)
);
}
catch (BadCredentialsException ex) {
throw new Exception("Incorrect username or password", ex);
}
final UserDetails userDetails = userDetailsService
.loadUserByUsername(username);
final String jwt = jwtUtl.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(jwt));
}
} | Nastyplayer/Backend_kleding_bieb | src/main/java/com/example/backen_kleding_bieb/controller/AuthenticationController.java | 611 | /*
Deze methode geeft het JWT token terug wanneer de gebruiker de juiste inloggegevens op geeft.
*/ | block_comment | nl | package com.example.backen_kleding_bieb.controller;
import com.example.backen_kleding_bieb.dto.AuthenticationRequest;
import com.example.backen_kleding_bieb.dto.AuthenticationResponse;
import com.example.backen_kleding_bieb.service.CustomUserDetailsService;
import com.example.backen_kleding_bieb.utils.JwtUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@CrossOrigin
@RestController
public class AuthenticationController {
private final AuthenticationManager authenticationManager;
private final CustomUserDetailsService userDetailsService;
private final JwtUtil jwtUtl;
public AuthenticationController(AuthenticationManager authenticationManager, CustomUserDetailsService userDetailsService, JwtUtil jwtUtl) {
this.authenticationManager = authenticationManager;
this.userDetailsService = userDetailsService;
this.jwtUtl = jwtUtl;
}
@GetMapping(value = "/authenticated")
public ResponseEntity<Object> authenticated(Authentication authentication, Principal principal) {
return ResponseEntity.ok().body(principal);
}
/*
Deze methode geeft<SUF>*/
@PostMapping(value = "/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
throws Exception {
String username = authenticationRequest.getUsername();
String password = authenticationRequest.getPassword();
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password)
);
}
catch (BadCredentialsException ex) {
throw new Exception("Incorrect username or password", ex);
}
final UserDetails userDetails = userDetailsService
.loadUserByUsername(username);
final String jwt = jwtUtl.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(jwt));
}
} |
116399_4 | /* ###
* IP: GHIDRA
*
* 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 db;
import java.io.IOException;
import db.buffers.DataBuffer;
/**
* <code>LongField</code> provides a wrapper for 8-byte signed long data
* which is read or written to a Record.
*/
public final class LongField extends PrimitiveField {
/**
* Minimum long field value
*/
public static final LongField MIN_VALUE = new LongField(Long.MIN_VALUE, true);
/**
* Maximum long field value
*/
public static final LongField MAX_VALUE = new LongField(Long.MAX_VALUE, true);
/**
* Zero long field value
*/
public static final LongField ZERO_VALUE = new LongField(0, true);
/**
* Instance intended for defining a {@link Table} {@link Schema}
*/
public static final LongField INSTANCE = ZERO_VALUE;
private long value;
/**
* Construct a long field with an initial value of 0.
*/
public LongField() {
}
/**
* Construct a long field with an initial value of l.
* @param l initial value
*/
public LongField(long l) {
this(l, false);
}
/**
* Construct a long field with an initial value of l.
* @param l initial value
* @param immutable true if field value is immutable
*/
LongField(long l, boolean immutable) {
super(immutable);
value = l;
}
@Override
void setNull() {
super.setNull();
value = 0;
}
@Override
public long getLongValue() {
return value;
}
@Override
public void setLongValue(long value) {
updatingPrimitiveValue();
this.value = value;
}
@Override
int length() {
return 8;
}
@Override
int write(Buffer buf, int offset) throws IndexOutOfBoundsException, IOException {
return buf.putLong(offset, value);
}
@Override
int read(Buffer buf, int offset) throws IndexOutOfBoundsException, IOException {
updatingPrimitiveValue();
value = buf.getLong(offset);
return offset + 8;
}
@Override
int readLength(Buffer buf, int offset) {
return 8;
}
@Override
byte getFieldType() {
return LONG_TYPE;
}
@Override
public String getValueAsString() {
return "0x" + Long.toHexString(value);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LongField)) {
return false;
}
return ((LongField) obj).value == value;
}
@Override
public int compareTo(Field o) {
if (!(o instanceof LongField)) {
throw new UnsupportedOperationException("may only compare similar Field types");
}
LongField f = (LongField) o;
if (value == f.value) {
return 0;
}
else if (value < f.value) {
return -1;
}
return 1;
}
@Override
int compareTo(DataBuffer buffer, int offset) {
long otherValue = buffer.getLong(offset);
if (value == otherValue) {
return 0;
}
else if (value < otherValue) {
return -1;
}
return 1;
}
@Override
public LongField copyField() {
if (isNull()) {
LongField copy = new LongField();
copy.setNull();
return copy;
}
return new LongField(getLongValue());
}
@Override
public LongField newField() {
return new LongField();
}
@Override
public byte[] getBinaryData() {
return new byte[] { (byte) (value >> 56), (byte) (value >> 48), (byte) (value >> 40),
(byte) (value >> 32), (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8),
(byte) value };
}
@Override
public void setBinaryData(byte[] bytes) {
if (bytes == null) {
setNull();
return;
}
if (bytes.length != 8) {
throw new IllegalFieldAccessException();
}
updatingPrimitiveValue();
value = (((long) bytes[0] & 0xff) << 56) | (((long) bytes[1] & 0xff) << 48) |
(((long) bytes[2] & 0xff) << 40) | (((long) bytes[3] & 0xff) << 32) |
(((long) bytes[4] & 0xff) << 24) | (((long) bytes[5] & 0xff) << 16) |
(((long) bytes[6] & 0xff) << 8) | ((long) bytes[7] & 0xff);
}
@Override
public int hashCode() {
return (int) (value ^ (value >>> 32));
}
@Override
LongField getMinValue() {
return MIN_VALUE;
}
@Override
LongField getMaxValue() {
return MAX_VALUE;
}
}
| NationalSecurityAgency/ghidra | Ghidra/Framework/DB/src/main/java/db/LongField.java | 1,530 | /**
* Zero long field value
*/ | block_comment | nl | /* ###
* IP: GHIDRA
*
* 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 db;
import java.io.IOException;
import db.buffers.DataBuffer;
/**
* <code>LongField</code> provides a wrapper for 8-byte signed long data
* which is read or written to a Record.
*/
public final class LongField extends PrimitiveField {
/**
* Minimum long field value
*/
public static final LongField MIN_VALUE = new LongField(Long.MIN_VALUE, true);
/**
* Maximum long field value
*/
public static final LongField MAX_VALUE = new LongField(Long.MAX_VALUE, true);
/**
* Zero long field<SUF>*/
public static final LongField ZERO_VALUE = new LongField(0, true);
/**
* Instance intended for defining a {@link Table} {@link Schema}
*/
public static final LongField INSTANCE = ZERO_VALUE;
private long value;
/**
* Construct a long field with an initial value of 0.
*/
public LongField() {
}
/**
* Construct a long field with an initial value of l.
* @param l initial value
*/
public LongField(long l) {
this(l, false);
}
/**
* Construct a long field with an initial value of l.
* @param l initial value
* @param immutable true if field value is immutable
*/
LongField(long l, boolean immutable) {
super(immutable);
value = l;
}
@Override
void setNull() {
super.setNull();
value = 0;
}
@Override
public long getLongValue() {
return value;
}
@Override
public void setLongValue(long value) {
updatingPrimitiveValue();
this.value = value;
}
@Override
int length() {
return 8;
}
@Override
int write(Buffer buf, int offset) throws IndexOutOfBoundsException, IOException {
return buf.putLong(offset, value);
}
@Override
int read(Buffer buf, int offset) throws IndexOutOfBoundsException, IOException {
updatingPrimitiveValue();
value = buf.getLong(offset);
return offset + 8;
}
@Override
int readLength(Buffer buf, int offset) {
return 8;
}
@Override
byte getFieldType() {
return LONG_TYPE;
}
@Override
public String getValueAsString() {
return "0x" + Long.toHexString(value);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LongField)) {
return false;
}
return ((LongField) obj).value == value;
}
@Override
public int compareTo(Field o) {
if (!(o instanceof LongField)) {
throw new UnsupportedOperationException("may only compare similar Field types");
}
LongField f = (LongField) o;
if (value == f.value) {
return 0;
}
else if (value < f.value) {
return -1;
}
return 1;
}
@Override
int compareTo(DataBuffer buffer, int offset) {
long otherValue = buffer.getLong(offset);
if (value == otherValue) {
return 0;
}
else if (value < otherValue) {
return -1;
}
return 1;
}
@Override
public LongField copyField() {
if (isNull()) {
LongField copy = new LongField();
copy.setNull();
return copy;
}
return new LongField(getLongValue());
}
@Override
public LongField newField() {
return new LongField();
}
@Override
public byte[] getBinaryData() {
return new byte[] { (byte) (value >> 56), (byte) (value >> 48), (byte) (value >> 40),
(byte) (value >> 32), (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8),
(byte) value };
}
@Override
public void setBinaryData(byte[] bytes) {
if (bytes == null) {
setNull();
return;
}
if (bytes.length != 8) {
throw new IllegalFieldAccessException();
}
updatingPrimitiveValue();
value = (((long) bytes[0] & 0xff) << 56) | (((long) bytes[1] & 0xff) << 48) |
(((long) bytes[2] & 0xff) << 40) | (((long) bytes[3] & 0xff) << 32) |
(((long) bytes[4] & 0xff) << 24) | (((long) bytes[5] & 0xff) << 16) |
(((long) bytes[6] & 0xff) << 8) | ((long) bytes[7] & 0xff);
}
@Override
public int hashCode() {
return (int) (value ^ (value >>> 32));
}
@Override
LongField getMinValue() {
return MIN_VALUE;
}
@Override
LongField getMaxValue() {
return MAX_VALUE;
}
}
|
78060_70 | //
// Copyright (c) 2017-present, ViroMedia, Inc.
// All rights reserved.
//
// 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.
/*
* Java JNI wrapper for linking the following classes across the bridge:
*
* Android Java Object : com.viromedia.bridge.viewgroups.Scene.java
* Java JNI Wrapper : com.viro.core.Scene.java
* Cpp JNI wrapper : Scene_JNI.cpp
* Cpp Object : VROScene.cpp
*/
package com.viro.core;
import android.graphics.Bitmap;
import android.net.Uri;
import java.util.HashMap;
import java.util.Map;
/**
* Scene represents a scene graph - a hierarchy of {@link Node}s that together represent the 3D
* world. UI controls, 3D objects, lights, camera, and more are attached to the Nodes to build the
* displayable 3D scene. To display a Scene in an Android View, use {@link ViroView}.
* <p>
* For an extended discussion of Viro's scene graph, refer to the <a
* href="https://virocore.viromedia.com/docs/scenes">Scene Guide</a>.
*/
public class Scene {
/**
* AudioMaterial is used to define the Scene's reverb effects. These are used in conjunction
* with {@link #setSoundRoom(ViroContext, Vector, AudioMaterial, AudioMaterial, AudioMaterial)}.
* In general, harder surface materials are more reverberant than rooms made of soft, absorbent
* materials.
*/
public enum AudioMaterial {
/**
* Transparent, no reverb.
*/
TRANSPARENT("transparent"),
/**
* Acoustic ceiling tiles.
*/
ACOUSTIC_CEILING_TILES("acoustic_ceiling_tiles"),
/**
* Brick, bare.
*/
BRICK_BARE("brick_bare"),
/**
* Painted brick.
*/
BRICK_PAINTED("brick_painted"),
/**
* Coarse concrete.
*/
CONCRETE_BLOCK_COARSE("concrete_block_coarse"),
/**
* Painted concrete.
*/
CONCRETE_BLOCK_PAINTED("concrete_block_painted"),
/**
* Heavy curtain.
*/
CURTAIN_HEAVY("curtain_heavy"),
/**
* Fiber glass.
*/
FIBER_GLASS_INSULATION("fiber_glass_insulation"),
/**
* Thin glass.
*/
GLASS_THIN("glass_thin"),
/**
* Thick glass.
*/
GLASS_THICK("glass_thick"),
/**
* Grass.
*/
GRASS("grass"),
/**
* Linoleum on concrete.
*/
LINOLEUM_ON_CONCRETE("linoleum_on_concrete"),
/**
* Marble.
*/
MARBLE("marble"),
/**
* Metal.
*/
METAL("metal"),
/**
* Parquet on concrete.
*/
PARQUET_ON_CONRETE("parquet_on_concrete"),
/**
* Rough plaster.
*/
PLASTER_ROUGH("plaster_rough"),
/**
* Smooth plaster.
*/
PLASTER_SMOOTH("plaster_smooth"),
/**
* Plywood panel.
*/
PLYWOOD_PANEL("plywood_panel"),
/**
* Polished concrete or tile.
*/
POLISHED_CONCRETE_OR_TILE("polished_concrete_or_tile"),
/**
* Sheet rock.
*/
SHEET_ROCK("sheet_rock"),
/**
* Water or ice.
*/
WATER_OR_ICE_SURFACE("water_or_ice_surface"),
/**
* Wood ceiling.
*/
WOOD_CEILING("wood_ceiling"),
/**
* Wood panel.
*/
WOOD_PANEL("wood_panel");
private String mStringValue;
private AudioMaterial(String value) {
this.mStringValue = value;
}
/**
* @hide
* @return
*/
public String getStringValue() {
return mStringValue;
}
private static Map<String, AudioMaterial> map = new HashMap<String, AudioMaterial>();
static {
for (AudioMaterial value : AudioMaterial.values()) {
map.put(value.getStringValue().toLowerCase(), value);
}
}
/**
* @hide
* @return
*/
public static AudioMaterial valueFromString(String str) {
return map.get(str.toLowerCase());
}
};
protected long mNativeRef;
protected long mNativeDelegateRef;
private Node mRootNode;
private PhysicsWorld mPhysicsWorld;
private Texture mLightingEnvironment;
private Texture mBackgroundTexture;
private VisibilityListener mListener = null;
/**
* Construct a new Scene.
*/
public Scene() {
setSceneRef(createNativeScene());
}
/**
* Subclass constructor, does not set the scene-ref.
*
* @hide
*/
Scene(boolean dummy) {
}
/**
* @hide
* @return
*/
protected long createNativeScene() {
return nativeCreateSceneController();
}
/**
* After-construction method when the sceneRef is known. Initializes
* the rest of the Scene.
*
* @hide
*/
protected void setSceneRef(long sceneRef) {
mNativeRef = sceneRef;
mNativeDelegateRef = nativeCreateSceneControllerDelegate(mNativeRef);
PortalScene root = new PortalScene(false);
root.initWithNativeRef(nativeGetSceneNodeRef(mNativeRef));
root.attachDelegate();
mRootNode = root;
mPhysicsWorld = new PhysicsWorld(this);
}
@Override
protected void finalize() throws Throwable {
try {
dispose();
} finally {
super.finalize();
}
}
/**
* Release native resources associated with this Scene.
*/
public void dispose() {
if (mNativeRef != 0) {
nativeDestroySceneController(mNativeRef);
mNativeRef = 0;
}
if (mNativeDelegateRef != 0) {
nativeDestroySceneControllerDelegate(mNativeDelegateRef);
mNativeDelegateRef = 0;
}
if (mBackgroundTexture != null) {
mBackgroundTexture.dispose();
mBackgroundTexture = null;
}
}
/**
* Retrieve the root {@link Node} of the scene graph.
*
* @return The root node.
*/
public Node getRootNode() {
return mRootNode;
}
/**
* Get the physics simulation for the Scene.
*
* @return The {@link PhysicsWorld} for the Scene.
*/
public PhysicsWorld getPhysicsWorld() {
return mPhysicsWorld;
}
/**
* Set the background of this Scene to display the texture. The provided {@link Texture} should
* contain a spherical image or spherical video. The image or video will be rendered behind all other
* content.
*
* @param texture The {@link Texture} containing the image, or {@link VideoTexture} containing
* the video.
*/
public void setBackgroundTexture(Texture texture) {
mBackgroundTexture = texture;
nativeSetBackgroundTexture(mNativeRef, texture.mNativeRef);
}
/**
* Rotate the background image or video by the given radians about the X, Y, and Z axes.
*
* @param rotation {@link Vector} containing rotation about the X, Y, and Z axes.
*/
public void setBackgroundRotation(Vector rotation) {
nativeSetBackgroundRotation(mNativeRef, rotation.x, rotation.y, rotation.z);
}
/**
* Set the background of this Scene to display a cube-map. The provided {@link Texture} should
* wrap a cube-map image. The cube-map will be rendered behind all other content.
*
* @param cubeTexture The {@link Texture} containing the cube-map.
*/
public void setBackgroundCubeTexture(Texture cubeTexture) {
nativeSetBackgroundCubeImageTexture(mNativeRef, cubeTexture.mNativeRef);
}
/**
* Set the background of this Scene to display the given color. The color will be rendered
* behind all other content.
*
* @param color The {@link android.graphics.Color}'s int value.
*/
public void setBackgroundCubeWithColor(long color) {
nativeSetBackgroundCubeWithColor(mNativeRef, color);
}
/**
* Set the lighting environment to use for the Scene. The lighting environment is a {@link
* Texture} that acts as a global light source, illuminating surfaces with diffuse and specular
* ambient light. Each pixel in the lighting environment is treated as a light emitter, thereby
* capturing the environment's global lighting and general feel. This gives objects a sense of
* belonging to their environment. For this reason it is common to use the scene's background
* texture as the lighting environment, but this is not necessary.
* <p>
* This method expects an equirectangular texture. Radiance HDR textures (*.hdr) work best,
* and can be loaded with {@link Texture#loadRadianceHDRTexture(Uri)}.
*
* @param lightingEnvironment The equirectangular {@link Texture} to use as the lighting
* environment.
*/
public void setLightingEnvironment(Texture lightingEnvironment) {
mLightingEnvironment = lightingEnvironment;
long ref = lightingEnvironment == null ? 0 : lightingEnvironment.mNativeRef;
nativeSetLightingEnvironment(mNativeRef, ref);
}
/**
* Get the lighting environment used by this Scene. The lighting environment is a {@link
* Texture} that acts as a global light source, illuminating surfaces with diffuse and specular
* ambient light.
*
* @return The equirectangular {@link Texture} being used as the lighting environment.
*/
public Texture getLightingEnvironment() {
return mLightingEnvironment;
}
/**
* Set the sound room, which enables reverb effects for all {@link SpatialSound} in the Scene.
* The sound room is defined by three {@link AudioMaterial}s, each of which has unique
* absorption properties which differ with frequency. The room is also give a size in meters,
* which is centered around the user. Larger rooms are more reverberant than smaller rooms, and
* harder surface materials are more reverberant than rooms made of soft, absorbent materials.
*
* @param viroContext {@link ViroContext} is required to set the sound room.
* @param size The size of the room's X, Y, and Z dimensions in meters, as a {@link
* Vector}.
* @param wall The wall {@link AudioMaterial}.
* @param ceiling The ceiling {@link AudioMaterial}.
* @param floor The floor {@link AudioMaterial}.
*/
public void setSoundRoom(ViroContext viroContext, Vector size, AudioMaterial wall,
AudioMaterial ceiling, AudioMaterial floor) {
nativeSetSoundRoom(mNativeRef, viroContext.mNativeRef, size.x, size.y, size.z,
wall.getStringValue(), ceiling.getStringValue(), floor.getStringValue());
}
/**
* @hide
* @param effects
* @return
*/
//#IFDEF 'viro_react'
public boolean setEffects(String[] effects){
return nativeSetEffects(mNativeRef, effects);
}
//#ENDIF
/*
* Native Functions called into JNI
*/
private native long nativeCreateSceneController();
private native long nativeCreateSceneControllerDelegate(long sceneRef);
private native void nativeDestroySceneController(long sceneReference);
private native long nativeGetSceneNodeRef(long sceneRef);
private native void nativeSetBackgroundTexture(long sceneRef, long imageRef);
private native void nativeSetBackgroundCubeImageTexture(long sceneRef, long textureRef);
private native void nativeSetBackgroundCubeWithColor(long sceneRef, long color);
private native void nativeSetBackgroundRotation(long sceneRef, float radiansX, float radiansY,
float radiansZ);
private native void nativeSetLightingEnvironment(long sceneRef, long textureRef);
private native void nativeSetSoundRoom(long sceneRef, long renderContextRef, float sizeX,
float sizeY, float sizeZ, String wallMaterial,
String ceilingMaterial, String floorMaterial);
private native boolean nativeSetEffects(long sceneRef, String[] effects);
/**
* @hide
* @param sceneDelegateRef
*/
protected native void nativeDestroySceneControllerDelegate(long sceneDelegateRef);
/**
* Receives callbacks in response to a {@link Scene} appearing and disappearing.
*/
public interface VisibilityListener {
/**
* Callback invoked when a Scene is about to appear.
*/
void onSceneWillAppear();
/**
* Callback invoked immediately after a Scene has appeared (after the transition).
*/
void onSceneDidAppear();
/**
* Callback invoked when a Scene is about to disappear.
*/
void onSceneWillDisappear();
/**
* Callback invoked immediately after a Scene has disappeared (after the transition).
*/
void onSceneDidDisappear();
}
/**
* Set the given {@link VisibilityListener} to receive callbacks when the Scene's visibility
* status changes.
*/
public void setVisibilityListener(VisibilityListener listener) {
mListener = listener;
}
/*
Called by Native functions.
*/
/**
* @hide
*/
public void onSceneWillAppear() {
if (mListener != null) {
mListener.onSceneWillAppear();
}
}
/**
* @hide
*/
public void onSceneDidAppear() {
if (mListener != null) {
mListener.onSceneDidAppear();
}
}
/**
* @hide
*/
public void onSceneWillDisappear(){
if (mListener != null) {
mListener.onSceneWillDisappear();
}
}
/**
* @hide
*/
public void onSceneDidDisappear() {
if (mListener != null) {
mListener.onSceneDidDisappear();
}
}
/*
Native Viro Physics JNI Functions
*/
private native void nativeSetPhysicsWorldGravity(long sceneRef, float gravity[]);
private native void findCollisionsWithRayAsync(long sceneRef, float[] from, float[] to,
boolean closest, String tag,
PhysicsWorld.HitTestListener callback);
private native void findCollisionsWithShapeAsync(long sceneRef, float[] from, float[] to,
String shapeType, float[] params, String tag,
PhysicsWorld.HitTestListener callback);
private native void nativeSetPhysicsWorldDebugDraw(long sceneRef, boolean debugDraw);
/*
Invoked by PhysicsWorld
*/
/**
* @hide
* @param gravity
*/
void setPhysicsWorldGravity(float gravity[]){
nativeSetPhysicsWorldGravity(mNativeRef, gravity);
}
/**
* @hide
* @param debugDraw
*/
void setPhysicsDebugDraw(boolean debugDraw){
nativeSetPhysicsWorldDebugDraw(mNativeRef, debugDraw);
}
/**
* @hide
* @param fromPos
* @param toPos
* @param closest
* @param tag
* @param callback
*/
void findCollisionsWithRayAsync(float[] fromPos, float toPos[], boolean closest,
String tag, PhysicsWorld.HitTestListener callback){
findCollisionsWithRayAsync(mNativeRef, fromPos, toPos, closest, tag, callback);
}
/**
* @hide
* @param from
* @param to
* @param shapeType
* @param params
* @param tag
* @param callback
*/
void findCollisionsWithShapeAsync(float[] from, float[] to, String shapeType, float[] params,
String tag, PhysicsWorld.HitTestListener callback){
findCollisionsWithShapeAsync(mNativeRef, from,to, shapeType, params, tag, callback);
}
/**
* Creates a builder for building complex {@link Scene} objects.
*
* @return {@link SceneBuilder} object.
*/
public static SceneBuilder<? extends Scene, ? extends SceneBuilder> builder() {
return new SceneBuilder<>();
}
// +---------------------------------------------------------------------------+
// | SceneBuilder class for Scene
// +---------------------------------------------------------------------------+
/**
* SceneBuilder for creating {@link Scene} objects.
*/
public static class SceneBuilder<R extends Scene, B extends SceneBuilder<R, B>> {
private R scene;
/**
* Constructor for SceneBuilder class.
*/
public SceneBuilder() {
this.scene = (R) new Scene();
}
/**
* Refer to {@link Scene#setVisibilityListener(VisibilityListener)}.
*
* @return This builder.
*/
public SceneBuilder listener(VisibilityListener listener) {
this.scene.setVisibilityListener(listener);
return (B) this;
}
/**
* Refer to {@link Scene#setBackgroundTexture(Texture)}.
*
* @return This builder.
*/
public SceneBuilder backgroundTexture(Texture backgroundTexture) {
this.scene.setBackgroundTexture(backgroundTexture);
return (B) this;
}
/**
* Refer to {@link Scene#setBackgroundRotation(Vector)}.
*
* @return This builder.
*/
public SceneBuilder backgroundRotation(Vector backgroundRotation) {
this.scene.setBackgroundRotation(backgroundRotation);
return (B) this;
}
/**
* Refer to {@link Scene#setBackgroundCubeWithColor(long)}}.
*
* @return This builder.
*/
public SceneBuilder backgroundCubeWithColor(long backgroundCubeWithColor) {
this.scene.setBackgroundCubeWithColor(backgroundCubeWithColor);
return (B) this;
}
/**
* Refer to {@link Scene#setLightingEnvironment(Texture)}.
*
* @return This builder.
*/
public SceneBuilder lightingEnvironment(Texture lightingEnvironment) {
this.scene.setLightingEnvironment(lightingEnvironment);;
return (B) this;
}
/**
* Refer to {@link Scene#setSoundRoom(ViroContext, Vector, AudioMaterial, AudioMaterial, AudioMaterial)}.
*
* @return This builder.
*/
public SceneBuilder soundRoom(ViroContext viroContext, Vector size, AudioMaterial wall,
AudioMaterial ceiling, AudioMaterial floor) {
this.scene.setSoundRoom(viroContext,size, wall, ceiling, floor);
return (B) this;
}
/**
* Returns the built {@link Scene} object.
*
* @return The build Scene.
*/
public R build() {
return scene;
}
}
}
| NativeVision/virocore | android/sharedCode/src/main/java/com/viro/core/Scene.java | 5,356 | /**
* @hide
*/ | block_comment | nl | //
// Copyright (c) 2017-present, ViroMedia, Inc.
// All rights reserved.
//
// 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.
/*
* Java JNI wrapper for linking the following classes across the bridge:
*
* Android Java Object : com.viromedia.bridge.viewgroups.Scene.java
* Java JNI Wrapper : com.viro.core.Scene.java
* Cpp JNI wrapper : Scene_JNI.cpp
* Cpp Object : VROScene.cpp
*/
package com.viro.core;
import android.graphics.Bitmap;
import android.net.Uri;
import java.util.HashMap;
import java.util.Map;
/**
* Scene represents a scene graph - a hierarchy of {@link Node}s that together represent the 3D
* world. UI controls, 3D objects, lights, camera, and more are attached to the Nodes to build the
* displayable 3D scene. To display a Scene in an Android View, use {@link ViroView}.
* <p>
* For an extended discussion of Viro's scene graph, refer to the <a
* href="https://virocore.viromedia.com/docs/scenes">Scene Guide</a>.
*/
public class Scene {
/**
* AudioMaterial is used to define the Scene's reverb effects. These are used in conjunction
* with {@link #setSoundRoom(ViroContext, Vector, AudioMaterial, AudioMaterial, AudioMaterial)}.
* In general, harder surface materials are more reverberant than rooms made of soft, absorbent
* materials.
*/
public enum AudioMaterial {
/**
* Transparent, no reverb.
*/
TRANSPARENT("transparent"),
/**
* Acoustic ceiling tiles.
*/
ACOUSTIC_CEILING_TILES("acoustic_ceiling_tiles"),
/**
* Brick, bare.
*/
BRICK_BARE("brick_bare"),
/**
* Painted brick.
*/
BRICK_PAINTED("brick_painted"),
/**
* Coarse concrete.
*/
CONCRETE_BLOCK_COARSE("concrete_block_coarse"),
/**
* Painted concrete.
*/
CONCRETE_BLOCK_PAINTED("concrete_block_painted"),
/**
* Heavy curtain.
*/
CURTAIN_HEAVY("curtain_heavy"),
/**
* Fiber glass.
*/
FIBER_GLASS_INSULATION("fiber_glass_insulation"),
/**
* Thin glass.
*/
GLASS_THIN("glass_thin"),
/**
* Thick glass.
*/
GLASS_THICK("glass_thick"),
/**
* Grass.
*/
GRASS("grass"),
/**
* Linoleum on concrete.
*/
LINOLEUM_ON_CONCRETE("linoleum_on_concrete"),
/**
* Marble.
*/
MARBLE("marble"),
/**
* Metal.
*/
METAL("metal"),
/**
* Parquet on concrete.
*/
PARQUET_ON_CONRETE("parquet_on_concrete"),
/**
* Rough plaster.
*/
PLASTER_ROUGH("plaster_rough"),
/**
* Smooth plaster.
*/
PLASTER_SMOOTH("plaster_smooth"),
/**
* Plywood panel.
*/
PLYWOOD_PANEL("plywood_panel"),
/**
* Polished concrete or tile.
*/
POLISHED_CONCRETE_OR_TILE("polished_concrete_or_tile"),
/**
* Sheet rock.
*/
SHEET_ROCK("sheet_rock"),
/**
* Water or ice.
*/
WATER_OR_ICE_SURFACE("water_or_ice_surface"),
/**
* Wood ceiling.
*/
WOOD_CEILING("wood_ceiling"),
/**
* Wood panel.
*/
WOOD_PANEL("wood_panel");
private String mStringValue;
private AudioMaterial(String value) {
this.mStringValue = value;
}
/**
* @hide
* @return
*/
public String getStringValue() {
return mStringValue;
}
private static Map<String, AudioMaterial> map = new HashMap<String, AudioMaterial>();
static {
for (AudioMaterial value : AudioMaterial.values()) {
map.put(value.getStringValue().toLowerCase(), value);
}
}
/**
* @hide
* @return
*/
public static AudioMaterial valueFromString(String str) {
return map.get(str.toLowerCase());
}
};
protected long mNativeRef;
protected long mNativeDelegateRef;
private Node mRootNode;
private PhysicsWorld mPhysicsWorld;
private Texture mLightingEnvironment;
private Texture mBackgroundTexture;
private VisibilityListener mListener = null;
/**
* Construct a new Scene.
*/
public Scene() {
setSceneRef(createNativeScene());
}
/**
* Subclass constructor, does not set the scene-ref.
*
* @hide
*/
Scene(boolean dummy) {
}
/**
* @hide
* @return
*/
protected long createNativeScene() {
return nativeCreateSceneController();
}
/**
* After-construction method when the sceneRef is known. Initializes
* the rest of the Scene.
*
* @hide
*/
protected void setSceneRef(long sceneRef) {
mNativeRef = sceneRef;
mNativeDelegateRef = nativeCreateSceneControllerDelegate(mNativeRef);
PortalScene root = new PortalScene(false);
root.initWithNativeRef(nativeGetSceneNodeRef(mNativeRef));
root.attachDelegate();
mRootNode = root;
mPhysicsWorld = new PhysicsWorld(this);
}
@Override
protected void finalize() throws Throwable {
try {
dispose();
} finally {
super.finalize();
}
}
/**
* Release native resources associated with this Scene.
*/
public void dispose() {
if (mNativeRef != 0) {
nativeDestroySceneController(mNativeRef);
mNativeRef = 0;
}
if (mNativeDelegateRef != 0) {
nativeDestroySceneControllerDelegate(mNativeDelegateRef);
mNativeDelegateRef = 0;
}
if (mBackgroundTexture != null) {
mBackgroundTexture.dispose();
mBackgroundTexture = null;
}
}
/**
* Retrieve the root {@link Node} of the scene graph.
*
* @return The root node.
*/
public Node getRootNode() {
return mRootNode;
}
/**
* Get the physics simulation for the Scene.
*
* @return The {@link PhysicsWorld} for the Scene.
*/
public PhysicsWorld getPhysicsWorld() {
return mPhysicsWorld;
}
/**
* Set the background of this Scene to display the texture. The provided {@link Texture} should
* contain a spherical image or spherical video. The image or video will be rendered behind all other
* content.
*
* @param texture The {@link Texture} containing the image, or {@link VideoTexture} containing
* the video.
*/
public void setBackgroundTexture(Texture texture) {
mBackgroundTexture = texture;
nativeSetBackgroundTexture(mNativeRef, texture.mNativeRef);
}
/**
* Rotate the background image or video by the given radians about the X, Y, and Z axes.
*
* @param rotation {@link Vector} containing rotation about the X, Y, and Z axes.
*/
public void setBackgroundRotation(Vector rotation) {
nativeSetBackgroundRotation(mNativeRef, rotation.x, rotation.y, rotation.z);
}
/**
* Set the background of this Scene to display a cube-map. The provided {@link Texture} should
* wrap a cube-map image. The cube-map will be rendered behind all other content.
*
* @param cubeTexture The {@link Texture} containing the cube-map.
*/
public void setBackgroundCubeTexture(Texture cubeTexture) {
nativeSetBackgroundCubeImageTexture(mNativeRef, cubeTexture.mNativeRef);
}
/**
* Set the background of this Scene to display the given color. The color will be rendered
* behind all other content.
*
* @param color The {@link android.graphics.Color}'s int value.
*/
public void setBackgroundCubeWithColor(long color) {
nativeSetBackgroundCubeWithColor(mNativeRef, color);
}
/**
* Set the lighting environment to use for the Scene. The lighting environment is a {@link
* Texture} that acts as a global light source, illuminating surfaces with diffuse and specular
* ambient light. Each pixel in the lighting environment is treated as a light emitter, thereby
* capturing the environment's global lighting and general feel. This gives objects a sense of
* belonging to their environment. For this reason it is common to use the scene's background
* texture as the lighting environment, but this is not necessary.
* <p>
* This method expects an equirectangular texture. Radiance HDR textures (*.hdr) work best,
* and can be loaded with {@link Texture#loadRadianceHDRTexture(Uri)}.
*
* @param lightingEnvironment The equirectangular {@link Texture} to use as the lighting
* environment.
*/
public void setLightingEnvironment(Texture lightingEnvironment) {
mLightingEnvironment = lightingEnvironment;
long ref = lightingEnvironment == null ? 0 : lightingEnvironment.mNativeRef;
nativeSetLightingEnvironment(mNativeRef, ref);
}
/**
* Get the lighting environment used by this Scene. The lighting environment is a {@link
* Texture} that acts as a global light source, illuminating surfaces with diffuse and specular
* ambient light.
*
* @return The equirectangular {@link Texture} being used as the lighting environment.
*/
public Texture getLightingEnvironment() {
return mLightingEnvironment;
}
/**
* Set the sound room, which enables reverb effects for all {@link SpatialSound} in the Scene.
* The sound room is defined by three {@link AudioMaterial}s, each of which has unique
* absorption properties which differ with frequency. The room is also give a size in meters,
* which is centered around the user. Larger rooms are more reverberant than smaller rooms, and
* harder surface materials are more reverberant than rooms made of soft, absorbent materials.
*
* @param viroContext {@link ViroContext} is required to set the sound room.
* @param size The size of the room's X, Y, and Z dimensions in meters, as a {@link
* Vector}.
* @param wall The wall {@link AudioMaterial}.
* @param ceiling The ceiling {@link AudioMaterial}.
* @param floor The floor {@link AudioMaterial}.
*/
public void setSoundRoom(ViroContext viroContext, Vector size, AudioMaterial wall,
AudioMaterial ceiling, AudioMaterial floor) {
nativeSetSoundRoom(mNativeRef, viroContext.mNativeRef, size.x, size.y, size.z,
wall.getStringValue(), ceiling.getStringValue(), floor.getStringValue());
}
/**
* @hide
* @param effects
* @return
*/
//#IFDEF 'viro_react'
public boolean setEffects(String[] effects){
return nativeSetEffects(mNativeRef, effects);
}
//#ENDIF
/*
* Native Functions called into JNI
*/
private native long nativeCreateSceneController();
private native long nativeCreateSceneControllerDelegate(long sceneRef);
private native void nativeDestroySceneController(long sceneReference);
private native long nativeGetSceneNodeRef(long sceneRef);
private native void nativeSetBackgroundTexture(long sceneRef, long imageRef);
private native void nativeSetBackgroundCubeImageTexture(long sceneRef, long textureRef);
private native void nativeSetBackgroundCubeWithColor(long sceneRef, long color);
private native void nativeSetBackgroundRotation(long sceneRef, float radiansX, float radiansY,
float radiansZ);
private native void nativeSetLightingEnvironment(long sceneRef, long textureRef);
private native void nativeSetSoundRoom(long sceneRef, long renderContextRef, float sizeX,
float sizeY, float sizeZ, String wallMaterial,
String ceilingMaterial, String floorMaterial);
private native boolean nativeSetEffects(long sceneRef, String[] effects);
/**
* @hide
* @param sceneDelegateRef
*/
protected native void nativeDestroySceneControllerDelegate(long sceneDelegateRef);
/**
* Receives callbacks in response to a {@link Scene} appearing and disappearing.
*/
public interface VisibilityListener {
/**
* Callback invoked when a Scene is about to appear.
*/
void onSceneWillAppear();
/**
* Callback invoked immediately after a Scene has appeared (after the transition).
*/
void onSceneDidAppear();
/**
* Callback invoked when a Scene is about to disappear.
*/
void onSceneWillDisappear();
/**
* Callback invoked immediately after a Scene has disappeared (after the transition).
*/
void onSceneDidDisappear();
}
/**
* Set the given {@link VisibilityListener} to receive callbacks when the Scene's visibility
* status changes.
*/
public void setVisibilityListener(VisibilityListener listener) {
mListener = listener;
}
/*
Called by Native functions.
*/
/**
* @hide
<SUF>*/
public void onSceneWillAppear() {
if (mListener != null) {
mListener.onSceneWillAppear();
}
}
/**
* @hide
*/
public void onSceneDidAppear() {
if (mListener != null) {
mListener.onSceneDidAppear();
}
}
/**
* @hide
*/
public void onSceneWillDisappear(){
if (mListener != null) {
mListener.onSceneWillDisappear();
}
}
/**
* @hide
*/
public void onSceneDidDisappear() {
if (mListener != null) {
mListener.onSceneDidDisappear();
}
}
/*
Native Viro Physics JNI Functions
*/
private native void nativeSetPhysicsWorldGravity(long sceneRef, float gravity[]);
private native void findCollisionsWithRayAsync(long sceneRef, float[] from, float[] to,
boolean closest, String tag,
PhysicsWorld.HitTestListener callback);
private native void findCollisionsWithShapeAsync(long sceneRef, float[] from, float[] to,
String shapeType, float[] params, String tag,
PhysicsWorld.HitTestListener callback);
private native void nativeSetPhysicsWorldDebugDraw(long sceneRef, boolean debugDraw);
/*
Invoked by PhysicsWorld
*/
/**
* @hide
* @param gravity
*/
void setPhysicsWorldGravity(float gravity[]){
nativeSetPhysicsWorldGravity(mNativeRef, gravity);
}
/**
* @hide
* @param debugDraw
*/
void setPhysicsDebugDraw(boolean debugDraw){
nativeSetPhysicsWorldDebugDraw(mNativeRef, debugDraw);
}
/**
* @hide
* @param fromPos
* @param toPos
* @param closest
* @param tag
* @param callback
*/
void findCollisionsWithRayAsync(float[] fromPos, float toPos[], boolean closest,
String tag, PhysicsWorld.HitTestListener callback){
findCollisionsWithRayAsync(mNativeRef, fromPos, toPos, closest, tag, callback);
}
/**
* @hide
* @param from
* @param to
* @param shapeType
* @param params
* @param tag
* @param callback
*/
void findCollisionsWithShapeAsync(float[] from, float[] to, String shapeType, float[] params,
String tag, PhysicsWorld.HitTestListener callback){
findCollisionsWithShapeAsync(mNativeRef, from,to, shapeType, params, tag, callback);
}
/**
* Creates a builder for building complex {@link Scene} objects.
*
* @return {@link SceneBuilder} object.
*/
public static SceneBuilder<? extends Scene, ? extends SceneBuilder> builder() {
return new SceneBuilder<>();
}
// +---------------------------------------------------------------------------+
// | SceneBuilder class for Scene
// +---------------------------------------------------------------------------+
/**
* SceneBuilder for creating {@link Scene} objects.
*/
public static class SceneBuilder<R extends Scene, B extends SceneBuilder<R, B>> {
private R scene;
/**
* Constructor for SceneBuilder class.
*/
public SceneBuilder() {
this.scene = (R) new Scene();
}
/**
* Refer to {@link Scene#setVisibilityListener(VisibilityListener)}.
*
* @return This builder.
*/
public SceneBuilder listener(VisibilityListener listener) {
this.scene.setVisibilityListener(listener);
return (B) this;
}
/**
* Refer to {@link Scene#setBackgroundTexture(Texture)}.
*
* @return This builder.
*/
public SceneBuilder backgroundTexture(Texture backgroundTexture) {
this.scene.setBackgroundTexture(backgroundTexture);
return (B) this;
}
/**
* Refer to {@link Scene#setBackgroundRotation(Vector)}.
*
* @return This builder.
*/
public SceneBuilder backgroundRotation(Vector backgroundRotation) {
this.scene.setBackgroundRotation(backgroundRotation);
return (B) this;
}
/**
* Refer to {@link Scene#setBackgroundCubeWithColor(long)}}.
*
* @return This builder.
*/
public SceneBuilder backgroundCubeWithColor(long backgroundCubeWithColor) {
this.scene.setBackgroundCubeWithColor(backgroundCubeWithColor);
return (B) this;
}
/**
* Refer to {@link Scene#setLightingEnvironment(Texture)}.
*
* @return This builder.
*/
public SceneBuilder lightingEnvironment(Texture lightingEnvironment) {
this.scene.setLightingEnvironment(lightingEnvironment);;
return (B) this;
}
/**
* Refer to {@link Scene#setSoundRoom(ViroContext, Vector, AudioMaterial, AudioMaterial, AudioMaterial)}.
*
* @return This builder.
*/
public SceneBuilder soundRoom(ViroContext viroContext, Vector size, AudioMaterial wall,
AudioMaterial ceiling, AudioMaterial floor) {
this.scene.setSoundRoom(viroContext,size, wall, ceiling, floor);
return (B) this;
}
/**
* Returns the built {@link Scene} object.
*
* @return The build Scene.
*/
public R build() {
return scene;
}
}
}
|
37153_13 | package gui;
import entities.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utils.HibernateUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.JOptionPane.showMessageDialog;
/**
* Created by Nav on 06-10-15 21:05.
*/
class RegisterPanel extends JPanel implements ActionListener {
private static SessionFactory factory;
public JTextField firstnameInput;
public JTextField lastnameInput;
public JTextField ibanInput;
public JTextField usernameInput;
public JTextField passwordInput;
public JTextField password2Input;
public JButton submit;
public JFrame frame;
public JTextField nameField;
public JTextField lastNameField;
public JComboBox sexSelect;
public String[] sexSelectText = { "male", "Female"};
public RegisterPanel() {
initialize();
//
// setLayout(new FlowLayout());
// this.setPreferredSize(new Dimension(300,400));
// setBounds(0,0,300,400);
// firstnameInput = new JTextField("", 15);
// lastnameInput = new JTextField("", 15);
// ibanInput = new JTextField("", 15);
// Font font = new Font("Courier", Font.BOLD,12);
// usernameInput = new JTextField("", 15);
// passwordInput = new JTextField("", 15);
// password2Input = new JTextField("", 15);
// JButton submit = new JButton("Registreer");
// JLabel personalLabel = new JLabel("<html>Persoonlijke gegevens<br>" + "Vul je persoonlijke gegevens in. <br></html>");
// JLabel accountLabel = new JLabel("<html>Account gegevens<br>" + "Registreer jezelf met een unieke username en eigen gekozen wachtwoord. <br></html>");
//
// add(personalLabel);
//
// add(new JLabel("Voornaam"));
// add(firstnameInput);
// add(new JLabel("Achternaam"));
// add(lastnameInput);
// add(new JLabel("Iban nummer"));
// add(ibanInput);
//
// add(accountLabel);
//// add(new JLabel("Account gegevens \n\n"));
// add(new JLabel("Gebruikersnaam"));
// add(usernameInput);
// add(new JLabel("Wachtwoord"));
// add(passwordInput);
// add(new JLabel("Wachtwoord nogmaals"));
// add(password2Input);
// add(submit);
// submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String username = usernameInput.getText();
String password = passwordInput.getText();
String password2 = password2Input.getText();
String firstname = firstnameInput.getText();
String lastname = lastnameInput.getText();
String iban = ibanInput.getText();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
if (username.isEmpty()) {
showMessageDialog(null, "Gebruikersnaam is niet ingevuld! ");
}
else if (password.isEmpty()) {
showMessageDialog(null, "Wachtwoord is niet ingevuld! ");
}
else if (password2.isEmpty()) {
showMessageDialog(null, "Controle Wachtwoord is niet ingevuld! ");
}
//
// session.beginTransaction();
// int p;
// p = session
// .createQuery("from Player where username = :username")
// .setString("username", username)
// .executeUpdate();
// session.getTransaction().commit();
// if(p == 1) System.out.println(p);
// else System.out.println("did not find");
//
// showMessageDialog(null, "Gebruikersnaam al in gebruik, kies een andere gebruikersnaam. ");
//
// // Check password controle
// if(!password.equals(password2)){
// showMessageDialog(null, "Wachtwoord controle gefaald, controleer uw wachtwoord.");
// }
// this.hide();
}
public JTextField getUsernameInput() {
return usernameInput;
}
public RegisterPanel setUsernameInput(JTextField usernameInput) {
this.usernameInput = usernameInput;
return this;
}
public JTextField getPasswordInput() {
return passwordInput;
}
public RegisterPanel setPasswordInput(JTextField passwordInput) {
this.passwordInput = passwordInput;
return this;
}
public JButton getSubmit() {
return submit;
}
public RegisterPanel setSubmit(JButton submit) {
this.submit = submit;
return this;
}
public void initialize(){
final JFrame frame = new JFrame();
frame.setBounds(100, 100, 565, 456);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblName = new JLabel("Voornaam");
lblName.setBounds(10, 10, 417, 27);
frame.getContentPane().add(lblName);
JLabel label = new JLabel("Achternaam");
label.setBounds(10, 50, 417, 27);
frame.getContentPane().add(label);
JLabel iban = new JLabel("Iban");
iban.setBounds(10, 90, 76, 33);
frame.getContentPane().add(iban);
final JLabel label_1 = new JLabel("ACCOUNT GEGEVENS");
label_1.setBounds(10, 130, 300, 33);
frame.getContentPane().add(label_1);
final JTextField firstnameField = new JTextField();
firstnameField.setBackground(SystemColor.menu);
firstnameField.setBounds(122, 10, 417, 27);
firstnameField.setColumns(10);
frame.getContentPane().add(firstnameField);
final JTextField lastNameField = new JTextField();
lastNameField.setColumns(10);
lastNameField.setBounds(122, 50, 417, 27);
frame.getContentPane().add(lastNameField);
final JTextField ibanField = new JTextField();
ibanField.setBackground(SystemColor.menu);
ibanField.setColumns(10);
ibanField.setBounds(122, 90, 417, 27);
frame.getContentPane().add(ibanField);
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10, 175, 100, 33);
frame.getContentPane().add(usernameLabel);
final JTextField usernameField = new JTextField();
usernameField.setColumns(10);
usernameField.setBounds(122, 175, 417, 27);
frame.getContentPane().add(usernameField);
JLabel passwordLabel = new JLabel("Wachtwoord");
passwordLabel.setBounds(10, 225, 100, 33);
frame.getContentPane().add(passwordLabel);
final JTextField passwordField = new JTextField();
passwordField.setColumns(10);
passwordField.setBounds(122, 225, 417, 27);
frame.getContentPane().add(passwordField);
final JButton submitButton = new JButton("Registreer");
submitButton.setBounds(10, 361, 118, 46);
frame.getContentPane().add(submitButton);
frame.setVisible(true);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String u = usernameField.getText();
String p = passwordField.getText();
if(!u.isEmpty() && !p.isEmpty()){
Session registreerSessie = HibernateUtil.getSessionFactory()
.getCurrentSession();
registreerSessie.beginTransaction();
boolean exists = registreerSessie
.createQuery("from Player where username = :username")
.setParameter("username", u)
.setMaxResults(1)
.uniqueResult() != null;
if (exists == true) {
showMessageDialog(null, "Gebruikersnaam al in gebruik, kies een andere.");
registreerSessie.getTransaction().rollback();
frame.setVisible(true);
} else {
Player user = new Player();
user.setBalance("0");
user.setBanned(false);
user.setCharacterslots("5");
user.setFirstname(firstnameField.getText());
user.setLastname(lastNameField.getText());
user.setIban(ibanField.getText());
user.setUsername(usernameField.getText());
user.setPassword(passwordField.getText());
registreerSessie.save(user);
registreerSessie.getTransaction().commit();
showMessageDialog(null, "Gebruiker " + usernameField.getText() + " is aangemaakt. Login met je wachtwoord: " + passwordField.getText());
frame.dispose();
}
}
}
});
}
}
| Nav-Appaiya/INFDEV22-5_HibernateMMORPG | src/main/java/gui/RegisterPanel.java | 2,527 | // add(new JLabel("Wachtwoord nogmaals")); | line_comment | nl | package gui;
import entities.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utils.HibernateUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.JOptionPane.showMessageDialog;
/**
* Created by Nav on 06-10-15 21:05.
*/
class RegisterPanel extends JPanel implements ActionListener {
private static SessionFactory factory;
public JTextField firstnameInput;
public JTextField lastnameInput;
public JTextField ibanInput;
public JTextField usernameInput;
public JTextField passwordInput;
public JTextField password2Input;
public JButton submit;
public JFrame frame;
public JTextField nameField;
public JTextField lastNameField;
public JComboBox sexSelect;
public String[] sexSelectText = { "male", "Female"};
public RegisterPanel() {
initialize();
//
// setLayout(new FlowLayout());
// this.setPreferredSize(new Dimension(300,400));
// setBounds(0,0,300,400);
// firstnameInput = new JTextField("", 15);
// lastnameInput = new JTextField("", 15);
// ibanInput = new JTextField("", 15);
// Font font = new Font("Courier", Font.BOLD,12);
// usernameInput = new JTextField("", 15);
// passwordInput = new JTextField("", 15);
// password2Input = new JTextField("", 15);
// JButton submit = new JButton("Registreer");
// JLabel personalLabel = new JLabel("<html>Persoonlijke gegevens<br>" + "Vul je persoonlijke gegevens in. <br></html>");
// JLabel accountLabel = new JLabel("<html>Account gegevens<br>" + "Registreer jezelf met een unieke username en eigen gekozen wachtwoord. <br></html>");
//
// add(personalLabel);
//
// add(new JLabel("Voornaam"));
// add(firstnameInput);
// add(new JLabel("Achternaam"));
// add(lastnameInput);
// add(new JLabel("Iban nummer"));
// add(ibanInput);
//
// add(accountLabel);
//// add(new JLabel("Account gegevens \n\n"));
// add(new JLabel("Gebruikersnaam"));
// add(usernameInput);
// add(new JLabel("Wachtwoord"));
// add(passwordInput);
// add(new JLabel("Wachtwoord<SUF>
// add(password2Input);
// add(submit);
// submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String username = usernameInput.getText();
String password = passwordInput.getText();
String password2 = password2Input.getText();
String firstname = firstnameInput.getText();
String lastname = lastnameInput.getText();
String iban = ibanInput.getText();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
if (username.isEmpty()) {
showMessageDialog(null, "Gebruikersnaam is niet ingevuld! ");
}
else if (password.isEmpty()) {
showMessageDialog(null, "Wachtwoord is niet ingevuld! ");
}
else if (password2.isEmpty()) {
showMessageDialog(null, "Controle Wachtwoord is niet ingevuld! ");
}
//
// session.beginTransaction();
// int p;
// p = session
// .createQuery("from Player where username = :username")
// .setString("username", username)
// .executeUpdate();
// session.getTransaction().commit();
// if(p == 1) System.out.println(p);
// else System.out.println("did not find");
//
// showMessageDialog(null, "Gebruikersnaam al in gebruik, kies een andere gebruikersnaam. ");
//
// // Check password controle
// if(!password.equals(password2)){
// showMessageDialog(null, "Wachtwoord controle gefaald, controleer uw wachtwoord.");
// }
// this.hide();
}
public JTextField getUsernameInput() {
return usernameInput;
}
public RegisterPanel setUsernameInput(JTextField usernameInput) {
this.usernameInput = usernameInput;
return this;
}
public JTextField getPasswordInput() {
return passwordInput;
}
public RegisterPanel setPasswordInput(JTextField passwordInput) {
this.passwordInput = passwordInput;
return this;
}
public JButton getSubmit() {
return submit;
}
public RegisterPanel setSubmit(JButton submit) {
this.submit = submit;
return this;
}
public void initialize(){
final JFrame frame = new JFrame();
frame.setBounds(100, 100, 565, 456);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblName = new JLabel("Voornaam");
lblName.setBounds(10, 10, 417, 27);
frame.getContentPane().add(lblName);
JLabel label = new JLabel("Achternaam");
label.setBounds(10, 50, 417, 27);
frame.getContentPane().add(label);
JLabel iban = new JLabel("Iban");
iban.setBounds(10, 90, 76, 33);
frame.getContentPane().add(iban);
final JLabel label_1 = new JLabel("ACCOUNT GEGEVENS");
label_1.setBounds(10, 130, 300, 33);
frame.getContentPane().add(label_1);
final JTextField firstnameField = new JTextField();
firstnameField.setBackground(SystemColor.menu);
firstnameField.setBounds(122, 10, 417, 27);
firstnameField.setColumns(10);
frame.getContentPane().add(firstnameField);
final JTextField lastNameField = new JTextField();
lastNameField.setColumns(10);
lastNameField.setBounds(122, 50, 417, 27);
frame.getContentPane().add(lastNameField);
final JTextField ibanField = new JTextField();
ibanField.setBackground(SystemColor.menu);
ibanField.setColumns(10);
ibanField.setBounds(122, 90, 417, 27);
frame.getContentPane().add(ibanField);
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10, 175, 100, 33);
frame.getContentPane().add(usernameLabel);
final JTextField usernameField = new JTextField();
usernameField.setColumns(10);
usernameField.setBounds(122, 175, 417, 27);
frame.getContentPane().add(usernameField);
JLabel passwordLabel = new JLabel("Wachtwoord");
passwordLabel.setBounds(10, 225, 100, 33);
frame.getContentPane().add(passwordLabel);
final JTextField passwordField = new JTextField();
passwordField.setColumns(10);
passwordField.setBounds(122, 225, 417, 27);
frame.getContentPane().add(passwordField);
final JButton submitButton = new JButton("Registreer");
submitButton.setBounds(10, 361, 118, 46);
frame.getContentPane().add(submitButton);
frame.setVisible(true);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String u = usernameField.getText();
String p = passwordField.getText();
if(!u.isEmpty() && !p.isEmpty()){
Session registreerSessie = HibernateUtil.getSessionFactory()
.getCurrentSession();
registreerSessie.beginTransaction();
boolean exists = registreerSessie
.createQuery("from Player where username = :username")
.setParameter("username", u)
.setMaxResults(1)
.uniqueResult() != null;
if (exists == true) {
showMessageDialog(null, "Gebruikersnaam al in gebruik, kies een andere.");
registreerSessie.getTransaction().rollback();
frame.setVisible(true);
} else {
Player user = new Player();
user.setBalance("0");
user.setBanned(false);
user.setCharacterslots("5");
user.setFirstname(firstnameField.getText());
user.setLastname(lastNameField.getText());
user.setIban(ibanField.getText());
user.setUsername(usernameField.getText());
user.setPassword(passwordField.getText());
registreerSessie.save(user);
registreerSessie.getTransaction().commit();
showMessageDialog(null, "Gebruiker " + usernameField.getText() + " is aangemaakt. Login met je wachtwoord: " + passwordField.getText());
frame.dispose();
}
}
}
});
}
}
|
132132_15 | package nl.hr.cmi.infdev226a;
public class GelinkteLijst {
private Node first, last;
private int size;
public Object getFirst() {
return first.data;
}
public Object getLast() {
return last.data;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe aan de voorkant
*/
public void insertFirst(Object o) {
Node newNode = new Node();
newNode.data = o;
newNode.next = first;
newNode.previous = null;
if (this.first != null) {
//set the old first's previous to the newNode
this.first.previous = newNode;
} else {
//list was empty, newNode will be the only node.
//so also set the last
this.last = newNode;
}
//set the head to the newNode
this.first = newNode;
size++;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe aan de achterkant
*/
public void insertLast(Object o) {
// n = new Node();
Node n = new Node();
n.data = o;
n.next = null;
n.previous = last;
//if the list is not empty
if (last != null) {
last.previous = n;
} else {
this.last = n;
}
size++;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe voor een ander element
*/
public void insertBefore(Object o, Object before) {
Node s = first;
while (s != null) {
if (s.data.equals(before)) {
Node n = new Node();
n.data = o;
n.next = s;
n.next.previous = n;
if (!isFirst(before)) {
n.previous = s.previous;
n.previous.next = n;
} else {
first = n;
}
size++;
break;
} else {
s = s.next;
}
}
this.size++;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe na een ander element
*/
public void insertAfter(Object o, Object after) {
Node s = first;
while (s != null) {
if (s.data.equals(after)) {
Node n = new Node();
n.data = o;
n.previous = s;
n.previous.next = n;
// System.out.println("@Nav Todo: debug till here ===============");
if (!isLast(after)) {
n.next = s.next;
n.next.previous = n;
} else {
last = n;
}
size++;
break;
} else {
s = s.next;
}
}
size++;
}
/**
* Done - Nav Appaiya 29 November
* Verwijder een element
*
* @param data
*/
public void remove(Object data) {
Node s = first;
while (s != null) {
if (s.data.equals(data)) {
if (!isFirst(s.data) && !isLast(s.data)) {
s.previous.next = s.next;
s.next.previous = s.previous;
} else if (getSize() == 1) {
first = null;
last = null;
} else if (isFirst(s.data)) {
first = s.next;
s.next.previous = null;
} else if (isLast(s.data)) {
last = s.previous;
s.previous.next = null;
}
size--;
break;
} else {
s = s.next;
}
}
}
/**
* Done - Nav Appaiya 29 November
* Het aantal elementen in de gelinkte lijst
*
* @return
*/
public int getSize() {
return size;
}
/**
* @param o
* @return
*/
boolean isFirst(Object o) {
return first.data.equals(o);
}
/**
* @param o
* @return
*/
boolean isLast(Object o) {
return last.data.equals(o);
}
Object getData(Node n) {
return n.data;
}
@Override
public String toString() {
Node s = first;
String r = "";
int c = 1;
while (s != null) {
r += "Node " + c++ + ":" + s + "\n";
s = s.next;
}
return r;
}
/**
* Alleen de gelinkte lijst heeft toegang tot de node
*/
private class Node {
//Dit is de data die je opslaat
Object data;
// referenties naar de eerste en laatste nodes
Node next, previous;
}
}
| Nav-Appaiya/INFDEV226A-LinkedLists | src/main/java/nl/hr/cmi/infdev226a/GelinkteLijst.java | 1,391 | /**
* Alleen de gelinkte lijst heeft toegang tot de node
*/ | block_comment | nl | package nl.hr.cmi.infdev226a;
public class GelinkteLijst {
private Node first, last;
private int size;
public Object getFirst() {
return first.data;
}
public Object getLast() {
return last.data;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe aan de voorkant
*/
public void insertFirst(Object o) {
Node newNode = new Node();
newNode.data = o;
newNode.next = first;
newNode.previous = null;
if (this.first != null) {
//set the old first's previous to the newNode
this.first.previous = newNode;
} else {
//list was empty, newNode will be the only node.
//so also set the last
this.last = newNode;
}
//set the head to the newNode
this.first = newNode;
size++;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe aan de achterkant
*/
public void insertLast(Object o) {
// n = new Node();
Node n = new Node();
n.data = o;
n.next = null;
n.previous = last;
//if the list is not empty
if (last != null) {
last.previous = n;
} else {
this.last = n;
}
size++;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe voor een ander element
*/
public void insertBefore(Object o, Object before) {
Node s = first;
while (s != null) {
if (s.data.equals(before)) {
Node n = new Node();
n.data = o;
n.next = s;
n.next.previous = n;
if (!isFirst(before)) {
n.previous = s.previous;
n.previous.next = n;
} else {
first = n;
}
size++;
break;
} else {
s = s.next;
}
}
this.size++;
}
/**
* Done - Nav Appaiya 29 November
* Voeg toe na een ander element
*/
public void insertAfter(Object o, Object after) {
Node s = first;
while (s != null) {
if (s.data.equals(after)) {
Node n = new Node();
n.data = o;
n.previous = s;
n.previous.next = n;
// System.out.println("@Nav Todo: debug till here ===============");
if (!isLast(after)) {
n.next = s.next;
n.next.previous = n;
} else {
last = n;
}
size++;
break;
} else {
s = s.next;
}
}
size++;
}
/**
* Done - Nav Appaiya 29 November
* Verwijder een element
*
* @param data
*/
public void remove(Object data) {
Node s = first;
while (s != null) {
if (s.data.equals(data)) {
if (!isFirst(s.data) && !isLast(s.data)) {
s.previous.next = s.next;
s.next.previous = s.previous;
} else if (getSize() == 1) {
first = null;
last = null;
} else if (isFirst(s.data)) {
first = s.next;
s.next.previous = null;
} else if (isLast(s.data)) {
last = s.previous;
s.previous.next = null;
}
size--;
break;
} else {
s = s.next;
}
}
}
/**
* Done - Nav Appaiya 29 November
* Het aantal elementen in de gelinkte lijst
*
* @return
*/
public int getSize() {
return size;
}
/**
* @param o
* @return
*/
boolean isFirst(Object o) {
return first.data.equals(o);
}
/**
* @param o
* @return
*/
boolean isLast(Object o) {
return last.data.equals(o);
}
Object getData(Node n) {
return n.data;
}
@Override
public String toString() {
Node s = first;
String r = "";
int c = 1;
while (s != null) {
r += "Node " + c++ + ":" + s + "\n";
s = s.next;
}
return r;
}
/**
* Alleen de gelinkte<SUF>*/
private class Node {
//Dit is de data die je opslaat
Object data;
// referenties naar de eerste en laatste nodes
Node next, previous;
}
}
|
82017_6 | /**
* Created by Nav on 22-3-2015.
*/
// The Exceptions from Exceptions Package
import Exceptions.CrashException;
import Exceptions.EngineException;
import Exceptions.FlapException;
import Exceptions.PilotException;
public class Airplane {
// Create a Parts Array
static Part[] parts = new Part[9];
// Boolean to define failed or not
static boolean[] fails = new boolean[parts.length];
Airplane(){
// Een Boeing 747 heeft 4 motoren, genummerd van 1 t/m 4.
// Motor 1 en 4 zijn de buitenste motoren; Motor 2 en 3 de binnenste.
parts[0] = new Engine(); // Buitenste
parts[1] = new Engine(); // Buitenste
parts[2] = new Engine(); // Binnenste
parts[3] = new Engine(); // Binnenste
// Alleen als beide flaps uitvallen, zal het vliegtuig neerstorten.
parts[4] = new Flap();
parts[5] = new Flap();
// Alleen als alle piloten uitvallen, zal het vliegtuig neerstorten.
parts[6] = new Pilot();
parts[7] = new Pilot();
parts[8] = new Pilot();
}
static void flight(int n) throws CrashException
{
int engineNummer = 0;
int flapNummer = 0;
int pilotNummer = 0;
for (int i=0; i<parts.length; i++)
{
try
{
parts[i].calculate();
}
catch (EngineException e)
{
engineNummer++;
fails[i] = true;
}
catch (FlapException e)
{
flapNummer++;
fails[i] = true;
}
catch (PilotException e)
{
pilotNummer++;
fails[i] = true;
}
catch (Exception e){} // dummy
}
Recorder.engineFailure += engineNummer;
Recorder.flapFailure += flapNummer;
Recorder.pilotFailure += pilotNummer;
// chance for fEngine is really small (0.001^3)
// check if both inner engines failed
boolean fEngine = (engineNummer >= 3 && fails[1] && fails[2]);
if (fEngine || flapNummer == 2 || pilotNummer == 3)
{
String s = "\n\tFlight: "+n
+(engineNummer>0 ? "\n\tEngines: "+engineNummer : "")
+(flapNummer>0 ? "\n\tFlaps: "+flapNummer : "")
+(pilotNummer>0 ? "\n\tPilots: "+pilotNummer : "");
throw new CrashException(s);
}
}
}
| Nav-Appaiya/JavaAssignments | HetVliegtuig/src/Airplane.java | 762 | // Alleen als beide flaps uitvallen, zal het vliegtuig neerstorten. | line_comment | nl | /**
* Created by Nav on 22-3-2015.
*/
// The Exceptions from Exceptions Package
import Exceptions.CrashException;
import Exceptions.EngineException;
import Exceptions.FlapException;
import Exceptions.PilotException;
public class Airplane {
// Create a Parts Array
static Part[] parts = new Part[9];
// Boolean to define failed or not
static boolean[] fails = new boolean[parts.length];
Airplane(){
// Een Boeing 747 heeft 4 motoren, genummerd van 1 t/m 4.
// Motor 1 en 4 zijn de buitenste motoren; Motor 2 en 3 de binnenste.
parts[0] = new Engine(); // Buitenste
parts[1] = new Engine(); // Buitenste
parts[2] = new Engine(); // Binnenste
parts[3] = new Engine(); // Binnenste
// Alleen als<SUF>
parts[4] = new Flap();
parts[5] = new Flap();
// Alleen als alle piloten uitvallen, zal het vliegtuig neerstorten.
parts[6] = new Pilot();
parts[7] = new Pilot();
parts[8] = new Pilot();
}
static void flight(int n) throws CrashException
{
int engineNummer = 0;
int flapNummer = 0;
int pilotNummer = 0;
for (int i=0; i<parts.length; i++)
{
try
{
parts[i].calculate();
}
catch (EngineException e)
{
engineNummer++;
fails[i] = true;
}
catch (FlapException e)
{
flapNummer++;
fails[i] = true;
}
catch (PilotException e)
{
pilotNummer++;
fails[i] = true;
}
catch (Exception e){} // dummy
}
Recorder.engineFailure += engineNummer;
Recorder.flapFailure += flapNummer;
Recorder.pilotFailure += pilotNummer;
// chance for fEngine is really small (0.001^3)
// check if both inner engines failed
boolean fEngine = (engineNummer >= 3 && fails[1] && fails[2]);
if (fEngine || flapNummer == 2 || pilotNummer == 3)
{
String s = "\n\tFlight: "+n
+(engineNummer>0 ? "\n\tEngines: "+engineNummer : "")
+(flapNummer>0 ? "\n\tFlaps: "+flapNummer : "")
+(pilotNummer>0 ? "\n\tPilots: "+pilotNummer : "");
throw new CrashException(s);
}
}
}
|
26298_9 | package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.commons.codec.digest.DigestUtils;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.AudioData;
import org.myrobotlab.service.interfaces.AudioListener;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.slf4j.Logger;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.polly.AmazonPollyClient;
import com.amazonaws.services.polly.AmazonPollyClientBuilder;
import com.amazonaws.services.polly.model.DescribeVoicesRequest;
import com.amazonaws.services.polly.model.DescribeVoicesResult;
import com.amazonaws.services.polly.model.OutputFormat;
import com.amazonaws.services.polly.model.SynthesizeSpeechRequest;
import com.amazonaws.services.polly.model.SynthesizeSpeechResult;
import com.amazonaws.services.polly.model.Voice;
/**
* Amazon's cloud speech service
*
* Free Tier The Amazon Polly free tier includes 5 million characters per month,
* for the first 12 months, starting from the first request for speech.
*
* Polly Pricing Pay-as-you-go $4.00 per 1 million characters (when outside the
* free tier).
*
* @author gperry
*
*/
public class Polly extends Service implements SpeechSynthesis, AudioListener {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Polly.class);
transient AWSCredentials credentials;
transient AmazonPollyClient polly;
transient Voice awsVoice;
transient List<Voice> awsVoices;
// this is a peer service.
transient AudioFile audioFile = null;
transient Map<String, Voice> voiceMap = new HashMap<String, Voice>();
transient Map<String, Voice> langMap = new HashMap<String, Voice>();
String voice;
Stack<String> audioFiles = new Stack<String>();
private String keyIdSecret;
private String keyId;
transient HashMap<AudioData, String> utterances = new HashMap<AudioData, String>();
String lang;
public Polly(String n) {
super(n);
}
public void setKey(String keyId, String keyIdSecret) {
this.keyId = keyId;
this.keyIdSecret = keyIdSecret;
}
@Override
public List<String> getVoices() {
getPolly();
return new ArrayList<String>(voiceMap.keySet());
}
@Override
public boolean setVoice(String voice) {
getPolly();
if (voiceMap.containsKey(voice)) {
log.info("setting voice to {}", voice);
awsVoice = voiceMap.get(voice);
this.voice = voice;
this.lang = awsVoice.getLanguageCode();
return true;
}
log.info("could not set voice to {}", voice);
return false;
}
@Override
public void setLanguage(String l) {
if (langMap.containsKey(l)) {
setVoice(langMap.get(l).getName());
}
}
@Override
public String getLanguage() {
return lang;
}
@Override
public List<String> getLanguages() {
return new ArrayList<String>(langMap.keySet());
}
/**
* Proxy works in 3 modes
* client - consumer of mrl services
* relay - proxy (running as cloud service)
* direct - goes direct to service
* In Polly's case -
* client - would be an end user using a client key
* relay - is the mrl proxy service
* direct would be from a users, by-passing mrl and going directly to Amazon with amazon keys
* cache file - caches file locally (both client or relay)
* @param toSpeak
* @param format
* @throws IOException
*/
public byte[] cacheFile(String toSpeak, OutputFormat format) throws IOException {
byte[] mp3File = null;
// cache it begin -----
String localFileName = getLocalFileName(this, toSpeak, "mp3");
// String filename = AudioFile.globalFileCacheDir + File.separator +
// localFileName;
if (!audioFile.cacheContains(localFileName)) {
log.info("retrieving speech from Amazon - {}", localFileName);
AmazonPollyClient polly = getPolly();
SynthesizeSpeechRequest synthReq = new SynthesizeSpeechRequest().withText(toSpeak).withVoiceId(awsVoice.getId()).withOutputFormat(format);
SynthesizeSpeechResult synthRes = polly.synthesizeSpeech(synthReq);
InputStream data = synthRes.getAudioStream();
mp3File = FileIO.toByteArray(data);
audioFile.cache(localFileName, mp3File, toSpeak);
} else {
log.info("using local cached file");
mp3File = FileIO.toByteArray(new File(AudioFile.globalFileCacheDir + File.separator + getLocalFileName(this, toSpeak, "mp3")));
}
// invoke("publishStartSpeaking", toSpeak);
// audioFile.playBlocking(filename);
// invoke("publishEndSpeaking", toSpeak);
// log.info("Finished waiting for completion.");
return mp3File;
}
@Override
public AudioData speak(String toSpeak) throws Exception {
cacheFile(toSpeak, OutputFormat.Mp3);
AudioData audioData = audioFile.playCachedFile(getLocalFileName(this, toSpeak, "mp3"));
utterances.put(audioData, toSpeak);
return audioData;
/*
* InputStream speechStream = synthesize(toSpeak, OutputFormat.Mp3); //
* create an MP3 player AdvancedPlayer player = new
* AdvancedPlayer(speechStream,
* javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice());
*
* player.setPlayBackListener(new PlaybackListener() {
*
* @Override public void playbackStarted(PlaybackEvent evt) {
* System.out.println("Playback started"); System.out.println(toSpeak); }
*
* @Override public void playbackFinished(PlaybackEvent evt) {
* System.out.println("Playback finished"); } });
*
* // play it! player.play();
*/
}
private void processVoicesRequest() {
// Create describe voices request.
DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
// Synchronously ask Polly Polly to describe available TTS voices.
DescribeVoicesResult describeVoicesResult = polly.describeVoices(describeVoicesRequest);
awsVoices = describeVoicesResult.getVoices();
log.info("found {} voices", awsVoices.size());
for (int i = 0; i < awsVoices.size(); ++i) {
Voice voice = awsVoices.get(i);
voiceMap.put(voice.getName(), voice);
langMap.put(voice.getLanguageCode(), voice);
log.info("{} {} - {}", i, voice.getName(), voice.getLanguageCode());
}
// set default voice
if (voice == null) {
voice = awsVoices.get(0).getName();
awsVoice = awsVoices.get(0);
lang = awsVoice.getLanguageCode();
log.info("setting default voice to {}", voice);
}
}
private AmazonPollyClient getPolly() {
if (polly == null) {
try {
// AWSCredentials creds = new
// BasicAWSCredentials("AKIAJGL6AEN37LDO3N7A", "secret-access-key");
if (credentials == null) {
// try credential chain - in case they have set env vars
credentials = new BasicAWSCredentials(keyId, keyIdSecret);
}
// polly = (AmazonPollyClient)
// AmazonPollyClientBuilder.standard().withCredentials(new
// AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build();
polly = (AmazonPollyClient) AmazonPollyClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_WEST_2).build();
processVoicesRequest();
} catch (Exception e) {
try {
log.error("could not get client with keys supplied - trying default chain", e);
polly = new AmazonPollyClient(new DefaultAWSCredentialsProviderChain(), new ClientConfiguration());
// polly.setRegion(Region.getRegion(Regions.US_EAST_1));
polly.setRegion(Region.getRegion(Regions.US_WEST_2));
processVoicesRequest();
} catch (Exception e2) {
error("could not get Polly client - did you setKeys ?");
error("Environment variables – AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or");
error("check http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html");
log.error("giving up", e2);
}
}
}
return polly;
}
@Override
public String publishStartSpeaking(String utterance) {
log.info("publishStartSpeaking {}", utterance);
return utterance;
}
@Override
public String publishEndSpeaking(String utterance) {
log.info("publishEndSpeaking {}", utterance);
return utterance;
}
@Override
public void onAudioStart(AudioData data) {
log.info("onAudioStart {} {}", getName(), data.toString());
// filters on only our speech
if (utterances.containsKey(data)) {
String utterance = utterances.get(data);
invoke("publishStartSpeaking", utterance);
}
}
@Override
public void onAudioEnd(AudioData data) {
log.info("onAudioEnd {} {}", getName(), data.toString());
// filters on only our speech
if (utterances.containsKey(data)) {
String utterance = utterances.get(data);
invoke("publishEndSpeaking", utterance);
utterances.remove(data);
}
}
@Override
public boolean speakBlocking(String toSpeak) throws Exception {
cacheFile(toSpeak, OutputFormat.Mp3);
invoke("publishStartSpeaking", toSpeak);
audioFile.playBlocking(AudioFile.globalFileCacheDir + File.separator + getLocalFileName(this, toSpeak, "mp3"));
invoke("publishEndSpeaking", toSpeak);
return false;
}
@Override
public void setVolume(float volume) {
audioFile.setVolume(volume);
}
@Override
public float getVolume() {
return audioFile.getVolume();
}
@Override
public void interrupt() {
// TODO Auto-generated method stub
}
@Override
public String getVoice() {
getPolly();
return voice;
}
@Override
public String getLocalFileName(SpeechSynthesis provider, String toSpeak, String audioFileType) throws UnsupportedEncodingException {
// TODO: make this a base class sort of thing.
getPolly();
// having - AudioFile.globalFileCacheDir exposed like this is a bad idea ..
// AudioFile should just globallyCache - the details of that cache should not be exposed :(
return provider.getClass().getSimpleName() + File.separator + URLEncoder.encode(provider.getVoice(), "UTF-8") + File.separator + DigestUtils.md5Hex(toSpeak) + "."
+ audioFileType;
}
// can this be defaulted ?
@Override
public void addEar(SpeechRecognizer ear) {
// TODO Auto-generated method stub
}
@Override
public void onRequestConfirmation(String text) {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Polly.class.getCanonicalName());
meta.addDescription("used as a general template");
meta.setAvailable(true); // false if you do not want it viewable in a
// gui
// add dependency if necessary
meta.addPeer("audioFile", "AudioFile", "audioFile");
meta.addDependency("org.joda", "2.9.4");
meta.addDependency("org.apache.commons.httpclient", "4.5.2");
meta.addDependency("com.amazonaws.services", "1.11.118");
meta.addCategory("speech");
return meta;
}
public void startService() {
super.startService();
audioFile = (AudioFile) startPeer("audioFile");
audioFile.startService();
subscribe(audioFile.getName(), "publishAudioStart");
subscribe(audioFile.getName(), "publishAudioEnd");
// attach a listener when the audio file ends playing.
audioFile.addListener("finishedPlaying", this.getName(), "publishEndSpeaking");
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Polly polly = (Polly) Runtime.start("polly", "Polly");
// add your amazon access key & secret
polly.setKey("{AWS_ACCESS_KEY_ID}", "{AWS_SECRET_ACCESS_KEY}");
List<String> voices = polly.getVoices();
for (String voice : voices) {
polly.setVoice(voice);
String lang = polly.getLanguage();
log.info("{} speaks {}", voice, lang);
if (lang.startsWith("es")) {
polly.speak(String.format("Hola, mi nombre es %s y creo que myrobotlab es genial!", voice));
} else if (lang.startsWith("en")) {
polly.speak(String.format("Hi my name is %s and I think myrobotlab is great!", voice));
} else if (lang.startsWith("fr")) {
polly.speak(String.format("Bonjour, mon nom est %s et je pense que myrobotlab est génial!!", voice));
} else if (lang.startsWith("nl")) {
polly.speak(String.format("Hallo, mijn naam is %s en ik denk dat myrobotlab is geweldig!", voice));
} else if (lang.startsWith("ru")) {
polly.speak(String.format("Привет, меня зовут %s, и я думаю, что myrobotlab - это здорово!", voice));
} else if (lang.startsWith("ro")){
polly.speak(String.format("Buna ziua, numele meu este %s și cred că myrobotlab este mare!", voice));
} else if (lang.startsWith("ro")){
polly.speak(String.format("Witam, nazywam się %s i myślę, że myrobotlab jest świetny!", voice));
} else if (lang.startsWith("it")){
polly.speak(String.format("Ciao, il mio nome è %s e penso myrobotlab è grande!", voice));
} else if (lang.startsWith("is")){
polly.speak(String.format("Halló, Nafn mitt er %s og ég held myrobotlab er frábært!", voice));
} else if (lang.startsWith("cy")){
polly.speak(String.format("Helo, fy enw i yw %s a fi yn meddwl myrobotlab yn wych!", voice));
} else if (lang.startsWith("de")){
polly.speak(String.format("Hallo, mein Name ist %s und ich denke, myrobotlab ist toll!", voice));
} else if (lang.startsWith("da")){
polly.speak(String.format("Hej, mit navn er %s og jeg tror myrobotlab er fantastisk!", voice));
} else if (lang.startsWith("sv")){
polly.speak(String.format("Hej, mitt namn %s och jag tror ElektronikWikin är stor!", voice));
} else if (lang.startsWith("pl")){
polly.speak(String.format("Witam, nazywam się %s i myślę, że myrobotlab jest świetny!", voice));
} else if (lang.startsWith("tr")){
polly.speak(String.format("Merhaba, adım adım %s ve myrobotlab'ın harika olduğunu düşünüyorum!", voice));
} else if (lang.startsWith("pt")){
polly.speak(String.format("Olá, meu nome é %s e eu acho que myrobotlab é ótimo!!", voice));
} else if (lang.startsWith("ja")){
polly.speak(String.format("こんにちは、私の名前は%sで、私はmyrobotlabが素晴らしいと思います!", voice));
} else {
log.info("dunno");
}
}
polly.setVoice("Russel");
polly.setVoice("Nicole");
polly.setVoice("Brian");
polly.setVoice("Amy");
polly.setVoice("Emma");
polly.setVoice("Brian");
polly.setVoice("Kimberly");
polly.setVoice("Justin");
polly.setVoice("Joey");
polly.setVoice("Raveena");
polly.setVoice("Ivy");
polly.setVoice("Kendra");
polly.speak("this is a new thing");
polly.speak("Hello there, i am a cloud service .. i probably sound like the echo");
polly.speak("Here is another sentence");
polly.speak("To be or not to be that is the question");
polly.speakBlocking("now i am blocking my speech");
polly.speakBlocking("put one foot in front of the other and");
// xxx
polly.speakBlocking("soon you'll be walking out the door");
polly.speak("this is a new sentence");
polly.speak("to be or not to be that is the question");
polly.speak("weather tis nobler in the mind to suffer");
polly.speak("the slings and arrows of ourtrageous fortune");
polly.speak("or to take arms against a see of troubles");
} catch (Exception e) {
log.error("Polly main threw", e);
}
}
}
| Navi-nk/Bernard-InMoov | myrobotlab/src/org/myrobotlab/service/Polly.java | 5,430 | // set default voice | line_comment | nl | package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.commons.codec.digest.DigestUtils;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.AudioData;
import org.myrobotlab.service.interfaces.AudioListener;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.slf4j.Logger;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.polly.AmazonPollyClient;
import com.amazonaws.services.polly.AmazonPollyClientBuilder;
import com.amazonaws.services.polly.model.DescribeVoicesRequest;
import com.amazonaws.services.polly.model.DescribeVoicesResult;
import com.amazonaws.services.polly.model.OutputFormat;
import com.amazonaws.services.polly.model.SynthesizeSpeechRequest;
import com.amazonaws.services.polly.model.SynthesizeSpeechResult;
import com.amazonaws.services.polly.model.Voice;
/**
* Amazon's cloud speech service
*
* Free Tier The Amazon Polly free tier includes 5 million characters per month,
* for the first 12 months, starting from the first request for speech.
*
* Polly Pricing Pay-as-you-go $4.00 per 1 million characters (when outside the
* free tier).
*
* @author gperry
*
*/
public class Polly extends Service implements SpeechSynthesis, AudioListener {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Polly.class);
transient AWSCredentials credentials;
transient AmazonPollyClient polly;
transient Voice awsVoice;
transient List<Voice> awsVoices;
// this is a peer service.
transient AudioFile audioFile = null;
transient Map<String, Voice> voiceMap = new HashMap<String, Voice>();
transient Map<String, Voice> langMap = new HashMap<String, Voice>();
String voice;
Stack<String> audioFiles = new Stack<String>();
private String keyIdSecret;
private String keyId;
transient HashMap<AudioData, String> utterances = new HashMap<AudioData, String>();
String lang;
public Polly(String n) {
super(n);
}
public void setKey(String keyId, String keyIdSecret) {
this.keyId = keyId;
this.keyIdSecret = keyIdSecret;
}
@Override
public List<String> getVoices() {
getPolly();
return new ArrayList<String>(voiceMap.keySet());
}
@Override
public boolean setVoice(String voice) {
getPolly();
if (voiceMap.containsKey(voice)) {
log.info("setting voice to {}", voice);
awsVoice = voiceMap.get(voice);
this.voice = voice;
this.lang = awsVoice.getLanguageCode();
return true;
}
log.info("could not set voice to {}", voice);
return false;
}
@Override
public void setLanguage(String l) {
if (langMap.containsKey(l)) {
setVoice(langMap.get(l).getName());
}
}
@Override
public String getLanguage() {
return lang;
}
@Override
public List<String> getLanguages() {
return new ArrayList<String>(langMap.keySet());
}
/**
* Proxy works in 3 modes
* client - consumer of mrl services
* relay - proxy (running as cloud service)
* direct - goes direct to service
* In Polly's case -
* client - would be an end user using a client key
* relay - is the mrl proxy service
* direct would be from a users, by-passing mrl and going directly to Amazon with amazon keys
* cache file - caches file locally (both client or relay)
* @param toSpeak
* @param format
* @throws IOException
*/
public byte[] cacheFile(String toSpeak, OutputFormat format) throws IOException {
byte[] mp3File = null;
// cache it begin -----
String localFileName = getLocalFileName(this, toSpeak, "mp3");
// String filename = AudioFile.globalFileCacheDir + File.separator +
// localFileName;
if (!audioFile.cacheContains(localFileName)) {
log.info("retrieving speech from Amazon - {}", localFileName);
AmazonPollyClient polly = getPolly();
SynthesizeSpeechRequest synthReq = new SynthesizeSpeechRequest().withText(toSpeak).withVoiceId(awsVoice.getId()).withOutputFormat(format);
SynthesizeSpeechResult synthRes = polly.synthesizeSpeech(synthReq);
InputStream data = synthRes.getAudioStream();
mp3File = FileIO.toByteArray(data);
audioFile.cache(localFileName, mp3File, toSpeak);
} else {
log.info("using local cached file");
mp3File = FileIO.toByteArray(new File(AudioFile.globalFileCacheDir + File.separator + getLocalFileName(this, toSpeak, "mp3")));
}
// invoke("publishStartSpeaking", toSpeak);
// audioFile.playBlocking(filename);
// invoke("publishEndSpeaking", toSpeak);
// log.info("Finished waiting for completion.");
return mp3File;
}
@Override
public AudioData speak(String toSpeak) throws Exception {
cacheFile(toSpeak, OutputFormat.Mp3);
AudioData audioData = audioFile.playCachedFile(getLocalFileName(this, toSpeak, "mp3"));
utterances.put(audioData, toSpeak);
return audioData;
/*
* InputStream speechStream = synthesize(toSpeak, OutputFormat.Mp3); //
* create an MP3 player AdvancedPlayer player = new
* AdvancedPlayer(speechStream,
* javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice());
*
* player.setPlayBackListener(new PlaybackListener() {
*
* @Override public void playbackStarted(PlaybackEvent evt) {
* System.out.println("Playback started"); System.out.println(toSpeak); }
*
* @Override public void playbackFinished(PlaybackEvent evt) {
* System.out.println("Playback finished"); } });
*
* // play it! player.play();
*/
}
private void processVoicesRequest() {
// Create describe voices request.
DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
// Synchronously ask Polly Polly to describe available TTS voices.
DescribeVoicesResult describeVoicesResult = polly.describeVoices(describeVoicesRequest);
awsVoices = describeVoicesResult.getVoices();
log.info("found {} voices", awsVoices.size());
for (int i = 0; i < awsVoices.size(); ++i) {
Voice voice = awsVoices.get(i);
voiceMap.put(voice.getName(), voice);
langMap.put(voice.getLanguageCode(), voice);
log.info("{} {} - {}", i, voice.getName(), voice.getLanguageCode());
}
// set default<SUF>
if (voice == null) {
voice = awsVoices.get(0).getName();
awsVoice = awsVoices.get(0);
lang = awsVoice.getLanguageCode();
log.info("setting default voice to {}", voice);
}
}
private AmazonPollyClient getPolly() {
if (polly == null) {
try {
// AWSCredentials creds = new
// BasicAWSCredentials("AKIAJGL6AEN37LDO3N7A", "secret-access-key");
if (credentials == null) {
// try credential chain - in case they have set env vars
credentials = new BasicAWSCredentials(keyId, keyIdSecret);
}
// polly = (AmazonPollyClient)
// AmazonPollyClientBuilder.standard().withCredentials(new
// AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build();
polly = (AmazonPollyClient) AmazonPollyClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_WEST_2).build();
processVoicesRequest();
} catch (Exception e) {
try {
log.error("could not get client with keys supplied - trying default chain", e);
polly = new AmazonPollyClient(new DefaultAWSCredentialsProviderChain(), new ClientConfiguration());
// polly.setRegion(Region.getRegion(Regions.US_EAST_1));
polly.setRegion(Region.getRegion(Regions.US_WEST_2));
processVoicesRequest();
} catch (Exception e2) {
error("could not get Polly client - did you setKeys ?");
error("Environment variables – AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY or");
error("check http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html");
log.error("giving up", e2);
}
}
}
return polly;
}
@Override
public String publishStartSpeaking(String utterance) {
log.info("publishStartSpeaking {}", utterance);
return utterance;
}
@Override
public String publishEndSpeaking(String utterance) {
log.info("publishEndSpeaking {}", utterance);
return utterance;
}
@Override
public void onAudioStart(AudioData data) {
log.info("onAudioStart {} {}", getName(), data.toString());
// filters on only our speech
if (utterances.containsKey(data)) {
String utterance = utterances.get(data);
invoke("publishStartSpeaking", utterance);
}
}
@Override
public void onAudioEnd(AudioData data) {
log.info("onAudioEnd {} {}", getName(), data.toString());
// filters on only our speech
if (utterances.containsKey(data)) {
String utterance = utterances.get(data);
invoke("publishEndSpeaking", utterance);
utterances.remove(data);
}
}
@Override
public boolean speakBlocking(String toSpeak) throws Exception {
cacheFile(toSpeak, OutputFormat.Mp3);
invoke("publishStartSpeaking", toSpeak);
audioFile.playBlocking(AudioFile.globalFileCacheDir + File.separator + getLocalFileName(this, toSpeak, "mp3"));
invoke("publishEndSpeaking", toSpeak);
return false;
}
@Override
public void setVolume(float volume) {
audioFile.setVolume(volume);
}
@Override
public float getVolume() {
return audioFile.getVolume();
}
@Override
public void interrupt() {
// TODO Auto-generated method stub
}
@Override
public String getVoice() {
getPolly();
return voice;
}
@Override
public String getLocalFileName(SpeechSynthesis provider, String toSpeak, String audioFileType) throws UnsupportedEncodingException {
// TODO: make this a base class sort of thing.
getPolly();
// having - AudioFile.globalFileCacheDir exposed like this is a bad idea ..
// AudioFile should just globallyCache - the details of that cache should not be exposed :(
return provider.getClass().getSimpleName() + File.separator + URLEncoder.encode(provider.getVoice(), "UTF-8") + File.separator + DigestUtils.md5Hex(toSpeak) + "."
+ audioFileType;
}
// can this be defaulted ?
@Override
public void addEar(SpeechRecognizer ear) {
// TODO Auto-generated method stub
}
@Override
public void onRequestConfirmation(String text) {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Polly.class.getCanonicalName());
meta.addDescription("used as a general template");
meta.setAvailable(true); // false if you do not want it viewable in a
// gui
// add dependency if necessary
meta.addPeer("audioFile", "AudioFile", "audioFile");
meta.addDependency("org.joda", "2.9.4");
meta.addDependency("org.apache.commons.httpclient", "4.5.2");
meta.addDependency("com.amazonaws.services", "1.11.118");
meta.addCategory("speech");
return meta;
}
public void startService() {
super.startService();
audioFile = (AudioFile) startPeer("audioFile");
audioFile.startService();
subscribe(audioFile.getName(), "publishAudioStart");
subscribe(audioFile.getName(), "publishAudioEnd");
// attach a listener when the audio file ends playing.
audioFile.addListener("finishedPlaying", this.getName(), "publishEndSpeaking");
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Polly polly = (Polly) Runtime.start("polly", "Polly");
// add your amazon access key & secret
polly.setKey("{AWS_ACCESS_KEY_ID}", "{AWS_SECRET_ACCESS_KEY}");
List<String> voices = polly.getVoices();
for (String voice : voices) {
polly.setVoice(voice);
String lang = polly.getLanguage();
log.info("{} speaks {}", voice, lang);
if (lang.startsWith("es")) {
polly.speak(String.format("Hola, mi nombre es %s y creo que myrobotlab es genial!", voice));
} else if (lang.startsWith("en")) {
polly.speak(String.format("Hi my name is %s and I think myrobotlab is great!", voice));
} else if (lang.startsWith("fr")) {
polly.speak(String.format("Bonjour, mon nom est %s et je pense que myrobotlab est génial!!", voice));
} else if (lang.startsWith("nl")) {
polly.speak(String.format("Hallo, mijn naam is %s en ik denk dat myrobotlab is geweldig!", voice));
} else if (lang.startsWith("ru")) {
polly.speak(String.format("Привет, меня зовут %s, и я думаю, что myrobotlab - это здорово!", voice));
} else if (lang.startsWith("ro")){
polly.speak(String.format("Buna ziua, numele meu este %s și cred că myrobotlab este mare!", voice));
} else if (lang.startsWith("ro")){
polly.speak(String.format("Witam, nazywam się %s i myślę, że myrobotlab jest świetny!", voice));
} else if (lang.startsWith("it")){
polly.speak(String.format("Ciao, il mio nome è %s e penso myrobotlab è grande!", voice));
} else if (lang.startsWith("is")){
polly.speak(String.format("Halló, Nafn mitt er %s og ég held myrobotlab er frábært!", voice));
} else if (lang.startsWith("cy")){
polly.speak(String.format("Helo, fy enw i yw %s a fi yn meddwl myrobotlab yn wych!", voice));
} else if (lang.startsWith("de")){
polly.speak(String.format("Hallo, mein Name ist %s und ich denke, myrobotlab ist toll!", voice));
} else if (lang.startsWith("da")){
polly.speak(String.format("Hej, mit navn er %s og jeg tror myrobotlab er fantastisk!", voice));
} else if (lang.startsWith("sv")){
polly.speak(String.format("Hej, mitt namn %s och jag tror ElektronikWikin är stor!", voice));
} else if (lang.startsWith("pl")){
polly.speak(String.format("Witam, nazywam się %s i myślę, że myrobotlab jest świetny!", voice));
} else if (lang.startsWith("tr")){
polly.speak(String.format("Merhaba, adım adım %s ve myrobotlab'ın harika olduğunu düşünüyorum!", voice));
} else if (lang.startsWith("pt")){
polly.speak(String.format("Olá, meu nome é %s e eu acho que myrobotlab é ótimo!!", voice));
} else if (lang.startsWith("ja")){
polly.speak(String.format("こんにちは、私の名前は%sで、私はmyrobotlabが素晴らしいと思います!", voice));
} else {
log.info("dunno");
}
}
polly.setVoice("Russel");
polly.setVoice("Nicole");
polly.setVoice("Brian");
polly.setVoice("Amy");
polly.setVoice("Emma");
polly.setVoice("Brian");
polly.setVoice("Kimberly");
polly.setVoice("Justin");
polly.setVoice("Joey");
polly.setVoice("Raveena");
polly.setVoice("Ivy");
polly.setVoice("Kendra");
polly.speak("this is a new thing");
polly.speak("Hello there, i am a cloud service .. i probably sound like the echo");
polly.speak("Here is another sentence");
polly.speak("To be or not to be that is the question");
polly.speakBlocking("now i am blocking my speech");
polly.speakBlocking("put one foot in front of the other and");
// xxx
polly.speakBlocking("soon you'll be walking out the door");
polly.speak("this is a new sentence");
polly.speak("to be or not to be that is the question");
polly.speak("weather tis nobler in the mind to suffer");
polly.speak("the slings and arrows of ourtrageous fortune");
polly.speak("or to take arms against a see of troubles");
} catch (Exception e) {
log.error("Polly main threw", e);
}
}
}
|
34869_1 | package exercise05_01;
public class TypeConversie {
public static void main(String[] args) {
boolean aBoolean = false; // variable types: var
char aCharacter = 'd';
byte aByte = 124;
short aShortInteger = 115; // probeer voor deze variable 0342 -octaal 0x78b 0x54_4 0x78 - hexadecimaal 0b101100111 binair
int anInteger = 67;
long aLongInteger = 45631341L;
float aDecimalnumber = 1256.32F;
double aBigDecimalNumber = 12.365987451236;
final double PI=3.14;
// PI=3.15; Cannot assign again a value to final variable 'PI'
// aByte=aShortInteger; not possiable
aByte=(byte) aShortInteger;
System.out.println(aByte);
aShortInteger=(short) aCharacter;
aByte=(byte) aCharacter;
System.out.println(aShortInteger);
System.out.println(aByte);
aCharacter=(char) anInteger;
System.out.println(aCharacter);
for (int i=0;i<200;i++) {
char a=(char) i;
System.out.println(a);
}
char b='※';
int a=b;
System.out.println(a);
}
}
| NazifAltintas/JavaFundamentals | src/exercise05_01/TypeConversie.java | 377 | // probeer voor deze variable 0342 -octaal 0x78b 0x54_4 0x78 - hexadecimaal 0b101100111 binair | line_comment | nl | package exercise05_01;
public class TypeConversie {
public static void main(String[] args) {
boolean aBoolean = false; // variable types: var
char aCharacter = 'd';
byte aByte = 124;
short aShortInteger = 115; // probeer voor<SUF>
int anInteger = 67;
long aLongInteger = 45631341L;
float aDecimalnumber = 1256.32F;
double aBigDecimalNumber = 12.365987451236;
final double PI=3.14;
// PI=3.15; Cannot assign again a value to final variable 'PI'
// aByte=aShortInteger; not possiable
aByte=(byte) aShortInteger;
System.out.println(aByte);
aShortInteger=(short) aCharacter;
aByte=(byte) aCharacter;
System.out.println(aShortInteger);
System.out.println(aByte);
aCharacter=(char) anInteger;
System.out.println(aCharacter);
for (int i=0;i<200;i++) {
char a=(char) i;
System.out.println(a);
}
char b='※';
int a=b;
System.out.println(a);
}
}
|
74030_2 | package be.intecbrussel;
import java.util.Scanner;
public class BasicProgrammingApp {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter 4 getal.");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
int num3 = scan.nextInt();
int num4 = scan.nextInt();
// Print het grootste getal.
int grootsteGetal = num1;
if (num2 > grootsteGetal) {
grootsteGetal = num2;
}
if (num3 > grootsteGetal) {
grootsteGetal = num3;
}
if (num4 > grootsteGetal) {
grootsteGetal = num4;
}
System.out.println("Grootstegetal is: " + grootsteGetal);
// Print het kleinste getal.
int kleinsteGetal = num1;
if (num2 < kleinsteGetal) {
kleinsteGetal = num2;
}
if (num3 < kleinsteGetal) {
kleinsteGetal = num3;
}
if (num4 < kleinsteGetal) {
kleinsteGetal = num4;
}
System.out.println("Kleinstegetal is: " + kleinsteGetal);
// Print alle getallen van het kleinste getal tot het gemiddelde van de 4 getallen.
int gemiddelde = (num1 + num2 + num3 + num4) / 4;
System.out.println("Alle getallen van het kleinste getal tot het gemiddelde van de 4 getallen:");
for (int i = kleinsteGetal; i <= gemiddelde; i++) {
System.out.print(i);
if (i < gemiddelde) {
System.out.print(",");
}
}
System.out.println("");
// Print alle getallen van 0 tot 2000 maar wanneer het een van de 4 getallen tegenkomt, stopt de loop.
System.out.println("Alle getallen van 0 tot 2000 maar wanneer het een van de 4 getallen tegenkomt.");
for (int j = 0; j < 2000; j++) {
System.out.print(j);
int count = 0;
if (j == num1 || j == num2 || j == num3 || j == num4) {
count = 1;
break;
}
if (count == 0) {
System.out.print(",");
}
}
// Print alle getallen van 0 tot 100, van groot naar klein EN klein naar groot in afwisselende volgorde.
System.out.println("");
System.out.println("Alle getallen van 0 tot 100, van groot naar klein EN klein naar groot in afwisselende volgorde.");
int l=0;
for (int k=99;k>=0;k--) {
System.out.print(k+"-"+l);
l++;
if (l<=99){
System.out.print("-");
}
}
scan.close();
}
}
| NazifAltintas/Nazif_Altintas_test_basisprogrameren | src/be/intecbrussel/BasicProgrammingApp.java | 844 | // Print alle getallen van het kleinste getal tot het gemiddelde van de 4 getallen. | line_comment | nl | package be.intecbrussel;
import java.util.Scanner;
public class BasicProgrammingApp {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter 4 getal.");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
int num3 = scan.nextInt();
int num4 = scan.nextInt();
// Print het grootste getal.
int grootsteGetal = num1;
if (num2 > grootsteGetal) {
grootsteGetal = num2;
}
if (num3 > grootsteGetal) {
grootsteGetal = num3;
}
if (num4 > grootsteGetal) {
grootsteGetal = num4;
}
System.out.println("Grootstegetal is: " + grootsteGetal);
// Print het kleinste getal.
int kleinsteGetal = num1;
if (num2 < kleinsteGetal) {
kleinsteGetal = num2;
}
if (num3 < kleinsteGetal) {
kleinsteGetal = num3;
}
if (num4 < kleinsteGetal) {
kleinsteGetal = num4;
}
System.out.println("Kleinstegetal is: " + kleinsteGetal);
// Print alle<SUF>
int gemiddelde = (num1 + num2 + num3 + num4) / 4;
System.out.println("Alle getallen van het kleinste getal tot het gemiddelde van de 4 getallen:");
for (int i = kleinsteGetal; i <= gemiddelde; i++) {
System.out.print(i);
if (i < gemiddelde) {
System.out.print(",");
}
}
System.out.println("");
// Print alle getallen van 0 tot 2000 maar wanneer het een van de 4 getallen tegenkomt, stopt de loop.
System.out.println("Alle getallen van 0 tot 2000 maar wanneer het een van de 4 getallen tegenkomt.");
for (int j = 0; j < 2000; j++) {
System.out.print(j);
int count = 0;
if (j == num1 || j == num2 || j == num3 || j == num4) {
count = 1;
break;
}
if (count == 0) {
System.out.print(",");
}
}
// Print alle getallen van 0 tot 100, van groot naar klein EN klein naar groot in afwisselende volgorde.
System.out.println("");
System.out.println("Alle getallen van 0 tot 100, van groot naar klein EN klein naar groot in afwisselende volgorde.");
int l=0;
for (int k=99;k>=0;k--) {
System.out.print(k+"-"+l);
l++;
if (l<=99){
System.out.print("-");
}
}
scan.close();
}
}
|
28777_1 | public class HelloWorldMultilingual {
/***************************************************************************
*
* Prints "Hello World!".
* By tradition, this is everyone's first program.
* It was first written by Brian Kernighan in 1974 at Bell Labs.
*
* This programs also prints "Hello World!" in 147 other languages.
* The translations are compiled from Google Translate, an article
* by Manoj Ahirwar, and Fun Translations.
*
* https://translate.google.com
* https://medium.com/illumination/hello-world-in-human-languages-18282994b887
* https://funtranslations.com
*
* To suggest improvements to this file (e.g., a more accurate translation
* or a new language), please email [email protected].
*
**************************************************************************/
public static void main(String[] args) {
System.out.println("Hello World!"); // English
System.out.println("Hallo Wêreld!"); // Afrikaans
System.out.println("Përshendetje Botë!"); // Albanian
System.out.println("ሰላም ልዑል!"); // Amharic
System.out.println("مرحبا بالعالم!"); // Arabic
System.out.println("Բարեւ աշխարհ!"); // Armenian
System.out.println("নমস্কাৰ বিশ্ব!"); // Assamese
System.out.println("¡Aski urukipanaya Uraqpacha!"); // Aymara
System.out.println("Salam Dünya!"); // Azerbaijani
System.out.println("Bonjour Diɲɛ!"); // Bambara
System.out.println("Kaixo Mundua!"); // Basque
System.out.println("Прывітанне Сусвет!"); // Belarusian
System.out.println("Shani Mwechalo!"); // Bemba
System.out.println("ওহে বিশ্ব!"); // Bengali
System.out.println("नमस्कार दुनिया के बा!"); // Bhojpuri
System.out.println("Zdravo Svijete!"); // Bosnian
System.out.println("⠠⠓⠑⠇⠇⠕ ⠠⠺⠕⠗⠇⠙⠖"); // Braille
System.out.println("Здравей свят!"); // Bulgarian
System.out.println("Hola món!"); // Catalan
System.out.println("ជំរាបសួរ ពិភពលោក!"); // Cambodian
System.out.println("Hello Kalibutan!"); // Cebuano
System.out.println("ᎣᏏᏲ ᎡᎶᎯ"); // Cherokee
System.out.println("Moni Dziko Lapansi!"); // Chichewa
System.out.println("世界您好!"); // Chinese
System.out.println("Wawa Klahowya Hayas Klaska"); // Chinook
System.out.println("Salutu Munnu!"); // Corsican
System.out.println("Pozdrav Svijete!"); // Croatian
System.out.println("Ahoj Světe!"); // Czech
System.out.println("Hej Verden!"); // Danish
System.out.println("ހެލޯ ވޯލްޑް!"); // Dhivehi
System.out.println("नमस्कार दुनिया !"); // Dogri
System.out.println("Hello Rhaesheser!"); // Dothraki
System.out.println("Hallo Wereld!"); // Dutch
System.out.println("👋🌎"); // Emoji
System.out.println("Saluton mondo!"); // Esperanto
System.out.println("Tere Maailm!"); // Estonian
System.out.println("Mido gbe na Xexeame!"); // Ewe
System.out.println("Hello Mundo!"); // Filipino
System.out.println("Hei maailma!"); // Finnish
System.out.println("Salut le monde!"); // French
System.out.println("Hallo wrâld!"); // Frisian
System.out.println("Ola mundo!"); // Galician
System.out.println("გამარჯობა სამყაროს!"); // Georgian
System.out.println("Hallo Welt!"); // German
System.out.println("Γειά σου Κόσμε!"); // Greek
System.out.println("Maitei Mundo!"); // Guarani
System.out.println("હેલો વર્લ્ડ!"); // Gujarati
System.out.println("Bonjou mond!"); // Haitian Creole
System.out.println("Sannu Duniya!"); // Hausa
System.out.println("Aloha Honua!"); // Hawaiian
System.out.println("שלום עולם!"); // Hebrew
System.out.println("नमस्ते दुनिया!"); // Hindi
System.out.println("Nyob zoo ntiaj teb!"); // Hmong
System.out.println("Helló Világ!"); // Hungarian
System.out.println("Halló heimur!"); // Icelandic
System.out.println("Ndewo Ụwa!"); // Igbo
System.out.println("Hello Lubong!"); // Ilocano
System.out.println("Halo Dunia!"); // Indonesian
System.out.println("Dia duit Domhanda!"); // Irish
System.out.println("Ciao Mondo!"); // Italian
System.out.println("こんにちは、 世界!"); // Japanese
System.out.println("Halo Donya!"); // Javanese
System.out.println("ಹಲೋ ವರ್ಲ್ಡ್!"); // Kannada
System.out.println("Сәлем Әлем!"); // Kazakh
System.out.println("សួស្តីពិភពលោក!"); // Khmer
System.out.println("Mwaramutse Isi!"); // Kinyarwanda
System.out.println("Habari dunia!"); // Kiswahili
System.out.println("qo' Vivan!"); // Klingon
System.out.println("नमस्कार संवसार!"); // Konkani
System.out.println("안녕하세요 월드입니다!"); // Korean
System.out.println("Halo Wɔl"); // Krio
System.out.println("Silav Cîhan!"); // Kurdish (Kurmanji)
System.out.println("سڵاو جیهان!"); // Kurdish (Sorani)
System.out.println("Салам дүйнө!"); // Kyrgyz
System.out.println("ສະບາຍດີຊາວໂລກ!"); // Lao
System.out.println("salve mundi!"); // Latin
System.out.println("Sveika Pasaule!"); // Latvian
System.out.println("h3l1O W()rL|)!"); // Leet / H4X0R Slang
System.out.println("Mbote Mokili!"); // Lingala
System.out.println("Sveikas Pasauli!"); // Lithuanian
System.out.println("coi li terdi!"); // Lojban
System.out.println("Mwasuze Mutya Ensi!"); // Luganda
System.out.println("Moien Welt!"); // Luxembourgish
System.out.println("Здраво свету!"); // Macedonian
System.out.println("नमस्कार दुनिया!"); // Maithili
System.out.println("Manahoana izao tontolo izao!"); // Malagasy
System.out.println("Hai dunia!"); // Malay
System.out.println("ഹലോ വേൾഡ്!"); // Malayalam
System.out.println("Ħello dinja!"); // Maltese
System.out.println("Kia ora te Ao!"); // Maori
System.out.println("हॅलो वर्ल्ड!"); // Marathi
System.out.println("ꯍꯜꯂꯣꯏ ꯃꯥꯂꯦꯝ!"); // Meiteilon (Manipuri)
System.out.println("Bello Globo!"); // Minions Speak
System.out.println("Hello Khawvel!"); // Mizo
System.out.println("Сайн уу Дэлхий!"); // Mongolian
System.out.println(".... . .-.. .-.. --- .-- --- .-. .-.. -.. ---."); // Morse Code
System.out.println("မင်္ဂလာပါကမ္ဘာလောက!"); // Myanmar (Burmese)
System.out.println("नमस्कार संसार!"); // Nepali
System.out.println("Hallo Verden!"); // Norwegian
System.out.println("ନମସ୍କାର ବିଶ୍ୱବାସି!"); // Odia (Oriya)
System.out.println("Akkam jirtu Addunyaa!"); // Oromo
System.out.println("!سلام نړی"); // Pashto
System.out.println("!سلام دنیا"); // Persian
System.out.println("Ellohay Orldway!"); // Pig Latin
System.out.println("Witaj świecie!"); // Polish
System.out.println("Olá Mundo!"); // Portuguese
System.out.println("ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ ਦੁਨਿਆ!"); // Punjabi
System.out.println("Hola Mundo!"); // Quechua
System.out.println("Salut Lume!"); // Romanian
System.out.println("Здравствуй мир!"); // Russian
System.out.println("Talofa le Lalolagi!"); // Samoan
System.out.println("नमस्कार विश्व!"); // Sanskrit
System.out.println("Halò a Shaoghail!"); // Scots Gaelic
System.out.println("Thobela Lefase!"); // Sepedi
System.out.println("Здраво Свете!"); // Serbian
System.out.println("Lefatše Lumela!"); // Sesotho
System.out.println("Mhoro Nyika!"); // Shona
System.out.println("هيلو دنيا!"); // Sindhi
System.out.println("හෙලෝ වර්ල්ඩ්!"); // Sinhala
System.out.println("Ahoj svet!"); // Slovak
System.out.println("Pozdravljen svet!"); // Slovenian
System.out.println("Salaamu Calaykum!"); // Somali
System.out.println("¡Hola Mundo!"); // Spanish
System.out.println("Halo Dunya!"); // Sundanese
System.out.println("Salamu Dunia!"); // Swahili
System.out.println("Hallå världen!"); // Swedish
System.out.println("Kamusta mundo!"); // Tagalog
System.out.println("Салом Ҷаҳон!"); // Tajik
System.out.println("ஹலோ உலகம்!"); // Tamil
System.out.println("Сәлам, Дөнья!"); // Tatar
System.out.println("హలో వరల్డ్!"); // Telugu
System.out.println("สวัสดีโลก!"); // Thai
System.out.println("ሰላም ዓለም!"); // Tigrinya
System.out.println("Xewani Misava!"); // Tsonga
System.out.println("Merhaba Dünya!"); // Turkish
System.out.println("Salam Dünýä!"); // Turkmen
System.out.println("Hello Wiase!"); // Twi
System.out.println("Привіт Світ!"); // Ukranian
System.out.println("ہیلو دنیا والو"); // Urdu
System.out.println("ياخشىمۇسىز دۇنيا!"); // Uyghur
System.out.println("Salom Dunyo!"); // Uzbek
System.out.println("Rytsas Vys!"); // Valyrian
System.out.println("Xin chào thế giới!"); // Vietnamese
System.out.println("Helô Byd!"); // Welsh
System.out.println("Molo Lizwe!"); // Xhosa
System.out.println("העלא וועלט!"); // Yiddish
System.out.println("Mo ki O Ile Aiye!"); // Yoruba
System.out.println("Sawubona Mhlaba!"); // Zulu
}
}
| NazifAltintas/codes-princeteon | programming-assignment/HelloWorldMultilingual.java | 3,654 | // Leet / H4X0R Slang | line_comment | nl | public class HelloWorldMultilingual {
/***************************************************************************
*
* Prints "Hello World!".
* By tradition, this is everyone's first program.
* It was first written by Brian Kernighan in 1974 at Bell Labs.
*
* This programs also prints "Hello World!" in 147 other languages.
* The translations are compiled from Google Translate, an article
* by Manoj Ahirwar, and Fun Translations.
*
* https://translate.google.com
* https://medium.com/illumination/hello-world-in-human-languages-18282994b887
* https://funtranslations.com
*
* To suggest improvements to this file (e.g., a more accurate translation
* or a new language), please email [email protected].
*
**************************************************************************/
public static void main(String[] args) {
System.out.println("Hello World!"); // English
System.out.println("Hallo Wêreld!"); // Afrikaans
System.out.println("Përshendetje Botë!"); // Albanian
System.out.println("ሰላም ልዑል!"); // Amharic
System.out.println("مرحبا بالعالم!"); // Arabic
System.out.println("Բարեւ աշխարհ!"); // Armenian
System.out.println("নমস্কাৰ বিশ্ব!"); // Assamese
System.out.println("¡Aski urukipanaya Uraqpacha!"); // Aymara
System.out.println("Salam Dünya!"); // Azerbaijani
System.out.println("Bonjour Diɲɛ!"); // Bambara
System.out.println("Kaixo Mundua!"); // Basque
System.out.println("Прывітанне Сусвет!"); // Belarusian
System.out.println("Shani Mwechalo!"); // Bemba
System.out.println("ওহে বিশ্ব!"); // Bengali
System.out.println("नमस्कार दुनिया के बा!"); // Bhojpuri
System.out.println("Zdravo Svijete!"); // Bosnian
System.out.println("⠠⠓⠑⠇⠇⠕ ⠠⠺⠕⠗⠇⠙⠖"); // Braille
System.out.println("Здравей свят!"); // Bulgarian
System.out.println("Hola món!"); // Catalan
System.out.println("ជំរាបសួរ ពិភពលោក!"); // Cambodian
System.out.println("Hello Kalibutan!"); // Cebuano
System.out.println("ᎣᏏᏲ ᎡᎶᎯ"); // Cherokee
System.out.println("Moni Dziko Lapansi!"); // Chichewa
System.out.println("世界您好!"); // Chinese
System.out.println("Wawa Klahowya Hayas Klaska"); // Chinook
System.out.println("Salutu Munnu!"); // Corsican
System.out.println("Pozdrav Svijete!"); // Croatian
System.out.println("Ahoj Světe!"); // Czech
System.out.println("Hej Verden!"); // Danish
System.out.println("ހެލޯ ވޯލްޑް!"); // Dhivehi
System.out.println("नमस्कार दुनिया !"); // Dogri
System.out.println("Hello Rhaesheser!"); // Dothraki
System.out.println("Hallo Wereld!"); // Dutch
System.out.println("👋🌎"); // Emoji
System.out.println("Saluton mondo!"); // Esperanto
System.out.println("Tere Maailm!"); // Estonian
System.out.println("Mido gbe na Xexeame!"); // Ewe
System.out.println("Hello Mundo!"); // Filipino
System.out.println("Hei maailma!"); // Finnish
System.out.println("Salut le monde!"); // French
System.out.println("Hallo wrâld!"); // Frisian
System.out.println("Ola mundo!"); // Galician
System.out.println("გამარჯობა სამყაროს!"); // Georgian
System.out.println("Hallo Welt!"); // German
System.out.println("Γειά σου Κόσμε!"); // Greek
System.out.println("Maitei Mundo!"); // Guarani
System.out.println("હેલો વર્લ્ડ!"); // Gujarati
System.out.println("Bonjou mond!"); // Haitian Creole
System.out.println("Sannu Duniya!"); // Hausa
System.out.println("Aloha Honua!"); // Hawaiian
System.out.println("שלום עולם!"); // Hebrew
System.out.println("नमस्ते दुनिया!"); // Hindi
System.out.println("Nyob zoo ntiaj teb!"); // Hmong
System.out.println("Helló Világ!"); // Hungarian
System.out.println("Halló heimur!"); // Icelandic
System.out.println("Ndewo Ụwa!"); // Igbo
System.out.println("Hello Lubong!"); // Ilocano
System.out.println("Halo Dunia!"); // Indonesian
System.out.println("Dia duit Domhanda!"); // Irish
System.out.println("Ciao Mondo!"); // Italian
System.out.println("こんにちは、 世界!"); // Japanese
System.out.println("Halo Donya!"); // Javanese
System.out.println("ಹಲೋ ವರ್ಲ್ಡ್!"); // Kannada
System.out.println("Сәлем Әлем!"); // Kazakh
System.out.println("សួស្តីពិភពលោក!"); // Khmer
System.out.println("Mwaramutse Isi!"); // Kinyarwanda
System.out.println("Habari dunia!"); // Kiswahili
System.out.println("qo' Vivan!"); // Klingon
System.out.println("नमस्कार संवसार!"); // Konkani
System.out.println("안녕하세요 월드입니다!"); // Korean
System.out.println("Halo Wɔl"); // Krio
System.out.println("Silav Cîhan!"); // Kurdish (Kurmanji)
System.out.println("سڵاو جیهان!"); // Kurdish (Sorani)
System.out.println("Салам дүйнө!"); // Kyrgyz
System.out.println("ສະບາຍດີຊາວໂລກ!"); // Lao
System.out.println("salve mundi!"); // Latin
System.out.println("Sveika Pasaule!"); // Latvian
System.out.println("h3l1O W()rL|)!"); // Leet /<SUF>
System.out.println("Mbote Mokili!"); // Lingala
System.out.println("Sveikas Pasauli!"); // Lithuanian
System.out.println("coi li terdi!"); // Lojban
System.out.println("Mwasuze Mutya Ensi!"); // Luganda
System.out.println("Moien Welt!"); // Luxembourgish
System.out.println("Здраво свету!"); // Macedonian
System.out.println("नमस्कार दुनिया!"); // Maithili
System.out.println("Manahoana izao tontolo izao!"); // Malagasy
System.out.println("Hai dunia!"); // Malay
System.out.println("ഹലോ വേൾഡ്!"); // Malayalam
System.out.println("Ħello dinja!"); // Maltese
System.out.println("Kia ora te Ao!"); // Maori
System.out.println("हॅलो वर्ल्ड!"); // Marathi
System.out.println("ꯍꯜꯂꯣꯏ ꯃꯥꯂꯦꯝ!"); // Meiteilon (Manipuri)
System.out.println("Bello Globo!"); // Minions Speak
System.out.println("Hello Khawvel!"); // Mizo
System.out.println("Сайн уу Дэлхий!"); // Mongolian
System.out.println(".... . .-.. .-.. --- .-- --- .-. .-.. -.. ---."); // Morse Code
System.out.println("မင်္ဂလာပါကမ္ဘာလောက!"); // Myanmar (Burmese)
System.out.println("नमस्कार संसार!"); // Nepali
System.out.println("Hallo Verden!"); // Norwegian
System.out.println("ନମସ୍କାର ବିଶ୍ୱବାସି!"); // Odia (Oriya)
System.out.println("Akkam jirtu Addunyaa!"); // Oromo
System.out.println("!سلام نړی"); // Pashto
System.out.println("!سلام دنیا"); // Persian
System.out.println("Ellohay Orldway!"); // Pig Latin
System.out.println("Witaj świecie!"); // Polish
System.out.println("Olá Mundo!"); // Portuguese
System.out.println("ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ ਦੁਨਿਆ!"); // Punjabi
System.out.println("Hola Mundo!"); // Quechua
System.out.println("Salut Lume!"); // Romanian
System.out.println("Здравствуй мир!"); // Russian
System.out.println("Talofa le Lalolagi!"); // Samoan
System.out.println("नमस्कार विश्व!"); // Sanskrit
System.out.println("Halò a Shaoghail!"); // Scots Gaelic
System.out.println("Thobela Lefase!"); // Sepedi
System.out.println("Здраво Свете!"); // Serbian
System.out.println("Lefatše Lumela!"); // Sesotho
System.out.println("Mhoro Nyika!"); // Shona
System.out.println("هيلو دنيا!"); // Sindhi
System.out.println("හෙලෝ වර්ල්ඩ්!"); // Sinhala
System.out.println("Ahoj svet!"); // Slovak
System.out.println("Pozdravljen svet!"); // Slovenian
System.out.println("Salaamu Calaykum!"); // Somali
System.out.println("¡Hola Mundo!"); // Spanish
System.out.println("Halo Dunya!"); // Sundanese
System.out.println("Salamu Dunia!"); // Swahili
System.out.println("Hallå världen!"); // Swedish
System.out.println("Kamusta mundo!"); // Tagalog
System.out.println("Салом Ҷаҳон!"); // Tajik
System.out.println("ஹலோ உலகம்!"); // Tamil
System.out.println("Сәлам, Дөнья!"); // Tatar
System.out.println("హలో వరల్డ్!"); // Telugu
System.out.println("สวัสดีโลก!"); // Thai
System.out.println("ሰላም ዓለም!"); // Tigrinya
System.out.println("Xewani Misava!"); // Tsonga
System.out.println("Merhaba Dünya!"); // Turkish
System.out.println("Salam Dünýä!"); // Turkmen
System.out.println("Hello Wiase!"); // Twi
System.out.println("Привіт Світ!"); // Ukranian
System.out.println("ہیلو دنیا والو"); // Urdu
System.out.println("ياخشىمۇسىز دۇنيا!"); // Uyghur
System.out.println("Salom Dunyo!"); // Uzbek
System.out.println("Rytsas Vys!"); // Valyrian
System.out.println("Xin chào thế giới!"); // Vietnamese
System.out.println("Helô Byd!"); // Welsh
System.out.println("Molo Lizwe!"); // Xhosa
System.out.println("העלא וועלט!"); // Yiddish
System.out.println("Mo ki O Ile Aiye!"); // Yoruba
System.out.println("Sawubona Mhlaba!"); // Zulu
}
}
|
180327_4 | package wtf.norma.nekito.module.impl.visuals;
import me.zero.alpine.listener.Listener;
import me.zero.alpine.listener.Subscribe;
import me.zero.alpine.listener.Subscriber;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import wtf.norma.nekito.Nekito;
import wtf.norma.nekito.module.Module;
import wtf.norma.nekito.event.impl.render.EventCustomModel;
import wtf.norma.nekito.settings.impl.ModeSetting;
import wtf.norma.nekito.util.math.MathUtility;
import wtf.norma.nekito.util.render.models.TessellatorModel;
public class CustomModel extends Module implements Subscriber {
public ModeSetting mode = new ModeSetting("Mode", "Hitla", "Hitla", "Jake", "Baba");
private TessellatorModel hitlerHead;
private TessellatorModel hitlerBody;
private TessellatorModel jake;
private TessellatorModel baba;
public CustomModel() {
super("CustomModel", Category.VISUALS, Keyboard.KEY_NONE);
addSettings(mode);
}
@Override
public void onEnable() {
super.onEnable();
Nekito.EVENT_BUS.subscribe(this);
this.hitlerHead = new TessellatorModel("/assets/minecraft/nekito/head.obj");
this.hitlerBody = new TessellatorModel("/assets/minecraft/nekito/body.obj");
this.jake = new TessellatorModel("/assets/minecraft/nekito/Jake.obj");
this.baba = new TessellatorModel("/assets/minecraft/nekito/Aether.obj"); // ta z genshina kojarze ja bo gralem
// cwele z mihoyo kiedy kurwa wkoncu ten jeabny nintendo switch support bo na tym jebanym nvidia now sie grac nie dai
}
@Override
public void onDisable() {
super.onDisable();
Nekito.EVENT_BUS.unsubscribe(this);
this.hitlerHead = null;
this.jake = null;
this.hitlerBody = null;
this.baba = null;
}
// nie wiem
// https://www.youtube.com/watch?v=xjD8MiCe9BU
@Subscribe
private final Listener<EventCustomModel> listener = new Listener<>(event -> {
GlStateManager.pushMatrix();
AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
RenderManager manager = mc.getRenderManager();
double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
boolean sneak = mc.thePlayer.isSneaking();
GL11.glTranslated(x, y, z);
if (!(mc.currentScreen instanceof GuiContainer))
GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
switch (mode.getMode()) {
case "Hitla":
GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.hitlerHead.render();
this.hitlerBody.render();
break;
case "Jake":
GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.jake.render();
break;
case "Baba":
GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.baba.render();
break;
}
GlStateManager.enableLighting();
GlStateManager.resetColor();
GlStateManager.popMatrix();
});
//Commented out by DevOfDeath 😂😂😂😂😂
// public void onEvent(Event event) {
// if (event instanceof EventCustomModel) {
// GlStateManager.pushMatrix();
// AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
// RenderManager manager = mc.getRenderManager();
// double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
// double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
// double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
// float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
// boolean sneak = mc.thePlayer.isSneaking();
// GL11.glTranslated(x, y, z);
// if (!(mc.currentScreen instanceof GuiContainer))
// GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
//
//
// switch (mode.getMode()) {
// case "Hitla":
// GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.hitlerHead.render();
// this.hitlerBody.render();
// break;
// case "Jake":
// GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.jake.render();
// break;
// case "Baba":
// GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.baba.render();
// break;
// }
// GlStateManager.enableLighting();
// GlStateManager.resetColor();
// GlStateManager.popMatrix();
// }
// }
}
| Nekito-Development/openkito | src/main/java/wtf/norma/nekito/module/impl/visuals/CustomModel.java | 2,113 | // public void onEvent(Event event) { | line_comment | nl | package wtf.norma.nekito.module.impl.visuals;
import me.zero.alpine.listener.Listener;
import me.zero.alpine.listener.Subscribe;
import me.zero.alpine.listener.Subscriber;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import wtf.norma.nekito.Nekito;
import wtf.norma.nekito.module.Module;
import wtf.norma.nekito.event.impl.render.EventCustomModel;
import wtf.norma.nekito.settings.impl.ModeSetting;
import wtf.norma.nekito.util.math.MathUtility;
import wtf.norma.nekito.util.render.models.TessellatorModel;
public class CustomModel extends Module implements Subscriber {
public ModeSetting mode = new ModeSetting("Mode", "Hitla", "Hitla", "Jake", "Baba");
private TessellatorModel hitlerHead;
private TessellatorModel hitlerBody;
private TessellatorModel jake;
private TessellatorModel baba;
public CustomModel() {
super("CustomModel", Category.VISUALS, Keyboard.KEY_NONE);
addSettings(mode);
}
@Override
public void onEnable() {
super.onEnable();
Nekito.EVENT_BUS.subscribe(this);
this.hitlerHead = new TessellatorModel("/assets/minecraft/nekito/head.obj");
this.hitlerBody = new TessellatorModel("/assets/minecraft/nekito/body.obj");
this.jake = new TessellatorModel("/assets/minecraft/nekito/Jake.obj");
this.baba = new TessellatorModel("/assets/minecraft/nekito/Aether.obj"); // ta z genshina kojarze ja bo gralem
// cwele z mihoyo kiedy kurwa wkoncu ten jeabny nintendo switch support bo na tym jebanym nvidia now sie grac nie dai
}
@Override
public void onDisable() {
super.onDisable();
Nekito.EVENT_BUS.unsubscribe(this);
this.hitlerHead = null;
this.jake = null;
this.hitlerBody = null;
this.baba = null;
}
// nie wiem
// https://www.youtube.com/watch?v=xjD8MiCe9BU
@Subscribe
private final Listener<EventCustomModel> listener = new Listener<>(event -> {
GlStateManager.pushMatrix();
AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
RenderManager manager = mc.getRenderManager();
double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
boolean sneak = mc.thePlayer.isSneaking();
GL11.glTranslated(x, y, z);
if (!(mc.currentScreen instanceof GuiContainer))
GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
switch (mode.getMode()) {
case "Hitla":
GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.hitlerHead.render();
this.hitlerBody.render();
break;
case "Jake":
GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.jake.render();
break;
case "Baba":
GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.baba.render();
break;
}
GlStateManager.enableLighting();
GlStateManager.resetColor();
GlStateManager.popMatrix();
});
//Commented out by DevOfDeath 😂😂😂😂😂
// public void<SUF>
// if (event instanceof EventCustomModel) {
// GlStateManager.pushMatrix();
// AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
// RenderManager manager = mc.getRenderManager();
// double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
// double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
// double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
// float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
// boolean sneak = mc.thePlayer.isSneaking();
// GL11.glTranslated(x, y, z);
// if (!(mc.currentScreen instanceof GuiContainer))
// GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
//
//
// switch (mode.getMode()) {
// case "Hitla":
// GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.hitlerHead.render();
// this.hitlerBody.render();
// break;
// case "Jake":
// GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.jake.render();
// break;
// case "Baba":
// GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.baba.render();
// break;
// }
// GlStateManager.enableLighting();
// GlStateManager.resetColor();
// GlStateManager.popMatrix();
// }
// }
}
|
18580_1 | /*
* Copyright (C) 2014-2015 Dominik Schürmann <[email protected]>
*
* 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 org.openintents.openpgp.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
public class OpenPgpApi {
public static final String TAG = "OpenPgp API";
public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2";
/**
* see CHANGELOG.md
*/
public static final int API_VERSION = 11;
/**
* General extras
* --------------
*
* required extras:
* int EXTRA_API_VERSION (always required)
*
* returned extras:
* int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
* OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR)
* PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
*/
/**
* This action performs no operation, but can be used to check if the App has permission
* to access the API in general, returning a user interaction PendingIntent otherwise.
* This can be used to trigger the permission dialog explicitly.
*
* This action uses no extras.
*/
public static final String ACTION_CHECK_PERMISSION = "org.openintents.openpgp.action.CHECK_PERMISSION";
@Deprecated
public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
/**
* Sign text resulting in a cleartext signature
* Some magic pre-processing of the text is done to convert it to a format usable for
* cleartext signatures per RFC 4880 before the text is actually signed:
* - end cleartext with newline
* - remove whitespaces on line endings
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* char[] EXTRA_PASSPHRASE (key passphrase)
*/
public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN";
/**
* Sign text or binary data resulting in a detached signature.
* No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)!
* The detached signature is returned separately in RESULT_DETACHED_SIGNATURE.
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature)
* char[] EXTRA_PASSPHRASE (key passphrase)
*
* returned extras:
* byte[] RESULT_DETACHED_SIGNATURE
* String RESULT_SIGNATURE_MICALG (contains the name of the used signature algorithm as a string)
*/
public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN";
/**
* Encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
/**
* Sign and encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
public static final String ACTION_QUERY_AUTOCRYPT_STATUS = "org.openintents.openpgp.action.QUERY_AUTOCRYPT_STATUS";
/**
* Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
* OutputStream is optional, e.g., for verifying detached signatures!
*
* If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING
* in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
* On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open
* the key view in OpenKeychain.
*
* optional extras:
* byte[] EXTRA_DETACHED_SIGNATURE (detached signature)
*
* returned extras:
* OpenPgpSignatureResult RESULT_SIGNATURE
* OpenPgpDecryptionResult RESULT_DECRYPTION
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
/**
* Decrypts the header of an encrypted file to retrieve metadata such as original filename.
*
* This does not decrypt the actual content of the file.
*
* returned extras:
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA";
/**
* Select key id for signing
*
* optional extras:
* String EXTRA_USER_ID
*
* returned extras:
* long EXTRA_SIGN_KEY_ID
*/
public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID";
public static final String ACTION_GET_SIGN_KEY_ID_LEGACY = "org.openintents.openpgp.action.GET_SIGN_KEY_ID_LEGACY";
/**
* Get key ids based on given user ids (=emails)
*
* required extras:
* String[] EXTRA_USER_IDS
*
* returned extras:
* long[] RESULT_KEY_IDS
*/
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/**
* This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
* corresponding to the given key id in its database.
*
* It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
* The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
*
* If an Output stream has been defined the whole public key is returned.
* required extras:
* long EXTRA_KEY_ID
*
* optional extras:
* String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor)
*/
public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
/**
* Backup all keys given by EXTRA_KEY_IDS and if requested their secret parts.
* The encrypted backup will be written to the OutputStream.
* The client app has no access to the backup code used to encrypt the backup!
* This operation always requires user interaction with RESULT_CODE_USER_INTERACTION_REQUIRED!
*
* required extras:
* long[] EXTRA_KEY_IDS (keys that should be included in the backup)
* boolean EXTRA_BACKUP_SECRET (also backup secret keys)
*/
public static final String ACTION_BACKUP = "org.openintents.openpgp.action.BACKUP";
public static final String ACTION_UPDATE_AUTOCRYPT_PEER = "org.openintents.openpgp.action.UPDATE_AUTOCRYPT_PEER";
/* Intent extras */
public static final String EXTRA_API_VERSION = "api_version";
// ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
// request ASCII Armor for output
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
// ACTION_DETACHED_SIGN
public static final String RESULT_DETACHED_SIGNATURE = "detached_signature";
public static final String RESULT_SIGNATURE_MICALG = "signature_micalg";
// ENCRYPT, SIGN_AND_ENCRYPT, QUERY_AUTOCRYPT_STATUS
public static final String EXTRA_USER_IDS = "user_ids";
public static final String EXTRA_KEY_IDS = "key_ids";
public static final String EXTRA_KEY_IDS_SELECTED = "key_ids_selected";
public static final String EXTRA_SIGN_KEY_ID = "sign_key_id";
public static final String RESULT_KEYS_CONFIRMED = "keys_confirmed";
public static final String RESULT_AUTOCRYPT_STATUS = "autocrypt_status";
public static final int AUTOCRYPT_STATUS_UNAVAILABLE = 0;
public static final int AUTOCRYPT_STATUS_DISCOURAGE = 1;
public static final int AUTOCRYPT_STATUS_AVAILABLE = 2;
public static final int AUTOCRYPT_STATUS_MUTUAL = 3;
// optional extras:
public static final String EXTRA_PASSPHRASE = "passphrase";
public static final String EXTRA_ORIGINAL_FILENAME = "original_filename";
public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression";
public static final String EXTRA_OPPORTUNISTIC_ENCRYPTION = "opportunistic";
public static final String EXTRA_CUSTOM_HEADERS = "custom_headers";
// GET_SIGN_KEY_ID
public static final String EXTRA_USER_ID = "user_id";
public static final String EXTRA_PRESELECT_KEY_ID = "preselect_key_id";
public static final String EXTRA_SHOW_AUTOCRYPT_HINT = "show_autocrypt_hint";
public static final String RESULT_SIGN_KEY_ID = "sign_key_id";
public static final String RESULT_PRIMARY_USER_ID = "primary_user_id";
public static final String RESULT_KEY_CREATION_TIME = "key_creation_time";
// GET_KEY
public static final String EXTRA_KEY_ID = "key_id";
public static final String EXTRA_MINIMIZE = "minimize";
public static final String EXTRA_MINIMIZE_USER_ID = "minimize_user_id";
public static final String RESULT_KEY_IDS = "key_ids";
// BACKUP
public static final String EXTRA_BACKUP_SECRET = "backup_secret";
public static final String ACTION_AUTOCRYPT_KEY_TRANSFER = "autocrypt_key_transfer";
/* Service Intent returns */
public static final String RESULT_CODE = "result_code";
// get actual error object from RESULT_ERROR
public static final int RESULT_CODE_ERROR = 0;
// success!
public static final int RESULT_CODE_SUCCESS = 1;
// get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
// and execute service method again in onActivityResult
public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
public static final String RESULT_ERROR = "error";
public static final String RESULT_INTENT = "intent";
// DECRYPT_VERIFY
public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature";
public static final String EXTRA_PROGRESS_MESSENGER = "progress_messenger";
public static final String EXTRA_DATA_LENGTH = "data_length";
public static final String EXTRA_DECRYPTION_RESULT = "decryption_result";
public static final String EXTRA_SENDER_ADDRESS = "sender_address";
public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning";
public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id";
public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update";
public static final String EXTRA_AUTOCRYPT_PEER_GOSSIP_UPDATES = "autocrypt_peer_gossip_updates";
public static final String RESULT_SIGNATURE = "signature";
public static final String RESULT_DECRYPTION = "decryption";
public static final String RESULT_METADATA = "metadata";
public static final String RESULT_INSECURE_DETAIL_INTENT = "insecure_detail_intent";
public static final String RESULT_OVERRIDE_CRYPTO_WARNING = "override_crypto_warning";
// This will be the charset which was specified in the headers of ascii armored input, if any
public static final String RESULT_CHARSET = "charset";
// INTERNAL, must not be used
public static final String EXTRA_CALL_UUID1 = "call_uuid1";
public static final String EXTRA_CALL_UUID2 = "call_uuid2";
IOpenPgpService2 mService;
Context mContext;
final AtomicInteger mPipeIdGen = new AtomicInteger();
public OpenPgpApi(Context context, IOpenPgpService2 service) {
this.mContext = context;
this.mService = service;
}
public interface IOpenPgpCallback {
void onReturn(final Intent result);
}
private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
Intent data;
InputStream is;
OutputStream os;
IOpenPgpCallback callback;
private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
this.data = data;
this.is = is;
this.os = os;
this.callback = callback;
}
@Override
protected Intent doInBackground(Void... unused) {
return executeApi(data, is, os);
}
protected void onPostExecute(Intent result) {
callback.onReturn(result);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
} else {
task.execute((Void[]) null);
}
}
public Intent executeApi(Intent data, InputStream is, OutputStream os) {
ParcelFileDescriptor input = null;
try {
if (is != null) {
input = ParcelFileDescriptorUtil.pipeFrom(is);
}
return executeApi(data, input, os);
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
}
}
}
}
/**
* InputStream and OutputStreams are always closed after operating on them!
*/
public Intent executeApi(Intent data, ParcelFileDescriptor input, OutputStream os) {
ParcelFileDescriptor output = null;
try {
// always send version from client
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result;
Thread pumpThread = null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
// blocks until result is ready
result = mService.execute(data, input, outputPipeId);
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
//wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
// close() is required to halt the TransferThread
if (output != null) {
try {
output.close();
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
}
}
}
}
}
| NekoX-Dev/NekoX | openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpApi.java | 5,635 | /**
* see CHANGELOG.md
*/ | block_comment | nl | /*
* Copyright (C) 2014-2015 Dominik Schürmann <[email protected]>
*
* 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 org.openintents.openpgp.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
public class OpenPgpApi {
public static final String TAG = "OpenPgp API";
public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2";
/**
* see CHANGELOG.md
<SUF>*/
public static final int API_VERSION = 11;
/**
* General extras
* --------------
*
* required extras:
* int EXTRA_API_VERSION (always required)
*
* returned extras:
* int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
* OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR)
* PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
*/
/**
* This action performs no operation, but can be used to check if the App has permission
* to access the API in general, returning a user interaction PendingIntent otherwise.
* This can be used to trigger the permission dialog explicitly.
*
* This action uses no extras.
*/
public static final String ACTION_CHECK_PERMISSION = "org.openintents.openpgp.action.CHECK_PERMISSION";
@Deprecated
public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
/**
* Sign text resulting in a cleartext signature
* Some magic pre-processing of the text is done to convert it to a format usable for
* cleartext signatures per RFC 4880 before the text is actually signed:
* - end cleartext with newline
* - remove whitespaces on line endings
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* char[] EXTRA_PASSPHRASE (key passphrase)
*/
public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN";
/**
* Sign text or binary data resulting in a detached signature.
* No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)!
* The detached signature is returned separately in RESULT_DETACHED_SIGNATURE.
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature)
* char[] EXTRA_PASSPHRASE (key passphrase)
*
* returned extras:
* byte[] RESULT_DETACHED_SIGNATURE
* String RESULT_SIGNATURE_MICALG (contains the name of the used signature algorithm as a string)
*/
public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN";
/**
* Encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
/**
* Sign and encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
public static final String ACTION_QUERY_AUTOCRYPT_STATUS = "org.openintents.openpgp.action.QUERY_AUTOCRYPT_STATUS";
/**
* Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
* OutputStream is optional, e.g., for verifying detached signatures!
*
* If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING
* in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
* On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open
* the key view in OpenKeychain.
*
* optional extras:
* byte[] EXTRA_DETACHED_SIGNATURE (detached signature)
*
* returned extras:
* OpenPgpSignatureResult RESULT_SIGNATURE
* OpenPgpDecryptionResult RESULT_DECRYPTION
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
/**
* Decrypts the header of an encrypted file to retrieve metadata such as original filename.
*
* This does not decrypt the actual content of the file.
*
* returned extras:
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA";
/**
* Select key id for signing
*
* optional extras:
* String EXTRA_USER_ID
*
* returned extras:
* long EXTRA_SIGN_KEY_ID
*/
public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID";
public static final String ACTION_GET_SIGN_KEY_ID_LEGACY = "org.openintents.openpgp.action.GET_SIGN_KEY_ID_LEGACY";
/**
* Get key ids based on given user ids (=emails)
*
* required extras:
* String[] EXTRA_USER_IDS
*
* returned extras:
* long[] RESULT_KEY_IDS
*/
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/**
* This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
* corresponding to the given key id in its database.
*
* It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
* The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
*
* If an Output stream has been defined the whole public key is returned.
* required extras:
* long EXTRA_KEY_ID
*
* optional extras:
* String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor)
*/
public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
/**
* Backup all keys given by EXTRA_KEY_IDS and if requested their secret parts.
* The encrypted backup will be written to the OutputStream.
* The client app has no access to the backup code used to encrypt the backup!
* This operation always requires user interaction with RESULT_CODE_USER_INTERACTION_REQUIRED!
*
* required extras:
* long[] EXTRA_KEY_IDS (keys that should be included in the backup)
* boolean EXTRA_BACKUP_SECRET (also backup secret keys)
*/
public static final String ACTION_BACKUP = "org.openintents.openpgp.action.BACKUP";
public static final String ACTION_UPDATE_AUTOCRYPT_PEER = "org.openintents.openpgp.action.UPDATE_AUTOCRYPT_PEER";
/* Intent extras */
public static final String EXTRA_API_VERSION = "api_version";
// ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
// request ASCII Armor for output
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
// ACTION_DETACHED_SIGN
public static final String RESULT_DETACHED_SIGNATURE = "detached_signature";
public static final String RESULT_SIGNATURE_MICALG = "signature_micalg";
// ENCRYPT, SIGN_AND_ENCRYPT, QUERY_AUTOCRYPT_STATUS
public static final String EXTRA_USER_IDS = "user_ids";
public static final String EXTRA_KEY_IDS = "key_ids";
public static final String EXTRA_KEY_IDS_SELECTED = "key_ids_selected";
public static final String EXTRA_SIGN_KEY_ID = "sign_key_id";
public static final String RESULT_KEYS_CONFIRMED = "keys_confirmed";
public static final String RESULT_AUTOCRYPT_STATUS = "autocrypt_status";
public static final int AUTOCRYPT_STATUS_UNAVAILABLE = 0;
public static final int AUTOCRYPT_STATUS_DISCOURAGE = 1;
public static final int AUTOCRYPT_STATUS_AVAILABLE = 2;
public static final int AUTOCRYPT_STATUS_MUTUAL = 3;
// optional extras:
public static final String EXTRA_PASSPHRASE = "passphrase";
public static final String EXTRA_ORIGINAL_FILENAME = "original_filename";
public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression";
public static final String EXTRA_OPPORTUNISTIC_ENCRYPTION = "opportunistic";
public static final String EXTRA_CUSTOM_HEADERS = "custom_headers";
// GET_SIGN_KEY_ID
public static final String EXTRA_USER_ID = "user_id";
public static final String EXTRA_PRESELECT_KEY_ID = "preselect_key_id";
public static final String EXTRA_SHOW_AUTOCRYPT_HINT = "show_autocrypt_hint";
public static final String RESULT_SIGN_KEY_ID = "sign_key_id";
public static final String RESULT_PRIMARY_USER_ID = "primary_user_id";
public static final String RESULT_KEY_CREATION_TIME = "key_creation_time";
// GET_KEY
public static final String EXTRA_KEY_ID = "key_id";
public static final String EXTRA_MINIMIZE = "minimize";
public static final String EXTRA_MINIMIZE_USER_ID = "minimize_user_id";
public static final String RESULT_KEY_IDS = "key_ids";
// BACKUP
public static final String EXTRA_BACKUP_SECRET = "backup_secret";
public static final String ACTION_AUTOCRYPT_KEY_TRANSFER = "autocrypt_key_transfer";
/* Service Intent returns */
public static final String RESULT_CODE = "result_code";
// get actual error object from RESULT_ERROR
public static final int RESULT_CODE_ERROR = 0;
// success!
public static final int RESULT_CODE_SUCCESS = 1;
// get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
// and execute service method again in onActivityResult
public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
public static final String RESULT_ERROR = "error";
public static final String RESULT_INTENT = "intent";
// DECRYPT_VERIFY
public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature";
public static final String EXTRA_PROGRESS_MESSENGER = "progress_messenger";
public static final String EXTRA_DATA_LENGTH = "data_length";
public static final String EXTRA_DECRYPTION_RESULT = "decryption_result";
public static final String EXTRA_SENDER_ADDRESS = "sender_address";
public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning";
public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id";
public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update";
public static final String EXTRA_AUTOCRYPT_PEER_GOSSIP_UPDATES = "autocrypt_peer_gossip_updates";
public static final String RESULT_SIGNATURE = "signature";
public static final String RESULT_DECRYPTION = "decryption";
public static final String RESULT_METADATA = "metadata";
public static final String RESULT_INSECURE_DETAIL_INTENT = "insecure_detail_intent";
public static final String RESULT_OVERRIDE_CRYPTO_WARNING = "override_crypto_warning";
// This will be the charset which was specified in the headers of ascii armored input, if any
public static final String RESULT_CHARSET = "charset";
// INTERNAL, must not be used
public static final String EXTRA_CALL_UUID1 = "call_uuid1";
public static final String EXTRA_CALL_UUID2 = "call_uuid2";
IOpenPgpService2 mService;
Context mContext;
final AtomicInteger mPipeIdGen = new AtomicInteger();
public OpenPgpApi(Context context, IOpenPgpService2 service) {
this.mContext = context;
this.mService = service;
}
public interface IOpenPgpCallback {
void onReturn(final Intent result);
}
private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
Intent data;
InputStream is;
OutputStream os;
IOpenPgpCallback callback;
private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
this.data = data;
this.is = is;
this.os = os;
this.callback = callback;
}
@Override
protected Intent doInBackground(Void... unused) {
return executeApi(data, is, os);
}
protected void onPostExecute(Intent result) {
callback.onReturn(result);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
} else {
task.execute((Void[]) null);
}
}
public Intent executeApi(Intent data, InputStream is, OutputStream os) {
ParcelFileDescriptor input = null;
try {
if (is != null) {
input = ParcelFileDescriptorUtil.pipeFrom(is);
}
return executeApi(data, input, os);
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
}
}
}
}
/**
* InputStream and OutputStreams are always closed after operating on them!
*/
public Intent executeApi(Intent data, ParcelFileDescriptor input, OutputStream os) {
ParcelFileDescriptor output = null;
try {
// always send version from client
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result;
Thread pumpThread = null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
// blocks until result is ready
result = mService.execute(data, input, outputPipeId);
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
//wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
// close() is required to halt the TransferThread
if (output != null) {
try {
output.close();
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
}
}
}
}
}
|
6399_3 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utilities {
public static Pattern pattern = Pattern.compile("[\\-0-9]+");
public static SecureRandom random = new SecureRandom();
public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong());
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue");
public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue");
public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue");
public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue");
public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue");
public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue");
public static volatile DispatchQueue videoPlayerQueue;
private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
static {
try {
File URANDOM_FILE = new File("/dev/urandom");
FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE);
byte[] buffer = new byte[1024];
sUrandomIn.read(buffer);
sUrandomIn.close();
random.setSeed(buffer);
} catch (Exception e) {
FileLog.e(e);
}
}
public native static int pinBitmap(Bitmap bitmap);
public native static void unpinBitmap(Bitmap bitmap);
public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride);
public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride);
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer);
//public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length);
public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n);
private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt);
public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt);
public native static String readlink(String path);
public native static String readlinkFd(int fd);
public native static long getDirSize(String path, int docType, boolean subdirs);
public native static long getLastUsageFileTime(String path);
public native static void clearDir(String path, int docType, long time, boolean subdirs);
private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations);
public static native void stackBlurBitmap(Bitmap bitmap, int radius);
public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY);
//public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path);
public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors);
public static native void setupNativeCrashesListener(String path);
public static Bitmap stackBlurBitmapMax(Bitmap bitmap) {
return stackBlurBitmapMax(bitmap, false);
}
public static Bitmap stackBlurBitmapMax(Bitmap bitmap, boolean round) {
int w = AndroidUtilities.dp(20);
int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth());
Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.save();
canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight());
if (round) {
Path path = new Path();
path.addCircle(bitmap.getWidth() / 2f, bitmap.getHeight() / 2f, Math.min(bitmap.getWidth(), bitmap.getHeight()) / 2f - 1, Path.Direction.CW);
canvas.clipPath(path);
}
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.restore();
Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150));
return scaledBitmap;
}
public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) {
int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor);
int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor);
Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.save();
canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight());
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.restore();
Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150));
return scaledBitmap;
}
public static Bitmap blurWallpaper(Bitmap src) {
if (src == null) {
return null;
}
Bitmap b;
if (src.getHeight() > src.getWidth()) {
b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888);
} else {
b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888);
}
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight());
new Canvas(b).drawBitmap(src, null, rect, paint);
stackBlurBitmap(b, 12);
return b;
}
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) {
aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt);
}
public static Integer parseInt(CharSequence value) {
if (value == null) {
return 0;
}
if (false) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return Integer.valueOf(matcher.group());
}
} else {
int val = 0;
try {
int start = -1, end;
for (end = 0; end < value.length(); ++end) {
char character = value.charAt(end);
boolean allowedChar = character == '-' || character >= '0' && character <= '9';
if (allowedChar && start < 0) {
start = end;
} else if (!allowedChar && start >= 0) {
end++;
break;
}
}
if (start >= 0) {
String str = value.subSequence(start, end).toString();
// val = parseInt(str);
val = Integer.parseInt(str);
}
} catch (Exception ignore) {}
return val;
}
return 0;
}
private static int parseInt(final String s) {
int num = 0;
boolean negative = true;
final int len = s.length();
final char ch = s.charAt(0);
if (ch == '-') {
negative = false;
} else {
num = '0' - ch;
}
int i = 1;
while (i < len) {
num = num * 10 + '0' - s.charAt(i++);
}
return negative ? -num : num;
}
public static Long parseLong(String value) {
if (value == null) {
return 0L;
}
long val = 0L;
try {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
String num = matcher.group(0);
val = Long.parseLong(num);
}
} catch (Exception ignore) {
}
return val;
}
public static String parseIntToString(String value) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return matcher.group(0);
}
return null;
}
public static String bytesToHex(byte[] bytes) {
if (bytes == null) {
return "";
}
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexToBytes(String hex) {
if (hex == null) {
return null;
}
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
public static boolean isGoodPrime(byte[] prime, int g) {
if (!(g >= 2 && g <= 7)) {
return false;
}
if (prime.length != 256 || prime[0] >= 0) {
return false;
}
BigInteger dhBI = new BigInteger(1, prime);
if (g == 2) { // p mod 8 = 7 for g = 2;
BigInteger res = dhBI.mod(BigInteger.valueOf(8));
if (res.intValue() != 7) {
return false;
}
} else if (g == 3) { // p mod 3 = 2 for g = 3;
BigInteger res = dhBI.mod(BigInteger.valueOf(3));
if (res.intValue() != 2) {
return false;
}
} else if (g == 5) { // p mod 5 = 1 or 4 for g = 5;
BigInteger res = dhBI.mod(BigInteger.valueOf(5));
int val = res.intValue();
if (val != 1 && val != 4) {
return false;
}
} else if (g == 6) { // p mod 24 = 19 or 23 for g = 6;
BigInteger res = dhBI.mod(BigInteger.valueOf(24));
int val = res.intValue();
if (val != 19 && val != 23) {
return false;
}
} else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7.
BigInteger res = dhBI.mod(BigInteger.valueOf(7));
int val = res.intValue();
if (val != 3 && val != 5 && val != 6) {
return false;
}
}
String hex = bytesToHex(prime);
if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) {
return true;
}
BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2));
return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30));
}
public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) {
return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0);
}
public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) {
if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) {
return false;
}
boolean result = true;
for (int a = offset1; a < arr1.length; a++) {
if (arr1[a + offset1] != arr2[a + offset2]) {
result = false;
}
}
return result;
}
public static byte[] computeSHA1(byte[] convertme, int offset, int len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(convertme, offset, len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
int oldp = convertme.position();
int oldl = convertme.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
convertme.position(offset);
convertme.limit(len);
md.update(convertme);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
convertme.limit(oldl);
convertme.position(oldp);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme) {
return computeSHA1(convertme, 0, convertme.limit());
}
public static byte[] computeSHA1(byte[] convertme) {
return computeSHA1(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme) {
return computeSHA256(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme, int offset, long len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(convertme, offset, (int) len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA256(byte[]... args) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (int a = 0; a < args.length; a++) {
md.update(args[a], 0, args[a].length);
}
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA512(byte[] convertme) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computePBKDF2(byte[] password, byte[] salt) {
byte[] dst = new byte[64];
Utilities.pbkdf2(password, salt, dst, 100000);
return dst;
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
md.update(convertme3, 0, convertme3.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) {
int oldp = b2.position();
int oldl = b2.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(b1, o1, l1);
b2.position(o2);
b2.limit(l2);
md.update(b2);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
b2.limit(oldl);
b2.position(oldp);
}
return new byte[32];
}
public static long bytesToLong(byte[] bytes) {
return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32)
+ (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF);
}
public static int bytesToInt(byte[] bytes) {
return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF);
}
public static byte[] intToBytes(int value) {
return new byte[]{
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value};
}
public static String MD5(String md5) {
if (md5 == null) {
return null;
}
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(AndroidUtilities.getStringBytes(md5));
StringBuilder sb = new StringBuilder();
for (int a = 0; a < array.length; a++) {
sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
FileLog.e(e);
}
return null;
}
public static int clamp(int value, int maxValue, int minValue) {
return Math.max(Math.min(value, maxValue), minValue);
}
public static long clamp(long value, long maxValue, long minValue) {
return Math.max(Math.min(value, maxValue), minValue);
}
public static float clamp(float value, float maxValue, float minValue) {
if (Float.isNaN(value)) {
return minValue;
}
if (Float.isInfinite(value)) {
return maxValue;
}
return Math.max(Math.min(value, maxValue), minValue);
}
public static double clamp(double value, double maxValue, double minValue) {
if (Double.isNaN(value)) {
return minValue;
}
if (Double.isInfinite(value)) {
return maxValue;
}
return Math.max(Math.min(value, maxValue), minValue);
}
public static String generateRandomString() {
return generateRandomString(16);
}
public static String generateRandomString(int chars) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars; i++) {
sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length())));
}
return sb.toString();
}
public static String getExtension(String fileName) {
int idx = fileName.lastIndexOf('.');
String ext = null;
if (idx != -1) {
ext = fileName.substring(idx + 1);
}
if (ext == null) {
return null;
}
ext = ext.toUpperCase();
return ext;
}
public static interface Callback<T> {
public void run(T arg);
}
public static interface CallbackVoidReturn<ReturnType> {
public ReturnType run();
}
public static interface Callback0Return<ReturnType> {
public ReturnType run();
}
public static interface CallbackReturn<Arg, ReturnType> {
public ReturnType run(Arg arg);
}
public static interface Callback2Return<T1, T2, ReturnType> {
public ReturnType run(T1 arg, T2 arg2);
}
public static interface Callback3Return<T1, T2, T3, ReturnType> {
public ReturnType run(T1 arg, T2 arg2, T3 arg3);
}
public static interface Callback2<T, T2> {
public void run(T arg, T2 arg2);
}
public static interface Callback3<T, T2, T3> {
public void run(T arg, T2 arg2, T3 arg3);
}
public static interface Callback4<T, T2, T3, T4> {
public void run(T arg, T2 arg2, T3 arg3, T4 arg4);
}
public static interface Callback4Return<T, T2, T3, T4, ReturnType> {
public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4);
}
public static interface Callback5<T, T2, T3, T4, T5> {
public void run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
}
public static interface Callback5Return<T, T2, T3, T4, T5, ReturnType> {
public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
}
public static interface IndexedConsumer<T> {
void accept(T t, int index);
}
public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) {
Value v = map.get(key);
if (v == null) {
return defaultValue;
}
return v;
}
public static void doCallbacks(Utilities.Callback<Runnable> ...actions) {
doCallbacks(0, actions);
}
private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) {
if (actions != null && actions.length > i) {
actions[i].run(() -> doCallbacks(i + 1, actions));
}
}
public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) {
if (actions == null || actions.length == 0) {
if (onFinish != null) {
onFinish.run();
}
return;
}
final int[] finished = new int[] { 0 };
Runnable checkFinish = () -> {
finished[0]++;
if (finished[0] == actions.length) {
if (onFinish != null) {
onFinish.run();
}
}
};
for (int i = 0; i < actions.length; ++i) {
actions[i].run(checkFinish);
}
}
public static DispatchQueue getOrCreatePlayerQueue() {
if (videoPlayerQueue == null) {
videoPlayerQueue = new DispatchQueue("playerQueue");
}
return videoPlayerQueue;
}
public static boolean isNullOrEmpty(final Collection<?> list) {
return list == null || list.isEmpty();
}
}
| Nekogram/Nekogram | TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java | 7,599 | // val = parseInt(str); | line_comment | nl | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utilities {
public static Pattern pattern = Pattern.compile("[\\-0-9]+");
public static SecureRandom random = new SecureRandom();
public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong());
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue");
public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue");
public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue");
public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue");
public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue");
public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue");
public static volatile DispatchQueue videoPlayerQueue;
private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
static {
try {
File URANDOM_FILE = new File("/dev/urandom");
FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE);
byte[] buffer = new byte[1024];
sUrandomIn.read(buffer);
sUrandomIn.close();
random.setSeed(buffer);
} catch (Exception e) {
FileLog.e(e);
}
}
public native static int pinBitmap(Bitmap bitmap);
public native static void unpinBitmap(Bitmap bitmap);
public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride);
public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride);
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer);
//public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length);
public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n);
private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt);
public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt);
public native static String readlink(String path);
public native static String readlinkFd(int fd);
public native static long getDirSize(String path, int docType, boolean subdirs);
public native static long getLastUsageFileTime(String path);
public native static void clearDir(String path, int docType, long time, boolean subdirs);
private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations);
public static native void stackBlurBitmap(Bitmap bitmap, int radius);
public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY);
//public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path);
public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors);
public static native void setupNativeCrashesListener(String path);
public static Bitmap stackBlurBitmapMax(Bitmap bitmap) {
return stackBlurBitmapMax(bitmap, false);
}
public static Bitmap stackBlurBitmapMax(Bitmap bitmap, boolean round) {
int w = AndroidUtilities.dp(20);
int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth());
Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.save();
canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight());
if (round) {
Path path = new Path();
path.addCircle(bitmap.getWidth() / 2f, bitmap.getHeight() / 2f, Math.min(bitmap.getWidth(), bitmap.getHeight()) / 2f - 1, Path.Direction.CW);
canvas.clipPath(path);
}
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.restore();
Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150));
return scaledBitmap;
}
public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) {
int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor);
int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor);
Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.save();
canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight());
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.restore();
Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150));
return scaledBitmap;
}
public static Bitmap blurWallpaper(Bitmap src) {
if (src == null) {
return null;
}
Bitmap b;
if (src.getHeight() > src.getWidth()) {
b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888);
} else {
b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888);
}
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight());
new Canvas(b).drawBitmap(src, null, rect, paint);
stackBlurBitmap(b, 12);
return b;
}
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) {
aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt);
}
public static Integer parseInt(CharSequence value) {
if (value == null) {
return 0;
}
if (false) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return Integer.valueOf(matcher.group());
}
} else {
int val = 0;
try {
int start = -1, end;
for (end = 0; end < value.length(); ++end) {
char character = value.charAt(end);
boolean allowedChar = character == '-' || character >= '0' && character <= '9';
if (allowedChar && start < 0) {
start = end;
} else if (!allowedChar && start >= 0) {
end++;
break;
}
}
if (start >= 0) {
String str = value.subSequence(start, end).toString();
// val =<SUF>
val = Integer.parseInt(str);
}
} catch (Exception ignore) {}
return val;
}
return 0;
}
private static int parseInt(final String s) {
int num = 0;
boolean negative = true;
final int len = s.length();
final char ch = s.charAt(0);
if (ch == '-') {
negative = false;
} else {
num = '0' - ch;
}
int i = 1;
while (i < len) {
num = num * 10 + '0' - s.charAt(i++);
}
return negative ? -num : num;
}
public static Long parseLong(String value) {
if (value == null) {
return 0L;
}
long val = 0L;
try {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
String num = matcher.group(0);
val = Long.parseLong(num);
}
} catch (Exception ignore) {
}
return val;
}
public static String parseIntToString(String value) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return matcher.group(0);
}
return null;
}
public static String bytesToHex(byte[] bytes) {
if (bytes == null) {
return "";
}
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexToBytes(String hex) {
if (hex == null) {
return null;
}
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
public static boolean isGoodPrime(byte[] prime, int g) {
if (!(g >= 2 && g <= 7)) {
return false;
}
if (prime.length != 256 || prime[0] >= 0) {
return false;
}
BigInteger dhBI = new BigInteger(1, prime);
if (g == 2) { // p mod 8 = 7 for g = 2;
BigInteger res = dhBI.mod(BigInteger.valueOf(8));
if (res.intValue() != 7) {
return false;
}
} else if (g == 3) { // p mod 3 = 2 for g = 3;
BigInteger res = dhBI.mod(BigInteger.valueOf(3));
if (res.intValue() != 2) {
return false;
}
} else if (g == 5) { // p mod 5 = 1 or 4 for g = 5;
BigInteger res = dhBI.mod(BigInteger.valueOf(5));
int val = res.intValue();
if (val != 1 && val != 4) {
return false;
}
} else if (g == 6) { // p mod 24 = 19 or 23 for g = 6;
BigInteger res = dhBI.mod(BigInteger.valueOf(24));
int val = res.intValue();
if (val != 19 && val != 23) {
return false;
}
} else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7.
BigInteger res = dhBI.mod(BigInteger.valueOf(7));
int val = res.intValue();
if (val != 3 && val != 5 && val != 6) {
return false;
}
}
String hex = bytesToHex(prime);
if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) {
return true;
}
BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2));
return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30));
}
public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) {
return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0);
}
public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) {
if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) {
return false;
}
boolean result = true;
for (int a = offset1; a < arr1.length; a++) {
if (arr1[a + offset1] != arr2[a + offset2]) {
result = false;
}
}
return result;
}
public static byte[] computeSHA1(byte[] convertme, int offset, int len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(convertme, offset, len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
int oldp = convertme.position();
int oldl = convertme.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
convertme.position(offset);
convertme.limit(len);
md.update(convertme);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
convertme.limit(oldl);
convertme.position(oldp);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme) {
return computeSHA1(convertme, 0, convertme.limit());
}
public static byte[] computeSHA1(byte[] convertme) {
return computeSHA1(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme) {
return computeSHA256(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme, int offset, long len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(convertme, offset, (int) len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA256(byte[]... args) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (int a = 0; a < args.length; a++) {
md.update(args[a], 0, args[a].length);
}
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA512(byte[] convertme) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computePBKDF2(byte[] password, byte[] salt) {
byte[] dst = new byte[64];
Utilities.pbkdf2(password, salt, dst, 100000);
return dst;
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
md.update(convertme3, 0, convertme3.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) {
int oldp = b2.position();
int oldl = b2.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(b1, o1, l1);
b2.position(o2);
b2.limit(l2);
md.update(b2);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
b2.limit(oldl);
b2.position(oldp);
}
return new byte[32];
}
public static long bytesToLong(byte[] bytes) {
return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32)
+ (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF);
}
public static int bytesToInt(byte[] bytes) {
return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF);
}
public static byte[] intToBytes(int value) {
return new byte[]{
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value};
}
public static String MD5(String md5) {
if (md5 == null) {
return null;
}
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(AndroidUtilities.getStringBytes(md5));
StringBuilder sb = new StringBuilder();
for (int a = 0; a < array.length; a++) {
sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
FileLog.e(e);
}
return null;
}
public static int clamp(int value, int maxValue, int minValue) {
return Math.max(Math.min(value, maxValue), minValue);
}
public static long clamp(long value, long maxValue, long minValue) {
return Math.max(Math.min(value, maxValue), minValue);
}
public static float clamp(float value, float maxValue, float minValue) {
if (Float.isNaN(value)) {
return minValue;
}
if (Float.isInfinite(value)) {
return maxValue;
}
return Math.max(Math.min(value, maxValue), minValue);
}
public static double clamp(double value, double maxValue, double minValue) {
if (Double.isNaN(value)) {
return minValue;
}
if (Double.isInfinite(value)) {
return maxValue;
}
return Math.max(Math.min(value, maxValue), minValue);
}
public static String generateRandomString() {
return generateRandomString(16);
}
public static String generateRandomString(int chars) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars; i++) {
sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length())));
}
return sb.toString();
}
public static String getExtension(String fileName) {
int idx = fileName.lastIndexOf('.');
String ext = null;
if (idx != -1) {
ext = fileName.substring(idx + 1);
}
if (ext == null) {
return null;
}
ext = ext.toUpperCase();
return ext;
}
public static interface Callback<T> {
public void run(T arg);
}
public static interface CallbackVoidReturn<ReturnType> {
public ReturnType run();
}
public static interface Callback0Return<ReturnType> {
public ReturnType run();
}
public static interface CallbackReturn<Arg, ReturnType> {
public ReturnType run(Arg arg);
}
public static interface Callback2Return<T1, T2, ReturnType> {
public ReturnType run(T1 arg, T2 arg2);
}
public static interface Callback3Return<T1, T2, T3, ReturnType> {
public ReturnType run(T1 arg, T2 arg2, T3 arg3);
}
public static interface Callback2<T, T2> {
public void run(T arg, T2 arg2);
}
public static interface Callback3<T, T2, T3> {
public void run(T arg, T2 arg2, T3 arg3);
}
public static interface Callback4<T, T2, T3, T4> {
public void run(T arg, T2 arg2, T3 arg3, T4 arg4);
}
public static interface Callback4Return<T, T2, T3, T4, ReturnType> {
public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4);
}
public static interface Callback5<T, T2, T3, T4, T5> {
public void run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
}
public static interface Callback5Return<T, T2, T3, T4, T5, ReturnType> {
public ReturnType run(T arg, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
}
public static interface IndexedConsumer<T> {
void accept(T t, int index);
}
public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) {
Value v = map.get(key);
if (v == null) {
return defaultValue;
}
return v;
}
public static void doCallbacks(Utilities.Callback<Runnable> ...actions) {
doCallbacks(0, actions);
}
private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) {
if (actions != null && actions.length > i) {
actions[i].run(() -> doCallbacks(i + 1, actions));
}
}
public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) {
if (actions == null || actions.length == 0) {
if (onFinish != null) {
onFinish.run();
}
return;
}
final int[] finished = new int[] { 0 };
Runnable checkFinish = () -> {
finished[0]++;
if (finished[0] == actions.length) {
if (onFinish != null) {
onFinish.run();
}
}
};
for (int i = 0; i < actions.length; ++i) {
actions[i].run(checkFinish);
}
}
public static DispatchQueue getOrCreatePlayerQueue() {
if (videoPlayerQueue == null) {
videoPlayerQueue = new DispatchQueue("playerQueue");
}
return videoPlayerQueue;
}
public static boolean isNullOrEmpty(final Collection<?> list) {
return list == null || list.isEmpty();
}
}
|
199986_7 | package RoomServicePkg;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Created by cmpe 202 - group 4 on 4/12/16.
*/
public class RoomServiceController {
// price list
public Double burgerPrice = 12.0;
public Double fishPrice = 15.5;
public Double saladPrice = 11.0;
public Double eggPrice = 2.45;
public Double baconPrice = 3.50;
public Double mushPrice = 3.00;
private static RoomServiceController ourInstance = new RoomServiceController();
public static RoomServiceController getInstance() {
return ourInstance;
}
private RoomServiceControllerState burgerState;
private RoomServiceControllerState saladState;
private RoomServiceControllerState currentState;
private RoomServiceController() {
burgerState = new BurgerState(this);
saladState = new SaladState(this);
// start in burger state by default;
currentState = new NoEntreeState(this);
}
RoomService currentOrder;
ArrayList<RoomService> burgerList = null;
ArrayList<RoomService> saladList = null;
Integer baconCnt = 0;
Integer eggCnt = 0;
Integer mushCnt = 0;
Integer fishCnt = 0;
Double bill = 0.0;
PriceDecorator billDecorator = null;
private RoomServiceScreen menuScreen = new RoomServiceScreen(this);
public void setMenuScreenFrame(JFrame frame, Container pane){
menuScreen.setFrame(frame, pane);
}
public void startNewOrder(Integer roomNumber){
bill = 0.0;
// start menu screen
menuScreen.draw();
// start order
currentOrder = new RoomServiceOrder("Order for room: " + roomNumber.toString(), 0.0);
}
public void newBurger(){
if (burgerList == null){
burgerList = new ArrayList<RoomService>();
}
burgerList.add(new MominetteBurger("MominetteBurger", burgerPrice));
currentState = burgerState;
}
public void GrilledAppleSalad(){
if (saladList == null){
saladList = new ArrayList<RoomService>();
}
saladList.add(new GrilledAppleSalad("GrilledAppleSalad", saladPrice));
currentState = saladState;
}
public void addBacon(){
PriceDecorator baconDecorator = null;
/* if (burgerList != null){
if (billDecorator == null){
baconDecorator = new Bacon("Bacon", baconPrice, burgerList.get(burgerList.size() - 1));
} else {
baconDecorator = new Bacon("Bacon", baconPrice, (RoomService) billDecorator);
}
billDecorator = baconDecorator;
burgerList.get(burgerList.size() - 1).addChild((RoomService) baconDecorator);
}*/
currentState.doAddOnBacon(baconDecorator);
baconCnt++;
}
public void addEgg(){
PriceDecorator eggDecorator = null;
/* if (burgerList != null){
if (billDecorator == null){
eggDecorator = new Egg("Egg", eggPrice, burgerList.get(burgerList.size() - 1));
} else {
eggDecorator = new Egg("Egg", eggPrice, (RoomService) billDecorator);
}
billDecorator = eggDecorator;
burgerList.get(burgerList.size() - 1).addChild((RoomService) eggDecorator);
}*/
currentState.doAddOnEgg(eggDecorator);
eggCnt++;
}
public void addMushroom(){
PriceDecorator mush = null;
/* if (burgerList != null){
if (billDecorator == null){
mush = new Egg("Mushroom", mushPrice, burgerList.get(burgerList.size() - 1));
} else {
mush = new Egg("Mushroom", mushPrice, (RoomService) billDecorator);
}
billDecorator = mush;
burgerList.get(burgerList.size() - 1).addChild((RoomService) mush);
}*/
currentState.doAddOnMushroom(mush);
mushCnt++;
}
public void newMarketFish(){
currentOrder.addChild(new WildMarketFish("Alaskan Halibut", fishPrice));
fishCnt++;
}
public Double finishOrder(){
bill = 0.0;
if (burgerList != null) {
for (RoomService burger : burgerList) {
currentOrder.addChild(burger);
}
if (billDecorator != null) {
bill += billDecorator.getPrice() + (burgerList.size() - 1) * burgerPrice + fishCnt * fishPrice;
} else {
if (burgerList != null) {
bill += burgerList.size() * burgerPrice;
}
}
}
if (saladList != null){
for (RoomService salad : saladList) {
currentOrder.addChild(salad);
}
if (billDecorator != null) {
bill += billDecorator.getPrice() + (saladList.size() - 1) * saladPrice + fishCnt * fishPrice;
} else {
if (saladList != null) {
bill += saladList.size() * saladPrice;
}
}
}
bill += fishCnt * fishPrice;
//Composite prints bill
currentOrder.printItems();
//Decorator gets prioe
System.out.print("Final bill: $" + bill.toString());
System.out.println(); System.out.println();
// clear all billing
burgerList = null;
saladList = null;
billDecorator = null;
fishCnt = 0;
return bill;
}
void clearBill(){
bill = 0.0;
}
}
| Nergal16/cmpe202project | src/RoomServicePkg/RoomServiceController.java | 1,644 | //Decorator gets prioe | line_comment | nl | package RoomServicePkg;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Created by cmpe 202 - group 4 on 4/12/16.
*/
public class RoomServiceController {
// price list
public Double burgerPrice = 12.0;
public Double fishPrice = 15.5;
public Double saladPrice = 11.0;
public Double eggPrice = 2.45;
public Double baconPrice = 3.50;
public Double mushPrice = 3.00;
private static RoomServiceController ourInstance = new RoomServiceController();
public static RoomServiceController getInstance() {
return ourInstance;
}
private RoomServiceControllerState burgerState;
private RoomServiceControllerState saladState;
private RoomServiceControllerState currentState;
private RoomServiceController() {
burgerState = new BurgerState(this);
saladState = new SaladState(this);
// start in burger state by default;
currentState = new NoEntreeState(this);
}
RoomService currentOrder;
ArrayList<RoomService> burgerList = null;
ArrayList<RoomService> saladList = null;
Integer baconCnt = 0;
Integer eggCnt = 0;
Integer mushCnt = 0;
Integer fishCnt = 0;
Double bill = 0.0;
PriceDecorator billDecorator = null;
private RoomServiceScreen menuScreen = new RoomServiceScreen(this);
public void setMenuScreenFrame(JFrame frame, Container pane){
menuScreen.setFrame(frame, pane);
}
public void startNewOrder(Integer roomNumber){
bill = 0.0;
// start menu screen
menuScreen.draw();
// start order
currentOrder = new RoomServiceOrder("Order for room: " + roomNumber.toString(), 0.0);
}
public void newBurger(){
if (burgerList == null){
burgerList = new ArrayList<RoomService>();
}
burgerList.add(new MominetteBurger("MominetteBurger", burgerPrice));
currentState = burgerState;
}
public void GrilledAppleSalad(){
if (saladList == null){
saladList = new ArrayList<RoomService>();
}
saladList.add(new GrilledAppleSalad("GrilledAppleSalad", saladPrice));
currentState = saladState;
}
public void addBacon(){
PriceDecorator baconDecorator = null;
/* if (burgerList != null){
if (billDecorator == null){
baconDecorator = new Bacon("Bacon", baconPrice, burgerList.get(burgerList.size() - 1));
} else {
baconDecorator = new Bacon("Bacon", baconPrice, (RoomService) billDecorator);
}
billDecorator = baconDecorator;
burgerList.get(burgerList.size() - 1).addChild((RoomService) baconDecorator);
}*/
currentState.doAddOnBacon(baconDecorator);
baconCnt++;
}
public void addEgg(){
PriceDecorator eggDecorator = null;
/* if (burgerList != null){
if (billDecorator == null){
eggDecorator = new Egg("Egg", eggPrice, burgerList.get(burgerList.size() - 1));
} else {
eggDecorator = new Egg("Egg", eggPrice, (RoomService) billDecorator);
}
billDecorator = eggDecorator;
burgerList.get(burgerList.size() - 1).addChild((RoomService) eggDecorator);
}*/
currentState.doAddOnEgg(eggDecorator);
eggCnt++;
}
public void addMushroom(){
PriceDecorator mush = null;
/* if (burgerList != null){
if (billDecorator == null){
mush = new Egg("Mushroom", mushPrice, burgerList.get(burgerList.size() - 1));
} else {
mush = new Egg("Mushroom", mushPrice, (RoomService) billDecorator);
}
billDecorator = mush;
burgerList.get(burgerList.size() - 1).addChild((RoomService) mush);
}*/
currentState.doAddOnMushroom(mush);
mushCnt++;
}
public void newMarketFish(){
currentOrder.addChild(new WildMarketFish("Alaskan Halibut", fishPrice));
fishCnt++;
}
public Double finishOrder(){
bill = 0.0;
if (burgerList != null) {
for (RoomService burger : burgerList) {
currentOrder.addChild(burger);
}
if (billDecorator != null) {
bill += billDecorator.getPrice() + (burgerList.size() - 1) * burgerPrice + fishCnt * fishPrice;
} else {
if (burgerList != null) {
bill += burgerList.size() * burgerPrice;
}
}
}
if (saladList != null){
for (RoomService salad : saladList) {
currentOrder.addChild(salad);
}
if (billDecorator != null) {
bill += billDecorator.getPrice() + (saladList.size() - 1) * saladPrice + fishCnt * fishPrice;
} else {
if (saladList != null) {
bill += saladList.size() * saladPrice;
}
}
}
bill += fishCnt * fishPrice;
//Composite prints bill
currentOrder.printItems();
//Decorator gets<SUF>
System.out.print("Final bill: $" + bill.toString());
System.out.println(); System.out.println();
// clear all billing
burgerList = null;
saladList = null;
billDecorator = null;
fishCnt = 0;
return bill;
}
void clearBill(){
bill = 0.0;
}
}
|
12524_2 | /*
* (c) Copyright IBM Corp 2001, 2006
*/
package com.ibm.wsdl.util;
import java.util.*;
/**
* The <em>ObjectRegistry</em> is used to do name-to-object reference lookups.
* If an <em>ObjectRegistry</em> is passed as a constructor argument, then this
* <em>ObjectRegistry</em> will be a cascading registry: when a lookup is
* invoked, it will first look in its own table for a name, and if it's not
* there, it will cascade to the parent <em>ObjectRegistry</em>.
* All registration is always local. [??]
*
* @author Sanjiva Weerawarana
* @author Matthew J. Duftler
*/
public class ObjectRegistry {
Hashtable reg = new Hashtable ();
ObjectRegistry parent = null;
public ObjectRegistry () {
}
public ObjectRegistry (Map initialValues) {
if(initialValues != null)
{
Iterator itr = initialValues.keySet().iterator();
while(itr.hasNext())
{
String name = (String) itr.next();
register(name, initialValues.get(name));
}
}
}
public ObjectRegistry (ObjectRegistry parent) {
this.parent = parent;
}
// register an object
public void register (String name, Object obj) {
reg.put (name, obj);
}
// unregister an object (silent if unknown name)
public void unregister (String name) {
reg.remove (name);
}
// lookup an object: cascade up if needed
public Object lookup (String name) throws IllegalArgumentException {
Object obj = reg.get (name);
if (obj == null && parent != null) {
obj = parent.lookup (name);
}
if (obj == null) {
throw new IllegalArgumentException ("object '" + name + "' not in registry");
}
return obj;
}
} | NetSPI/Wsdler | src/main/java/com/ibm/wsdl/util/ObjectRegistry.java | 513 | // register an object | line_comment | nl | /*
* (c) Copyright IBM Corp 2001, 2006
*/
package com.ibm.wsdl.util;
import java.util.*;
/**
* The <em>ObjectRegistry</em> is used to do name-to-object reference lookups.
* If an <em>ObjectRegistry</em> is passed as a constructor argument, then this
* <em>ObjectRegistry</em> will be a cascading registry: when a lookup is
* invoked, it will first look in its own table for a name, and if it's not
* there, it will cascade to the parent <em>ObjectRegistry</em>.
* All registration is always local. [??]
*
* @author Sanjiva Weerawarana
* @author Matthew J. Duftler
*/
public class ObjectRegistry {
Hashtable reg = new Hashtable ();
ObjectRegistry parent = null;
public ObjectRegistry () {
}
public ObjectRegistry (Map initialValues) {
if(initialValues != null)
{
Iterator itr = initialValues.keySet().iterator();
while(itr.hasNext())
{
String name = (String) itr.next();
register(name, initialValues.get(name));
}
}
}
public ObjectRegistry (ObjectRegistry parent) {
this.parent = parent;
}
// register an<SUF>
public void register (String name, Object obj) {
reg.put (name, obj);
}
// unregister an object (silent if unknown name)
public void unregister (String name) {
reg.remove (name);
}
// lookup an object: cascade up if needed
public Object lookup (String name) throws IllegalArgumentException {
Object obj = reg.get (name);
if (obj == null && parent != null) {
obj = parent.lookup (name);
}
if (obj == null) {
throw new IllegalArgumentException ("object '" + name + "' not in registry");
}
return obj;
}
} |
191120_7 | /*
* Copyright 2012 Netflix, Inc.
*
* 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.netflix.blitz4j;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.Loader;
import org.apache.log4j.spi.LoggerFactory;
import org.slf4j.Logger;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.ExpandedConfigurationListenerAdapter;
import com.netflix.config.PropertyListener;
import com.netflix.logging.messaging.BatcherFactory;
import com.netflix.logging.messaging.MessageBatcher;
/**
* The main configuration class that bootstraps the <em>blitz4j</em>
* implementation.
*
* <p>
* The users can either use {@link #configure()} or
* {@link #configure(Properties)} to kick start the configuration. If the
* <code>log4j.configuration</code> is provided, the properties are additionally
* loaded from the provided {@link URL}.
* </p>
*
* <p>
* The list of appenders to be automatically converted can be provided by the
* property <code>log4j.logger.asyncAppenders</code>. The configuration takes
* these appenders and automatically enables them for asynchronous logging.
* </p>
*
* @author Karthik Ranganathan
*
*/
public class LoggingConfiguration implements PropertyListener {
private static final String LOG4J_ROOT_LOGGER = "log4j.rootLogger";
private static final String LOG4J_ROOT_CATEGORY = "log4j.rootCategory";
private static final String LOG4J_PROPERTIES = "log4j.properties";
private static final String BLITZ_LOGGER_FACTORY = "com.netflix.blitz4j.NFCategoryFactory";
private static final String PROP_LOG4J_CONFIGURATION = "log4j.configuration";
private static final Object guard = new Object();
private static final String PROP_LOG4J_LOGGER_FACTORY = "log4j.loggerFactory";
private static final String LOG4J_FACTORY_IMPL = "com.netflix.logging.log4jAdapter.NFCategoryFactory";
private static final String LOG4J_LOGGER_FACTORY = "log4j.loggerFactory";
private static final String PROP_LOG4J_ORIGINAL_APPENDER_NAME = "originalAppenderName";
private static final String LOG4J_PREFIX = "log4j.logger";
private static final String LOG4J_APPENDER_DELIMITER = ".";
private static final String LOG4J_APPENDER_PREFIX = "log4j.appender";
private static final String ASYNC_APPENDERNAME_SUFFIX = "_ASYNC";
private static final String ROOT_CATEGORY = "rootCategory";
private static final String ROOT_LOGGER = "rootLogger";
private Map<String, String> originalAsyncAppenderNameMap = new HashMap<String, String>();
private BlitzConfig blitz4jConfig;
private Properties initialProps = new Properties();
private Properties overrideProps = new Properties();
private final ExecutorService executorPool;
private final AtomicInteger pendingRefreshes = new AtomicInteger();
private final AtomicInteger refreshCount = new AtomicInteger();
private Logger logger;
private static final int MIN_DELAY_BETWEEN_REFRESHES = 200;
private static final CharSequence PROP_LOG4J_ASYNC_APPENDERS = "log4j.logger.asyncAppenders";
private static LoggingConfiguration instance = new LoggingConfiguration();
protected LoggingConfiguration() {
this.executorPool = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(false)
.setNameFormat("DynamicLog4jListener")
.build());
}
/**
* Kick start the blitz4j implementation
*/
public void configure() {
this.configure(new Properties());
}
/**
* Kick start the blitz4j implementation.
*
* @param props
* - The overriding <em>log4j</em> properties if any.
*/
public void configure(Properties props) {
this.refreshCount.set(0);
this.overrideProps.clear();
this.originalAsyncAppenderNameMap.clear();
// First try to load the log4j configuration file from the classpath
String log4jConfigurationFile = System.getProperty(PROP_LOG4J_CONFIGURATION);
NFHierarchy nfHierarchy = null;
// Make log4j use blitz4j implementations
if ((!NFHierarchy.class.equals(LogManager.getLoggerRepository().getClass()))) {
nfHierarchy = new NFHierarchy(new NFRootLogger(org.apache.log4j.Level.INFO));
org.apache.log4j.LogManager.setRepositorySelector(new NFRepositorySelector(nfHierarchy), guard);
}
String log4jLoggerFactory = System.getProperty(PROP_LOG4J_LOGGER_FACTORY);
if (log4jLoggerFactory != null) {
this.initialProps.setProperty(PROP_LOG4J_LOGGER_FACTORY, log4jLoggerFactory);
if (nfHierarchy != null) {
try {
LoggerFactory loggerFactory = (LoggerFactory) Class.forName(log4jLoggerFactory).newInstance();
nfHierarchy.setLoggerFactory(loggerFactory);
} catch (Exception e) {
System.err.println("Cannot set the logger factory. Hence reverting to default.");
e.printStackTrace();
}
}
} else {
this.initialProps.setProperty(PROP_LOG4J_LOGGER_FACTORY, BLITZ_LOGGER_FACTORY);
}
if (log4jConfigurationFile != null) {
loadLog4jConfigurationFile(log4jConfigurationFile);
// First configure without async so that we can capture the output
// of dependent libraries
clearAsyncAppenderList();
PropertyConfigurator.configure(this.initialProps);
}
this.blitz4jConfig = new DefaultBlitz4jConfig(props);
if ((log4jConfigurationFile == null) && (blitz4jConfig.shouldLoadLog4jPropertiesFromClassPath())) {
try {
URL url = Loader.getResource(LOG4J_PROPERTIES);
if (url != null) {
try (InputStream in = url.openStream()) {
this.initialProps.load(in);
}
}
} catch (Exception t) {
System.err.println("Error loading properties from " + LOG4J_PROPERTIES);
}
}
Enumeration enumeration = props.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String propertyValue = props.getProperty(key);
this.initialProps.setProperty(key, propertyValue);
}
this.blitz4jConfig = new DefaultBlitz4jConfig(this.initialProps);
String[] asyncAppenderArray = blitz4jConfig.getAsyncAppenders();
if (asyncAppenderArray == null) {
return;
}
for (int i = 0; i < asyncAppenderArray.length; i++) {
String oneAppenderName = asyncAppenderArray[i];
if ((i == 0) || (oneAppenderName == null)) {
continue;
}
oneAppenderName = oneAppenderName.trim();
String oneAsyncAppenderName = oneAppenderName + ASYNC_APPENDERNAME_SUFFIX;
originalAsyncAppenderNameMap.put(oneAppenderName, oneAsyncAppenderName);
}
try {
convertConfiguredAppendersToAsync(this.initialProps);
} catch (Exception e) {
throw new RuntimeException("Could not configure async appenders ",
e);
}
// Yes second time init required as properties would have been during async appender conversion
this.blitz4jConfig = new DefaultBlitz4jConfig(this.initialProps);
clearAsyncAppenderList();
PropertyConfigurator.configure(this.initialProps);
closeNonexistingAsyncAppenders();
this.logger = org.slf4j.LoggerFactory.getLogger(LoggingConfiguration.class);
ConfigurationManager.getConfigInstance().addConfigurationListener(
new ExpandedConfigurationListenerAdapter(this));
}
private void clearAsyncAppenderList() {
org.apache.log4j.Logger asyncLogger = LoggerCache.getInstance().getOrCreateLogger("asyncAppenders");
if (asyncLogger != null) {
asyncLogger.removeAllAppenders();
}
}
private void loadLog4jConfigurationFile(String log4jConfigurationFile) {
try {
URL url = new URL(log4jConfigurationFile);
try (InputStream in = url.openStream()) {
this.initialProps.load(in);
}
} catch (Exception t) {
throw new RuntimeException(
"Cannot load log4 configuration file specified in " + PROP_LOG4J_CONFIGURATION, t);
}
}
public static LoggingConfiguration getInstance() {
return instance;
}
public BlitzConfig getConfiguration() {
return this.blitz4jConfig;
}
public Properties getInitialProperties() {
Properties props = new Properties();
props.putAll(this.initialProps);
return props;
}
public Properties getOverrideProperties() {
Properties props = new Properties();
props.putAll(this.overrideProps);
return props;
}
public int getRefreshCount() {
return this.refreshCount.get();
}
/**
* Shuts down blitz4j cleanly by flushing out all the async related
* messages.
*/
public void stop() {
MessageBatcher batcher = null;
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
String batcherName = AsyncAppender.class.getName() + "." + originalAppenderName;
batcher = BatcherFactory.getBatcher(batcherName);
if (batcher == null) {
continue;
}
batcher.stop();
}
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
String batcherName = AsyncAppender.class.getName() + "." + originalAppenderName;
batcher = BatcherFactory.getBatcher(batcherName);
if (batcher == null) {
continue;
}
BatcherFactory.removeBatcher(batcherName);
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#addProperty(java.lang.Object,
* java.lang.String, java.lang.Object, boolean)
*/
public synchronized void addProperty(Object source, String name, Object value, boolean beforeUpdate) {
if (beforeUpdate == false && isLog4JProperty(name)) {
overrideProps.put(name, value);
reConfigureAsynchronously();
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#clear(java.lang.Object, boolean)
*/
public void clear(Object source, boolean beforeUpdate) {
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#clearProperty(java.lang.Object,
* java.lang.String, java.lang.Object, boolean)
*/
public synchronized void clearProperty(Object source, String name, Object value, boolean beforeUpdate) {
if (beforeUpdate == false && isLog4JProperty(name)) {
overrideProps.remove(name);
reConfigureAsynchronously();
}
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.config.PropertyListener#configSourceLoaded(java.lang.Object)
*/
public void configSourceLoaded(Object source) {
AbstractConfiguration config = ConfigurationManager.getConfigInstance();
Properties props = new Properties();
char delimiter = config.getListDelimiter();
for (Iterator<String> keys = config.getKeys(LOG4J_PREFIX); keys.hasNext();) {
String key = keys.next();
List<Object> list = config.getList(key);
// turn the list into a string
props.setProperty(key, StringUtils.join(list.iterator(), delimiter));
}
reconfigure(props);
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#setProperty(java.lang.Object,
* java.lang.String, java.lang.Object, boolean)
*/
public synchronized void setProperty(Object source, String name, Object value,
boolean beforeUpdate) {
if (beforeUpdate == false && isLog4JProperty(name)) {
overrideProps.put(name, value);
reConfigureAsynchronously();
}
}
/**
* Set a snapshot of all LOG4J properties and reconfigure if properties have been
* changed. This assumes that the Properties being set here has already been filtered
* to only properties starting with LOG4J_PREFIX.
* @param props Complete set of ALL log4j configuration properties including all
* appenders and log level overrides
*/
public synchronized void reconfigure(Properties props) {
// First isolate any property that is different from the immutable
// set of original initialization properties
Properties newOverrideProps = new Properties();
for (Entry<Object, Object> prop : props.entrySet()) {
Object initialValue = initialProps.get(prop.getKey());
if (initialValue == null || !initialValue.equals(prop.getValue())) {
newOverrideProps.put(prop.getKey(), prop.getValue());
}
}
// Compare against our cached set of override
if (!overrideProps.equals(newOverrideProps)) {
this.overrideProps.clear();
this.overrideProps.putAll(newOverrideProps);
reConfigureAsynchronously();
}
}
/**
* Refresh the configuration asynchronously
*/
private void reConfigureAsynchronously() {
refreshCount.incrementAndGet();
if (pendingRefreshes.incrementAndGet() == 1) {
executorPool.submit(new Runnable() {
@Override
public void run() {
do {
try {
Thread.sleep(MIN_DELAY_BETWEEN_REFRESHES);
logger.info("Configuring log4j dynamically");
reconfigure();
}
catch (Exception th) {
logger.error("Cannot dynamically configure log4j :", th);
}
} while (0 != pendingRefreshes.getAndSet(0));
}
});
}
}
private synchronized Properties getConsolidatedProperties() {
logger.info("Override properties are :" + overrideProps);
Properties consolidatedProps = new Properties();
consolidatedProps.putAll(initialProps);
consolidatedProps.putAll(overrideProps);
return consolidatedProps;
}
/**
* Reconfigure log4j at run-time.
*
* @param name
* - The name of the property that changed
* @param value
* - The new value of the property
* @throws FileNotFoundException
* @throws ConfigurationException
*/
private void reconfigure() throws ConfigurationException, FileNotFoundException {
Properties consolidatedProps = getConsolidatedProperties();
logger.info("The root category for log4j.rootCategory now is {}", consolidatedProps.getProperty(LOG4J_ROOT_CATEGORY));
logger.info("The root category for log4j.rootLogger now is {}", consolidatedProps.getProperty(LOG4J_ROOT_LOGGER));
// Pause the async appenders so that the appenders are not accessed
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
MessageBatcher asyncBatcher = BatcherFactory.getBatcher(AsyncAppender.class.getName() + "." + originalAppenderName);
if (asyncBatcher == null) {
continue;
}
asyncBatcher.pause();
}
// Configure log4j using the new set of properties
configureLog4j(consolidatedProps);
// Resume all the batchers to continue logging
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
MessageBatcher asyncBatcher = BatcherFactory.getBatcher(AsyncAppender.class.getName() + "." + originalAppenderName);
if (asyncBatcher == null) {
continue;
}
asyncBatcher.resume();
}
}
/**
* Configure log4j with the given properties.
*
* @param props
* The properties that needs to be configured for log4j
* @throws ConfigurationException
* @throws FileNotFoundException
*/
private void configureLog4j(Properties props) throws ConfigurationException, FileNotFoundException {
if (blitz4jConfig.shouldUseLockFree() && (props.getProperty(LOG4J_LOGGER_FACTORY) == null)) {
props.setProperty(LOG4J_LOGGER_FACTORY, LOG4J_FACTORY_IMPL);
}
convertConfiguredAppendersToAsync(props);
clearAsyncAppenderList();
logger.info("Configuring log4j with properties :" + props);
PropertyConfigurator.configure(props);
}
/**
* Check if the property that is being changed is something that this
* configuration cares about.
*
* The implementation only cares about changes related to <code>log4j</code>
* properties.
*
* @param name
* -The name of the property which should be checked.
* @param beforeUpdate
* -true, if this call is made before the property has been
* updated, false otherwise.
* @return
*/
private boolean isLog4JProperty(String name) {
if (name == null) {
return false;
}
return name.startsWith(LOG4J_PREFIX);
}
/**
* Convert appenders specified by the property
* <code>log4j.logger.asyncAppender</code> to the blitz4j Asynchronous
* appenders.
*
* @param props
* - The properties that need to be passed into the log4j for
* configuration.
* @throws ConfigurationException
* @throws FileNotFoundException
*/
private void convertConfiguredAppendersToAsync(Properties props) throws ConfigurationException, FileNotFoundException {
for (Map.Entry<String, String> originalAsyncAppenderMapEntry : originalAsyncAppenderNameMap.entrySet()) {
String asyncAppenderName = originalAsyncAppenderMapEntry.getValue();
props.setProperty(LOG4J_APPENDER_PREFIX + LOG4J_APPENDER_DELIMITER + asyncAppenderName, AsyncAppender.class.getName());
// Set the original appender so that it can be fetched later after configuration
String originalAppenderName = originalAsyncAppenderMapEntry.getKey();
props.setProperty(LOG4J_APPENDER_PREFIX + LOG4J_APPENDER_DELIMITER
+ asyncAppenderName + LOG4J_APPENDER_DELIMITER
+ PROP_LOG4J_ORIGINAL_APPENDER_NAME, originalAppenderName);
// Set the batcher to reject the collector request instead of it
// participating in processing
this.initialProps.setProperty("batcher." + AsyncAppender.class.getName() + "." + originalAppenderName + "." + "rejectWhenFull", "true");
// Set the default value of the processing max threads to 1, if a
// value is not specified
String maxThreads = this.initialProps.getProperty("batcher." + AsyncAppender.class.getName() + "." + originalAppenderName + "." + "maxThreads");
if (maxThreads == null) {
this.initialProps.setProperty("batcher." + AsyncAppender.class.getName() + "." + originalAppenderName + "." + "maxThreads", "1");
}
for (Map.Entry mapEntry : props.entrySet()) {
String key = mapEntry.getKey().toString();
if ((key.contains(LOG4J_PREFIX) || key.contains(ROOT_CATEGORY) || key.contains(ROOT_LOGGER))
&& !key.contains(PROP_LOG4J_ASYNC_APPENDERS)
&& !key.contains(PROP_LOG4J_ORIGINAL_APPENDER_NAME)) {
Object value = mapEntry.getValue();
if (value != null) {
String[] values = (String.class.cast(value)).split(",");
String valueString = "";
int ctr = 0;
for (String oneValue : values) {
if (oneValue == null) {
continue;
}
++ctr;
if (originalAppenderName.equals(oneValue.trim())) {
oneValue = asyncAppenderName;
}
if (ctr != values.length) {
valueString = valueString + oneValue + ",";
} else {
valueString = valueString + oneValue;
}
}
mapEntry.setValue(valueString);
}
}
}
}
}
/**
* Closes any asynchronous appenders that were not removed during configuration.
*/
private void closeNonexistingAsyncAppenders() {
org.apache.log4j.Logger rootLogger = LogManager.getRootLogger();
if (NFLockFreeLogger.class.isInstance(rootLogger)) {
((NFLockFreeLogger)rootLogger).reconcileAppenders();
}
Enumeration enums = LogManager.getCurrentLoggers();
while (enums.hasMoreElements()) {
Object myLogger = enums.nextElement();
if (NFLockFreeLogger.class.isInstance(myLogger)) {
((NFLockFreeLogger)myLogger).reconcileAppenders();
}
}
}
}
| Netflix/blitz4j | src/main/java/com/netflix/blitz4j/LoggingConfiguration.java | 6,143 | // of dependent libraries | line_comment | nl | /*
* Copyright 2012 Netflix, Inc.
*
* 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.netflix.blitz4j;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.Loader;
import org.apache.log4j.spi.LoggerFactory;
import org.slf4j.Logger;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.ExpandedConfigurationListenerAdapter;
import com.netflix.config.PropertyListener;
import com.netflix.logging.messaging.BatcherFactory;
import com.netflix.logging.messaging.MessageBatcher;
/**
* The main configuration class that bootstraps the <em>blitz4j</em>
* implementation.
*
* <p>
* The users can either use {@link #configure()} or
* {@link #configure(Properties)} to kick start the configuration. If the
* <code>log4j.configuration</code> is provided, the properties are additionally
* loaded from the provided {@link URL}.
* </p>
*
* <p>
* The list of appenders to be automatically converted can be provided by the
* property <code>log4j.logger.asyncAppenders</code>. The configuration takes
* these appenders and automatically enables them for asynchronous logging.
* </p>
*
* @author Karthik Ranganathan
*
*/
public class LoggingConfiguration implements PropertyListener {
private static final String LOG4J_ROOT_LOGGER = "log4j.rootLogger";
private static final String LOG4J_ROOT_CATEGORY = "log4j.rootCategory";
private static final String LOG4J_PROPERTIES = "log4j.properties";
private static final String BLITZ_LOGGER_FACTORY = "com.netflix.blitz4j.NFCategoryFactory";
private static final String PROP_LOG4J_CONFIGURATION = "log4j.configuration";
private static final Object guard = new Object();
private static final String PROP_LOG4J_LOGGER_FACTORY = "log4j.loggerFactory";
private static final String LOG4J_FACTORY_IMPL = "com.netflix.logging.log4jAdapter.NFCategoryFactory";
private static final String LOG4J_LOGGER_FACTORY = "log4j.loggerFactory";
private static final String PROP_LOG4J_ORIGINAL_APPENDER_NAME = "originalAppenderName";
private static final String LOG4J_PREFIX = "log4j.logger";
private static final String LOG4J_APPENDER_DELIMITER = ".";
private static final String LOG4J_APPENDER_PREFIX = "log4j.appender";
private static final String ASYNC_APPENDERNAME_SUFFIX = "_ASYNC";
private static final String ROOT_CATEGORY = "rootCategory";
private static final String ROOT_LOGGER = "rootLogger";
private Map<String, String> originalAsyncAppenderNameMap = new HashMap<String, String>();
private BlitzConfig blitz4jConfig;
private Properties initialProps = new Properties();
private Properties overrideProps = new Properties();
private final ExecutorService executorPool;
private final AtomicInteger pendingRefreshes = new AtomicInteger();
private final AtomicInteger refreshCount = new AtomicInteger();
private Logger logger;
private static final int MIN_DELAY_BETWEEN_REFRESHES = 200;
private static final CharSequence PROP_LOG4J_ASYNC_APPENDERS = "log4j.logger.asyncAppenders";
private static LoggingConfiguration instance = new LoggingConfiguration();
protected LoggingConfiguration() {
this.executorPool = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(false)
.setNameFormat("DynamicLog4jListener")
.build());
}
/**
* Kick start the blitz4j implementation
*/
public void configure() {
this.configure(new Properties());
}
/**
* Kick start the blitz4j implementation.
*
* @param props
* - The overriding <em>log4j</em> properties if any.
*/
public void configure(Properties props) {
this.refreshCount.set(0);
this.overrideProps.clear();
this.originalAsyncAppenderNameMap.clear();
// First try to load the log4j configuration file from the classpath
String log4jConfigurationFile = System.getProperty(PROP_LOG4J_CONFIGURATION);
NFHierarchy nfHierarchy = null;
// Make log4j use blitz4j implementations
if ((!NFHierarchy.class.equals(LogManager.getLoggerRepository().getClass()))) {
nfHierarchy = new NFHierarchy(new NFRootLogger(org.apache.log4j.Level.INFO));
org.apache.log4j.LogManager.setRepositorySelector(new NFRepositorySelector(nfHierarchy), guard);
}
String log4jLoggerFactory = System.getProperty(PROP_LOG4J_LOGGER_FACTORY);
if (log4jLoggerFactory != null) {
this.initialProps.setProperty(PROP_LOG4J_LOGGER_FACTORY, log4jLoggerFactory);
if (nfHierarchy != null) {
try {
LoggerFactory loggerFactory = (LoggerFactory) Class.forName(log4jLoggerFactory).newInstance();
nfHierarchy.setLoggerFactory(loggerFactory);
} catch (Exception e) {
System.err.println("Cannot set the logger factory. Hence reverting to default.");
e.printStackTrace();
}
}
} else {
this.initialProps.setProperty(PROP_LOG4J_LOGGER_FACTORY, BLITZ_LOGGER_FACTORY);
}
if (log4jConfigurationFile != null) {
loadLog4jConfigurationFile(log4jConfigurationFile);
// First configure without async so that we can capture the output
// of dependent<SUF>
clearAsyncAppenderList();
PropertyConfigurator.configure(this.initialProps);
}
this.blitz4jConfig = new DefaultBlitz4jConfig(props);
if ((log4jConfigurationFile == null) && (blitz4jConfig.shouldLoadLog4jPropertiesFromClassPath())) {
try {
URL url = Loader.getResource(LOG4J_PROPERTIES);
if (url != null) {
try (InputStream in = url.openStream()) {
this.initialProps.load(in);
}
}
} catch (Exception t) {
System.err.println("Error loading properties from " + LOG4J_PROPERTIES);
}
}
Enumeration enumeration = props.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String propertyValue = props.getProperty(key);
this.initialProps.setProperty(key, propertyValue);
}
this.blitz4jConfig = new DefaultBlitz4jConfig(this.initialProps);
String[] asyncAppenderArray = blitz4jConfig.getAsyncAppenders();
if (asyncAppenderArray == null) {
return;
}
for (int i = 0; i < asyncAppenderArray.length; i++) {
String oneAppenderName = asyncAppenderArray[i];
if ((i == 0) || (oneAppenderName == null)) {
continue;
}
oneAppenderName = oneAppenderName.trim();
String oneAsyncAppenderName = oneAppenderName + ASYNC_APPENDERNAME_SUFFIX;
originalAsyncAppenderNameMap.put(oneAppenderName, oneAsyncAppenderName);
}
try {
convertConfiguredAppendersToAsync(this.initialProps);
} catch (Exception e) {
throw new RuntimeException("Could not configure async appenders ",
e);
}
// Yes second time init required as properties would have been during async appender conversion
this.blitz4jConfig = new DefaultBlitz4jConfig(this.initialProps);
clearAsyncAppenderList();
PropertyConfigurator.configure(this.initialProps);
closeNonexistingAsyncAppenders();
this.logger = org.slf4j.LoggerFactory.getLogger(LoggingConfiguration.class);
ConfigurationManager.getConfigInstance().addConfigurationListener(
new ExpandedConfigurationListenerAdapter(this));
}
private void clearAsyncAppenderList() {
org.apache.log4j.Logger asyncLogger = LoggerCache.getInstance().getOrCreateLogger("asyncAppenders");
if (asyncLogger != null) {
asyncLogger.removeAllAppenders();
}
}
private void loadLog4jConfigurationFile(String log4jConfigurationFile) {
try {
URL url = new URL(log4jConfigurationFile);
try (InputStream in = url.openStream()) {
this.initialProps.load(in);
}
} catch (Exception t) {
throw new RuntimeException(
"Cannot load log4 configuration file specified in " + PROP_LOG4J_CONFIGURATION, t);
}
}
public static LoggingConfiguration getInstance() {
return instance;
}
public BlitzConfig getConfiguration() {
return this.blitz4jConfig;
}
public Properties getInitialProperties() {
Properties props = new Properties();
props.putAll(this.initialProps);
return props;
}
public Properties getOverrideProperties() {
Properties props = new Properties();
props.putAll(this.overrideProps);
return props;
}
public int getRefreshCount() {
return this.refreshCount.get();
}
/**
* Shuts down blitz4j cleanly by flushing out all the async related
* messages.
*/
public void stop() {
MessageBatcher batcher = null;
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
String batcherName = AsyncAppender.class.getName() + "." + originalAppenderName;
batcher = BatcherFactory.getBatcher(batcherName);
if (batcher == null) {
continue;
}
batcher.stop();
}
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
String batcherName = AsyncAppender.class.getName() + "." + originalAppenderName;
batcher = BatcherFactory.getBatcher(batcherName);
if (batcher == null) {
continue;
}
BatcherFactory.removeBatcher(batcherName);
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#addProperty(java.lang.Object,
* java.lang.String, java.lang.Object, boolean)
*/
public synchronized void addProperty(Object source, String name, Object value, boolean beforeUpdate) {
if (beforeUpdate == false && isLog4JProperty(name)) {
overrideProps.put(name, value);
reConfigureAsynchronously();
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#clear(java.lang.Object, boolean)
*/
public void clear(Object source, boolean beforeUpdate) {
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#clearProperty(java.lang.Object,
* java.lang.String, java.lang.Object, boolean)
*/
public synchronized void clearProperty(Object source, String name, Object value, boolean beforeUpdate) {
if (beforeUpdate == false && isLog4JProperty(name)) {
overrideProps.remove(name);
reConfigureAsynchronously();
}
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.config.PropertyListener#configSourceLoaded(java.lang.Object)
*/
public void configSourceLoaded(Object source) {
AbstractConfiguration config = ConfigurationManager.getConfigInstance();
Properties props = new Properties();
char delimiter = config.getListDelimiter();
for (Iterator<String> keys = config.getKeys(LOG4J_PREFIX); keys.hasNext();) {
String key = keys.next();
List<Object> list = config.getList(key);
// turn the list into a string
props.setProperty(key, StringUtils.join(list.iterator(), delimiter));
}
reconfigure(props);
}
/*
* (non-Javadoc)
*
* @see com.netflix.config.PropertyListener#setProperty(java.lang.Object,
* java.lang.String, java.lang.Object, boolean)
*/
public synchronized void setProperty(Object source, String name, Object value,
boolean beforeUpdate) {
if (beforeUpdate == false && isLog4JProperty(name)) {
overrideProps.put(name, value);
reConfigureAsynchronously();
}
}
/**
* Set a snapshot of all LOG4J properties and reconfigure if properties have been
* changed. This assumes that the Properties being set here has already been filtered
* to only properties starting with LOG4J_PREFIX.
* @param props Complete set of ALL log4j configuration properties including all
* appenders and log level overrides
*/
public synchronized void reconfigure(Properties props) {
// First isolate any property that is different from the immutable
// set of original initialization properties
Properties newOverrideProps = new Properties();
for (Entry<Object, Object> prop : props.entrySet()) {
Object initialValue = initialProps.get(prop.getKey());
if (initialValue == null || !initialValue.equals(prop.getValue())) {
newOverrideProps.put(prop.getKey(), prop.getValue());
}
}
// Compare against our cached set of override
if (!overrideProps.equals(newOverrideProps)) {
this.overrideProps.clear();
this.overrideProps.putAll(newOverrideProps);
reConfigureAsynchronously();
}
}
/**
* Refresh the configuration asynchronously
*/
private void reConfigureAsynchronously() {
refreshCount.incrementAndGet();
if (pendingRefreshes.incrementAndGet() == 1) {
executorPool.submit(new Runnable() {
@Override
public void run() {
do {
try {
Thread.sleep(MIN_DELAY_BETWEEN_REFRESHES);
logger.info("Configuring log4j dynamically");
reconfigure();
}
catch (Exception th) {
logger.error("Cannot dynamically configure log4j :", th);
}
} while (0 != pendingRefreshes.getAndSet(0));
}
});
}
}
private synchronized Properties getConsolidatedProperties() {
logger.info("Override properties are :" + overrideProps);
Properties consolidatedProps = new Properties();
consolidatedProps.putAll(initialProps);
consolidatedProps.putAll(overrideProps);
return consolidatedProps;
}
/**
* Reconfigure log4j at run-time.
*
* @param name
* - The name of the property that changed
* @param value
* - The new value of the property
* @throws FileNotFoundException
* @throws ConfigurationException
*/
private void reconfigure() throws ConfigurationException, FileNotFoundException {
Properties consolidatedProps = getConsolidatedProperties();
logger.info("The root category for log4j.rootCategory now is {}", consolidatedProps.getProperty(LOG4J_ROOT_CATEGORY));
logger.info("The root category for log4j.rootLogger now is {}", consolidatedProps.getProperty(LOG4J_ROOT_LOGGER));
// Pause the async appenders so that the appenders are not accessed
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
MessageBatcher asyncBatcher = BatcherFactory.getBatcher(AsyncAppender.class.getName() + "." + originalAppenderName);
if (asyncBatcher == null) {
continue;
}
asyncBatcher.pause();
}
// Configure log4j using the new set of properties
configureLog4j(consolidatedProps);
// Resume all the batchers to continue logging
for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) {
MessageBatcher asyncBatcher = BatcherFactory.getBatcher(AsyncAppender.class.getName() + "." + originalAppenderName);
if (asyncBatcher == null) {
continue;
}
asyncBatcher.resume();
}
}
/**
* Configure log4j with the given properties.
*
* @param props
* The properties that needs to be configured for log4j
* @throws ConfigurationException
* @throws FileNotFoundException
*/
private void configureLog4j(Properties props) throws ConfigurationException, FileNotFoundException {
if (blitz4jConfig.shouldUseLockFree() && (props.getProperty(LOG4J_LOGGER_FACTORY) == null)) {
props.setProperty(LOG4J_LOGGER_FACTORY, LOG4J_FACTORY_IMPL);
}
convertConfiguredAppendersToAsync(props);
clearAsyncAppenderList();
logger.info("Configuring log4j with properties :" + props);
PropertyConfigurator.configure(props);
}
/**
* Check if the property that is being changed is something that this
* configuration cares about.
*
* The implementation only cares about changes related to <code>log4j</code>
* properties.
*
* @param name
* -The name of the property which should be checked.
* @param beforeUpdate
* -true, if this call is made before the property has been
* updated, false otherwise.
* @return
*/
private boolean isLog4JProperty(String name) {
if (name == null) {
return false;
}
return name.startsWith(LOG4J_PREFIX);
}
/**
* Convert appenders specified by the property
* <code>log4j.logger.asyncAppender</code> to the blitz4j Asynchronous
* appenders.
*
* @param props
* - The properties that need to be passed into the log4j for
* configuration.
* @throws ConfigurationException
* @throws FileNotFoundException
*/
private void convertConfiguredAppendersToAsync(Properties props) throws ConfigurationException, FileNotFoundException {
for (Map.Entry<String, String> originalAsyncAppenderMapEntry : originalAsyncAppenderNameMap.entrySet()) {
String asyncAppenderName = originalAsyncAppenderMapEntry.getValue();
props.setProperty(LOG4J_APPENDER_PREFIX + LOG4J_APPENDER_DELIMITER + asyncAppenderName, AsyncAppender.class.getName());
// Set the original appender so that it can be fetched later after configuration
String originalAppenderName = originalAsyncAppenderMapEntry.getKey();
props.setProperty(LOG4J_APPENDER_PREFIX + LOG4J_APPENDER_DELIMITER
+ asyncAppenderName + LOG4J_APPENDER_DELIMITER
+ PROP_LOG4J_ORIGINAL_APPENDER_NAME, originalAppenderName);
// Set the batcher to reject the collector request instead of it
// participating in processing
this.initialProps.setProperty("batcher." + AsyncAppender.class.getName() + "." + originalAppenderName + "." + "rejectWhenFull", "true");
// Set the default value of the processing max threads to 1, if a
// value is not specified
String maxThreads = this.initialProps.getProperty("batcher." + AsyncAppender.class.getName() + "." + originalAppenderName + "." + "maxThreads");
if (maxThreads == null) {
this.initialProps.setProperty("batcher." + AsyncAppender.class.getName() + "." + originalAppenderName + "." + "maxThreads", "1");
}
for (Map.Entry mapEntry : props.entrySet()) {
String key = mapEntry.getKey().toString();
if ((key.contains(LOG4J_PREFIX) || key.contains(ROOT_CATEGORY) || key.contains(ROOT_LOGGER))
&& !key.contains(PROP_LOG4J_ASYNC_APPENDERS)
&& !key.contains(PROP_LOG4J_ORIGINAL_APPENDER_NAME)) {
Object value = mapEntry.getValue();
if (value != null) {
String[] values = (String.class.cast(value)).split(",");
String valueString = "";
int ctr = 0;
for (String oneValue : values) {
if (oneValue == null) {
continue;
}
++ctr;
if (originalAppenderName.equals(oneValue.trim())) {
oneValue = asyncAppenderName;
}
if (ctr != values.length) {
valueString = valueString + oneValue + ",";
} else {
valueString = valueString + oneValue;
}
}
mapEntry.setValue(valueString);
}
}
}
}
}
/**
* Closes any asynchronous appenders that were not removed during configuration.
*/
private void closeNonexistingAsyncAppenders() {
org.apache.log4j.Logger rootLogger = LogManager.getRootLogger();
if (NFLockFreeLogger.class.isInstance(rootLogger)) {
((NFLockFreeLogger)rootLogger).reconcileAppenders();
}
Enumeration enums = LogManager.getCurrentLoggers();
while (enums.hasMoreElements()) {
Object myLogger = enums.nextElement();
if (NFLockFreeLogger.class.isInstance(myLogger)) {
((NFLockFreeLogger)myLogger).reconcileAppenders();
}
}
}
}
|
24090_3 | /*
*
* Copyright 2014 Netflix, Inc.
*
* 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.netflix.zeno.flatblob;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.record.ByteDataBuffer;
import com.netflix.zeno.fastblob.record.VarInt;
import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState;
import com.netflix.zeno.serializer.FrameworkSerializer;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FlatBlobFrameworkSerializer extends FrameworkSerializer<FlatBlobSerializationRecord> {
static final int NULL_FLOAT_BITS = Float.floatToIntBits(Float.NaN) + 1;
static final long NULL_DOUBLE_BITS = Double.doubleToLongBits(Double.NaN) + 1;
private final FastBlobStateEngine stateEngine;
private final ThreadLocal<Map<String, FlatBlobSerializationRecord>> cachedSerializationRecords;
public FlatBlobFrameworkSerializer(FlatBlobSerializationFramework flatBlobFramework, FastBlobStateEngine stateEngine) {
super(flatBlobFramework);
this.stateEngine = stateEngine;
this.cachedSerializationRecords = new ThreadLocal<Map<String, FlatBlobSerializationRecord>>();
}
/**
* Serialize a primitive element
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, Object value) {
if (value == null) {
return;
}
if (value instanceof Integer) {
serializePrimitive(rec, fieldName, ((Integer) value).intValue());
} else if (value instanceof Long) {
serializePrimitive(rec, fieldName, ((Long) value).longValue());
} else if (value instanceof Float) {
serializePrimitive(rec, fieldName, ((Float) value).floatValue());
} else if (value instanceof Double) {
serializePrimitive(rec, fieldName, ((Double) value).doubleValue());
} else if (value instanceof Boolean) {
serializePrimitive(rec, fieldName, ((Boolean) value).booleanValue());
} else if (value instanceof String) {
serializeString(rec, fieldName, (String) value);
} else if (value instanceof byte[]){
serializeBytes(rec, fieldName, (byte[]) value);
} else {
throw new RuntimeException("Primitive type " + value.getClass().getSimpleName() + " not supported!");
}
}
/**
* Serialize an integer, use zig-zag encoding to (probably) get a small positive value, then encode the result as a variable-byte integer.
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, int value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
// zig zag encoding
VarInt.writeVInt(fieldBuffer, (value << 1) ^ (value >> 31));
}
/**
* Serialize a long, use zig-zag encoding to (probably) get a small positive value, then encode the result as a variable-byte long.
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, long value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
// zig zag encoding
VarInt.writeVLong(fieldBuffer, (value << 1) ^ (value >> 63));
}
/**
* Serialize a float into 4 consecutive bytes
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, float value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
int intBits = Float.floatToIntBits(value);
writeFixedLengthInt(fieldBuffer, intBits);
}
/**
* Write 4 consecutive bytes
*/
private static void writeFixedLengthInt(ByteDataBuffer fieldBuffer, int intBits) {
fieldBuffer.write((byte) (intBits >>> 24));
fieldBuffer.write((byte) (intBits >>> 16));
fieldBuffer.write((byte) (intBits >>> 8));
fieldBuffer.write((byte) (intBits));
}
/**
* Serialize a double into 8 consecutive bytes
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, double value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
long intBits = Double.doubleToLongBits(value);
writeFixedLengthLong(fieldBuffer, intBits);
}
/**
* Write 8 consecutive bytes
*/
private static void writeFixedLengthLong(ByteDataBuffer fieldBuffer, long intBits) {
fieldBuffer.write((byte) (intBits >>> 56));
fieldBuffer.write((byte) (intBits >>> 48));
fieldBuffer.write((byte) (intBits >>> 40));
fieldBuffer.write((byte) (intBits >>> 32));
fieldBuffer.write((byte) (intBits >>> 24));
fieldBuffer.write((byte) (intBits >>> 16));
fieldBuffer.write((byte) (intBits >>> 8));
fieldBuffer.write((byte) (intBits));
}
/**
* Serialize a boolean as a single byte
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, boolean value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
byte byteValue = value ? (byte) 1 : (byte) 0;
fieldBuffer.write(byteValue);
}
private void serializeString(FlatBlobSerializationRecord rec, String fieldName, String value) {
if(value == null)
return;
writeString(value, rec.getFieldBuffer(fieldName));
}
@Override
public void serializeBytes(FlatBlobSerializationRecord rec, String fieldName, byte[] value) {
if(value == null)
return;
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
for (int i = 0; i < value.length; i++) {
fieldBuffer.write(value[i]);
}
}
/*
* @Deprecated instead use serializeObject(FlatBlobSerializationRecord rec, String fieldName, Object obj)
*
*/
@Deprecated
@Override
public void serializeObject(FlatBlobSerializationRecord rec, String fieldName, String typeName, Object obj) {
int fieldPosition = rec.getSchema().getPosition(fieldName);
validateField(fieldName, fieldPosition);
serializeObject(rec, fieldPosition, typeName, obj);
}
private void validateField(String fieldName, int fieldPosition) {
if(fieldPosition == -1) {
throw new IllegalArgumentException("Attempting to serialize non existent field " + fieldName + ".");
}
}
private void serializeObject(FlatBlobSerializationRecord rec, int fieldPosition, String typeName, Object obj) {
if(obj == null)
return;
int ordinal = findOrdinalInStateEngine(typeName, obj);
FlatBlobSerializationRecord subRecord = getSerializationRecord(typeName);
framework.getSerializer(typeName).serialize(obj, subRecord);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
VarInt.writeVInt(fieldBuffer, ordinal);
VarInt.writeVInt(fieldBuffer, subRecord.sizeOfData());
subRecord.writeDataTo(fieldBuffer);
}
@Override
public void serializeObject(FlatBlobSerializationRecord rec, String fieldName, Object obj) {
int fieldPosition = rec.getSchema().getPosition(fieldName);
validateField(fieldName, fieldPosition);
serializeObject(rec, fieldPosition, rec.getSchema().getObjectType(fieldName), obj);
}
@Override
public <T> void serializeList(FlatBlobSerializationRecord rec, String fieldName, String typeName, Collection<T> obj) {
if(obj == null)
return;
NFTypeSerializer<Object> elementSerializer = framework.getSerializer(typeName);
int fieldPosition = rec.getSchema().getPosition(fieldName);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
FlatBlobSerializationRecord subRecord = getSerializationRecord(typeName);
for(T t : obj) {
if(t == null) {
VarInt.writeVNull(fieldBuffer);
} else {
int ordinal = findOrdinalInStateEngine(typeName, t);
elementSerializer.serialize(t, subRecord);
VarInt.writeVInt(fieldBuffer, ordinal);
VarInt.writeVInt(fieldBuffer, subRecord.sizeOfData());
subRecord.writeDataTo(fieldBuffer);
subRecord.reset();
}
}
}
@Override
public <T> void serializeSet(FlatBlobSerializationRecord rec, String fieldName, String typeName, Set<T> set) {
if(set == null)
return;
FastBlobTypeDeserializationState<Object> typeDeserializationState = stateEngine.getTypeDeserializationState(typeName);
int fieldPosition = rec.getSchema().getPosition(fieldName);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
int setOrdinals[] = new int[set.size()];
Object unidentifiedSetObjects[] = null;
int i = 0;
for (T obj : set) {
if(obj == null) {
setOrdinals[i++] = -1;
} else {
setOrdinals[i] = typeDeserializationState.find(obj);
if(setOrdinals[i] == -1) {
if(unidentifiedSetObjects == null)
unidentifiedSetObjects = new Object[set.size()];
unidentifiedSetObjects[i] = obj;
setOrdinals[i] = Integer.MIN_VALUE;
}
i++;
}
}
Arrays.sort(setOrdinals);
FlatBlobSerializationRecord subRecord = getSerializationRecord(typeName);
int currentOrdinal = 0;
for(i=0;i<setOrdinals.length;i++) {
if(setOrdinals[i] == -1) {
VarInt.writeVNull(fieldBuffer);
VarInt.writeVNull(fieldBuffer);
} else {
if(setOrdinals[i] == Integer.MIN_VALUE) {
Object element = unidentifiedSetObjects[i];
framework.getSerializer(typeName).serialize(element, subRecord);
VarInt.writeVNull(fieldBuffer);
} else {
Object element = typeDeserializationState.get(setOrdinals[i]);
framework.getSerializer(typeName).serialize(element, subRecord);
VarInt.writeVInt(fieldBuffer, setOrdinals[i] - currentOrdinal);
currentOrdinal = setOrdinals[i];
}
VarInt.writeVInt(fieldBuffer, subRecord.sizeOfData());
subRecord.writeDataTo(fieldBuffer);
subRecord.reset();
}
}
}
@Override
public <K, V> void serializeMap(FlatBlobSerializationRecord rec, String fieldName, String keyTypeName, String valueTypeName, Map<K, V> map) {
if(map == null)
return;
FastBlobTypeDeserializationState<Object> keyDeserializationState = stateEngine.getTypeDeserializationState(keyTypeName);
FastBlobTypeDeserializationState<Object> valueDeserializationState = stateEngine.getTypeDeserializationState(valueTypeName);
int fieldPosition = rec.getSchema().getPosition(fieldName);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
FlatBlobSerializationRecord keyRecord = getSerializationRecord(keyTypeName);
FlatBlobSerializationRecord valueRecord = getSerializationRecord(valueTypeName);
long mapEntries[] = new long[map.size()];
int i = 0;
for (Map.Entry<K, V> entry : map.entrySet()) {
int keyOrdinal = -1;
int valueOrdinal = -1;
if(entry.getKey() != null)
keyOrdinal = keyDeserializationState.find(entry.getKey());
if(entry.getValue() != null)
valueOrdinal = valueDeserializationState.find(entry.getValue());
mapEntries[i++] = ((long)valueOrdinal << 32) | (keyOrdinal & 0xFFFFFFFFL);
}
if(mapEntries.length > i) {
mapEntries = Arrays.copyOf(mapEntries, i);
throw new RuntimeException("This should not happen."); ///TODO: Remove this sanity check.
}
Arrays.sort(mapEntries);
int currentValueOrdinal = 0;
for(i=0;i<mapEntries.length;i++) {
int keyOrdinal = (int) mapEntries[i];
int valueOrdinal = (int) (mapEntries[i] >> 32);
if(keyOrdinal == -1) {
VarInt.writeVNull(fieldBuffer);
} else {
Object key = keyDeserializationState.get(keyOrdinal);
keyRecord.reset();
framework.getSerializer(keyTypeName).serialize(key, keyRecord);
VarInt.writeVInt(fieldBuffer, keyOrdinal);
VarInt.writeVInt(fieldBuffer, keyRecord.sizeOfData());
keyRecord.writeDataTo(fieldBuffer);
}
if(valueOrdinal == -1) {
VarInt.writeVNull(fieldBuffer);
} else {
Object value = valueDeserializationState.get(valueOrdinal);
valueRecord.reset();
framework.getSerializer(valueTypeName).serialize(value, valueRecord);
VarInt.writeVInt(fieldBuffer, valueOrdinal - currentValueOrdinal);
VarInt.writeVInt(fieldBuffer, valueRecord.sizeOfData());
valueRecord.writeDataTo(fieldBuffer);
currentValueOrdinal = valueOrdinal;
}
}
}
/**
* Encode a String as a series of VarInts, one per character.<p/>
*
* @param str
* @param out
* @return
* @throws IOException
*/
private void writeString(String str, ByteDataBuffer out) {
for(int i=0;i<str.length();i++) {
VarInt.writeVInt(out, str.charAt(i));
}
}
private int findOrdinalInStateEngine(String typeName, Object obj) {
FastBlobTypeDeserializationState<Object> typeDeserializationState = stateEngine.getTypeDeserializationState(typeName);
int ordinal = typeDeserializationState.find(obj);
return ordinal;
}
FlatBlobSerializationRecord getSerializationRecord(String type) {
Map<String, FlatBlobSerializationRecord> cachedSerializationRecords = this.cachedSerializationRecords.get();
if(cachedSerializationRecords == null) {
cachedSerializationRecords = new HashMap<String, FlatBlobSerializationRecord>();
this.cachedSerializationRecords.set(cachedSerializationRecords);
}
FlatBlobSerializationRecord rec = cachedSerializationRecords.get(type);
if(rec == null) {
rec = new FlatBlobSerializationRecord(framework.getSerializer(type).getFastBlobSchema());
cachedSerializationRecords.put(type, rec);
}
rec.reset();
return rec;
}
}
| Netflix/zeno | src/main/java/com/netflix/zeno/flatblob/FlatBlobFrameworkSerializer.java | 4,319 | // zig zag encoding | line_comment | nl | /*
*
* Copyright 2014 Netflix, Inc.
*
* 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.netflix.zeno.flatblob;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.record.ByteDataBuffer;
import com.netflix.zeno.fastblob.record.VarInt;
import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState;
import com.netflix.zeno.serializer.FrameworkSerializer;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FlatBlobFrameworkSerializer extends FrameworkSerializer<FlatBlobSerializationRecord> {
static final int NULL_FLOAT_BITS = Float.floatToIntBits(Float.NaN) + 1;
static final long NULL_DOUBLE_BITS = Double.doubleToLongBits(Double.NaN) + 1;
private final FastBlobStateEngine stateEngine;
private final ThreadLocal<Map<String, FlatBlobSerializationRecord>> cachedSerializationRecords;
public FlatBlobFrameworkSerializer(FlatBlobSerializationFramework flatBlobFramework, FastBlobStateEngine stateEngine) {
super(flatBlobFramework);
this.stateEngine = stateEngine;
this.cachedSerializationRecords = new ThreadLocal<Map<String, FlatBlobSerializationRecord>>();
}
/**
* Serialize a primitive element
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, Object value) {
if (value == null) {
return;
}
if (value instanceof Integer) {
serializePrimitive(rec, fieldName, ((Integer) value).intValue());
} else if (value instanceof Long) {
serializePrimitive(rec, fieldName, ((Long) value).longValue());
} else if (value instanceof Float) {
serializePrimitive(rec, fieldName, ((Float) value).floatValue());
} else if (value instanceof Double) {
serializePrimitive(rec, fieldName, ((Double) value).doubleValue());
} else if (value instanceof Boolean) {
serializePrimitive(rec, fieldName, ((Boolean) value).booleanValue());
} else if (value instanceof String) {
serializeString(rec, fieldName, (String) value);
} else if (value instanceof byte[]){
serializeBytes(rec, fieldName, (byte[]) value);
} else {
throw new RuntimeException("Primitive type " + value.getClass().getSimpleName() + " not supported!");
}
}
/**
* Serialize an integer, use zig-zag encoding to (probably) get a small positive value, then encode the result as a variable-byte integer.
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, int value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
// zig zag<SUF>
VarInt.writeVInt(fieldBuffer, (value << 1) ^ (value >> 31));
}
/**
* Serialize a long, use zig-zag encoding to (probably) get a small positive value, then encode the result as a variable-byte long.
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, long value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
// zig zag encoding
VarInt.writeVLong(fieldBuffer, (value << 1) ^ (value >> 63));
}
/**
* Serialize a float into 4 consecutive bytes
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, float value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
int intBits = Float.floatToIntBits(value);
writeFixedLengthInt(fieldBuffer, intBits);
}
/**
* Write 4 consecutive bytes
*/
private static void writeFixedLengthInt(ByteDataBuffer fieldBuffer, int intBits) {
fieldBuffer.write((byte) (intBits >>> 24));
fieldBuffer.write((byte) (intBits >>> 16));
fieldBuffer.write((byte) (intBits >>> 8));
fieldBuffer.write((byte) (intBits));
}
/**
* Serialize a double into 8 consecutive bytes
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, double value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
long intBits = Double.doubleToLongBits(value);
writeFixedLengthLong(fieldBuffer, intBits);
}
/**
* Write 8 consecutive bytes
*/
private static void writeFixedLengthLong(ByteDataBuffer fieldBuffer, long intBits) {
fieldBuffer.write((byte) (intBits >>> 56));
fieldBuffer.write((byte) (intBits >>> 48));
fieldBuffer.write((byte) (intBits >>> 40));
fieldBuffer.write((byte) (intBits >>> 32));
fieldBuffer.write((byte) (intBits >>> 24));
fieldBuffer.write((byte) (intBits >>> 16));
fieldBuffer.write((byte) (intBits >>> 8));
fieldBuffer.write((byte) (intBits));
}
/**
* Serialize a boolean as a single byte
*/
@Override
public void serializePrimitive(FlatBlobSerializationRecord rec, String fieldName, boolean value) {
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
byte byteValue = value ? (byte) 1 : (byte) 0;
fieldBuffer.write(byteValue);
}
private void serializeString(FlatBlobSerializationRecord rec, String fieldName, String value) {
if(value == null)
return;
writeString(value, rec.getFieldBuffer(fieldName));
}
@Override
public void serializeBytes(FlatBlobSerializationRecord rec, String fieldName, byte[] value) {
if(value == null)
return;
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldName);
for (int i = 0; i < value.length; i++) {
fieldBuffer.write(value[i]);
}
}
/*
* @Deprecated instead use serializeObject(FlatBlobSerializationRecord rec, String fieldName, Object obj)
*
*/
@Deprecated
@Override
public void serializeObject(FlatBlobSerializationRecord rec, String fieldName, String typeName, Object obj) {
int fieldPosition = rec.getSchema().getPosition(fieldName);
validateField(fieldName, fieldPosition);
serializeObject(rec, fieldPosition, typeName, obj);
}
private void validateField(String fieldName, int fieldPosition) {
if(fieldPosition == -1) {
throw new IllegalArgumentException("Attempting to serialize non existent field " + fieldName + ".");
}
}
private void serializeObject(FlatBlobSerializationRecord rec, int fieldPosition, String typeName, Object obj) {
if(obj == null)
return;
int ordinal = findOrdinalInStateEngine(typeName, obj);
FlatBlobSerializationRecord subRecord = getSerializationRecord(typeName);
framework.getSerializer(typeName).serialize(obj, subRecord);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
VarInt.writeVInt(fieldBuffer, ordinal);
VarInt.writeVInt(fieldBuffer, subRecord.sizeOfData());
subRecord.writeDataTo(fieldBuffer);
}
@Override
public void serializeObject(FlatBlobSerializationRecord rec, String fieldName, Object obj) {
int fieldPosition = rec.getSchema().getPosition(fieldName);
validateField(fieldName, fieldPosition);
serializeObject(rec, fieldPosition, rec.getSchema().getObjectType(fieldName), obj);
}
@Override
public <T> void serializeList(FlatBlobSerializationRecord rec, String fieldName, String typeName, Collection<T> obj) {
if(obj == null)
return;
NFTypeSerializer<Object> elementSerializer = framework.getSerializer(typeName);
int fieldPosition = rec.getSchema().getPosition(fieldName);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
FlatBlobSerializationRecord subRecord = getSerializationRecord(typeName);
for(T t : obj) {
if(t == null) {
VarInt.writeVNull(fieldBuffer);
} else {
int ordinal = findOrdinalInStateEngine(typeName, t);
elementSerializer.serialize(t, subRecord);
VarInt.writeVInt(fieldBuffer, ordinal);
VarInt.writeVInt(fieldBuffer, subRecord.sizeOfData());
subRecord.writeDataTo(fieldBuffer);
subRecord.reset();
}
}
}
@Override
public <T> void serializeSet(FlatBlobSerializationRecord rec, String fieldName, String typeName, Set<T> set) {
if(set == null)
return;
FastBlobTypeDeserializationState<Object> typeDeserializationState = stateEngine.getTypeDeserializationState(typeName);
int fieldPosition = rec.getSchema().getPosition(fieldName);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
int setOrdinals[] = new int[set.size()];
Object unidentifiedSetObjects[] = null;
int i = 0;
for (T obj : set) {
if(obj == null) {
setOrdinals[i++] = -1;
} else {
setOrdinals[i] = typeDeserializationState.find(obj);
if(setOrdinals[i] == -1) {
if(unidentifiedSetObjects == null)
unidentifiedSetObjects = new Object[set.size()];
unidentifiedSetObjects[i] = obj;
setOrdinals[i] = Integer.MIN_VALUE;
}
i++;
}
}
Arrays.sort(setOrdinals);
FlatBlobSerializationRecord subRecord = getSerializationRecord(typeName);
int currentOrdinal = 0;
for(i=0;i<setOrdinals.length;i++) {
if(setOrdinals[i] == -1) {
VarInt.writeVNull(fieldBuffer);
VarInt.writeVNull(fieldBuffer);
} else {
if(setOrdinals[i] == Integer.MIN_VALUE) {
Object element = unidentifiedSetObjects[i];
framework.getSerializer(typeName).serialize(element, subRecord);
VarInt.writeVNull(fieldBuffer);
} else {
Object element = typeDeserializationState.get(setOrdinals[i]);
framework.getSerializer(typeName).serialize(element, subRecord);
VarInt.writeVInt(fieldBuffer, setOrdinals[i] - currentOrdinal);
currentOrdinal = setOrdinals[i];
}
VarInt.writeVInt(fieldBuffer, subRecord.sizeOfData());
subRecord.writeDataTo(fieldBuffer);
subRecord.reset();
}
}
}
@Override
public <K, V> void serializeMap(FlatBlobSerializationRecord rec, String fieldName, String keyTypeName, String valueTypeName, Map<K, V> map) {
if(map == null)
return;
FastBlobTypeDeserializationState<Object> keyDeserializationState = stateEngine.getTypeDeserializationState(keyTypeName);
FastBlobTypeDeserializationState<Object> valueDeserializationState = stateEngine.getTypeDeserializationState(valueTypeName);
int fieldPosition = rec.getSchema().getPosition(fieldName);
ByteDataBuffer fieldBuffer = rec.getFieldBuffer(fieldPosition);
FlatBlobSerializationRecord keyRecord = getSerializationRecord(keyTypeName);
FlatBlobSerializationRecord valueRecord = getSerializationRecord(valueTypeName);
long mapEntries[] = new long[map.size()];
int i = 0;
for (Map.Entry<K, V> entry : map.entrySet()) {
int keyOrdinal = -1;
int valueOrdinal = -1;
if(entry.getKey() != null)
keyOrdinal = keyDeserializationState.find(entry.getKey());
if(entry.getValue() != null)
valueOrdinal = valueDeserializationState.find(entry.getValue());
mapEntries[i++] = ((long)valueOrdinal << 32) | (keyOrdinal & 0xFFFFFFFFL);
}
if(mapEntries.length > i) {
mapEntries = Arrays.copyOf(mapEntries, i);
throw new RuntimeException("This should not happen."); ///TODO: Remove this sanity check.
}
Arrays.sort(mapEntries);
int currentValueOrdinal = 0;
for(i=0;i<mapEntries.length;i++) {
int keyOrdinal = (int) mapEntries[i];
int valueOrdinal = (int) (mapEntries[i] >> 32);
if(keyOrdinal == -1) {
VarInt.writeVNull(fieldBuffer);
} else {
Object key = keyDeserializationState.get(keyOrdinal);
keyRecord.reset();
framework.getSerializer(keyTypeName).serialize(key, keyRecord);
VarInt.writeVInt(fieldBuffer, keyOrdinal);
VarInt.writeVInt(fieldBuffer, keyRecord.sizeOfData());
keyRecord.writeDataTo(fieldBuffer);
}
if(valueOrdinal == -1) {
VarInt.writeVNull(fieldBuffer);
} else {
Object value = valueDeserializationState.get(valueOrdinal);
valueRecord.reset();
framework.getSerializer(valueTypeName).serialize(value, valueRecord);
VarInt.writeVInt(fieldBuffer, valueOrdinal - currentValueOrdinal);
VarInt.writeVInt(fieldBuffer, valueRecord.sizeOfData());
valueRecord.writeDataTo(fieldBuffer);
currentValueOrdinal = valueOrdinal;
}
}
}
/**
* Encode a String as a series of VarInts, one per character.<p/>
*
* @param str
* @param out
* @return
* @throws IOException
*/
private void writeString(String str, ByteDataBuffer out) {
for(int i=0;i<str.length();i++) {
VarInt.writeVInt(out, str.charAt(i));
}
}
private int findOrdinalInStateEngine(String typeName, Object obj) {
FastBlobTypeDeserializationState<Object> typeDeserializationState = stateEngine.getTypeDeserializationState(typeName);
int ordinal = typeDeserializationState.find(obj);
return ordinal;
}
FlatBlobSerializationRecord getSerializationRecord(String type) {
Map<String, FlatBlobSerializationRecord> cachedSerializationRecords = this.cachedSerializationRecords.get();
if(cachedSerializationRecords == null) {
cachedSerializationRecords = new HashMap<String, FlatBlobSerializationRecord>();
this.cachedSerializationRecords.set(cachedSerializationRecords);
}
FlatBlobSerializationRecord rec = cachedSerializationRecords.get(type);
if(rec == null) {
rec = new FlatBlobSerializationRecord(framework.getSerializer(type).getFastBlobSchema());
cachedSerializationRecords.put(type, rec);
}
rec.reset();
return rec;
}
}
|
201670_32 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ Atlassian Pty Ltd
*
* 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 org.jitsi.jicofo.recording.jibri;
import org.jitsi.jicofo.util.*;
import org.jitsi.utils.*;
import org.jitsi.xmpp.extensions.jibri.*;
import org.jitsi.xmpp.extensions.jibri.JibriIq.*;
import net.java.sip.communicator.service.protocol.*;
import org.jetbrains.annotations.*;
import org.jitsi.eventadmin.*;
import org.jitsi.jicofo.*;
import org.jitsi.osgi.*;
import org.jitsi.protocol.xmpp.*;
import org.jitsi.utils.logging.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jxmpp.jid.*;
import org.osgi.framework.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Class holds the information about Jibri session. It can be either live
* streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic
* which is supposed to try another instance when the current one fails. To make
* this happen it needs to cache all the information required to start new
* session. It uses {@link JibriDetector} to select new Jibri.
*
* @author Pawel Domas
*/
public class JibriSession
{
/**
* The class logger which can be used to override logging level inherited
* from {@link JitsiMeetConference}.
*/
static private final Logger classLogger
= Logger.getLogger(JibriSession.class);
/**
* Provides the {@link EventAdmin} instance for emitting events.
*/
private final EventAdminProvider eventAdminProvider;
/**
* Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in
* the middle of starting of the recording process.
*/
static private boolean isStartingStatus(JibriIq.Status status)
{
return JibriIq.Status.PENDING.equals(status);
}
/**
* The JID of the Jibri currently being used by this session or
* <tt>null</tt> otherwise.
*/
private Jid currentJibriJid;
/**
* The display name Jibri attribute received from Jitsi Meet to be passed
* further to Jibri instance that will be used.
*/
private final String displayName;
/**
* Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for
* regular Jibri (<tt>false</tt>).
*/
private final boolean isSIP;
/**
* {@link JibriDetector} instance used to select a Jibri which will be used
* by this session.
*/
private final JibriDetector jibriDetector;
/**
* Helper class that registers for {@link JibriEvent}s in the OSGi context
* obtained from the {@link FocusBundleActivator}.
*/
private final JibriEventHandler jibriEventHandler = new JibriEventHandler();
/**
* Current Jibri recording status.
*/
private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED;
/**
* The logger for this instance. Uses the logging level either of the
* {@link #classLogger} or {@link JitsiMeetConference#getLogger()}
* whichever is higher.
*/
private final Logger logger;
/**
* The owner which will be notified about status changes of this session.
*/
private final Owner owner;
/**
* Reference to scheduled {@link PendingStatusTimeout}
*/
private ScheduledFuture<?> pendingTimeoutTask;
/**
* How long this session can stay in "pending" status, before retry is made
* (given in seconds).
*/
private final long pendingTimeout;
/**
* The (bare) JID of the MUC room.
*/
private final EntityBareJid roomName;
/**
* Executor service for used to schedule pending timeout tasks.
*/
private final ScheduledExecutorService scheduledExecutor;
/**
* The SIP address attribute received from Jitsi Meet which is to be used to
* start a SIP call. This field's used only if {@link #isSIP} is set to
* <tt>true</tt>.
*/
private final String sipAddress;
/**
* The id of the live stream received from Jitsi Meet, which will be used to
* start live streaming session (used only if {@link #isSIP is set to
* <tt>true</tt>}.
*/
private final String streamID;
private final String sessionId;
/**
* The broadcast id of the YouTube broadcast, if available. This is used
* to generate and distribute the viewing url of the live stream
*/
private final String youTubeBroadcastId;
/**
* A JSON-encoded string containing arbitrary application data for Jibri
*/
private final String applicationData;
/**
* {@link XmppConnection} instance used to send/listen for XMPP packets.
*/
private final XmppConnection xmpp;
/**
* The maximum amount of retries we'll attempt
*/
private final int maxNumRetries;
/**
* How many times we've retried this request to another Jibri
*/
private int numRetries = 0;
/**
* The full JID of the entity that has initiated the recording flow.
*/
private Jid initiator;
/**
* The full JID of the entity that has initiated the stop of the recording.
*/
private Jid terminator;
/**
* Creates new {@link JibriSession} instance.
* @param bundleContext the OSGI context.
* @param owner the session owner which will be notified about this session
* state changes.
* @param roomName the name if the XMPP MUC room (full address).
* @param pendingTimeout how many seconds this session can wait in pending
* state, before trying another Jibri instance or failing with an error.
* @param connection the XMPP connection which will be used to send/listen
* for packets.
* @param scheduledExecutor the executor service which will be used to
* schedule pending timeout task execution.
* @param jibriDetector the Jibri detector which will be used to select
* Jibri instance.
* @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for
* a regular live streaming Jibri type of session.
* @param sipAddress a SIP address if it's a SIP session
* @param displayName a display name to be used by Jibri participant
* entering the conference once the session starts.
* @param streamID a live streaming ID if it's not a SIP session
* @param youTubeBroadcastId the YouTube broadcast id (optional)
* @param applicationData a JSON-encoded string containing application-specific
* data for Jibri
* @param logLevelDelegate logging level delegate which will be used to
* select logging level for this instance {@link #logger}.
*/
JibriSession(
BundleContext bundleContext,
JibriSession.Owner owner,
EntityBareJid roomName,
Jid initiator,
long pendingTimeout,
int maxNumRetries,
XmppConnection connection,
ScheduledExecutorService scheduledExecutor,
JibriDetector jibriDetector,
boolean isSIP,
String sipAddress,
String displayName,
String streamID,
String youTubeBroadcastId,
String sessionId,
String applicationData,
Logger logLevelDelegate)
{
this.eventAdminProvider = new EventAdminProvider(bundleContext);
this.owner = owner;
this.roomName = roomName;
this.initiator = initiator;
this.scheduledExecutor
= Objects.requireNonNull(scheduledExecutor, "scheduledExecutor");
this.pendingTimeout = pendingTimeout;
this.maxNumRetries = maxNumRetries;
this.isSIP = isSIP;
this.jibriDetector = jibriDetector;
this.sipAddress = sipAddress;
this.displayName = displayName;
this.streamID = streamID;
this.youTubeBroadcastId = youTubeBroadcastId;
this.sessionId = sessionId;
this.applicationData = applicationData;
this.xmpp = connection;
logger = Logger.getLogger(classLogger, logLevelDelegate);
}
/**
* Used internally to call
* {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}.
* @param newStatus the new status to dispatch.
* @param failureReason the failure reason associated with the state
* transition if any.
*/
private void dispatchSessionStateChanged(
Status newStatus, FailureReason failureReason)
{
if (failureReason != null)
{
emitSessionFailedEvent();
}
owner.onSessionStateChanged(this, newStatus, failureReason);
}
/**
* Asynchronously emits {@link JibriSessionEvent#FAILED_TO_START} event over
* the {@link EventAdmin} bus.
*/
private void emitSessionFailedEvent()
{
JibriSessionEvent.Type jibriType;
if (isSIP)
{
jibriType = JibriSessionEvent.Type.SIP_CALL;
}
else if (StringUtils.isNullOrEmpty(streamID))
{
jibriType = JibriSessionEvent.Type.RECORDING;
}
else
{
jibriType = JibriSessionEvent.Type.LIVE_STREAMING;
}
eventAdminProvider
.get()
.postEvent(
JibriSessionEvent.newFailedToStartEvent(jibriType));
}
/**
* Starts this session. A new Jibri instance will be selected and start
* request will be sent (in non blocking mode).
* @throws StartException if failed to start.
*/
synchronized public void start()
throws StartException
{
try
{
startInternal();
}
catch (Exception e)
{
emitSessionFailedEvent();
throw e;
}
}
/**
* Does the actual start logic.
*
* @throws StartException if fails to start.
*/
private void startInternal()
throws StartException
{
final Jid jibriJid = jibriDetector.selectJibri();
if (jibriJid == null) {
logger.error("Unable to find an available Jibri, can't start");
if (jibriDetector.isAnyInstanceConnected()) {
throw new StartException(StartException.ALL_BUSY);
}
throw new StartException(StartException.NOT_AVAILABLE);
}
try
{
jibriEventHandler.start(FocusBundleActivator.bundleContext);
logger.info("Starting session with Jibri " + jibriJid);
sendJibriStartIq(jibriJid);
}
catch (Exception e)
{
logger.error("Failed to send start Jibri IQ: " + e, e);
throw new StartException(StartException.INTERNAL_SERVER_ERROR);
}
}
/**
* Stops this session if it's not already stopped.
* @param initiator The jid of the initiator of the stop request.
*/
synchronized public void stop(Jid initiator)
{
if (currentJibriJid == null)
{
return;
}
this.terminator = initiator;
JibriIq stopRequest = new JibriIq();
stopRequest.setType(IQ.Type.set);
stopRequest.setTo(currentJibriJid);
stopRequest.setAction(JibriIq.Action.STOP);
logger.info("Trying to stop: " + stopRequest.toXML());
// When we send stop, we won't get an OFF presence back (just
// a response to this message) so clean up the session
// in the processing of the response.
try
{
xmpp.sendIqWithResponseCallback(
stopRequest,
stanza -> {
if (stanza instanceof JibriIq) {
processJibriIqFromJibri((JibriIq) stanza);
} else {
logger.error(
"Unexpected response to stop iq: "
+ (stanza != null ? stanza.toXML() : "null"));
JibriIq error = new JibriIq();
error.setFrom(stopRequest.getTo());
error.setFailureReason(FailureReason.ERROR);
error.setStatus(Status.OFF);
processJibriIqFromJibri(error);
}
},
exception -> {
logger.error(
"Error sending stop iq: " + exception.toString());
},
60000);
} catch (SmackException.NotConnectedException | InterruptedException e)
{
logger.error("Error sending stop iq: " + e.toString());
}
}
private void cleanupSession()
{
logger.info("Cleaning up current JibriSession");
currentJibriJid = null;
numRetries = 0;
try
{
jibriEventHandler.stop(FocusBundleActivator.bundleContext);
}
catch (Exception e)
{
logger.error("Failed to stop Jibri event handler: " + e, e);
}
}
/**
* Accept only XMPP packets which are coming from the Jibri currently used
* by this session.
* {@inheritDoc}
*/
public boolean accept(JibriIq packet)
{
return currentJibriJid != null
&& (packet.getFrom().equals(currentJibriJid));
}
/**
* @return a string describing this session instance, used for logging
* purpose
*/
private String nickname()
{
return this.isSIP ? "SIP Jibri" : "Jibri";
}
/**
* Process a {@link JibriIq} *request* from Jibri
* @param request
* @return the response
*/
IQ processJibriIqRequestFromJibri(JibriIq request)
{
processJibriIqFromJibri(request);
return IQ.createResultIQ(request);
}
/**
* Process a {@link JibriIq} from Jibri (note that this
* may be an IQ request or an IQ response)
* @param iq
*/
private void processJibriIqFromJibri(JibriIq iq)
{
// We have something from Jibri - let's update recording status
JibriIq.Status status = iq.getStatus();
if (!JibriIq.Status.UNDEFINED.equals(status))
{
logger.info(
"Updating status from JIBRI: "
+ iq.toXML() + " for " + roomName);
handleJibriStatusUpdate(
iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry());
}
else
{
logger.error(
"Received UNDEFINED status from jibri: " + iq.toString());
}
}
/**
* Gets the recording mode of this jibri session
* @return the recording mode for this session (STREAM, FILE or UNDEFINED
* in the case that this isn't a recording session but actually a SIP
* session)
*/
JibriIq.RecordingMode getRecordingMode()
{
if (sipAddress != null)
{
return RecordingMode.UNDEFINED;
}
else if (streamID != null)
{
return RecordingMode.STREAM;
}
return RecordingMode.FILE;
}
/**
* Sends an IQ to the given Jibri instance and asks it to start
* recording/SIP call.
* @throws OperationFailedException if XMPP connection failed
* @throws StartException if something went wrong
*/
private void sendJibriStartIq(final Jid jibriJid)
throws OperationFailedException,
StartException
{
// Store Jibri JID to make the packet filter accept the response
currentJibriJid = jibriJid;
logger.info(
"Starting Jibri " + jibriJid
+ (isSIP
? ("for SIP address: " + sipAddress)
: (" for stream ID: " + streamID))
+ " in room: " + roomName);
final JibriIq startIq = new JibriIq();
startIq.setTo(jibriJid);
startIq.setType(IQ.Type.set);
startIq.setAction(JibriIq.Action.START);
startIq.setSessionId(this.sessionId);
logger.debug(
"Passing on jibri application data: " + this.applicationData);
startIq.setAppData(this.applicationData);
if (streamID != null)
{
startIq.setStreamId(streamID);
startIq.setRecordingMode(RecordingMode.STREAM);
if (youTubeBroadcastId != null) {
startIq.setYouTubeBroadcastId(youTubeBroadcastId);
}
}
else
{
startIq.setRecordingMode(RecordingMode.FILE);
}
startIq.setSipAddress(sipAddress);
startIq.setDisplayName(displayName);
// Insert name of the room into Jibri START IQ
startIq.setRoom(roomName);
// We will not wait forever for the Jibri to start. This method can be
// run multiple times on retry, so we want to restart the pending
// timeout each time.
reschedulePendingTimeout();
IQ reply = xmpp.sendPacketAndGetReply(startIq);
if (!(reply instanceof JibriIq))
{
logger.error(
"Unexpected response to start request: "
+ (reply != null ? reply.toXML() : "null"));
throw new StartException(StartException.UNEXPECTED_RESPONSE);
}
JibriIq jibriIq = (JibriIq) reply;
// According to the "protocol" only PENDING status is allowed in
// response to the start request.
if (!Status.PENDING.equals(jibriIq.getStatus()))
{
logger.error(
"Unexpected status received in response to the start IQ: "
+ jibriIq.toXML());
throw new StartException(StartException.UNEXPECTED_RESPONSE);
}
processJibriIqFromJibri(jibriIq);
}
/**
* Method schedules/reschedules {@link PendingStatusTimeout} which will
* clear recording state after
* {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}.
*/
private void reschedulePendingTimeout()
{
if (pendingTimeoutTask != null)
{
logger.info(
"Rescheduling pending timeout task for room: " + roomName);
pendingTimeoutTask.cancel(false);
}
if (pendingTimeout > 0)
{
pendingTimeoutTask
= scheduledExecutor.schedule(
new PendingStatusTimeout(),
pendingTimeout, TimeUnit.SECONDS);
}
}
/**
* Check whether or not we should retry the current request to another Jibri
* @return true if we've not exceeded the max amount of retries,
* false otherwise
*/
private boolean maxRetriesExceeded()
{
return (maxNumRetries >= 0 && numRetries >= maxNumRetries);
}
/**
* Retry the current request with another Jibri (if one is available)
* @throws StartException if failed to start.
*/
private void retryRequestWithAnotherJibri()
throws StartException
{
numRetries++;
start();
}
/**
* Handle a Jibri status update (this could come from an IQ response, a new
* IQ from Jibri, an XMPP event, etc.).
* This will handle:
* 1) Retrying with a new Jibri in case of an error
* 2) Cleaning up the session when the Jibri session finished successfully
* (or there was an error but we have no more Jibris left to try)
* @param jibriJid the jid of the jibri for which this status update applies
* @param newStatus the jibri's new status
* @param failureReason the jibri's failure reason, if any (otherwise null)
* @param shouldRetryParam if {@code failureReason} is not null, shouldRetry
* denotes whether or not we should retry the same
* request with another Jibri
*/
private void handleJibriStatusUpdate(
@NotNull Jid jibriJid,
JibriIq.Status newStatus,
@Nullable JibriIq.FailureReason failureReason,
@Nullable Boolean shouldRetryParam)
{
jibriStatus = newStatus;
logger.info("Got Jibri status update: Jibri " + jibriJid
+ " has status " + newStatus
+ " and failure reason " + failureReason
+ ", current Jibri jid is " + currentJibriJid);
if (currentJibriJid == null)
{
logger.info("Current session has already been cleaned up, ignoring");
return;
}
if (jibriJid.compareTo(currentJibriJid) != 0)
{
logger.info("This status update is from " + jibriJid +
" but the current Jibri is " + currentJibriJid + ", ignoring");
return;
}
// First: if we're no longer pending (regardless of the Jibri's
// new state), make sure we stop the pending timeout task
if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus))
{
logger.info(
"Jibri is no longer pending, cancelling pending timeout task");
pendingTimeoutTask.cancel(false);
pendingTimeoutTask = null;
}
// Now, if there was a failure of any kind we'll try and find another
// Jibri to keep things going
if (failureReason != null)
{
boolean shouldRetry;
if (shouldRetryParam == null)
{
logger.warn("failureReason was non-null but shouldRetry " +
"wasn't set, will NOT retry");
shouldRetry = false;
}
else
{
shouldRetry = shouldRetryParam;
}
// There was an error with the current Jibri, see if we should retry
if (shouldRetry && !maxRetriesExceeded())
{
logger.info("Jibri failed, trying to fall back to another Jibri");
try
{
retryRequestWithAnotherJibri();
// The fallback to another Jibri succeeded.
logger.info(
"Successfully resumed session with another Jibri");
}
catch (StartException exc)
{
logger.info(
"Failed to fall back to another Jibri, this "
+ "session has now failed: " + exc, exc);
// Propagate up that the session has failed entirely.
// We'll pass the original failure reason.
dispatchSessionStateChanged(newStatus, failureReason);
cleanupSession();
}
}
else
{
if (!shouldRetry)
{
logger.info("Jibri failed and signaled that we " +
"should not retry the same request");
}
else
{
// The Jibri we tried failed and we've reached the maxmium
// amount of retries we've been configured to attempt, so we'll
// give up trying to handle this request.
logger.info("Jibri failed, but max amount of retries ("
+ maxNumRetries + ") reached, giving up");
}
dispatchSessionStateChanged(newStatus, failureReason);
cleanupSession();
}
}
else if (Status.OFF.equals(newStatus))
{
logger.info("Jibri session ended cleanly, notifying owner and "
+ "cleaning up session");
// The Jibri stopped for some non-error reason
dispatchSessionStateChanged(newStatus, null);
cleanupSession();
}
else if (Status.ON.equals(newStatus))
{
logger.info("Jibri session started, notifying owner");
dispatchSessionStateChanged(newStatus, null);
}
}
/**
* @return SIP address received from Jitsi Meet, which is used for SIP
* gateway session (makes sense only for SIP sessions).
*/
String getSipAddress()
{
return sipAddress;
}
/**
* Get the unique ID for this session. This is used to uniquely
* identify a Jibri session instance, even of the same type (meaning,
* for example, that two file recordings would have different session
* IDs). It will be passed to Jibri and Jibri will put the session ID
* in its presence, so the Jibri user for a particular session can
* be identified by the clients.
* @return the session ID
*/
public String getSessionId()
{
return this.sessionId;
}
/**
* Helper class handles registration for the {@link JibriEvent}s.
*/
private class JibriEventHandler
extends EventHandlerActivator
{
private JibriEventHandler()
{
super(new String[]{
JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE});
}
@Override
public void handleEvent(Event event)
{
if (!JibriEvent.isJibriEvent(event))
{
logger.error("Invalid event: " + event);
return;
}
final JibriEvent jibriEvent = (JibriEvent) event;
final String topic = jibriEvent.getTopic();
final Jid jibriJid = jibriEvent.getJibriJid();
synchronized (JibriSession.this)
{
if (JibriEvent.WENT_OFFLINE.equals(topic)
&& jibriJid.equals(currentJibriJid))
{
logger.error(
nickname() + " went offline: " + jibriJid
+ " for room: " + roomName);
handleJibriStatusUpdate(
jibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* Task scheduled after we have received RESULT response from Jibri and
* entered PENDING state. Will abort the recording if we do not transit to
* ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}
* limit is exceeded.
*/
private class PendingStatusTimeout implements Runnable
{
public void run()
{
synchronized (JibriSession.this)
{
// Clear this task reference, so it won't be
// cancelling itself on status change from PENDING
pendingTimeoutTask = null;
if (isStartingStatus(jibriStatus))
{
logger.error(
nickname() + " pending timeout! " + roomName);
// If a Jibri times out during the pending phase, it's
// likely hung or having some issue. We'll send a stop (so
// if/when it does 'recover', it knows to stop) and simulate
// an error status (like we do in
// JibriEventHandler#handleEvent when a Jibri goes offline)
// to trigger the fallback logic.
stop(null);
handleJibriStatusUpdate(
currentJibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* The JID of the entity that has initiated the recording flow.
* @return The JID of the entity that has initiated the recording flow.
*/
public Jid getInitiator()
{
return initiator;
}
/**
* The JID of the entity that has initiated the stop of the recording.
* @return The JID of the entity that has stopped the recording.
*/
public Jid getTerminator()
{
return terminator;
}
/**
* Interface instance passed to {@link JibriSession} constructor which
* specifies the session owner which will be notified about any status
* changes.
*/
public interface Owner
{
/**
* Called on {@link JibriSession} status update.
* @param jibriSession which status has changed
* @param newStatus the new status
* @param failureReason optional error for {@link JibriIq.Status#OFF}.
*/
void onSessionStateChanged(
JibriSession jibriSession,
JibriIq.Status newStatus,
JibriIq.FailureReason failureReason);
}
static public class StartException extends Exception
{
final static String ALL_BUSY = "All Jibri instances are busy";
final static String INTERNAL_SERVER_ERROR = "Internal server error";
final static String NOT_AVAILABLE = "No Jibris available";
final static String UNEXPECTED_RESPONSE = "Unexpected response";
private final String reason;
StartException(String reason)
{
super(reason);
this.reason = reason;
}
String getReason()
{
return reason;
}
}
}
| Neustradamus/jicofo | src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java | 8,176 | // When we send stop, we won't get an OFF presence back (just | line_comment | nl | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ Atlassian Pty Ltd
*
* 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 org.jitsi.jicofo.recording.jibri;
import org.jitsi.jicofo.util.*;
import org.jitsi.utils.*;
import org.jitsi.xmpp.extensions.jibri.*;
import org.jitsi.xmpp.extensions.jibri.JibriIq.*;
import net.java.sip.communicator.service.protocol.*;
import org.jetbrains.annotations.*;
import org.jitsi.eventadmin.*;
import org.jitsi.jicofo.*;
import org.jitsi.osgi.*;
import org.jitsi.protocol.xmpp.*;
import org.jitsi.utils.logging.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jxmpp.jid.*;
import org.osgi.framework.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Class holds the information about Jibri session. It can be either live
* streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic
* which is supposed to try another instance when the current one fails. To make
* this happen it needs to cache all the information required to start new
* session. It uses {@link JibriDetector} to select new Jibri.
*
* @author Pawel Domas
*/
public class JibriSession
{
/**
* The class logger which can be used to override logging level inherited
* from {@link JitsiMeetConference}.
*/
static private final Logger classLogger
= Logger.getLogger(JibriSession.class);
/**
* Provides the {@link EventAdmin} instance for emitting events.
*/
private final EventAdminProvider eventAdminProvider;
/**
* Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in
* the middle of starting of the recording process.
*/
static private boolean isStartingStatus(JibriIq.Status status)
{
return JibriIq.Status.PENDING.equals(status);
}
/**
* The JID of the Jibri currently being used by this session or
* <tt>null</tt> otherwise.
*/
private Jid currentJibriJid;
/**
* The display name Jibri attribute received from Jitsi Meet to be passed
* further to Jibri instance that will be used.
*/
private final String displayName;
/**
* Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for
* regular Jibri (<tt>false</tt>).
*/
private final boolean isSIP;
/**
* {@link JibriDetector} instance used to select a Jibri which will be used
* by this session.
*/
private final JibriDetector jibriDetector;
/**
* Helper class that registers for {@link JibriEvent}s in the OSGi context
* obtained from the {@link FocusBundleActivator}.
*/
private final JibriEventHandler jibriEventHandler = new JibriEventHandler();
/**
* Current Jibri recording status.
*/
private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED;
/**
* The logger for this instance. Uses the logging level either of the
* {@link #classLogger} or {@link JitsiMeetConference#getLogger()}
* whichever is higher.
*/
private final Logger logger;
/**
* The owner which will be notified about status changes of this session.
*/
private final Owner owner;
/**
* Reference to scheduled {@link PendingStatusTimeout}
*/
private ScheduledFuture<?> pendingTimeoutTask;
/**
* How long this session can stay in "pending" status, before retry is made
* (given in seconds).
*/
private final long pendingTimeout;
/**
* The (bare) JID of the MUC room.
*/
private final EntityBareJid roomName;
/**
* Executor service for used to schedule pending timeout tasks.
*/
private final ScheduledExecutorService scheduledExecutor;
/**
* The SIP address attribute received from Jitsi Meet which is to be used to
* start a SIP call. This field's used only if {@link #isSIP} is set to
* <tt>true</tt>.
*/
private final String sipAddress;
/**
* The id of the live stream received from Jitsi Meet, which will be used to
* start live streaming session (used only if {@link #isSIP is set to
* <tt>true</tt>}.
*/
private final String streamID;
private final String sessionId;
/**
* The broadcast id of the YouTube broadcast, if available. This is used
* to generate and distribute the viewing url of the live stream
*/
private final String youTubeBroadcastId;
/**
* A JSON-encoded string containing arbitrary application data for Jibri
*/
private final String applicationData;
/**
* {@link XmppConnection} instance used to send/listen for XMPP packets.
*/
private final XmppConnection xmpp;
/**
* The maximum amount of retries we'll attempt
*/
private final int maxNumRetries;
/**
* How many times we've retried this request to another Jibri
*/
private int numRetries = 0;
/**
* The full JID of the entity that has initiated the recording flow.
*/
private Jid initiator;
/**
* The full JID of the entity that has initiated the stop of the recording.
*/
private Jid terminator;
/**
* Creates new {@link JibriSession} instance.
* @param bundleContext the OSGI context.
* @param owner the session owner which will be notified about this session
* state changes.
* @param roomName the name if the XMPP MUC room (full address).
* @param pendingTimeout how many seconds this session can wait in pending
* state, before trying another Jibri instance or failing with an error.
* @param connection the XMPP connection which will be used to send/listen
* for packets.
* @param scheduledExecutor the executor service which will be used to
* schedule pending timeout task execution.
* @param jibriDetector the Jibri detector which will be used to select
* Jibri instance.
* @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for
* a regular live streaming Jibri type of session.
* @param sipAddress a SIP address if it's a SIP session
* @param displayName a display name to be used by Jibri participant
* entering the conference once the session starts.
* @param streamID a live streaming ID if it's not a SIP session
* @param youTubeBroadcastId the YouTube broadcast id (optional)
* @param applicationData a JSON-encoded string containing application-specific
* data for Jibri
* @param logLevelDelegate logging level delegate which will be used to
* select logging level for this instance {@link #logger}.
*/
JibriSession(
BundleContext bundleContext,
JibriSession.Owner owner,
EntityBareJid roomName,
Jid initiator,
long pendingTimeout,
int maxNumRetries,
XmppConnection connection,
ScheduledExecutorService scheduledExecutor,
JibriDetector jibriDetector,
boolean isSIP,
String sipAddress,
String displayName,
String streamID,
String youTubeBroadcastId,
String sessionId,
String applicationData,
Logger logLevelDelegate)
{
this.eventAdminProvider = new EventAdminProvider(bundleContext);
this.owner = owner;
this.roomName = roomName;
this.initiator = initiator;
this.scheduledExecutor
= Objects.requireNonNull(scheduledExecutor, "scheduledExecutor");
this.pendingTimeout = pendingTimeout;
this.maxNumRetries = maxNumRetries;
this.isSIP = isSIP;
this.jibriDetector = jibriDetector;
this.sipAddress = sipAddress;
this.displayName = displayName;
this.streamID = streamID;
this.youTubeBroadcastId = youTubeBroadcastId;
this.sessionId = sessionId;
this.applicationData = applicationData;
this.xmpp = connection;
logger = Logger.getLogger(classLogger, logLevelDelegate);
}
/**
* Used internally to call
* {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}.
* @param newStatus the new status to dispatch.
* @param failureReason the failure reason associated with the state
* transition if any.
*/
private void dispatchSessionStateChanged(
Status newStatus, FailureReason failureReason)
{
if (failureReason != null)
{
emitSessionFailedEvent();
}
owner.onSessionStateChanged(this, newStatus, failureReason);
}
/**
* Asynchronously emits {@link JibriSessionEvent#FAILED_TO_START} event over
* the {@link EventAdmin} bus.
*/
private void emitSessionFailedEvent()
{
JibriSessionEvent.Type jibriType;
if (isSIP)
{
jibriType = JibriSessionEvent.Type.SIP_CALL;
}
else if (StringUtils.isNullOrEmpty(streamID))
{
jibriType = JibriSessionEvent.Type.RECORDING;
}
else
{
jibriType = JibriSessionEvent.Type.LIVE_STREAMING;
}
eventAdminProvider
.get()
.postEvent(
JibriSessionEvent.newFailedToStartEvent(jibriType));
}
/**
* Starts this session. A new Jibri instance will be selected and start
* request will be sent (in non blocking mode).
* @throws StartException if failed to start.
*/
synchronized public void start()
throws StartException
{
try
{
startInternal();
}
catch (Exception e)
{
emitSessionFailedEvent();
throw e;
}
}
/**
* Does the actual start logic.
*
* @throws StartException if fails to start.
*/
private void startInternal()
throws StartException
{
final Jid jibriJid = jibriDetector.selectJibri();
if (jibriJid == null) {
logger.error("Unable to find an available Jibri, can't start");
if (jibriDetector.isAnyInstanceConnected()) {
throw new StartException(StartException.ALL_BUSY);
}
throw new StartException(StartException.NOT_AVAILABLE);
}
try
{
jibriEventHandler.start(FocusBundleActivator.bundleContext);
logger.info("Starting session with Jibri " + jibriJid);
sendJibriStartIq(jibriJid);
}
catch (Exception e)
{
logger.error("Failed to send start Jibri IQ: " + e, e);
throw new StartException(StartException.INTERNAL_SERVER_ERROR);
}
}
/**
* Stops this session if it's not already stopped.
* @param initiator The jid of the initiator of the stop request.
*/
synchronized public void stop(Jid initiator)
{
if (currentJibriJid == null)
{
return;
}
this.terminator = initiator;
JibriIq stopRequest = new JibriIq();
stopRequest.setType(IQ.Type.set);
stopRequest.setTo(currentJibriJid);
stopRequest.setAction(JibriIq.Action.STOP);
logger.info("Trying to stop: " + stopRequest.toXML());
// When we<SUF>
// a response to this message) so clean up the session
// in the processing of the response.
try
{
xmpp.sendIqWithResponseCallback(
stopRequest,
stanza -> {
if (stanza instanceof JibriIq) {
processJibriIqFromJibri((JibriIq) stanza);
} else {
logger.error(
"Unexpected response to stop iq: "
+ (stanza != null ? stanza.toXML() : "null"));
JibriIq error = new JibriIq();
error.setFrom(stopRequest.getTo());
error.setFailureReason(FailureReason.ERROR);
error.setStatus(Status.OFF);
processJibriIqFromJibri(error);
}
},
exception -> {
logger.error(
"Error sending stop iq: " + exception.toString());
},
60000);
} catch (SmackException.NotConnectedException | InterruptedException e)
{
logger.error("Error sending stop iq: " + e.toString());
}
}
private void cleanupSession()
{
logger.info("Cleaning up current JibriSession");
currentJibriJid = null;
numRetries = 0;
try
{
jibriEventHandler.stop(FocusBundleActivator.bundleContext);
}
catch (Exception e)
{
logger.error("Failed to stop Jibri event handler: " + e, e);
}
}
/**
* Accept only XMPP packets which are coming from the Jibri currently used
* by this session.
* {@inheritDoc}
*/
public boolean accept(JibriIq packet)
{
return currentJibriJid != null
&& (packet.getFrom().equals(currentJibriJid));
}
/**
* @return a string describing this session instance, used for logging
* purpose
*/
private String nickname()
{
return this.isSIP ? "SIP Jibri" : "Jibri";
}
/**
* Process a {@link JibriIq} *request* from Jibri
* @param request
* @return the response
*/
IQ processJibriIqRequestFromJibri(JibriIq request)
{
processJibriIqFromJibri(request);
return IQ.createResultIQ(request);
}
/**
* Process a {@link JibriIq} from Jibri (note that this
* may be an IQ request or an IQ response)
* @param iq
*/
private void processJibriIqFromJibri(JibriIq iq)
{
// We have something from Jibri - let's update recording status
JibriIq.Status status = iq.getStatus();
if (!JibriIq.Status.UNDEFINED.equals(status))
{
logger.info(
"Updating status from JIBRI: "
+ iq.toXML() + " for " + roomName);
handleJibriStatusUpdate(
iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry());
}
else
{
logger.error(
"Received UNDEFINED status from jibri: " + iq.toString());
}
}
/**
* Gets the recording mode of this jibri session
* @return the recording mode for this session (STREAM, FILE or UNDEFINED
* in the case that this isn't a recording session but actually a SIP
* session)
*/
JibriIq.RecordingMode getRecordingMode()
{
if (sipAddress != null)
{
return RecordingMode.UNDEFINED;
}
else if (streamID != null)
{
return RecordingMode.STREAM;
}
return RecordingMode.FILE;
}
/**
* Sends an IQ to the given Jibri instance and asks it to start
* recording/SIP call.
* @throws OperationFailedException if XMPP connection failed
* @throws StartException if something went wrong
*/
private void sendJibriStartIq(final Jid jibriJid)
throws OperationFailedException,
StartException
{
// Store Jibri JID to make the packet filter accept the response
currentJibriJid = jibriJid;
logger.info(
"Starting Jibri " + jibriJid
+ (isSIP
? ("for SIP address: " + sipAddress)
: (" for stream ID: " + streamID))
+ " in room: " + roomName);
final JibriIq startIq = new JibriIq();
startIq.setTo(jibriJid);
startIq.setType(IQ.Type.set);
startIq.setAction(JibriIq.Action.START);
startIq.setSessionId(this.sessionId);
logger.debug(
"Passing on jibri application data: " + this.applicationData);
startIq.setAppData(this.applicationData);
if (streamID != null)
{
startIq.setStreamId(streamID);
startIq.setRecordingMode(RecordingMode.STREAM);
if (youTubeBroadcastId != null) {
startIq.setYouTubeBroadcastId(youTubeBroadcastId);
}
}
else
{
startIq.setRecordingMode(RecordingMode.FILE);
}
startIq.setSipAddress(sipAddress);
startIq.setDisplayName(displayName);
// Insert name of the room into Jibri START IQ
startIq.setRoom(roomName);
// We will not wait forever for the Jibri to start. This method can be
// run multiple times on retry, so we want to restart the pending
// timeout each time.
reschedulePendingTimeout();
IQ reply = xmpp.sendPacketAndGetReply(startIq);
if (!(reply instanceof JibriIq))
{
logger.error(
"Unexpected response to start request: "
+ (reply != null ? reply.toXML() : "null"));
throw new StartException(StartException.UNEXPECTED_RESPONSE);
}
JibriIq jibriIq = (JibriIq) reply;
// According to the "protocol" only PENDING status is allowed in
// response to the start request.
if (!Status.PENDING.equals(jibriIq.getStatus()))
{
logger.error(
"Unexpected status received in response to the start IQ: "
+ jibriIq.toXML());
throw new StartException(StartException.UNEXPECTED_RESPONSE);
}
processJibriIqFromJibri(jibriIq);
}
/**
* Method schedules/reschedules {@link PendingStatusTimeout} which will
* clear recording state after
* {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}.
*/
private void reschedulePendingTimeout()
{
if (pendingTimeoutTask != null)
{
logger.info(
"Rescheduling pending timeout task for room: " + roomName);
pendingTimeoutTask.cancel(false);
}
if (pendingTimeout > 0)
{
pendingTimeoutTask
= scheduledExecutor.schedule(
new PendingStatusTimeout(),
pendingTimeout, TimeUnit.SECONDS);
}
}
/**
* Check whether or not we should retry the current request to another Jibri
* @return true if we've not exceeded the max amount of retries,
* false otherwise
*/
private boolean maxRetriesExceeded()
{
return (maxNumRetries >= 0 && numRetries >= maxNumRetries);
}
/**
* Retry the current request with another Jibri (if one is available)
* @throws StartException if failed to start.
*/
private void retryRequestWithAnotherJibri()
throws StartException
{
numRetries++;
start();
}
/**
* Handle a Jibri status update (this could come from an IQ response, a new
* IQ from Jibri, an XMPP event, etc.).
* This will handle:
* 1) Retrying with a new Jibri in case of an error
* 2) Cleaning up the session when the Jibri session finished successfully
* (or there was an error but we have no more Jibris left to try)
* @param jibriJid the jid of the jibri for which this status update applies
* @param newStatus the jibri's new status
* @param failureReason the jibri's failure reason, if any (otherwise null)
* @param shouldRetryParam if {@code failureReason} is not null, shouldRetry
* denotes whether or not we should retry the same
* request with another Jibri
*/
private void handleJibriStatusUpdate(
@NotNull Jid jibriJid,
JibriIq.Status newStatus,
@Nullable JibriIq.FailureReason failureReason,
@Nullable Boolean shouldRetryParam)
{
jibriStatus = newStatus;
logger.info("Got Jibri status update: Jibri " + jibriJid
+ " has status " + newStatus
+ " and failure reason " + failureReason
+ ", current Jibri jid is " + currentJibriJid);
if (currentJibriJid == null)
{
logger.info("Current session has already been cleaned up, ignoring");
return;
}
if (jibriJid.compareTo(currentJibriJid) != 0)
{
logger.info("This status update is from " + jibriJid +
" but the current Jibri is " + currentJibriJid + ", ignoring");
return;
}
// First: if we're no longer pending (regardless of the Jibri's
// new state), make sure we stop the pending timeout task
if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus))
{
logger.info(
"Jibri is no longer pending, cancelling pending timeout task");
pendingTimeoutTask.cancel(false);
pendingTimeoutTask = null;
}
// Now, if there was a failure of any kind we'll try and find another
// Jibri to keep things going
if (failureReason != null)
{
boolean shouldRetry;
if (shouldRetryParam == null)
{
logger.warn("failureReason was non-null but shouldRetry " +
"wasn't set, will NOT retry");
shouldRetry = false;
}
else
{
shouldRetry = shouldRetryParam;
}
// There was an error with the current Jibri, see if we should retry
if (shouldRetry && !maxRetriesExceeded())
{
logger.info("Jibri failed, trying to fall back to another Jibri");
try
{
retryRequestWithAnotherJibri();
// The fallback to another Jibri succeeded.
logger.info(
"Successfully resumed session with another Jibri");
}
catch (StartException exc)
{
logger.info(
"Failed to fall back to another Jibri, this "
+ "session has now failed: " + exc, exc);
// Propagate up that the session has failed entirely.
// We'll pass the original failure reason.
dispatchSessionStateChanged(newStatus, failureReason);
cleanupSession();
}
}
else
{
if (!shouldRetry)
{
logger.info("Jibri failed and signaled that we " +
"should not retry the same request");
}
else
{
// The Jibri we tried failed and we've reached the maxmium
// amount of retries we've been configured to attempt, so we'll
// give up trying to handle this request.
logger.info("Jibri failed, but max amount of retries ("
+ maxNumRetries + ") reached, giving up");
}
dispatchSessionStateChanged(newStatus, failureReason);
cleanupSession();
}
}
else if (Status.OFF.equals(newStatus))
{
logger.info("Jibri session ended cleanly, notifying owner and "
+ "cleaning up session");
// The Jibri stopped for some non-error reason
dispatchSessionStateChanged(newStatus, null);
cleanupSession();
}
else if (Status.ON.equals(newStatus))
{
logger.info("Jibri session started, notifying owner");
dispatchSessionStateChanged(newStatus, null);
}
}
/**
* @return SIP address received from Jitsi Meet, which is used for SIP
* gateway session (makes sense only for SIP sessions).
*/
String getSipAddress()
{
return sipAddress;
}
/**
* Get the unique ID for this session. This is used to uniquely
* identify a Jibri session instance, even of the same type (meaning,
* for example, that two file recordings would have different session
* IDs). It will be passed to Jibri and Jibri will put the session ID
* in its presence, so the Jibri user for a particular session can
* be identified by the clients.
* @return the session ID
*/
public String getSessionId()
{
return this.sessionId;
}
/**
* Helper class handles registration for the {@link JibriEvent}s.
*/
private class JibriEventHandler
extends EventHandlerActivator
{
private JibriEventHandler()
{
super(new String[]{
JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE});
}
@Override
public void handleEvent(Event event)
{
if (!JibriEvent.isJibriEvent(event))
{
logger.error("Invalid event: " + event);
return;
}
final JibriEvent jibriEvent = (JibriEvent) event;
final String topic = jibriEvent.getTopic();
final Jid jibriJid = jibriEvent.getJibriJid();
synchronized (JibriSession.this)
{
if (JibriEvent.WENT_OFFLINE.equals(topic)
&& jibriJid.equals(currentJibriJid))
{
logger.error(
nickname() + " went offline: " + jibriJid
+ " for room: " + roomName);
handleJibriStatusUpdate(
jibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* Task scheduled after we have received RESULT response from Jibri and
* entered PENDING state. Will abort the recording if we do not transit to
* ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}
* limit is exceeded.
*/
private class PendingStatusTimeout implements Runnable
{
public void run()
{
synchronized (JibriSession.this)
{
// Clear this task reference, so it won't be
// cancelling itself on status change from PENDING
pendingTimeoutTask = null;
if (isStartingStatus(jibriStatus))
{
logger.error(
nickname() + " pending timeout! " + roomName);
// If a Jibri times out during the pending phase, it's
// likely hung or having some issue. We'll send a stop (so
// if/when it does 'recover', it knows to stop) and simulate
// an error status (like we do in
// JibriEventHandler#handleEvent when a Jibri goes offline)
// to trigger the fallback logic.
stop(null);
handleJibriStatusUpdate(
currentJibriJid, Status.OFF, FailureReason.ERROR, true);
}
}
}
}
/**
* The JID of the entity that has initiated the recording flow.
* @return The JID of the entity that has initiated the recording flow.
*/
public Jid getInitiator()
{
return initiator;
}
/**
* The JID of the entity that has initiated the stop of the recording.
* @return The JID of the entity that has stopped the recording.
*/
public Jid getTerminator()
{
return terminator;
}
/**
* Interface instance passed to {@link JibriSession} constructor which
* specifies the session owner which will be notified about any status
* changes.
*/
public interface Owner
{
/**
* Called on {@link JibriSession} status update.
* @param jibriSession which status has changed
* @param newStatus the new status
* @param failureReason optional error for {@link JibriIq.Status#OFF}.
*/
void onSessionStateChanged(
JibriSession jibriSession,
JibriIq.Status newStatus,
JibriIq.FailureReason failureReason);
}
static public class StartException extends Exception
{
final static String ALL_BUSY = "All Jibri instances are busy";
final static String INTERNAL_SERVER_ERROR = "Internal server error";
final static String NOT_AVAILABLE = "No Jibris available";
final static String UNEXPECTED_RESPONSE = "Unexpected response";
private final String reason;
StartException(String reason)
{
super(reason);
this.reason = reason;
}
String getReason()
{
return reason;
}
}
}
|
23801_4 | package domein;
import java.util.Vector;
public class Rubriek {
public String naam;
public Integer id;
// /**
// *
// * @element-type Veiling
// */
// public Vector veilingen;
// /**
// *
// * @element-type Rubriek
// */
// public Vector childeren;
public Rubriek parent;
public Rubriek(String naam, Rubriek parent) {
super();
this.naam = naam;
this.parent = parent;
}
public Rubriek(){
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
//
// public Vector getVeilingen() {
// return veilingen;
// }
//
// public void setVeilingen(Vector veilingen) {
// this.veilingen = veilingen;
// }
//
// public Vector getChilderen() {
// return childeren;
// }
//
// public void setChilderen(Vector childeren) {
// this.childeren = childeren;
// }
public Rubriek getParent() {
return parent;
}
public void setParent(Rubriek parent) {
this.parent = parent;
}
} | Neverfor/TO5 | src/domein/Rubriek.java | 398 | // this.veilingen = veilingen; | line_comment | nl | package domein;
import java.util.Vector;
public class Rubriek {
public String naam;
public Integer id;
// /**
// *
// * @element-type Veiling
// */
// public Vector veilingen;
// /**
// *
// * @element-type Rubriek
// */
// public Vector childeren;
public Rubriek parent;
public Rubriek(String naam, Rubriek parent) {
super();
this.naam = naam;
this.parent = parent;
}
public Rubriek(){
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
//
// public Vector getVeilingen() {
// return veilingen;
// }
//
// public void setVeilingen(Vector veilingen) {
// this.veilingen =<SUF>
// }
//
// public Vector getChilderen() {
// return childeren;
// }
//
// public void setChilderen(Vector childeren) {
// this.childeren = childeren;
// }
public Rubriek getParent() {
return parent;
}
public void setParent(Rubriek parent) {
this.parent = parent;
}
} |
Subsets and Splits