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
|
---|---|---|---|---|---|---|---|---|
22065_1 | package com.company;
import java.io.Serializable;
import java.time.LocalTime;
import java.util.ArrayList;
public class Battle implements Serializable {
/*
Als eerste krijgen we de Object attributen voor deze klasse.
*/
private LocalTime beginTime;
private LocalTime endTime;
private int popularityPercent;
private Arena arena;
private Trainer trainer1;
private Trainer trainer2;
/*
Als tweede krijgen we de constructor(s) voor deze klasse.
*/
//TODO Add percentage availability check.
public Battle(LocalTime beginTime, LocalTime endTime, int popularityPercent, Arena arena, Trainer trainer1, Trainer trainer2) {
this.beginTime = beginTime;
this.endTime = endTime;
this.popularityPercent = popularityPercent;
this.arena = arena;
this.trainer1 = trainer1;
this.trainer2 = trainer2;
Battle.list.add(this);
}
/*
Nu komen methods die public zijn en dus door andere Klassen bereikt kunnen worden.
*/
public LocalTime getBeginTime() {
return this.beginTime;
}
public LocalTime getEndTime() {
return this.endTime;
}
public int getPopularity() {
return this.popularityPercent;
}
public String getPopularityString() {
String popularityString = String.valueOf(getPopularity());
return popularityString;
}
public Arena getArena() {
return this.arena;
}
public Trainer getTrainer1() {
return this.trainer1;
}
public Trainer getTrainer2() {
return this.trainer2;
}
public void setBeginTime(LocalTime beginTime) {
this.beginTime = beginTime;
}
public void setEndTime(LocalTime endTime) {
this.endTime = endTime;
}
//TODO Add Availablity check.
public void setPopularity(int popularityPercent) {
this.popularityPercent = popularityPercent;
}
public void setArena(Arena arena) {
this.arena = arena;
}
public void setTrainer1(Trainer trainer1) {
this.trainer1 = trainer1;
}
public void setTrainer2(Trainer trainer2) {
this.trainer2 = trainer2;
}
public static ArrayList<Battle> list = new ArrayList<>();
public void remove() {
Battle.list.remove(this);
}
public int availablePopulationPercent() {
int availablePopulation = 100;
if (Battle.list.size() > 0) {
for (Battle battle : Battle.list) {
availablePopulation -= battle.getPopularity();
if (availablePopulation < 0) {
int givingPopulation = battle.getPopularity() - (availablePopulation * -1);
availablePopulation = 0;
return givingPopulation;
}
}
}
return availablePopulation;
}
public boolean populationIsAvailable(int population) {
if ((availablePopulationPercent() - population) >= 0) {
return true;
}
return false;
}
@Override
public String toString() {
return "Battle{" +
"beginTime=" + beginTime +
", endTime=" + endTime +
", popularity=" + popularityPercent +
", arena=" + arena +
", trainer1=" + trainer1 +
", trainer2=" + trainer2 +
'}';
}
}
| KaanMol/FestivalPlanner-1.3 | src/com/company/Battle.java | 943 | /*
Als tweede krijgen we de constructor(s) voor deze klasse.
*/ | block_comment | nl | package com.company;
import java.io.Serializable;
import java.time.LocalTime;
import java.util.ArrayList;
public class Battle implements Serializable {
/*
Als eerste krijgen we de Object attributen voor deze klasse.
*/
private LocalTime beginTime;
private LocalTime endTime;
private int popularityPercent;
private Arena arena;
private Trainer trainer1;
private Trainer trainer2;
/*
Als tweede krijgen<SUF>*/
//TODO Add percentage availability check.
public Battle(LocalTime beginTime, LocalTime endTime, int popularityPercent, Arena arena, Trainer trainer1, Trainer trainer2) {
this.beginTime = beginTime;
this.endTime = endTime;
this.popularityPercent = popularityPercent;
this.arena = arena;
this.trainer1 = trainer1;
this.trainer2 = trainer2;
Battle.list.add(this);
}
/*
Nu komen methods die public zijn en dus door andere Klassen bereikt kunnen worden.
*/
public LocalTime getBeginTime() {
return this.beginTime;
}
public LocalTime getEndTime() {
return this.endTime;
}
public int getPopularity() {
return this.popularityPercent;
}
public String getPopularityString() {
String popularityString = String.valueOf(getPopularity());
return popularityString;
}
public Arena getArena() {
return this.arena;
}
public Trainer getTrainer1() {
return this.trainer1;
}
public Trainer getTrainer2() {
return this.trainer2;
}
public void setBeginTime(LocalTime beginTime) {
this.beginTime = beginTime;
}
public void setEndTime(LocalTime endTime) {
this.endTime = endTime;
}
//TODO Add Availablity check.
public void setPopularity(int popularityPercent) {
this.popularityPercent = popularityPercent;
}
public void setArena(Arena arena) {
this.arena = arena;
}
public void setTrainer1(Trainer trainer1) {
this.trainer1 = trainer1;
}
public void setTrainer2(Trainer trainer2) {
this.trainer2 = trainer2;
}
public static ArrayList<Battle> list = new ArrayList<>();
public void remove() {
Battle.list.remove(this);
}
public int availablePopulationPercent() {
int availablePopulation = 100;
if (Battle.list.size() > 0) {
for (Battle battle : Battle.list) {
availablePopulation -= battle.getPopularity();
if (availablePopulation < 0) {
int givingPopulation = battle.getPopularity() - (availablePopulation * -1);
availablePopulation = 0;
return givingPopulation;
}
}
}
return availablePopulation;
}
public boolean populationIsAvailable(int population) {
if ((availablePopulationPercent() - population) >= 0) {
return true;
}
return false;
}
@Override
public String toString() {
return "Battle{" +
"beginTime=" + beginTime +
", endTime=" + endTime +
", popularity=" + popularityPercent +
", arena=" + arena +
", trainer1=" + trainer1 +
", trainer2=" + trainer2 +
'}';
}
}
|
57428_0 | public class Antwoord {
private String antwoord;
private Vraag huidigeVraag;
public Antwoord(Vraag huidigeVraag, String antwoord) {
this.huidigeVraag = huidigeVraag;
this.antwoord = antwoord;
}
public String getAntwoord() {
return antwoord;
}
// public Vraag controleerAntwoord() {
// if (huidigeVraag.getAntwoord().equals(antwoord)) {
// return huidigeVraag;
// }
// return null;
// }
}
| Kafune/ooad-finch-app | src/Antwoord.java | 156 | // public Vraag controleerAntwoord() { | line_comment | nl | public class Antwoord {
private String antwoord;
private Vraag huidigeVraag;
public Antwoord(Vraag huidigeVraag, String antwoord) {
this.huidigeVraag = huidigeVraag;
this.antwoord = antwoord;
}
public String getAntwoord() {
return antwoord;
}
// public Vraag<SUF>
// if (huidigeVraag.getAntwoord().equals(antwoord)) {
// return huidigeVraag;
// }
// return null;
// }
}
|
43984_4 | package nl.han.ica.oopd.bubbletrouble;
import java.util.List;
import java.util.Random;
import nl.han.ica.oopg.collision.CollidedTile;
import nl.han.ica.oopg.collision.CollisionSide;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.collision.ICollidableWithTiles;
import nl.han.ica.oopg.exceptions.TileNotFoundException;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.objects.Sprite;
import nl.han.ica.oopg.objects.SpriteObject;
import processing.core.PGraphics;
import processing.core.PVector;
public class Bubble extends SpriteObject implements ICollidableWithTiles, ICollidableWithGameObjects {
private BubbleTrouble bubbleTrouble;
private Powerup powerupMovespeed;
private Powerup powerupProjectilespeed;
private Projectile projectile;
private Player player;
private Random random;
private int bubbleSize;
public Bubble(int bubbleSize, BubbleTrouble bubbleTrouble, Sprite sprite, Player player, Projectile projectile) {
super(sprite);
this.bubbleTrouble = bubbleTrouble;
this.player = player;
this.projectile = projectile;
powerupMovespeed = new PowerupMoveSpeed(new Sprite("src/main/resources/bubble-trouble/movespeedpowerup.png"),
bubbleTrouble, player);
powerupProjectilespeed = new PowerupProjectileSpeed(
new Sprite("src/main/resources/bubble-trouble/projectilespeedpowerup.png"), bubbleTrouble, player, projectile);
this.bubbleSize = bubbleSize;
random = new Random();
setGravity(0.20f);
setySpeed(-bubbleSize / 10f);
setxSpeed(-bubbleSize / 8f);
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
}
@Override
public void tileCollisionOccurred(List<CollidedTile> collidedTiles) {
PVector vector;
for (CollidedTile ct : collidedTiles) {
if (ct.getTile() instanceof FloorTile) {
try {
if (CollisionSide.BOTTOM.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
setDirection(225);
}
if (CollisionSide.LEFT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setX(vector.x - getWidth());
setxSpeed(-getxSpeed());
setDirection(345);
}
if (CollisionSide.TOP.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
if (getDirection() <= 180) {
setDirection(15);
} else {
setDirection(345);
}
}
if (CollisionSide.RIGHT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
System.out.println(bubbleSize);
if (bubbleSize == 64) {
setX(vector.x + getWidth());
} else if (bubbleSize == 32) {
setX(vector.x + getWidth()+32);
} else if (bubbleSize == 16) {
setX(vector.x + getWidth()+64);
}
setxSpeed(-getxSpeed());
setDirection(15);
}
} catch (TileNotFoundException e) {
e.printStackTrace();
}
}
}
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Projectile || g instanceof ProjectileTrail) {
// Projectile projectile = (Projectile) g;
// bubbleTrouble.deleteGameObject(this);
if (bubbleSize > 16) {
System.out.println("Bubble groter dan 16: splitsen");
int smallerBubbleSize = bubbleSize / 2;
Bubble newBubble1 = new Bubble(smallerBubbleSize, bubbleTrouble,
new Sprite("src/main/resources/bubble-trouble/bubbleblue.png"), player, player.getProjectile());
newBubble1.setxSpeed(-getxSpeed());
// De twee nieuwe bubbles moeten verplaatst om te voorkomen dat ze direct weer
// botsen.
// En wellicht daardoor direct verdwijnen, omdat projectiel niet direct
// verdwijnt bij botsing.
// TODO: Mooier om in plaats hiervan nieuwe bubbels na aanmaken even tijdje
// 'onbotsbaar te maken'
// Dit via ander stukje bubble logica, dan verschieten ze niet opeens.
final int VERPLAATSEN_BIJ_BOTSING = 40;
newBubble1.setX(getX() + VERPLAATSEN_BIJ_BOTSING);
newBubble1.setY(getY());
newBubble1.setySpeed(getySpeed());
bubbleTrouble.addGameObject(newBubble1);
// Maak ook de huidige bubbel kleiner.
this.bubbleSize = smallerBubbleSize;
setWidth(bubbleSize);
setX(getX() - VERPLAATSEN_BIJ_BOTSING);
setHeight(bubbleSize);
} else {
bubbleTrouble.deleteGameObject(this);
}
int powerupRoll = random.nextInt(4);
System.out.println(powerupRoll);
if (powerupRoll == 0) {
if (bubbleTrouble.isProjectilePowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupProjectilespeed, getX(), getY() + 10);
bubbleTrouble.setProjectilePowerupSpawned(true);
}
} else if (powerupRoll == 1) {
if (bubbleTrouble.isMovespeedPowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupMovespeed, getX(), getY() + 10);
bubbleTrouble.setMovespeedPowerupSpawned(true);
}
}
} else if (g instanceof Bubble) {
// bubble
}
}
}
@Override
public void draw(PGraphics g) {
// g.fill(120, 120, 230);
// g.ellipse(x, y, bubbleSize, bubbleSize);
g.image(getImage(), x, y, getWidth(), getHeight());
}
}
| Kafune/oopd-bp-bubble-trouble | src/main/java/nl/han/ica/oopd/bubbletrouble/Bubble.java | 2,025 | // TODO: Mooier om in plaats hiervan nieuwe bubbels na aanmaken even tijdje | line_comment | nl | package nl.han.ica.oopd.bubbletrouble;
import java.util.List;
import java.util.Random;
import nl.han.ica.oopg.collision.CollidedTile;
import nl.han.ica.oopg.collision.CollisionSide;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.collision.ICollidableWithTiles;
import nl.han.ica.oopg.exceptions.TileNotFoundException;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.objects.Sprite;
import nl.han.ica.oopg.objects.SpriteObject;
import processing.core.PGraphics;
import processing.core.PVector;
public class Bubble extends SpriteObject implements ICollidableWithTiles, ICollidableWithGameObjects {
private BubbleTrouble bubbleTrouble;
private Powerup powerupMovespeed;
private Powerup powerupProjectilespeed;
private Projectile projectile;
private Player player;
private Random random;
private int bubbleSize;
public Bubble(int bubbleSize, BubbleTrouble bubbleTrouble, Sprite sprite, Player player, Projectile projectile) {
super(sprite);
this.bubbleTrouble = bubbleTrouble;
this.player = player;
this.projectile = projectile;
powerupMovespeed = new PowerupMoveSpeed(new Sprite("src/main/resources/bubble-trouble/movespeedpowerup.png"),
bubbleTrouble, player);
powerupProjectilespeed = new PowerupProjectileSpeed(
new Sprite("src/main/resources/bubble-trouble/projectilespeedpowerup.png"), bubbleTrouble, player, projectile);
this.bubbleSize = bubbleSize;
random = new Random();
setGravity(0.20f);
setySpeed(-bubbleSize / 10f);
setxSpeed(-bubbleSize / 8f);
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
}
@Override
public void tileCollisionOccurred(List<CollidedTile> collidedTiles) {
PVector vector;
for (CollidedTile ct : collidedTiles) {
if (ct.getTile() instanceof FloorTile) {
try {
if (CollisionSide.BOTTOM.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
setDirection(225);
}
if (CollisionSide.LEFT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setX(vector.x - getWidth());
setxSpeed(-getxSpeed());
setDirection(345);
}
if (CollisionSide.TOP.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
if (getDirection() <= 180) {
setDirection(15);
} else {
setDirection(345);
}
}
if (CollisionSide.RIGHT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
System.out.println(bubbleSize);
if (bubbleSize == 64) {
setX(vector.x + getWidth());
} else if (bubbleSize == 32) {
setX(vector.x + getWidth()+32);
} else if (bubbleSize == 16) {
setX(vector.x + getWidth()+64);
}
setxSpeed(-getxSpeed());
setDirection(15);
}
} catch (TileNotFoundException e) {
e.printStackTrace();
}
}
}
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Projectile || g instanceof ProjectileTrail) {
// Projectile projectile = (Projectile) g;
// bubbleTrouble.deleteGameObject(this);
if (bubbleSize > 16) {
System.out.println("Bubble groter dan 16: splitsen");
int smallerBubbleSize = bubbleSize / 2;
Bubble newBubble1 = new Bubble(smallerBubbleSize, bubbleTrouble,
new Sprite("src/main/resources/bubble-trouble/bubbleblue.png"), player, player.getProjectile());
newBubble1.setxSpeed(-getxSpeed());
// De twee nieuwe bubbles moeten verplaatst om te voorkomen dat ze direct weer
// botsen.
// En wellicht daardoor direct verdwijnen, omdat projectiel niet direct
// verdwijnt bij botsing.
// TODO: Mooier<SUF>
// 'onbotsbaar te maken'
// Dit via ander stukje bubble logica, dan verschieten ze niet opeens.
final int VERPLAATSEN_BIJ_BOTSING = 40;
newBubble1.setX(getX() + VERPLAATSEN_BIJ_BOTSING);
newBubble1.setY(getY());
newBubble1.setySpeed(getySpeed());
bubbleTrouble.addGameObject(newBubble1);
// Maak ook de huidige bubbel kleiner.
this.bubbleSize = smallerBubbleSize;
setWidth(bubbleSize);
setX(getX() - VERPLAATSEN_BIJ_BOTSING);
setHeight(bubbleSize);
} else {
bubbleTrouble.deleteGameObject(this);
}
int powerupRoll = random.nextInt(4);
System.out.println(powerupRoll);
if (powerupRoll == 0) {
if (bubbleTrouble.isProjectilePowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupProjectilespeed, getX(), getY() + 10);
bubbleTrouble.setProjectilePowerupSpawned(true);
}
} else if (powerupRoll == 1) {
if (bubbleTrouble.isMovespeedPowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupMovespeed, getX(), getY() + 10);
bubbleTrouble.setMovespeedPowerupSpawned(true);
}
}
} else if (g instanceof Bubble) {
// bubble
}
}
}
@Override
public void draw(PGraphics g) {
// g.fill(120, 120, 230);
// g.ellipse(x, y, bubbleSize, bubbleSize);
g.image(getImage(), x, y, getWidth(), getHeight());
}
}
|
148545_9 | /**
*
*/
package ea.aco.gui;
import static ea.gui.GUIKonstante.ZAUSTAVI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import de.congrace.exp4j.UnknownFunctionException;
import de.congrace.exp4j.UnparsableExpressionException;
import ea.aco.Grad;
import ea.gui.DijeljenaPloca;
import ea.gui.GUI;
import ea.gui.RadioGumbi;
import ea.gui.TekstPodrucje;
import ea.gui.TekstualnaVrijednost;
import ea.simulatori.ACOSimulator;
import ea.util.Par;
import static ea.aco.gui.ACOGUIKonstante.*;
/**
* @author Zlikavac32
*
*/
public class ACOGUI extends GUI {
private TekstPodrucje gradovi;
private TekstualnaVrijednost brojGeneracija;
private TekstualnaVrijednost sjeme;
private RadioGumbi algoritam;
private TekstualnaVrijednost brojMrava;
private TekstualnaVrijednost konstantaIsparavanja;
private TekstualnaVrijednost alfa;
private TekstualnaVrijednost beta;
private TekstualnaVrijednost brojMravaAzurira;
//private TekstualnaVrijednost brojKoraka;
//private TekstualnaVrijednost a;
private Ploca gradoviPloca = new Ploca();
private Ploca brojMravaAzuriraPloca = new Ploca();
private Ploca brojGeneracijaPloca = new Ploca();
private Ploca sjemePloca = new Ploca();
private Ploca algoritamPloca = new Ploca();
private Ploca brojMravaPloca = new Ploca();
private Ploca konstantaIsparavanjaPloca = new Ploca();
private Ploca alfaPloca = new Ploca();
private Ploca betaPloca = new Ploca();
//private Ploca brojKorakaPloca = new Ploca();
//private Ploca aPloca = new Ploca();
/**
*
*/
private static final long serialVersionUID = -8465945028324200176L;
private XYSeriesCollection putanjeKolekcija;
private XYSeriesCollection najboljaPutanjaKolekcija;
protected XYSeriesCollection kolekcija;
protected JFreeChart graf;
protected XYPlot nacrt;
public ACOGUI(String title) { super(title); }
private class NacrtajGradove implements Runnable {
Grad[] gradovi;
NacrtajGradove(Grad[] gradovi) { this.gradovi = gradovi; }
@Override
public void run() {
XYSeries podatci = new XYSeries("Gradovi");
XYShapeRenderer renderer = (XYShapeRenderer) nacrt.getRenderer(0);
renderer.removeAnnotations();
for (Grad grad : gradovi) {
podatci.add(grad.x, grad.y);
renderer.addAnnotation(new XYTextAnnotation(grad.ime, grad.x, grad.y));
}
nacrt.setRenderer(0, null);
kolekcija.removeSeries(0);
kolekcija.addSeries(podatci);
nacrt.setRenderer(0, renderer);
nacrt.setDataset(kolekcija);
}
}
private class NacrtajPutanju implements Runnable {
Grad[] najbolji;
Grad[] gradovi;
NacrtajPutanju(Grad[] najbolji, Grad[] gradovi) {
this.najbolji = najbolji;
this.gradovi = gradovi;
}
@Override
public void run() {
XYSeries podatci = new XYSeries(PUTANJA, false, true);
Grad prvi = gradovi[0];
for (Grad grad : gradovi) { podatci.add(grad.x, grad.y); }
podatci.add(prvi.x, prvi.y);
putanjeKolekcija.removeSeries(0);
putanjeKolekcija.addSeries(podatci);
nacrt.setDataset(1, putanjeKolekcija);
podatci = new XYSeries(NAJBOLJA_PUTANJA, false, true);
prvi = najbolji[0];
for (Grad grad : najbolji) { podatci.add(grad.x, grad.y); }
podatci.add(prvi.x, prvi.y);
najboljaPutanjaKolekcija.removeSeries(0);
najboljaPutanjaKolekcija.addSeries(podatci);
nacrt.setDataset(2, najboljaPutanjaKolekcija);
}
}
protected JPanel stvoriKontroleKontejner() {
JPanel kontroleKontejnerVanjski = new JPanel(new BorderLayout());
JPanel kontroleKontejner = new JPanel();
kontroleKontejner.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));
kontroleKontejner.setLayout(new BoxLayout(kontroleKontejner, BoxLayout.Y_AXIS));
inicijalizirajElementeKontrola();
DijeljenaPloca[] elementi = new DijeljenaPloca[] {
gradovi, sjeme, brojMrava,
algoritam, konstantaIsparavanja,
alfa, beta, /* a ,*/ brojMravaAzurira, /* brojKoraka ,*/ brojGeneracija
};
Ploca[] ploce = new Ploca[] {
gradoviPloca, sjemePloca, brojMravaPloca,
algoritamPloca, konstantaIsparavanjaPloca,
alfaPloca, betaPloca, /* aPloca ,*/ brojMravaAzuriraPloca, /* brojKorakaPloca ,*/ brojGeneracijaPloca
};
for (int i = 0; i < elementi.length; i++) {
JPanel ploca = new JPanel();
ploca.setLayout(new BoxLayout(ploca, BoxLayout.Y_AXIS));
ploca.add(elementi[i]);
ploca.add(Box.createRigidArea(new Dimension(0, 10)));
ploce[i].ploca = ploca;
kontroleKontejner.add(ploca);
}
kontroleKontejnerVanjski.add(kontroleKontejner, BorderLayout.NORTH);
return kontroleKontejnerVanjski;
}
protected void inicijalizirajElementeKontrola() {
ActionListener sakrijOtkrij = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean flag = !algoritam.vratiOdabrani().getActionCommand().equals(SIMPLE_ACO);
beta.setEnabled(flag);
flag = algoritam.vratiOdabrani().getActionCommand().equals(SIMPLE_ACO);
brojMravaAzurira.setEnabled(flag);
//flag = algoritam.vratiOdabrani().getActionCommand().equals(MAX_MIN_ANT_SYSTEM);
//brojKoraka.setEnabled(flag);
//a.setEnabled(flag);
}
};
brojMravaAzurira = new TekstualnaVrijednost(BROJ_MRAVA_AZURIRA, "10");
brojMrava = new TekstualnaVrijednost(BROJ_MRAVA, "50");
brojGeneracija = new TekstualnaVrijednost(BROJ_GENERACIJA, "2000");
sjeme = new TekstualnaVrijednost(SJEME, "123456");
algoritam = new RadioGumbi(ALGORITAM, new String[] {
SIMPLE_ACO, ANT_SYSTEM//, MAX_MIN_ANT_SYSTEM
}, 0, new ActionListener[] {
sakrijOtkrij, sakrijOtkrij//, sakrijOtkrij
});
konstantaIsparavanja = new TekstualnaVrijednost(KONSTANTA_ISPARAVANJA, "0.5");
alfa = new TekstualnaVrijednost(ALFA, "1");
beta = new TekstualnaVrijednost(BETA, "2");
beta.setEnabled(false);
gradovi = new TekstPodrucje(GRADOVI,
"1 565 575\n"
+ "2 25 185\n"
+ "3 345 750\n"
+ "4 945 685\n"
+ "5 845 655\n"
+ "6 880 660\n"
+ "7 25 230\n"
+ "8 525 1000\n"
+ "9 580 1175\n"
+ "10 650 1130\n"
+ "11 1605 620\n"
+ "12 1220 580\n"
+ "13 1465 200\n"
+ "14 1530 5\n"
+ "15 845 680\n"
+ "16 725 370\n"
+ "17 145 665\n"
+ "18 415 635\n"
+ "19 510 875\n"
+ "20 560 365\n"
+ "21 300 465\n"
+ "22 520 585\n"
+ "23 480 415\n"
+ "24 835 625\n"
+ "25 975 580\n"
+ "26 1215 245\n"
+ "27 1320 315\n"
+ "28 1250 400\n"
+ "29 660 180\n"
+ "30 410 250\n"
+ "31 420 555\n"
+ "32 575 665\n"
+ "33 1150 1160\n"
+ "34 700 580\n"
+ "35 685 595\n"
+ "36 685 610\n"
+ "37 770 610\n"
+ "38 795 645\n"
+ "39 720 635\n"
+ "40 760 650\n"
+ "41 475 960\n"
+ "42 95 260\n"
+ "43 875 920\n"
+ "44 700 500\n"
+ "45 555 815\n"
+ "46 830 485\n"
+ "47 1170 65\n"
+ "48 830 610\n"
+ "49 605 625\n"
+ "50 595 360\n"
+ "51 1340 725\n"
+ "52 1740 245\n",
10);
//brojKoraka = new TekstualnaVrijednost(BROJ_KORAKA, "20");
//brojKoraka.setEnabled(false);
//a = new TekstualnaVrijednost("A", "5");
//a.setEnabled(false);
}
protected ChartPanel stvoriGraf() {
XYSeries podatci = new XYSeries("Gradovi");
kolekcija = new XYSeriesCollection();
kolekcija.addSeries(podatci);
graf = ChartFactory.createXYLineChart("Gradovi", "", "", null, PlotOrientation.VERTICAL, true, false, false);
nacrt = graf.getXYPlot();
nacrt.setRenderer(0, new XYShapeRenderer());
java.awt.geom.Ellipse2D.Double kruzici = new java.awt.geom.Ellipse2D.Double(-4D, -4D, 8D, 8D);
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setBaseShapesVisible(true);
renderer.setSeriesShape(0, kruzici);
renderer.setSeriesPaint(0, Color.RED);
renderer.setSeriesFillPaint(0, Color.YELLOW);
renderer.setSeriesOutlinePaint(0, Color.GRAY);
podatci = new XYSeries(PUTANJA);
putanjeKolekcija = new XYSeriesCollection();
putanjeKolekcija.addSeries(podatci);
nacrt.setRenderer(1, renderer);
kruzici = new java.awt.geom.Ellipse2D.Double(-4D, -4D, 8D, 8D);
renderer = new XYLineAndShapeRenderer();
renderer.setBaseShapesVisible(true);
renderer.setSeriesShape(0, kruzici);
renderer.setSeriesPaint(0, Color.BLUE);
renderer.setSeriesFillPaint(0, Color.YELLOW);
renderer.setSeriesOutlinePaint(0, Color.GRAY);
podatci = new XYSeries(NAJBOLJA_PUTANJA);
najboljaPutanjaKolekcija = new XYSeriesCollection();
najboljaPutanjaKolekcija.addSeries(podatci);
nacrt.setRenderer(2, renderer);
ChartPanel grafPloca = new ChartPanel(graf);
return grafPloca;
}
protected void pokreniSimulaciju(JButton gumb)
throws UnknownFunctionException, UnparsableExpressionException {
ACOSimulator simulator = new ACOSimulator();
try {
simulator.koristeciSjeme(Long.parseLong(sjeme.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Sjeme mora biti cijeli broj");
return ;
}
try {
simulator.koristeciBrojMrava(Integer.parseInt(brojMrava.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj mrava mora biti cijeli broj");
return ;
}
List<Par<String, Par<Double, Double>>> gradoviLista = new ArrayList<Par<String, Par<Double, Double>>>();
String[] linije = gradovi.vratiVrijednost().split("\n");
for (int i = 0; i < linije.length; i++) {
// String dijelovi[] = linije[i].split(",");
// int x = Integer.parseInt(dijelovi[0].trim());
// int y = Integer.parseInt(dijelovi[1].trim());
// Par<String, Par<Integer, Integer>> grad = new Par<String, Par<Integer, Integer>>(
// dijelovi.length > 2 ? dijelovi[2].trim() : Integer.toString(i + 1),
// new Par<Integer, Integer>(x, y)
// );
String dijelovi[] = linije[i].split(" ");
double x = Double.parseDouble(dijelovi[1].trim());
double y = Double.parseDouble(dijelovi[2].trim());
Par<String, Par<Double, Double>> grad = new Par<String, Par<Double, Double>>(
dijelovi[0].trim(),
new Par<Double, Double>(x, y)
);
gradoviLista.add(grad);
}
simulator.koristeciGradove(gradoviLista);
int odabraniAlgoritam;
if (algoritam.vratiOdabrani().getActionCommand().equals(SIMPLE_ACO)) {
odabraniAlgoritam = ACOSimulator.SIMPLE_ACO_ALGORITAM;
} else if (algoritam.vratiOdabrani().getActionCommand().equals(ANT_SYSTEM)) {
odabraniAlgoritam = ACOSimulator.ANT_SYSTEM_ALGORITAM;
} else {
odabraniAlgoritam = ACOSimulator.MAX_MIN_ANT_SYSTEM_ALGORITM;
}
simulator.koristeciAlgoritam(odabraniAlgoritam);
try {
simulator.koristeciAlfa(Double.parseDouble(alfa.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Alfa mora biti broj");
return ;
}
if (odabraniAlgoritam == ACOSimulator.SIMPLE_ACO_ALGORITAM) {
try {
simulator.koristeciBrojMravaZaAzuriranje(Integer.parseInt(brojMravaAzurira.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj mrava za azuriranje mora biti cijeli broj");
return ;
}
} else {
try {
simulator.koristeciBeta(Double.parseDouble(beta.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Beta mora biti broj");
return ;
}
/*if (odabraniAlgoritam == ACOSimulator.MAX_MIN_ANT_SYSTEM_ALGORITM) {
try {
simulator.koristecKonstantuA(Double.parseDouble(a.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Konstanta A mora biti broj");
return ;
}
try {
simulator.uzBrojKoraka(Integer.parseInt(brojKoraka.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj koraka mora biti cijeli broj");
return ;
}
}*/
}
try {
simulator.koristeciKonstantuIsparavanja(Double.parseDouble(konstantaIsparavanja.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Konstanta isparavanja mora biti broj");
return ;
}
try {
simulator.uzBrojGeneracija(Integer.parseInt(brojGeneracija.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj generacija mora biti cijeli broj");
return ;
}
simulator.postaviGUI(this);
simulator.addPropertyChangeListener(new ZaustaviSimulaciju(gumb));
simulator.execute();
this.simulator = simulator;
gumb.setText(ZAUSTAVI);
}
public void iscrtajPutanju(Grad[] najbolji, Grad[] gradovi) { SwingUtilities.invokeLater(new NacrtajPutanju(najbolji, gradovi)); }
public void iscrtajGradove(Grad[] gradovi) { SwingUtilities.invokeLater(new NacrtajGradove(gradovi)); }
}
| KarloKnezevic/EvolutionaryAlgorithms | Projekt-EA/src/ea/aco/gui/ACOGUI.java | 5,714 | // int x = Integer.parseInt(dijelovi[0].trim()); | line_comment | nl | /**
*
*/
package ea.aco.gui;
import static ea.gui.GUIKonstante.ZAUSTAVI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import de.congrace.exp4j.UnknownFunctionException;
import de.congrace.exp4j.UnparsableExpressionException;
import ea.aco.Grad;
import ea.gui.DijeljenaPloca;
import ea.gui.GUI;
import ea.gui.RadioGumbi;
import ea.gui.TekstPodrucje;
import ea.gui.TekstualnaVrijednost;
import ea.simulatori.ACOSimulator;
import ea.util.Par;
import static ea.aco.gui.ACOGUIKonstante.*;
/**
* @author Zlikavac32
*
*/
public class ACOGUI extends GUI {
private TekstPodrucje gradovi;
private TekstualnaVrijednost brojGeneracija;
private TekstualnaVrijednost sjeme;
private RadioGumbi algoritam;
private TekstualnaVrijednost brojMrava;
private TekstualnaVrijednost konstantaIsparavanja;
private TekstualnaVrijednost alfa;
private TekstualnaVrijednost beta;
private TekstualnaVrijednost brojMravaAzurira;
//private TekstualnaVrijednost brojKoraka;
//private TekstualnaVrijednost a;
private Ploca gradoviPloca = new Ploca();
private Ploca brojMravaAzuriraPloca = new Ploca();
private Ploca brojGeneracijaPloca = new Ploca();
private Ploca sjemePloca = new Ploca();
private Ploca algoritamPloca = new Ploca();
private Ploca brojMravaPloca = new Ploca();
private Ploca konstantaIsparavanjaPloca = new Ploca();
private Ploca alfaPloca = new Ploca();
private Ploca betaPloca = new Ploca();
//private Ploca brojKorakaPloca = new Ploca();
//private Ploca aPloca = new Ploca();
/**
*
*/
private static final long serialVersionUID = -8465945028324200176L;
private XYSeriesCollection putanjeKolekcija;
private XYSeriesCollection najboljaPutanjaKolekcija;
protected XYSeriesCollection kolekcija;
protected JFreeChart graf;
protected XYPlot nacrt;
public ACOGUI(String title) { super(title); }
private class NacrtajGradove implements Runnable {
Grad[] gradovi;
NacrtajGradove(Grad[] gradovi) { this.gradovi = gradovi; }
@Override
public void run() {
XYSeries podatci = new XYSeries("Gradovi");
XYShapeRenderer renderer = (XYShapeRenderer) nacrt.getRenderer(0);
renderer.removeAnnotations();
for (Grad grad : gradovi) {
podatci.add(grad.x, grad.y);
renderer.addAnnotation(new XYTextAnnotation(grad.ime, grad.x, grad.y));
}
nacrt.setRenderer(0, null);
kolekcija.removeSeries(0);
kolekcija.addSeries(podatci);
nacrt.setRenderer(0, renderer);
nacrt.setDataset(kolekcija);
}
}
private class NacrtajPutanju implements Runnable {
Grad[] najbolji;
Grad[] gradovi;
NacrtajPutanju(Grad[] najbolji, Grad[] gradovi) {
this.najbolji = najbolji;
this.gradovi = gradovi;
}
@Override
public void run() {
XYSeries podatci = new XYSeries(PUTANJA, false, true);
Grad prvi = gradovi[0];
for (Grad grad : gradovi) { podatci.add(grad.x, grad.y); }
podatci.add(prvi.x, prvi.y);
putanjeKolekcija.removeSeries(0);
putanjeKolekcija.addSeries(podatci);
nacrt.setDataset(1, putanjeKolekcija);
podatci = new XYSeries(NAJBOLJA_PUTANJA, false, true);
prvi = najbolji[0];
for (Grad grad : najbolji) { podatci.add(grad.x, grad.y); }
podatci.add(prvi.x, prvi.y);
najboljaPutanjaKolekcija.removeSeries(0);
najboljaPutanjaKolekcija.addSeries(podatci);
nacrt.setDataset(2, najboljaPutanjaKolekcija);
}
}
protected JPanel stvoriKontroleKontejner() {
JPanel kontroleKontejnerVanjski = new JPanel(new BorderLayout());
JPanel kontroleKontejner = new JPanel();
kontroleKontejner.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));
kontroleKontejner.setLayout(new BoxLayout(kontroleKontejner, BoxLayout.Y_AXIS));
inicijalizirajElementeKontrola();
DijeljenaPloca[] elementi = new DijeljenaPloca[] {
gradovi, sjeme, brojMrava,
algoritam, konstantaIsparavanja,
alfa, beta, /* a ,*/ brojMravaAzurira, /* brojKoraka ,*/ brojGeneracija
};
Ploca[] ploce = new Ploca[] {
gradoviPloca, sjemePloca, brojMravaPloca,
algoritamPloca, konstantaIsparavanjaPloca,
alfaPloca, betaPloca, /* aPloca ,*/ brojMravaAzuriraPloca, /* brojKorakaPloca ,*/ brojGeneracijaPloca
};
for (int i = 0; i < elementi.length; i++) {
JPanel ploca = new JPanel();
ploca.setLayout(new BoxLayout(ploca, BoxLayout.Y_AXIS));
ploca.add(elementi[i]);
ploca.add(Box.createRigidArea(new Dimension(0, 10)));
ploce[i].ploca = ploca;
kontroleKontejner.add(ploca);
}
kontroleKontejnerVanjski.add(kontroleKontejner, BorderLayout.NORTH);
return kontroleKontejnerVanjski;
}
protected void inicijalizirajElementeKontrola() {
ActionListener sakrijOtkrij = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean flag = !algoritam.vratiOdabrani().getActionCommand().equals(SIMPLE_ACO);
beta.setEnabled(flag);
flag = algoritam.vratiOdabrani().getActionCommand().equals(SIMPLE_ACO);
brojMravaAzurira.setEnabled(flag);
//flag = algoritam.vratiOdabrani().getActionCommand().equals(MAX_MIN_ANT_SYSTEM);
//brojKoraka.setEnabled(flag);
//a.setEnabled(flag);
}
};
brojMravaAzurira = new TekstualnaVrijednost(BROJ_MRAVA_AZURIRA, "10");
brojMrava = new TekstualnaVrijednost(BROJ_MRAVA, "50");
brojGeneracija = new TekstualnaVrijednost(BROJ_GENERACIJA, "2000");
sjeme = new TekstualnaVrijednost(SJEME, "123456");
algoritam = new RadioGumbi(ALGORITAM, new String[] {
SIMPLE_ACO, ANT_SYSTEM//, MAX_MIN_ANT_SYSTEM
}, 0, new ActionListener[] {
sakrijOtkrij, sakrijOtkrij//, sakrijOtkrij
});
konstantaIsparavanja = new TekstualnaVrijednost(KONSTANTA_ISPARAVANJA, "0.5");
alfa = new TekstualnaVrijednost(ALFA, "1");
beta = new TekstualnaVrijednost(BETA, "2");
beta.setEnabled(false);
gradovi = new TekstPodrucje(GRADOVI,
"1 565 575\n"
+ "2 25 185\n"
+ "3 345 750\n"
+ "4 945 685\n"
+ "5 845 655\n"
+ "6 880 660\n"
+ "7 25 230\n"
+ "8 525 1000\n"
+ "9 580 1175\n"
+ "10 650 1130\n"
+ "11 1605 620\n"
+ "12 1220 580\n"
+ "13 1465 200\n"
+ "14 1530 5\n"
+ "15 845 680\n"
+ "16 725 370\n"
+ "17 145 665\n"
+ "18 415 635\n"
+ "19 510 875\n"
+ "20 560 365\n"
+ "21 300 465\n"
+ "22 520 585\n"
+ "23 480 415\n"
+ "24 835 625\n"
+ "25 975 580\n"
+ "26 1215 245\n"
+ "27 1320 315\n"
+ "28 1250 400\n"
+ "29 660 180\n"
+ "30 410 250\n"
+ "31 420 555\n"
+ "32 575 665\n"
+ "33 1150 1160\n"
+ "34 700 580\n"
+ "35 685 595\n"
+ "36 685 610\n"
+ "37 770 610\n"
+ "38 795 645\n"
+ "39 720 635\n"
+ "40 760 650\n"
+ "41 475 960\n"
+ "42 95 260\n"
+ "43 875 920\n"
+ "44 700 500\n"
+ "45 555 815\n"
+ "46 830 485\n"
+ "47 1170 65\n"
+ "48 830 610\n"
+ "49 605 625\n"
+ "50 595 360\n"
+ "51 1340 725\n"
+ "52 1740 245\n",
10);
//brojKoraka = new TekstualnaVrijednost(BROJ_KORAKA, "20");
//brojKoraka.setEnabled(false);
//a = new TekstualnaVrijednost("A", "5");
//a.setEnabled(false);
}
protected ChartPanel stvoriGraf() {
XYSeries podatci = new XYSeries("Gradovi");
kolekcija = new XYSeriesCollection();
kolekcija.addSeries(podatci);
graf = ChartFactory.createXYLineChart("Gradovi", "", "", null, PlotOrientation.VERTICAL, true, false, false);
nacrt = graf.getXYPlot();
nacrt.setRenderer(0, new XYShapeRenderer());
java.awt.geom.Ellipse2D.Double kruzici = new java.awt.geom.Ellipse2D.Double(-4D, -4D, 8D, 8D);
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setBaseShapesVisible(true);
renderer.setSeriesShape(0, kruzici);
renderer.setSeriesPaint(0, Color.RED);
renderer.setSeriesFillPaint(0, Color.YELLOW);
renderer.setSeriesOutlinePaint(0, Color.GRAY);
podatci = new XYSeries(PUTANJA);
putanjeKolekcija = new XYSeriesCollection();
putanjeKolekcija.addSeries(podatci);
nacrt.setRenderer(1, renderer);
kruzici = new java.awt.geom.Ellipse2D.Double(-4D, -4D, 8D, 8D);
renderer = new XYLineAndShapeRenderer();
renderer.setBaseShapesVisible(true);
renderer.setSeriesShape(0, kruzici);
renderer.setSeriesPaint(0, Color.BLUE);
renderer.setSeriesFillPaint(0, Color.YELLOW);
renderer.setSeriesOutlinePaint(0, Color.GRAY);
podatci = new XYSeries(NAJBOLJA_PUTANJA);
najboljaPutanjaKolekcija = new XYSeriesCollection();
najboljaPutanjaKolekcija.addSeries(podatci);
nacrt.setRenderer(2, renderer);
ChartPanel grafPloca = new ChartPanel(graf);
return grafPloca;
}
protected void pokreniSimulaciju(JButton gumb)
throws UnknownFunctionException, UnparsableExpressionException {
ACOSimulator simulator = new ACOSimulator();
try {
simulator.koristeciSjeme(Long.parseLong(sjeme.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Sjeme mora biti cijeli broj");
return ;
}
try {
simulator.koristeciBrojMrava(Integer.parseInt(brojMrava.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj mrava mora biti cijeli broj");
return ;
}
List<Par<String, Par<Double, Double>>> gradoviLista = new ArrayList<Par<String, Par<Double, Double>>>();
String[] linije = gradovi.vratiVrijednost().split("\n");
for (int i = 0; i < linije.length; i++) {
// String dijelovi[] = linije[i].split(",");
// int x<SUF>
// int y = Integer.parseInt(dijelovi[1].trim());
// Par<String, Par<Integer, Integer>> grad = new Par<String, Par<Integer, Integer>>(
// dijelovi.length > 2 ? dijelovi[2].trim() : Integer.toString(i + 1),
// new Par<Integer, Integer>(x, y)
// );
String dijelovi[] = linije[i].split(" ");
double x = Double.parseDouble(dijelovi[1].trim());
double y = Double.parseDouble(dijelovi[2].trim());
Par<String, Par<Double, Double>> grad = new Par<String, Par<Double, Double>>(
dijelovi[0].trim(),
new Par<Double, Double>(x, y)
);
gradoviLista.add(grad);
}
simulator.koristeciGradove(gradoviLista);
int odabraniAlgoritam;
if (algoritam.vratiOdabrani().getActionCommand().equals(SIMPLE_ACO)) {
odabraniAlgoritam = ACOSimulator.SIMPLE_ACO_ALGORITAM;
} else if (algoritam.vratiOdabrani().getActionCommand().equals(ANT_SYSTEM)) {
odabraniAlgoritam = ACOSimulator.ANT_SYSTEM_ALGORITAM;
} else {
odabraniAlgoritam = ACOSimulator.MAX_MIN_ANT_SYSTEM_ALGORITM;
}
simulator.koristeciAlgoritam(odabraniAlgoritam);
try {
simulator.koristeciAlfa(Double.parseDouble(alfa.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Alfa mora biti broj");
return ;
}
if (odabraniAlgoritam == ACOSimulator.SIMPLE_ACO_ALGORITAM) {
try {
simulator.koristeciBrojMravaZaAzuriranje(Integer.parseInt(brojMravaAzurira.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj mrava za azuriranje mora biti cijeli broj");
return ;
}
} else {
try {
simulator.koristeciBeta(Double.parseDouble(beta.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Beta mora biti broj");
return ;
}
/*if (odabraniAlgoritam == ACOSimulator.MAX_MIN_ANT_SYSTEM_ALGORITM) {
try {
simulator.koristecKonstantuA(Double.parseDouble(a.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Konstanta A mora biti broj");
return ;
}
try {
simulator.uzBrojKoraka(Integer.parseInt(brojKoraka.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj koraka mora biti cijeli broj");
return ;
}
}*/
}
try {
simulator.koristeciKonstantuIsparavanja(Double.parseDouble(konstantaIsparavanja.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Konstanta isparavanja mora biti broj");
return ;
}
try {
simulator.uzBrojGeneracija(Integer.parseInt(brojGeneracija.vratiVrijednost()));
} catch (NumberFormatException e) {
zapisiUZapisnik("Broj generacija mora biti cijeli broj");
return ;
}
simulator.postaviGUI(this);
simulator.addPropertyChangeListener(new ZaustaviSimulaciju(gumb));
simulator.execute();
this.simulator = simulator;
gumb.setText(ZAUSTAVI);
}
public void iscrtajPutanju(Grad[] najbolji, Grad[] gradovi) { SwingUtilities.invokeLater(new NacrtajPutanju(najbolji, gradovi)); }
public void iscrtajGradove(Grad[] gradovi) { SwingUtilities.invokeLater(new NacrtajGradove(gradovi)); }
}
|
130844_15 | package gmm.web.controller;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import gmm.collections.ArrayList;
import gmm.collections.List;
import gmm.domain.Comment;
import gmm.domain.Label;
import gmm.domain.UniqueObject;
import gmm.domain.User;
import gmm.domain.task.Task;
import gmm.service.ajax.MessageResponse;
import gmm.service.data.DataAccess;
import gmm.service.data.DataChangeEvent.ClientDataChangeEvent;
import gmm.service.users.CurrentUser;
import gmm.web.ControllerArgs;
import gmm.web.FtlTemplateService;
import gmm.web.forms.CommentForm;
import gmm.web.forms.TaskForm;
import gmm.web.sessions.BasicSession;
import gmm.web.sessions.BasicSession.TaskDataResult;
import gmm.web.sessions.TaskSession;
import gmm.web.sessions.tasklist.WorkbenchSession;
/**
* Main task page controller.<br>
* This controller is responsible for most task-CRUD operations requested by "tasks" page:<br>
* Creating, editing or deleting tasks or task comments. State for these operations is managed by
* session object {@link #taskSession}.
*
* @see {@link WorkbenchController}
*
* @author Jan Mothes
*/
@RequestMapping(value={"tasks"})
@PreAuthorize("hasRole('ROLE_USER')")
@Controller
public class TaskController {
@SuppressWarnings("unused")
private final Logger logger = LoggerFactory.getLogger(getClass());
private final BasicSession session;
private final TaskSession taskSession;
private final WorkbenchSession workbench;// TODO remove
private final DataAccess data;
private final FtlTemplateService ftlTemplates;
private final CurrentUser user;
@Autowired
public TaskController(BasicSession session, TaskSession taskSession, WorkbenchSession workbench,
DataAccess data, CurrentUser user, FtlTemplateService ftlTemplates) {
this.session = session;
this.taskSession = taskSession;
this.workbench = workbench;
this.data = data;
this.ftlTemplates = ftlTemplates;
this.user = user;
// taskForm template dependencies
ftlTemplates.registerVariable("users", ()->data.getList(User.class));
ftlTemplates.registerVariable("taskLabels", ()->data.getList(Label.class));
ftlTemplates.registerVariable("taskForm", taskSession::getTaskForm);
ftlTemplates.registerForm("taskForm", taskSession::getTaskForm);
ftlTemplates.registerFtl("all_taskForm", "users", "taskLabels", "taskForm");
}
/**
* Delete Task <br>
* -----------------------------------------------------------------
* @param idLink - identifies the task which will be deleted
*/
@RequestMapping(value="/deleteTask/{idLink}", method = POST)
@ResponseBody
public void handleTasksDelete(@PathVariable String idLink) {
data.remove(UniqueObject.getFromIdLink(data.getList(Task.class), idLink));
}
/**
* Edit Comment <br>
* @param taskIdLink - identifies the task which contains the comment
* @param commentIdLink - identifies the comment to be edited
* @param edited - the edited text of the comment
* -----------------------------------------------------------------
*/
@RequestMapping(value="/editComment/{taskIdLink}/{commentIdLink}", method = POST)
@ResponseBody
public void editComment(
@PathVariable String taskIdLink,
@PathVariable String commentIdLink,
@RequestParam("editedComment") String edited) {
final Task task = UniqueObject.getFromIdLink(data.getList(Task.class), taskIdLink);
final Comment comment = UniqueObject.getFromIdLink(task.getComments(), commentIdLink);
if(comment.getAuthor().getId() == user.get().getId()) {
comment.setText(edited);
}
//TODO: Tasks immutable
data.edit(task);
}
/**
* Create Comment <br>
* -----------------------------------------------------------------
* @param principal - user sending the request
* @param idLink - identifies the task to which the comment will be added
* @param form - object containing all comment information
*/
@RequestMapping(value="/submitComment/{idLink}", method = POST)
@ResponseBody
public void handleTasksComment(
@PathVariable String idLink,
@ModelAttribute("commentForm") CommentForm form) {
final Task task = UniqueObject.getFromIdLink(data.getList(Task.class), idLink);
final Comment comment = new Comment(user.get(), form.getText());
task.getComments().add(comment);
//TODO: Tasks immutable
data.edit(task);
}
/**
* Edit task <br>
* -----------------------------------------------------------------
*/
@RequestMapping(value="/editTask/announce", method = POST)
@ResponseBody
public void editTask(
@RequestParam("idLink") String idLink) {
final Task task = UniqueObject.getFromIdLink(data.getList(Task.class), idLink);
if(task == null) {
throw new IllegalArgumentException("Cannot edit task: idLink does not exist!");
}
taskSession.setupTaskFormNewEdit(task);
}
@RequestMapping(value="/editTask/submit", method = POST)
@ResponseBody
public void editTask(
@ModelAttribute("taskForm") TaskForm form) {
// if tasks can be viewed from any page, edit will be broken because it only works on tasks page
taskSession.executeEdit(form);
}
/**
* Create new task <br>
* -----------------------------------------------------------------
*/
@RequestMapping(value="/createTask", method = POST)
@ResponseBody
public List<MessageResponse> createTask(
@ModelAttribute("taskForm") TaskForm form) {
return taskSession.firstTaskCheck(form);
}
@RequestMapping(value="/createTask/next", method = POST)
@ResponseBody
public List<MessageResponse> createTaskNext(
@RequestParam("operation") String operation) {
return taskSession.getNextTaskCheck(operation, false);
}
/**
* TaskForm <br>
* -----------------------------------------------------------------
*/
@RequestMapping(value = "/resetTaskForm", method = POST)
@ResponseBody
public void resetTaskForm() {
taskSession.setupTaskFormNewTask();
}
@RequestMapping(value = "/saveTaskForm", method = POST)
@ResponseBody
public void saveTaskForm(
@ModelAttribute("taskForm") TaskForm form) {
taskSession.updateTaskForm(form);
}
@RequestMapping(value = "/renderTaskForm", method = GET)
@ResponseBody
public TaskFormResult renderTaskForm(
ModelMap model,
HttpServletRequest request,
HttpServletResponse response) {
final ControllerArgs requestData = new ControllerArgs(model, request, response);
final String taskFormHtml = ftlTemplates.insertFtl("all_taskForm", requestData);
return new TaskFormResult(taskFormHtml, taskSession.getEditedIdLink());
}
public static class TaskFormResult {
public final String editedTaskIdLink;
public final String taskFormHtml;
public TaskFormResult(String taskFormHtml, String editedTaskIdLink) {
this.editedTaskIdLink = editedTaskIdLink;
this.taskFormHtml = taskFormHtml;
}
}
/**
* Default Handler <br>
* -----------------------------------------------------------------
* CLeansup leftover state from previous page and returns new tasks.jsp page.
*/
@RequestMapping(method = GET)
public String send(ModelMap model) {
taskSession.cleanUp();
// TODO remove when converted to ftl to reduce dependencies on Workbench
model.addAttribute("workbench-sortForm", workbench.getSortForm());
return "tasks";
}
/**
* Task data <br>
* -----------------------------------------------------------------
*/
/**
* Get task data for specified ids.
*/
@RequestMapping(value = "/renderTaskData", method = POST)
@ResponseBody
public List<TaskDataResult> renderSelectedTasks(
@RequestParam(value="idLinks[]", required=false) java.util.List<String> idLinks,
ModelMap model,
HttpServletRequest request,
HttpServletResponse response) {
if(idLinks == null) {
return new ArrayList<>(TaskDataResult.class, 0);
} else {
long start = System.currentTimeMillis();
ControllerArgs args = new ControllerArgs(model, request, response);
List<TaskDataResult> result = session.renderTasks(idLinks, data.getList(Task.class), args);
long duration = System.currentTimeMillis() - start;
logger.debug("Time (POST /renderTaskData, " + result.size() + " tasks): " + duration + "ms");
return result;
}
}
/**
* Get data change events.
*/
@RequestMapping(value = "/taskDataEvents", method = GET)
@ResponseBody
public List<ClientDataChangeEvent> syncTaskData() {
return session.retrieveTaskDataEvents();
}
}
| Katharsas/GMM | src/main/java/gmm/web/controller/TaskController.java | 2,674 | /**
* Get data change events.
*/ | block_comment | nl | package gmm.web.controller;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import gmm.collections.ArrayList;
import gmm.collections.List;
import gmm.domain.Comment;
import gmm.domain.Label;
import gmm.domain.UniqueObject;
import gmm.domain.User;
import gmm.domain.task.Task;
import gmm.service.ajax.MessageResponse;
import gmm.service.data.DataAccess;
import gmm.service.data.DataChangeEvent.ClientDataChangeEvent;
import gmm.service.users.CurrentUser;
import gmm.web.ControllerArgs;
import gmm.web.FtlTemplateService;
import gmm.web.forms.CommentForm;
import gmm.web.forms.TaskForm;
import gmm.web.sessions.BasicSession;
import gmm.web.sessions.BasicSession.TaskDataResult;
import gmm.web.sessions.TaskSession;
import gmm.web.sessions.tasklist.WorkbenchSession;
/**
* Main task page controller.<br>
* This controller is responsible for most task-CRUD operations requested by "tasks" page:<br>
* Creating, editing or deleting tasks or task comments. State for these operations is managed by
* session object {@link #taskSession}.
*
* @see {@link WorkbenchController}
*
* @author Jan Mothes
*/
@RequestMapping(value={"tasks"})
@PreAuthorize("hasRole('ROLE_USER')")
@Controller
public class TaskController {
@SuppressWarnings("unused")
private final Logger logger = LoggerFactory.getLogger(getClass());
private final BasicSession session;
private final TaskSession taskSession;
private final WorkbenchSession workbench;// TODO remove
private final DataAccess data;
private final FtlTemplateService ftlTemplates;
private final CurrentUser user;
@Autowired
public TaskController(BasicSession session, TaskSession taskSession, WorkbenchSession workbench,
DataAccess data, CurrentUser user, FtlTemplateService ftlTemplates) {
this.session = session;
this.taskSession = taskSession;
this.workbench = workbench;
this.data = data;
this.ftlTemplates = ftlTemplates;
this.user = user;
// taskForm template dependencies
ftlTemplates.registerVariable("users", ()->data.getList(User.class));
ftlTemplates.registerVariable("taskLabels", ()->data.getList(Label.class));
ftlTemplates.registerVariable("taskForm", taskSession::getTaskForm);
ftlTemplates.registerForm("taskForm", taskSession::getTaskForm);
ftlTemplates.registerFtl("all_taskForm", "users", "taskLabels", "taskForm");
}
/**
* Delete Task <br>
* -----------------------------------------------------------------
* @param idLink - identifies the task which will be deleted
*/
@RequestMapping(value="/deleteTask/{idLink}", method = POST)
@ResponseBody
public void handleTasksDelete(@PathVariable String idLink) {
data.remove(UniqueObject.getFromIdLink(data.getList(Task.class), idLink));
}
/**
* Edit Comment <br>
* @param taskIdLink - identifies the task which contains the comment
* @param commentIdLink - identifies the comment to be edited
* @param edited - the edited text of the comment
* -----------------------------------------------------------------
*/
@RequestMapping(value="/editComment/{taskIdLink}/{commentIdLink}", method = POST)
@ResponseBody
public void editComment(
@PathVariable String taskIdLink,
@PathVariable String commentIdLink,
@RequestParam("editedComment") String edited) {
final Task task = UniqueObject.getFromIdLink(data.getList(Task.class), taskIdLink);
final Comment comment = UniqueObject.getFromIdLink(task.getComments(), commentIdLink);
if(comment.getAuthor().getId() == user.get().getId()) {
comment.setText(edited);
}
//TODO: Tasks immutable
data.edit(task);
}
/**
* Create Comment <br>
* -----------------------------------------------------------------
* @param principal - user sending the request
* @param idLink - identifies the task to which the comment will be added
* @param form - object containing all comment information
*/
@RequestMapping(value="/submitComment/{idLink}", method = POST)
@ResponseBody
public void handleTasksComment(
@PathVariable String idLink,
@ModelAttribute("commentForm") CommentForm form) {
final Task task = UniqueObject.getFromIdLink(data.getList(Task.class), idLink);
final Comment comment = new Comment(user.get(), form.getText());
task.getComments().add(comment);
//TODO: Tasks immutable
data.edit(task);
}
/**
* Edit task <br>
* -----------------------------------------------------------------
*/
@RequestMapping(value="/editTask/announce", method = POST)
@ResponseBody
public void editTask(
@RequestParam("idLink") String idLink) {
final Task task = UniqueObject.getFromIdLink(data.getList(Task.class), idLink);
if(task == null) {
throw new IllegalArgumentException("Cannot edit task: idLink does not exist!");
}
taskSession.setupTaskFormNewEdit(task);
}
@RequestMapping(value="/editTask/submit", method = POST)
@ResponseBody
public void editTask(
@ModelAttribute("taskForm") TaskForm form) {
// if tasks can be viewed from any page, edit will be broken because it only works on tasks page
taskSession.executeEdit(form);
}
/**
* Create new task <br>
* -----------------------------------------------------------------
*/
@RequestMapping(value="/createTask", method = POST)
@ResponseBody
public List<MessageResponse> createTask(
@ModelAttribute("taskForm") TaskForm form) {
return taskSession.firstTaskCheck(form);
}
@RequestMapping(value="/createTask/next", method = POST)
@ResponseBody
public List<MessageResponse> createTaskNext(
@RequestParam("operation") String operation) {
return taskSession.getNextTaskCheck(operation, false);
}
/**
* TaskForm <br>
* -----------------------------------------------------------------
*/
@RequestMapping(value = "/resetTaskForm", method = POST)
@ResponseBody
public void resetTaskForm() {
taskSession.setupTaskFormNewTask();
}
@RequestMapping(value = "/saveTaskForm", method = POST)
@ResponseBody
public void saveTaskForm(
@ModelAttribute("taskForm") TaskForm form) {
taskSession.updateTaskForm(form);
}
@RequestMapping(value = "/renderTaskForm", method = GET)
@ResponseBody
public TaskFormResult renderTaskForm(
ModelMap model,
HttpServletRequest request,
HttpServletResponse response) {
final ControllerArgs requestData = new ControllerArgs(model, request, response);
final String taskFormHtml = ftlTemplates.insertFtl("all_taskForm", requestData);
return new TaskFormResult(taskFormHtml, taskSession.getEditedIdLink());
}
public static class TaskFormResult {
public final String editedTaskIdLink;
public final String taskFormHtml;
public TaskFormResult(String taskFormHtml, String editedTaskIdLink) {
this.editedTaskIdLink = editedTaskIdLink;
this.taskFormHtml = taskFormHtml;
}
}
/**
* Default Handler <br>
* -----------------------------------------------------------------
* CLeansup leftover state from previous page and returns new tasks.jsp page.
*/
@RequestMapping(method = GET)
public String send(ModelMap model) {
taskSession.cleanUp();
// TODO remove when converted to ftl to reduce dependencies on Workbench
model.addAttribute("workbench-sortForm", workbench.getSortForm());
return "tasks";
}
/**
* Task data <br>
* -----------------------------------------------------------------
*/
/**
* Get task data for specified ids.
*/
@RequestMapping(value = "/renderTaskData", method = POST)
@ResponseBody
public List<TaskDataResult> renderSelectedTasks(
@RequestParam(value="idLinks[]", required=false) java.util.List<String> idLinks,
ModelMap model,
HttpServletRequest request,
HttpServletResponse response) {
if(idLinks == null) {
return new ArrayList<>(TaskDataResult.class, 0);
} else {
long start = System.currentTimeMillis();
ControllerArgs args = new ControllerArgs(model, request, response);
List<TaskDataResult> result = session.renderTasks(idLinks, data.getList(Task.class), args);
long duration = System.currentTimeMillis() - start;
logger.debug("Time (POST /renderTaskData, " + result.size() + " tasks): " + duration + "ms");
return result;
}
}
/**
* Get data change<SUF>*/
@RequestMapping(value = "/taskDataEvents", method = GET)
@ResponseBody
public List<ClientDataChangeEvent> syncTaskData() {
return session.retrieveTaskDataEvents();
}
}
|
177540_2 | package VoorraadBeheer.View.LoginView;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class LoginView extends GridPane {
private Text loginText = new Text(" Login ");
private ImageView backgroundImageView = new ImageView("achtergrond foto.png");
private TextField userNameField = new TextField();
private PasswordField passwordField = new PasswordField();
private Button loginButton = new Button("Inloggen");
private Button registerButton = new Button("Nieuwe gebruiker");
private Image icon = new Image("th.jpg"); //om het te kunnen
//gebruiken zonder OP
// voor de achter grond foto en om daarboven te kunnen schrijven ...
public static StackPane stackPaneRoot = new StackPane();
private BorderPane borderPaneRoot = new BorderPane();
private Scene LoginScene = new Scene(stackPaneRoot, 400, 500);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
public LoginView (){
initialiseNodes();
layoutNodes();
}
private void initialiseNodes(){
}
private void layoutNodes(){
loginText.setFont(Font.font("Verdana", 30));
loginText.setFill(Color.LIGHTSALMON);
borderPaneRoot.setTop(loginText);
stackPaneRoot.getChildren().add(borderPaneRoot);
stackPaneRoot.getChildren().add(backgroundImageView);
//this, gidPane
this.setAlignment(Pos.TOP_LEFT);
//Gebruik Hgap en Vgap om de
//ruimte tussen de cellen in te stellen
this.setVgap(10);
this.setPadding(new Insets(200, 25, 25, 25));
userNameField.setPromptText("Gebruikersnaam");
this.add(userNameField, 0, 0);
passwordField.setPromptText("Wachtwoord");
this.add(passwordField, 0, 1);
this.add(loginButton, 0, 2);
this.add(registerButton, 1, 2);
// Voeg de GridPane toe aan de StackPane
stackPaneRoot.getChildren().add(this);
// Stel de titel en de inhoud van de alert in voor de knop niuewe gebruiker
alert.setTitle("Nieuwe gebruiker");
//Door null in te stellen, verwijder je de standaard kopregel die bij bepaalde Alert-typen wordt weergegeven.
alert.setHeaderText(null);
// die werkt momenteel niet.
alert.setContentText("Je verzoek is ingediend voor gebruiker: " + getUserNameField().getText());
}
public Text getLoginText() {
return loginText;
}
public TextField getUserNameField() {
return userNameField;
}
public PasswordField getPasswordField() {
return passwordField;
}
public Button getLoginButton() {
return loginButton;
}
public Button getRegisterButton() {
return registerButton;
}
public Alert getAlert() {
return alert;
}
public Image getIcon() {
return icon;
}
public Scene getLoginScene() {
return LoginScene;
}
}
| Keanu-VW/VoorraadbeheerMedicatie | src/VoorraadBeheer/View/LoginView/LoginView.java | 1,001 | // voor de achter grond foto en om daarboven te kunnen schrijven ... | line_comment | nl | package VoorraadBeheer.View.LoginView;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class LoginView extends GridPane {
private Text loginText = new Text(" Login ");
private ImageView backgroundImageView = new ImageView("achtergrond foto.png");
private TextField userNameField = new TextField();
private PasswordField passwordField = new PasswordField();
private Button loginButton = new Button("Inloggen");
private Button registerButton = new Button("Nieuwe gebruiker");
private Image icon = new Image("th.jpg"); //om het te kunnen
//gebruiken zonder OP
// voor de<SUF>
public static StackPane stackPaneRoot = new StackPane();
private BorderPane borderPaneRoot = new BorderPane();
private Scene LoginScene = new Scene(stackPaneRoot, 400, 500);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
public LoginView (){
initialiseNodes();
layoutNodes();
}
private void initialiseNodes(){
}
private void layoutNodes(){
loginText.setFont(Font.font("Verdana", 30));
loginText.setFill(Color.LIGHTSALMON);
borderPaneRoot.setTop(loginText);
stackPaneRoot.getChildren().add(borderPaneRoot);
stackPaneRoot.getChildren().add(backgroundImageView);
//this, gidPane
this.setAlignment(Pos.TOP_LEFT);
//Gebruik Hgap en Vgap om de
//ruimte tussen de cellen in te stellen
this.setVgap(10);
this.setPadding(new Insets(200, 25, 25, 25));
userNameField.setPromptText("Gebruikersnaam");
this.add(userNameField, 0, 0);
passwordField.setPromptText("Wachtwoord");
this.add(passwordField, 0, 1);
this.add(loginButton, 0, 2);
this.add(registerButton, 1, 2);
// Voeg de GridPane toe aan de StackPane
stackPaneRoot.getChildren().add(this);
// Stel de titel en de inhoud van de alert in voor de knop niuewe gebruiker
alert.setTitle("Nieuwe gebruiker");
//Door null in te stellen, verwijder je de standaard kopregel die bij bepaalde Alert-typen wordt weergegeven.
alert.setHeaderText(null);
// die werkt momenteel niet.
alert.setContentText("Je verzoek is ingediend voor gebruiker: " + getUserNameField().getText());
}
public Text getLoginText() {
return loginText;
}
public TextField getUserNameField() {
return userNameField;
}
public PasswordField getPasswordField() {
return passwordField;
}
public Button getLoginButton() {
return loginButton;
}
public Button getRegisterButton() {
return registerButton;
}
public Alert getAlert() {
return alert;
}
public Image getIcon() {
return icon;
}
public Scene getLoginScene() {
return LoginScene;
}
}
|
124743_29 | package com.bai.util;
import static java.lang.Integer.parseInt;
import com.bai.checkers.CheckerManager;
import ghidra.util.exception.InvalidInputException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Configuration class.
*/
public class Config {
/**
* The config parser for headless mode arguments.
*/
public static class HeadlessParser {
private static boolean checkArgument(String optionName, String[] args, int argi)
throws InvalidInputException {
// everything after this requires an argument
if (!optionName.equalsIgnoreCase(args[argi])) {
return false;
}
if (argi + 1 == args.length) {
throw new InvalidInputException(optionName + " requires an argument");
}
return true;
}
private static String[] getSubArguments(String[] args, int argi) {
List<String> subArgs = new LinkedList<>();
int i = argi + 1;
while (i < args.length && !args[i].startsWith("-")) {
subArgs.add(args[i++]);
}
return subArgs.toArray(new String[0]);
}
private static void usage() {
System.out.println("Usage: ");
System.out.println(
"analyzeHeadless <project_location> <project_name[/folder_path]> -import <file>");
System.out.println("-postScript BinAbsInspector.java \"@@<script parameters>\"");
System.out.println("where <script parameters> in following format: ");
System.out.println(" [-K <kElement>]");
System.out.println(" [-callStringK <callStringMaxLen>]");
System.out.println(" [-Z3Timeout <timeout>]");
System.out.println(" [-timeout <timeout>]");
System.out.println(" [-entry <address>]");
System.out.println(" [-externalMap <file>]");
System.out.println(" [-json]");
System.out.println(" [-disableZ3]");
System.out.println(" [-all]");
System.out.println(" [-debug]");
System.out.println(" [-PreserveCalleeSavedReg]");
System.out.println(" [-check \"<cweNo1>[;<cweNo2>...]\"]");
}
public static Config parseConfig(String fullArgs) {
Config config = new Config();
if (fullArgs.isEmpty()) {
return config;
}
if (fullArgs.getBytes()[0] != '@' && fullArgs.getBytes()[1] != '@') {
System.out.println("Wrong parameters: <script parameters> should start with '@@'");
usage();
System.exit(-1);
}
try {
String[] args = fullArgs.substring(2).split(" ");
for (int argi = 0; argi < args.length; argi++) {
String arg = args[argi];
if (checkArgument("-K", args, argi)) {
config.setK(parseInt(args[++argi]));
} else if (checkArgument("-callStringK", args, argi)) {
config.setCallStringK(parseInt(args[++argi]));
} else if (checkArgument("-Z3Timeout", args, argi)) {
config.setZ3TimeOut(parseInt(args[++argi]));
} else if (checkArgument("-timeout", args, argi)) {
config.setTimeout(parseInt(args[++argi]));
} else if (checkArgument("-entry", args, argi)) {
config.setEntryAddress(args[++argi]);
} else if (checkArgument("-externalMap", args, argi)) {
config.setExternalMapPath(args[++argi]);
} else if (arg.equalsIgnoreCase("-json")) {
config.setOutputJson(true);
} else if (arg.equalsIgnoreCase("-disableZ3")) {
config.setEnableZ3(false);
} else if (arg.equalsIgnoreCase("-all")) {
CheckerManager.loadAllCheckers(config);
} else if (arg.equalsIgnoreCase("-debug")) {
config.setDebug(true);
} else if (arg.equalsIgnoreCase("-preserveCalleeSavedReg")) {
config.setPreserveCalleeSavedReg(true);
} else if (checkArgument("-check", args, argi)) {
String[] checkers = getSubArguments(args, argi);
Arrays.stream(checkers)
.filter(CheckerManager::hasChecker)
.forEach(config::addChecker);
argi += checkers.length;
}
}
} catch (InvalidInputException | IllegalArgumentException e) {
System.out.println("Fail to parse config from: \"" + fullArgs + "\"");
usage();
System.exit(-1);
}
System.out.println("Loaded config: " + config);
return config;
}
}
private static final int DEFAULT_Z3_TIMEOUT = 1000; // unit in millisecond
private static final int DEFAULT_CALLSTRING_K = 3;
private static final int DEFAULT_K = 50;
private static final int DEFAULT_TIMEOUT = -1; // unit in second, no timeout by default
private int z3TimeOut;
private boolean isDebug;
private boolean isOutputJson;
@SuppressWarnings("checkstyle:MemberName")
private int K;
private int callStringK;
private List<String> checkers = new ArrayList<>();
private String entryAddress;
private int timeout;
private boolean isEnableZ3;
private String externalMapPath;
private boolean isGUI;
private boolean preserveCalleeSavedReg;
// for tactic tuning, see:
// http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm
private List<String> z3Tactics = new ArrayList<>();
public Config() {
// default config
this.callStringK = DEFAULT_CALLSTRING_K;
this.K = DEFAULT_K;
this.isDebug = false;
this.isOutputJson = false;
this.z3TimeOut = DEFAULT_Z3_TIMEOUT; // ms
this.timeout = DEFAULT_TIMEOUT;
this.entryAddress = null;
this.isEnableZ3 = true;
this.externalMapPath = null;
this.preserveCalleeSavedReg = false;
}
/**
* Get the timeout (millisecond) for z3 constraint solving.
* @return the timeout (millisecond).
*/
public int getZ3TimeOut() {
return z3TimeOut;
}
/**
* Set the timeout (millisecond) for z3 constraint solving.
* @param z3TimeOut the timeout (millisecond).
*/
public void setZ3TimeOut(int z3TimeOut) {
this.z3TimeOut = z3TimeOut;
}
/**
* Get a list of z3 tactic names.
* @return the list of z3 tactic names.
*/
public List<String> getZ3Tactics() {
return z3Tactics;
}
/**
* Checks if in debug config.
* @return true if in debug config, false otherwise.
*/
public boolean isDebug() {
return isDebug;
}
/**
* Set debug config.
* @param debug in debug config or not.
*/
public void setDebug(boolean debug) {
this.isDebug = debug;
}
/**
* Check if using json output.
* @return ture if using json output, false otherwise.
*/
public boolean isOutputJson() {
return isOutputJson;
}
/**
* Set json output
* @param isOutputJson use json format output or not.
*/
public void setOutputJson(boolean isOutputJson) {
this.isOutputJson = isOutputJson;
}
/**
* Get the K parameter.
* @return the K parameter.
*/
public int getK() {
return K;
}
/**
* Set the K parameter.
* @param k the K parameter.
*/
public void setK(int k) {
K = k;
}
/**
* Get the call string max length: K.
* @return the call string k.
*/
public int getCallStringK() {
return callStringK;
}
/**
* Set the call string max length: K.
* @param callStringK the call string k.
*/
public void setCallStringK(int callStringK) {
this.callStringK = callStringK;
}
/**
* Get a list of checker names to run.
* @return a list of checker names.
*/
public List<String> getCheckers() {
return checkers;
}
/**
* Add a checker to run.
* @param name the checker name.
*/
public void addChecker(String name) {
checkers.add(name);
}
/**
* Clear all checkers config.
*/
public void clearCheckers() {
checkers.clear();
}
/**
* Get the analysis timeout (in second).
* @return the analysis timout (in second).
*/
public int getTimeout() {
return timeout;
}
/**
* Set the analysis timeout (in second).
* @param timeout the analysis timout (in second).
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* Get the entry address string.
* @return the entry address string.
*/
public String getEntryAddress() {
return entryAddress;
}
/**
* Set the entry address, accept format of decimal or hexadecimal.
* @param entryAddress the entry address.
*/
public void setEntryAddress(String entryAddress) {
this.entryAddress = entryAddress;
}
/**
* Checks if enable z3 constraint solving.
* @return true if enabled, false otherwise.
*/
public boolean isEnableZ3() {
return isEnableZ3;
}
/**
* Enable z3 config.
* @param enableZ3 enable or not.
*/
public void setEnableZ3(boolean enableZ3) {
isEnableZ3 = enableZ3;
}
/**
* Get the path of external map config json file.
* @return the file path.
*/
public String getExternalMapPath() {
return externalMapPath;
}
/**
* Set the path of external map config json file.
* @param externalMapPath the file path.
*/
public void setExternalMapPath(String externalMapPath) {
this.externalMapPath = externalMapPath;
}
/**
* Checks if running in GUI mode.
* @return true if in GUI mode, false otherwise.
*/
public boolean isGUI() {
return isGUI;
}
/**
* @hidden
* @param isGUI
*/
public void setGUI(boolean isGUI) {
this.isGUI = isGUI;
}
/**
* Preserve the callee saved registers.
* @param preserveCalleeSavedReg preserve or not.
*/
public void setPreserveCalleeSavedReg(boolean preserveCalleeSavedReg) {
this.preserveCalleeSavedReg = preserveCalleeSavedReg;
}
/**
* Get if the callee saved registers are preserved.
* @return true if preserved, false otherwise.
*/
public boolean getPreserveCalleeSavedReg() {
return preserveCalleeSavedReg;
}
@Override
public String toString() {
return "Config{"
+ "z3TimeOut=" + z3TimeOut
+ ", isDebug=" + isDebug
+ ", isOutputJson=" + isOutputJson
+ ", K=" + K
+ ", callStringK=" + callStringK
+ ", checkers=" + checkers
+ ", entryAddress='" + entryAddress + '\''
+ ", timeout=" + timeout
+ ", isEnableZ3=" + isEnableZ3
+ ", z3Tactics=" + z3Tactics
+ ", externalMapPath=" + externalMapPath
+ '}';
}
}
| KeenSecurityLab/BinAbsInspector | src/main/java/com/bai/util/Config.java | 3,334 | /**
* @hidden
* @param isGUI
*/ | block_comment | nl | package com.bai.util;
import static java.lang.Integer.parseInt;
import com.bai.checkers.CheckerManager;
import ghidra.util.exception.InvalidInputException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Configuration class.
*/
public class Config {
/**
* The config parser for headless mode arguments.
*/
public static class HeadlessParser {
private static boolean checkArgument(String optionName, String[] args, int argi)
throws InvalidInputException {
// everything after this requires an argument
if (!optionName.equalsIgnoreCase(args[argi])) {
return false;
}
if (argi + 1 == args.length) {
throw new InvalidInputException(optionName + " requires an argument");
}
return true;
}
private static String[] getSubArguments(String[] args, int argi) {
List<String> subArgs = new LinkedList<>();
int i = argi + 1;
while (i < args.length && !args[i].startsWith("-")) {
subArgs.add(args[i++]);
}
return subArgs.toArray(new String[0]);
}
private static void usage() {
System.out.println("Usage: ");
System.out.println(
"analyzeHeadless <project_location> <project_name[/folder_path]> -import <file>");
System.out.println("-postScript BinAbsInspector.java \"@@<script parameters>\"");
System.out.println("where <script parameters> in following format: ");
System.out.println(" [-K <kElement>]");
System.out.println(" [-callStringK <callStringMaxLen>]");
System.out.println(" [-Z3Timeout <timeout>]");
System.out.println(" [-timeout <timeout>]");
System.out.println(" [-entry <address>]");
System.out.println(" [-externalMap <file>]");
System.out.println(" [-json]");
System.out.println(" [-disableZ3]");
System.out.println(" [-all]");
System.out.println(" [-debug]");
System.out.println(" [-PreserveCalleeSavedReg]");
System.out.println(" [-check \"<cweNo1>[;<cweNo2>...]\"]");
}
public static Config parseConfig(String fullArgs) {
Config config = new Config();
if (fullArgs.isEmpty()) {
return config;
}
if (fullArgs.getBytes()[0] != '@' && fullArgs.getBytes()[1] != '@') {
System.out.println("Wrong parameters: <script parameters> should start with '@@'");
usage();
System.exit(-1);
}
try {
String[] args = fullArgs.substring(2).split(" ");
for (int argi = 0; argi < args.length; argi++) {
String arg = args[argi];
if (checkArgument("-K", args, argi)) {
config.setK(parseInt(args[++argi]));
} else if (checkArgument("-callStringK", args, argi)) {
config.setCallStringK(parseInt(args[++argi]));
} else if (checkArgument("-Z3Timeout", args, argi)) {
config.setZ3TimeOut(parseInt(args[++argi]));
} else if (checkArgument("-timeout", args, argi)) {
config.setTimeout(parseInt(args[++argi]));
} else if (checkArgument("-entry", args, argi)) {
config.setEntryAddress(args[++argi]);
} else if (checkArgument("-externalMap", args, argi)) {
config.setExternalMapPath(args[++argi]);
} else if (arg.equalsIgnoreCase("-json")) {
config.setOutputJson(true);
} else if (arg.equalsIgnoreCase("-disableZ3")) {
config.setEnableZ3(false);
} else if (arg.equalsIgnoreCase("-all")) {
CheckerManager.loadAllCheckers(config);
} else if (arg.equalsIgnoreCase("-debug")) {
config.setDebug(true);
} else if (arg.equalsIgnoreCase("-preserveCalleeSavedReg")) {
config.setPreserveCalleeSavedReg(true);
} else if (checkArgument("-check", args, argi)) {
String[] checkers = getSubArguments(args, argi);
Arrays.stream(checkers)
.filter(CheckerManager::hasChecker)
.forEach(config::addChecker);
argi += checkers.length;
}
}
} catch (InvalidInputException | IllegalArgumentException e) {
System.out.println("Fail to parse config from: \"" + fullArgs + "\"");
usage();
System.exit(-1);
}
System.out.println("Loaded config: " + config);
return config;
}
}
private static final int DEFAULT_Z3_TIMEOUT = 1000; // unit in millisecond
private static final int DEFAULT_CALLSTRING_K = 3;
private static final int DEFAULT_K = 50;
private static final int DEFAULT_TIMEOUT = -1; // unit in second, no timeout by default
private int z3TimeOut;
private boolean isDebug;
private boolean isOutputJson;
@SuppressWarnings("checkstyle:MemberName")
private int K;
private int callStringK;
private List<String> checkers = new ArrayList<>();
private String entryAddress;
private int timeout;
private boolean isEnableZ3;
private String externalMapPath;
private boolean isGUI;
private boolean preserveCalleeSavedReg;
// for tactic tuning, see:
// http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm
private List<String> z3Tactics = new ArrayList<>();
public Config() {
// default config
this.callStringK = DEFAULT_CALLSTRING_K;
this.K = DEFAULT_K;
this.isDebug = false;
this.isOutputJson = false;
this.z3TimeOut = DEFAULT_Z3_TIMEOUT; // ms
this.timeout = DEFAULT_TIMEOUT;
this.entryAddress = null;
this.isEnableZ3 = true;
this.externalMapPath = null;
this.preserveCalleeSavedReg = false;
}
/**
* Get the timeout (millisecond) for z3 constraint solving.
* @return the timeout (millisecond).
*/
public int getZ3TimeOut() {
return z3TimeOut;
}
/**
* Set the timeout (millisecond) for z3 constraint solving.
* @param z3TimeOut the timeout (millisecond).
*/
public void setZ3TimeOut(int z3TimeOut) {
this.z3TimeOut = z3TimeOut;
}
/**
* Get a list of z3 tactic names.
* @return the list of z3 tactic names.
*/
public List<String> getZ3Tactics() {
return z3Tactics;
}
/**
* Checks if in debug config.
* @return true if in debug config, false otherwise.
*/
public boolean isDebug() {
return isDebug;
}
/**
* Set debug config.
* @param debug in debug config or not.
*/
public void setDebug(boolean debug) {
this.isDebug = debug;
}
/**
* Check if using json output.
* @return ture if using json output, false otherwise.
*/
public boolean isOutputJson() {
return isOutputJson;
}
/**
* Set json output
* @param isOutputJson use json format output or not.
*/
public void setOutputJson(boolean isOutputJson) {
this.isOutputJson = isOutputJson;
}
/**
* Get the K parameter.
* @return the K parameter.
*/
public int getK() {
return K;
}
/**
* Set the K parameter.
* @param k the K parameter.
*/
public void setK(int k) {
K = k;
}
/**
* Get the call string max length: K.
* @return the call string k.
*/
public int getCallStringK() {
return callStringK;
}
/**
* Set the call string max length: K.
* @param callStringK the call string k.
*/
public void setCallStringK(int callStringK) {
this.callStringK = callStringK;
}
/**
* Get a list of checker names to run.
* @return a list of checker names.
*/
public List<String> getCheckers() {
return checkers;
}
/**
* Add a checker to run.
* @param name the checker name.
*/
public void addChecker(String name) {
checkers.add(name);
}
/**
* Clear all checkers config.
*/
public void clearCheckers() {
checkers.clear();
}
/**
* Get the analysis timeout (in second).
* @return the analysis timout (in second).
*/
public int getTimeout() {
return timeout;
}
/**
* Set the analysis timeout (in second).
* @param timeout the analysis timout (in second).
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* Get the entry address string.
* @return the entry address string.
*/
public String getEntryAddress() {
return entryAddress;
}
/**
* Set the entry address, accept format of decimal or hexadecimal.
* @param entryAddress the entry address.
*/
public void setEntryAddress(String entryAddress) {
this.entryAddress = entryAddress;
}
/**
* Checks if enable z3 constraint solving.
* @return true if enabled, false otherwise.
*/
public boolean isEnableZ3() {
return isEnableZ3;
}
/**
* Enable z3 config.
* @param enableZ3 enable or not.
*/
public void setEnableZ3(boolean enableZ3) {
isEnableZ3 = enableZ3;
}
/**
* Get the path of external map config json file.
* @return the file path.
*/
public String getExternalMapPath() {
return externalMapPath;
}
/**
* Set the path of external map config json file.
* @param externalMapPath the file path.
*/
public void setExternalMapPath(String externalMapPath) {
this.externalMapPath = externalMapPath;
}
/**
* Checks if running in GUI mode.
* @return true if in GUI mode, false otherwise.
*/
public boolean isGUI() {
return isGUI;
}
/**
* @hidden
<SUF>*/
public void setGUI(boolean isGUI) {
this.isGUI = isGUI;
}
/**
* Preserve the callee saved registers.
* @param preserveCalleeSavedReg preserve or not.
*/
public void setPreserveCalleeSavedReg(boolean preserveCalleeSavedReg) {
this.preserveCalleeSavedReg = preserveCalleeSavedReg;
}
/**
* Get if the callee saved registers are preserved.
* @return true if preserved, false otherwise.
*/
public boolean getPreserveCalleeSavedReg() {
return preserveCalleeSavedReg;
}
@Override
public String toString() {
return "Config{"
+ "z3TimeOut=" + z3TimeOut
+ ", isDebug=" + isDebug
+ ", isOutputJson=" + isOutputJson
+ ", K=" + K
+ ", callStringK=" + callStringK
+ ", checkers=" + checkers
+ ", entryAddress='" + entryAddress + '\''
+ ", timeout=" + timeout
+ ", isEnableZ3=" + isEnableZ3
+ ", z3Tactics=" + z3Tactics
+ ", externalMapPath=" + externalMapPath
+ '}';
}
}
|
15798_48 | package codecademyher.gui;
import codecademyher.database.CursusDB;
import codecademyher.database.ModuleDB;
import codecademyher.database.StatistiekDB;
import codecademyher.domain.Cursus;
import codecademyher.domain.Niveau;
import codecademyher.domain.Module;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class CursusView extends View {
// aanmaken van alle nodige databases, een tabel met alle cursus gegevens, en
// een lijst met alle cursus objecten
private final CursusDB cursusdb;
private final TableView cursusTable = new TableView();
private final ObservableList<Cursus> cursus;
private final StatistiekDB sdb;
private final ModuleDB mdb;
// constructormethode van CursusView
public CursusView(ObservableList<Cursus> cursus, CursusDB cdb, StatistiekDB sdb, ModuleDB mdb) {
this.cursus = cursus;
this.cursusdb = cdb;
this.sdb = sdb;
this.mdb = mdb;
TableColumn naamColumn = new TableColumn("Naam");
TableColumn owColumn = new TableColumn("Onderwerp");
TableColumn introColumn = new TableColumn("Introductie Tekst");
TableColumn niveauColumn = new TableColumn("Niveau Aanduiding");
naamColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("naam"));
owColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("onderwerp"));
introColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("introductietekst"));
niveauColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("niveauaanduiding"));
// vullen van de TableView tabel met gegevens
cursusTable.setItems(cursus);
cursusTable.getColumns().addAll(naamColumn, introColumn, owColumn, niveauColumn);
}
// methode die een nieuwe stage returnt naar de GUI klasse, wanneer de gebruiker
// op de cursussen knop drukt
// de gebruiker krijgt deze stage te zien
public Stage getScene() throws SQLException {
Stage window = new Stage();
setTitle(window);
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setSpacing(5);
layout.setMinHeight(200);
layout.setMinWidth(900);
layout.getChildren().add(cursusTable);
// deze labels laten het percentage zien van het aantal cursisten dat de
// cursussen behaald heeft, gefilterd op geslacht
Label percentageBehaaldMannen = new Label(
"Percentage voltooide cursussen mannen: " + sdb.percentageBehaaldeCursussenPerGeslacht("Man") + "%");
Label percentageBehaaldVrouwen = new Label(
"Percentage voltooide cursussen vrouwen: " + sdb.percentageBehaaldeCursussenPerGeslacht("Vrouw") + "%");
layout.getChildren().addAll(percentageBehaaldMannen, percentageBehaaldVrouwen);
// als de gebruiker een cursus selecteert en op deze knop drukt wordt de methode
// amtCertStage aangeroepen
// deze methode geeft een stage terug, deze krijgt de gebruiker te zien
// op deze stage zijn het aantal behaalde certificaten en de aanbevolen
// cursussen voor de cursus te zien
Button amtCert = new Button("Certificaten & Aanbevolen Cursussen");
amtCert.setOnAction((e) -> {
try {
Stage amtCertWindow = amtCertStage(
((Cursus) cursusTable.getSelectionModel().getSelectedItem()).getId());
amtCertWindow.setWidth(500);
amtCertWindow.setHeight(350);
amtCertWindow.show();
} catch (Exception ex) {
nothingSelected().show();
}
});
layout.getChildren().add(amtCert);
HBox cursusButtons = new HBox();
// Error label
Label errorLabel = new Label("");
// CRUD buttons voor cursus
// als de gebruiker op de create button drukt wordt de createCursist methode
// aangeroepen
// deze methode geeft een stage terug en deze wordt getoond aan de gebruiker
Button create = new Button("Create");
create.setOnAction((e) -> {
Stage createWindow = createCursus();
createWindow.setWidth(500);
createWindow.setHeight(350);
createWindow.show();
});
cursusButtons.getChildren().addAll(create);
// als de gebruiker een cursus selecteert uit de tabel en op de delete button
// drukt wordt de cursus uit de cursus database verwijderd
Button delete = new Button("Delete");
delete.setOnAction((e) -> {
try {
Cursus c = (Cursus) cursusTable.getSelectionModel().getSelectedItem();
boolean deleted = cursusdb.deleteCursus(c);
if (!deleted) {
errorLabel.setText("Deletion failed, possible FK constraint");
} else {
errorLabel.setText("");
}
System.out.println(deleted);
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
} catch (Exception ex) {
nothingSelected().show();
}
});
cursusButtons.getChildren().add(delete);
// als de gebruiker een cursus selecteert uit de tabel en op de update button
// drukt wordt de editCursus methode aangeroepen
// deze methode geeft een stage terug en deze wordt getoond aan de gebruiker
Button update = new Button("Update");
update.setOnAction((e) -> {
try {
Stage updateWindow = editCursus((Cursus) cursusTable.getSelectionModel().getSelectedItem());
updateWindow.setWidth(500);
updateWindow.setHeight(350);
updateWindow.show();
} catch (Exception ex) {
nothingSelected().show(); // doesn't work?
}
});
cursusButtons.getChildren().add(update);
// als de gebruiker een cursus uit de tabel selecteert en op de add modules knop
// drukt wordt de addCursusModules methode aangeroepen
// deze geeft een stage terug en deze wordt getoond aan de gebruiker
Button addModules = new Button("Add Modules");
addModules.setOnAction((e) -> {
try {
Stage addModulesWindow = addCursusModules((Cursus) cursusTable.getSelectionModel().getSelectedItem());
addModulesWindow.setWidth(500);
addModulesWindow.setHeight(350);
addModulesWindow.show();
} catch (Exception ex) {
nothingSelected().show(); // doesn't work?
}
});
cursusButtons.getChildren().add(addModules);
// als de gebruiker een cursus selecteert uit de tabel en op de delete modules
// knop drukt wordt de removeCursusModules methode aangeroepen
// deze geeft een stage terug en deze wordt getoond aan de gebruiker
Button removeModules = new Button("Delete Modules");
removeModules.setOnAction((e) -> {
try {
Stage removeModulesWindow = removeCursusModules(
(Cursus) cursusTable.getSelectionModel().getSelectedItem());
removeModulesWindow.setWidth(500);
removeModulesWindow.setHeight(350);
removeModulesWindow.show();
} catch (Exception ex) {
nothingSelected().show();
}
});
cursusButtons.getChildren().add(removeModules);
// als de gebruiker een cursus uit de tabel selecteert en op de voortgang per
// module knop drukt wordt de gemiddeldeCursusVoortgang methode aangeroepen
// deze geeft een stage terug en deze wordt getoond aan de gebruiker
Button gemvoortgang = new Button("Voortgang per module");
gemvoortgang.setOnAction((e) -> {
try {
Stage voortgangModulesWindow = gemiddeldeCursusVoortgang(
(Cursus) cursusTable.getSelectionModel().getSelectedItem());
voortgangModulesWindow.setWidth(500);
voortgangModulesWindow.setHeight(350);
voortgangModulesWindow.show();
} catch (Exception ex) {
nothingSelected().show();
}
});
cursusButtons.getChildren().add(gemvoortgang);
// return knop sluit de stage
Button returnButton = new Button("Return");
returnButton.setOnAction((e) -> {
window.hide();
});
cursusButtons.getChildren().addAll(returnButton, errorLabel);
// Buttons
layout.setSpacing(5);
layout.setPadding(new Insets(5, 5, 5, 5));
cursusButtons.setSpacing(5);
layout.getChildren().add(cursusButtons);
Scene cursusScene = new Scene(layout);
window.setScene(cursusScene);
return window;
}
// methode die alle cursus gegevens verwijderd en opnieuw de getAllCursussen
// methode aanroept in de cursus database
public void refreshCursusTable() {
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
}
// methode returnt een stage
// in deze stage kan de gebruiker de gemiddelde voortgang voor elke module van
// een cursus zien
public Stage gemiddeldeCursusVoortgang(Cursus c) {
Stage window = new Stage();
HBox layout = new HBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
VBox v = new VBox();
// gemiddeldeVoortgangPerModulePerCursus uit de statistieken database wordt
// aangeroepen
HashMap<Integer, Double> voortgang = sdb.gemiddeldeVoortgangPerModulePerCursus(c);
for (Map.Entry<Integer, Double> entry : voortgang.entrySet()) {
Label l = new Label(
mdb.getModuleById(entry.getKey()).toString() + ": " + entry.getValue().toString() + "%");
v.getChildren().add(l);
}
// Return
Button returnButton = new Button("Return");
returnButton.setOnAction((e) -> {
window.hide();
});
v.getChildren().add(returnButton);
layout.getChildren().add(v);
Scene editCursus = new Scene(layout);
window.setScene(editCursus);
return window;
}
// methode return een stage
// in deze stage kan de gebruiker het aantal behaalde certificaten en de
// aanbevolen cursussen voor een cursus zien
public Stage amtCertStage(int cursusId) {
Stage window = new Stage();
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
// methodes uit de statistiek database worden aangeroepen
Label amtCertLabel = new Label("Certificaten: " + sdb.hoeveelCertificatenPerCursus(cursusId));
Label aanbevolen = new Label("Aanbevolen cursussen:");
layout.getChildren().addAll(amtCertLabel, aanbevolen);
ArrayList<Cursus> aanbevolenCursus = sdb.aanbevolenCursussenBijCursus(cursusId);
if (!(aanbevolenCursus.isEmpty())) {
for (Cursus cursus : aanbevolenCursus) {
Label cursusLabel = new Label(cursus.toString());
layout.getChildren().add(cursusLabel);
}
}
Scene amtCertScene = new Scene(layout);
window.setScene(amtCertScene);
return window;
}
// deze methode returnt een stage waarin de gebruiker input kan invullen en een
// nieuwe cursus kan aanmaken
public Stage createCursus() {
Stage window = new Stage();
GridPane layout = new GridPane();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setHgap(10);
layout.setVgap(5);
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
Label cursusLabel = new Label("Create Cursus:");
layout.add(cursusLabel, 0, 0);
Label naamLabel = new Label("Naam");
layout.add(naamLabel, 0, 1);
TextField naamField = new TextField("Naam");
layout.add(naamField, 1, 1);
Label owLabel = new Label("Onderwerp");
layout.add(owLabel, 0, 2);
TextField owField = new TextField("Onderwerp");
layout.add(owField, 1, 2);
Label introLabel = new Label("Introductie Tekst");
layout.add(introLabel, 0, 3);
TextField introField = new TextField("Introductie Tekst");
layout.add(introField, 1, 3);
Label niveauLabel = new Label("Niveau");
layout.add(niveauLabel, 0, 4);
ComboBox niveauField = new ComboBox();
niveauField.getItems().addAll("Beginner", "Gevorderd", "Expert");
layout.add(niveauField, 1, 4);
Button create = new Button("Create");
layout.add(create, 0, 5);
// create button sluit de stage af, en maakt een nieuwe cursus in de cursus
// database aan met de gegevens uit de input velden
create.setOnAction((e) -> {
Cursus newC = new Cursus(
0,
naamField.getText(),
owField.getText(),
introField.getText(),
Niveau.fromString((String) niveauField.getValue()));
cursusdb.addCursus(newC);
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
window.hide();
});
Scene createCursus = new Scene(layout);
window.setScene(createCursus);
return window;
}
// deze methode returnt een stage waarin de gebruiker modules kan toevoegen aan
// een cursus
public Stage addCursusModules(Cursus c) {
Stage window = new Stage();
ScrollPane scroll = new ScrollPane();
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
VBox pm = new VBox();
Label possibleModules = new Label("Beschikbare modules voor de cursus " + c.getNaam() + ": ");
ArrayList<Module> possibleModulesList = mdb.getAllModulesWithoutCursus();
layout.getChildren().add(possibleModules);
for (Module module : possibleModulesList) {
HBox h = new HBox();
Label l = new Label(module.toString());
Button attach = new Button("Attach");
attach.setOnAction((e) -> {
mdb.moduleSetCursus(module.getId(), c.getId());
pm.getChildren().removeAll(h);
});
h.getChildren().addAll(l, attach);
pm.getChildren().add(h);
}
layout.getChildren().add(pm);
scroll.setContent(layout);
Scene editCursusModules = new Scene(scroll);
window.setScene(editCursusModules);
return window;
}
// deze methode returnt een stage waarin de gebruiker modules kan verwijderen
// uit een cursus
public Stage removeCursusModules(Cursus c) {
Stage window = new Stage();
ScrollPane scroll = new ScrollPane();
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
VBox cm = new VBox();
Label courseModules = new Label("Modules in de cursus " + c.getNaam() + ": ");
ArrayList<Module> courseModulesList = mdb.getCourseModules(c.getId());
layout.getChildren().add(courseModules);
for (Module module : courseModulesList) {
HBox h = new HBox();
Label l = new Label(module.toString());
Button detach = new Button("Detach");
detach.setOnAction((e) -> {
mdb.moduleClearCursus(module.getId());
cm.getChildren().removeAll(h);
});
h.getChildren().addAll(l, detach);
cm.getChildren().add(h);
}
layout.getChildren().add(cm);
scroll.setContent(layout);
Scene editCursusModules = new Scene(scroll);
window.setScene(editCursusModules);
return window;
}
// methode returnt een stage waarop de gebruiker gegevens van een cursist kan
// wijzigen
public Stage editCursus(Cursus c) {
Stage window = new Stage();
GridPane layout = new GridPane();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setHgap(10);
layout.setVgap(5);
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
Label cursusLabel = new Label("Update Cursus:");
layout.add(cursusLabel, 0, 0);
Label naamLabel = new Label("Naam");
layout.add(naamLabel, 0, 1);
TextField naamField = new TextField(c.getNaam());
layout.add(naamField, 1, 1);
Label owLabel = new Label("Onderwerp");
layout.add(owLabel, 0, 2);
TextField owField = new TextField(c.getOnderwerp());
layout.add(owField, 1, 2);
Label introLabel = new Label("Introductie Tekst");
layout.add(introLabel, 0, 3);
TextField introField = new TextField(c.getIntroductietekst());
layout.add(introField, 1, 3);
Label niveauLabel = new Label("Niveau (" + c.getNiveauaanduiding().getNiveauNaam() + ")");
layout.add(niveauLabel, 0, 4);
ComboBox niveauField = new ComboBox();
niveauField.getItems().addAll("Beginner", "Gevorderd", "Expert");
layout.add(niveauField, 1, 4);
Button update = new Button("Update");
layout.add(update, 0, 5);
// update button sluit de stage af, en maakt een nieuwe cursist aan en deze
// vervangt de oude cursist in de cursist database
update.setOnAction((e) -> {
Cursus newC = new Cursus(
0,
naamField.getText(),
owField.getText(),
introField.getText(),
Niveau.fromString((String) niveauField.getValue()));
cursusdb.updateCursus(c, newC);
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
window.hide();
});
Scene editCursus = new Scene(layout);
window.setScene(editCursus);
return window;
}
}
| KelvinLai2912/CodeCademyHerkansing | src/main/java/codecademyher/gui/CursusView.java | 5,671 | // methode returnt een stage waarop de gebruiker gegevens van een cursist kan | line_comment | nl | package codecademyher.gui;
import codecademyher.database.CursusDB;
import codecademyher.database.ModuleDB;
import codecademyher.database.StatistiekDB;
import codecademyher.domain.Cursus;
import codecademyher.domain.Niveau;
import codecademyher.domain.Module;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class CursusView extends View {
// aanmaken van alle nodige databases, een tabel met alle cursus gegevens, en
// een lijst met alle cursus objecten
private final CursusDB cursusdb;
private final TableView cursusTable = new TableView();
private final ObservableList<Cursus> cursus;
private final StatistiekDB sdb;
private final ModuleDB mdb;
// constructormethode van CursusView
public CursusView(ObservableList<Cursus> cursus, CursusDB cdb, StatistiekDB sdb, ModuleDB mdb) {
this.cursus = cursus;
this.cursusdb = cdb;
this.sdb = sdb;
this.mdb = mdb;
TableColumn naamColumn = new TableColumn("Naam");
TableColumn owColumn = new TableColumn("Onderwerp");
TableColumn introColumn = new TableColumn("Introductie Tekst");
TableColumn niveauColumn = new TableColumn("Niveau Aanduiding");
naamColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("naam"));
owColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("onderwerp"));
introColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("introductietekst"));
niveauColumn.setCellValueFactory(new PropertyValueFactory<Cursus, String>("niveauaanduiding"));
// vullen van de TableView tabel met gegevens
cursusTable.setItems(cursus);
cursusTable.getColumns().addAll(naamColumn, introColumn, owColumn, niveauColumn);
}
// methode die een nieuwe stage returnt naar de GUI klasse, wanneer de gebruiker
// op de cursussen knop drukt
// de gebruiker krijgt deze stage te zien
public Stage getScene() throws SQLException {
Stage window = new Stage();
setTitle(window);
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setSpacing(5);
layout.setMinHeight(200);
layout.setMinWidth(900);
layout.getChildren().add(cursusTable);
// deze labels laten het percentage zien van het aantal cursisten dat de
// cursussen behaald heeft, gefilterd op geslacht
Label percentageBehaaldMannen = new Label(
"Percentage voltooide cursussen mannen: " + sdb.percentageBehaaldeCursussenPerGeslacht("Man") + "%");
Label percentageBehaaldVrouwen = new Label(
"Percentage voltooide cursussen vrouwen: " + sdb.percentageBehaaldeCursussenPerGeslacht("Vrouw") + "%");
layout.getChildren().addAll(percentageBehaaldMannen, percentageBehaaldVrouwen);
// als de gebruiker een cursus selecteert en op deze knop drukt wordt de methode
// amtCertStage aangeroepen
// deze methode geeft een stage terug, deze krijgt de gebruiker te zien
// op deze stage zijn het aantal behaalde certificaten en de aanbevolen
// cursussen voor de cursus te zien
Button amtCert = new Button("Certificaten & Aanbevolen Cursussen");
amtCert.setOnAction((e) -> {
try {
Stage amtCertWindow = amtCertStage(
((Cursus) cursusTable.getSelectionModel().getSelectedItem()).getId());
amtCertWindow.setWidth(500);
amtCertWindow.setHeight(350);
amtCertWindow.show();
} catch (Exception ex) {
nothingSelected().show();
}
});
layout.getChildren().add(amtCert);
HBox cursusButtons = new HBox();
// Error label
Label errorLabel = new Label("");
// CRUD buttons voor cursus
// als de gebruiker op de create button drukt wordt de createCursist methode
// aangeroepen
// deze methode geeft een stage terug en deze wordt getoond aan de gebruiker
Button create = new Button("Create");
create.setOnAction((e) -> {
Stage createWindow = createCursus();
createWindow.setWidth(500);
createWindow.setHeight(350);
createWindow.show();
});
cursusButtons.getChildren().addAll(create);
// als de gebruiker een cursus selecteert uit de tabel en op de delete button
// drukt wordt de cursus uit de cursus database verwijderd
Button delete = new Button("Delete");
delete.setOnAction((e) -> {
try {
Cursus c = (Cursus) cursusTable.getSelectionModel().getSelectedItem();
boolean deleted = cursusdb.deleteCursus(c);
if (!deleted) {
errorLabel.setText("Deletion failed, possible FK constraint");
} else {
errorLabel.setText("");
}
System.out.println(deleted);
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
} catch (Exception ex) {
nothingSelected().show();
}
});
cursusButtons.getChildren().add(delete);
// als de gebruiker een cursus selecteert uit de tabel en op de update button
// drukt wordt de editCursus methode aangeroepen
// deze methode geeft een stage terug en deze wordt getoond aan de gebruiker
Button update = new Button("Update");
update.setOnAction((e) -> {
try {
Stage updateWindow = editCursus((Cursus) cursusTable.getSelectionModel().getSelectedItem());
updateWindow.setWidth(500);
updateWindow.setHeight(350);
updateWindow.show();
} catch (Exception ex) {
nothingSelected().show(); // doesn't work?
}
});
cursusButtons.getChildren().add(update);
// als de gebruiker een cursus uit de tabel selecteert en op de add modules knop
// drukt wordt de addCursusModules methode aangeroepen
// deze geeft een stage terug en deze wordt getoond aan de gebruiker
Button addModules = new Button("Add Modules");
addModules.setOnAction((e) -> {
try {
Stage addModulesWindow = addCursusModules((Cursus) cursusTable.getSelectionModel().getSelectedItem());
addModulesWindow.setWidth(500);
addModulesWindow.setHeight(350);
addModulesWindow.show();
} catch (Exception ex) {
nothingSelected().show(); // doesn't work?
}
});
cursusButtons.getChildren().add(addModules);
// als de gebruiker een cursus selecteert uit de tabel en op de delete modules
// knop drukt wordt de removeCursusModules methode aangeroepen
// deze geeft een stage terug en deze wordt getoond aan de gebruiker
Button removeModules = new Button("Delete Modules");
removeModules.setOnAction((e) -> {
try {
Stage removeModulesWindow = removeCursusModules(
(Cursus) cursusTable.getSelectionModel().getSelectedItem());
removeModulesWindow.setWidth(500);
removeModulesWindow.setHeight(350);
removeModulesWindow.show();
} catch (Exception ex) {
nothingSelected().show();
}
});
cursusButtons.getChildren().add(removeModules);
// als de gebruiker een cursus uit de tabel selecteert en op de voortgang per
// module knop drukt wordt de gemiddeldeCursusVoortgang methode aangeroepen
// deze geeft een stage terug en deze wordt getoond aan de gebruiker
Button gemvoortgang = new Button("Voortgang per module");
gemvoortgang.setOnAction((e) -> {
try {
Stage voortgangModulesWindow = gemiddeldeCursusVoortgang(
(Cursus) cursusTable.getSelectionModel().getSelectedItem());
voortgangModulesWindow.setWidth(500);
voortgangModulesWindow.setHeight(350);
voortgangModulesWindow.show();
} catch (Exception ex) {
nothingSelected().show();
}
});
cursusButtons.getChildren().add(gemvoortgang);
// return knop sluit de stage
Button returnButton = new Button("Return");
returnButton.setOnAction((e) -> {
window.hide();
});
cursusButtons.getChildren().addAll(returnButton, errorLabel);
// Buttons
layout.setSpacing(5);
layout.setPadding(new Insets(5, 5, 5, 5));
cursusButtons.setSpacing(5);
layout.getChildren().add(cursusButtons);
Scene cursusScene = new Scene(layout);
window.setScene(cursusScene);
return window;
}
// methode die alle cursus gegevens verwijderd en opnieuw de getAllCursussen
// methode aanroept in de cursus database
public void refreshCursusTable() {
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
}
// methode returnt een stage
// in deze stage kan de gebruiker de gemiddelde voortgang voor elke module van
// een cursus zien
public Stage gemiddeldeCursusVoortgang(Cursus c) {
Stage window = new Stage();
HBox layout = new HBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
VBox v = new VBox();
// gemiddeldeVoortgangPerModulePerCursus uit de statistieken database wordt
// aangeroepen
HashMap<Integer, Double> voortgang = sdb.gemiddeldeVoortgangPerModulePerCursus(c);
for (Map.Entry<Integer, Double> entry : voortgang.entrySet()) {
Label l = new Label(
mdb.getModuleById(entry.getKey()).toString() + ": " + entry.getValue().toString() + "%");
v.getChildren().add(l);
}
// Return
Button returnButton = new Button("Return");
returnButton.setOnAction((e) -> {
window.hide();
});
v.getChildren().add(returnButton);
layout.getChildren().add(v);
Scene editCursus = new Scene(layout);
window.setScene(editCursus);
return window;
}
// methode return een stage
// in deze stage kan de gebruiker het aantal behaalde certificaten en de
// aanbevolen cursussen voor een cursus zien
public Stage amtCertStage(int cursusId) {
Stage window = new Stage();
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
// methodes uit de statistiek database worden aangeroepen
Label amtCertLabel = new Label("Certificaten: " + sdb.hoeveelCertificatenPerCursus(cursusId));
Label aanbevolen = new Label("Aanbevolen cursussen:");
layout.getChildren().addAll(amtCertLabel, aanbevolen);
ArrayList<Cursus> aanbevolenCursus = sdb.aanbevolenCursussenBijCursus(cursusId);
if (!(aanbevolenCursus.isEmpty())) {
for (Cursus cursus : aanbevolenCursus) {
Label cursusLabel = new Label(cursus.toString());
layout.getChildren().add(cursusLabel);
}
}
Scene amtCertScene = new Scene(layout);
window.setScene(amtCertScene);
return window;
}
// deze methode returnt een stage waarin de gebruiker input kan invullen en een
// nieuwe cursus kan aanmaken
public Stage createCursus() {
Stage window = new Stage();
GridPane layout = new GridPane();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setHgap(10);
layout.setVgap(5);
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
Label cursusLabel = new Label("Create Cursus:");
layout.add(cursusLabel, 0, 0);
Label naamLabel = new Label("Naam");
layout.add(naamLabel, 0, 1);
TextField naamField = new TextField("Naam");
layout.add(naamField, 1, 1);
Label owLabel = new Label("Onderwerp");
layout.add(owLabel, 0, 2);
TextField owField = new TextField("Onderwerp");
layout.add(owField, 1, 2);
Label introLabel = new Label("Introductie Tekst");
layout.add(introLabel, 0, 3);
TextField introField = new TextField("Introductie Tekst");
layout.add(introField, 1, 3);
Label niveauLabel = new Label("Niveau");
layout.add(niveauLabel, 0, 4);
ComboBox niveauField = new ComboBox();
niveauField.getItems().addAll("Beginner", "Gevorderd", "Expert");
layout.add(niveauField, 1, 4);
Button create = new Button("Create");
layout.add(create, 0, 5);
// create button sluit de stage af, en maakt een nieuwe cursus in de cursus
// database aan met de gegevens uit de input velden
create.setOnAction((e) -> {
Cursus newC = new Cursus(
0,
naamField.getText(),
owField.getText(),
introField.getText(),
Niveau.fromString((String) niveauField.getValue()));
cursusdb.addCursus(newC);
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
window.hide();
});
Scene createCursus = new Scene(layout);
window.setScene(createCursus);
return window;
}
// deze methode returnt een stage waarin de gebruiker modules kan toevoegen aan
// een cursus
public Stage addCursusModules(Cursus c) {
Stage window = new Stage();
ScrollPane scroll = new ScrollPane();
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
VBox pm = new VBox();
Label possibleModules = new Label("Beschikbare modules voor de cursus " + c.getNaam() + ": ");
ArrayList<Module> possibleModulesList = mdb.getAllModulesWithoutCursus();
layout.getChildren().add(possibleModules);
for (Module module : possibleModulesList) {
HBox h = new HBox();
Label l = new Label(module.toString());
Button attach = new Button("Attach");
attach.setOnAction((e) -> {
mdb.moduleSetCursus(module.getId(), c.getId());
pm.getChildren().removeAll(h);
});
h.getChildren().addAll(l, attach);
pm.getChildren().add(h);
}
layout.getChildren().add(pm);
scroll.setContent(layout);
Scene editCursusModules = new Scene(scroll);
window.setScene(editCursusModules);
return window;
}
// deze methode returnt een stage waarin de gebruiker modules kan verwijderen
// uit een cursus
public Stage removeCursusModules(Cursus c) {
Stage window = new Stage();
ScrollPane scroll = new ScrollPane();
VBox layout = new VBox();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
VBox cm = new VBox();
Label courseModules = new Label("Modules in de cursus " + c.getNaam() + ": ");
ArrayList<Module> courseModulesList = mdb.getCourseModules(c.getId());
layout.getChildren().add(courseModules);
for (Module module : courseModulesList) {
HBox h = new HBox();
Label l = new Label(module.toString());
Button detach = new Button("Detach");
detach.setOnAction((e) -> {
mdb.moduleClearCursus(module.getId());
cm.getChildren().removeAll(h);
});
h.getChildren().addAll(l, detach);
cm.getChildren().add(h);
}
layout.getChildren().add(cm);
scroll.setContent(layout);
Scene editCursusModules = new Scene(scroll);
window.setScene(editCursusModules);
return window;
}
// methode returnt<SUF>
// wijzigen
public Stage editCursus(Cursus c) {
Stage window = new Stage();
GridPane layout = new GridPane();
layout.setPadding(new Insets(8, 8, 8, 8));
layout.setHgap(10);
layout.setVgap(5);
layout.setMinHeight(300);
layout.setMinWidth(600);
setTitle(window);
Label cursusLabel = new Label("Update Cursus:");
layout.add(cursusLabel, 0, 0);
Label naamLabel = new Label("Naam");
layout.add(naamLabel, 0, 1);
TextField naamField = new TextField(c.getNaam());
layout.add(naamField, 1, 1);
Label owLabel = new Label("Onderwerp");
layout.add(owLabel, 0, 2);
TextField owField = new TextField(c.getOnderwerp());
layout.add(owField, 1, 2);
Label introLabel = new Label("Introductie Tekst");
layout.add(introLabel, 0, 3);
TextField introField = new TextField(c.getIntroductietekst());
layout.add(introField, 1, 3);
Label niveauLabel = new Label("Niveau (" + c.getNiveauaanduiding().getNiveauNaam() + ")");
layout.add(niveauLabel, 0, 4);
ComboBox niveauField = new ComboBox();
niveauField.getItems().addAll("Beginner", "Gevorderd", "Expert");
layout.add(niveauField, 1, 4);
Button update = new Button("Update");
layout.add(update, 0, 5);
// update button sluit de stage af, en maakt een nieuwe cursist aan en deze
// vervangt de oude cursist in de cursist database
update.setOnAction((e) -> {
Cursus newC = new Cursus(
0,
naamField.getText(),
owField.getText(),
introField.getText(),
Niveau.fromString((String) niveauField.getValue()));
cursusdb.updateCursus(c, newC);
cursus.clear();
cursus.addAll(cursusdb.getAllCursussen());
window.hide();
});
Scene editCursus = new Scene(layout);
window.setScene(editCursus);
return window;
}
}
|
55793_4 | package com.company;
public class Main {
public static void main(String[] args) {
//vraagt alle informatie op circus.
Circus circus = new Circus();
circus.getAlles();
System.out.println("");
//vraagt de voedingschema van grootKooi(Singleton)
voedingSchema.getInstance();
System.out.println("");
//vraag afmetingen van "kleinKooi".
Kooi kooi = new kleinKooi();
System.out.println("klein kooi: "+kooi.lengteCM() +"cm lang, "+kooi.breedteCM()+"cm breed en "+ kooi.lengteCM()+"cm hoog");
System.out.println("");
//haalt personeels gegevens van de kantoorwerknemer.
Personeelslid personeel = new Kantoorwerknemer();
personeel.personeelsBestand();
System.out.println("");
//haalt gegevens van de Buffalo.
Dier dier = new Buffallo();
dier.dierGegevens();
}
}
| KemalUzr/Object-oriented-programming-project | src/com/company/Main.java | 298 | //haalt gegevens van de Buffalo. | line_comment | nl | package com.company;
public class Main {
public static void main(String[] args) {
//vraagt alle informatie op circus.
Circus circus = new Circus();
circus.getAlles();
System.out.println("");
//vraagt de voedingschema van grootKooi(Singleton)
voedingSchema.getInstance();
System.out.println("");
//vraag afmetingen van "kleinKooi".
Kooi kooi = new kleinKooi();
System.out.println("klein kooi: "+kooi.lengteCM() +"cm lang, "+kooi.breedteCM()+"cm breed en "+ kooi.lengteCM()+"cm hoog");
System.out.println("");
//haalt personeels gegevens van de kantoorwerknemer.
Personeelslid personeel = new Kantoorwerknemer();
personeel.personeelsBestand();
System.out.println("");
//haalt gegevens<SUF>
Dier dier = new Buffallo();
dier.dierGegevens();
}
}
|
83214_9 | package program;
import java.io.IOException;
import java.net.URL;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.control.TextArea;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.image.Image ;
import static program.Afname.*;
public class SchrijvenController {
public TextArea test1Field;
public Label testNumber;
public Button checkButton;
public Button playButton;
public Label middleText;
public ImageView endscreenImage;
public int current = 1; //houd bij welke mp3 file gebruikt moet worden
private static SchrijvenController instance;
// ik heb hieronder een private controller gemaakt. Hier door kan er maar 1 instance gemaakt worden
// je vraagt deze dan ook alsvolgt op: SchrijvenController.getInstance();
// je kunt nu niet meer SchrijvenController schrijven = new SchrijvenController();
// Kijk maar naar de if statement hieronder.
// als er al een instance is dan is 'instance == null' false, waardoor hij de zelfde 'return instance' geven.
// Als er geen instance is dus 'instance == nul' is true, dan kun je maar als het ware 1 object aanmaken.
private SchrijvenController(){
//System.out.println("hoi");
}
// ik heb dit weggehaald: static SchrijvenController obj = new SchrijvenController();
public static SchrijvenController getInstance(){
if (instance == null){
instance = new SchrijvenController();
}
return instance;
// dit ook: return obj;
}
public int teller = 2; //
public int count = 0;
//Speelt de mp3 file die is geselecteerd
public void startTest(){
StartToets("Schrijven");
Input input = Afname.opdrachten.get(count);
System.out.println(((SchrijvenInput) input).getMp3());
final URL resource = getClass().getResource("../mp3/" + ((SchrijvenInput) input).getMp3() +".mp3");
final Media media = new Media(resource.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
//Controleerd antwoord
public void checkTest() {
System.out.println("size = " + opdrachten.size());
Input opdracht = Afname.opdrachten.get(count);
String answer = ((SchrijvenInput) opdracht).getAntwoord();
String input = test1Field.getText();
if (count < 2) {
if (input.equals(answer)) {
alertBox(true);
test1Field.clear();
testNumber.setText("Test " + (count + 1));
count++;
} else {
alertBox(false);
}
} else {
done();
}
}
//Eindscherm laten zien voor als de gebruiker alles goed heeft
public void done(){
test1Field.setVisible(false);
playButton.setVisible(false);
checkButton.setVisible(false);
testNumber.setText("Good Job!");
middleText.setText("You have completed your test!");
endscreenImage.setVisible(true);
}
//Alertbox laten zien bij het checken van antwoord
public void alertBox(boolean status){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
if (status == true){
alert.setTitle("Good Job!");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/goodjob.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}else{
alert.setTitle("False answer");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/false.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}
}
public void toHomescreen(ActionEvent event) throws IOException {
Parent tohome = FXMLLoader.load(getClass().getResource("homescreen.fxml"));
Scene homeScene = new Scene(tohome);
//pakt stage informatie
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(homeScene);
window.show();
}
}
| KemalUzr/project-zeroXess | src/program/SchrijvenController.java | 1,323 | //Speelt de mp3 file die is geselecteerd | line_comment | nl | package program;
import java.io.IOException;
import java.net.URL;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.control.TextArea;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.image.Image ;
import static program.Afname.*;
public class SchrijvenController {
public TextArea test1Field;
public Label testNumber;
public Button checkButton;
public Button playButton;
public Label middleText;
public ImageView endscreenImage;
public int current = 1; //houd bij welke mp3 file gebruikt moet worden
private static SchrijvenController instance;
// ik heb hieronder een private controller gemaakt. Hier door kan er maar 1 instance gemaakt worden
// je vraagt deze dan ook alsvolgt op: SchrijvenController.getInstance();
// je kunt nu niet meer SchrijvenController schrijven = new SchrijvenController();
// Kijk maar naar de if statement hieronder.
// als er al een instance is dan is 'instance == null' false, waardoor hij de zelfde 'return instance' geven.
// Als er geen instance is dus 'instance == nul' is true, dan kun je maar als het ware 1 object aanmaken.
private SchrijvenController(){
//System.out.println("hoi");
}
// ik heb dit weggehaald: static SchrijvenController obj = new SchrijvenController();
public static SchrijvenController getInstance(){
if (instance == null){
instance = new SchrijvenController();
}
return instance;
// dit ook: return obj;
}
public int teller = 2; //
public int count = 0;
//Speelt de<SUF>
public void startTest(){
StartToets("Schrijven");
Input input = Afname.opdrachten.get(count);
System.out.println(((SchrijvenInput) input).getMp3());
final URL resource = getClass().getResource("../mp3/" + ((SchrijvenInput) input).getMp3() +".mp3");
final Media media = new Media(resource.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
//Controleerd antwoord
public void checkTest() {
System.out.println("size = " + opdrachten.size());
Input opdracht = Afname.opdrachten.get(count);
String answer = ((SchrijvenInput) opdracht).getAntwoord();
String input = test1Field.getText();
if (count < 2) {
if (input.equals(answer)) {
alertBox(true);
test1Field.clear();
testNumber.setText("Test " + (count + 1));
count++;
} else {
alertBox(false);
}
} else {
done();
}
}
//Eindscherm laten zien voor als de gebruiker alles goed heeft
public void done(){
test1Field.setVisible(false);
playButton.setVisible(false);
checkButton.setVisible(false);
testNumber.setText("Good Job!");
middleText.setText("You have completed your test!");
endscreenImage.setVisible(true);
}
//Alertbox laten zien bij het checken van antwoord
public void alertBox(boolean status){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
if (status == true){
alert.setTitle("Good Job!");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/goodjob.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}else{
alert.setTitle("False answer");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/false.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}
}
public void toHomescreen(ActionEvent event) throws IOException {
Parent tohome = FXMLLoader.load(getClass().getResource("homescreen.fxml"));
Scene homeScene = new Scene(tohome);
//pakt stage informatie
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(homeScene);
window.show();
}
}
|
123475_1 |
public class Punt
{
// implement UML notation
private double x;
private double y;
// constructor
public Punt(double xCoordinaat, double yCoordinaat)
{
x = xCoordinaat;
y = yCoordinaat;
}
// getters,setters
public double getX() {return x;}
public void setX(double x) {this.x = x;}
public double getY() {return y;}
public void setY(double y) {this.y = y;}
public String toString() // override
{
return "<Punt("+x+","+y+")>";
}
public void transleer(double dx, double dy)
{
x += dx;
y += dy;
}
// Euclidean distance between 2 points (kortste weg)
public double afstand(Punt p)
{
// sqrt( (x2-x1)^2 + (y2-y1)^2 )
return Math.sqrt(Math.pow(p.x - this.x,2) + Math.pow(p.y - this.y,2));
}
public boolean equals(Object obj) // override
{
if (obj instanceof Punt) // check if obj is more specifically, a Punt object
{
Punt p = (Punt) obj; // temp Punt object
return this.x==p.x && this.y==p.y;
}
return false; // obj is not Punt type
}
}
| Ketho/misc | edu/TUD/TI1206 OOP/Opdracht 2/Punt.java | 407 | // Euclidean distance between 2 points (kortste weg) | line_comment | nl |
public class Punt
{
// implement UML notation
private double x;
private double y;
// constructor
public Punt(double xCoordinaat, double yCoordinaat)
{
x = xCoordinaat;
y = yCoordinaat;
}
// getters,setters
public double getX() {return x;}
public void setX(double x) {this.x = x;}
public double getY() {return y;}
public void setY(double y) {this.y = y;}
public String toString() // override
{
return "<Punt("+x+","+y+")>";
}
public void transleer(double dx, double dy)
{
x += dx;
y += dy;
}
// Euclidean distance<SUF>
public double afstand(Punt p)
{
// sqrt( (x2-x1)^2 + (y2-y1)^2 )
return Math.sqrt(Math.pow(p.x - this.x,2) + Math.pow(p.y - this.y,2));
}
public boolean equals(Object obj) // override
{
if (obj instanceof Punt) // check if obj is more specifically, a Punt object
{
Punt p = (Punt) obj; // temp Punt object
return this.x==p.x && this.y==p.y;
}
return false; // obj is not Punt type
}
}
|
97038_4 | package com.example.openov.Utilz;
// Dit is de distributable van de database settings, deze dus niet aanpassen.
// Copieeer de inhoud en maak een neiuwe file aan genaamd DbSettings in dezelfde map.
public class DbSettings {
// database host, default is meestal localhost of 127.0.0.1
public static String db_host = "localhost";
// Gebruikersnaam van je database configuratie, meestal root
public static String db_user = "root";
// Wachtwoord van je database configuratie meestal leeg, aanpassen indien nodig.
public static String db_pass = "";
// Naam van de database die je hebt aangemaakt voorbeeld, openov
public static String db_name = "openov";
// 3306 is de standaard database port van xampp mysql, aanpassen indien nodig.
public static int db_port = 3306;
}
| Kevin0532/OVApp | OVApp/src/main/java/com/example/openov/Utilz/DbSettings.java | 241 | // Wachtwoord van je database configuratie meestal leeg, aanpassen indien nodig. | line_comment | nl | package com.example.openov.Utilz;
// Dit is de distributable van de database settings, deze dus niet aanpassen.
// Copieeer de inhoud en maak een neiuwe file aan genaamd DbSettings in dezelfde map.
public class DbSettings {
// database host, default is meestal localhost of 127.0.0.1
public static String db_host = "localhost";
// Gebruikersnaam van je database configuratie, meestal root
public static String db_user = "root";
// Wachtwoord van<SUF>
public static String db_pass = "";
// Naam van de database die je hebt aangemaakt voorbeeld, openov
public static String db_name = "openov";
// 3306 is de standaard database port van xampp mysql, aanpassen indien nodig.
public static int db_port = 3306;
}
|
105198_10 | package be.kevindenys.pocbachelorproef.Tasks;
import android.content.Context;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import be.kevindenys.pocbachelorproef.App;
/**
* Created by Kevin on 7/03/2018.
*/
public class NfcLeesTaak extends AsyncTask<Tag, Void, byte[]> {
private Context context;
// Via onderzoek weten we de sensor byte grote (320) en de block grote (8)
private final int AANTAL_BLOKKEN = 320 / 8;
//byteArray maken om de sensor data in op te slaan
private byte[] sensorInBytes = new byte[320];
private App myApp;
public NfcLeesTaak(Context context, App app) {
this.context = context;
this.myApp = app;
}
@Override
protected byte[] doInBackground(Tag... tags) {
int byteOffset = 2;
byte[] temp;
byte[] block = new byte[320];
// Sensor Tag
Tag tag = tags[0];
// ID van de Sensor tag
final byte[] uid = tag.getId();
// NfcV sensor
NfcV NfcVsensor = NfcV.get(tag);
try {
// connecteren
NfcVsensor.connect();
for (int i = 0; i < AANTAL_BLOKKEN; i++) {
temp = new byte[]{
(byte) 0x60, (byte) 0x20, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) (i & 0x0ff), (byte) (0x00)
};
System.arraycopy(uid, 0, temp, 2, 8);
// Loopen tot we iets ontvangen van de NfcVsensor
while (true) {
try {
block = NfcVsensor.transceive(temp);
break;
} catch (IOException e) {
return null;
}
}
// 2 bytes opschuiven van de block
block = Arrays.copyOfRange(block, byteOffset, block.length);
for (int j = 0; j < 8; j++) {
sensorInBytes[i * 8 + j] = block[j];
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
NfcVsensor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sensorInBytes;
}
// En nu de magic
@Override
protected void onPostExecute(byte[] sensorInBytes) {
super.onPostExecute(sensorInBytes);
// NFC Bytes naar Hex Blocks en toevoegen aan logs
myApp.voegToeAanLog("Blocks", bytesNaarHexBlocks(sensorInBytes));
// Info die we weten gebruiken
// Byte 26 bevat het nummer van de trent block
// Trent block is de block die de actuele glucose weet
// De trent block is de block die ook naar history geschreven zal worden
String recentBlockStartHex = byteToHex(sensorInBytes[26]);
myApp.voegToeAanLog("Overschrijf Index Recent", recentBlockStartHex + " => " + Integer.parseInt(recentBlockStartHex,16));
// De index waar history zijn circle start
String geschiedenisBlockStartHex = byteToHex(sensorInBytes[27]);
myApp.voegToeAanLog("Overschrijf Index Geschiedenis", geschiedenisBlockStartHex + " => " + Integer.parseInt(geschiedenisBlockStartHex,16));
int leeftijd = Integer.parseInt(bytesToHex(new byte[]{sensorInBytes[317], sensorInBytes[316]}),16);
// De sensor leeftijd bevind zich in byte 317 en byte 316
myApp.voegToeAanLog("Leeftijd", Integer.toString(leeftijd));
// De sensor kan 14 dagen gebruikt worden, we kunnen dus berekenen hoelang de sensor nog gebruikt kan worden
myApp.voegToeAanLog("14 dagen in min", Integer.toString(14 * 24 * 60));
// Aantal minuten over
myApp.voegToeAanLog("Tijd over in min", Integer.toString(14 * 24 * 60 - leeftijd) );
// Glucose Ophalen
// Recent blocks
myApp.voegToeAanLog("Recent Blocks", bytesArrayNaarGlucoseBlocks(krijgRecenteData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[26]),16)));
// Recent
myApp.voegToeAanLog("Recent Glucose - gesorteerd", bytesArrayNaarGlucoseLijst(krijgRecenteData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[26]),16)));
// Current
myApp.setCurrentGlucose(Integer.parseInt(getCurrentGlucoseHex(krijgRecenteData(sensorInBytes),Integer.parseInt(byteToHex(sensorInBytes[26]),16)),16));
// Glucose Ophalen
// Geschiedenis blocks
myApp.voegToeAanLog("Geschiedenis Blocks", bytesArrayNaarGlucoseBlocks(krijgGeschiedenisData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[27]),16)));
// Geschiedenis
myApp.voegToeAanLog("Geschiedenis Glucose - gesorteerd", bytesArrayNaarGlucoseLijst(krijgGeschiedenisData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[27]),16)));
// LOG
myApp.updateUi();
}
public ArrayList<String> bytesArrayNaarGlucoseBlocks(byte[] sib, int startIndex){
ArrayList<String> glucoseBlocks = new ArrayList<>();
// Glucose blocks zijn 6 bytes lang
int aantalBlocks = (sib.length / 6);
for (int i = 0; i < aantalBlocks; i++) {
String special = "";
if((i) == startIndex){
special = "!";
}
String block = "[Glucose Block " + special + (i) + special + " ]: " + byteToHex(sib[i*6+0]) + byteToHex(sib[i*6+1])
+ byteToHex(sib[i*6+2]) + byteToHex(sib[i*6+3])
+ byteToHex(sib[i*6+4]) + byteToHex(sib[i*6+5]);
glucoseBlocks.add(block);
}
return glucoseBlocks;
}
public String getCurrentGlucoseHex(byte[] sib, int startIndex){
//Arrays start at 0
startIndex--;
return bytesToHex((new byte[]{sib[(startIndex * 6 + 1)], sib[(startIndex * 6 + 0)]}));
}
public ArrayList<String> bytesArrayNaarGlucoseLijst(byte[] sib, int startIndex){
ArrayList<String> glucoseLijst = new ArrayList<>();
// Glucose blocks zijn 6 bytes lang
int aantalBlocks = (sib.length / 6);
for (int index = 0; index < aantalBlocks; index++) {
int i = startIndex - index - 1;
if (i < 0) i += aantalBlocks;
//Hexadecimale glucose
String glucose = bytesToHex((new byte[]{sib[(i * 6 + 1)], sib[(i * 6 + 0)]}));
// Decimale glucose
int glucoseD = Integer.parseInt(glucose, 16);
glucoseLijst.add("[" + (i) + "]: HEX: " + glucose + " => RAW: " + Integer.toString(glucoseD) + " => " + Double.toString(glucoseD/10));
}
return glucoseLijst;
}
public byte[] krijgRecenteData(byte [] sib){
return Arrays.copyOfRange(sib, 28, 124);
}
public byte[] krijgGeschiedenisData(byte [] sib){
return Arrays.copyOfRange(sib, 124, 315);
}
public List<String> bytesNaarHexBlocks(byte[] sib){
List<String> hexBlocks = new ArrayList<>();
for (int i = 0; i < 320; i += 8) {
// 8 Bytes per block
hexBlocks.add("[BLOCK " + Integer.toString(i / 8, 16) + "]: " + byteToHex(sib[i]) + byteToHex(sib[i+1])
+ byteToHex(sib[i+2]) + byteToHex(sib[i+3])
+ byteToHex(sib[i+4]) + byteToHex(sib[i+5])
+ byteToHex(sib[i+6]) + byteToHex(sib[i+7]));
}
return hexBlocks;
}
// https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
final char[] charArray = "0123456789ABCDEF".toCharArray();
public String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = charArray[v >>> 4];
hexChars[j * 2 + 1] = charArray[v & 0x0F];
}
return new String(hexChars);
}
public String byteToHex(byte byte_) {
char[] hexChars = new char[2];
int v = byte_ & 0xFF;
hexChars[0] = charArray[v >>> 4];
hexChars[1] = charArray[v & 0x0F];
return new String(hexChars);
}
}
| KevinDenys/ProofOfConceptBachelorproef | app/src/main/java/be/kevindenys/pocbachelorproef/Tasks/NfcLeesTaak.java | 2,851 | // Trent block is de block die de actuele glucose weet | line_comment | nl | package be.kevindenys.pocbachelorproef.Tasks;
import android.content.Context;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import be.kevindenys.pocbachelorproef.App;
/**
* Created by Kevin on 7/03/2018.
*/
public class NfcLeesTaak extends AsyncTask<Tag, Void, byte[]> {
private Context context;
// Via onderzoek weten we de sensor byte grote (320) en de block grote (8)
private final int AANTAL_BLOKKEN = 320 / 8;
//byteArray maken om de sensor data in op te slaan
private byte[] sensorInBytes = new byte[320];
private App myApp;
public NfcLeesTaak(Context context, App app) {
this.context = context;
this.myApp = app;
}
@Override
protected byte[] doInBackground(Tag... tags) {
int byteOffset = 2;
byte[] temp;
byte[] block = new byte[320];
// Sensor Tag
Tag tag = tags[0];
// ID van de Sensor tag
final byte[] uid = tag.getId();
// NfcV sensor
NfcV NfcVsensor = NfcV.get(tag);
try {
// connecteren
NfcVsensor.connect();
for (int i = 0; i < AANTAL_BLOKKEN; i++) {
temp = new byte[]{
(byte) 0x60, (byte) 0x20, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) (i & 0x0ff), (byte) (0x00)
};
System.arraycopy(uid, 0, temp, 2, 8);
// Loopen tot we iets ontvangen van de NfcVsensor
while (true) {
try {
block = NfcVsensor.transceive(temp);
break;
} catch (IOException e) {
return null;
}
}
// 2 bytes opschuiven van de block
block = Arrays.copyOfRange(block, byteOffset, block.length);
for (int j = 0; j < 8; j++) {
sensorInBytes[i * 8 + j] = block[j];
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
NfcVsensor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sensorInBytes;
}
// En nu de magic
@Override
protected void onPostExecute(byte[] sensorInBytes) {
super.onPostExecute(sensorInBytes);
// NFC Bytes naar Hex Blocks en toevoegen aan logs
myApp.voegToeAanLog("Blocks", bytesNaarHexBlocks(sensorInBytes));
// Info die we weten gebruiken
// Byte 26 bevat het nummer van de trent block
// Trent block<SUF>
// De trent block is de block die ook naar history geschreven zal worden
String recentBlockStartHex = byteToHex(sensorInBytes[26]);
myApp.voegToeAanLog("Overschrijf Index Recent", recentBlockStartHex + " => " + Integer.parseInt(recentBlockStartHex,16));
// De index waar history zijn circle start
String geschiedenisBlockStartHex = byteToHex(sensorInBytes[27]);
myApp.voegToeAanLog("Overschrijf Index Geschiedenis", geschiedenisBlockStartHex + " => " + Integer.parseInt(geschiedenisBlockStartHex,16));
int leeftijd = Integer.parseInt(bytesToHex(new byte[]{sensorInBytes[317], sensorInBytes[316]}),16);
// De sensor leeftijd bevind zich in byte 317 en byte 316
myApp.voegToeAanLog("Leeftijd", Integer.toString(leeftijd));
// De sensor kan 14 dagen gebruikt worden, we kunnen dus berekenen hoelang de sensor nog gebruikt kan worden
myApp.voegToeAanLog("14 dagen in min", Integer.toString(14 * 24 * 60));
// Aantal minuten over
myApp.voegToeAanLog("Tijd over in min", Integer.toString(14 * 24 * 60 - leeftijd) );
// Glucose Ophalen
// Recent blocks
myApp.voegToeAanLog("Recent Blocks", bytesArrayNaarGlucoseBlocks(krijgRecenteData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[26]),16)));
// Recent
myApp.voegToeAanLog("Recent Glucose - gesorteerd", bytesArrayNaarGlucoseLijst(krijgRecenteData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[26]),16)));
// Current
myApp.setCurrentGlucose(Integer.parseInt(getCurrentGlucoseHex(krijgRecenteData(sensorInBytes),Integer.parseInt(byteToHex(sensorInBytes[26]),16)),16));
// Glucose Ophalen
// Geschiedenis blocks
myApp.voegToeAanLog("Geschiedenis Blocks", bytesArrayNaarGlucoseBlocks(krijgGeschiedenisData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[27]),16)));
// Geschiedenis
myApp.voegToeAanLog("Geschiedenis Glucose - gesorteerd", bytesArrayNaarGlucoseLijst(krijgGeschiedenisData(sensorInBytes), Integer.parseInt(byteToHex(sensorInBytes[27]),16)));
// LOG
myApp.updateUi();
}
public ArrayList<String> bytesArrayNaarGlucoseBlocks(byte[] sib, int startIndex){
ArrayList<String> glucoseBlocks = new ArrayList<>();
// Glucose blocks zijn 6 bytes lang
int aantalBlocks = (sib.length / 6);
for (int i = 0; i < aantalBlocks; i++) {
String special = "";
if((i) == startIndex){
special = "!";
}
String block = "[Glucose Block " + special + (i) + special + " ]: " + byteToHex(sib[i*6+0]) + byteToHex(sib[i*6+1])
+ byteToHex(sib[i*6+2]) + byteToHex(sib[i*6+3])
+ byteToHex(sib[i*6+4]) + byteToHex(sib[i*6+5]);
glucoseBlocks.add(block);
}
return glucoseBlocks;
}
public String getCurrentGlucoseHex(byte[] sib, int startIndex){
//Arrays start at 0
startIndex--;
return bytesToHex((new byte[]{sib[(startIndex * 6 + 1)], sib[(startIndex * 6 + 0)]}));
}
public ArrayList<String> bytesArrayNaarGlucoseLijst(byte[] sib, int startIndex){
ArrayList<String> glucoseLijst = new ArrayList<>();
// Glucose blocks zijn 6 bytes lang
int aantalBlocks = (sib.length / 6);
for (int index = 0; index < aantalBlocks; index++) {
int i = startIndex - index - 1;
if (i < 0) i += aantalBlocks;
//Hexadecimale glucose
String glucose = bytesToHex((new byte[]{sib[(i * 6 + 1)], sib[(i * 6 + 0)]}));
// Decimale glucose
int glucoseD = Integer.parseInt(glucose, 16);
glucoseLijst.add("[" + (i) + "]: HEX: " + glucose + " => RAW: " + Integer.toString(glucoseD) + " => " + Double.toString(glucoseD/10));
}
return glucoseLijst;
}
public byte[] krijgRecenteData(byte [] sib){
return Arrays.copyOfRange(sib, 28, 124);
}
public byte[] krijgGeschiedenisData(byte [] sib){
return Arrays.copyOfRange(sib, 124, 315);
}
public List<String> bytesNaarHexBlocks(byte[] sib){
List<String> hexBlocks = new ArrayList<>();
for (int i = 0; i < 320; i += 8) {
// 8 Bytes per block
hexBlocks.add("[BLOCK " + Integer.toString(i / 8, 16) + "]: " + byteToHex(sib[i]) + byteToHex(sib[i+1])
+ byteToHex(sib[i+2]) + byteToHex(sib[i+3])
+ byteToHex(sib[i+4]) + byteToHex(sib[i+5])
+ byteToHex(sib[i+6]) + byteToHex(sib[i+7]));
}
return hexBlocks;
}
// https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
final char[] charArray = "0123456789ABCDEF".toCharArray();
public String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = charArray[v >>> 4];
hexChars[j * 2 + 1] = charArray[v & 0x0F];
}
return new String(hexChars);
}
public String byteToHex(byte byte_) {
char[] hexChars = new char[2];
int v = byte_ & 0xFF;
hexChars[0] = charArray[v >>> 4];
hexChars[1] = charArray[v & 0x0F];
return new String(hexChars);
}
}
|
12411_4 | package agenda;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.Timer;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.FactoryRegistry;
import javazoom.jl.player.advanced.AdvancedPlayer;
import simulator.World;
public class Simulator extends JPanel
{
File json;
Planner planner;
Font font = new Font("SANS_SERIF", Font.PLAIN, 14);
Font timeFont = new Font("SANS_SERIF", Font.BOLD, 36);
Map<agenda.Stage, Integer> stageMap = new HashMap<>();
World world;
Time tijd;
int uren;
int minuten;
int updatetijd = 1000/30;
ActionListener updateTime;
Timer updateT;
private AdvancedPlayer player;
private int bezoekers;
public Simulator(File json, Planner planner, Map<agenda.Stage, Integer> stageMap, int bezoekers)
{
super(new BorderLayout());
this.json = json;
this.planner = planner;
this.stageMap = stageMap;
this.bezoekers = bezoekers;
world = new World(planner.agenda, stageMap, json, "tileSet\\Tiled2.png", false, false, bezoekers);
ButtonPanel buttonPanel = new ButtonPanel(planner);
add(buttonPanel, BorderLayout.NORTH);
add(new SimulatiePanel(planner), BorderLayout.CENTER);
add(new TimePanel(planner), BorderLayout.SOUTH);
buttonPanel.playMusic("static_data\\music\\music.mp3");
}
class ButtonPanel extends JPanel
{
Planner planner;
ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
ArrayList<Area> plaatjes = new ArrayList<Area>();
ArrayList<Rectangle2D> rechthoek = new ArrayList<Rectangle2D>();
JLabel speed1 = new JLabel("Speed: ");
JLabel speed2 = new JLabel(" min/sec");
JLabel time = new JLabel("09:00");
JTextField speedInvoer = new JTextField("0.0", 3);
JLabel visitors = new JLabel("Bezoekers:");
JTextField visitorsField = new JTextField("1", 2);
JLabel visitors2 = new JLabel(" aantal/min");
boolean plays = false;
boolean musicOn = true;
double oldSpeed = 0.0;
int oldVisitors = 0;
int breedte = 1200;
SpringLayout layout;
public ButtonPanel(Planner planner)
{
super(null);
setPreferredSize(new Dimension(1350, 80));
setBackground(Color.WHITE);
layout = new SpringLayout();
setLayout(layout);
this.planner = planner;
updateTime();
add(speed1);
add(speedInvoer);
add(speed2);
add(time);
add(visitors);
add(visitorsField);
add(visitors2);
speed1.setFont(font);
speed2.setFont(font);
time.setFont(timeFont);
visitors.setFont(font);
visitors2.setFont(font);
layout.putConstraint(SpringLayout.WEST, visitors, 180 , SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, visitors, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, visitorsField, 75, SpringLayout.WEST, visitors);
layout.putConstraint(SpringLayout.NORTH, visitorsField, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, visitors2, 23, SpringLayout.WEST, visitorsField);
layout.putConstraint(SpringLayout.NORTH, visitors2, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, speed1, 80, SpringLayout.WEST, visitors2);
layout.putConstraint(SpringLayout.NORTH, speed1, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, speedInvoer, 45, SpringLayout.WEST, speed1);
layout.putConstraint(SpringLayout.NORTH, speedInvoer, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, speed2, 30, SpringLayout.WEST, speedInvoer);
layout.putConstraint(SpringLayout.NORTH, speed2, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, time, 1050, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, time, 15, SpringLayout.NORTH, this);
File mapmap = new File("static_data/simulator_GUI/");
fillArrayList(mapmap);
fillPlaatjes();
clicked();
}
public void fillArrayList(File file)
{
int teller = 1;
if(file.exists())
{
if (file.isDirectory())
{
File[] files = file.listFiles(); // All files and subdirectories
for (int i = 0; files != null && i < files.length; i++)
{
if(getFileExtension(files[i]).equals("png"))
{
try
{
File chooseImage = new File("static_data/simulator_GUI/" + teller + "-" + ".png");
BufferedImage image = ImageIO.read(chooseImage);
images.add(image);
teller++;
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
}
else
{
//System.out.println("Map bestaat niet");
}
}
public String getFileExtension(File file)
{
String fileName = file.getName();
if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
return fileName.substring(fileName.lastIndexOf(".")+1);
else return "";
}
public void fillPlaatjes()
{
Rectangle2D refresh2D = new Rectangle2D.Double(25 , 10, 50, 50);
Rectangle2D back2D = new Rectangle2D.Double(550 , 10, 50, 50);
Rectangle2D play2D = new Rectangle2D.Double(650 , 10, 50, 50);
Rectangle2D pause2D = new Rectangle2D.Double(750 , 10, 50, 50);
Rectangle2D forward2D = new Rectangle2D.Double(850 , 10, 50, 50);
Rectangle2D music2D = new Rectangle2D.Double(1250 , 10, 50, 50);
Area refresh = new Area(refresh2D);
Area back = new Area(back2D);
Area play = new Area(play2D);
Area pause = new Area(pause2D);
Area forward = new Area(forward2D);
Area music = new Area(music2D);
rechthoek.add(refresh2D);
rechthoek.add(back2D);
rechthoek.add(play2D);
rechthoek.add(pause2D);
rechthoek.add(forward2D);
rechthoek.add(music2D);
plaatjes.add(refresh);
plaatjes.add(back);
plaatjes.add(play);
plaatjes.add(pause);
plaatjes.add(forward);
plaatjes.add(music);
}
public void clicked()
{
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
for(int i = 0; i < plaatjes.size(); i++)
{
if(plaatjes.get(i).contains(e.getPoint()))
{
switch (i)
{
case 0:
musicOn = false;
synchronized(this) {
if(player != null) {
player.stop();
player = null;
}
}
refreshSim();
break;
case 1:
backSim();
break;
case 2:
playSim();
break;
case 3:
pauseSim();
break;
case 4:
forwardSim();
break;
case 5:
if(musicOn){
musicOn = false;
synchronized(this) {
if(player != null) {
player.stop();
player = null;
}
}
}
else{
playMusic("static_data\\music\\music.mp3");
musicOn = true;
}
repaint();
break;
default:
break;
}
}
}
}
});
ActionListener update = new ActionListener()
{
int newVisitors = 0;
double speed = 0.0;
@Override
public void actionPerformed(ActionEvent arg0)
{
if(!speedInvoer.getText().equals(""))
{
speed = Double.parseDouble(speedInvoer.getText());
}
if(!visitorsField.getText().equals(""))
{
newVisitors = Integer.parseInt(visitorsField.getText());
}
if(speed != oldSpeed)
{
double realTimeToSimTime = (speed * 60)/1000;
if(plays)
{
world.setRealTimeToSimTime(realTimeToSimTime);
}
/*
* min /sec
* 60*sec /sec
* 60*sec/1000 / millisec
*/
//min*60/1000
}
if(newVisitors != oldVisitors)
{
if(plays)
{
world.setVisPerMin(newVisitors);
}
}
oldSpeed = speed;
oldVisitors = newVisitors;
}
};
Timer updateTimer = new Timer(50, update);
updateTimer.start();
}
public void updateTime()
{
updateTime = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
tijd = world.getTime();
minuten = tijd.getMinutes();
uren = tijd.getHours();
if(uren > 26 || world.noVisitors()) // wanneer alle bezoekers wegzijn stopt de simulatie of wanneer 3 uur nachts is bereikt
{
//System.out.println("World : " + world + "bezoekers : " + bezoekers);
pauseSim();
world.close();
world = new World(planner.agenda, stageMap, json, "tileSet\\Tiled2.png", false, false, bezoekers);
tijd = world.getTime();
minuten = tijd.getMinutes();
uren = tijd.getHours();
}
if(uren > 23)
{
minuten = tijd.getMinutes();
uren = (tijd.getHours() - 24);
}
String urenS;
if(uren < 10)
{
urenS = "0" + uren;
}
else
{
urenS = "" + uren;
}
String minutenS;
if(minuten < 10)
{
minutenS = "0" + minuten;
}
else
{
minutenS = "" + minuten;
}
time.setText(urenS + ":" + minutenS);
}
};
updateT = new Timer(updatetijd, updateTime);
}
public void refreshSim()
{
pauseSim();
planner.tabbedPane.removeTabAt(2);
planner.tabbedPane.addTab("Simulatie", new SimulatieGUI(planner));
planner.tabbedPane.setSelectedIndex(2);
planner.repaint();
planner.revalidate();
}
public void backSim()
{
tijd = world.getTime();
int h = 9;
int m = tijd.getMinutes();
if(tijd.getHours() != 9)
{
h = tijd.getHours() - 1;
}
world.setTime(h, m);
}
public void playSim()
{
world.setRealTimeToSimTime((Double.parseDouble(speedInvoer.getText())*60)/1000);
//An explanation given for the used formule can be found in this class at line 269
updateT.start();
plays = true;
}
public void pauseSim()
{
world.setRealTimeToSimTime(0.0);
updateT.stop();
plays = false;
}
public void forwardSim()
{
world.setRealTimeToSimTime((90*60)/1000);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D balk = new Rectangle2D.Double(0 , 0, 1328, 75);
g2.draw(balk);
int teller = 0;
for(Rectangle2D image : rechthoek)
{
TexturePaint tp;
if(teller == 5 && musicOn)
tp = new TexturePaint(images.get(teller+1), image);
else
tp = new TexturePaint(images.get(teller), image);
g2.setPaint(tp);
g2.fill(plaatjes.get(teller));
teller++;
}
}
public void playMusic(String filename) {
try {
try {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
player = new AdvancedPlayer(is, FactoryRegistry.systemRegistry().createAudioDevice());
} catch (IOException e) {
//System.out.println("ERROR - Play music");
} catch (JavaLayerException e) {
//System.out.println("ERROR - Play music");
}
Thread playerThread = new Thread() {
public void run() {
try {
player.play(5000);
} catch (JavaLayerException e) {
//System.out.println("ERROR - Play music");
} finally {
if(musicOn)
playMusic("static_data\\music\\music.mp3");
}
}
};
playerThread.start();
} catch (Exception ex) {
//System.out.println("ERROR - Play music");
}
}
}
class SimulatiePanel extends JPanel implements MouseMotionListener, MouseListener
{
Planner planner;
int x = 0;
int y = 0;
int oldX = -1;
int oldY = -1;
float scale = 1;
AffineTransform transform = new AffineTransform();
public SimulatiePanel(Planner planner)
{
super(null);
setPreferredSize(new Dimension(1350, 500));
setBackground(Color.WHITE);
this.planner = planner;
setForeground(Color.BLACK);
addMouseMotionListener(this);
addMouseListener(this);
addMouseWheelListener(new zoomMap());
ActionListener simulate = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
repaint();
}
};
Timer simulateTime = new Timer(1000/30, simulate);
simulateTime.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
AffineTransform oldtransform = g2d.getTransform();
transform = new AffineTransform();
transform.scale(scale, scale);
transform.translate(x, y);
world.inclusiveUpdate(g2d, transform, oldtransform);
}
public void mouseDragged(MouseEvent e) {
x += (-1 * ((oldX - e.getX())) / scale);
y += (-1 * ((oldY - e.getY())) / scale);
oldX = e.getX();
oldY = e.getY();
repaint();
}
class zoomMap implements MouseWheelListener {
float maxScale = 1.20f;
float minScale = 0.50f;
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
double delta = -(0.05f * e.getPreciseWheelRotation());
scale += delta;
if (scale <= minScale) {
scale = minScale;
} else if (scale >= maxScale) {
scale = maxScale;
}
repaint();
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
class TimePanel extends JPanel
{
Planner planner;
JSlider timeSlider;
int oldTime;
JSlider slider;
SpringLayout layout;
public TimePanel(Planner planner)
{
super(null);
layout = new SpringLayout();
setLayout(layout);
setPreferredSize(new Dimension(1350, 80));
setBackground(Color.WHITE);
this.planner = planner;
slider = new JSlider(JSlider.HORIZONTAL, 9, 24, 9);
slider.setBackground(Color.WHITE);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setLabelTable(slider.createStandardLabels(1));
slider.setPreferredSize(new Dimension(1100,50));
add(slider);
slider.setFont(font);
ActionListener update = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(slider.getValue() != oldTime)
{
oldTime = slider.getValue();
uren = oldTime;
minuten = 0;
if(uren != 24)
{
world.setTime(uren, minuten);
}
}
if(uren < 9)
{
slider.setValue(24);
}
else
{
slider.setValue(uren);
}
}
};
Timer updateTime = new Timer(50, update);
updateTime.start();
layout.putConstraint(SpringLayout.WEST, slider, 125 , SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, slider, 25, SpringLayout.NORTH, this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D balk = new Rectangle2D.Double(0 , 0, 1328, 80);
g2.draw(balk);
}
}
}
| Kevintjeb/ProjectA5 | code/agenda/Simulator.java | 6,124 | //System.out.println("World : " + world + "bezoekers : " + bezoekers); | line_comment | nl | package agenda;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.Timer;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.FactoryRegistry;
import javazoom.jl.player.advanced.AdvancedPlayer;
import simulator.World;
public class Simulator extends JPanel
{
File json;
Planner planner;
Font font = new Font("SANS_SERIF", Font.PLAIN, 14);
Font timeFont = new Font("SANS_SERIF", Font.BOLD, 36);
Map<agenda.Stage, Integer> stageMap = new HashMap<>();
World world;
Time tijd;
int uren;
int minuten;
int updatetijd = 1000/30;
ActionListener updateTime;
Timer updateT;
private AdvancedPlayer player;
private int bezoekers;
public Simulator(File json, Planner planner, Map<agenda.Stage, Integer> stageMap, int bezoekers)
{
super(new BorderLayout());
this.json = json;
this.planner = planner;
this.stageMap = stageMap;
this.bezoekers = bezoekers;
world = new World(planner.agenda, stageMap, json, "tileSet\\Tiled2.png", false, false, bezoekers);
ButtonPanel buttonPanel = new ButtonPanel(planner);
add(buttonPanel, BorderLayout.NORTH);
add(new SimulatiePanel(planner), BorderLayout.CENTER);
add(new TimePanel(planner), BorderLayout.SOUTH);
buttonPanel.playMusic("static_data\\music\\music.mp3");
}
class ButtonPanel extends JPanel
{
Planner planner;
ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
ArrayList<Area> plaatjes = new ArrayList<Area>();
ArrayList<Rectangle2D> rechthoek = new ArrayList<Rectangle2D>();
JLabel speed1 = new JLabel("Speed: ");
JLabel speed2 = new JLabel(" min/sec");
JLabel time = new JLabel("09:00");
JTextField speedInvoer = new JTextField("0.0", 3);
JLabel visitors = new JLabel("Bezoekers:");
JTextField visitorsField = new JTextField("1", 2);
JLabel visitors2 = new JLabel(" aantal/min");
boolean plays = false;
boolean musicOn = true;
double oldSpeed = 0.0;
int oldVisitors = 0;
int breedte = 1200;
SpringLayout layout;
public ButtonPanel(Planner planner)
{
super(null);
setPreferredSize(new Dimension(1350, 80));
setBackground(Color.WHITE);
layout = new SpringLayout();
setLayout(layout);
this.planner = planner;
updateTime();
add(speed1);
add(speedInvoer);
add(speed2);
add(time);
add(visitors);
add(visitorsField);
add(visitors2);
speed1.setFont(font);
speed2.setFont(font);
time.setFont(timeFont);
visitors.setFont(font);
visitors2.setFont(font);
layout.putConstraint(SpringLayout.WEST, visitors, 180 , SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, visitors, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, visitorsField, 75, SpringLayout.WEST, visitors);
layout.putConstraint(SpringLayout.NORTH, visitorsField, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, visitors2, 23, SpringLayout.WEST, visitorsField);
layout.putConstraint(SpringLayout.NORTH, visitors2, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, speed1, 80, SpringLayout.WEST, visitors2);
layout.putConstraint(SpringLayout.NORTH, speed1, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, speedInvoer, 45, SpringLayout.WEST, speed1);
layout.putConstraint(SpringLayout.NORTH, speedInvoer, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, speed2, 30, SpringLayout.WEST, speedInvoer);
layout.putConstraint(SpringLayout.NORTH, speed2, 25, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, time, 1050, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, time, 15, SpringLayout.NORTH, this);
File mapmap = new File("static_data/simulator_GUI/");
fillArrayList(mapmap);
fillPlaatjes();
clicked();
}
public void fillArrayList(File file)
{
int teller = 1;
if(file.exists())
{
if (file.isDirectory())
{
File[] files = file.listFiles(); // All files and subdirectories
for (int i = 0; files != null && i < files.length; i++)
{
if(getFileExtension(files[i]).equals("png"))
{
try
{
File chooseImage = new File("static_data/simulator_GUI/" + teller + "-" + ".png");
BufferedImage image = ImageIO.read(chooseImage);
images.add(image);
teller++;
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
}
else
{
//System.out.println("Map bestaat niet");
}
}
public String getFileExtension(File file)
{
String fileName = file.getName();
if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
return fileName.substring(fileName.lastIndexOf(".")+1);
else return "";
}
public void fillPlaatjes()
{
Rectangle2D refresh2D = new Rectangle2D.Double(25 , 10, 50, 50);
Rectangle2D back2D = new Rectangle2D.Double(550 , 10, 50, 50);
Rectangle2D play2D = new Rectangle2D.Double(650 , 10, 50, 50);
Rectangle2D pause2D = new Rectangle2D.Double(750 , 10, 50, 50);
Rectangle2D forward2D = new Rectangle2D.Double(850 , 10, 50, 50);
Rectangle2D music2D = new Rectangle2D.Double(1250 , 10, 50, 50);
Area refresh = new Area(refresh2D);
Area back = new Area(back2D);
Area play = new Area(play2D);
Area pause = new Area(pause2D);
Area forward = new Area(forward2D);
Area music = new Area(music2D);
rechthoek.add(refresh2D);
rechthoek.add(back2D);
rechthoek.add(play2D);
rechthoek.add(pause2D);
rechthoek.add(forward2D);
rechthoek.add(music2D);
plaatjes.add(refresh);
plaatjes.add(back);
plaatjes.add(play);
plaatjes.add(pause);
plaatjes.add(forward);
plaatjes.add(music);
}
public void clicked()
{
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
for(int i = 0; i < plaatjes.size(); i++)
{
if(plaatjes.get(i).contains(e.getPoint()))
{
switch (i)
{
case 0:
musicOn = false;
synchronized(this) {
if(player != null) {
player.stop();
player = null;
}
}
refreshSim();
break;
case 1:
backSim();
break;
case 2:
playSim();
break;
case 3:
pauseSim();
break;
case 4:
forwardSim();
break;
case 5:
if(musicOn){
musicOn = false;
synchronized(this) {
if(player != null) {
player.stop();
player = null;
}
}
}
else{
playMusic("static_data\\music\\music.mp3");
musicOn = true;
}
repaint();
break;
default:
break;
}
}
}
}
});
ActionListener update = new ActionListener()
{
int newVisitors = 0;
double speed = 0.0;
@Override
public void actionPerformed(ActionEvent arg0)
{
if(!speedInvoer.getText().equals(""))
{
speed = Double.parseDouble(speedInvoer.getText());
}
if(!visitorsField.getText().equals(""))
{
newVisitors = Integer.parseInt(visitorsField.getText());
}
if(speed != oldSpeed)
{
double realTimeToSimTime = (speed * 60)/1000;
if(plays)
{
world.setRealTimeToSimTime(realTimeToSimTime);
}
/*
* min /sec
* 60*sec /sec
* 60*sec/1000 / millisec
*/
//min*60/1000
}
if(newVisitors != oldVisitors)
{
if(plays)
{
world.setVisPerMin(newVisitors);
}
}
oldSpeed = speed;
oldVisitors = newVisitors;
}
};
Timer updateTimer = new Timer(50, update);
updateTimer.start();
}
public void updateTime()
{
updateTime = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
tijd = world.getTime();
minuten = tijd.getMinutes();
uren = tijd.getHours();
if(uren > 26 || world.noVisitors()) // wanneer alle bezoekers wegzijn stopt de simulatie of wanneer 3 uur nachts is bereikt
{
//System.out.println("World :<SUF>
pauseSim();
world.close();
world = new World(planner.agenda, stageMap, json, "tileSet\\Tiled2.png", false, false, bezoekers);
tijd = world.getTime();
minuten = tijd.getMinutes();
uren = tijd.getHours();
}
if(uren > 23)
{
minuten = tijd.getMinutes();
uren = (tijd.getHours() - 24);
}
String urenS;
if(uren < 10)
{
urenS = "0" + uren;
}
else
{
urenS = "" + uren;
}
String minutenS;
if(minuten < 10)
{
minutenS = "0" + minuten;
}
else
{
minutenS = "" + minuten;
}
time.setText(urenS + ":" + minutenS);
}
};
updateT = new Timer(updatetijd, updateTime);
}
public void refreshSim()
{
pauseSim();
planner.tabbedPane.removeTabAt(2);
planner.tabbedPane.addTab("Simulatie", new SimulatieGUI(planner));
planner.tabbedPane.setSelectedIndex(2);
planner.repaint();
planner.revalidate();
}
public void backSim()
{
tijd = world.getTime();
int h = 9;
int m = tijd.getMinutes();
if(tijd.getHours() != 9)
{
h = tijd.getHours() - 1;
}
world.setTime(h, m);
}
public void playSim()
{
world.setRealTimeToSimTime((Double.parseDouble(speedInvoer.getText())*60)/1000);
//An explanation given for the used formule can be found in this class at line 269
updateT.start();
plays = true;
}
public void pauseSim()
{
world.setRealTimeToSimTime(0.0);
updateT.stop();
plays = false;
}
public void forwardSim()
{
world.setRealTimeToSimTime((90*60)/1000);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D balk = new Rectangle2D.Double(0 , 0, 1328, 75);
g2.draw(balk);
int teller = 0;
for(Rectangle2D image : rechthoek)
{
TexturePaint tp;
if(teller == 5 && musicOn)
tp = new TexturePaint(images.get(teller+1), image);
else
tp = new TexturePaint(images.get(teller), image);
g2.setPaint(tp);
g2.fill(plaatjes.get(teller));
teller++;
}
}
public void playMusic(String filename) {
try {
try {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
player = new AdvancedPlayer(is, FactoryRegistry.systemRegistry().createAudioDevice());
} catch (IOException e) {
//System.out.println("ERROR - Play music");
} catch (JavaLayerException e) {
//System.out.println("ERROR - Play music");
}
Thread playerThread = new Thread() {
public void run() {
try {
player.play(5000);
} catch (JavaLayerException e) {
//System.out.println("ERROR - Play music");
} finally {
if(musicOn)
playMusic("static_data\\music\\music.mp3");
}
}
};
playerThread.start();
} catch (Exception ex) {
//System.out.println("ERROR - Play music");
}
}
}
class SimulatiePanel extends JPanel implements MouseMotionListener, MouseListener
{
Planner planner;
int x = 0;
int y = 0;
int oldX = -1;
int oldY = -1;
float scale = 1;
AffineTransform transform = new AffineTransform();
public SimulatiePanel(Planner planner)
{
super(null);
setPreferredSize(new Dimension(1350, 500));
setBackground(Color.WHITE);
this.planner = planner;
setForeground(Color.BLACK);
addMouseMotionListener(this);
addMouseListener(this);
addMouseWheelListener(new zoomMap());
ActionListener simulate = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
repaint();
}
};
Timer simulateTime = new Timer(1000/30, simulate);
simulateTime.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
AffineTransform oldtransform = g2d.getTransform();
transform = new AffineTransform();
transform.scale(scale, scale);
transform.translate(x, y);
world.inclusiveUpdate(g2d, transform, oldtransform);
}
public void mouseDragged(MouseEvent e) {
x += (-1 * ((oldX - e.getX())) / scale);
y += (-1 * ((oldY - e.getY())) / scale);
oldX = e.getX();
oldY = e.getY();
repaint();
}
class zoomMap implements MouseWheelListener {
float maxScale = 1.20f;
float minScale = 0.50f;
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
double delta = -(0.05f * e.getPreciseWheelRotation());
scale += delta;
if (scale <= minScale) {
scale = minScale;
} else if (scale >= maxScale) {
scale = maxScale;
}
repaint();
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
class TimePanel extends JPanel
{
Planner planner;
JSlider timeSlider;
int oldTime;
JSlider slider;
SpringLayout layout;
public TimePanel(Planner planner)
{
super(null);
layout = new SpringLayout();
setLayout(layout);
setPreferredSize(new Dimension(1350, 80));
setBackground(Color.WHITE);
this.planner = planner;
slider = new JSlider(JSlider.HORIZONTAL, 9, 24, 9);
slider.setBackground(Color.WHITE);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setLabelTable(slider.createStandardLabels(1));
slider.setPreferredSize(new Dimension(1100,50));
add(slider);
slider.setFont(font);
ActionListener update = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(slider.getValue() != oldTime)
{
oldTime = slider.getValue();
uren = oldTime;
minuten = 0;
if(uren != 24)
{
world.setTime(uren, minuten);
}
}
if(uren < 9)
{
slider.setValue(24);
}
else
{
slider.setValue(uren);
}
}
};
Timer updateTime = new Timer(50, update);
updateTime.start();
layout.putConstraint(SpringLayout.WEST, slider, 125 , SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, slider, 25, SpringLayout.NORTH, this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D balk = new Rectangle2D.Double(0 , 0, 1328, 80);
g2.draw(balk);
}
}
}
|
30670_0 | package regex;
import automata.Automata;
import java.util.*;
/**
* Voorbeeld class voor het representeren van reguliere expressies
*
* @author Kevin & Rick
* @version 1.0
*/
public class RegExp {
Operator operator;
String terminals;
// De mogelijke operatoren voor een reguliere expressie (+, *, |, .)
// Daarnaast ook een operator definitie voor 1 keer repeteren (default)
public enum Operator {
PLUS, STAR, OR, DOT, ONE, LEFTPARENTHESES, RIGHTPARENTHESES
}
RegExp left;
RegExp right;
static final Comparator<String> compareByLength
= (s1, s2) -> {
if (s1.length() == s2.length()) {
return s1.compareTo(s2);
} else {
return s1.length() - s2.length();
}
};
public RegExp() {
operator = Operator.ONE;
terminals = "";
left = null;
right = null;
}
public RegExp(String p) {
operator = Operator.ONE;
terminals = p;
left = null;
right = null;
}
public RegExp(char p) {
operator = Operator.ONE;
terminals = String.valueOf(p);
left = null;
right = null;
}
public RegExp plus() {
RegExp result = new RegExp();
result.operator = Operator.PLUS;
result.left = this;
return result;
}
public RegExp star() {
RegExp result = new RegExp();
result.operator = Operator.STAR;
result.left = this;
return result;
}
public RegExp or(RegExp e2) {
RegExp result = new RegExp();
result.operator = Operator.OR;
result.left = this;
result.right = e2;
return result;
}
public RegExp dot(RegExp e2) {
RegExp result = new RegExp();
result.operator = Operator.DOT;
result.left = this;
result.right = e2;
return result;
}
public SortedSet<String> getLanguage(int maxSteps) {
SortedSet<String> emptyLanguage = new TreeSet<String>(compareByLength);
SortedSet<String> languageResult = new TreeSet<String>(compareByLength);
SortedSet<String> languageLeft, languageRight;
if (maxSteps < 1) return emptyLanguage;
switch (this.operator) {
case ONE: {
languageResult.add(terminals);
}
case OR:
languageLeft = left == null ? emptyLanguage : left.getLanguage(maxSteps - 1);
languageRight = right == null ? emptyLanguage : right.getLanguage(maxSteps - 1);
languageResult.addAll(languageLeft);
languageResult.addAll(languageRight);
break;
case DOT:
languageLeft = left == null ? emptyLanguage : left.getLanguage(maxSteps - 1);
languageRight = right == null ? emptyLanguage : right.getLanguage(maxSteps - 1);
for (String s1 : languageLeft)
for (String s2 : languageRight) {
languageResult.add(s1 + s2);
}
break;
// STAR(*) en PLUS(+) kunnen we bijna op dezelfde manier uitwerken:
case STAR:
case PLUS:
languageLeft = left == null ? emptyLanguage : left.getLanguage(maxSteps - 1);
languageResult.addAll(languageLeft);
for (int i = 1; i < maxSteps; i++) {
HashSet<String> languageTemp = new HashSet<String>(languageResult);
for (String s1 : languageLeft) {
for (String s2 : languageTemp) {
languageResult.add(s1 + s2);
}
}
}
if (this.operator == Operator.STAR) {
languageResult.add("");
}
break;
default:
System.out.println("getLanguage is nog niet gedefinieerd voor de operator: " + this.operator);
break;
}
return languageResult;
}
public boolean equals(RegExp r2) {
Thompson thompson = new Thompson();
Thompson thompson2 = new Thompson();
Automata a1 = thompson.parseAutomata(this);
Automata a2 = thompson2.parseAutomata(r2);
Automata dfa1 = a1.NDFAtoDFA();
Automata dfa2 = a2.NDFAtoDFA();
Automata optA1 = dfa1.brzozowski();
Automata optA2 = dfa2.brzozowski();
Automata NotOptA2 = optA2.denial();
Automata a3 = optA1.and(NotOptA2);
Automata result = a3.brzozowski();
if (result.getFinalStates().size() == 0)
return true;
else
return false;
}
public SortedSet getAcceptedWords() {
Thompson thompson = new Thompson();
Automata automata = thompson.parseAutomata(this).NDFAtoDFA();
return this.getLanguage(automata.getStates().size());
}
public Operator getOperator() {
return operator;
}
}
| Kevintjeb/automata | src/main/java/regex/RegExp.java | 1,463 | /**
* Voorbeeld class voor het representeren van reguliere expressies
*
* @author Kevin & Rick
* @version 1.0
*/ | block_comment | nl | package regex;
import automata.Automata;
import java.util.*;
/**
* Voorbeeld class voor<SUF>*/
public class RegExp {
Operator operator;
String terminals;
// De mogelijke operatoren voor een reguliere expressie (+, *, |, .)
// Daarnaast ook een operator definitie voor 1 keer repeteren (default)
public enum Operator {
PLUS, STAR, OR, DOT, ONE, LEFTPARENTHESES, RIGHTPARENTHESES
}
RegExp left;
RegExp right;
static final Comparator<String> compareByLength
= (s1, s2) -> {
if (s1.length() == s2.length()) {
return s1.compareTo(s2);
} else {
return s1.length() - s2.length();
}
};
public RegExp() {
operator = Operator.ONE;
terminals = "";
left = null;
right = null;
}
public RegExp(String p) {
operator = Operator.ONE;
terminals = p;
left = null;
right = null;
}
public RegExp(char p) {
operator = Operator.ONE;
terminals = String.valueOf(p);
left = null;
right = null;
}
public RegExp plus() {
RegExp result = new RegExp();
result.operator = Operator.PLUS;
result.left = this;
return result;
}
public RegExp star() {
RegExp result = new RegExp();
result.operator = Operator.STAR;
result.left = this;
return result;
}
public RegExp or(RegExp e2) {
RegExp result = new RegExp();
result.operator = Operator.OR;
result.left = this;
result.right = e2;
return result;
}
public RegExp dot(RegExp e2) {
RegExp result = new RegExp();
result.operator = Operator.DOT;
result.left = this;
result.right = e2;
return result;
}
public SortedSet<String> getLanguage(int maxSteps) {
SortedSet<String> emptyLanguage = new TreeSet<String>(compareByLength);
SortedSet<String> languageResult = new TreeSet<String>(compareByLength);
SortedSet<String> languageLeft, languageRight;
if (maxSteps < 1) return emptyLanguage;
switch (this.operator) {
case ONE: {
languageResult.add(terminals);
}
case OR:
languageLeft = left == null ? emptyLanguage : left.getLanguage(maxSteps - 1);
languageRight = right == null ? emptyLanguage : right.getLanguage(maxSteps - 1);
languageResult.addAll(languageLeft);
languageResult.addAll(languageRight);
break;
case DOT:
languageLeft = left == null ? emptyLanguage : left.getLanguage(maxSteps - 1);
languageRight = right == null ? emptyLanguage : right.getLanguage(maxSteps - 1);
for (String s1 : languageLeft)
for (String s2 : languageRight) {
languageResult.add(s1 + s2);
}
break;
// STAR(*) en PLUS(+) kunnen we bijna op dezelfde manier uitwerken:
case STAR:
case PLUS:
languageLeft = left == null ? emptyLanguage : left.getLanguage(maxSteps - 1);
languageResult.addAll(languageLeft);
for (int i = 1; i < maxSteps; i++) {
HashSet<String> languageTemp = new HashSet<String>(languageResult);
for (String s1 : languageLeft) {
for (String s2 : languageTemp) {
languageResult.add(s1 + s2);
}
}
}
if (this.operator == Operator.STAR) {
languageResult.add("");
}
break;
default:
System.out.println("getLanguage is nog niet gedefinieerd voor de operator: " + this.operator);
break;
}
return languageResult;
}
public boolean equals(RegExp r2) {
Thompson thompson = new Thompson();
Thompson thompson2 = new Thompson();
Automata a1 = thompson.parseAutomata(this);
Automata a2 = thompson2.parseAutomata(r2);
Automata dfa1 = a1.NDFAtoDFA();
Automata dfa2 = a2.NDFAtoDFA();
Automata optA1 = dfa1.brzozowski();
Automata optA2 = dfa2.brzozowski();
Automata NotOptA2 = optA2.denial();
Automata a3 = optA1.and(NotOptA2);
Automata result = a3.brzozowski();
if (result.getFinalStates().size() == 0)
return true;
else
return false;
}
public SortedSet getAcceptedWords() {
Thompson thompson = new Thompson();
Automata automata = thompson.parseAutomata(this).NDFAtoDFA();
return this.getLanguage(automata.getStates().size());
}
public Operator getOperator() {
return operator;
}
}
|
62946_5 | package stamboom.domain;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import javafx.collections.FXCollections;
import static javafx.collections.FXCollections.*;
import javafx.collections.ObservableList;
public class Administratie implements Serializable {
//************************datavelden*************************************
private int nextGezinsNr = 0;
private int nextPersNr = 0;
private final List<Persoon> personen;
private final List<Gezin> gezinnen;
private transient ObservableList<Persoon> observablePersonen;
private transient ObservableList<Gezin> observableGezinnen;
private final static long serialVersionUID = -3123920467171138433L;
//***********************constructoren***********************************
/**
* er wordt een administratie gecreeerd met 0 personen en dus 0 gezinnen
* personen en gezinnen die in de toekomst zullen worden gecreeerd, worden
* elk opvolgend genummerd vanaf 1
*/
public Administratie() {
personen = new ArrayList<>();
gezinnen = new ArrayList<>();
observablePersonen = observableList(personen);
observableGezinnen = observableList(gezinnen);
}
//**********************methoden****************************************
/**
* er wordt een persoon met een gegeven geslacht, met als voornamen vnamen,
* achternaam anaam, tussenvoegsel tvoegsel, geboortedatum gebdat,
* geboorteplaats gebplaats en een gegeven ouderlijk gezin gecreeerd; de persoon
* krijgt een uniek nummer toegewezen de persoon is voortaan ook bij het
* ouderlijk gezin bekend. Voor de voornamen, achternaam en gebplaats geldt
* dat de eerste letter naar een hoofdletter en de resterende letters naar
* een kleine letter zijn geconverteerd; het tussenvoegsel is zo nodig in
* zijn geheel geconverteerd naar kleine letters; overbodige spaties zijn
* verwijderd
*
* @param geslacht
* @param vnamen vnamen.length>0; alle strings zijn niet leeg
* @param anaam niet leeg
* @param tvoegsel
* @param gebdat
* @param gebplaats niet leeg
* @param ouderlijkGezin mag de waarde null (=onbekend) hebben
*
* @return als de persoon al bekend was (op basis van combinatie van getNaam(),
* geboorteplaats en geboortedatum), wordt er null geretourneerd, anders de
* nieuwe persoon
*/
public Persoon addPersoon(Geslacht geslacht, String[] vnamen, String anaam,
String tvoegsel, Calendar gebdat,
String gebplaats, Gezin ouderlijkGezin) {
if (vnamen.length == 0) {
throw new IllegalArgumentException("ten minst 1 voornaam");
}
for (String voornaam : vnamen) {
if (voornaam.trim().isEmpty()) {
throw new IllegalArgumentException("lege voornaam is niet toegestaan");
}
}
if (anaam.trim().isEmpty()) {
throw new IllegalArgumentException("lege achternaam is niet toegestaan");
}
if (gebplaats.trim().isEmpty()) {
throw new IllegalArgumentException("lege geboorteplaats is niet toegestaan");
}
nextPersNr++;
Persoon newPersoon = new Persoon(this.nextPersNr, vnamen, anaam, tvoegsel, gebdat, gebplaats, geslacht, ouderlijkGezin);
if (getPersoon(vnamen, anaam, tvoegsel, gebdat, gebplaats) != null) {
return null;
}
observablePersonen.add(newPersoon);
if(ouderlijkGezin != null)
{
newPersoon.getOuderlijkGezin().breidUitMet(newPersoon);
}
return newPersoon;
}
/**
* er wordt, zo mogelijk (zie return) een (kinderloos) ongehuwd gezin met
* ouder1 en ouder2 als ouders gecreeerd; de huwelijks- en scheidingsdatum
* zijn onbekend (null); het gezin krijgt een uniek nummer toegewezen; dit
* gezin wordt ook bij de afzonderlijke ouders geregistreerd;
*
* @param ouder1
* @param ouder2 mag null zijn
*
* @return null als ouder1 = ouder2 of als de volgende voorwaarden worden
* overtreden: 1) een van de ouders is op dit moment getrouwd 2) het koppel
* uit een ongehuwd gezin kan niet tegelijkertijd als koppel bij een ander
* ongehuwd gezin betrokken zijn anders het gewenste gezin
*/
public Gezin addOngehuwdGezin(Persoon ouder1, Persoon ouder2) {
Calendar nu = Calendar.getInstance();
if (ouder1 == ouder2)
{
return null;
}
if(ongehuwdGezinBestaat(ouder1, ouder2))
{
return null;
}
if (ouder1.isGetrouwdOp(nu))
{
return null;
} else if (ouder2 != null && ouder2.isGetrouwdOp(nu))
{
return null;
} else if (ongehuwdGezinBestaat(ouder1, ouder2))
{
return null;
}
nextGezinsNr++;
Gezin gezin = new Gezin(nextGezinsNr, ouder1, ouder2);
observableGezinnen.add(gezin);
ouder1.wordtOuderIn(gezin);
if (ouder2 != null)
{
ouder2.wordtOuderIn(gezin);
}
return gezin;
}
/**
* Als het ouderlijk gezin van persoon nog onbekend is dan wordt persoon een
* kind van ouderlijkGezin en tevens wordt persoon als kind in dat gezin
* geregistreerd; <br>
* Als de ouders bij aanroep al bekend zijn, verandert er
* niets
*
* @param persoon
* @param ouderlijkGezin
*/
public void setOuders(Persoon persoon, Gezin ouderlijkGezin) {
persoon.setOuders(ouderlijkGezin);
}
/**
* als de ouders van dit gezin gehuwd zijn en nog niet gescheiden en datum
* na de huwelijksdatum ligt, wordt dit de scheidingsdatum. Anders gebeurt
* er niets.
*
* @param gezin
* @param datum
* @return true als scheiding geaccepteerd, anders false
*/
public boolean setScheiding(Gezin gezin, Calendar datum) {
return gezin.setScheiding(datum);
}
/**
* registreert het huwelijk, mits gezin nog geen huwelijk is en beide ouders
* op deze datum mogen trouwen (pas op: ook de toekomst kan hierbij een rol
* spelen omdat toekomstige gezinnen eerder zijn geregisteerd)
*
* @param gezin
* @param datum de huwelijksdatum
* @return false als huwelijk niet mocht worden voltrokken, anders true
*/
public boolean setHuwelijk(Gezin gezin, Calendar datum) {
return gezin.setHuwelijk(datum);
}
/**
*
* @param ouder1
* @param ouder2
* @return true als dit koppel (ouder1,ouder2) al een ongehuwd gezin vormt
*/
boolean ongehuwdGezinBestaat(Persoon ouder1, Persoon ouder2) {
return ouder1.heeftOngehuwdGezinMet(ouder2) != null;
}
/**
* als er al een ongehuwd gezin voor dit koppel bestaat, wordt het huwelijk
* voltrokken, anders wordt er zo mogelijk (zie return) een (kinderloos)
* gehuwd gezin met ouder1 en ouder2 als ouders gecreeerd; de
* scheidingsdatum is onbekend (null); het gezin krijgt een uniek nummer
* toegewezen; dit gezin wordt ook bij de afzonderlijke ouders
* geregistreerd;
*
* @param ouder1
* @param ouder2
* @param huwdatum
* @return null als ouder1 = ouder2 of als een van de ouders getrouwd is
* anders het gehuwde gezin
*/
public Gezin addHuwelijk(Persoon ouder1, Persoon ouder2, Calendar huwdatum) {
if (ouder1 == ouder2) {
return null;
}
if (!ouder1.kanTrouwenOp(huwdatum) || !ouder2.kanTrouwenOp(huwdatum)) {
return null;
}
Gezin toeTeVoegenGezin;
boolean alOngehuwdGezin = false;
for (Gezin huidig: observableGezinnen) {
if (huidig.getOuder1() == ouder1 && huidig.getOuder2() == ouder2) {
toeTeVoegenGezin = huidig;
toeTeVoegenGezin.setHuwelijk(huwdatum);
alOngehuwdGezin = true;
return toeTeVoegenGezin;
}
if (huidig.getOuder2() == ouder1 && huidig.getOuder1() == ouder2) {
toeTeVoegenGezin = huidig;
toeTeVoegenGezin.setHuwelijk(huwdatum);
alOngehuwdGezin = true;
return toeTeVoegenGezin;
}
}
if (!alOngehuwdGezin) {
nextGezinsNr++;
toeTeVoegenGezin = new Gezin(nextGezinsNr, ouder1, ouder2);
ouder1.wordtOuderIn(toeTeVoegenGezin);
ouder2.wordtOuderIn(toeTeVoegenGezin);
if (toeTeVoegenGezin.setHuwelijk(huwdatum)) {
observableGezinnen.add(toeTeVoegenGezin);
return toeTeVoegenGezin;
}
else
{
return null;
}
}
else
{
return null;
}
}
/**
*
* @return het aantal geregistreerde personen
*/
public int aantalGeregistreerdePersonen() {
return nextPersNr ;
}
/**
*
* @return het aantal geregistreerde gezinnen
*/
public int aantalGeregistreerdeGezinnen() {
return nextGezinsNr ;
}
/**
*
* @param nr
* @return de persoon met nummer nr, als die niet bekend is wordt er null
* geretourneerd
*/
public Persoon getPersoon(int nr) {
for (Persoon huidig: observablePersonen) {
if (huidig.getNr() == nr) {
return huidig;
}
}
return null;
}
/**
* @param achternaam
* @return alle personen met een achternaam gelijk aan de meegegeven
* achternaam (ongeacht hoofd- en kleine letters)
*/
public ArrayList<Persoon> getPersonenMetAchternaam(String achternaam) {
ArrayList<Persoon> gevondenPersonen = new ArrayList<>();
for (Persoon huidig: observablePersonen) {
if (huidig.getAchternaam().toLowerCase().equals(achternaam.toLowerCase())) {
gevondenPersonen.add(huidig);
}
}
return gevondenPersonen;
}
/**
*
* @return de geregistreerde personen
*/
public ObservableList<Persoon> getPersonen() {
return (ObservableList<Persoon>)FXCollections.unmodifiableObservableList(observablePersonen);
}
/**
*
* @param vnamen
* @param anaam
* @param tvoegsel
* @param gebdat
* @param gebplaats
* @return de persoon met dezelfde initialen, tussenvoegsel, achternaam,
* geboortedatum en -plaats mits bekend (ongeacht hoofd- en kleine letters),
* anders null
*/
public Persoon getPersoon(String[] vnamen, String anaam, String tvoegsel,
Calendar gebdat, String gebplaats) {
ArrayList<Persoon> p = new ArrayList<>();
for (Persoon huidig: observablePersonen) {
String initialen = "";
for (String voornaam:vnamen) {
initialen += voornaam.substring(0, 1) + ".";
}
if (gebplaats.toLowerCase().equals(huidig.getGebPlaats().toLowerCase())
&& gebdat.equals(huidig.getGebDat())
&& tvoegsel.toLowerCase().equals(huidig.getTussenvoegsel().toLowerCase())
&& anaam.toLowerCase().equals(huidig.getAchternaam().toLowerCase())
&& initialen.toLowerCase().equals(huidig.getInitialen().toLowerCase())) {
p.add(huidig);
return p.get(0);
}
}
return null;
}
/**
*
* @return de geregistreerde gezinnen
*/
public ObservableList<Gezin> getGezinnen() {
return (ObservableList<Gezin>)FXCollections.unmodifiableObservableList(observableGezinnen);
}
/**
*
* @param gezinsNr
* @return het gezin met nummer nr. Als dat niet bekend is wordt er null
* geretourneerd
*/
public Gezin getGezin(int gezinsNr) {
// aanname: er worden geen gezinnen verwijderd
if (1 <= gezinsNr && 1 <= observableGezinnen.size()) {
return observableGezinnen.get(gezinsNr - 1);
}
return null;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException
{
ois.defaultReadObject();
observablePersonen = observableList(personen);
observableGezinnen = observableList(gezinnen);
}
public void addDBPersoon (Persoon p)
{
observablePersonen.add(p);
}
}
| KevinvdBurg/C2J31 | Stamboom (start)/src/stamboom/domain/Administratie.java | 4,250 | /**
* registreert het huwelijk, mits gezin nog geen huwelijk is en beide ouders
* op deze datum mogen trouwen (pas op: ook de toekomst kan hierbij een rol
* spelen omdat toekomstige gezinnen eerder zijn geregisteerd)
*
* @param gezin
* @param datum de huwelijksdatum
* @return false als huwelijk niet mocht worden voltrokken, anders true
*/ | block_comment | nl | package stamboom.domain;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import javafx.collections.FXCollections;
import static javafx.collections.FXCollections.*;
import javafx.collections.ObservableList;
public class Administratie implements Serializable {
//************************datavelden*************************************
private int nextGezinsNr = 0;
private int nextPersNr = 0;
private final List<Persoon> personen;
private final List<Gezin> gezinnen;
private transient ObservableList<Persoon> observablePersonen;
private transient ObservableList<Gezin> observableGezinnen;
private final static long serialVersionUID = -3123920467171138433L;
//***********************constructoren***********************************
/**
* er wordt een administratie gecreeerd met 0 personen en dus 0 gezinnen
* personen en gezinnen die in de toekomst zullen worden gecreeerd, worden
* elk opvolgend genummerd vanaf 1
*/
public Administratie() {
personen = new ArrayList<>();
gezinnen = new ArrayList<>();
observablePersonen = observableList(personen);
observableGezinnen = observableList(gezinnen);
}
//**********************methoden****************************************
/**
* er wordt een persoon met een gegeven geslacht, met als voornamen vnamen,
* achternaam anaam, tussenvoegsel tvoegsel, geboortedatum gebdat,
* geboorteplaats gebplaats en een gegeven ouderlijk gezin gecreeerd; de persoon
* krijgt een uniek nummer toegewezen de persoon is voortaan ook bij het
* ouderlijk gezin bekend. Voor de voornamen, achternaam en gebplaats geldt
* dat de eerste letter naar een hoofdletter en de resterende letters naar
* een kleine letter zijn geconverteerd; het tussenvoegsel is zo nodig in
* zijn geheel geconverteerd naar kleine letters; overbodige spaties zijn
* verwijderd
*
* @param geslacht
* @param vnamen vnamen.length>0; alle strings zijn niet leeg
* @param anaam niet leeg
* @param tvoegsel
* @param gebdat
* @param gebplaats niet leeg
* @param ouderlijkGezin mag de waarde null (=onbekend) hebben
*
* @return als de persoon al bekend was (op basis van combinatie van getNaam(),
* geboorteplaats en geboortedatum), wordt er null geretourneerd, anders de
* nieuwe persoon
*/
public Persoon addPersoon(Geslacht geslacht, String[] vnamen, String anaam,
String tvoegsel, Calendar gebdat,
String gebplaats, Gezin ouderlijkGezin) {
if (vnamen.length == 0) {
throw new IllegalArgumentException("ten minst 1 voornaam");
}
for (String voornaam : vnamen) {
if (voornaam.trim().isEmpty()) {
throw new IllegalArgumentException("lege voornaam is niet toegestaan");
}
}
if (anaam.trim().isEmpty()) {
throw new IllegalArgumentException("lege achternaam is niet toegestaan");
}
if (gebplaats.trim().isEmpty()) {
throw new IllegalArgumentException("lege geboorteplaats is niet toegestaan");
}
nextPersNr++;
Persoon newPersoon = new Persoon(this.nextPersNr, vnamen, anaam, tvoegsel, gebdat, gebplaats, geslacht, ouderlijkGezin);
if (getPersoon(vnamen, anaam, tvoegsel, gebdat, gebplaats) != null) {
return null;
}
observablePersonen.add(newPersoon);
if(ouderlijkGezin != null)
{
newPersoon.getOuderlijkGezin().breidUitMet(newPersoon);
}
return newPersoon;
}
/**
* er wordt, zo mogelijk (zie return) een (kinderloos) ongehuwd gezin met
* ouder1 en ouder2 als ouders gecreeerd; de huwelijks- en scheidingsdatum
* zijn onbekend (null); het gezin krijgt een uniek nummer toegewezen; dit
* gezin wordt ook bij de afzonderlijke ouders geregistreerd;
*
* @param ouder1
* @param ouder2 mag null zijn
*
* @return null als ouder1 = ouder2 of als de volgende voorwaarden worden
* overtreden: 1) een van de ouders is op dit moment getrouwd 2) het koppel
* uit een ongehuwd gezin kan niet tegelijkertijd als koppel bij een ander
* ongehuwd gezin betrokken zijn anders het gewenste gezin
*/
public Gezin addOngehuwdGezin(Persoon ouder1, Persoon ouder2) {
Calendar nu = Calendar.getInstance();
if (ouder1 == ouder2)
{
return null;
}
if(ongehuwdGezinBestaat(ouder1, ouder2))
{
return null;
}
if (ouder1.isGetrouwdOp(nu))
{
return null;
} else if (ouder2 != null && ouder2.isGetrouwdOp(nu))
{
return null;
} else if (ongehuwdGezinBestaat(ouder1, ouder2))
{
return null;
}
nextGezinsNr++;
Gezin gezin = new Gezin(nextGezinsNr, ouder1, ouder2);
observableGezinnen.add(gezin);
ouder1.wordtOuderIn(gezin);
if (ouder2 != null)
{
ouder2.wordtOuderIn(gezin);
}
return gezin;
}
/**
* Als het ouderlijk gezin van persoon nog onbekend is dan wordt persoon een
* kind van ouderlijkGezin en tevens wordt persoon als kind in dat gezin
* geregistreerd; <br>
* Als de ouders bij aanroep al bekend zijn, verandert er
* niets
*
* @param persoon
* @param ouderlijkGezin
*/
public void setOuders(Persoon persoon, Gezin ouderlijkGezin) {
persoon.setOuders(ouderlijkGezin);
}
/**
* als de ouders van dit gezin gehuwd zijn en nog niet gescheiden en datum
* na de huwelijksdatum ligt, wordt dit de scheidingsdatum. Anders gebeurt
* er niets.
*
* @param gezin
* @param datum
* @return true als scheiding geaccepteerd, anders false
*/
public boolean setScheiding(Gezin gezin, Calendar datum) {
return gezin.setScheiding(datum);
}
/**
* registreert het huwelijk,<SUF>*/
public boolean setHuwelijk(Gezin gezin, Calendar datum) {
return gezin.setHuwelijk(datum);
}
/**
*
* @param ouder1
* @param ouder2
* @return true als dit koppel (ouder1,ouder2) al een ongehuwd gezin vormt
*/
boolean ongehuwdGezinBestaat(Persoon ouder1, Persoon ouder2) {
return ouder1.heeftOngehuwdGezinMet(ouder2) != null;
}
/**
* als er al een ongehuwd gezin voor dit koppel bestaat, wordt het huwelijk
* voltrokken, anders wordt er zo mogelijk (zie return) een (kinderloos)
* gehuwd gezin met ouder1 en ouder2 als ouders gecreeerd; de
* scheidingsdatum is onbekend (null); het gezin krijgt een uniek nummer
* toegewezen; dit gezin wordt ook bij de afzonderlijke ouders
* geregistreerd;
*
* @param ouder1
* @param ouder2
* @param huwdatum
* @return null als ouder1 = ouder2 of als een van de ouders getrouwd is
* anders het gehuwde gezin
*/
public Gezin addHuwelijk(Persoon ouder1, Persoon ouder2, Calendar huwdatum) {
if (ouder1 == ouder2) {
return null;
}
if (!ouder1.kanTrouwenOp(huwdatum) || !ouder2.kanTrouwenOp(huwdatum)) {
return null;
}
Gezin toeTeVoegenGezin;
boolean alOngehuwdGezin = false;
for (Gezin huidig: observableGezinnen) {
if (huidig.getOuder1() == ouder1 && huidig.getOuder2() == ouder2) {
toeTeVoegenGezin = huidig;
toeTeVoegenGezin.setHuwelijk(huwdatum);
alOngehuwdGezin = true;
return toeTeVoegenGezin;
}
if (huidig.getOuder2() == ouder1 && huidig.getOuder1() == ouder2) {
toeTeVoegenGezin = huidig;
toeTeVoegenGezin.setHuwelijk(huwdatum);
alOngehuwdGezin = true;
return toeTeVoegenGezin;
}
}
if (!alOngehuwdGezin) {
nextGezinsNr++;
toeTeVoegenGezin = new Gezin(nextGezinsNr, ouder1, ouder2);
ouder1.wordtOuderIn(toeTeVoegenGezin);
ouder2.wordtOuderIn(toeTeVoegenGezin);
if (toeTeVoegenGezin.setHuwelijk(huwdatum)) {
observableGezinnen.add(toeTeVoegenGezin);
return toeTeVoegenGezin;
}
else
{
return null;
}
}
else
{
return null;
}
}
/**
*
* @return het aantal geregistreerde personen
*/
public int aantalGeregistreerdePersonen() {
return nextPersNr ;
}
/**
*
* @return het aantal geregistreerde gezinnen
*/
public int aantalGeregistreerdeGezinnen() {
return nextGezinsNr ;
}
/**
*
* @param nr
* @return de persoon met nummer nr, als die niet bekend is wordt er null
* geretourneerd
*/
public Persoon getPersoon(int nr) {
for (Persoon huidig: observablePersonen) {
if (huidig.getNr() == nr) {
return huidig;
}
}
return null;
}
/**
* @param achternaam
* @return alle personen met een achternaam gelijk aan de meegegeven
* achternaam (ongeacht hoofd- en kleine letters)
*/
public ArrayList<Persoon> getPersonenMetAchternaam(String achternaam) {
ArrayList<Persoon> gevondenPersonen = new ArrayList<>();
for (Persoon huidig: observablePersonen) {
if (huidig.getAchternaam().toLowerCase().equals(achternaam.toLowerCase())) {
gevondenPersonen.add(huidig);
}
}
return gevondenPersonen;
}
/**
*
* @return de geregistreerde personen
*/
public ObservableList<Persoon> getPersonen() {
return (ObservableList<Persoon>)FXCollections.unmodifiableObservableList(observablePersonen);
}
/**
*
* @param vnamen
* @param anaam
* @param tvoegsel
* @param gebdat
* @param gebplaats
* @return de persoon met dezelfde initialen, tussenvoegsel, achternaam,
* geboortedatum en -plaats mits bekend (ongeacht hoofd- en kleine letters),
* anders null
*/
public Persoon getPersoon(String[] vnamen, String anaam, String tvoegsel,
Calendar gebdat, String gebplaats) {
ArrayList<Persoon> p = new ArrayList<>();
for (Persoon huidig: observablePersonen) {
String initialen = "";
for (String voornaam:vnamen) {
initialen += voornaam.substring(0, 1) + ".";
}
if (gebplaats.toLowerCase().equals(huidig.getGebPlaats().toLowerCase())
&& gebdat.equals(huidig.getGebDat())
&& tvoegsel.toLowerCase().equals(huidig.getTussenvoegsel().toLowerCase())
&& anaam.toLowerCase().equals(huidig.getAchternaam().toLowerCase())
&& initialen.toLowerCase().equals(huidig.getInitialen().toLowerCase())) {
p.add(huidig);
return p.get(0);
}
}
return null;
}
/**
*
* @return de geregistreerde gezinnen
*/
public ObservableList<Gezin> getGezinnen() {
return (ObservableList<Gezin>)FXCollections.unmodifiableObservableList(observableGezinnen);
}
/**
*
* @param gezinsNr
* @return het gezin met nummer nr. Als dat niet bekend is wordt er null
* geretourneerd
*/
public Gezin getGezin(int gezinsNr) {
// aanname: er worden geen gezinnen verwijderd
if (1 <= gezinsNr && 1 <= observableGezinnen.size()) {
return observableGezinnen.get(gezinsNr - 1);
}
return null;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException
{
ois.defaultReadObject();
observablePersonen = observableList(personen);
observableGezinnen = observableList(gezinnen);
}
public void addDBPersoon (Persoon p)
{
observablePersonen.add(p);
}
}
|
113416_1 | package bank.server;
import java.beans.*;
import java.rmi.*;
import java.util.*;
/**
*
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: Fontys Hogeschool ICT</p>
*
* @author Frank Peeters
* @version 1.0
*/
public interface RemotePropertyListener
extends EventListener, Remote {
/**
* op basis van de informatie die evt overdraagt kan deze listener er voor
* zorgen dat de bijbehorende observer gesynchroniseerd wordt
* @param evt PropertyChangeEvent @see java.beans.PropertyChangeEvent
* @throws RemoteException
*/
void propertyChange(PropertyChangeEvent evt) throws RemoteException;
}
| KevinvdBurg/Internetbankieren_RMI | BankierenNoObserverFX/src/bank/server/RemotePropertyListener.java | 209 | /**
* op basis van de informatie die evt overdraagt kan deze listener er voor
* zorgen dat de bijbehorende observer gesynchroniseerd wordt
* @param evt PropertyChangeEvent @see java.beans.PropertyChangeEvent
* @throws RemoteException
*/ | block_comment | nl | package bank.server;
import java.beans.*;
import java.rmi.*;
import java.util.*;
/**
*
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: Fontys Hogeschool ICT</p>
*
* @author Frank Peeters
* @version 1.0
*/
public interface RemotePropertyListener
extends EventListener, Remote {
/**
* op basis van<SUF>*/
void propertyChange(PropertyChangeEvent evt) throws RemoteException;
}
|
173007_1 | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList<Period>();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
| KevinvdBurg/JSF31 | Week3/src/timeutil/TimeStamp.java | 1,270 | /**
* initialiseer klasse. begin met geen tijdsperiodes.
*/ | block_comment | nl | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin<SUF>*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList<Period>();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
|
160538_1 | package com.PPinera.Torrent_Movies.Activities;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.PPinera.Torrent_Movies.Adapters.FilmsGridAdapter;
import com.PPinera.Torrent_Movies.Adapters.MenuAdapter;
import com.PPinera.Torrent_Movies.R;
import com.PPinera.Torrent_Movies.Web.MovieItem;
import com.PPinera.Torrent_Movies.Web.YIFIClient;
import java.util.ArrayList;
public class MainActivity extends Activity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private GridView gridview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupDrawerLayout();
setupActionBar();
gridview = (GridView) findViewById(R.id.gridview);
}
private void reloadGridWithGenre(String genre){
YIFIClient.getFilmsByGenre(new YIFIClient.filmsListHandler() {
@Override
public void onSuccessFilms(ArrayList<MovieItem> films) {
FilmsGridAdapter adapter = new FilmsGridAdapter(MainActivity.this,films);
gridview.setAdapter(adapter);
}
@Override
public void onErrorFilms(Throwable e) {
}
},genre);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new MenuAdapter(this));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
gridview.setAdapter(null);
getActionBar().setTitle((String)parent.getItemAtPosition(position));
reloadGridWithGenre((String)parent.getItemAtPosition(position));
}
}
private void selectItem(int position) {
drawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerList);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| KhalidElSayed/Torrent-Movies | src/com/PPinera/Torrent_Movies/Activities/MainActivity.java | 1,127 | /* "open drawer" description */ | block_comment | nl | package com.PPinera.Torrent_Movies.Activities;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.PPinera.Torrent_Movies.Adapters.FilmsGridAdapter;
import com.PPinera.Torrent_Movies.Adapters.MenuAdapter;
import com.PPinera.Torrent_Movies.R;
import com.PPinera.Torrent_Movies.Web.MovieItem;
import com.PPinera.Torrent_Movies.Web.YIFIClient;
import java.util.ArrayList;
public class MainActivity extends Activity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private GridView gridview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupDrawerLayout();
setupActionBar();
gridview = (GridView) findViewById(R.id.gridview);
}
private void reloadGridWithGenre(String genre){
YIFIClient.getFilmsByGenre(new YIFIClient.filmsListHandler() {
@Override
public void onSuccessFilms(ArrayList<MovieItem> films) {
FilmsGridAdapter adapter = new FilmsGridAdapter(MainActivity.this,films);
gridview.setAdapter(adapter);
}
@Override
public void onErrorFilms(Throwable e) {
}
},genre);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new MenuAdapter(this));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description<SUF>*/
R.string.drawer_close /* "close drawer" description */
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
gridview.setAdapter(null);
getActionBar().setTitle((String)parent.getItemAtPosition(position));
reloadGridWithGenre((String)parent.getItemAtPosition(position));
}
}
private void selectItem(int position) {
drawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerList);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
14022_5 | package Model;
import AI.AI;
import Helper.CsvLogger;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.ArrayList;
import java.util.List;
abstract public class Model {
private boolean againstAi;
private int[] gameBoard;
private int currentPlayer;
private int startPlayer;
private boolean isWinner;
private boolean isTie;
private boolean isOnline;
private int winner;
private int size;
private AI ai;
private final CsvLogger csvLogger;
private final List<Long> timesPerMove;
private final int EMPTY = 0;
private final int PLAYER_ONE = 1;
private final int PLAYER_TWO = 2;
private final int SUGGESTED = 3;
public Model(int size, AI ai) {
this.size = size;
this.currentPlayer = PLAYER_ONE;
this.gameBoard = buildGameBoard();
this.isWinner = false;
this.isTie = false;
this.isOnline = false;
this.winner = EMPTY;
this.ai = ai;
this.csvLogger = new CsvLogger("./data/average-times.csv");
this.timesPerMove = new ArrayList<>();
}
/**
* Als een speler een zet heeft gedaan doet de AI.AI eventueel daarna meteen een zet.
*
* @param idx geeft de index mee waar een zet op gedaan is.
*/
public void sets(int idx) {
if (!validMove(idx, gameBoard)) {
return;
}
int player = getCurrentPlayer();
userSet(idx);
//Alleen als het spel nog niet geëindigd is.
//Alleen als er tegen de AI.AI gespeeld wordt.
if (!isWinner && !isTie && againstAi && getAvailableMoves(gameBoard, PLAYER_TWO).size() > 0) {
aiSet(player);
while (getAvailableMoves(gameBoard, PLAYER_ONE).isEmpty() && !((isWinner && !isTie) || (!isWinner && isTie))) {
aiSet(player);
}
}
}
/**
* Laat de ai een zet doen
*
* @param opponent geeft mee welke speler de tegenstander is.
* @return geeft de index terug waar de ai een zet op wil doen.
*/
public int aiSet(int opponent) {
long startTime = System.nanoTime();
int i = ai.aiNewSet(gameBoard, opponent, this);
long endTime = System.nanoTime();
long deltaTime = endTime - startTime;
timesPerMove.add(deltaTime);
userSet(i);
return i;
}
private void writeStatisticToCSV() {
double[] times = this.timesPerMove.stream().mapToDouble(d -> d).toArray();
DescriptiveStatistics stats = new DescriptiveStatistics(times);
int transpositionTableSize = ai.getTable().size();
double mean = stats.getMean();
double std = stats.getStandardDeviation();
double maxTime = stats.getMax();
double minTime = stats.getMin();
double q1 = stats.getPercentile(25);
double q2 = stats.getPercentile(50);
double q3 = stats.getPercentile(75);
csvLogger.writeDataToCsv(transpositionTableSize, mean, std, maxTime, minTime, q1, q2, q3);
}
/**
* Zet de zet op het bord en handelt de vervolgstappen af.
*
* @param idx geeft de index mee waar een zet op gedaan moet worden.
*/
public void userSet(int idx) {
//Controleert of er nog plaats is.
if (!validMove(idx, gameBoard)) {
return;
}
gameBoard = move(idx, gameBoard, currentPlayer);
gameBoard = showMoves(gameBoard, currentPlayer);
if (isFinished()) {
ai.saveTranspositionTable("./data/transposition-table");
writeStatisticToCSV();
winner = checkWinner();
if (winner == PLAYER_ONE || winner == PLAYER_TWO) {
isWinner = true;
} else {
isTie = checkTie();
}
}
//Veranderd wie er aan de beurt is.
changeTurn();
if (!availabeMovePlayer()) {
changeTurn();
}
}
public void changeTurn() {
currentPlayer = (currentPlayer == PLAYER_ONE) ? PLAYER_TWO : PLAYER_ONE;
}
/**
* Controleert of er nog plaats is waar de nieuwe set gedaan wordt.
*
* @param idx de index waar de zet op gedaan wordt.
* @return geeft terug of er nog plaats is op het bord.
*/
public boolean isEmptyColumn(int idx, int[] gameBoard) {
// Checkt of 'idx' buiten het speelveld valt en of het vakje al bezet is of niet
if (idx >= 0 && idx < gameBoard.length) {
if (gameBoard[idx] == EMPTY || gameBoard[idx] == SUGGESTED) {
return true;
}
}
return false;
}
abstract public int[] showMoves(int[] gameBoard, int currentPlayer);
abstract public int[] move(int idx, int[] currentBoard, int currentPlayer);
abstract public boolean validMove(int idx, int[] gameBoard);
abstract public ArrayList<Integer> getAvailableMoves(int[] gameBoard, int player);
abstract public boolean availabeMovePlayer();
abstract public int checkWinner();
abstract public boolean checkTie();
abstract public boolean isFinished();
abstract public boolean isFinished(ArrayList<Integer> availableMovesCurrentPlayer, ArrayList<Integer> availableMovesOtherPlayer);
/**
* @return geeft de huidige bord terug.
*/
public int[] getBoardData() {
return gameBoard;
}
/**
* Vervangt het huidige bord met de nieuwe.
*
* @param newGameBoard geeft de nieuwe bord status mee
*/
public void setGameBoard(int[] newGameBoard) {
gameBoard = newGameBoard;
}
/**
* @return geeft terug of er een winnaar is.
*/
public boolean isWinner() {
return isWinner;
}
/**
* @return geeft terug of er een gelijkspel is.
*/
public boolean isTie() {
return isTie;
}
public boolean isOnline() {
return isOnline;
}
public void toggleIsOnline() {
this.isOnline = !(this.isOnline);
}
/**
* @return geeft de winnaar terug.
*/
public int getWinner() {
return winner;
}
/**
* @return geeft de winnaar in een string terug.
*/
abstract public String getStringWinner();
abstract public int[] buildGameBoard();
/**
* Het resetten van het spel.
*
* @param playAi geeft aan of je tegen de ai speelt
* @param AiStart geeft aan of de ai mag beginnen
* @param start welke speler er mag starten
*/
public void resetGame(boolean playAi, boolean AiStart, int start) {
currentPlayer = start;
gameBoard = buildGameBoard();
isWinner = false;
isTie = false;
againstAi = playAi;
startPlayer = start;
winner = EMPTY;
if (AiStart && playAi) {
int idx = ai.aiNewSet(gameBoard, PLAYER_ONE, this);
userSet(idx);
}
}
/**
* @return geeft aan of je tegen ai speelt
*/
public boolean getAgainstAi() {
return againstAi;
}
/**
* @return geeft de huidige speler terug
*/
public int getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(int currentPlayer) {
this.currentPlayer = currentPlayer;
}
public abstract String getCurrentPlayerString();
/**
* @return geeft terug wie er begonnen is.
*/
public int getStartPlayer() {
return startPlayer;
}
/**
* @return geeft terug hoe groot het bord is.
*/
public int getSize() {
return size;
}
@Override
public String toString() {
for (int i = 0; i < gameBoard.length / 8; i++) {
for (int j = 0; j < gameBoard.length / 8; j++) {
if (gameBoard[i*8+j] == 3){
System.out.print(0 + "| ");
}else {
System.out.print(gameBoard[i * 8 + j] + "| ");
}
}
System.out.println();
}
return "";
}
}
| Kianvos/Inteligente_Systemen | src/main/java/Model/Model.java | 2,472 | //Controleert of er nog plaats is. | line_comment | nl | package Model;
import AI.AI;
import Helper.CsvLogger;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.ArrayList;
import java.util.List;
abstract public class Model {
private boolean againstAi;
private int[] gameBoard;
private int currentPlayer;
private int startPlayer;
private boolean isWinner;
private boolean isTie;
private boolean isOnline;
private int winner;
private int size;
private AI ai;
private final CsvLogger csvLogger;
private final List<Long> timesPerMove;
private final int EMPTY = 0;
private final int PLAYER_ONE = 1;
private final int PLAYER_TWO = 2;
private final int SUGGESTED = 3;
public Model(int size, AI ai) {
this.size = size;
this.currentPlayer = PLAYER_ONE;
this.gameBoard = buildGameBoard();
this.isWinner = false;
this.isTie = false;
this.isOnline = false;
this.winner = EMPTY;
this.ai = ai;
this.csvLogger = new CsvLogger("./data/average-times.csv");
this.timesPerMove = new ArrayList<>();
}
/**
* Als een speler een zet heeft gedaan doet de AI.AI eventueel daarna meteen een zet.
*
* @param idx geeft de index mee waar een zet op gedaan is.
*/
public void sets(int idx) {
if (!validMove(idx, gameBoard)) {
return;
}
int player = getCurrentPlayer();
userSet(idx);
//Alleen als het spel nog niet geëindigd is.
//Alleen als er tegen de AI.AI gespeeld wordt.
if (!isWinner && !isTie && againstAi && getAvailableMoves(gameBoard, PLAYER_TWO).size() > 0) {
aiSet(player);
while (getAvailableMoves(gameBoard, PLAYER_ONE).isEmpty() && !((isWinner && !isTie) || (!isWinner && isTie))) {
aiSet(player);
}
}
}
/**
* Laat de ai een zet doen
*
* @param opponent geeft mee welke speler de tegenstander is.
* @return geeft de index terug waar de ai een zet op wil doen.
*/
public int aiSet(int opponent) {
long startTime = System.nanoTime();
int i = ai.aiNewSet(gameBoard, opponent, this);
long endTime = System.nanoTime();
long deltaTime = endTime - startTime;
timesPerMove.add(deltaTime);
userSet(i);
return i;
}
private void writeStatisticToCSV() {
double[] times = this.timesPerMove.stream().mapToDouble(d -> d).toArray();
DescriptiveStatistics stats = new DescriptiveStatistics(times);
int transpositionTableSize = ai.getTable().size();
double mean = stats.getMean();
double std = stats.getStandardDeviation();
double maxTime = stats.getMax();
double minTime = stats.getMin();
double q1 = stats.getPercentile(25);
double q2 = stats.getPercentile(50);
double q3 = stats.getPercentile(75);
csvLogger.writeDataToCsv(transpositionTableSize, mean, std, maxTime, minTime, q1, q2, q3);
}
/**
* Zet de zet op het bord en handelt de vervolgstappen af.
*
* @param idx geeft de index mee waar een zet op gedaan moet worden.
*/
public void userSet(int idx) {
//Controleert of<SUF>
if (!validMove(idx, gameBoard)) {
return;
}
gameBoard = move(idx, gameBoard, currentPlayer);
gameBoard = showMoves(gameBoard, currentPlayer);
if (isFinished()) {
ai.saveTranspositionTable("./data/transposition-table");
writeStatisticToCSV();
winner = checkWinner();
if (winner == PLAYER_ONE || winner == PLAYER_TWO) {
isWinner = true;
} else {
isTie = checkTie();
}
}
//Veranderd wie er aan de beurt is.
changeTurn();
if (!availabeMovePlayer()) {
changeTurn();
}
}
public void changeTurn() {
currentPlayer = (currentPlayer == PLAYER_ONE) ? PLAYER_TWO : PLAYER_ONE;
}
/**
* Controleert of er nog plaats is waar de nieuwe set gedaan wordt.
*
* @param idx de index waar de zet op gedaan wordt.
* @return geeft terug of er nog plaats is op het bord.
*/
public boolean isEmptyColumn(int idx, int[] gameBoard) {
// Checkt of 'idx' buiten het speelveld valt en of het vakje al bezet is of niet
if (idx >= 0 && idx < gameBoard.length) {
if (gameBoard[idx] == EMPTY || gameBoard[idx] == SUGGESTED) {
return true;
}
}
return false;
}
abstract public int[] showMoves(int[] gameBoard, int currentPlayer);
abstract public int[] move(int idx, int[] currentBoard, int currentPlayer);
abstract public boolean validMove(int idx, int[] gameBoard);
abstract public ArrayList<Integer> getAvailableMoves(int[] gameBoard, int player);
abstract public boolean availabeMovePlayer();
abstract public int checkWinner();
abstract public boolean checkTie();
abstract public boolean isFinished();
abstract public boolean isFinished(ArrayList<Integer> availableMovesCurrentPlayer, ArrayList<Integer> availableMovesOtherPlayer);
/**
* @return geeft de huidige bord terug.
*/
public int[] getBoardData() {
return gameBoard;
}
/**
* Vervangt het huidige bord met de nieuwe.
*
* @param newGameBoard geeft de nieuwe bord status mee
*/
public void setGameBoard(int[] newGameBoard) {
gameBoard = newGameBoard;
}
/**
* @return geeft terug of er een winnaar is.
*/
public boolean isWinner() {
return isWinner;
}
/**
* @return geeft terug of er een gelijkspel is.
*/
public boolean isTie() {
return isTie;
}
public boolean isOnline() {
return isOnline;
}
public void toggleIsOnline() {
this.isOnline = !(this.isOnline);
}
/**
* @return geeft de winnaar terug.
*/
public int getWinner() {
return winner;
}
/**
* @return geeft de winnaar in een string terug.
*/
abstract public String getStringWinner();
abstract public int[] buildGameBoard();
/**
* Het resetten van het spel.
*
* @param playAi geeft aan of je tegen de ai speelt
* @param AiStart geeft aan of de ai mag beginnen
* @param start welke speler er mag starten
*/
public void resetGame(boolean playAi, boolean AiStart, int start) {
currentPlayer = start;
gameBoard = buildGameBoard();
isWinner = false;
isTie = false;
againstAi = playAi;
startPlayer = start;
winner = EMPTY;
if (AiStart && playAi) {
int idx = ai.aiNewSet(gameBoard, PLAYER_ONE, this);
userSet(idx);
}
}
/**
* @return geeft aan of je tegen ai speelt
*/
public boolean getAgainstAi() {
return againstAi;
}
/**
* @return geeft de huidige speler terug
*/
public int getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(int currentPlayer) {
this.currentPlayer = currentPlayer;
}
public abstract String getCurrentPlayerString();
/**
* @return geeft terug wie er begonnen is.
*/
public int getStartPlayer() {
return startPlayer;
}
/**
* @return geeft terug hoe groot het bord is.
*/
public int getSize() {
return size;
}
@Override
public String toString() {
for (int i = 0; i < gameBoard.length / 8; i++) {
for (int j = 0; j < gameBoard.length / 8; j++) {
if (gameBoard[i*8+j] == 3){
System.out.print(0 + "| ");
}else {
System.out.print(gameBoard[i * 8 + j] + "| ");
}
}
System.out.println();
}
return "";
}
}
|
71334_4 | package opgave;
public class Board {
public static final int NONE = 0;
public static final int PLAYER1 = 1;
public static final int PLAYER2 = 2;
public static final int NUMBER_OF_COLS = 8;
public static final int NUMBER_OF_ROWS = 8;
private final int[][] board;
public Board() {
board = new int[NUMBER_OF_COLS][NUMBER_OF_ROWS];
}
public Board(Board board) {
this();
// De array wordt gekopiëerd, om onbedoelde wijzigingen in de array van het argument te voorkomen.
for (int col = 0; col < NUMBER_OF_COLS; col++) {
for (int row = 0; row < NUMBER_OF_ROWS; row++) {
this.board[col][row] = board.get(col, row);
}
}
}
public Board(Board board, int player, int column) {
this(board);
if (isValidMove(column)) {
for (int i = NUMBER_OF_ROWS - 1; i >= 0; i--) {
if (board.get(column, i) == NONE) {
this.board[column][i] = player;
break;
}
}
// Verander de array board, zodat een steen van player in column terecht komt.
// ..(deze code dient te worden aangevuld)
} else {
throw new IllegalStateException("Invalid move");
}
}
public Board doMove(int player, int column) {
return new Board(this, player, column);
}
// getter voor een steen op bepaalde positie
public int get(int column, int row) {
return board[column][row];
}
// kan in de kolom een steen worden geworpen?
public boolean isValidMove(int column) {
for (int i = NUMBER_OF_ROWS - 1; i >= 0; i--) {
if (board[column][i] == NONE) {
return true;
}
}
return false;
}
// is het spel afgelopen?
public boolean isFinished() {
if (isWinner(PLAYER1) || isWinner(PLAYER2)) {
return true;
}
for (int i = 0; i < NUMBER_OF_COLS; i++) {
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
if (board[i][j] == NONE) {
return false;
}
}
}
return true;
}
// heeft player gewonnen?
public boolean isWinner(int player) {
if (horizontalWinner(player)) {
return true;
} else if (verticalWinner(player)) {
return true;
} else if (diagonalLeftTopRight(player)){
return true;
}
return diagonalRightTopLeft(player);
}
public boolean horizontalWinner(int player) {
for (int i = 0; i < NUMBER_OF_COLS; i++) {
int tmp = 0;
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
if (board[j][i] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
}
}
return false;
}
public boolean verticalWinner(int player) {
for (int i = 0; i < NUMBER_OF_COLS; i++) {
int tmp = 0;
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
if (board[i][j] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
}
}
return false;
}
public boolean diagonalLeftTopRight(int player) {
for (int i = NUMBER_OF_COLS - 1; i >= 0; i--) {
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
int tmpCol = i;
int tmpRow = j;
int tmp = 0;
while (tmpRow >= 0 && tmpRow < NUMBER_OF_ROWS && tmpCol >= 0 && tmpCol < NUMBER_OF_COLS) {
if (board[tmpCol][tmpRow] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
tmpCol--;
tmpRow++;
}
}
}
return false;
}
public boolean diagonalRightTopLeft(int player) {
for (int i = 0; i < NUMBER_OF_COLS; i++) {
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
int tmpCol = i;
int tmpRow = j;
int tmp = 0;
while (tmpRow >= 0 && tmpRow < NUMBER_OF_ROWS && tmpCol >= 0 && tmpCol < NUMBER_OF_COLS) {
if (board[tmpCol][tmpRow] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
tmpCol++;
tmpRow++;
}
}
}
return false;
}
}
| Kianvos/OOP-opgaven | Periode_2/Week_1/src/main/java/opgave/Board.java | 1,541 | // kan in de kolom een steen worden geworpen? | line_comment | nl | package opgave;
public class Board {
public static final int NONE = 0;
public static final int PLAYER1 = 1;
public static final int PLAYER2 = 2;
public static final int NUMBER_OF_COLS = 8;
public static final int NUMBER_OF_ROWS = 8;
private final int[][] board;
public Board() {
board = new int[NUMBER_OF_COLS][NUMBER_OF_ROWS];
}
public Board(Board board) {
this();
// De array wordt gekopiëerd, om onbedoelde wijzigingen in de array van het argument te voorkomen.
for (int col = 0; col < NUMBER_OF_COLS; col++) {
for (int row = 0; row < NUMBER_OF_ROWS; row++) {
this.board[col][row] = board.get(col, row);
}
}
}
public Board(Board board, int player, int column) {
this(board);
if (isValidMove(column)) {
for (int i = NUMBER_OF_ROWS - 1; i >= 0; i--) {
if (board.get(column, i) == NONE) {
this.board[column][i] = player;
break;
}
}
// Verander de array board, zodat een steen van player in column terecht komt.
// ..(deze code dient te worden aangevuld)
} else {
throw new IllegalStateException("Invalid move");
}
}
public Board doMove(int player, int column) {
return new Board(this, player, column);
}
// getter voor een steen op bepaalde positie
public int get(int column, int row) {
return board[column][row];
}
// kan in<SUF>
public boolean isValidMove(int column) {
for (int i = NUMBER_OF_ROWS - 1; i >= 0; i--) {
if (board[column][i] == NONE) {
return true;
}
}
return false;
}
// is het spel afgelopen?
public boolean isFinished() {
if (isWinner(PLAYER1) || isWinner(PLAYER2)) {
return true;
}
for (int i = 0; i < NUMBER_OF_COLS; i++) {
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
if (board[i][j] == NONE) {
return false;
}
}
}
return true;
}
// heeft player gewonnen?
public boolean isWinner(int player) {
if (horizontalWinner(player)) {
return true;
} else if (verticalWinner(player)) {
return true;
} else if (diagonalLeftTopRight(player)){
return true;
}
return diagonalRightTopLeft(player);
}
public boolean horizontalWinner(int player) {
for (int i = 0; i < NUMBER_OF_COLS; i++) {
int tmp = 0;
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
if (board[j][i] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
}
}
return false;
}
public boolean verticalWinner(int player) {
for (int i = 0; i < NUMBER_OF_COLS; i++) {
int tmp = 0;
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
if (board[i][j] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
}
}
return false;
}
public boolean diagonalLeftTopRight(int player) {
for (int i = NUMBER_OF_COLS - 1; i >= 0; i--) {
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
int tmpCol = i;
int tmpRow = j;
int tmp = 0;
while (tmpRow >= 0 && tmpRow < NUMBER_OF_ROWS && tmpCol >= 0 && tmpCol < NUMBER_OF_COLS) {
if (board[tmpCol][tmpRow] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
tmpCol--;
tmpRow++;
}
}
}
return false;
}
public boolean diagonalRightTopLeft(int player) {
for (int i = 0; i < NUMBER_OF_COLS; i++) {
for (int j = 0; j < NUMBER_OF_ROWS; j++) {
int tmpCol = i;
int tmpRow = j;
int tmp = 0;
while (tmpRow >= 0 && tmpRow < NUMBER_OF_ROWS && tmpCol >= 0 && tmpCol < NUMBER_OF_COLS) {
if (board[tmpCol][tmpRow] != player) {
tmp = 0;
} else {
tmp++;
if (tmp == 4) {
return true;
}
}
tmpCol++;
tmpRow++;
}
}
}
return false;
}
}
|
200620_39 | package swisseph;
/**
* Interface for different methods used for transit calculations.
*/
public abstract class TransitCalculator
implements java.io.Serializable
{
SwissEph sw;
// This method changes the offset value for the transit
/**
* @return Returns true, if one position value is identical to another
* position value. E.g., 360 degree is identical to 0 degree in
* circular angles.
* @see #rolloverVal
*/
public abstract boolean getRollover();
/**
* @return Returns the value, which is identical to zero on the other
* end of a linear scale.
* @see #rolloverVal
*/
public double getRolloverVal() {
return rolloverVal;
}
/**
* This sets the degree or other value for the position or speed of
* the planet to transit. It will be used on the next call to getTransit().
* @param value The desired offset value.
* @see #getOffset()
*/
public abstract void setOffset(double value);
/**
* This returns the degree or other value of the position or speed of
* the planet to transit.
* @return The currently set offset value.
* @see #setOffset(double)
*/
public abstract double getOffset();
/**
* This returns all the "object identifiers" used in this
* TransitCalculator. It may be the planet number or planet numbers,
* when calculating planets.
* @return An array of identifiers identifying the calculated objects.
*/
public Object[] getObjectIdentifiers() {
return null;
}
//////////////////////////////////////////////////////////////////////////////
// Rollover from 360 degrees to 0 degrees for planetary longitudinal positions
// or similar, or continuous and unlimited values:
protected boolean rollover = false; // We need a rollover of 360 degrees being
// equal to 0 degrees for longitudinal
// position transits only.
protected double rolloverVal = 360.; // if rollover, we roll over from 360 to 0
// as default. Other values than 0.0 for the
// minimum values are not supported for now.
// These methods have to return the maxima of the first derivative of the
// function, mathematically spoken...
protected abstract double getMaxSpeed();
protected abstract double getMinSpeed();
// This method returns the precision in x-direction in an x-y-coordinate
// system for the transit calculation routine.
protected abstract double getDegreePrecision(double jdET);
// This method returns the precision in y-direction in an x-y-coordinate
// system from the x-direction precision.
protected abstract double getTimePrecision(double degPrec);
// This is the main routine, mathematically speaking: returning f(x):
protected abstract double calc(double jdET);
// This routine allows for changing jdET before starting calculations.
double preprocessDate(double jdET, boolean back) {
return jdET;
}
// These routines check the result if it meets the stop condition
protected boolean checkIdenticalResult(double offset, double val) {
return val == offset;
}
protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) {
return (// transits from higher deg. to lower deg.:
( above && val<=offset && !pxway) ||
// transits from lower deg. to higher deg.:
(!above && val>=offset && pxway)) ||
(rollover && (
// transits from above the transit degree via rollover over
// 0 degrees to a higher degree:
(offset<lastVal && val>.9*rolloverVal && lastVal<20. && !pxway) ||
// transits from below the transit degree via rollover over
// 360 degrees to a lower degree:
(offset>lastVal && val<20. && lastVal>.9*rolloverVal && pxway) ||
// transits from below the transit degree via rollover over
// 0 degrees to a higher degree:
(offset>val && val>.9*rolloverVal && lastVal<20. && !pxway) ||
// transits from above the transit degree via rollover over
// 360 degrees to a lower degree:
(offset<val && val<20. && lastVal>.9*rolloverVal && pxway))
);
}
// Find next reasonable point to probe.
protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) {
double jdPlus = 0;
double jdMinus = 0;
if (rollover) {
// In most cases here we cannot find out for sure if the distance
// is decreasing or increasing. We take the smaller one of these:
jdPlus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(max);
jdMinus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(min);
if (back) {
jdET -= SMath.min(jdPlus,jdMinus);
} else {
jdET += SMath.min(jdPlus,jdMinus);
}
} else { // Latitude, distance and speed calculations...
//jdPlus = (back?(val-offset):(offset-val))/max;
//jdMinus = (back?(val-offset):(offset-val))/min;
jdPlus = (offset-val)/max;
jdMinus = (offset-val)/min;
if (back) {
if (jdPlus >= 0 && jdMinus >= 0) {
throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE,
-1, "No transit in ephemeris time range."); // I mean: No transits possible...
} else if (jdPlus >= 0) {
jdET += jdMinus;
} else { // if (jdMinus >= 0)
jdET += jdPlus;
}
} else {
if (jdPlus <= 0 && jdMinus <= 0) {
throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE,
-1, "No transit in ephemeris time range."); // I mean: No transits possible...
} else if (jdPlus <= 0) {
jdET += jdMinus;
} else { // if (jdMinus <= 0)
jdET += jdPlus;
}
}
}
return jdET;
}
}
| Kibo/AstroAPI | src/main/java/swisseph/TransitCalculator.java | 1,711 | //jdMinus = (back?(val-offset):(offset-val))/min; | line_comment | nl | package swisseph;
/**
* Interface for different methods used for transit calculations.
*/
public abstract class TransitCalculator
implements java.io.Serializable
{
SwissEph sw;
// This method changes the offset value for the transit
/**
* @return Returns true, if one position value is identical to another
* position value. E.g., 360 degree is identical to 0 degree in
* circular angles.
* @see #rolloverVal
*/
public abstract boolean getRollover();
/**
* @return Returns the value, which is identical to zero on the other
* end of a linear scale.
* @see #rolloverVal
*/
public double getRolloverVal() {
return rolloverVal;
}
/**
* This sets the degree or other value for the position or speed of
* the planet to transit. It will be used on the next call to getTransit().
* @param value The desired offset value.
* @see #getOffset()
*/
public abstract void setOffset(double value);
/**
* This returns the degree or other value of the position or speed of
* the planet to transit.
* @return The currently set offset value.
* @see #setOffset(double)
*/
public abstract double getOffset();
/**
* This returns all the "object identifiers" used in this
* TransitCalculator. It may be the planet number or planet numbers,
* when calculating planets.
* @return An array of identifiers identifying the calculated objects.
*/
public Object[] getObjectIdentifiers() {
return null;
}
//////////////////////////////////////////////////////////////////////////////
// Rollover from 360 degrees to 0 degrees for planetary longitudinal positions
// or similar, or continuous and unlimited values:
protected boolean rollover = false; // We need a rollover of 360 degrees being
// equal to 0 degrees for longitudinal
// position transits only.
protected double rolloverVal = 360.; // if rollover, we roll over from 360 to 0
// as default. Other values than 0.0 for the
// minimum values are not supported for now.
// These methods have to return the maxima of the first derivative of the
// function, mathematically spoken...
protected abstract double getMaxSpeed();
protected abstract double getMinSpeed();
// This method returns the precision in x-direction in an x-y-coordinate
// system for the transit calculation routine.
protected abstract double getDegreePrecision(double jdET);
// This method returns the precision in y-direction in an x-y-coordinate
// system from the x-direction precision.
protected abstract double getTimePrecision(double degPrec);
// This is the main routine, mathematically speaking: returning f(x):
protected abstract double calc(double jdET);
// This routine allows for changing jdET before starting calculations.
double preprocessDate(double jdET, boolean back) {
return jdET;
}
// These routines check the result if it meets the stop condition
protected boolean checkIdenticalResult(double offset, double val) {
return val == offset;
}
protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) {
return (// transits from higher deg. to lower deg.:
( above && val<=offset && !pxway) ||
// transits from lower deg. to higher deg.:
(!above && val>=offset && pxway)) ||
(rollover && (
// transits from above the transit degree via rollover over
// 0 degrees to a higher degree:
(offset<lastVal && val>.9*rolloverVal && lastVal<20. && !pxway) ||
// transits from below the transit degree via rollover over
// 360 degrees to a lower degree:
(offset>lastVal && val<20. && lastVal>.9*rolloverVal && pxway) ||
// transits from below the transit degree via rollover over
// 0 degrees to a higher degree:
(offset>val && val>.9*rolloverVal && lastVal<20. && !pxway) ||
// transits from above the transit degree via rollover over
// 360 degrees to a lower degree:
(offset<val && val<20. && lastVal>.9*rolloverVal && pxway))
);
}
// Find next reasonable point to probe.
protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) {
double jdPlus = 0;
double jdMinus = 0;
if (rollover) {
// In most cases here we cannot find out for sure if the distance
// is decreasing or increasing. We take the smaller one of these:
jdPlus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(max);
jdMinus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(min);
if (back) {
jdET -= SMath.min(jdPlus,jdMinus);
} else {
jdET += SMath.min(jdPlus,jdMinus);
}
} else { // Latitude, distance and speed calculations...
//jdPlus = (back?(val-offset):(offset-val))/max;
//jdMinus =<SUF>
jdPlus = (offset-val)/max;
jdMinus = (offset-val)/min;
if (back) {
if (jdPlus >= 0 && jdMinus >= 0) {
throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE,
-1, "No transit in ephemeris time range."); // I mean: No transits possible...
} else if (jdPlus >= 0) {
jdET += jdMinus;
} else { // if (jdMinus >= 0)
jdET += jdPlus;
}
} else {
if (jdPlus <= 0 && jdMinus <= 0) {
throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE,
-1, "No transit in ephemeris time range."); // I mean: No transits possible...
} else if (jdPlus <= 0) {
jdET += jdMinus;
} else { // if (jdMinus <= 0)
jdET += jdPlus;
}
}
}
return jdET;
}
}
|
30691_3 | package org.example.climber;
//Een klimmer heeft altijd klimschoentjes aan en gebruikt bijna altijd 'pof' (chalk), je kan 'pof' in poeder variant en in vloeibare variant gebruiken, er is een minimaal aantal klimmers dat geen pof gebruikt en daarom heb ik er een boolean van gemaakt, zodat de mogelijkheid is om hier 'false' aan mee te geven.
// Een klimmer kan meerdere disciplines doen, maar niet tegelijkertijd.
// Een klimmer is abstract, omdat je geen klimmer aanmaakt, maar de discipline die diegene op dat moment gaat uitvoeren.
//In eerste instantie had ik de locaties als losse classes gemaakt, maar dat maakt de applicatie onnodig moeilijk, omdat er eigenlijk niet zo heel veel dingen anders zijn aan de locaties waar je gaat klimmen. Daarom heb ik er toch voor gekozen om er een boolean van te maken of je buiten of binnen gaat klimmen. En de naam van de locatie toe te voegen.
public abstract class Climber {
String name;
int pairOfClimbingShoes;
public boolean usesLiquidChalk;
public boolean usesChalkPowder;
public boolean isLocationOutside;
String location;
public Climber(String name, int pairOfClimbingShoes, boolean usesLiquidChalk, boolean usesChalkPowder, boolean isLocationOutside, String location) {
this.name = name;
this.pairOfClimbingShoes = pairOfClimbingShoes;
this.usesLiquidChalk = usesLiquidChalk;
this.usesChalkPowder = usesChalkPowder;
this.isLocationOutside = isLocationOutside;
this.location = location;
}
}
| Kim007dus/java-climbing-project | src/main/java/org/example/climber/Climber.java | 454 | //In eerste instantie had ik de locaties als losse classes gemaakt, maar dat maakt de applicatie onnodig moeilijk, omdat er eigenlijk niet zo heel veel dingen anders zijn aan de locaties waar je gaat klimmen. Daarom heb ik er toch voor gekozen om er een boolean van te maken of je buiten of binnen gaat klimmen. En de naam van de locatie toe te voegen. | line_comment | nl | package org.example.climber;
//Een klimmer heeft altijd klimschoentjes aan en gebruikt bijna altijd 'pof' (chalk), je kan 'pof' in poeder variant en in vloeibare variant gebruiken, er is een minimaal aantal klimmers dat geen pof gebruikt en daarom heb ik er een boolean van gemaakt, zodat de mogelijkheid is om hier 'false' aan mee te geven.
// Een klimmer kan meerdere disciplines doen, maar niet tegelijkertijd.
// Een klimmer is abstract, omdat je geen klimmer aanmaakt, maar de discipline die diegene op dat moment gaat uitvoeren.
//In eerste<SUF>
public abstract class Climber {
String name;
int pairOfClimbingShoes;
public boolean usesLiquidChalk;
public boolean usesChalkPowder;
public boolean isLocationOutside;
String location;
public Climber(String name, int pairOfClimbingShoes, boolean usesLiquidChalk, boolean usesChalkPowder, boolean isLocationOutside, String location) {
this.name = name;
this.pairOfClimbingShoes = pairOfClimbingShoes;
this.usesLiquidChalk = usesLiquidChalk;
this.usesChalkPowder = usesChalkPowder;
this.isLocationOutside = isLocationOutside;
this.location = location;
}
}
|
28760_13 | package net.minecraft.src;
import java.util.Random;
import org.lwjgl.input.Keyboard;
public class GuiCreateWorld extends GuiScreen
{
private GuiScreen parentGuiScreen;
private GuiTextField textboxWorldName;
private GuiTextField textboxSeed;
private String folderName;
/** hardcore', 'creative' or 'survival */
private String gameMode = "survival";
private boolean generateStructures = true;
private boolean commandsAllowed;
/** True iif player has clicked buttonAllowCommands at least once */
private boolean commandsToggled;
/** toggles when GUIButton 7 is pressed */
private boolean bonusItems;
/** True if and only if gameMode.equals("hardcore") */
private boolean isHardcore;
private boolean createClicked;
/**
* True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown
*/
private boolean moreOptions;
/** The GUIButton that you click to change game modes. */
private GuiButton buttonGameMode;
/**
* The GUIButton that you click to get to options like the seed when creating a world.
*/
private GuiButton moreWorldOptions;
/** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */
private GuiButton buttonGenerateStructures;
private GuiButton buttonBonusItems;
/** The GuiButton in the more world options screen. */
private GuiButton buttonWorldType;
private GuiButton buttonAllowCommands;
/** GuiButton in the more world options screen. */
private GuiButton buttonCustomize;
/** The first line of text describing the currently selected game mode. */
private String gameModeDescriptionLine1;
/** The second line of text describing the currently selected game mode. */
private String gameModeDescriptionLine2;
/** The current textboxSeed text */
private String seed;
/** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */
private String localizedNewWorldText;
private int worldTypeId;
/** Generator options to use when creating the world. */
public String generatorOptionsToUse = "";
/**
* If the world name is one of these, it'll be surrounded with underscores.
*/
private static final String[] ILLEGAL_WORLD_NAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"};
public GuiCreateWorld(GuiScreen par1GuiScreen)
{
this.parentGuiScreen = par1GuiScreen;
this.seed = "";
this.localizedNewWorldText = I18n.getString("selectWorld.newWorld");
}
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
this.textboxWorldName.updateCursorCounter();
this.textboxSeed.updateCursorCounter();
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
public void initGui()
{
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.getString("selectWorld.create")));
this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.getString("gui.cancel")));
this.buttonList.add(this.buttonGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.getString("selectWorld.gameMode")));
this.buttonList.add(this.moreWorldOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.getString("selectWorld.moreWorldOptions")));
this.buttonList.add(this.buttonGenerateStructures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.getString("selectWorld.mapFeatures")));
this.buttonGenerateStructures.drawButton = false;
this.buttonList.add(this.buttonBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.getString("selectWorld.bonusItems")));
this.buttonBonusItems.drawButton = false;
this.buttonList.add(this.buttonWorldType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.getString("selectWorld.mapType")));
this.buttonWorldType.drawButton = false;
this.buttonList.add(this.buttonAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.getString("selectWorld.allowCommands")));
this.buttonAllowCommands.drawButton = false;
this.buttonList.add(this.buttonCustomize = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.getString("selectWorld.customizeType")));
this.buttonCustomize.drawButton = false;
this.textboxWorldName = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20);
this.textboxWorldName.setFocused(true);
this.textboxWorldName.setText(this.localizedNewWorldText);
this.textboxSeed = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20);
this.textboxSeed.setText(this.seed);
this.func_82288_a(this.moreOptions);
this.makeUseableName();
this.updateButtonText();
}
/**
* Makes a the name for a world save folder based on your world name, replacing specific characters for _s and
* appending -s to the end until a free name is available.
*/
private void makeUseableName()
{
this.folderName = this.textboxWorldName.getText().trim();
char[] var1 = ChatAllowedCharacters.allowedCharactersArray;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3)
{
char var4 = var1[var3];
this.folderName = this.folderName.replace(var4, '_');
}
if (MathHelper.stringNullOrLengthZero(this.folderName))
{
this.folderName = "World";
}
this.folderName = func_73913_a(this.mc.getSaveLoader(), this.folderName);
}
private void updateButtonText()
{
this.buttonGameMode.displayString = I18n.getString("selectWorld.gameMode") + " " + I18n.getString("selectWorld.gameMode." + this.gameMode);
this.gameModeDescriptionLine1 = I18n.getString("selectWorld.gameMode." + this.gameMode + ".line1");
this.gameModeDescriptionLine2 = I18n.getString("selectWorld.gameMode." + this.gameMode + ".line2");
this.buttonGenerateStructures.displayString = I18n.getString("selectWorld.mapFeatures") + " ";
if (this.generateStructures)
{
this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.getString("options.on");
}
else
{
this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.getString("options.off");
}
this.buttonBonusItems.displayString = I18n.getString("selectWorld.bonusItems") + " ";
if (this.bonusItems && !this.isHardcore)
{
this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.getString("options.on");
}
else
{
this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.getString("options.off");
}
this.buttonWorldType.displayString = I18n.getString("selectWorld.mapType") + " " + I18n.getString(WorldType.worldTypes[this.worldTypeId].getTranslateName());
this.buttonAllowCommands.displayString = I18n.getString("selectWorld.allowCommands") + " ";
if (this.commandsAllowed && !this.isHardcore)
{
this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.getString("options.on");
}
else
{
this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.getString("options.off");
}
}
public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str)
{
par1Str = par1Str.replaceAll("[\\./\"]", "_");
String[] var2 = ILLEGAL_WORLD_NAMES;
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4)
{
String var5 = var2[var4];
if (par1Str.equalsIgnoreCase(var5))
{
par1Str = "_" + par1Str + "_";
}
}
while (par0ISaveFormat.getWorldInfo(par1Str) != null)
{
par1Str = par1Str + "-";
}
return par1Str;
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
/**
* Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).
*/
protected void actionPerformed(GuiButton par1GuiButton)
{
if (par1GuiButton.enabled)
{
if (par1GuiButton.id == 1)
{
this.mc.displayGuiScreen(this.parentGuiScreen);
}
else if (par1GuiButton.id == 0)
{
this.mc.displayGuiScreen((GuiScreen)null);
if (this.createClicked)
{
return;
}
this.createClicked = true;
long var2 = (new Random()).nextLong();
String var4 = this.textboxSeed.getText();
if (!MathHelper.stringNullOrLengthZero(var4))
{
try
{
long var5 = Long.parseLong(var4);
if (var5 != 0L)
{
var2 = var5;
}
}
catch (NumberFormatException var7)
{
var2 = (long)var4.hashCode();
}
}
EnumGameType var8 = EnumGameType.getByName(this.gameMode);
WorldSettings var6 = new WorldSettings(var2, var8, this.generateStructures, this.isHardcore, WorldType.worldTypes[this.worldTypeId]);
var6.func_82750_a(this.generatorOptionsToUse);
if (this.bonusItems && !this.isHardcore)
{
var6.enableBonusChest();
}
if (this.commandsAllowed && !this.isHardcore)
{
var6.enableCommands();
}
this.mc.launchIntegratedServer(this.folderName, this.textboxWorldName.getText().trim(), var6);
this.mc.statFileWriter.readStat(StatList.createWorldStat, 1);
}
else if (par1GuiButton.id == 3)
{
this.func_82287_i();
}
else if (par1GuiButton.id == 2)
{
if (this.gameMode.equals("survival"))
{
if (!this.commandsToggled)
{
this.commandsAllowed = false;
}
this.isHardcore = false;
this.gameMode = "hardcore";
this.isHardcore = true;
this.buttonAllowCommands.enabled = false;
this.buttonBonusItems.enabled = false;
this.updateButtonText();
}
else if (this.gameMode.equals("hardcore"))
{
if (!this.commandsToggled)
{
this.commandsAllowed = true;
}
this.isHardcore = false;
this.gameMode = "creative";
this.updateButtonText();
this.isHardcore = false;
this.buttonAllowCommands.enabled = true;
this.buttonBonusItems.enabled = true;
}
else
{
if (!this.commandsToggled)
{
this.commandsAllowed = false;
}
this.gameMode = "survival";
this.updateButtonText();
this.buttonAllowCommands.enabled = true;
this.buttonBonusItems.enabled = true;
this.isHardcore = false;
}
this.updateButtonText();
}
else if (par1GuiButton.id == 4)
{
this.generateStructures = !this.generateStructures;
this.updateButtonText();
}
else if (par1GuiButton.id == 7)
{
this.bonusItems = !this.bonusItems;
this.updateButtonText();
}
else if (par1GuiButton.id == 5)
{
++this.worldTypeId;
if (this.worldTypeId >= WorldType.worldTypes.length)
{
this.worldTypeId = 0;
}
while (WorldType.worldTypes[this.worldTypeId] == null || !WorldType.worldTypes[this.worldTypeId].getCanBeCreated())
{
++this.worldTypeId;
if (this.worldTypeId >= WorldType.worldTypes.length)
{
this.worldTypeId = 0;
}
}
this.generatorOptionsToUse = "";
this.updateButtonText();
this.func_82288_a(this.moreOptions);
}
else if (par1GuiButton.id == 6)
{
this.commandsToggled = true;
this.commandsAllowed = !this.commandsAllowed;
this.updateButtonText();
}
else if (par1GuiButton.id == 8)
{
this.mc.displayGuiScreen(new GuiCreateFlatWorld(this, this.generatorOptionsToUse));
}
}
}
private void func_82287_i()
{
this.func_82288_a(!this.moreOptions);
}
private void func_82288_a(boolean par1)
{
this.moreOptions = par1;
this.buttonGameMode.drawButton = !this.moreOptions;
this.buttonGenerateStructures.drawButton = this.moreOptions;
this.buttonBonusItems.drawButton = this.moreOptions;
this.buttonWorldType.drawButton = this.moreOptions;
this.buttonAllowCommands.drawButton = this.moreOptions;
this.buttonCustomize.drawButton = this.moreOptions && WorldType.worldTypes[this.worldTypeId] == WorldType.FLAT;
if (this.moreOptions)
{
this.moreWorldOptions.displayString = I18n.getString("gui.done");
}
else
{
this.moreWorldOptions.displayString = I18n.getString("selectWorld.moreWorldOptions");
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
protected void keyTyped(char par1, int par2)
{
if (this.textboxWorldName.isFocused() && !this.moreOptions)
{
this.textboxWorldName.textboxKeyTyped(par1, par2);
this.localizedNewWorldText = this.textboxWorldName.getText();
}
else if (this.textboxSeed.isFocused() && this.moreOptions)
{
this.textboxSeed.textboxKeyTyped(par1, par2);
this.seed = this.textboxSeed.getText();
}
if (par2 == 28 || par2 == 156)
{
this.actionPerformed((GuiButton)this.buttonList.get(0));
}
((GuiButton)this.buttonList.get(0)).enabled = this.textboxWorldName.getText().length() > 0;
this.makeUseableName();
}
/**
* Called when the mouse is clicked.
*/
protected void mouseClicked(int par1, int par2, int par3)
{
super.mouseClicked(par1, par2, par3);
if (this.moreOptions)
{
this.textboxSeed.mouseClicked(par1, par2, par3);
}
else
{
this.textboxWorldName.mouseClicked(par1, par2, par3);
}
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3)
{
this.drawDefaultBackground();
this.drawCenteredString(this.fontRenderer, I18n.getString("selectWorld.create"), this.width / 2, 20, 16777215);
if (this.moreOptions)
{
this.drawString(this.fontRenderer, I18n.getString("selectWorld.enterSeed"), this.width / 2 - 100, 47, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.seedInfo"), this.width / 2 - 100, 85, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.mapFeatures.info"), this.width / 2 - 150, 122, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.allowCommands.info"), this.width / 2 - 150, 172, 10526880);
this.textboxSeed.drawTextBox();
}
else
{
this.drawString(this.fontRenderer, I18n.getString("selectWorld.enterName"), this.width / 2 - 100, 47, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.resultFolder") + " " + this.folderName, this.width / 2 - 100, 85, 10526880);
this.textboxWorldName.drawTextBox();
this.drawString(this.fontRenderer, this.gameModeDescriptionLine1, this.width / 2 - 100, 137, 10526880);
this.drawString(this.fontRenderer, this.gameModeDescriptionLine2, this.width / 2 - 100, 149, 10526880);
}
super.drawScreen(par1, par2, par3);
}
public void func_82286_a(WorldInfo par1WorldInfo)
{
this.localizedNewWorldText = I18n.getStringParams("selectWorld.newWorld.copyOf", new Object[] {par1WorldInfo.getWorldName()});
this.seed = par1WorldInfo.getSeed() + "";
this.worldTypeId = par1WorldInfo.getTerrainType().getWorldTypeID();
this.generatorOptionsToUse = par1WorldInfo.getGeneratorOptions();
this.generateStructures = par1WorldInfo.isMapFeaturesEnabled();
this.commandsAllowed = par1WorldInfo.areCommandsAllowed();
if (par1WorldInfo.isHardcoreModeEnabled())
{
this.gameMode = "hardcore";
}
else if (par1WorldInfo.getGameType().isSurvivalOrAdventure())
{
this.gameMode = "survival";
}
else if (par1WorldInfo.getGameType().isCreative())
{
this.gameMode = "creative";
}
}
}
| KingYeezus/Yeezus-1.6 | minecraft/net/minecraft/src/GuiCreateWorld.java | 5,557 | /** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */ | block_comment | nl | package net.minecraft.src;
import java.util.Random;
import org.lwjgl.input.Keyboard;
public class GuiCreateWorld extends GuiScreen
{
private GuiScreen parentGuiScreen;
private GuiTextField textboxWorldName;
private GuiTextField textboxSeed;
private String folderName;
/** hardcore', 'creative' or 'survival */
private String gameMode = "survival";
private boolean generateStructures = true;
private boolean commandsAllowed;
/** True iif player has clicked buttonAllowCommands at least once */
private boolean commandsToggled;
/** toggles when GUIButton 7 is pressed */
private boolean bonusItems;
/** True if and only if gameMode.equals("hardcore") */
private boolean isHardcore;
private boolean createClicked;
/**
* True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown
*/
private boolean moreOptions;
/** The GUIButton that you click to change game modes. */
private GuiButton buttonGameMode;
/**
* The GUIButton that you click to get to options like the seed when creating a world.
*/
private GuiButton moreWorldOptions;
/** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */
private GuiButton buttonGenerateStructures;
private GuiButton buttonBonusItems;
/** The GuiButton in the more world options screen. */
private GuiButton buttonWorldType;
private GuiButton buttonAllowCommands;
/** GuiButton in the more world options screen. */
private GuiButton buttonCustomize;
/** The first line of text describing the currently selected game mode. */
private String gameModeDescriptionLine1;
/** The second line of text describing the currently selected game mode. */
private String gameModeDescriptionLine2;
/** The current textboxSeed text */
private String seed;
/** E.g. New World,<SUF>*/
private String localizedNewWorldText;
private int worldTypeId;
/** Generator options to use when creating the world. */
public String generatorOptionsToUse = "";
/**
* If the world name is one of these, it'll be surrounded with underscores.
*/
private static final String[] ILLEGAL_WORLD_NAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"};
public GuiCreateWorld(GuiScreen par1GuiScreen)
{
this.parentGuiScreen = par1GuiScreen;
this.seed = "";
this.localizedNewWorldText = I18n.getString("selectWorld.newWorld");
}
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
this.textboxWorldName.updateCursorCounter();
this.textboxSeed.updateCursorCounter();
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
public void initGui()
{
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.getString("selectWorld.create")));
this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.getString("gui.cancel")));
this.buttonList.add(this.buttonGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.getString("selectWorld.gameMode")));
this.buttonList.add(this.moreWorldOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.getString("selectWorld.moreWorldOptions")));
this.buttonList.add(this.buttonGenerateStructures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.getString("selectWorld.mapFeatures")));
this.buttonGenerateStructures.drawButton = false;
this.buttonList.add(this.buttonBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.getString("selectWorld.bonusItems")));
this.buttonBonusItems.drawButton = false;
this.buttonList.add(this.buttonWorldType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.getString("selectWorld.mapType")));
this.buttonWorldType.drawButton = false;
this.buttonList.add(this.buttonAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.getString("selectWorld.allowCommands")));
this.buttonAllowCommands.drawButton = false;
this.buttonList.add(this.buttonCustomize = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.getString("selectWorld.customizeType")));
this.buttonCustomize.drawButton = false;
this.textboxWorldName = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20);
this.textboxWorldName.setFocused(true);
this.textboxWorldName.setText(this.localizedNewWorldText);
this.textboxSeed = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20);
this.textboxSeed.setText(this.seed);
this.func_82288_a(this.moreOptions);
this.makeUseableName();
this.updateButtonText();
}
/**
* Makes a the name for a world save folder based on your world name, replacing specific characters for _s and
* appending -s to the end until a free name is available.
*/
private void makeUseableName()
{
this.folderName = this.textboxWorldName.getText().trim();
char[] var1 = ChatAllowedCharacters.allowedCharactersArray;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3)
{
char var4 = var1[var3];
this.folderName = this.folderName.replace(var4, '_');
}
if (MathHelper.stringNullOrLengthZero(this.folderName))
{
this.folderName = "World";
}
this.folderName = func_73913_a(this.mc.getSaveLoader(), this.folderName);
}
private void updateButtonText()
{
this.buttonGameMode.displayString = I18n.getString("selectWorld.gameMode") + " " + I18n.getString("selectWorld.gameMode." + this.gameMode);
this.gameModeDescriptionLine1 = I18n.getString("selectWorld.gameMode." + this.gameMode + ".line1");
this.gameModeDescriptionLine2 = I18n.getString("selectWorld.gameMode." + this.gameMode + ".line2");
this.buttonGenerateStructures.displayString = I18n.getString("selectWorld.mapFeatures") + " ";
if (this.generateStructures)
{
this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.getString("options.on");
}
else
{
this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.getString("options.off");
}
this.buttonBonusItems.displayString = I18n.getString("selectWorld.bonusItems") + " ";
if (this.bonusItems && !this.isHardcore)
{
this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.getString("options.on");
}
else
{
this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.getString("options.off");
}
this.buttonWorldType.displayString = I18n.getString("selectWorld.mapType") + " " + I18n.getString(WorldType.worldTypes[this.worldTypeId].getTranslateName());
this.buttonAllowCommands.displayString = I18n.getString("selectWorld.allowCommands") + " ";
if (this.commandsAllowed && !this.isHardcore)
{
this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.getString("options.on");
}
else
{
this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.getString("options.off");
}
}
public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str)
{
par1Str = par1Str.replaceAll("[\\./\"]", "_");
String[] var2 = ILLEGAL_WORLD_NAMES;
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4)
{
String var5 = var2[var4];
if (par1Str.equalsIgnoreCase(var5))
{
par1Str = "_" + par1Str + "_";
}
}
while (par0ISaveFormat.getWorldInfo(par1Str) != null)
{
par1Str = par1Str + "-";
}
return par1Str;
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
/**
* Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).
*/
protected void actionPerformed(GuiButton par1GuiButton)
{
if (par1GuiButton.enabled)
{
if (par1GuiButton.id == 1)
{
this.mc.displayGuiScreen(this.parentGuiScreen);
}
else if (par1GuiButton.id == 0)
{
this.mc.displayGuiScreen((GuiScreen)null);
if (this.createClicked)
{
return;
}
this.createClicked = true;
long var2 = (new Random()).nextLong();
String var4 = this.textboxSeed.getText();
if (!MathHelper.stringNullOrLengthZero(var4))
{
try
{
long var5 = Long.parseLong(var4);
if (var5 != 0L)
{
var2 = var5;
}
}
catch (NumberFormatException var7)
{
var2 = (long)var4.hashCode();
}
}
EnumGameType var8 = EnumGameType.getByName(this.gameMode);
WorldSettings var6 = new WorldSettings(var2, var8, this.generateStructures, this.isHardcore, WorldType.worldTypes[this.worldTypeId]);
var6.func_82750_a(this.generatorOptionsToUse);
if (this.bonusItems && !this.isHardcore)
{
var6.enableBonusChest();
}
if (this.commandsAllowed && !this.isHardcore)
{
var6.enableCommands();
}
this.mc.launchIntegratedServer(this.folderName, this.textboxWorldName.getText().trim(), var6);
this.mc.statFileWriter.readStat(StatList.createWorldStat, 1);
}
else if (par1GuiButton.id == 3)
{
this.func_82287_i();
}
else if (par1GuiButton.id == 2)
{
if (this.gameMode.equals("survival"))
{
if (!this.commandsToggled)
{
this.commandsAllowed = false;
}
this.isHardcore = false;
this.gameMode = "hardcore";
this.isHardcore = true;
this.buttonAllowCommands.enabled = false;
this.buttonBonusItems.enabled = false;
this.updateButtonText();
}
else if (this.gameMode.equals("hardcore"))
{
if (!this.commandsToggled)
{
this.commandsAllowed = true;
}
this.isHardcore = false;
this.gameMode = "creative";
this.updateButtonText();
this.isHardcore = false;
this.buttonAllowCommands.enabled = true;
this.buttonBonusItems.enabled = true;
}
else
{
if (!this.commandsToggled)
{
this.commandsAllowed = false;
}
this.gameMode = "survival";
this.updateButtonText();
this.buttonAllowCommands.enabled = true;
this.buttonBonusItems.enabled = true;
this.isHardcore = false;
}
this.updateButtonText();
}
else if (par1GuiButton.id == 4)
{
this.generateStructures = !this.generateStructures;
this.updateButtonText();
}
else if (par1GuiButton.id == 7)
{
this.bonusItems = !this.bonusItems;
this.updateButtonText();
}
else if (par1GuiButton.id == 5)
{
++this.worldTypeId;
if (this.worldTypeId >= WorldType.worldTypes.length)
{
this.worldTypeId = 0;
}
while (WorldType.worldTypes[this.worldTypeId] == null || !WorldType.worldTypes[this.worldTypeId].getCanBeCreated())
{
++this.worldTypeId;
if (this.worldTypeId >= WorldType.worldTypes.length)
{
this.worldTypeId = 0;
}
}
this.generatorOptionsToUse = "";
this.updateButtonText();
this.func_82288_a(this.moreOptions);
}
else if (par1GuiButton.id == 6)
{
this.commandsToggled = true;
this.commandsAllowed = !this.commandsAllowed;
this.updateButtonText();
}
else if (par1GuiButton.id == 8)
{
this.mc.displayGuiScreen(new GuiCreateFlatWorld(this, this.generatorOptionsToUse));
}
}
}
private void func_82287_i()
{
this.func_82288_a(!this.moreOptions);
}
private void func_82288_a(boolean par1)
{
this.moreOptions = par1;
this.buttonGameMode.drawButton = !this.moreOptions;
this.buttonGenerateStructures.drawButton = this.moreOptions;
this.buttonBonusItems.drawButton = this.moreOptions;
this.buttonWorldType.drawButton = this.moreOptions;
this.buttonAllowCommands.drawButton = this.moreOptions;
this.buttonCustomize.drawButton = this.moreOptions && WorldType.worldTypes[this.worldTypeId] == WorldType.FLAT;
if (this.moreOptions)
{
this.moreWorldOptions.displayString = I18n.getString("gui.done");
}
else
{
this.moreWorldOptions.displayString = I18n.getString("selectWorld.moreWorldOptions");
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
protected void keyTyped(char par1, int par2)
{
if (this.textboxWorldName.isFocused() && !this.moreOptions)
{
this.textboxWorldName.textboxKeyTyped(par1, par2);
this.localizedNewWorldText = this.textboxWorldName.getText();
}
else if (this.textboxSeed.isFocused() && this.moreOptions)
{
this.textboxSeed.textboxKeyTyped(par1, par2);
this.seed = this.textboxSeed.getText();
}
if (par2 == 28 || par2 == 156)
{
this.actionPerformed((GuiButton)this.buttonList.get(0));
}
((GuiButton)this.buttonList.get(0)).enabled = this.textboxWorldName.getText().length() > 0;
this.makeUseableName();
}
/**
* Called when the mouse is clicked.
*/
protected void mouseClicked(int par1, int par2, int par3)
{
super.mouseClicked(par1, par2, par3);
if (this.moreOptions)
{
this.textboxSeed.mouseClicked(par1, par2, par3);
}
else
{
this.textboxWorldName.mouseClicked(par1, par2, par3);
}
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3)
{
this.drawDefaultBackground();
this.drawCenteredString(this.fontRenderer, I18n.getString("selectWorld.create"), this.width / 2, 20, 16777215);
if (this.moreOptions)
{
this.drawString(this.fontRenderer, I18n.getString("selectWorld.enterSeed"), this.width / 2 - 100, 47, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.seedInfo"), this.width / 2 - 100, 85, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.mapFeatures.info"), this.width / 2 - 150, 122, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.allowCommands.info"), this.width / 2 - 150, 172, 10526880);
this.textboxSeed.drawTextBox();
}
else
{
this.drawString(this.fontRenderer, I18n.getString("selectWorld.enterName"), this.width / 2 - 100, 47, 10526880);
this.drawString(this.fontRenderer, I18n.getString("selectWorld.resultFolder") + " " + this.folderName, this.width / 2 - 100, 85, 10526880);
this.textboxWorldName.drawTextBox();
this.drawString(this.fontRenderer, this.gameModeDescriptionLine1, this.width / 2 - 100, 137, 10526880);
this.drawString(this.fontRenderer, this.gameModeDescriptionLine2, this.width / 2 - 100, 149, 10526880);
}
super.drawScreen(par1, par2, par3);
}
public void func_82286_a(WorldInfo par1WorldInfo)
{
this.localizedNewWorldText = I18n.getStringParams("selectWorld.newWorld.copyOf", new Object[] {par1WorldInfo.getWorldName()});
this.seed = par1WorldInfo.getSeed() + "";
this.worldTypeId = par1WorldInfo.getTerrainType().getWorldTypeID();
this.generatorOptionsToUse = par1WorldInfo.getGeneratorOptions();
this.generateStructures = par1WorldInfo.isMapFeaturesEnabled();
this.commandsAllowed = par1WorldInfo.areCommandsAllowed();
if (par1WorldInfo.isHardcoreModeEnabled())
{
this.gameMode = "hardcore";
}
else if (par1WorldInfo.getGameType().isSurvivalOrAdventure())
{
this.gameMode = "survival";
}
else if (par1WorldInfo.getGameType().isCreative())
{
this.gameMode = "creative";
}
}
}
|
135309_0 |
class Solution{
static int ans=0;
static int ladoos(Node root, int home, int k){
// Your code goes here
ans=0;
solve(root, home,k);
return ans;
}
static int solve(Node root, int home, int k)
{
if(root==null) return -1;
if(root.data==home)
{
add(root,k);
return k-1;
}
int rem = solve(root.right, home, k);
if(rem>=0)
{
ans+=root.data;
add(root.left, rem-1);
return rem-1;
}
rem = solve(root.left, home, k);
if(rem>=0)
{
ans+=root.data;
add(root.right, rem-1);
return rem-1;
}
return -1;
}
static void add(Node n, int dist){
if( (n==null) || (dist<0) ) return;
ans += n.data;
add(n.left, dist-1);
add(n.right, dist-1);
}
}
| Kishanpandey2/Problem-of-the-day-of-Leetcode-and-GeeksForGeeks | Bheem Wants Ladoos/Bheem Wants Ladoos.java | 334 | // Your code goes here | line_comment | nl |
class Solution{
static int ans=0;
static int ladoos(Node root, int home, int k){
// Your code<SUF>
ans=0;
solve(root, home,k);
return ans;
}
static int solve(Node root, int home, int k)
{
if(root==null) return -1;
if(root.data==home)
{
add(root,k);
return k-1;
}
int rem = solve(root.right, home, k);
if(rem>=0)
{
ans+=root.data;
add(root.left, rem-1);
return rem-1;
}
rem = solve(root.left, home, k);
if(rem>=0)
{
ans+=root.data;
add(root.right, rem-1);
return rem-1;
}
return -1;
}
static void add(Node n, int dist){
if( (n==null) || (dist<0) ) return;
ans += n.data;
add(n.left, dist-1);
add(n.right, dist-1);
}
}
|
179557_7 | package com.kleegroup.lord.moteur;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Logger;
import com.kleegroup.lord.config.xml.ObjectFactory;
import com.kleegroup.lord.config.xml.TypeSchema;
import com.kleegroup.lord.moteur.Fichier.ETAT;
import com.kleegroup.lord.moteur.config.ObjXmlTransformer;
import com.kleegroup.lord.moteur.config.XmlObjTransformer;
import com.kleegroup.lord.moteur.exceptions.EchecCreationLogs;
import com.kleegroup.lord.moteur.logs.ILogger;
import com.kleegroup.lord.moteur.logs.LoggueurFichierCSV;
import com.kleegroup.lord.moteur.logs.LoggueurMultiple;
import com.kleegroup.lord.moteur.logs.LoggueurRam;
import com.kleegroup.lord.moteur.reader.CsvReaderAdapter;
import com.kleegroup.lord.moteur.util.FichierComparteurGroupe;
import com.kleegroup.lord.moteur.util.FichierComparteurOrdreTopo;
import com.kleegroup.lord.moteur.util.ICSVDataSource;
import com.kleegroup.lord.moteur.util.INotifiable;
import com.kleegroup.lord.moteur.util.LogFilesZipper;
import com.kleegroup.lord.moteur.util.SeparateurChamps;
import com.kleegroup.lord.moteur.util.SeparateurDecimales;
/**
* Sert a ordonner les fichier selon leur dependeances.<br>
* voir http://en.wikipedia.org/wiki/Topological_sorting
*/
public class Schema implements INotifiable {
private static org.apache.log4j.Logger logAppli = Logger.getLogger(Schema.class);
protected List<Fichier> fichiers = new ArrayList<>();
protected int niveauActuel = -1;
protected Map<String, ILogger> loggeurs = new HashMap<>();
protected INotifiable eltANotifier = null;
protected String encoding;
protected String separateurLignes;
protected String charEchapGuillemets;
protected boolean ignorerGuillemets;
protected boolean afficherExportLogs;
protected Categories categories = new Categories();
protected SeparateurChamps separateurChamp = SeparateurChamps.SEPARATEUR_POINT_VIRGULE;
protected SeparateurDecimales separateurDecimales = SeparateurDecimales.SEPARATEUR_VIRGULE;
List<String> listCheminFichiersLog = new ArrayList<>();
private Fichier fichierEnCours;
private String emplacementFichiersLogs = "./logs/";
private final SortedMap<Integer, HashSet<Fichier>> groupes = new TreeMap<>();
private File fichierLogGeneral;
private PrintStream loggueurGeneral = null;
private Date dateDebut = null;
/**
* Ajoute le fichier au schema, en fin de la liste des fichiers.
*
* @param f fichier a rajouter au schema
*/
public void addFichier(Fichier f) {
addFichier(f, fichiers.size());
}
/**
* Ajoute le fichier f au schema � la position pos.
*
* @param f
* fichier a rajouter au schema
* @param pos
* la position du fichier
*/
public void addFichier(Fichier f, int pos) {
fichiers.add(pos, f);
categories.put(f, f.getNomCategorie());
}
/**
* Met en pause la vérification du fichier actuel. La vérification peut continuer
* en appelant {@link #resume()}
*/
public void pause() {
fichierEnCours.pause();
}
/**
* Lance la vérification du schéma.
*/
public void verifie() {
logAppli.info("debut de la verification du schema");
clean();
for (final Fichier f : fichiers) {
if (f.getGroupe() <= niveauActuel && f.isPretVerif()) {
creerSourceDonnee(f);// ouvre le fichier CSV en lecture
fichierEnCours = f;
f.verifie();
marquerFichierVerifie(f);
System.out.println(f.getNom() + " " + f.getEtatFichier());
if (f.getEtatFichier() == ETAT.ABANDONNE_UTILISATEUR) {
for (final Fichier f2 : fichiers) {
if (f2.isEnabled()) {
f2.setEtatFichier(ETAT.ABANDONNE_UTILISATEUR);
finFichier(f2.getNom(), f2.getEtatFichier());
}
}
return;
}
} else {
// signaler l'echec de la verification a cause d'un
// fichier dependant non verifie
if (f.getEtatFichier() == ETAT.EN_ATTENTE) {
f.abandonFichier(ETAT.ABANDONNE_DEPENDANCE);
}
}
}
creerLogGeneral();
logAppli.info("fin de la verification du schema");
}
private void creerSourceDonnee(Fichier f) {
final ICSVDataSource source = new CsvReaderAdapter(f.getChemin(), encoding);
source.setFieldSeparator(separateurChamp.value());
f.setSource(source);
}
/**
* Nettoie l'objet. Remet à zero les données spécifiques utilisées lors de la
* dernière vérification pour pouvoir réutiliser cet objet pour une nouvelle
* vérification
*/
public void clean() {
niveauActuel = 0;
for (final Fichier f : fichiers) {
f.clean();
}
trierLesFichiers();
calculGroupesDisponibles();
try {
creerDossierEtFichiersLogs();
initialiserLesFichiers();
} catch (final Exception e) {
logAppli.error(e);
}
}
private void marquerFichierVerifie(Fichier f) {
/*
* supprimer le fichier de son groupe.cela permet de determiner quand
* tous les fichiers d'un groupe ont ete verifie et de passer au groupe
* suivant
*/
groupes.get(f.getGroupe()).remove(f);
if (groupes.get(f.getGroupe()).isEmpty()) {
groupes.remove(f.getGroupe());
try {
if (!groupes.isEmpty()) {
niveauActuel = groupes.firstKey();
}
} catch (final NoSuchElementException ex) {
logAppli.error(ex);
}
}
}
private void creerDossierEtFichiersLogs() throws EchecCreationLogs {
final File dirLog = new File(emplacementFichiersLogs);
if (!dirLog.exists()) {
if (!dirLog.mkdir()) {
throw new EchecCreationLogs();
}
}
}
private void initialiserLesFichiers() {
listCheminFichiersLog.clear();
dateDebut = Calendar.getInstance().getTime();
for (final Fichier f : fichiers) {
final LoggueurMultiple lm = new LoggueurMultiple();
lm.setNomFichier(f.getNom());
final String timestamp = (new SimpleDateFormat("yyyyMMddHHmmss")).format(dateDebut) + "-";
final String chemin = emplacementFichiersLogs + timestamp + f.getNom() + ".csv";
listCheminFichiersLog.add(chemin);
final ILogger logCSV = new LoggueurFichierCSV(chemin);
logCSV.setNomFichier(f.getNom());
final ILogger logRam = new LoggueurRam();
logRam.setNomFichier(f.getNom());
lm.addLogger(logRam);
lm.addLogger(logCSV);
f.setLogger(lm);
loggeurs.put(f.getNom(), logRam);
if (f.getEtatFichier() != Fichier.ETAT.DESACTIVE_DEPENDANCE && f.getEtatFichier() != Fichier.ETAT.DESACTIVE_UTILISATEUR) {
f.setEtatFichier(Fichier.ETAT.EN_ATTENTE);
}
}
}
private void creerLogGeneral() {
final String timestamp = (new SimpleDateFormat("yyyyMMddHHmmss")).format(dateDebut) + "-";
try {
fichierLogGeneral = File.createTempFile(timestamp + " - LogGeneral ", ".log");
try (FileOutputStream fos = new FileOutputStream(fichierLogGeneral)) {
loggueurGeneral = new PrintStream(new FileOutputStream(fichierLogGeneral));
construireLogGeneral(loggueurGeneral);
listCheminFichiersLog.add(fichierLogGeneral.getAbsolutePath());
} catch (final FileNotFoundException e) {
logAppli.error(e);
}
} catch (final IOException e) {
fichierLogGeneral = null;
logAppli.error(e);
}
}
private void construireLogGeneral(PrintStream log) {
log.println("date de debut de verification" + dateDebut);
for (final Fichier f : fichiers) {
log.println(f.getNom() + " : ETAT FINAL : " + f.getEtatFichier());
log.println(f.getNom() + " : CHEMIN : " + f.getChemin());
}
}
private void calculGroupesDisponibles() {
groupes.clear();
for (final Fichier f : fichiers) {
if (f.isEnabled()) {
if (groupes.get(f.getGroupe()) == null) {
groupes.put(f.getGroupe(), new HashSet<Fichier>());
}
groupes.get(f.getGroupe()).add(f);
}
}
}
protected void trierLesFichiers() {
// trier par ordre de dependance (ordre "topologique")
/* voir Fichier#getNiveauTopo */
Collections.sort(fichiers, new FichierComparteurOrdreTopo());
// trier les fichiers par ordre de groupe(d�fini dans les specs)
Collections.sort(fichiers, new FichierComparteurGroupe());
niveauActuel = fichiers.get(0).getGroupe();
}
/**
* @return la liste des fichier du schema.
*/
public List<Fichier> getFichiers() {
return fichiers;
}
/**
* Ecrit le schema dans un fichier XML.
*
* @param path
* le chemin d'acces du fichier XML
* @throws JAXBException
* si la conversion de l'XML en schema objet en XML
*/
public void toXml(FileOutputStream path) throws JAXBException {
final JAXBContext context = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
final Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal((new ObjXmlTransformer()).transform(this), path);
}
/**
* renvoie le fichier identifie par ce nom.
*
* @param nom
* le nom du fichier
* @return le fichier correspondant
*/
public Fichier getFichier(String nom) {
for (final Fichier f : fichiers) {
if (nom.equals(f.getNom())) {
return f;
}
}
return null;
}
/**
* Construit un schema a partir d'un XML lu dans inputStream.
*
* @param inputStream
* sert a lire le fichier
* @return le schema XML
* @throws JAXBException
* si la conversion à partir du XML échoue
*/
public static Schema fromXML(InputStream inputStream) throws JAXBException {
final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
final Unmarshaller u = jc.createUnmarshaller();
final JAXBElement<?> schemaXML = (JAXBElement<?>) u.unmarshal(inputStream);
final XmlObjTransformer trans = new XmlObjTransformer();
try {
inputStream.close();
} catch (final IOException e) {
logAppli.error(e);
}
return trans.transform((TypeSchema) schemaXML.getValue());
}
/**
* @return une map contenant les logueurs(la liste des erreurs) de chaque
* fichier
*/
public Map<String, ILogger> getLoggeurs() {
return loggeurs;
}
/** {@inheritDoc} */
@Override
public void finFichier(String nomFichier, ETAT etat) {
if (eltANotifier != null) {
eltANotifier.finFichier(nomFichier, etat);
}
}
/** {@inheritDoc} */
@Override
public void caractereTraites(long nbCaracteres) {
if (eltANotifier != null) {
eltANotifier.caractereTraites(nbCaracteres);
}
}
/** {@inheritDoc} */
@Override
public void debutFichier(String nomFichier) {
if (eltANotifier != null) {
eltANotifier.debutFichier(nomFichier);
}
}
/**
* désigne l'objet à notifier lorsque certains �venements (voir
* {@link INotifiable}) ont lieu.
*
* @param eltANotifier
* l'objet à notifier
*/
public void setEltANotifier(INotifiable eltANotifier) {
this.eltANotifier = eltANotifier;
for (final Fichier f : fichiers) {
f.setEltAnotifier(eltANotifier);
}
}
/**
* Reprend la v�rification si elle est en pause. voir {@link #pause()}.
*/
public void resume() {
fichierEnCours.resume();
}
/**
* Annule la v�rification du fichier en cours.
*/
public void cancel() {
fichierEnCours.cancel();
}
/**
* @return le repertoire o� seront sauvegard�s les fichiers de logs.
*/
public String getEmplacementFichiersLogs() {
return emplacementFichiersLogs;
}
/**
* @param emplacementFichiersLogs
* repertoire o� seront sauvegard�s les fichiers de logs.
*/
public void setEmplacementFichiersLogs(String emplacementFichiersLogs) {
this.emplacementFichiersLogs = emplacementFichiersLogs;
}
/**
* active ou d�sactive un fichier.
*
* @param nom
* le nom du fichier a activer
* @param etat
* true s'il faut l'activer, false sinon
*/
public void setEnabledFichier(String nom, boolean etat) {
final Fichier f = getFichier(nom);
if (etat) {
f.setEtatFichier(ETAT.EN_ATTENTE);
reactiverDependancesAncetres(f);
} else {
f.setEtatFichier(ETAT.DESACTIVE_UTILISATEUR);
desactiverDependances(f);
}
}
private void desactiverDependances(Fichier f) {
for (final Fichier dependant : f.getFichiersQuiDependentDeNous()) {
if (dependant.getEtatFichier() == ETAT.EN_ATTENTE) {
dependant.setEtatFichier(ETAT.DESACTIVE_UTILISATEUR);
desactiverDependances(dependant);
}
}
}
private void reactiverDependancesAncetres(Fichier f) {
for (final Fichier onEnDepend : f.getFichiersDontOnDepend()) {
onEnDepend.setEtatFichier(ETAT.EN_ATTENTE);
reactiverDependancesAncetres(onEnDepend);
}
}
/**
* @return le nombre de fichier non-desactiv�s dans le schema
*/
public int getNbFichiersActifs() {
int nb = 0;
for (final Fichier f : fichiers) {
if (f.getEtatFichier() == ETAT.EN_ATTENTE) {
nb++;
}
}
return nb;
}
/**
* @return l'encodage des fichier
*/
public String getEncoding() {
return encoding;
}
/**
* Désigne l'encodage des fichiers.
*
* @param encoding string qui désigne l'encodage des fichiers. Voir{@link Charset}.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Zip les fichiers de log dans le fichier désigné.
*
* @param outputZip le fichier destination.
* @throws IOException si une erreur d'écriture a lieu.
*/
public void zipLogFiles(File outputZip) throws IOException {
LogFilesZipper.zip(outputZip, listCheminFichiersLog);
}
/**
* @param b
* true si on veut afficher le bouton Exporter les logs dans
* l'interface utilisateur
*/
public void setAfficherExportLogs(boolean b) {
afficherExportLogs = b;
}
/**
* @return true si on veut afficher le bouton Exporter les logs dans
* l'interface utilisateur
*/
public boolean isAfficherExportLogs() {
return afficherExportLogs;
}
/** {@inheritDoc} */
@Override
public String toString() {
String s = "";
for (final Fichier f : fichiers) {
s += f.getNom() + " : " + f.getEtatFichier() + "\n";
}
return s;
}
/**
* @return le separateur de champ utilisé.
*/
public SeparateurChamps getSeparateurChamp() {
return separateurChamp;
}
/**
* @param sep le séparateur de champs à utiliser. Voir {@link SeparateurChamps}.
*/
public void setSeparateurChamp(SeparateurChamps sep) {
this.separateurChamp = sep;
}
/**
* @param sep le séparateur de décimales à utiliser. Voir {@link SeparateurDecimales}.
*/
public void setSeparateurDecimales(SeparateurDecimales sep) {
this.separateurDecimales = sep;
}
/**
* @return le separateur des décimales.
*/
public SeparateurDecimales getSeparateurDecimales() {
return separateurDecimales;
}
/**
* @return les cat�gories du sch�ma.
*/
public Categories getCategories() {
return categories;
}
/**
* Retire le fichier du sch�ma.
*
* @param f
* le fichier � retirer.
*/
public void removeFichier(Fichier f) {
fichiers.remove(f);
}
/**
* @return le nombre total de fichiers dans le sch�ma.
*/
public int getNbFichiers() {
return fichiers.size();
}
}
| KleeGroup/LORD | src/main/java/com/kleegroup/lord/moteur/Schema.java | 5,753 | // fichier dependant non verifie | line_comment | nl | package com.kleegroup.lord.moteur;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Logger;
import com.kleegroup.lord.config.xml.ObjectFactory;
import com.kleegroup.lord.config.xml.TypeSchema;
import com.kleegroup.lord.moteur.Fichier.ETAT;
import com.kleegroup.lord.moteur.config.ObjXmlTransformer;
import com.kleegroup.lord.moteur.config.XmlObjTransformer;
import com.kleegroup.lord.moteur.exceptions.EchecCreationLogs;
import com.kleegroup.lord.moteur.logs.ILogger;
import com.kleegroup.lord.moteur.logs.LoggueurFichierCSV;
import com.kleegroup.lord.moteur.logs.LoggueurMultiple;
import com.kleegroup.lord.moteur.logs.LoggueurRam;
import com.kleegroup.lord.moteur.reader.CsvReaderAdapter;
import com.kleegroup.lord.moteur.util.FichierComparteurGroupe;
import com.kleegroup.lord.moteur.util.FichierComparteurOrdreTopo;
import com.kleegroup.lord.moteur.util.ICSVDataSource;
import com.kleegroup.lord.moteur.util.INotifiable;
import com.kleegroup.lord.moteur.util.LogFilesZipper;
import com.kleegroup.lord.moteur.util.SeparateurChamps;
import com.kleegroup.lord.moteur.util.SeparateurDecimales;
/**
* Sert a ordonner les fichier selon leur dependeances.<br>
* voir http://en.wikipedia.org/wiki/Topological_sorting
*/
public class Schema implements INotifiable {
private static org.apache.log4j.Logger logAppli = Logger.getLogger(Schema.class);
protected List<Fichier> fichiers = new ArrayList<>();
protected int niveauActuel = -1;
protected Map<String, ILogger> loggeurs = new HashMap<>();
protected INotifiable eltANotifier = null;
protected String encoding;
protected String separateurLignes;
protected String charEchapGuillemets;
protected boolean ignorerGuillemets;
protected boolean afficherExportLogs;
protected Categories categories = new Categories();
protected SeparateurChamps separateurChamp = SeparateurChamps.SEPARATEUR_POINT_VIRGULE;
protected SeparateurDecimales separateurDecimales = SeparateurDecimales.SEPARATEUR_VIRGULE;
List<String> listCheminFichiersLog = new ArrayList<>();
private Fichier fichierEnCours;
private String emplacementFichiersLogs = "./logs/";
private final SortedMap<Integer, HashSet<Fichier>> groupes = new TreeMap<>();
private File fichierLogGeneral;
private PrintStream loggueurGeneral = null;
private Date dateDebut = null;
/**
* Ajoute le fichier au schema, en fin de la liste des fichiers.
*
* @param f fichier a rajouter au schema
*/
public void addFichier(Fichier f) {
addFichier(f, fichiers.size());
}
/**
* Ajoute le fichier f au schema � la position pos.
*
* @param f
* fichier a rajouter au schema
* @param pos
* la position du fichier
*/
public void addFichier(Fichier f, int pos) {
fichiers.add(pos, f);
categories.put(f, f.getNomCategorie());
}
/**
* Met en pause la vérification du fichier actuel. La vérification peut continuer
* en appelant {@link #resume()}
*/
public void pause() {
fichierEnCours.pause();
}
/**
* Lance la vérification du schéma.
*/
public void verifie() {
logAppli.info("debut de la verification du schema");
clean();
for (final Fichier f : fichiers) {
if (f.getGroupe() <= niveauActuel && f.isPretVerif()) {
creerSourceDonnee(f);// ouvre le fichier CSV en lecture
fichierEnCours = f;
f.verifie();
marquerFichierVerifie(f);
System.out.println(f.getNom() + " " + f.getEtatFichier());
if (f.getEtatFichier() == ETAT.ABANDONNE_UTILISATEUR) {
for (final Fichier f2 : fichiers) {
if (f2.isEnabled()) {
f2.setEtatFichier(ETAT.ABANDONNE_UTILISATEUR);
finFichier(f2.getNom(), f2.getEtatFichier());
}
}
return;
}
} else {
// signaler l'echec de la verification a cause d'un
// fichier dependant<SUF>
if (f.getEtatFichier() == ETAT.EN_ATTENTE) {
f.abandonFichier(ETAT.ABANDONNE_DEPENDANCE);
}
}
}
creerLogGeneral();
logAppli.info("fin de la verification du schema");
}
private void creerSourceDonnee(Fichier f) {
final ICSVDataSource source = new CsvReaderAdapter(f.getChemin(), encoding);
source.setFieldSeparator(separateurChamp.value());
f.setSource(source);
}
/**
* Nettoie l'objet. Remet à zero les données spécifiques utilisées lors de la
* dernière vérification pour pouvoir réutiliser cet objet pour une nouvelle
* vérification
*/
public void clean() {
niveauActuel = 0;
for (final Fichier f : fichiers) {
f.clean();
}
trierLesFichiers();
calculGroupesDisponibles();
try {
creerDossierEtFichiersLogs();
initialiserLesFichiers();
} catch (final Exception e) {
logAppli.error(e);
}
}
private void marquerFichierVerifie(Fichier f) {
/*
* supprimer le fichier de son groupe.cela permet de determiner quand
* tous les fichiers d'un groupe ont ete verifie et de passer au groupe
* suivant
*/
groupes.get(f.getGroupe()).remove(f);
if (groupes.get(f.getGroupe()).isEmpty()) {
groupes.remove(f.getGroupe());
try {
if (!groupes.isEmpty()) {
niveauActuel = groupes.firstKey();
}
} catch (final NoSuchElementException ex) {
logAppli.error(ex);
}
}
}
private void creerDossierEtFichiersLogs() throws EchecCreationLogs {
final File dirLog = new File(emplacementFichiersLogs);
if (!dirLog.exists()) {
if (!dirLog.mkdir()) {
throw new EchecCreationLogs();
}
}
}
private void initialiserLesFichiers() {
listCheminFichiersLog.clear();
dateDebut = Calendar.getInstance().getTime();
for (final Fichier f : fichiers) {
final LoggueurMultiple lm = new LoggueurMultiple();
lm.setNomFichier(f.getNom());
final String timestamp = (new SimpleDateFormat("yyyyMMddHHmmss")).format(dateDebut) + "-";
final String chemin = emplacementFichiersLogs + timestamp + f.getNom() + ".csv";
listCheminFichiersLog.add(chemin);
final ILogger logCSV = new LoggueurFichierCSV(chemin);
logCSV.setNomFichier(f.getNom());
final ILogger logRam = new LoggueurRam();
logRam.setNomFichier(f.getNom());
lm.addLogger(logRam);
lm.addLogger(logCSV);
f.setLogger(lm);
loggeurs.put(f.getNom(), logRam);
if (f.getEtatFichier() != Fichier.ETAT.DESACTIVE_DEPENDANCE && f.getEtatFichier() != Fichier.ETAT.DESACTIVE_UTILISATEUR) {
f.setEtatFichier(Fichier.ETAT.EN_ATTENTE);
}
}
}
private void creerLogGeneral() {
final String timestamp = (new SimpleDateFormat("yyyyMMddHHmmss")).format(dateDebut) + "-";
try {
fichierLogGeneral = File.createTempFile(timestamp + " - LogGeneral ", ".log");
try (FileOutputStream fos = new FileOutputStream(fichierLogGeneral)) {
loggueurGeneral = new PrintStream(new FileOutputStream(fichierLogGeneral));
construireLogGeneral(loggueurGeneral);
listCheminFichiersLog.add(fichierLogGeneral.getAbsolutePath());
} catch (final FileNotFoundException e) {
logAppli.error(e);
}
} catch (final IOException e) {
fichierLogGeneral = null;
logAppli.error(e);
}
}
private void construireLogGeneral(PrintStream log) {
log.println("date de debut de verification" + dateDebut);
for (final Fichier f : fichiers) {
log.println(f.getNom() + " : ETAT FINAL : " + f.getEtatFichier());
log.println(f.getNom() + " : CHEMIN : " + f.getChemin());
}
}
private void calculGroupesDisponibles() {
groupes.clear();
for (final Fichier f : fichiers) {
if (f.isEnabled()) {
if (groupes.get(f.getGroupe()) == null) {
groupes.put(f.getGroupe(), new HashSet<Fichier>());
}
groupes.get(f.getGroupe()).add(f);
}
}
}
protected void trierLesFichiers() {
// trier par ordre de dependance (ordre "topologique")
/* voir Fichier#getNiveauTopo */
Collections.sort(fichiers, new FichierComparteurOrdreTopo());
// trier les fichiers par ordre de groupe(d�fini dans les specs)
Collections.sort(fichiers, new FichierComparteurGroupe());
niveauActuel = fichiers.get(0).getGroupe();
}
/**
* @return la liste des fichier du schema.
*/
public List<Fichier> getFichiers() {
return fichiers;
}
/**
* Ecrit le schema dans un fichier XML.
*
* @param path
* le chemin d'acces du fichier XML
* @throws JAXBException
* si la conversion de l'XML en schema objet en XML
*/
public void toXml(FileOutputStream path) throws JAXBException {
final JAXBContext context = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
final Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal((new ObjXmlTransformer()).transform(this), path);
}
/**
* renvoie le fichier identifie par ce nom.
*
* @param nom
* le nom du fichier
* @return le fichier correspondant
*/
public Fichier getFichier(String nom) {
for (final Fichier f : fichiers) {
if (nom.equals(f.getNom())) {
return f;
}
}
return null;
}
/**
* Construit un schema a partir d'un XML lu dans inputStream.
*
* @param inputStream
* sert a lire le fichier
* @return le schema XML
* @throws JAXBException
* si la conversion à partir du XML échoue
*/
public static Schema fromXML(InputStream inputStream) throws JAXBException {
final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
final Unmarshaller u = jc.createUnmarshaller();
final JAXBElement<?> schemaXML = (JAXBElement<?>) u.unmarshal(inputStream);
final XmlObjTransformer trans = new XmlObjTransformer();
try {
inputStream.close();
} catch (final IOException e) {
logAppli.error(e);
}
return trans.transform((TypeSchema) schemaXML.getValue());
}
/**
* @return une map contenant les logueurs(la liste des erreurs) de chaque
* fichier
*/
public Map<String, ILogger> getLoggeurs() {
return loggeurs;
}
/** {@inheritDoc} */
@Override
public void finFichier(String nomFichier, ETAT etat) {
if (eltANotifier != null) {
eltANotifier.finFichier(nomFichier, etat);
}
}
/** {@inheritDoc} */
@Override
public void caractereTraites(long nbCaracteres) {
if (eltANotifier != null) {
eltANotifier.caractereTraites(nbCaracteres);
}
}
/** {@inheritDoc} */
@Override
public void debutFichier(String nomFichier) {
if (eltANotifier != null) {
eltANotifier.debutFichier(nomFichier);
}
}
/**
* désigne l'objet à notifier lorsque certains �venements (voir
* {@link INotifiable}) ont lieu.
*
* @param eltANotifier
* l'objet à notifier
*/
public void setEltANotifier(INotifiable eltANotifier) {
this.eltANotifier = eltANotifier;
for (final Fichier f : fichiers) {
f.setEltAnotifier(eltANotifier);
}
}
/**
* Reprend la v�rification si elle est en pause. voir {@link #pause()}.
*/
public void resume() {
fichierEnCours.resume();
}
/**
* Annule la v�rification du fichier en cours.
*/
public void cancel() {
fichierEnCours.cancel();
}
/**
* @return le repertoire o� seront sauvegard�s les fichiers de logs.
*/
public String getEmplacementFichiersLogs() {
return emplacementFichiersLogs;
}
/**
* @param emplacementFichiersLogs
* repertoire o� seront sauvegard�s les fichiers de logs.
*/
public void setEmplacementFichiersLogs(String emplacementFichiersLogs) {
this.emplacementFichiersLogs = emplacementFichiersLogs;
}
/**
* active ou d�sactive un fichier.
*
* @param nom
* le nom du fichier a activer
* @param etat
* true s'il faut l'activer, false sinon
*/
public void setEnabledFichier(String nom, boolean etat) {
final Fichier f = getFichier(nom);
if (etat) {
f.setEtatFichier(ETAT.EN_ATTENTE);
reactiverDependancesAncetres(f);
} else {
f.setEtatFichier(ETAT.DESACTIVE_UTILISATEUR);
desactiverDependances(f);
}
}
private void desactiverDependances(Fichier f) {
for (final Fichier dependant : f.getFichiersQuiDependentDeNous()) {
if (dependant.getEtatFichier() == ETAT.EN_ATTENTE) {
dependant.setEtatFichier(ETAT.DESACTIVE_UTILISATEUR);
desactiverDependances(dependant);
}
}
}
private void reactiverDependancesAncetres(Fichier f) {
for (final Fichier onEnDepend : f.getFichiersDontOnDepend()) {
onEnDepend.setEtatFichier(ETAT.EN_ATTENTE);
reactiverDependancesAncetres(onEnDepend);
}
}
/**
* @return le nombre de fichier non-desactiv�s dans le schema
*/
public int getNbFichiersActifs() {
int nb = 0;
for (final Fichier f : fichiers) {
if (f.getEtatFichier() == ETAT.EN_ATTENTE) {
nb++;
}
}
return nb;
}
/**
* @return l'encodage des fichier
*/
public String getEncoding() {
return encoding;
}
/**
* Désigne l'encodage des fichiers.
*
* @param encoding string qui désigne l'encodage des fichiers. Voir{@link Charset}.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Zip les fichiers de log dans le fichier désigné.
*
* @param outputZip le fichier destination.
* @throws IOException si une erreur d'écriture a lieu.
*/
public void zipLogFiles(File outputZip) throws IOException {
LogFilesZipper.zip(outputZip, listCheminFichiersLog);
}
/**
* @param b
* true si on veut afficher le bouton Exporter les logs dans
* l'interface utilisateur
*/
public void setAfficherExportLogs(boolean b) {
afficherExportLogs = b;
}
/**
* @return true si on veut afficher le bouton Exporter les logs dans
* l'interface utilisateur
*/
public boolean isAfficherExportLogs() {
return afficherExportLogs;
}
/** {@inheritDoc} */
@Override
public String toString() {
String s = "";
for (final Fichier f : fichiers) {
s += f.getNom() + " : " + f.getEtatFichier() + "\n";
}
return s;
}
/**
* @return le separateur de champ utilisé.
*/
public SeparateurChamps getSeparateurChamp() {
return separateurChamp;
}
/**
* @param sep le séparateur de champs à utiliser. Voir {@link SeparateurChamps}.
*/
public void setSeparateurChamp(SeparateurChamps sep) {
this.separateurChamp = sep;
}
/**
* @param sep le séparateur de décimales à utiliser. Voir {@link SeparateurDecimales}.
*/
public void setSeparateurDecimales(SeparateurDecimales sep) {
this.separateurDecimales = sep;
}
/**
* @return le separateur des décimales.
*/
public SeparateurDecimales getSeparateurDecimales() {
return separateurDecimales;
}
/**
* @return les cat�gories du sch�ma.
*/
public Categories getCategories() {
return categories;
}
/**
* Retire le fichier du sch�ma.
*
* @param f
* le fichier � retirer.
*/
public void removeFichier(Fichier f) {
fichiers.remove(f);
}
/**
* @return le nombre total de fichiers dans le sch�ma.
*/
public int getNbFichiers() {
return fichiers.size();
}
}
|
185933_17 | package game;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import org.joml.Vector2f;
import org.joml.Vector4f;
import engine.ColorRGBA8;
import engine.SpriteBatch;
import engine.Texture;
import engine.UV;
public class Room {
final public static int ROOM_WIDTH = 20;
final public static int ROOM_HEIGHT = 15;
final public static int TILE_WIDTH = 16;
final public static float TILE_SCALE = 4f;
final public static float TILE_RADIUS = Room.TILE_WIDTH * Room.TILE_SCALE / 2f;
final private static int TILE_SHEET_WIDTH = 128;
final private static int TILE_SHEET_HEIGHT = 64;
final private static int TILES_PER_ROW = TILE_SHEET_WIDTH / TILE_WIDTH;
final private static int TILES_PER_COLUMN = TILE_SHEET_HEIGHT / TILE_WIDTH;
final private static float TILE_UV_WIDTH = 1f / (float) TILES_PER_ROW;
final private static float TILE_UV_HEIGHT = 1f / (float) TILES_PER_COLUMN;
final private static int NUM_TILES = 32;
final public static char TILE_SYMBOL_FLOOR = '*';
final public static char TILE_SYMBOL_BLOCK = 'b';
final public static char TILE_SYMBOL_WALL = 'w';
final public static char TILE_SYMBOL_DOOR = 'd';
final private static int TILE_INDEX_DOWN_LEFT_CORNER = 0;
final private static int TILE_INDEX_DOWN_WALL = 1;
final private static int TILE_INDEX_DOWN_RIGHT_CORNER = 2;
final private static int TILE_INDEX_LEFT_DOOR_LOWER = 3;
final private static int TILE_INDEX_RIGHT_DOOR_LOWER = 4;
final private static int TILE_INDEX_BLOCK = 5;
final private static int TILE_INDEX_UP_DOOR_LEFT_OPEN = 6;
final private static int TILE_INDEX_UP_DOOR_RIGHT_OPEN = 7;
final private static int TILE_INDEX_LEFT_WALL = 8;
final private static int TILE_INDEX_FLOOR = 9;
final private static int TILE_INDEX_RIGHT_WALL = 10;
final private static int TILE_INDEX_LEFT_DOOR_MID_OPEN = 11;
final private static int TILE_INDEX_RIGHT_DOOR_MID_OPEN = 12;
final private static int TILE_INDEX_RIGHT_DOOR_MID_CLOSED = 13;
final private static int TILE_INDEX_UP_DOOR_LEFT_CLOSED = 14;
final private static int TILE_INDEX_UP_DOOR_RIGHT_CLOSED = 15;
final private static int TILE_INDEX_UP_LEFT_CORNER = 16;
final private static int TILE_INDEX_UP_WALL = 17;
final private static int TILE_INDEX_UP_RIGHT_CORNER = 18;
final private static int TILE_INDEX_LEFT_DOOR_UPPER = 19;
final private static int TILE_INDEX_RIGHT_DOOR_UPPER = 20;
final private static int TILE_INDEX_LEFT_DOOR_MID_CLOSED = 21;
final private static int TILE_INDEX_DOWN_DOOR_LEFT_OPEN = 22;
final private static int TILE_INDEX_DOWN_DOOR_RIGHT_OPEN = 23;
final private static int TILE_INDEX_DOWN_DOOR_LEFT_CLOSED = 24;
final private static int TILE_INDEX_DOWN_DOOR_RIGHT_CLOSED = 25;
final private static int TILE_INDEX_UP_DOOR_LEFT_LOCKED = 26;
final private static int TILE_INDEX_UP_DOOR_RIGHT_LOCKED = 27;
final private static int TILE_INDEX_DOWN_DOOR_LEFT_LOCKED = 28;
final private static int TILE_INDEX_DOWN_DOOR_RIGHT_LOCKED = 29;
final private static int TILE_INDEX_RIGHT_DOOR_MID_LOCKED = 30;
final private static int TILE_INDEX_LEFT_DOOR_MID_LOCKED = 31;
private static Vector4f[] tileUVs = new Vector4f[NUM_TILES];
final private static Texture tileSheetTexture = new Texture("./textures/tiles.png");
private ArrayList<String> roomData;
private int numEnemies;
private Integer roomNo;
private ArrayList<String> enemies;
private ArrayList<Vector2f> enemyStartPositions;
private boolean isCleared = false;
public static enum DoorState {
OPEN, OPENABLE, CLOSED, LOCKED, BOSS_LOCKED
};
public DoorState upDoorState, downDoorState, leftDoorState, rightDoorState;
SpriteBatch roomSpriteBatch;
public static void tileInit() {
for (int i = 0; i < NUM_TILES; i++) {
// System.out.print(i + ": ");
// System.out.print((i % TILES_PER_ROW) + ", ");
// System.out.println((i / TILES_PER_ROW));
tileUVs[i] = new Vector4f((i % TILES_PER_ROW) * TILE_UV_WIDTH, (i / TILES_PER_ROW) * TILE_UV_HEIGHT,
TILE_UV_WIDTH, TILE_UV_HEIGHT);
// tileUVs[i] = UV.DEFAULT_UV_RECT;
}
}
public Room(boolean clear, DoorState up, DoorState down, DoorState left, DoorState right) throws IOException {
isCleared = clear;
upDoorState = up;
downDoorState = down;
leftDoorState = left;
rightDoorState = right;
enemies = new ArrayList<>();
enemyStartPositions = new ArrayList<>();
roomData = new ArrayList<>(ROOM_HEIGHT);
for (int i = 0; i < ROOM_HEIGHT; i++) {
roomData.add(null);
}
Random rn = new Random();
Integer roomNo = rn.nextInt(6) + 1;
FileReader input = null;
input = new FileReader("./rooms/Room" + roomNo.toString() + ".txt");
// input = new FileReader("./rooms/Room6.txt");
BufferedReader br = new BufferedReader(input);
for (int i = 1; i <= ROOM_HEIGHT; i++) {
roomData.set(ROOM_HEIGHT - i, br.readLine());
}
// for (String s : roomData) {
// System.out.println(s);
// }
numEnemies = Integer.parseInt(br.readLine());
if (numEnemies > 0) {
String enemyData;
while ((enemyData = br.readLine()) != null) {
StringTokenizer stok = new StringTokenizer(enemyData);
enemies.add(stok.nextToken());
enemyStartPositions
.add(new Vector2f(Integer.parseInt(stok.nextToken()), Integer.parseInt(stok.nextToken())));
}
}
br.close();
roomSpriteBatch = new SpriteBatch();
createRoomBatch();
}
public ArrayList<String> getRoomData() {
return roomData;
}
public boolean isCleared() {
return isCleared;
}
public DoorState getUpDoorState() {
return upDoorState;
}
public DoorState getDownDoorState() {
return downDoorState;
}
public DoorState getLeftDoorState() {
return leftDoorState;
}
public DoorState getRightDoorState() {
return rightDoorState;
}
public void clearRoom(boolean hasKey, boolean hasBossKey) {
isCleared = true;
updateRoomBatch();
if (hasKey) {
if (upDoorState == DoorState.LOCKED) {
upDoorState = DoorState.OPEN;
}
if (downDoorState == DoorState.LOCKED) {
downDoorState = DoorState.OPEN;
}
if (leftDoorState == DoorState.LOCKED) {
leftDoorState = DoorState.OPEN;
}
if (rightDoorState == DoorState.LOCKED) {
rightDoorState = DoorState.OPEN;
}
}
if (hasBossKey) {
if (upDoorState == DoorState.BOSS_LOCKED) {
upDoorState = DoorState.OPEN;
}
if (downDoorState == DoorState.BOSS_LOCKED) {
downDoorState = DoorState.OPEN;
}
if (leftDoorState == DoorState.BOSS_LOCKED) {
leftDoorState = DoorState.OPEN;
}
if (rightDoorState == DoorState.BOSS_LOCKED) {
rightDoorState = DoorState.OPEN;
}
}
if (upDoorState == DoorState.OPENABLE) {
upDoorState = DoorState.OPEN;
}
if (downDoorState == DoorState.OPENABLE) {
downDoorState = DoorState.OPEN;
}
if (leftDoorState == DoorState.OPENABLE) {
leftDoorState = DoorState.OPEN;
}
if (rightDoorState == DoorState.OPENABLE) {
rightDoorState = DoorState.OPEN;
}
}
public void createRoomBatch() {
roomSpriteBatch.begin(SpriteBatch.SORT_BY_TEXTURE);
for (int y = 0; y < ROOM_HEIGHT; y++) {
// System.out.println();
for (int x = 0; x < ROOM_WIDTH; x++) {
Vector4f destRect = new Vector4f(x * TILE_WIDTH * TILE_SCALE, y * TILE_WIDTH * TILE_SCALE,
TILE_WIDTH * TILE_SCALE, TILE_WIDTH * TILE_SCALE);
// Check if the tile is a corner
if (x == 0 && y == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_DOWN_LEFT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN LEFT Corner");
}
else if (x == 0 && y == ROOM_HEIGHT - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_UP_LEFT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP LEFT Corner");
}
else if (x == ROOM_WIDTH - 1 && y == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_DOWN_RIGHT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN RIGHT Corner");
}
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_UP_RIGHT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP RIGHT Corner");
}
// Check if the tile is a door tile and if the room is cleared,
// and can be opened set the door to be open
// Left Door tiles
else if (x == 0 && y == ROOM_HEIGHT / 2) {
int tileIndex;
if (leftDoorState == DoorState.LOCKED || leftDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_LEFT_DOOR_MID_LOCKED;
} else if (leftDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_LEFT_DOOR_MID_OPEN;
} else {
tileIndex = TILE_INDEX_LEFT_DOOR_MID_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("LEFT DOOR MID");
}
else if (x == 0 && y == ROOM_HEIGHT / 2 - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_LEFT_DOOR_LOWER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("LEFT DOOR LOWER");
}
else if (x == 0 && y == ROOM_HEIGHT / 2 + 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_LEFT_DOOR_UPPER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("LEFT DOOR UPPER");
}
// Right door tiles
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT / 2) {
int tileIndex;
if (rightDoorState == DoorState.LOCKED || rightDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_RIGHT_DOOR_MID_LOCKED;
} else if (rightDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_RIGHT_DOOR_MID_OPEN;
} else {
tileIndex = TILE_INDEX_RIGHT_DOOR_MID_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("RIGHT DOOR MID");
}
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT / 2 - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_RIGHT_DOOR_LOWER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("RIGHT DOOR LOWER");
}
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT / 2 + 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_RIGHT_DOOR_UPPER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("RIGHT DOOR UPPER");
}
// Down door
else if (x == ROOM_WIDTH / 2 - 1 && y == 0) {
int tileIndex;
if (downDoorState == DoorState.LOCKED || downDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_DOWN_DOOR_LEFT_LOCKED;
} else if (downDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_DOWN_DOOR_LEFT_OPEN;
} else {
tileIndex = TILE_INDEX_DOWN_DOOR_LEFT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN DOOR LEFT");
}
else if (x == ROOM_WIDTH / 2 && y == 0) {
int tileIndex;
if (downDoorState == DoorState.LOCKED || downDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_DOWN_DOOR_RIGHT_LOCKED;
} else if (downDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_DOWN_DOOR_RIGHT_OPEN;
} else {
tileIndex = TILE_INDEX_DOWN_DOOR_RIGHT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN DOOR RIGHT");
}
// Up door
else if (x == ROOM_WIDTH / 2 - 1 && y == ROOM_HEIGHT - 1) {
int tileIndex;
if (upDoorState == DoorState.LOCKED || upDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_UP_DOOR_LEFT_LOCKED;
} else if (upDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_UP_DOOR_LEFT_OPEN;
} else {
tileIndex = TILE_INDEX_UP_DOOR_LEFT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP DOOR LEFT");
}
else if (x == ROOM_WIDTH / 2 && y == ROOM_HEIGHT - 1) {
int tileIndex;
if (upDoorState == DoorState.LOCKED || upDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_UP_DOOR_RIGHT_LOCKED;
} else if (upDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_UP_DOOR_RIGHT_OPEN;
} else {
tileIndex = TILE_INDEX_UP_DOOR_RIGHT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP DOOR RIGHT");
}
// Otherwise it is a normal tile
else {
char currentTile = roomData.get(y).charAt(x);
switch (currentTile) {
// Floor tile
case '*':
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_FLOOR], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("F");
break;
// Block tile
case 'b':
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_BLOCK], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("B");
break;
// Wall tile
case 'w':
if (x == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_LEFT_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("L");
}
else if (x == ROOM_WIDTH - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_RIGHT_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("R");
}
else if (y == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_DOWN_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("D");
}
else {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_UP_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("U");
}
break;
/*case 'd' :
break;*/
default :
System.err.println("Illegal symbol '" + currentTile + "' in file Room" + roomNo.toString()
+ ".txt in line " + y);
throw new IllegalStateException("Illegal symbol in the room");
}
}
}
}
roomSpriteBatch.end();
}
private void updateRoomBatch() {
}
public void render() {
roomSpriteBatch.render();
}
}
| KnightShuffler/CSD207-Project-RogueCrawler | src/game/Room.java | 6,215 | // Right door tiles
| line_comment | nl | package game;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import org.joml.Vector2f;
import org.joml.Vector4f;
import engine.ColorRGBA8;
import engine.SpriteBatch;
import engine.Texture;
import engine.UV;
public class Room {
final public static int ROOM_WIDTH = 20;
final public static int ROOM_HEIGHT = 15;
final public static int TILE_WIDTH = 16;
final public static float TILE_SCALE = 4f;
final public static float TILE_RADIUS = Room.TILE_WIDTH * Room.TILE_SCALE / 2f;
final private static int TILE_SHEET_WIDTH = 128;
final private static int TILE_SHEET_HEIGHT = 64;
final private static int TILES_PER_ROW = TILE_SHEET_WIDTH / TILE_WIDTH;
final private static int TILES_PER_COLUMN = TILE_SHEET_HEIGHT / TILE_WIDTH;
final private static float TILE_UV_WIDTH = 1f / (float) TILES_PER_ROW;
final private static float TILE_UV_HEIGHT = 1f / (float) TILES_PER_COLUMN;
final private static int NUM_TILES = 32;
final public static char TILE_SYMBOL_FLOOR = '*';
final public static char TILE_SYMBOL_BLOCK = 'b';
final public static char TILE_SYMBOL_WALL = 'w';
final public static char TILE_SYMBOL_DOOR = 'd';
final private static int TILE_INDEX_DOWN_LEFT_CORNER = 0;
final private static int TILE_INDEX_DOWN_WALL = 1;
final private static int TILE_INDEX_DOWN_RIGHT_CORNER = 2;
final private static int TILE_INDEX_LEFT_DOOR_LOWER = 3;
final private static int TILE_INDEX_RIGHT_DOOR_LOWER = 4;
final private static int TILE_INDEX_BLOCK = 5;
final private static int TILE_INDEX_UP_DOOR_LEFT_OPEN = 6;
final private static int TILE_INDEX_UP_DOOR_RIGHT_OPEN = 7;
final private static int TILE_INDEX_LEFT_WALL = 8;
final private static int TILE_INDEX_FLOOR = 9;
final private static int TILE_INDEX_RIGHT_WALL = 10;
final private static int TILE_INDEX_LEFT_DOOR_MID_OPEN = 11;
final private static int TILE_INDEX_RIGHT_DOOR_MID_OPEN = 12;
final private static int TILE_INDEX_RIGHT_DOOR_MID_CLOSED = 13;
final private static int TILE_INDEX_UP_DOOR_LEFT_CLOSED = 14;
final private static int TILE_INDEX_UP_DOOR_RIGHT_CLOSED = 15;
final private static int TILE_INDEX_UP_LEFT_CORNER = 16;
final private static int TILE_INDEX_UP_WALL = 17;
final private static int TILE_INDEX_UP_RIGHT_CORNER = 18;
final private static int TILE_INDEX_LEFT_DOOR_UPPER = 19;
final private static int TILE_INDEX_RIGHT_DOOR_UPPER = 20;
final private static int TILE_INDEX_LEFT_DOOR_MID_CLOSED = 21;
final private static int TILE_INDEX_DOWN_DOOR_LEFT_OPEN = 22;
final private static int TILE_INDEX_DOWN_DOOR_RIGHT_OPEN = 23;
final private static int TILE_INDEX_DOWN_DOOR_LEFT_CLOSED = 24;
final private static int TILE_INDEX_DOWN_DOOR_RIGHT_CLOSED = 25;
final private static int TILE_INDEX_UP_DOOR_LEFT_LOCKED = 26;
final private static int TILE_INDEX_UP_DOOR_RIGHT_LOCKED = 27;
final private static int TILE_INDEX_DOWN_DOOR_LEFT_LOCKED = 28;
final private static int TILE_INDEX_DOWN_DOOR_RIGHT_LOCKED = 29;
final private static int TILE_INDEX_RIGHT_DOOR_MID_LOCKED = 30;
final private static int TILE_INDEX_LEFT_DOOR_MID_LOCKED = 31;
private static Vector4f[] tileUVs = new Vector4f[NUM_TILES];
final private static Texture tileSheetTexture = new Texture("./textures/tiles.png");
private ArrayList<String> roomData;
private int numEnemies;
private Integer roomNo;
private ArrayList<String> enemies;
private ArrayList<Vector2f> enemyStartPositions;
private boolean isCleared = false;
public static enum DoorState {
OPEN, OPENABLE, CLOSED, LOCKED, BOSS_LOCKED
};
public DoorState upDoorState, downDoorState, leftDoorState, rightDoorState;
SpriteBatch roomSpriteBatch;
public static void tileInit() {
for (int i = 0; i < NUM_TILES; i++) {
// System.out.print(i + ": ");
// System.out.print((i % TILES_PER_ROW) + ", ");
// System.out.println((i / TILES_PER_ROW));
tileUVs[i] = new Vector4f((i % TILES_PER_ROW) * TILE_UV_WIDTH, (i / TILES_PER_ROW) * TILE_UV_HEIGHT,
TILE_UV_WIDTH, TILE_UV_HEIGHT);
// tileUVs[i] = UV.DEFAULT_UV_RECT;
}
}
public Room(boolean clear, DoorState up, DoorState down, DoorState left, DoorState right) throws IOException {
isCleared = clear;
upDoorState = up;
downDoorState = down;
leftDoorState = left;
rightDoorState = right;
enemies = new ArrayList<>();
enemyStartPositions = new ArrayList<>();
roomData = new ArrayList<>(ROOM_HEIGHT);
for (int i = 0; i < ROOM_HEIGHT; i++) {
roomData.add(null);
}
Random rn = new Random();
Integer roomNo = rn.nextInt(6) + 1;
FileReader input = null;
input = new FileReader("./rooms/Room" + roomNo.toString() + ".txt");
// input = new FileReader("./rooms/Room6.txt");
BufferedReader br = new BufferedReader(input);
for (int i = 1; i <= ROOM_HEIGHT; i++) {
roomData.set(ROOM_HEIGHT - i, br.readLine());
}
// for (String s : roomData) {
// System.out.println(s);
// }
numEnemies = Integer.parseInt(br.readLine());
if (numEnemies > 0) {
String enemyData;
while ((enemyData = br.readLine()) != null) {
StringTokenizer stok = new StringTokenizer(enemyData);
enemies.add(stok.nextToken());
enemyStartPositions
.add(new Vector2f(Integer.parseInt(stok.nextToken()), Integer.parseInt(stok.nextToken())));
}
}
br.close();
roomSpriteBatch = new SpriteBatch();
createRoomBatch();
}
public ArrayList<String> getRoomData() {
return roomData;
}
public boolean isCleared() {
return isCleared;
}
public DoorState getUpDoorState() {
return upDoorState;
}
public DoorState getDownDoorState() {
return downDoorState;
}
public DoorState getLeftDoorState() {
return leftDoorState;
}
public DoorState getRightDoorState() {
return rightDoorState;
}
public void clearRoom(boolean hasKey, boolean hasBossKey) {
isCleared = true;
updateRoomBatch();
if (hasKey) {
if (upDoorState == DoorState.LOCKED) {
upDoorState = DoorState.OPEN;
}
if (downDoorState == DoorState.LOCKED) {
downDoorState = DoorState.OPEN;
}
if (leftDoorState == DoorState.LOCKED) {
leftDoorState = DoorState.OPEN;
}
if (rightDoorState == DoorState.LOCKED) {
rightDoorState = DoorState.OPEN;
}
}
if (hasBossKey) {
if (upDoorState == DoorState.BOSS_LOCKED) {
upDoorState = DoorState.OPEN;
}
if (downDoorState == DoorState.BOSS_LOCKED) {
downDoorState = DoorState.OPEN;
}
if (leftDoorState == DoorState.BOSS_LOCKED) {
leftDoorState = DoorState.OPEN;
}
if (rightDoorState == DoorState.BOSS_LOCKED) {
rightDoorState = DoorState.OPEN;
}
}
if (upDoorState == DoorState.OPENABLE) {
upDoorState = DoorState.OPEN;
}
if (downDoorState == DoorState.OPENABLE) {
downDoorState = DoorState.OPEN;
}
if (leftDoorState == DoorState.OPENABLE) {
leftDoorState = DoorState.OPEN;
}
if (rightDoorState == DoorState.OPENABLE) {
rightDoorState = DoorState.OPEN;
}
}
public void createRoomBatch() {
roomSpriteBatch.begin(SpriteBatch.SORT_BY_TEXTURE);
for (int y = 0; y < ROOM_HEIGHT; y++) {
// System.out.println();
for (int x = 0; x < ROOM_WIDTH; x++) {
Vector4f destRect = new Vector4f(x * TILE_WIDTH * TILE_SCALE, y * TILE_WIDTH * TILE_SCALE,
TILE_WIDTH * TILE_SCALE, TILE_WIDTH * TILE_SCALE);
// Check if the tile is a corner
if (x == 0 && y == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_DOWN_LEFT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN LEFT Corner");
}
else if (x == 0 && y == ROOM_HEIGHT - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_UP_LEFT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP LEFT Corner");
}
else if (x == ROOM_WIDTH - 1 && y == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_DOWN_RIGHT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN RIGHT Corner");
}
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_UP_RIGHT_CORNER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP RIGHT Corner");
}
// Check if the tile is a door tile and if the room is cleared,
// and can be opened set the door to be open
// Left Door tiles
else if (x == 0 && y == ROOM_HEIGHT / 2) {
int tileIndex;
if (leftDoorState == DoorState.LOCKED || leftDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_LEFT_DOOR_MID_LOCKED;
} else if (leftDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_LEFT_DOOR_MID_OPEN;
} else {
tileIndex = TILE_INDEX_LEFT_DOOR_MID_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("LEFT DOOR MID");
}
else if (x == 0 && y == ROOM_HEIGHT / 2 - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_LEFT_DOOR_LOWER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("LEFT DOOR LOWER");
}
else if (x == 0 && y == ROOM_HEIGHT / 2 + 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_LEFT_DOOR_UPPER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("LEFT DOOR UPPER");
}
// Right door<SUF>
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT / 2) {
int tileIndex;
if (rightDoorState == DoorState.LOCKED || rightDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_RIGHT_DOOR_MID_LOCKED;
} else if (rightDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_RIGHT_DOOR_MID_OPEN;
} else {
tileIndex = TILE_INDEX_RIGHT_DOOR_MID_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("RIGHT DOOR MID");
}
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT / 2 - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_RIGHT_DOOR_LOWER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("RIGHT DOOR LOWER");
}
else if (x == ROOM_WIDTH - 1 && y == ROOM_HEIGHT / 2 + 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_RIGHT_DOOR_UPPER], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("RIGHT DOOR UPPER");
}
// Down door
else if (x == ROOM_WIDTH / 2 - 1 && y == 0) {
int tileIndex;
if (downDoorState == DoorState.LOCKED || downDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_DOWN_DOOR_LEFT_LOCKED;
} else if (downDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_DOWN_DOOR_LEFT_OPEN;
} else {
tileIndex = TILE_INDEX_DOWN_DOOR_LEFT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN DOOR LEFT");
}
else if (x == ROOM_WIDTH / 2 && y == 0) {
int tileIndex;
if (downDoorState == DoorState.LOCKED || downDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_DOWN_DOOR_RIGHT_LOCKED;
} else if (downDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_DOWN_DOOR_RIGHT_OPEN;
} else {
tileIndex = TILE_INDEX_DOWN_DOOR_RIGHT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("DOWN DOOR RIGHT");
}
// Up door
else if (x == ROOM_WIDTH / 2 - 1 && y == ROOM_HEIGHT - 1) {
int tileIndex;
if (upDoorState == DoorState.LOCKED || upDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_UP_DOOR_LEFT_LOCKED;
} else if (upDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_UP_DOOR_LEFT_OPEN;
} else {
tileIndex = TILE_INDEX_UP_DOOR_LEFT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP DOOR LEFT");
}
else if (x == ROOM_WIDTH / 2 && y == ROOM_HEIGHT - 1) {
int tileIndex;
if (upDoorState == DoorState.LOCKED || upDoorState == DoorState.BOSS_LOCKED) {
tileIndex = TILE_INDEX_UP_DOOR_RIGHT_LOCKED;
} else if (upDoorState == DoorState.OPEN && isCleared) {
tileIndex = TILE_INDEX_UP_DOOR_RIGHT_OPEN;
} else {
tileIndex = TILE_INDEX_UP_DOOR_RIGHT_CLOSED;
}
roomSpriteBatch.addGlyph(destRect, tileUVs[tileIndex], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.println("UP DOOR RIGHT");
}
// Otherwise it is a normal tile
else {
char currentTile = roomData.get(y).charAt(x);
switch (currentTile) {
// Floor tile
case '*':
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_FLOOR], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("F");
break;
// Block tile
case 'b':
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_BLOCK], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("B");
break;
// Wall tile
case 'w':
if (x == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_LEFT_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("L");
}
else if (x == ROOM_WIDTH - 1) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_RIGHT_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("R");
}
else if (y == 0) {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_DOWN_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("D");
}
else {
roomSpriteBatch.addGlyph(destRect, tileUVs[TILE_INDEX_UP_WALL], ColorRGBA8.WHITE,
tileSheetTexture.getTexture(), 1f);
// System.out.print("U");
}
break;
/*case 'd' :
break;*/
default :
System.err.println("Illegal symbol '" + currentTile + "' in file Room" + roomNo.toString()
+ ".txt in line " + y);
throw new IllegalStateException("Illegal symbol in the room");
}
}
}
}
roomSpriteBatch.end();
}
private void updateRoomBatch() {
}
public void render() {
roomSpriteBatch.render();
}
}
|
175943_3 | /*
* Knowage, Open Source Business Intelligence suite
* Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
*
* Knowage is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knowage is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.eng.knowage.document.cockpit.template.widget;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import it.eng.spagobi.utilities.assertion.Assert;
/**
* @author Dragan Pirkovic
*
*/
public abstract class AbstactWidgetReader implements ICockpitWidget {
protected JSONObject jsonWidget;
/**
*
*/
protected AbstactWidgetReader() {
}
@Override
public JSONArray getColumnSelectedOfDataSet() {
Assert.assertNotNull(getContent(), "content cannot be null");
return getContent().optJSONArray("columnSelectedOfDataset");
}
@Override
public Integer getDsId() {
Assert.assertNotNull(getDataset(), "dataset cannot be null");
return getDataset().optInt("dsId");
}
@Override
public String getDsLabel() {
Assert.assertNotNull(getDataset(), "dataset cannot be null");
return getDataset().optString("dsLabel");
}
/*
* (non-Javadoc)
*
* @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getId()
*/
@Override
public Integer getId() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return this.jsonWidget.optInt("id");
}
/*
* (non-Javadoc)
*
* @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getJsonWidget()
*/
@Override
public JSONObject getJsonWidget() {
return jsonWidget;
}
/**
*
*/
protected JSONObject getContent() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return this.jsonWidget.optJSONObject("content");
}
/**
* @return
*/
protected String getContentName() {
Assert.assertNotNull(getContent(), "content cannot be null");
return getContent().optString("name");
}
/**
* @return
* @throws JSONException
*/
protected JSONObject getDataset() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return jsonWidget.optJSONObject("dataset");
}
/**
* @return
*/
protected String getWidgetTitleLabel() {
Assert.assertNotNull(getTitle(), "title cannot be null");
return getTitle().optString("label");
}
/**
* @return
* @throws JSONException
*/
protected boolean isTilteDefined() {
return styleContainsProperties() && isWidgetTitleLabelDefined();
}
/**
* @return
* @throws JSONException
*/
private JSONObject getStyle() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return jsonWidget.optJSONObject("style");
}
/**
* @return
* @throws JSONException
*/
private JSONObject getTitle() {
Assert.assertNotNull(getStyle(), "style cannot be null");
return getStyle().optJSONObject("title");
}
private boolean isWidgetTitleLabelDefined() {
return getTitle() != null && getWidgetTitleLabel() != null && !getWidgetTitleLabel().equals("");
}
/**
* @return
* @throws JSONException
*/
private boolean styleContainsProperties() {
return getStyle() != null && getStyle().length() != 0;
}
} | KnowageLabs/Knowage-Server | knowage-core/src/main/java/it/eng/knowage/document/cockpit/template/widget/AbstactWidgetReader.java | 1,117 | /*
* (non-Javadoc)
*
* @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getJsonWidget()
*/ | block_comment | nl | /*
* Knowage, Open Source Business Intelligence suite
* Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
*
* Knowage is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knowage is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.eng.knowage.document.cockpit.template.widget;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import it.eng.spagobi.utilities.assertion.Assert;
/**
* @author Dragan Pirkovic
*
*/
public abstract class AbstactWidgetReader implements ICockpitWidget {
protected JSONObject jsonWidget;
/**
*
*/
protected AbstactWidgetReader() {
}
@Override
public JSONArray getColumnSelectedOfDataSet() {
Assert.assertNotNull(getContent(), "content cannot be null");
return getContent().optJSONArray("columnSelectedOfDataset");
}
@Override
public Integer getDsId() {
Assert.assertNotNull(getDataset(), "dataset cannot be null");
return getDataset().optInt("dsId");
}
@Override
public String getDsLabel() {
Assert.assertNotNull(getDataset(), "dataset cannot be null");
return getDataset().optString("dsLabel");
}
/*
* (non-Javadoc)
*
* @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getId()
*/
@Override
public Integer getId() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return this.jsonWidget.optInt("id");
}
/*
* (non-Javadoc)
<SUF>*/
@Override
public JSONObject getJsonWidget() {
return jsonWidget;
}
/**
*
*/
protected JSONObject getContent() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return this.jsonWidget.optJSONObject("content");
}
/**
* @return
*/
protected String getContentName() {
Assert.assertNotNull(getContent(), "content cannot be null");
return getContent().optString("name");
}
/**
* @return
* @throws JSONException
*/
protected JSONObject getDataset() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return jsonWidget.optJSONObject("dataset");
}
/**
* @return
*/
protected String getWidgetTitleLabel() {
Assert.assertNotNull(getTitle(), "title cannot be null");
return getTitle().optString("label");
}
/**
* @return
* @throws JSONException
*/
protected boolean isTilteDefined() {
return styleContainsProperties() && isWidgetTitleLabelDefined();
}
/**
* @return
* @throws JSONException
*/
private JSONObject getStyle() {
Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null");
return jsonWidget.optJSONObject("style");
}
/**
* @return
* @throws JSONException
*/
private JSONObject getTitle() {
Assert.assertNotNull(getStyle(), "style cannot be null");
return getStyle().optJSONObject("title");
}
private boolean isWidgetTitleLabelDefined() {
return getTitle() != null && getWidgetTitleLabel() != null && !getWidgetTitleLabel().equals("");
}
/**
* @return
* @throws JSONException
*/
private boolean styleContainsProperties() {
return getStyle() != null && getStyle().length() != 0;
}
} |
33988_1 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author voel
*/
public class Macros implements Function {
public Object apply(Object args[]) {
return null;
}
}
| KodeKunstner/lightscript | .attic2/code/.old22/old/Macros.java | 67 | /**
*
* @author voel
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author voel
<SUF>*/
public class Macros implements Function {
public Object apply(Object args[]) {
return null;
}
}
|
53002_9 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bigdata;
import java.awt.event.ActionEvent;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
/**
*
* @author HP
*/
public class Controller {
private ParserGUI pGui;
public Controller(ParserGUI pGui) {
this.pGui = pGui;
this.pGui.setVisible(true);
this.pGui.setActions(new BrowseAction(), new OutputAction(), new ParseAction(), new CloseAction());
}
//button action for selecting file to parse
class BrowseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser input = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
input.setDialogTitle("Select a list file");
input.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(".list files", "list");
input.addChoosableFileFilter(filter);
int result = input.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
pGui.updateInputPath(selectedFile.getPath());
}
}
}
//button action for selecting directory to export .csv file into
class OutputAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e){
JFileChooser output = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
output.setDialogTitle("Choose a directory to save your file in:");
output.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// output.setAcceptAllFileFilterUsed(false);
int result = output.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
pGui.updateOutputPath(output.getCurrentDirectory().getPath() + "/");
}
}
}
//button action to begin parsing file
class ParseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
pGui.addLog("---------------------------------------");
File f = new File(pGui.getInputPath());
FileReader fr;
BufferedReader br;
int linesToSkip = 0;
String pattern;
String[] header;
String substitution;
String result;
String option = "test";
String outpath;
int[] substitutions;
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
//Path path = Paths.get(pGui.getInputPath());
//Stream<String> stream = Files.lines(path);
} catch (IOException err) {
pGui.addLog(err.toString());
return;
}
switch (f.getName()) {
case "countries.list": {
pattern = "\"?(.*?)\"?\\s\\((.{4,7}|\\?\\?\\?\\?|\\d{4}\\/.*)\\)\\s*(\\((.*)\\))?\\s*(\\{([^\\{}]*)\\})?\\s(\\{(SUSPENDED)\\})?\\s*(.*)";
substitution = "$1; $2; $6; $9";
header = new String[]{};
linesToSkip = 14;
substitutions = null;
result = "countries.csv";
break;
}
case "movies.list": {
pattern = "\\s?([^\"].*[^\"])\\s(?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\))\\s(\\((.{1,2})\\))?\\s*(\\{\\{(.*?)\\}\\})?\\s*(\\d{4}|\\?{4})";
substitution = "$1; $2; $8";
header = new String[]{};
linesToSkip = 14;
substitutions = null;
result = "movies.csv";
break;
}
case "series.list": {
pattern = "\\\"(.*?)\\\"\\s\\((.*?)\\)\\s(\\{([^\\{].*?[^\\}])\\})?\\s*(\\{(.*?)\\})?\\s*(.{4,9})";
substitution = "$1; $2; $4; $7";
header = new String[]{};
linesToSkip = 15;
substitutions = null;
result = "series.csv";
break;
}
case "actors.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $12; $15; $18";
header = new String[]{};
linesToSkip = 239;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 12, 15, 18};
result = "actors.csv";
break;
}
case "actresses.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $12; $15; $18";
header = new String[]{};
linesToSkip = 241;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 12, 15, 18};
result = "actresses.csv";
break;
}
case "directors.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $11; $15";
header = new String[]{};
linesToSkip = 235;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 11, 15};
result = "directors.csv";
break;
}
case "producers.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $11; $15";
header = new String[]{};
linesToSkip = 219;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 11, 15};
result = "producers.csv";
break;
}
case "ratings.list": {
pattern = "(.{20}) ([0-9]\\.[0-9]) (.+) (?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\)) ?(\\{(.+)\\}?)?";
substitution = "$2; $3; $4; $7";
header = new String[]{};
linesToSkip = 28;
substitutions = null;
result = "ratings.csv";
break;
}
case "running-times.list": {
pattern = "(?:\")(.*)(?:\") \\((\\d{4}|[?]{4})\\W(?:.*\\{|.*\\))?(.*\\))?(?:.*\\t|.*:)((\\d)?(\\d))(?:.*)";
substitution = "$1, $2, $3, $4";
header = new String[]{};
linesToSkip = 14;
substitutions = null;
result = "running-times.csv";
break;
}
default: {
pattern = "";
substitution = "";
header = new String[]{};
pGui.addLog("List not found.");
result = null;
option = null;
substitutions = null;
linesToSkip = 0;
break;
}
}
outpath = pGui.getOutputPath() + result;
new Parser(pattern, substitution, header, outpath, br, fr, linesToSkip, option, substitutions).execute();
}
}
//de hele parser klasse staat hieronder en is ge-extend naar swingworker zodat de parse-operatie in een achtergroundthread gebeurt zodat
//de UI niet tijdens de operatie vast loopt. Er wordt in de vorige switch-case gekeken wat voor lijst is geselecteerd en daarvan wordt de filepath (outpath)
//doorgegeven aan de Parser.
class Parser extends SwingWorker<Void, Void> {
private String pattern;
private String substitution;
private String[] header;
private String outpath;
private BufferedReader br;
private FileReader fr;
private String nextLine;
private String result;
private Matcher matcher;
private Pattern r;
private int count;
private String current;
private int linesToSkip;
private String option;
private int[] subs;
public Parser(String pattern, String substitution, String[] header, String outpath, BufferedReader br, FileReader fr, int linesToSkip, String option, int[] subs) {
this.pattern = pattern;
this.substitution = substitution;
this.header = header;
this.outpath = outpath;
this.br = br;
this.fr = fr;
this.linesToSkip = linesToSkip;
this.option = option;
count = 0;
current = "";
this.subs = subs;
}
public int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int cnt = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++cnt;
}
}
}
return (cnt == 0 && !empty) ? 1 : cnt;
} finally {
is.close();
}
}
@Override
protected Void doInBackground() throws IOException{
int lineNumber = 0;
int lts = this.linesToSkip;
pGui.setProgressBar(countLines(pGui.getInputPath()) - lts); //set progress bar length to amount of lines in file minus lts
switch(option){
case "tabbed": {
String prevName = "";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath)))
{
r = Pattern.compile(pattern);
while ((nextLine = br.readLine()) != null) {
if (++lineNumber <= lts) continue;
matcher = r.matcher(nextLine);
List<String> rows = new ArrayList<>();
if (matcher.find()) {
if (Objects.equals("", matcher.group(1))) {
rows.add(prevName);
for (int i : subs) {
rows.add("\t" + matcher.group(i));
}
} else {
rows.add(matcher.group(1));
for (int i : subs) {
rows.add("\t" + matcher.group(i));
}
prevName = matcher.group(1);
}
}
//if (!nextLine.startsWith("\"")) {
// System.out.println(nextLine);
StringBuilder lineString = new StringBuilder();
for (String row : rows) {
if (row != null) {
row = row.trim();
}
// System.out.println(lineString);
assert row != null;
lineString.append(row.trim()).append(";\t");
}
result = matcher.replaceAll(substitution);
System.out.println(result);
if (lineString.length() != 0) {
count++; //update current line count
writer.write(lineString.toString());
pGui.addLog(result); //prints converted data to log
pGui.updateProgressBar(count); //update progress bar
writer.newLine();
}
//} else continue;
}
writer.close();
}
catch (IOException e)
{
pGui.addLog(e.toString());
}
break;
}
default: {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath)))
{
r = Pattern.compile(pattern);
while ((nextLine = br.readLine()) != null) {
if (++lineNumber <= lts) continue;
//if (!nextLine.startsWith("\"")) {
// System.out.println(nextLine);
matcher = r.matcher(nextLine);
result = matcher.replaceAll(substitution);
System.out.println(result);
if (result.length() != 0) {
count++;
writer.write(result);
writer.newLine();
pGui.addLog(result);
pGui.updateProgressBar(count);
}
//} else continue;
}
writer.close();
}
catch (IOException e)
{
pGui.addLog(e.toString());
}
break;
}
}
return null;
}
@Override
protected void done() {
pGui.addLog("Conversion finished!");
pGui.addLog("--------------------------------------");
}
}
//button action to close the program
class CloseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
pGui.dispose();
}
}
}
| Koenzk/bigmovie | BigDataGUI/src/bigdata/Controller.java | 4,354 | //doorgegeven aan de Parser. | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bigdata;
import java.awt.event.ActionEvent;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
/**
*
* @author HP
*/
public class Controller {
private ParserGUI pGui;
public Controller(ParserGUI pGui) {
this.pGui = pGui;
this.pGui.setVisible(true);
this.pGui.setActions(new BrowseAction(), new OutputAction(), new ParseAction(), new CloseAction());
}
//button action for selecting file to parse
class BrowseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser input = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
input.setDialogTitle("Select a list file");
input.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(".list files", "list");
input.addChoosableFileFilter(filter);
int result = input.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
pGui.updateInputPath(selectedFile.getPath());
}
}
}
//button action for selecting directory to export .csv file into
class OutputAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e){
JFileChooser output = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
output.setDialogTitle("Choose a directory to save your file in:");
output.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// output.setAcceptAllFileFilterUsed(false);
int result = output.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
pGui.updateOutputPath(output.getCurrentDirectory().getPath() + "/");
}
}
}
//button action to begin parsing file
class ParseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
pGui.addLog("---------------------------------------");
File f = new File(pGui.getInputPath());
FileReader fr;
BufferedReader br;
int linesToSkip = 0;
String pattern;
String[] header;
String substitution;
String result;
String option = "test";
String outpath;
int[] substitutions;
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
//Path path = Paths.get(pGui.getInputPath());
//Stream<String> stream = Files.lines(path);
} catch (IOException err) {
pGui.addLog(err.toString());
return;
}
switch (f.getName()) {
case "countries.list": {
pattern = "\"?(.*?)\"?\\s\\((.{4,7}|\\?\\?\\?\\?|\\d{4}\\/.*)\\)\\s*(\\((.*)\\))?\\s*(\\{([^\\{}]*)\\})?\\s(\\{(SUSPENDED)\\})?\\s*(.*)";
substitution = "$1; $2; $6; $9";
header = new String[]{};
linesToSkip = 14;
substitutions = null;
result = "countries.csv";
break;
}
case "movies.list": {
pattern = "\\s?([^\"].*[^\"])\\s(?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\))\\s(\\((.{1,2})\\))?\\s*(\\{\\{(.*?)\\}\\})?\\s*(\\d{4}|\\?{4})";
substitution = "$1; $2; $8";
header = new String[]{};
linesToSkip = 14;
substitutions = null;
result = "movies.csv";
break;
}
case "series.list": {
pattern = "\\\"(.*?)\\\"\\s\\((.*?)\\)\\s(\\{([^\\{].*?[^\\}])\\})?\\s*(\\{(.*?)\\})?\\s*(.{4,9})";
substitution = "$1; $2; $4; $7";
header = new String[]{};
linesToSkip = 15;
substitutions = null;
result = "series.csv";
break;
}
case "actors.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $12; $15; $18";
header = new String[]{};
linesToSkip = 239;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 12, 15, 18};
result = "actors.csv";
break;
}
case "actresses.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $12; $15; $18";
header = new String[]{};
linesToSkip = 241;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 12, 15, 18};
result = "actresses.csv";
break;
}
case "directors.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $11; $15";
header = new String[]{};
linesToSkip = 235;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 11, 15};
result = "directors.csv";
break;
}
case "producers.list": {
pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?";
substitution = "$1; $3; $6; $9; $11; $15";
header = new String[]{};
linesToSkip = 219;
option = "tabbed";
substitutions = new int[]{3, 6, 9, 11, 15};
result = "producers.csv";
break;
}
case "ratings.list": {
pattern = "(.{20}) ([0-9]\\.[0-9]) (.+) (?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\)) ?(\\{(.+)\\}?)?";
substitution = "$2; $3; $4; $7";
header = new String[]{};
linesToSkip = 28;
substitutions = null;
result = "ratings.csv";
break;
}
case "running-times.list": {
pattern = "(?:\")(.*)(?:\") \\((\\d{4}|[?]{4})\\W(?:.*\\{|.*\\))?(.*\\))?(?:.*\\t|.*:)((\\d)?(\\d))(?:.*)";
substitution = "$1, $2, $3, $4";
header = new String[]{};
linesToSkip = 14;
substitutions = null;
result = "running-times.csv";
break;
}
default: {
pattern = "";
substitution = "";
header = new String[]{};
pGui.addLog("List not found.");
result = null;
option = null;
substitutions = null;
linesToSkip = 0;
break;
}
}
outpath = pGui.getOutputPath() + result;
new Parser(pattern, substitution, header, outpath, br, fr, linesToSkip, option, substitutions).execute();
}
}
//de hele parser klasse staat hieronder en is ge-extend naar swingworker zodat de parse-operatie in een achtergroundthread gebeurt zodat
//de UI niet tijdens de operatie vast loopt. Er wordt in de vorige switch-case gekeken wat voor lijst is geselecteerd en daarvan wordt de filepath (outpath)
//doorgegeven aan<SUF>
class Parser extends SwingWorker<Void, Void> {
private String pattern;
private String substitution;
private String[] header;
private String outpath;
private BufferedReader br;
private FileReader fr;
private String nextLine;
private String result;
private Matcher matcher;
private Pattern r;
private int count;
private String current;
private int linesToSkip;
private String option;
private int[] subs;
public Parser(String pattern, String substitution, String[] header, String outpath, BufferedReader br, FileReader fr, int linesToSkip, String option, int[] subs) {
this.pattern = pattern;
this.substitution = substitution;
this.header = header;
this.outpath = outpath;
this.br = br;
this.fr = fr;
this.linesToSkip = linesToSkip;
this.option = option;
count = 0;
current = "";
this.subs = subs;
}
public int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int cnt = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++cnt;
}
}
}
return (cnt == 0 && !empty) ? 1 : cnt;
} finally {
is.close();
}
}
@Override
protected Void doInBackground() throws IOException{
int lineNumber = 0;
int lts = this.linesToSkip;
pGui.setProgressBar(countLines(pGui.getInputPath()) - lts); //set progress bar length to amount of lines in file minus lts
switch(option){
case "tabbed": {
String prevName = "";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath)))
{
r = Pattern.compile(pattern);
while ((nextLine = br.readLine()) != null) {
if (++lineNumber <= lts) continue;
matcher = r.matcher(nextLine);
List<String> rows = new ArrayList<>();
if (matcher.find()) {
if (Objects.equals("", matcher.group(1))) {
rows.add(prevName);
for (int i : subs) {
rows.add("\t" + matcher.group(i));
}
} else {
rows.add(matcher.group(1));
for (int i : subs) {
rows.add("\t" + matcher.group(i));
}
prevName = matcher.group(1);
}
}
//if (!nextLine.startsWith("\"")) {
// System.out.println(nextLine);
StringBuilder lineString = new StringBuilder();
for (String row : rows) {
if (row != null) {
row = row.trim();
}
// System.out.println(lineString);
assert row != null;
lineString.append(row.trim()).append(";\t");
}
result = matcher.replaceAll(substitution);
System.out.println(result);
if (lineString.length() != 0) {
count++; //update current line count
writer.write(lineString.toString());
pGui.addLog(result); //prints converted data to log
pGui.updateProgressBar(count); //update progress bar
writer.newLine();
}
//} else continue;
}
writer.close();
}
catch (IOException e)
{
pGui.addLog(e.toString());
}
break;
}
default: {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath)))
{
r = Pattern.compile(pattern);
while ((nextLine = br.readLine()) != null) {
if (++lineNumber <= lts) continue;
//if (!nextLine.startsWith("\"")) {
// System.out.println(nextLine);
matcher = r.matcher(nextLine);
result = matcher.replaceAll(substitution);
System.out.println(result);
if (result.length() != 0) {
count++;
writer.write(result);
writer.newLine();
pGui.addLog(result);
pGui.updateProgressBar(count);
}
//} else continue;
}
writer.close();
}
catch (IOException e)
{
pGui.addLog(e.toString());
}
break;
}
}
return null;
}
@Override
protected void done() {
pGui.addLog("Conversion finished!");
pGui.addLog("--------------------------------------");
}
}
//button action to close the program
class CloseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
pGui.dispose();
}
}
}
|
67743_9 | /*
* Copyright (c) 2021 Kokhaviel.
*
* 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 fr.kokhaviel.api.hypixel.games;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* Tnt Games Hypixel Player Statistics
*
* @author Kokhaviel
* @since 1.0
*/
public class TntGames {
/**
* Tnt Games Coins
*/
@SerializedName("coins")
int coins = 0;
/**
* Bow Spleef Deaths
*/
@SerializedName("deaths_bowspleef")
int bowSpleefDeaths = 0;
/**
* Capture Deaths
*/
@SerializedName("deaths_capture")
int captureDeaths = 0;
/**
* Tnt Run Double Jump
*/
@SerializedName("doublejump_tntrun")
int doubleJumpTntRun = 0;
/**
* Capture Kills
*/
@SerializedName("kills_capture")
int captureKills = 0;
/**
* Packages (Cosmetics) Unlocked
*/
@SerializedName("packages")
List<String> packagesUnlocked = new ArrayList<>();
/**
* Bow Spleef Double Jump
*/
@SerializedName("spleef_doublejump")
int spleefDoubleJump = 0;
/**
* Bow Spleef Repulse Level
*/
@SerializedName("spleef_repulse")
int spleefRepulse = 0;
/**
* Bow Spleef Triple Shot
*/
@SerializedName("spleef_triple")
int spleefTripleShot = 0;
/**
* Bow Spleef Tags
*/
@SerializedName("tags_bowspleef")
int spleefTags = 0;
/**
* Bow Spleef Wins
*/
@SerializedName("wins_bowspleef")
int spleefWins = 0;
/**
* Capture Wins
*/
@SerializedName("wins_capture")
int captureWins = 0;
/**
* Tnt Tag Wins
*/
@SerializedName("wins_tntag")
int tntTagWins = 0;
/**
* Tnt Run Wins
*/
@SerializedName("wins_tntrun")
int tntRunWins = 0;
/**
* Capture Current Class in Use
*/
@SerializedName("capture_class")
String captureClass = "";
/**
* Tnt Tag Kills
*/
@SerializedName("kills_tntag")
int tntTagKills = 0;
/**
* Capture Assists
*/
@SerializedName("assists_capture")
int captureAssists = 0;
/**
* Tnt Run Record
*/
@SerializedName("record_tntrun")
int tntRunRecord = 0;
/**
* Tnt Tag Speed
*/
@SerializedName("tag_speed")
int tntTagSpeed = 0;
/**
* Pvp Run Record
*/
@SerializedName("record_pvprun")
int pvpRunRecord = 0;
/**
* Pvp Run Wins
*/
@SerializedName("wins_pvprun")
int pvpRunWins = 0;
/**
* Pvp Run Kills
*/
@SerializedName("kills_pvprun")
int pvpRunKills = 0;
/**
* Current Particle Effect in Use
*/
@SerializedName("active_particle_effect")
String particleEffect = "";
/**
* Current Death Effect in Use
*/
@SerializedName("active_death_effect")
String deathEffect = "";
/**
* Current Tnt Games Winstreak
*/
@SerializedName("winstreak")
int winstreak = 0;
/**
* Blast Protection Tags
*/
@SerializedName("tag_blastprotection")
int blastprotectionTags = 0;
/**
* Slow It Down Tags
*/
@SerializedName("tag_slowitdown")
int slowItDownTags = 0;
/**
* Speed It Up Tags
*/
@SerializedName("tag_speeditup")
int speedItUpTags = 0;
/**
* Tnt Run Speed Potions
*/
@SerializedName("new_tntrun_speed_potions")
int tntRunSpeedPotions = 0;
/**
* Tnt Run Slowness Potions
*/
@SerializedName("new_tntrun_slowness_potions")
int tntRunSlownessPotions = 0;
/**
* Tnt Run Potions Splashed On Players
*/
@SerializedName("run_potions_splashed_on_players")
int potionsSplashed = 0;
/**
* Pvp Run Notoriety
*/
@SerializedName("new_pvprun_notoriety")
int pvpRunNotoriety = 0;
/**
* Pvp Run Fortitude
*/
@SerializedName("new_pvprun_fortitude")
int pvpRunFortitude = 0;
/**
* Pvp Run Regeneration
*/
@SerializedName("new_pvprun_regeneration")
int pvpRunRegeneration = 0;
/**
* Pvp Run Deaths
*/
@SerializedName("deaths_pvprun")
int pvpRunDeaths = 0;
/**
* Tnt Run Deaths
*/
@SerializedName("deaths_tntrun")
int tntRunDeaths = 0;
/**
* Current Wizards Class in Use
*/
@SerializedName("wizards_selected_class")
String WizardsClass = "";
/**
* Total Tnt Games Wins
*/
@SerializedName("wins")
int wins = 0;
/**
* Capture Points
*/
@SerializedName("points_capture")
int capturePoints = 0;
/**
* Bow Spleef Arrows Rain Level
*/
@SerializedName("new_spleef_arrowrain")
int spleefArrowsRain = 0;
/**
* Bow Spleef Explosive Dash level
*/
@SerializedName("new_spleef_exlosive_dash")
int spleefExplosiveDash = 0;
/**
* Capture Time Elapsed in Air
*/
@SerializedName("air_time_capture")
int captureAirTime = 0;
/**
* Get Tnt Games Coins of the Player
*
* @return Tnt Games Coins
*/
public int getCoins() {
return coins;
}
/**
* Get Bow Spleef Deaths of the Player
*
* @return Number Bow Spleef Deaths
*/
public int getBowSpleefDeaths() {
return bowSpleefDeaths;
}
/**
* Get Capture Deaths of the Player
*
* @return Number of Capture Deaths
*/
public int getCaptureDeaths() {
return captureDeaths;
}
/**
* Get Current Tnt Run Double Jumps of the Player
*
* @return Tnt Run Double Jumps
*/
public int getDoubleJumpTntRun() {
return doubleJumpTntRun;
}
/**
* Get Capture Kills of the Player
*
* @return Capture Kills
*/
public int getCaptureKills() {
return captureKills;
}
/**
* Get All Unlocked Tnt Games Packages of the Player
*
* @return List of All Tnt Games Unlocked Packages
*/
public List<String> getPackagesUnlocked() {
return packagesUnlocked;
}
/**
* Get Current Bow Spleef Double Jumps of the Player
*
* @return Bow Spleef Double Jumps
*/
public int getSpleefDoubleJump() {
return spleefDoubleJump;
}
/**
* Get Bow Spleef Repulse Level of the Player
*
* @return Bow Spleef Repulse Level
*/
public int getSpleefRepulse() {
return spleefRepulse;
}
/**
* Get Bow Spleef Triple Shot Level of the Player
*
* @return Bow Spleef Triple Shot Level
*/
public int getSpleefTripleShot() {
return spleefTripleShot;
}
/**
* Get Bow Spleef Tags of the Player
*
* @return Bow Spleef Tags
*/
public int getSpleefTags() {
return spleefTags;
}
/**
* Get Bow Spleef Wins of the Player
*
* @return Bow Spleef Wins
*/
public int getSpleefWins() {
return spleefWins;
}
/**
* Get Capture Wins of the Player
*
* @return Capture Wins
*/
public int getCaptureWins() {
return captureWins;
}
/**
* Get Tnt Tag Wins of the Player
*
* @return Tnt Tag Wins
*/
public int getTntTagWins() {
return tntTagWins;
}
/**
* Get Tnt Run Wins of the Player
*
* @return Tnt Run Wins
*/
public int getTntRunWins() {
return tntRunWins;
}
/**
* Get Current Capture Class of the Player
*
* @return Current Capture Class
*/
public String getCaptureClass() {
return captureClass;
}
/**
* Get Tnt Tag Kills of the Player
*
* @return Tnt Tag kills
*/
public int getTntTagKills() {
return tntTagKills;
}
/**
* Get Capture Assists of the Player
*
* @return Capture Assists
*/
public int getCaptureAssists() {
return captureAssists;
}
/**
* Get Tnt Run Record of the Player
*
* @return Tnt Run Record
*/
public int getTntRunRecord() {
return tntRunRecord;
}
/**
* Get Tnt Tag Speed Level of the Player
*
* @return Tnt Tag Speed Level
*/
public int getTntTagSpeed() {
return tntTagSpeed;
}
/**
* Get Pvp Run Record of the Player
*
* @return Pvp Run Record
*/
public int getPvpRunRecord() {
return pvpRunRecord;
}
/**
* Get Pvp Run Wins of the Player
*
* @return Pvp Run Wins
*/
public int getPvpRunWins() {
return pvpRunWins;
}
/**
* Get Pvp Run Kills of the Player
*
* @return Pvp Run Kills
*/
public int getPvpRunKills() {
return pvpRunKills;
}
/**
* Get Current Particle Effect of the Player
*
* @return Current Particle Effect
*/
public String getParticleEffect() {
return particleEffect;
}
/**
* Get Current Death Effect of the Player
*
* @return Current Death Effect
*/
public String getDeathEffect() {
return deathEffect;
}
/**
* Get Current Tnt Games Winstreak of the Player
*
* @return Winstreak
*/
public int getWinstreak() {
return winstreak;
}
/**
* Get Blast Protection Tags of the Player
*
* @return Blast Protection Tags
*/
public int getBlastprotectionTags() {
return blastprotectionTags;
}
/**
* Get Slow It Down Tags of the Player
*
* @return Slow It Down Tags
*/
public int getSlowItDownTags() {
return slowItDownTags;
}
/**
* Get Speed It Up Tags of the Player
*
* @return Speed It Up Tags
*/
public int getSpeedItUpTags() {
return speedItUpTags;
}
/**
* Get Tnt Run Speed Potions of the Player (At Start of the Game)
*
* @return Tnt Run Speed Potions
*/
public int getTntRunSpeedPotions() {
return tntRunSpeedPotions;
}
/**
* Get Tnt Run Slowness Potions of the Player (At Start of the Game)
*
* @return Tnt Run Slowness Potions
*/
public int getTntRunSlownessPotions() {
return tntRunSlownessPotions;
}
/**
* Get Potions Splashed on others Players
*
* @return Potions Splashed
*/
public int getPotionsSplashed() {
return potionsSplashed;
}
/**
* Get Pvp Run Notoriety Level of the Player
*
* @return Pvp Run Notoriety Level
*/
public int getPvpRunNotoriety() {
return pvpRunNotoriety;
}
/**
* Get Pvp Run Fortitude Level of the Player
*
* @return Pvp Run Fortitude Level
*/
public int getPvpRunFortitude() {
return pvpRunFortitude;
}
/**
* Get Pvp Run Regeneration Level of the Player
*
* @return Pvp Run Regeneration Level
*/
public int getPvpRunRegeneration() {
return pvpRunRegeneration;
}
/**
* Get Pvp Run Deaths of the Player
*
* @return Pvp Run Deaths
*/
public int getPvpRunDeaths() {
return pvpRunDeaths;
}
/**
* Get Tnt Run Deaths of the Player
*
* @return Tnt Run Deaths
*/
public int getTntRunDeaths() {
return tntRunDeaths;
}
/**
* Get Current Wizards Class of the Player
*
* @return Current Wizards Class
*/
public String getWizardsClass() {
return WizardsClass;
}
/**
* Get Total Tnt Games Wins of the Player
*
* @return Tnt Games Wins
*/
public int getWins() {
return wins;
}
/**
* Get Capture points of the player
*
* @return Capture Points
*/
public int getCapturePoints() {
return capturePoints;
}
/**
* Get Bow Spleef Arrows Rain Level of the Player
*
* @return Bow Spleef Arrows Rain Level
*/
public int getSpleefArrowsRain() {
return spleefArrowsRain;
}
/**
* Get Bow Spleef Explosive Dash of the Player
*
* @return Bow Spleef Explosive Dash
*/
public int getSpleefExplosiveDash() {
return spleefExplosiveDash;
}
/**
* Get Capture Elapsed Time in Air of the Player
*
* @return Capture Air Time
*/
public int getCaptureAirTime() {
return captureAirTime;
}
@Override
public String toString() {
return "TntGames{" +
"coins=" + coins +
", bowSpleefDeaths=" + bowSpleefDeaths +
", captureDeaths=" + captureDeaths +
", doubleJumpTntRun=" + doubleJumpTntRun +
", captureKills=" + captureKills +
", packagesUnlocked=" + packagesUnlocked +
", spleefDoubleJump=" + spleefDoubleJump +
", spleefRepulse=" + spleefRepulse +
", spleefTripleShot=" + spleefTripleShot +
", spleefTags=" + spleefTags +
", spleefWins=" + spleefWins +
", captureWins=" + captureWins +
", tntTagWins=" + tntTagWins +
", tntRunWins=" + tntRunWins +
", captureClass='" + captureClass + '\'' +
", tntTagKills=" + tntTagKills +
", captureAssists=" + captureAssists +
", tntRunRecord=" + tntRunRecord +
", tntTagSpeed=" + tntTagSpeed +
", pvpRunRecord=" + pvpRunRecord +
", pvpRunWins=" + pvpRunWins +
", pvpRunKills=" + pvpRunKills +
", particleEffect='" + particleEffect + '\'' +
", deathEffect='" + deathEffect + '\'' +
", winstreak=" + winstreak +
", blastprotectionTags=" + blastprotectionTags +
", slowItDownTags=" + slowItDownTags +
", speedItUpTags=" + speedItUpTags +
", tntRunSpeedPotions=" + tntRunSpeedPotions +
", tntRunSlownessPotions=" + tntRunSlownessPotions +
", potionsSplashed=" + potionsSplashed +
", pvpRunNotoriety=" + pvpRunNotoriety +
", pvpRunFortitude=" + pvpRunFortitude +
", pvpRunRegeneration=" + pvpRunRegeneration +
", pvpRunDeaths=" + pvpRunDeaths +
", tntRunDeaths=" + tntRunDeaths +
", WizardsClass='" + WizardsClass + '\'' +
", wins=" + wins +
", capturePoints=" + capturePoints +
", spleefArrowsRain=" + spleefArrowsRain +
", spleefExplosiveDash=" + spleefExplosiveDash +
", captureAirTime=" + captureAirTime +
'}';
}
}
| Kokhaviel/HypixelAPI4J | src/main/java/fr/kokhaviel/api/hypixel/games/TntGames.java | 5,025 | /**
* Bow Spleef Repulse Level
*/ | block_comment | nl | /*
* Copyright (c) 2021 Kokhaviel.
*
* 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 fr.kokhaviel.api.hypixel.games;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* Tnt Games Hypixel Player Statistics
*
* @author Kokhaviel
* @since 1.0
*/
public class TntGames {
/**
* Tnt Games Coins
*/
@SerializedName("coins")
int coins = 0;
/**
* Bow Spleef Deaths
*/
@SerializedName("deaths_bowspleef")
int bowSpleefDeaths = 0;
/**
* Capture Deaths
*/
@SerializedName("deaths_capture")
int captureDeaths = 0;
/**
* Tnt Run Double Jump
*/
@SerializedName("doublejump_tntrun")
int doubleJumpTntRun = 0;
/**
* Capture Kills
*/
@SerializedName("kills_capture")
int captureKills = 0;
/**
* Packages (Cosmetics) Unlocked
*/
@SerializedName("packages")
List<String> packagesUnlocked = new ArrayList<>();
/**
* Bow Spleef Double Jump
*/
@SerializedName("spleef_doublejump")
int spleefDoubleJump = 0;
/**
* Bow Spleef Repulse<SUF>*/
@SerializedName("spleef_repulse")
int spleefRepulse = 0;
/**
* Bow Spleef Triple Shot
*/
@SerializedName("spleef_triple")
int spleefTripleShot = 0;
/**
* Bow Spleef Tags
*/
@SerializedName("tags_bowspleef")
int spleefTags = 0;
/**
* Bow Spleef Wins
*/
@SerializedName("wins_bowspleef")
int spleefWins = 0;
/**
* Capture Wins
*/
@SerializedName("wins_capture")
int captureWins = 0;
/**
* Tnt Tag Wins
*/
@SerializedName("wins_tntag")
int tntTagWins = 0;
/**
* Tnt Run Wins
*/
@SerializedName("wins_tntrun")
int tntRunWins = 0;
/**
* Capture Current Class in Use
*/
@SerializedName("capture_class")
String captureClass = "";
/**
* Tnt Tag Kills
*/
@SerializedName("kills_tntag")
int tntTagKills = 0;
/**
* Capture Assists
*/
@SerializedName("assists_capture")
int captureAssists = 0;
/**
* Tnt Run Record
*/
@SerializedName("record_tntrun")
int tntRunRecord = 0;
/**
* Tnt Tag Speed
*/
@SerializedName("tag_speed")
int tntTagSpeed = 0;
/**
* Pvp Run Record
*/
@SerializedName("record_pvprun")
int pvpRunRecord = 0;
/**
* Pvp Run Wins
*/
@SerializedName("wins_pvprun")
int pvpRunWins = 0;
/**
* Pvp Run Kills
*/
@SerializedName("kills_pvprun")
int pvpRunKills = 0;
/**
* Current Particle Effect in Use
*/
@SerializedName("active_particle_effect")
String particleEffect = "";
/**
* Current Death Effect in Use
*/
@SerializedName("active_death_effect")
String deathEffect = "";
/**
* Current Tnt Games Winstreak
*/
@SerializedName("winstreak")
int winstreak = 0;
/**
* Blast Protection Tags
*/
@SerializedName("tag_blastprotection")
int blastprotectionTags = 0;
/**
* Slow It Down Tags
*/
@SerializedName("tag_slowitdown")
int slowItDownTags = 0;
/**
* Speed It Up Tags
*/
@SerializedName("tag_speeditup")
int speedItUpTags = 0;
/**
* Tnt Run Speed Potions
*/
@SerializedName("new_tntrun_speed_potions")
int tntRunSpeedPotions = 0;
/**
* Tnt Run Slowness Potions
*/
@SerializedName("new_tntrun_slowness_potions")
int tntRunSlownessPotions = 0;
/**
* Tnt Run Potions Splashed On Players
*/
@SerializedName("run_potions_splashed_on_players")
int potionsSplashed = 0;
/**
* Pvp Run Notoriety
*/
@SerializedName("new_pvprun_notoriety")
int pvpRunNotoriety = 0;
/**
* Pvp Run Fortitude
*/
@SerializedName("new_pvprun_fortitude")
int pvpRunFortitude = 0;
/**
* Pvp Run Regeneration
*/
@SerializedName("new_pvprun_regeneration")
int pvpRunRegeneration = 0;
/**
* Pvp Run Deaths
*/
@SerializedName("deaths_pvprun")
int pvpRunDeaths = 0;
/**
* Tnt Run Deaths
*/
@SerializedName("deaths_tntrun")
int tntRunDeaths = 0;
/**
* Current Wizards Class in Use
*/
@SerializedName("wizards_selected_class")
String WizardsClass = "";
/**
* Total Tnt Games Wins
*/
@SerializedName("wins")
int wins = 0;
/**
* Capture Points
*/
@SerializedName("points_capture")
int capturePoints = 0;
/**
* Bow Spleef Arrows Rain Level
*/
@SerializedName("new_spleef_arrowrain")
int spleefArrowsRain = 0;
/**
* Bow Spleef Explosive Dash level
*/
@SerializedName("new_spleef_exlosive_dash")
int spleefExplosiveDash = 0;
/**
* Capture Time Elapsed in Air
*/
@SerializedName("air_time_capture")
int captureAirTime = 0;
/**
* Get Tnt Games Coins of the Player
*
* @return Tnt Games Coins
*/
public int getCoins() {
return coins;
}
/**
* Get Bow Spleef Deaths of the Player
*
* @return Number Bow Spleef Deaths
*/
public int getBowSpleefDeaths() {
return bowSpleefDeaths;
}
/**
* Get Capture Deaths of the Player
*
* @return Number of Capture Deaths
*/
public int getCaptureDeaths() {
return captureDeaths;
}
/**
* Get Current Tnt Run Double Jumps of the Player
*
* @return Tnt Run Double Jumps
*/
public int getDoubleJumpTntRun() {
return doubleJumpTntRun;
}
/**
* Get Capture Kills of the Player
*
* @return Capture Kills
*/
public int getCaptureKills() {
return captureKills;
}
/**
* Get All Unlocked Tnt Games Packages of the Player
*
* @return List of All Tnt Games Unlocked Packages
*/
public List<String> getPackagesUnlocked() {
return packagesUnlocked;
}
/**
* Get Current Bow Spleef Double Jumps of the Player
*
* @return Bow Spleef Double Jumps
*/
public int getSpleefDoubleJump() {
return spleefDoubleJump;
}
/**
* Get Bow Spleef Repulse Level of the Player
*
* @return Bow Spleef Repulse Level
*/
public int getSpleefRepulse() {
return spleefRepulse;
}
/**
* Get Bow Spleef Triple Shot Level of the Player
*
* @return Bow Spleef Triple Shot Level
*/
public int getSpleefTripleShot() {
return spleefTripleShot;
}
/**
* Get Bow Spleef Tags of the Player
*
* @return Bow Spleef Tags
*/
public int getSpleefTags() {
return spleefTags;
}
/**
* Get Bow Spleef Wins of the Player
*
* @return Bow Spleef Wins
*/
public int getSpleefWins() {
return spleefWins;
}
/**
* Get Capture Wins of the Player
*
* @return Capture Wins
*/
public int getCaptureWins() {
return captureWins;
}
/**
* Get Tnt Tag Wins of the Player
*
* @return Tnt Tag Wins
*/
public int getTntTagWins() {
return tntTagWins;
}
/**
* Get Tnt Run Wins of the Player
*
* @return Tnt Run Wins
*/
public int getTntRunWins() {
return tntRunWins;
}
/**
* Get Current Capture Class of the Player
*
* @return Current Capture Class
*/
public String getCaptureClass() {
return captureClass;
}
/**
* Get Tnt Tag Kills of the Player
*
* @return Tnt Tag kills
*/
public int getTntTagKills() {
return tntTagKills;
}
/**
* Get Capture Assists of the Player
*
* @return Capture Assists
*/
public int getCaptureAssists() {
return captureAssists;
}
/**
* Get Tnt Run Record of the Player
*
* @return Tnt Run Record
*/
public int getTntRunRecord() {
return tntRunRecord;
}
/**
* Get Tnt Tag Speed Level of the Player
*
* @return Tnt Tag Speed Level
*/
public int getTntTagSpeed() {
return tntTagSpeed;
}
/**
* Get Pvp Run Record of the Player
*
* @return Pvp Run Record
*/
public int getPvpRunRecord() {
return pvpRunRecord;
}
/**
* Get Pvp Run Wins of the Player
*
* @return Pvp Run Wins
*/
public int getPvpRunWins() {
return pvpRunWins;
}
/**
* Get Pvp Run Kills of the Player
*
* @return Pvp Run Kills
*/
public int getPvpRunKills() {
return pvpRunKills;
}
/**
* Get Current Particle Effect of the Player
*
* @return Current Particle Effect
*/
public String getParticleEffect() {
return particleEffect;
}
/**
* Get Current Death Effect of the Player
*
* @return Current Death Effect
*/
public String getDeathEffect() {
return deathEffect;
}
/**
* Get Current Tnt Games Winstreak of the Player
*
* @return Winstreak
*/
public int getWinstreak() {
return winstreak;
}
/**
* Get Blast Protection Tags of the Player
*
* @return Blast Protection Tags
*/
public int getBlastprotectionTags() {
return blastprotectionTags;
}
/**
* Get Slow It Down Tags of the Player
*
* @return Slow It Down Tags
*/
public int getSlowItDownTags() {
return slowItDownTags;
}
/**
* Get Speed It Up Tags of the Player
*
* @return Speed It Up Tags
*/
public int getSpeedItUpTags() {
return speedItUpTags;
}
/**
* Get Tnt Run Speed Potions of the Player (At Start of the Game)
*
* @return Tnt Run Speed Potions
*/
public int getTntRunSpeedPotions() {
return tntRunSpeedPotions;
}
/**
* Get Tnt Run Slowness Potions of the Player (At Start of the Game)
*
* @return Tnt Run Slowness Potions
*/
public int getTntRunSlownessPotions() {
return tntRunSlownessPotions;
}
/**
* Get Potions Splashed on others Players
*
* @return Potions Splashed
*/
public int getPotionsSplashed() {
return potionsSplashed;
}
/**
* Get Pvp Run Notoriety Level of the Player
*
* @return Pvp Run Notoriety Level
*/
public int getPvpRunNotoriety() {
return pvpRunNotoriety;
}
/**
* Get Pvp Run Fortitude Level of the Player
*
* @return Pvp Run Fortitude Level
*/
public int getPvpRunFortitude() {
return pvpRunFortitude;
}
/**
* Get Pvp Run Regeneration Level of the Player
*
* @return Pvp Run Regeneration Level
*/
public int getPvpRunRegeneration() {
return pvpRunRegeneration;
}
/**
* Get Pvp Run Deaths of the Player
*
* @return Pvp Run Deaths
*/
public int getPvpRunDeaths() {
return pvpRunDeaths;
}
/**
* Get Tnt Run Deaths of the Player
*
* @return Tnt Run Deaths
*/
public int getTntRunDeaths() {
return tntRunDeaths;
}
/**
* Get Current Wizards Class of the Player
*
* @return Current Wizards Class
*/
public String getWizardsClass() {
return WizardsClass;
}
/**
* Get Total Tnt Games Wins of the Player
*
* @return Tnt Games Wins
*/
public int getWins() {
return wins;
}
/**
* Get Capture points of the player
*
* @return Capture Points
*/
public int getCapturePoints() {
return capturePoints;
}
/**
* Get Bow Spleef Arrows Rain Level of the Player
*
* @return Bow Spleef Arrows Rain Level
*/
public int getSpleefArrowsRain() {
return spleefArrowsRain;
}
/**
* Get Bow Spleef Explosive Dash of the Player
*
* @return Bow Spleef Explosive Dash
*/
public int getSpleefExplosiveDash() {
return spleefExplosiveDash;
}
/**
* Get Capture Elapsed Time in Air of the Player
*
* @return Capture Air Time
*/
public int getCaptureAirTime() {
return captureAirTime;
}
@Override
public String toString() {
return "TntGames{" +
"coins=" + coins +
", bowSpleefDeaths=" + bowSpleefDeaths +
", captureDeaths=" + captureDeaths +
", doubleJumpTntRun=" + doubleJumpTntRun +
", captureKills=" + captureKills +
", packagesUnlocked=" + packagesUnlocked +
", spleefDoubleJump=" + spleefDoubleJump +
", spleefRepulse=" + spleefRepulse +
", spleefTripleShot=" + spleefTripleShot +
", spleefTags=" + spleefTags +
", spleefWins=" + spleefWins +
", captureWins=" + captureWins +
", tntTagWins=" + tntTagWins +
", tntRunWins=" + tntRunWins +
", captureClass='" + captureClass + '\'' +
", tntTagKills=" + tntTagKills +
", captureAssists=" + captureAssists +
", tntRunRecord=" + tntRunRecord +
", tntTagSpeed=" + tntTagSpeed +
", pvpRunRecord=" + pvpRunRecord +
", pvpRunWins=" + pvpRunWins +
", pvpRunKills=" + pvpRunKills +
", particleEffect='" + particleEffect + '\'' +
", deathEffect='" + deathEffect + '\'' +
", winstreak=" + winstreak +
", blastprotectionTags=" + blastprotectionTags +
", slowItDownTags=" + slowItDownTags +
", speedItUpTags=" + speedItUpTags +
", tntRunSpeedPotions=" + tntRunSpeedPotions +
", tntRunSlownessPotions=" + tntRunSlownessPotions +
", potionsSplashed=" + potionsSplashed +
", pvpRunNotoriety=" + pvpRunNotoriety +
", pvpRunFortitude=" + pvpRunFortitude +
", pvpRunRegeneration=" + pvpRunRegeneration +
", pvpRunDeaths=" + pvpRunDeaths +
", tntRunDeaths=" + tntRunDeaths +
", WizardsClass='" + WizardsClass + '\'' +
", wins=" + wins +
", capturePoints=" + capturePoints +
", spleefArrowsRain=" + spleefArrowsRain +
", spleefExplosiveDash=" + spleefExplosiveDash +
", captureAirTime=" + captureAirTime +
'}';
}
}
|
60551_0 | package features;
import static features.hero.timeStampToDate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import starlight.*;
import static starlight.CommandParser.unknownUser;
import static starlight.CommandParser.userIsOffline;
import tools.*;
import tools.database.ConnectionPool;
import tools.database.PoolConnection;
import tools.popup.*;
public class fanifybutler {
public static Long time = System.currentTimeMillis()/1000;
public static void functionMake(Client client,Channel channel, String arg) {
String[] l = client.getFeature("Butler-Fan");
Feature ft = Server.get().getFeature("Butler-Fan");
if (ft == null) {
return;
}
if (l[0].equals("0")) {
client.sendButlerMessage(channel.getName(),"Du hast das "+ft.getName()+" Feature nicht.");
return;
}
if (l[0].equals("1")) {
client.sendButlerMessage(channel.getName(),"Du kannst das Feature "+ft.getName()+" erst am "+timeStampToDate(Long.parseLong(l[5]))+" Uhr wieder nutzen.");
return;
}
boolean on = true;
Client target = Server.get().getClient(arg);
if (target == null) {
target = new Client(null);
on = false;
target.loadStats(arg);
}
if (arg.isEmpty()) {
client.sendButlerMessage(channel.getName(),"Verwende _/fanifybutler NICK_ um James Fan von Nick werden zu lassen.");
return;
}
if(target.getName() == null) {
client.sendButlerMessage(channel.getName(), unknownUser(arg));
return;
}
if(!on) {
client.sendButlerMessage(channel.getName(), userIsOffline(target));
return;
}
if (target == client) {
client.sendButlerMessage(channel.getName(),"Mit dir selbst geht das aber nicht.");
return;
}
if (target == Server.get().getButler()) {
client.sendButlerMessage(channel.getName(),String.format(Server.get().getButler().getName()+" kannst du nicht auswählen."));
return;
}
boolean isFan = false;
PoolConnection pcon3 = ConnectionPool.getConnection();
PreparedStatement ps3 = null;
try
{
Connection con = pcon3.connect();
ps3 = con.prepareStatement("SELECT * FROM `fans` where von='"+Server.get().getButler().getName()+"' and an='"+target.getName()+"'");
ResultSet rs3 = ps3.executeQuery();
while (rs3.next()) {
isFan = true;
}
}
catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps3 != null)
try {
ps3.close();
}
catch (SQLException e)
{
}
pcon3.close();
}
if (isFan) {
client.sendButlerMessage(channel.getName(),Server.get().getButler().getName()+" ist bereits ein Fan von "+target.getName());
return;
}
String text = "Ich bin hocherfreut, dass "+client.getName()+" uns einander vorgestellt hat und ich deine Bekanntschaft machen durfte. Ich hoffe, wir führen noch viele interessante Konversationen.\n\nHochachtungsvoll, dein "+Server.get().getButler().getName();
Server.get().query("insert into fans set von='"+Server.get().getButler().getName()+"', an='"+target.getName()+"', time='"+(System.currentTimeMillis()/1000)+"',typ='foto',text='"+text+"'");
target.setFans(target.getFans()+1);
target.saveStats();
target.sendButlerMessage(channel.getName(),"Soeben ist "+Server.get().getButler().getName()+" _°BB°°>_hdein Fan|http://heaven24.zapto.org/index.php?page=photo_fans&n="+target.getName()+"&photo<°°r°_ geworden");
Server.get().newMessage(Server.get().getButler().getName(), target.getName(),"", "Hallo "+target.getName()+",##soeben ist "+Server.get().getButler().getName()+" _°BB°°>_hdein Fan|http://heaven24.zapto.org/index.php?page=photo_fans&n="+target.getName()+"&photo<°°r°_ geworden und hat dir außerdem folgende Nachricht hinterlassen:##''Ich bin hocherfreut, dass "+client.getName()+ "uns einander vorgestellt hat und ich deine Bekanntschaft machen durfte. Ich hoffe, wir führen noch viele interessante Konversationen.##Hochachtungsvoll, dein "+Server.get().getButler().getName()+"''", (System.currentTimeMillis()/1000));
client.sendButlerMessage(channel.getName(),Server.get().getButler().getName()+" ist ab sofort ein Fan von "+target.getName());
}
} | Kokos-Ice/CuddlyChat-BETA | src/features/fanifybutler.java | 1,424 | //heaven24.zapto.org/index.php?page=photo_fans&n="+target.getName()+"&photo<°°r°_ geworden"); | line_comment | nl | package features;
import static features.hero.timeStampToDate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import starlight.*;
import static starlight.CommandParser.unknownUser;
import static starlight.CommandParser.userIsOffline;
import tools.*;
import tools.database.ConnectionPool;
import tools.database.PoolConnection;
import tools.popup.*;
public class fanifybutler {
public static Long time = System.currentTimeMillis()/1000;
public static void functionMake(Client client,Channel channel, String arg) {
String[] l = client.getFeature("Butler-Fan");
Feature ft = Server.get().getFeature("Butler-Fan");
if (ft == null) {
return;
}
if (l[0].equals("0")) {
client.sendButlerMessage(channel.getName(),"Du hast das "+ft.getName()+" Feature nicht.");
return;
}
if (l[0].equals("1")) {
client.sendButlerMessage(channel.getName(),"Du kannst das Feature "+ft.getName()+" erst am "+timeStampToDate(Long.parseLong(l[5]))+" Uhr wieder nutzen.");
return;
}
boolean on = true;
Client target = Server.get().getClient(arg);
if (target == null) {
target = new Client(null);
on = false;
target.loadStats(arg);
}
if (arg.isEmpty()) {
client.sendButlerMessage(channel.getName(),"Verwende _/fanifybutler NICK_ um James Fan von Nick werden zu lassen.");
return;
}
if(target.getName() == null) {
client.sendButlerMessage(channel.getName(), unknownUser(arg));
return;
}
if(!on) {
client.sendButlerMessage(channel.getName(), userIsOffline(target));
return;
}
if (target == client) {
client.sendButlerMessage(channel.getName(),"Mit dir selbst geht das aber nicht.");
return;
}
if (target == Server.get().getButler()) {
client.sendButlerMessage(channel.getName(),String.format(Server.get().getButler().getName()+" kannst du nicht auswählen."));
return;
}
boolean isFan = false;
PoolConnection pcon3 = ConnectionPool.getConnection();
PreparedStatement ps3 = null;
try
{
Connection con = pcon3.connect();
ps3 = con.prepareStatement("SELECT * FROM `fans` where von='"+Server.get().getButler().getName()+"' and an='"+target.getName()+"'");
ResultSet rs3 = ps3.executeQuery();
while (rs3.next()) {
isFan = true;
}
}
catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps3 != null)
try {
ps3.close();
}
catch (SQLException e)
{
}
pcon3.close();
}
if (isFan) {
client.sendButlerMessage(channel.getName(),Server.get().getButler().getName()+" ist bereits ein Fan von "+target.getName());
return;
}
String text = "Ich bin hocherfreut, dass "+client.getName()+" uns einander vorgestellt hat und ich deine Bekanntschaft machen durfte. Ich hoffe, wir führen noch viele interessante Konversationen.\n\nHochachtungsvoll, dein "+Server.get().getButler().getName();
Server.get().query("insert into fans set von='"+Server.get().getButler().getName()+"', an='"+target.getName()+"', time='"+(System.currentTimeMillis()/1000)+"',typ='foto',text='"+text+"'");
target.setFans(target.getFans()+1);
target.saveStats();
target.sendButlerMessage(channel.getName(),"Soeben ist "+Server.get().getButler().getName()+" _°BB°°>_hdein Fan|http://heaven24.zapto.org/index.php?page=photo_fans&n="+target.getName()+"&photo<°°r°_ geworden");<SUF>
Server.get().newMessage(Server.get().getButler().getName(), target.getName(),"", "Hallo "+target.getName()+",##soeben ist "+Server.get().getButler().getName()+" _°BB°°>_hdein Fan|http://heaven24.zapto.org/index.php?page=photo_fans&n="+target.getName()+"&photo<°°r°_ geworden und hat dir außerdem folgende Nachricht hinterlassen:##''Ich bin hocherfreut, dass "+client.getName()+ "uns einander vorgestellt hat und ich deine Bekanntschaft machen durfte. Ich hoffe, wir führen noch viele interessante Konversationen.##Hochachtungsvoll, dein "+Server.get().getButler().getName()+"''", (System.currentTimeMillis()/1000));
client.sendButlerMessage(channel.getName(),Server.get().getButler().getName()+" ist ab sofort ein Fan von "+target.getName());
}
} |
88380_3 | /**
* Copyright 2015 Ralph Jones
*
* 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.totalchange.servlicle;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* Extend this {@link HttpServlet servlet} to provide a decent way of streaming
* back files form somewhere other than your web application. Just extend this
* class and implement
* {@link #gimmeFile(HttpServletRequest, HttpServletResponse)}.
*/
public abstract class Servliclet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String[] SERVLICLERS = new String[] { "com.totalchange.servlicle.tomcat8.Tomcat8Servlicler" };
private HttpServlet wrapped;
/**
* @see HttpServlet#init()
*/
@Override
public void init() throws ServletException {
wrapped = whereAmI();
}
/**
* @see HttpServlet#doGet(HttpServletRequest)
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final File file = gimmeFile(request, response);
wrapped.service(new HttpServletRequestWrapper(request) {
@Override
public String getPathInfo() {
return null;
}
@Override
public String getServletPath() {
return file.getAbsolutePath();
}
}, response);
}
/**
* Return the file you want to be streamed back.
*
* @param request
* the originating request
* @param response
* the originating response
* @return the file you want to be returned in the response
*/
protected abstract File gimmeFile(HttpServletRequest request,
HttpServletResponse response);
private HttpServlet whereAmI() throws ServletException {
for (String servliclerClassName : SERVLICLERS) {
try {
HttpServlet servlicler = makeAndInitMe(servliclerClassName);
log("Servlicle can use " + servliclerClassName);
return servlicler;
} catch (Exception ex) {
log("Servlicle can't use " + servliclerClassName + " because "
+ ex.getMessage());
}
}
log("Servlicle is out of luck so you're stuck with a rubbish "
+ "Servlicler. Consider adding a new better one at "
+ "https://github.com/KolonelKustard/servlicle");
return makeRubbishOne();
}
private HttpServlet makeAndInitMe(String servliclerClassName)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException, ServletException {
HttpServlet servlicler = (HttpServlet) this.getClass().getClassLoader()
.loadClass(servliclerClassName).newInstance();
initMe(servlicler);
return servlicler;
}
private void initMe(HttpServlet servlicler) throws ServletException {
servlicler.init(getServletConfig());
}
private HttpServlet makeRubbishOne() throws ServletException {
HttpServlet servlicler = new RubbishServlicler();
initMe(servlicler);
return servlicler;
}
}
| KolonelKustard/servlicle | servlicle/src/main/java/com/totalchange/servlicle/Servliclet.java | 1,021 | /**
* @see HttpServlet#doGet(HttpServletRequest)
*/ | block_comment | nl | /**
* Copyright 2015 Ralph Jones
*
* 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.totalchange.servlicle;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* Extend this {@link HttpServlet servlet} to provide a decent way of streaming
* back files form somewhere other than your web application. Just extend this
* class and implement
* {@link #gimmeFile(HttpServletRequest, HttpServletResponse)}.
*/
public abstract class Servliclet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String[] SERVLICLERS = new String[] { "com.totalchange.servlicle.tomcat8.Tomcat8Servlicler" };
private HttpServlet wrapped;
/**
* @see HttpServlet#init()
*/
@Override
public void init() throws ServletException {
wrapped = whereAmI();
}
/**
* @see HttpServlet#doGet(HttpServletRequest)
<SUF>*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final File file = gimmeFile(request, response);
wrapped.service(new HttpServletRequestWrapper(request) {
@Override
public String getPathInfo() {
return null;
}
@Override
public String getServletPath() {
return file.getAbsolutePath();
}
}, response);
}
/**
* Return the file you want to be streamed back.
*
* @param request
* the originating request
* @param response
* the originating response
* @return the file you want to be returned in the response
*/
protected abstract File gimmeFile(HttpServletRequest request,
HttpServletResponse response);
private HttpServlet whereAmI() throws ServletException {
for (String servliclerClassName : SERVLICLERS) {
try {
HttpServlet servlicler = makeAndInitMe(servliclerClassName);
log("Servlicle can use " + servliclerClassName);
return servlicler;
} catch (Exception ex) {
log("Servlicle can't use " + servliclerClassName + " because "
+ ex.getMessage());
}
}
log("Servlicle is out of luck so you're stuck with a rubbish "
+ "Servlicler. Consider adding a new better one at "
+ "https://github.com/KolonelKustard/servlicle");
return makeRubbishOne();
}
private HttpServlet makeAndInitMe(String servliclerClassName)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException, ServletException {
HttpServlet servlicler = (HttpServlet) this.getClass().getClassLoader()
.loadClass(servliclerClassName).newInstance();
initMe(servlicler);
return servlicler;
}
private void initMe(HttpServlet servlicler) throws ServletException {
servlicler.init(getServletConfig());
}
private HttpServlet makeRubbishOne() throws ServletException {
HttpServlet servlicler = new RubbishServlicler();
initMe(servlicler);
return servlicler;
}
}
|
93121_7 | import java.util.List;
import org.objectweb.asm.tree.ClassNode;
import the.bytecode.club.bytecodeviewer.api.*;
/**
** [Plugin Description Goes Here]
**
** @author [Your Name Goes Here]
**/
public class Template extends Plugin {
PluginConsole gui;
/**
* Execute function - this gets executed when the plugin is ran
*/
@Override
public void execute(List<ClassNode> classNodeList) {
// Create & show the console
gui = new PluginConsole("Java Template");
gui.setVisible(true);
// Print out to the console
print("Class Nodes: " + classNodeList.size());
// Iterate through each class node
for (ClassNode cn : classNodeList)
processClassNode(cn);
// Hide the console after 10 seconds
BCV.hideFrame(gui, 10000);
}
/**
* Process each class node
*/
public void processClassNode(ClassNode cn) {
print("Node: " + cn.name + ".class");
//TODO developer plugin code goes here
}
/**
* Print to console
*/
public void print(String text) {
gui.appendText(text);
}
} | Konloch/bytecode-viewer | src/main/resources/templates/Template_Plugin.java | 341 | //TODO developer plugin code goes here | line_comment | nl | import java.util.List;
import org.objectweb.asm.tree.ClassNode;
import the.bytecode.club.bytecodeviewer.api.*;
/**
** [Plugin Description Goes Here]
**
** @author [Your Name Goes Here]
**/
public class Template extends Plugin {
PluginConsole gui;
/**
* Execute function - this gets executed when the plugin is ran
*/
@Override
public void execute(List<ClassNode> classNodeList) {
// Create & show the console
gui = new PluginConsole("Java Template");
gui.setVisible(true);
// Print out to the console
print("Class Nodes: " + classNodeList.size());
// Iterate through each class node
for (ClassNode cn : classNodeList)
processClassNode(cn);
// Hide the console after 10 seconds
BCV.hideFrame(gui, 10000);
}
/**
* Process each class node
*/
public void processClassNode(ClassNode cn) {
print("Node: " + cn.name + ".class");
//TODO developer<SUF>
}
/**
* Print to console
*/
public void print(String text) {
gui.appendText(text);
}
} |
173933_7 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package extented.impl;
import base.impl.MyBaseClassImpl;
import extented.ExtentedPackage;
import extented.MyExtendedClass;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>My Extended Class</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link extented.impl.MyExtendedClassImpl#getDetailedField <em>Detailed Field</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MyExtendedClassImpl extends MyBaseClassImpl implements MyExtendedClass {
/**
* The default value of the '{@link #getDetailedField() <em>Detailed Field</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDetailedField()
* @generated
* @ordered
*/
protected static final String DETAILED_FIELD_EDEFAULT = null;
/**
* The cached value of the '{@link #getDetailedField() <em>Detailed Field</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDetailedField()
* @generated
* @ordered
*/
protected String detailedField = DETAILED_FIELD_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MyExtendedClassImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ExtentedPackage.Literals.MY_EXTENDED_CLASS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getDetailedField() {
return detailedField;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDetailedField(String newDetailedField) {
String oldDetailedField = detailedField;
detailedField = newDetailedField;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD, oldDetailedField, detailedField));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
return getDetailedField();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
setDetailedField((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
setDetailedField(DETAILED_FIELD_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
return DETAILED_FIELD_EDEFAULT == null ? detailedField != null : !DETAILED_FIELD_EDEFAULT.equals(detailedField);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (detailedField: ");
result.append(detailedField);
result.append(')');
return result.toString();
}
} //MyExtendedClassImpl
| KorbinianK/vogella | de.vogella.emf.inheritance/src/extented/impl/MyExtendedClassImpl.java | 1,420 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package extented.impl;
import base.impl.MyBaseClassImpl;
import extented.ExtentedPackage;
import extented.MyExtendedClass;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>My Extended Class</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link extented.impl.MyExtendedClassImpl#getDetailedField <em>Detailed Field</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MyExtendedClassImpl extends MyBaseClassImpl implements MyExtendedClass {
/**
* The default value of the '{@link #getDetailedField() <em>Detailed Field</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDetailedField()
* @generated
* @ordered
*/
protected static final String DETAILED_FIELD_EDEFAULT = null;
/**
* The cached value of the '{@link #getDetailedField() <em>Detailed Field</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDetailedField()
* @generated
* @ordered
*/
protected String detailedField = DETAILED_FIELD_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MyExtendedClassImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ExtentedPackage.Literals.MY_EXTENDED_CLASS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getDetailedField() {
return detailedField;
}
/**
* <!-- begin-user-doc -->
<SUF>*/
public void setDetailedField(String newDetailedField) {
String oldDetailedField = detailedField;
detailedField = newDetailedField;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD, oldDetailedField, detailedField));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
return getDetailedField();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
setDetailedField((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
setDetailedField(DETAILED_FIELD_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ExtentedPackage.MY_EXTENDED_CLASS__DETAILED_FIELD:
return DETAILED_FIELD_EDEFAULT == null ? detailedField != null : !DETAILED_FIELD_EDEFAULT.equals(detailedField);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (detailedField: ");
result.append(detailedField);
result.append(')');
return result.toString();
}
} //MyExtendedClassImpl
|
80536_4 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import static org.openmrs.Order.Action.DISCONTINUE;
import org.apache.commons.lang3.StringUtils;
import org.openmrs.util.OpenmrsUtil;
/**
* DrugOrder
*
* @version 1.0
*/
public class DrugOrder extends Order {
public static final long serialVersionUID = 72232L;
// Fields
private Double dose;
private Concept doseUnits;
private OrderFrequency frequency;
private Boolean asNeeded = false;
private Double quantity;
private Concept quantityUnits;
private Drug drug;
private String asNeededCondition;
private Class<? extends DosingInstructions> dosingType = SimpleDosingInstructions.class;
private Integer numRefills;
private String dosingInstructions;
private Integer duration;
private Concept durationUnits;
private Concept route;
private String brandName;
private Boolean dispenseAsWritten = Boolean.FALSE;
private String drugNonCoded;
// Constructors
/** default constructor */
public DrugOrder() {
}
/** constructor with id */
public DrugOrder(Integer orderId) {
this.setOrderId(orderId);
}
/**
* @see org.openmrs.Order#copy()
* <strong>Should</strong> copy all drug order fields
*/
@Override
public DrugOrder copy() {
return copyHelper(new DrugOrder());
}
/**
* @see org.openmrs.Order#copyHelper(Order)
*/
protected DrugOrder copyHelper(DrugOrder target) {
super.copyHelper(target);
target.setDose(getDose());
target.setDoseUnits(getDoseUnits());
target.setFrequency(getFrequency());
target.setAsNeeded(getAsNeeded());
target.setAsNeededCondition(getAsNeededCondition());
target.setQuantity(getQuantity());
target.setQuantityUnits(getQuantityUnits());
target.setDrug(getDrug());
target.setDosingType(getDosingType());
target.setDosingInstructions(getDosingInstructions());
target.setDuration(getDuration());
target.setDurationUnits(getDurationUnits());
target.setNumRefills(getNumRefills());
target.setRoute(getRoute());
target.setBrandName(getBrandName());
target.setDispenseAsWritten(getDispenseAsWritten());
target.setDrugNonCoded(getDrugNonCoded());
return target;
}
public boolean isDrugOrder() {
return true;
}
// Property accessors
/**
* Gets the doseUnits of this drug order
*
* @return doseUnits
*/
public Concept getDoseUnits() {
return this.doseUnits;
}
/**
* Sets the doseUnits of this drug order
*
* @param doseUnits
*/
public void setDoseUnits(Concept doseUnits) {
this.doseUnits = doseUnits;
}
/**
* Gets the frequency
*
* @return frequency
* @since 1.10 (signature changed)
*/
public OrderFrequency getFrequency() {
return this.frequency;
}
/**
* Sets the frequency
*
* @param frequency
* @since 1.10 (signature changed)
*/
public void setFrequency(OrderFrequency frequency) {
this.frequency = frequency;
}
/**
* Returns true/false whether the drug is a "pro re nata" drug
*
* @return Boolean
* @since 1.10
*/
public Boolean getAsNeeded() {
return asNeeded;
}
/**
* @param asNeeded the value to set
* @since 1.10
*/
public void setAsNeeded(Boolean asNeeded) {
this.asNeeded = asNeeded;
}
/**
* Gets the quantity
*
* @return quantity
*/
public Double getQuantity() {
return this.quantity;
}
/**
* Sets the quantity
*
* @param quantity
*/
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
/**
* @since 1.10
* @return concept
*/
public Concept getQuantityUnits() {
return quantityUnits;
}
/**
* @since 1.10
* @param quantityUnits
*/
public void setQuantityUnits(Concept quantityUnits) {
this.quantityUnits = quantityUnits;
}
/**
* Gets the drug
*
* @return drug
*/
public Drug getDrug() {
return this.drug;
}
/**
* Sets the drug
*
* @param drug
*/
public void setDrug(Drug drug) {
this.drug = drug;
if (drug != null && getConcept() == null) {
setConcept(drug.getConcept());
}
}
/**
* @return the asNeededCondition
* @since 1.10
*/
public String getAsNeededCondition() {
return asNeededCondition;
}
/**
* @param asNeededCondition the asNeededCondition to set
* @since 1.10
*/
public void setAsNeededCondition(String asNeededCondition) {
this.asNeededCondition = asNeededCondition;
}
/**
* Gets the route
*
* @since 1.10
*/
public Concept getRoute() {
return route;
}
/**
* Sets the route
*
* @param route
* @since 1.10
*/
public void setRoute(Concept route) {
this.route = route;
}
public void setDose(Double dose) {
this.dose = dose;
}
public Double getDose() {
return dose;
}
/**
* Gets the dosingType
*
* @since 1.10
*/
public Class<? extends DosingInstructions> getDosingType() {
return dosingType;
}
/**
* Sets the dosingType
*
* @param dosingType the dosingType to set
* @since 1.10
*/
public void setDosingType(Class<? extends DosingInstructions> dosingType) {
this.dosingType = dosingType;
}
/**
* Gets the dosingInstructions instance
*
* @since 1.10
*/
public DosingInstructions getDosingInstructionsInstance() {
try {
DosingInstructions instructions = getDosingType().newInstance();
return instructions.getDosingInstructions(this);
}
catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Gets numRefills
*
* @since 1.10
*/
public Integer getNumRefills() {
return numRefills;
}
/**
* Sets numRefills
*
* @param numRefills the numRefills to set
* @since 1.10
*/
public void setNumRefills(Integer numRefills) {
this.numRefills = numRefills;
}
/**
* Sets the dosingInstructions
*
* @param dosingInstructions to set
* @since 1.10
*/
public void setDosingInstructions(String dosingInstructions) {
this.dosingInstructions = dosingInstructions;
}
/**
* Gets the dosingInstructions
*
* @since 1.10
*/
public String getDosingInstructions() {
return this.dosingInstructions;
}
/**
* Gets the duration of a Drug Order
*
* @since 1.10
*/
public Integer getDuration() {
return duration;
}
/**
* Sets the duration of a Drug Order
*
* @param duration to set
* @since 1.10
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
* Gets durationUnits of a Drug Order
*
* @since 1.10
*/
public Concept getDurationUnits() {
return durationUnits;
}
/**
* Sets the durationUnits of a Drug Order
*
* @param durationUnits
* @since 1.10
*/
public void setDurationUnits(Concept durationUnits) {
this.durationUnits = durationUnits;
}
/**
* Gets the brandName
*
* @return brandName
* @since 1.10
*/
public String getBrandName() {
return brandName;
}
/**
* Sets the brandName
*
* @since 1.10
* @param brandName the brandName to set to
*/
public void setBrandName(String brandName) {
this.brandName = brandName;
}
/**
* @return true or false
* @since 1.10
*/
public Boolean getDispenseAsWritten() {
return dispenseAsWritten;
}
/**
* @param dispenseAsWritten
* @since 1.10
*/
public void setDispenseAsWritten(Boolean dispenseAsWritten) {
this.dispenseAsWritten = dispenseAsWritten;
}
/**
* @see org.openmrs.Order#cloneForDiscontinuing()
* <strong>Should</strong> set all the relevant fields
* @since 1.10
*/
@Override
public DrugOrder cloneForDiscontinuing() {
DrugOrder newOrder = new DrugOrder();
newOrder.setCareSetting(getCareSetting());
newOrder.setConcept(getConcept());
newOrder.setAction(DISCONTINUE);
newOrder.setPreviousOrder(this);
newOrder.setPatient(getPatient());
newOrder.setDrug(getDrug());
newOrder.setOrderType(getOrderType());
newOrder.setDrugNonCoded(getDrugNonCoded());
return newOrder;
}
/**
* Creates a DrugOrder for revision from this order, sets the previousOrder, action field and
* other drug order fields.
*
* @return the newly created order
* @since 1.10
* <strong>Should</strong> set all the relevant fields
* <strong>Should</strong> set the relevant fields for a DC order
*/
@Override
public DrugOrder cloneForRevision() {
return cloneForRevisionHelper(new DrugOrder());
}
/**
* @see Order#cloneForRevisionHelper(Order)
*/
protected DrugOrder cloneForRevisionHelper(DrugOrder target) {
super.cloneForRevisionHelper(target);
target.setDose(getDose());
target.setDoseUnits(getDoseUnits());
target.setFrequency(getFrequency());
target.setAsNeeded(getAsNeeded());
target.setAsNeededCondition(getAsNeededCondition());
target.setQuantity(getQuantity());
target.setQuantityUnits(getQuantityUnits());
target.setDrug(getDrug());
target.setDosingType(getDosingType());
target.setDosingInstructions(getDosingInstructions());
target.setDuration(getDuration());
target.setDurationUnits(getDurationUnits());
target.setRoute(getRoute());
target.setNumRefills(getNumRefills());
target.setBrandName(getBrandName());
target.setDispenseAsWritten(getDispenseAsWritten());
target.setDrugNonCoded(getDrugNonCoded());
return target;
}
/**
* Sets autoExpireDate based on duration.
*
* <strong>Should</strong> delegate calculation to dosingInstructions
* <strong>Should</strong> not calculate for discontinue action
* <strong>Should</strong> not calculate if autoExpireDate already set
*/
public void setAutoExpireDateBasedOnDuration() {
if (DISCONTINUE != getAction() && getAutoExpireDate() == null) {
setAutoExpireDate(getDosingInstructionsInstance().getAutoExpireDate(this));
}
}
@Override
public String toString() {
String prefix = DISCONTINUE == getAction() ? "DC " : "";
return prefix + "DrugOrder(" + getDose() + getDoseUnits() + " of "
+ (isNonCodedDrug() ? getDrugNonCoded() : (getDrug() != null ? getDrug().getName() : "[no drug]")) + " from " + getDateActivated() + " to "
+ (isDiscontinuedRightNow() ? getDateStopped() : getAutoExpireDate()) + ")";
}
/**
* Set dosing instructions to drug order
*
* @param di dosing instruction object to fetch data
* @since 1.10
*/
public void setDosing(DosingInstructions di) {
di.setDosingInstructions(this);
}
/**
* Checks whether orderable of this drug order is same as other order
*
* @since 1.10
* @param otherOrder the other order to match on
* @return true if the drugs match
* <strong>Should</strong> return false if the other order is null
* <strong>Should</strong> return false if the other order is not a drug order
* <strong>Should</strong> return false if both drugs are null and the concepts are different
* <strong>Should</strong> return false if the concepts match and only this has a drug
* <strong>Should</strong> return false if the concepts match and only the other has a drug
* <strong>Should</strong> return false if the concepts match and drugs are different and not null
* <strong>Should</strong> return true if both drugs are null and the concepts match
* <strong>Should</strong> return true if the drugs match
*/
@Override
public boolean hasSameOrderableAs(Order otherOrder) {
if (!super.hasSameOrderableAs(otherOrder)) {
return false;
}
if (!(otherOrder instanceof DrugOrder)) {
return false;
}
DrugOrder otherDrugOrder = (DrugOrder) otherOrder;
if (isNonCodedDrug() || otherDrugOrder.isNonCodedDrug()) {
return OpenmrsUtil.nullSafeEqualsIgnoreCase(this.getDrugNonCoded(), otherDrugOrder.getDrugNonCoded());
}
return OpenmrsUtil.nullSafeEquals(this.getDrug(), otherDrugOrder.getDrug());
}
/**
* @since 1.12
* @return drugNonCoded
*/
public String getDrugNonCoded() {
return drugNonCoded;
}
/**
* @since 1.12
* sets drugNonCoded
*/
public void setDrugNonCoded(String drugNonCoded) {
this.drugNonCoded = StringUtils.isNotBlank(drugNonCoded) ? drugNonCoded.trim() : drugNonCoded;
}
/**
* @since 1.12
* return true if a drug is non coded
*/
public boolean isNonCodedDrug() {
return StringUtils.isNotBlank(this.drugNonCoded);
}
}
| KrishnaSindhur/openmrs-core | api/src/main/java/org/openmrs/DrugOrder.java | 4,198 | /**
* @see org.openmrs.Order#copyHelper(Order)
*/ | block_comment | nl | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import static org.openmrs.Order.Action.DISCONTINUE;
import org.apache.commons.lang3.StringUtils;
import org.openmrs.util.OpenmrsUtil;
/**
* DrugOrder
*
* @version 1.0
*/
public class DrugOrder extends Order {
public static final long serialVersionUID = 72232L;
// Fields
private Double dose;
private Concept doseUnits;
private OrderFrequency frequency;
private Boolean asNeeded = false;
private Double quantity;
private Concept quantityUnits;
private Drug drug;
private String asNeededCondition;
private Class<? extends DosingInstructions> dosingType = SimpleDosingInstructions.class;
private Integer numRefills;
private String dosingInstructions;
private Integer duration;
private Concept durationUnits;
private Concept route;
private String brandName;
private Boolean dispenseAsWritten = Boolean.FALSE;
private String drugNonCoded;
// Constructors
/** default constructor */
public DrugOrder() {
}
/** constructor with id */
public DrugOrder(Integer orderId) {
this.setOrderId(orderId);
}
/**
* @see org.openmrs.Order#copy()
* <strong>Should</strong> copy all drug order fields
*/
@Override
public DrugOrder copy() {
return copyHelper(new DrugOrder());
}
/**
* @see org.openmrs.Order#copyHelper(Order)
<SUF>*/
protected DrugOrder copyHelper(DrugOrder target) {
super.copyHelper(target);
target.setDose(getDose());
target.setDoseUnits(getDoseUnits());
target.setFrequency(getFrequency());
target.setAsNeeded(getAsNeeded());
target.setAsNeededCondition(getAsNeededCondition());
target.setQuantity(getQuantity());
target.setQuantityUnits(getQuantityUnits());
target.setDrug(getDrug());
target.setDosingType(getDosingType());
target.setDosingInstructions(getDosingInstructions());
target.setDuration(getDuration());
target.setDurationUnits(getDurationUnits());
target.setNumRefills(getNumRefills());
target.setRoute(getRoute());
target.setBrandName(getBrandName());
target.setDispenseAsWritten(getDispenseAsWritten());
target.setDrugNonCoded(getDrugNonCoded());
return target;
}
public boolean isDrugOrder() {
return true;
}
// Property accessors
/**
* Gets the doseUnits of this drug order
*
* @return doseUnits
*/
public Concept getDoseUnits() {
return this.doseUnits;
}
/**
* Sets the doseUnits of this drug order
*
* @param doseUnits
*/
public void setDoseUnits(Concept doseUnits) {
this.doseUnits = doseUnits;
}
/**
* Gets the frequency
*
* @return frequency
* @since 1.10 (signature changed)
*/
public OrderFrequency getFrequency() {
return this.frequency;
}
/**
* Sets the frequency
*
* @param frequency
* @since 1.10 (signature changed)
*/
public void setFrequency(OrderFrequency frequency) {
this.frequency = frequency;
}
/**
* Returns true/false whether the drug is a "pro re nata" drug
*
* @return Boolean
* @since 1.10
*/
public Boolean getAsNeeded() {
return asNeeded;
}
/**
* @param asNeeded the value to set
* @since 1.10
*/
public void setAsNeeded(Boolean asNeeded) {
this.asNeeded = asNeeded;
}
/**
* Gets the quantity
*
* @return quantity
*/
public Double getQuantity() {
return this.quantity;
}
/**
* Sets the quantity
*
* @param quantity
*/
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
/**
* @since 1.10
* @return concept
*/
public Concept getQuantityUnits() {
return quantityUnits;
}
/**
* @since 1.10
* @param quantityUnits
*/
public void setQuantityUnits(Concept quantityUnits) {
this.quantityUnits = quantityUnits;
}
/**
* Gets the drug
*
* @return drug
*/
public Drug getDrug() {
return this.drug;
}
/**
* Sets the drug
*
* @param drug
*/
public void setDrug(Drug drug) {
this.drug = drug;
if (drug != null && getConcept() == null) {
setConcept(drug.getConcept());
}
}
/**
* @return the asNeededCondition
* @since 1.10
*/
public String getAsNeededCondition() {
return asNeededCondition;
}
/**
* @param asNeededCondition the asNeededCondition to set
* @since 1.10
*/
public void setAsNeededCondition(String asNeededCondition) {
this.asNeededCondition = asNeededCondition;
}
/**
* Gets the route
*
* @since 1.10
*/
public Concept getRoute() {
return route;
}
/**
* Sets the route
*
* @param route
* @since 1.10
*/
public void setRoute(Concept route) {
this.route = route;
}
public void setDose(Double dose) {
this.dose = dose;
}
public Double getDose() {
return dose;
}
/**
* Gets the dosingType
*
* @since 1.10
*/
public Class<? extends DosingInstructions> getDosingType() {
return dosingType;
}
/**
* Sets the dosingType
*
* @param dosingType the dosingType to set
* @since 1.10
*/
public void setDosingType(Class<? extends DosingInstructions> dosingType) {
this.dosingType = dosingType;
}
/**
* Gets the dosingInstructions instance
*
* @since 1.10
*/
public DosingInstructions getDosingInstructionsInstance() {
try {
DosingInstructions instructions = getDosingType().newInstance();
return instructions.getDosingInstructions(this);
}
catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Gets numRefills
*
* @since 1.10
*/
public Integer getNumRefills() {
return numRefills;
}
/**
* Sets numRefills
*
* @param numRefills the numRefills to set
* @since 1.10
*/
public void setNumRefills(Integer numRefills) {
this.numRefills = numRefills;
}
/**
* Sets the dosingInstructions
*
* @param dosingInstructions to set
* @since 1.10
*/
public void setDosingInstructions(String dosingInstructions) {
this.dosingInstructions = dosingInstructions;
}
/**
* Gets the dosingInstructions
*
* @since 1.10
*/
public String getDosingInstructions() {
return this.dosingInstructions;
}
/**
* Gets the duration of a Drug Order
*
* @since 1.10
*/
public Integer getDuration() {
return duration;
}
/**
* Sets the duration of a Drug Order
*
* @param duration to set
* @since 1.10
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
* Gets durationUnits of a Drug Order
*
* @since 1.10
*/
public Concept getDurationUnits() {
return durationUnits;
}
/**
* Sets the durationUnits of a Drug Order
*
* @param durationUnits
* @since 1.10
*/
public void setDurationUnits(Concept durationUnits) {
this.durationUnits = durationUnits;
}
/**
* Gets the brandName
*
* @return brandName
* @since 1.10
*/
public String getBrandName() {
return brandName;
}
/**
* Sets the brandName
*
* @since 1.10
* @param brandName the brandName to set to
*/
public void setBrandName(String brandName) {
this.brandName = brandName;
}
/**
* @return true or false
* @since 1.10
*/
public Boolean getDispenseAsWritten() {
return dispenseAsWritten;
}
/**
* @param dispenseAsWritten
* @since 1.10
*/
public void setDispenseAsWritten(Boolean dispenseAsWritten) {
this.dispenseAsWritten = dispenseAsWritten;
}
/**
* @see org.openmrs.Order#cloneForDiscontinuing()
* <strong>Should</strong> set all the relevant fields
* @since 1.10
*/
@Override
public DrugOrder cloneForDiscontinuing() {
DrugOrder newOrder = new DrugOrder();
newOrder.setCareSetting(getCareSetting());
newOrder.setConcept(getConcept());
newOrder.setAction(DISCONTINUE);
newOrder.setPreviousOrder(this);
newOrder.setPatient(getPatient());
newOrder.setDrug(getDrug());
newOrder.setOrderType(getOrderType());
newOrder.setDrugNonCoded(getDrugNonCoded());
return newOrder;
}
/**
* Creates a DrugOrder for revision from this order, sets the previousOrder, action field and
* other drug order fields.
*
* @return the newly created order
* @since 1.10
* <strong>Should</strong> set all the relevant fields
* <strong>Should</strong> set the relevant fields for a DC order
*/
@Override
public DrugOrder cloneForRevision() {
return cloneForRevisionHelper(new DrugOrder());
}
/**
* @see Order#cloneForRevisionHelper(Order)
*/
protected DrugOrder cloneForRevisionHelper(DrugOrder target) {
super.cloneForRevisionHelper(target);
target.setDose(getDose());
target.setDoseUnits(getDoseUnits());
target.setFrequency(getFrequency());
target.setAsNeeded(getAsNeeded());
target.setAsNeededCondition(getAsNeededCondition());
target.setQuantity(getQuantity());
target.setQuantityUnits(getQuantityUnits());
target.setDrug(getDrug());
target.setDosingType(getDosingType());
target.setDosingInstructions(getDosingInstructions());
target.setDuration(getDuration());
target.setDurationUnits(getDurationUnits());
target.setRoute(getRoute());
target.setNumRefills(getNumRefills());
target.setBrandName(getBrandName());
target.setDispenseAsWritten(getDispenseAsWritten());
target.setDrugNonCoded(getDrugNonCoded());
return target;
}
/**
* Sets autoExpireDate based on duration.
*
* <strong>Should</strong> delegate calculation to dosingInstructions
* <strong>Should</strong> not calculate for discontinue action
* <strong>Should</strong> not calculate if autoExpireDate already set
*/
public void setAutoExpireDateBasedOnDuration() {
if (DISCONTINUE != getAction() && getAutoExpireDate() == null) {
setAutoExpireDate(getDosingInstructionsInstance().getAutoExpireDate(this));
}
}
@Override
public String toString() {
String prefix = DISCONTINUE == getAction() ? "DC " : "";
return prefix + "DrugOrder(" + getDose() + getDoseUnits() + " of "
+ (isNonCodedDrug() ? getDrugNonCoded() : (getDrug() != null ? getDrug().getName() : "[no drug]")) + " from " + getDateActivated() + " to "
+ (isDiscontinuedRightNow() ? getDateStopped() : getAutoExpireDate()) + ")";
}
/**
* Set dosing instructions to drug order
*
* @param di dosing instruction object to fetch data
* @since 1.10
*/
public void setDosing(DosingInstructions di) {
di.setDosingInstructions(this);
}
/**
* Checks whether orderable of this drug order is same as other order
*
* @since 1.10
* @param otherOrder the other order to match on
* @return true if the drugs match
* <strong>Should</strong> return false if the other order is null
* <strong>Should</strong> return false if the other order is not a drug order
* <strong>Should</strong> return false if both drugs are null and the concepts are different
* <strong>Should</strong> return false if the concepts match and only this has a drug
* <strong>Should</strong> return false if the concepts match and only the other has a drug
* <strong>Should</strong> return false if the concepts match and drugs are different and not null
* <strong>Should</strong> return true if both drugs are null and the concepts match
* <strong>Should</strong> return true if the drugs match
*/
@Override
public boolean hasSameOrderableAs(Order otherOrder) {
if (!super.hasSameOrderableAs(otherOrder)) {
return false;
}
if (!(otherOrder instanceof DrugOrder)) {
return false;
}
DrugOrder otherDrugOrder = (DrugOrder) otherOrder;
if (isNonCodedDrug() || otherDrugOrder.isNonCodedDrug()) {
return OpenmrsUtil.nullSafeEqualsIgnoreCase(this.getDrugNonCoded(), otherDrugOrder.getDrugNonCoded());
}
return OpenmrsUtil.nullSafeEquals(this.getDrug(), otherDrugOrder.getDrug());
}
/**
* @since 1.12
* @return drugNonCoded
*/
public String getDrugNonCoded() {
return drugNonCoded;
}
/**
* @since 1.12
* sets drugNonCoded
*/
public void setDrugNonCoded(String drugNonCoded) {
this.drugNonCoded = StringUtils.isNotBlank(drugNonCoded) ? drugNonCoded.trim() : drugNonCoded;
}
/**
* @since 1.12
* return true if a drug is non coded
*/
public boolean isNonCodedDrug() {
return StringUtils.isNotBlank(this.drugNonCoded);
}
}
|
204393_37 | /*
* 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.Color;
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.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<Vector2> 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( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
// Algorithm 2
return getBevelVec2( pt_i, pt_j, 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 ( Vector2 pt, Vector2 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;
List<Color> colors = new ArrayList<Color>();
List<Vector3> normals = new ArrayList<Vector3>();
getFaces().add( new Face3( a, b, d, normals, colors, this.options.extrudeMaterial ) );
List<Color> colors2 = new ArrayList<Color>();
List<Vector3> normals2 = new ArrayList<Vector3>();
getFaces().add( new Face3( b, c, d, normals2, colors2, this.options.extrudeMaterial ) );
List<Vector2> uvs = WorldUVGenerator.generateSideWallUV(this, a, b, c, d);
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 0 ), uvs.get( 1 ), uvs.get( 3 ) ) );
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 1 ), uvs.get( 2 ), uvs.get( 3 ) ) );
}
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 )
);
}
}
}
} | KrissCardenas/parallax | src/thothbot/parallax/core/shared/core/ExtrudeGeometry.java | 7,175 | // Add bevel segments planes | 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.Color;
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.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<Vector2> 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<SUF>
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( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
// Algorithm 2
return getBevelVec2( pt_i, pt_j, 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 ( Vector2 pt, Vector2 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;
List<Color> colors = new ArrayList<Color>();
List<Vector3> normals = new ArrayList<Vector3>();
getFaces().add( new Face3( a, b, d, normals, colors, this.options.extrudeMaterial ) );
List<Color> colors2 = new ArrayList<Color>();
List<Vector3> normals2 = new ArrayList<Vector3>();
getFaces().add( new Face3( b, c, d, normals2, colors2, this.options.extrudeMaterial ) );
List<Vector2> uvs = WorldUVGenerator.generateSideWallUV(this, a, b, c, d);
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 0 ), uvs.get( 1 ), uvs.get( 3 ) ) );
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 1 ), uvs.get( 2 ), uvs.get( 3 ) ) );
}
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 )
);
}
}
}
} |
97311_36 | /**
* Approach.java
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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 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 net.sourceforge.xhsi.flightdeck.nd;
import java.io.*;
import java.util.*;
import net.sourceforge.xhsi.*;
import net.sourceforge.xhsi.model.*;
/**
* Approach
*/
public class Approach {
/**
* DEBUG
*/
public final static boolean DEBUG = System.getProperty("approach.debug") != null;
/**
* lastAirport
*/
private static String lastAirport = null;
/**
* Reference to the parient MovingMap
*/
private final MovingMap mm;
/**
* state
*/
private ApproachState state;
/**
* Approach
*/
public Approach(MovingMap mm) {
this.mm = mm;
state = new ApproachState(mm, "");
}
/**
* calcFingerPrint
*/
private String calcFingerPrint() {
StringBuilder sb = new StringBuilder();
int count = mm.fms.get_nb_of_entries();
for (int i = 0 ; i < count ; i++) {
FMSEntry entry = mm.fms.get_entry(i);
if (entry != null) {
sb.append(entry.name);
sb.append(entry.active ? '*' : '&');
}
}
return sb.toString();
}
/**
* newState
*/
private void newState() {
state = new ApproachState(mm, calcFingerPrint());
}
/**
* resetState
*/
private void resetState(String msg) {
if (state.legs.size() > 1) {
if (DEBUG) {
out.println(msg);
}
newState();
}
}
/**
* init
*/
float[] init() {
String str = calcFingerPrint();
String pstr = "";
if (DEBUG) {
pstr = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++ fingerPrint=" + str;
}
if (!state.fingerPrint.equals(str)) {
newState();
pstr += " *** NEW STATE ***";
}
if (DEBUG) {
out.println(pstr);
}
return state.legs.get(state.currentLeg - 1).getLocation(false);
}
/**
* kill
*/
void kill() {
resetState("**KILL**");
}
/**
* getPath
*/
ArrayList<ApproachState.Leg> getPath(FMSEntry entry, String navId) {
/*
* If the new waypoint is an FMS waypoint then delete the approach
*/
if (state.fmsWaypoints.contains(navId)) {
resetState("**RESET**");
}
/*
* Continue the approach or start a new one if navId is noty same as FMS target
*/
if (state.legs.size() > 1 || (entry.active && !entry.name.equals(navId))) {
return state.getPath(navId);
} else {
return null;
}
}
/**
* getCurrentLeg
*/
int getCurrentLeg() {
return state.currentLeg;
}
/**
* ApproachState
*/
static class ApproachState {
/**
* Reference to the parient MovingMap
*/
private final MovingMap mm;
/**
* aircraft
*/
private final Aircraft aircraft;
/**
* avionics
*/
private final Avionics avionics;
/**
* fingerPrint
*/
final String fingerPrint;
/**
* fmsWaypoints
*/
private final HashSet<String> fmsWaypoints;
/**
* path
*/
private final ProcFile file;
/**
* This is a list of approach legs (and may also include missed approach legs).
* The first leg is always the aircraft position either when the constructor
* was called. If this list is only one element long then this means that this
* class did not receive enough information to produce a set of approach
* waypoints. This can occur if an approach is being flown to an airport that
* has no GNS 430 "proc" file. or if no approach is being flown. This latter
* condition can only be established by the fact the FMS entry name is not the
* same as the GPS nav target name. Anyway, in In all cases when legs.size() == 1,
* this class just acts as a perpositary for the last known aircraft position poior
* to some desernable change in the FMS flight plan.
*/
private final ArrayList<Leg> legs = new ArrayList<Leg>();
/**
* airportId
*/
private final String airportId;
/**
* airportLoc
*/
private final float[] airportLoc;
/**
* lastNavId
*/
private String lastNavId;
/**
* currentLeg
*/
private int currentLeg;
/**
* ApproachState
*/
private ApproachState(MovingMap mm, String fingerPrint) {
this.mm = mm;
this.fingerPrint = fingerPrint;
this.aircraft = mm.aircraft;
this.avionics = mm.avionics;
FMSEntry dst = getLastFmsWaypoint();
if (dst != null) {
airportId = dst.name;
airportLoc = new float[] {dst.lat, dst.lon};
file = ProcFile.load(airportId);
if (DEBUG) {
out.println("airportId=" + airportId);
if (file == null) {
out.println("** NOT FOUND**");
} else if (!airportId.equals(lastAirport)) {
out.println(file);
lastAirport = airportId;
}
}
} else {
airportId = null;
airportLoc = null;
file = null;
}
fmsWaypoints = getFmsWaypoints();
clearLegs(null);
}
/**
* ApproachState
*/
ApproachState(ApproachState state) {
this(state.mm, state.fingerPrint);
}
/**
* getLastFmsWaypoint
*/
private FMSEntry getLastFmsWaypoint() {
FMSEntry wp = mm.avionics.get_fms().get_last_waypoint();
return (wp != null && wp.type == FMSEntry.ARPT) ? wp : null;
}
/**
* getWaypoints()
*/
private HashSet<String> getFmsWaypoints() {
HashSet<String> set = new HashSet<String>();
boolean flown = true;
int count = mm.fms.get_nb_of_entries();
for (int i = 0 ; i < count ; i++) {
FMSEntry entry = mm.fms.get_entry(i);
if (entry != null &&entry.type != FMSEntry.ARPT) {
set.add(entry.name);
}
}
return set;
}
// ------------------------------------------------------------------------
// Leg management
// ------------------------------------------------------------------------
/**
* Leg
*/
class Leg {
final String navId;
private float[] location;
final boolean isCertain;
final boolean calculate;
final boolean missed;
/**
* Leg
*/
Leg(String navId, float[] location, boolean certain, boolean calculate) {
this.navId = navId.toUpperCase();
this.location = location;
this.isCertain = certain;
this.calculate = calculate;
this.missed = navId.length() > 0 && Character.isLowerCase(navId.charAt(0));
}
/**
* getLocation
*/
float[] getLocation(boolean legIsActive) {
if (calculate && legIsActive) {
location = getCurrentNavPosition(); // Later calls get more accurate so keep calling...
}
return location;
}
/**
* toString
*/
public String toString() {
String locStr = (location == null) ? "" : " location=[" + location[0] + "," + location[1] + "]";
return "{navId=" + navId + locStr + " isCertain=" + isCertain + "}";
}
}
/**
* getLeg
*/
private ArrayList<ApproachState.Leg> getPath(String navId) {
boolean setup = false;
if (legs.size() > 1) {
boolean navIdEqualsAirport = navId.equals(airportId);
for (int i = currentLeg ; i < legs.size() ; i++) {
String id = legs.get(i).navId;
if (id.equals(navId) || (navIdEqualsAirport && id.startsWith("RW"))) {
currentLeg = i;
return legs;
}
}
/*
* If the navId cannot be found in the ProcFile data then it must be a
* special waypoint inserted by the GPS simulatlor so just insert it
* in the list. Otherwise it is time to reevaluate the path that
* is being used.
*/
float[] posn = file.getLatLon(navId);
if (posn == null) {
legs.add(++currentLeg, new Leg(navId, getCurrentNavPosition(), true, true));
if (DEBUG) {
out.println("+++ appended new leg currentLeg=" + currentLeg);
}
} else {
/*
* It is impossible to know if a new point appears because of a direct-to or an
* activate-leg operation. Here the assumptioon is made that it is the former if the
* current leg was uncertain, othersize it is assumed to be a direct-to. The
* difference is only in where the red line will origionate.
*/
Leg old = legs.get(currentLeg);
setupLegs(navId, false, (old.isCertain) ? null : old);
}
} else if (!navId.equals(lastNavId)) {
setupLegs(navId, false, null);
}
return (legs.size() <= 1) ? null : legs;
}
/**
* clearLegs
*/
private void clearLegs(Leg oldLeg) {
legs.clear();
Leg start = (oldLeg != null) ? oldLeg : new Leg("", new float[] {mm.center_lat, mm.center_lon}, true, false);
legs.add(start);
currentLeg = 1;
}
/**
* setupLegs
*/
private void setupLegs(String navId, boolean missedApproach, Leg oldLeg) {
if (DEBUG) {
out.println("+++ setupLegs navId = " + navId + " missedApproach=" + missedApproach + " oldLeg=" + oldLeg);
}
clearLegs(oldLeg);
lastNavId = navId;
if (file != null && navId != null) {
HashSet<String> navSet = findPaths(navId, missedApproach);
if (navSet != null) {
/*
* If oldLeg is non-null see if a smaller set can be found by staring from
* there and removing all the entries that do not start with navId. (A better
* approach would be to carry on like this beyond just the first two waypoints
* but just this works out pretty well.)
*/
if (navSet.size() > 1 && oldLeg != null) {
HashSet<String> oldSet = findPaths(oldLeg.navId, missedApproach);
if (oldSet != null) {
HashSet<String> possibles = new HashSet<String>();
String pref = navId + " ";
for (String str : oldSet) {
if (str.startsWith(pref)) {
possibles.add(str.substring(pref.length()));
}
}
if (possibles.size() != 0 && possibles.size() < navSet.size()) {
if (DEBUG) {
out.println("+++ setupLegs possibles reduced from " + navSet.size() + " to " + possibles.size());
}
navSet = possibles;
}
}
}
addPathLegs(navId, navSet);
}
}
}
/**
* findPaths
*/
HashSet<String> findPaths(String navId, boolean missedApproach) {
HashSet<String> pathSet = missedApproach ? null : file.getApproachPaths(navId);
return (pathSet != null) ? pathSet : file.getMissedPaths(navId);
}
/**
* addPathLegs
*/
private void addPathLegs(String navId, HashSet<String> pathSet) {
/*
* Always add the current navId because this is never in doubt.
*/
addLeg(navId);
/*
* Get the set of possible paths from this point forward. If there is only
* one (a common case) then just add the legs for this path. Otherwise try
* to deal with the more complex multi-path scenario.
*/
String[] paths = pathSet.toArray(new String[0]);
if (paths.length == 1) {
if (DEBUG) {
out.println("+++ addPathLegs single navId = " + navId + " path =" + paths[0]);
}
for (String id : paths[0].split("\\s+")) {
addLeg(id);
}
} else {
addMultiPathLegs(paths);
}
}
/**
* addMultiPathLegs
*/
private void addMultiPathLegs(String[] paths) {
if (DEBUG) {
for (String path : paths) {
out.println("path="+path);
}
}
/*
* First find out if all the paths lead to the same runway.
*/
String[][] pathParts = new String[paths.length][];
String[] runways = new String[pathParts.length];
String runway = "";
int minj = Integer.MAX_VALUE;
for (int i = 0 ; i < paths.length ; i++) {
pathParts[i] = paths[i].split("\\s+");
minj = Math.min(minj, pathParts[i].length);
for (int j = 0 ; j < pathParts[i].length ; j++) {
if (pathParts[i][j].startsWith("RW")) {
runway = pathParts[i][j];
runways[i] = runway;
}
}
}
/*
* If they do not then note this so an uncertain line to the airport.will be written.
* When the next waypoint is reached, it should be found in the ProcFile and
* this will trigger a re-evaluation of the approach which will eventually lead
* to a single unambigious runway (and evevtually a single unambigious path).
*/
for (String rw : runways) {
if (!runway.equals(rw)) {
if (DEBUG) {
out.println("different runways runway="+runway+" rw="+rw);
}
runway = null;
break;
}
}
if (DEBUG) {
out.println(" runway="+runway+" minj="+minj);
}
/*
* Add all the common legs (if any) before the runway
*/
boolean runwayLegAdded = false;
jloop: for (int j = 0 ; j < minj; j++) {
String str = pathParts[0][j];
for (int i = 1 ; i < pathParts.length ; i++) {
if (!str.equals(pathParts[i][j])) {
break jloop;
}
}
addLeg(str);
if (str.startsWith("RW")) {
runwayLegAdded = true;
break jloop;
}
}
/*
* If the runway was not reached then either add an uncertain leg to the
* airport (because the runways are different) or add an uncertain leg to it.
*/
if (!runwayLegAdded) {
if (runway == null) {
legs.add(new Leg(airportId, airportLoc, false, false));
} else {
addLeg(runway, false);
}
}
/*
* Now look to see if there is a common ending to the paths. This appears to be
* fairly common. as it seems that quite often one path will differ from another
* by just having one extra waypoint directly after the runway (this also seems
* to occur frequently before the runway as well). In these isolated subset cases
* a single uncertain leg can act as a "catch all," If not, all the missied approach
* waypoints are omitted (here again, a simpler path will after the missed approach).
*/
ArrayList<String> ends = new ArrayList<String>();
boolean certain = false;
kloop: for (int k = -1 ;; --k) {
String str = pathParts[0][pathParts[0].length + k];
for (int i = 1 ; i < pathParts.length ; i++) {
String str2 = pathParts[i][pathParts[i].length + k];
if (!str.equals(str2)) {
break kloop;
} else if (str.startsWith("RW")) {
certain = true;
break kloop;
}
}
ends.add(0, str);
}
for (String end : ends) {
addLeg(end, certain);
certain = true;
}
}
/**
* addLeg
*/
private void addLeg(String navId) {
addLeg(navId, true);
}
/**
* addLeg
*/
private void addLeg(String navId, boolean certain) {
/*
* Occasionally a path entry is synthesized (in ProcFile.java) for runways when
* they are missing (at least explicitly) from a FINAL section. The location is
* often known becasue the runway may be explicitly discribed in another FINAL
* section. However, this is not always case and so the fallback used
* here is to use the airport location instead (which is known), but also to
* mark the leg as one that must have the location calculated when it becomes
* active. This works because a lat/log can be calculated from the a/c position
* and the direction and distance to the GPS nav target (when the nav id is equal
* to the FMS entry name). This will always be the near end of the target runway.
* (It can be a little inaccurate to start with, but after a short time a nice
* average position can be calculated.)
*/
float[] posn = file.getLatLon(navId);
legs.add(new Leg(navId, (posn == null) ? airportLoc : posn, certain, posn == null));
}
// ------------------------------------------------------------------------
// Lat / Lon reconstruction
// ------------------------------------------------------------------------
/**
* getCurrentNavPosition
*/
float[] getCurrentNavPosition() {
NavigationObject nobj = mm.nor.get_nav_object(avionics.gps_nav_id()); // (Note: This facility is currently disabled)
if (nobj != null) {
return new float[] {nobj.lat, nobj.lon};
} else {
return getAveragedNavPositionFromGpsData();
}
}
/*
* The data derived from getCurrentNavPositionFromGpsData() is not always accurate. This is especially
* true just after a new waypoint is selected by the X-Plane Garmin GPS where lat/lon errors as large
* as 0.25 degrees can be seen. This only appears to be for the first few (or maybe just one) call
* but it seems prudent to skip though a few. This is what happens below, after which an average value
* is calculated.
*/
private final static int CALC_SKIP = 10;
private final static int CALC_COUNT = 10;
String navCalcLast;
int navCalcCount;
float[] navCalcFirst;
float[] navCalcTotals;
float[] navCalcAverage;
/**
* getAveragedNavPositionFromGpsData
*/
float[] getAveragedNavPositionFromGpsData() {
String navId = avionics.gps_nav_id();
if (!navId.equals(navCalcLast)) {
navCalcLast = navId;
navCalcCount = 0;
navCalcTotals = null;
navCalcAverage = null;
}
if(navCalcAverage != null) {
return navCalcAverage;
} else {
float[] res = getCurrentNavPositionFromGpsData();
navCalcCount++;
if (navCalcFirst == null) {
navCalcFirst = res;
}
if (navCalcCount == CALC_SKIP) {
navCalcTotals = new float[2];
}
if (navCalcTotals != null) {
navCalcTotals[0] += res[0];
navCalcTotals[1] += res[1];
}
if (navCalcCount == CALC_SKIP+CALC_COUNT-1) {
navCalcAverage = new float[] {navCalcTotals[0] / CALC_COUNT, navCalcTotals[1] / CALC_COUNT};
navCalcTotals = null;
//System.out.println("navCalc first=" + navCalcFirst[0] + ","+navCalcFirst[1] + " last=" + res[0] + "," + res[1] + " average=" + navCalcAverage[0] + "," + navCalcAverage[1]);
return navCalcAverage;
} else {
return navCalcFirst; // Use first until average is calculated then switch to that
}
}
}
/**
* getCurrentNavPositionFromGpsData
*/
float[] getCurrentNavPositionFromGpsData() {
double dir = Math.toRadians(aircraft.heading() - aircraft.magnetic_variation() + avionics.get_gps_radio().get_rel_bearing());
double dis = CoordinateSystem.nm_to_radians(avionics.get_gps_radio().get_distance());
MovingMap.Geo p0 = MovingMap.Geo.makeGeoDegrees(mm.center_lat, mm.center_lon);
MovingMap.Geo p1 = p0.offset(dis, dir);
//System.out.print("getCurrentNavPosition for "+navId+" = " + p1.getLatitude() + ", " + p1.getLongitude());
//System.out.print(" dist="+avionics.get_gps_radio().get_distance()+" course= " + avionics.get_gps_radio().get_course());
//System.out.println(" center_lat= " + center_lat + " center_lon=" + center_lon);
return new float[] {(float)p1.getLatitude(), (float)p1.getLongitude()};
}
}
// ------------------------------------------------------------------------
// Debugging Support
// ------------------------------------------------------------------------
/**
* lastString
*/
private String lastString;
/**
* done
*/
void done() {
String res = out.toString();
if (!res.equals(lastString)) {
if (res.length() > 0) {
System.out.println(res);
System.out.println("--------------------------------------------------------");
}
lastString = res;
}
}
/**
* Prt
*/
static class Prt {
StringBuilder sb = new StringBuilder();
Prt print(Object obj) {
return print(obj, false);
}
Prt println(Object obj) {
return print(obj, true);
}
Prt println() {
return print("", true);
}
private Prt print(Object obj, boolean nl) {
if (obj instanceof float[]) {
float[] fx = (float[]) obj;
if (fx.length == 0) {
sb.append("[]");
} else {
sb.append('[');
int i = 0;
for (; i < fx.length - 1; i++) {
sb.append(fx[i]);
sb.append(',');
}
sb.append(fx[i]);
sb.append(']');
}
} else {
sb.append(obj);
}
if (nl) {
sb.append('\n');
}
if (sb.length() > (1024*1024)) { // Don't run the VM out of memory if prog is stuck in a loop
System.out.print(toString());
}
return this;
}
public String toString() {
if (sb.length() == 0) {
return "";
} else {
String res = sb.toString();
sb = new StringBuilder();
return res;
}
}
}
/**
* out
*/
static Prt out = new Prt();
}
| Ksys-info/xhsi | src/net/sourceforge/xhsi/flightdeck/nd/Approach.java | 7,007 | /**
* getLeg
*/ | block_comment | nl | /**
* Approach.java
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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 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 net.sourceforge.xhsi.flightdeck.nd;
import java.io.*;
import java.util.*;
import net.sourceforge.xhsi.*;
import net.sourceforge.xhsi.model.*;
/**
* Approach
*/
public class Approach {
/**
* DEBUG
*/
public final static boolean DEBUG = System.getProperty("approach.debug") != null;
/**
* lastAirport
*/
private static String lastAirport = null;
/**
* Reference to the parient MovingMap
*/
private final MovingMap mm;
/**
* state
*/
private ApproachState state;
/**
* Approach
*/
public Approach(MovingMap mm) {
this.mm = mm;
state = new ApproachState(mm, "");
}
/**
* calcFingerPrint
*/
private String calcFingerPrint() {
StringBuilder sb = new StringBuilder();
int count = mm.fms.get_nb_of_entries();
for (int i = 0 ; i < count ; i++) {
FMSEntry entry = mm.fms.get_entry(i);
if (entry != null) {
sb.append(entry.name);
sb.append(entry.active ? '*' : '&');
}
}
return sb.toString();
}
/**
* newState
*/
private void newState() {
state = new ApproachState(mm, calcFingerPrint());
}
/**
* resetState
*/
private void resetState(String msg) {
if (state.legs.size() > 1) {
if (DEBUG) {
out.println(msg);
}
newState();
}
}
/**
* init
*/
float[] init() {
String str = calcFingerPrint();
String pstr = "";
if (DEBUG) {
pstr = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++ fingerPrint=" + str;
}
if (!state.fingerPrint.equals(str)) {
newState();
pstr += " *** NEW STATE ***";
}
if (DEBUG) {
out.println(pstr);
}
return state.legs.get(state.currentLeg - 1).getLocation(false);
}
/**
* kill
*/
void kill() {
resetState("**KILL**");
}
/**
* getPath
*/
ArrayList<ApproachState.Leg> getPath(FMSEntry entry, String navId) {
/*
* If the new waypoint is an FMS waypoint then delete the approach
*/
if (state.fmsWaypoints.contains(navId)) {
resetState("**RESET**");
}
/*
* Continue the approach or start a new one if navId is noty same as FMS target
*/
if (state.legs.size() > 1 || (entry.active && !entry.name.equals(navId))) {
return state.getPath(navId);
} else {
return null;
}
}
/**
* getCurrentLeg
*/
int getCurrentLeg() {
return state.currentLeg;
}
/**
* ApproachState
*/
static class ApproachState {
/**
* Reference to the parient MovingMap
*/
private final MovingMap mm;
/**
* aircraft
*/
private final Aircraft aircraft;
/**
* avionics
*/
private final Avionics avionics;
/**
* fingerPrint
*/
final String fingerPrint;
/**
* fmsWaypoints
*/
private final HashSet<String> fmsWaypoints;
/**
* path
*/
private final ProcFile file;
/**
* This is a list of approach legs (and may also include missed approach legs).
* The first leg is always the aircraft position either when the constructor
* was called. If this list is only one element long then this means that this
* class did not receive enough information to produce a set of approach
* waypoints. This can occur if an approach is being flown to an airport that
* has no GNS 430 "proc" file. or if no approach is being flown. This latter
* condition can only be established by the fact the FMS entry name is not the
* same as the GPS nav target name. Anyway, in In all cases when legs.size() == 1,
* this class just acts as a perpositary for the last known aircraft position poior
* to some desernable change in the FMS flight plan.
*/
private final ArrayList<Leg> legs = new ArrayList<Leg>();
/**
* airportId
*/
private final String airportId;
/**
* airportLoc
*/
private final float[] airportLoc;
/**
* lastNavId
*/
private String lastNavId;
/**
* currentLeg
*/
private int currentLeg;
/**
* ApproachState
*/
private ApproachState(MovingMap mm, String fingerPrint) {
this.mm = mm;
this.fingerPrint = fingerPrint;
this.aircraft = mm.aircraft;
this.avionics = mm.avionics;
FMSEntry dst = getLastFmsWaypoint();
if (dst != null) {
airportId = dst.name;
airportLoc = new float[] {dst.lat, dst.lon};
file = ProcFile.load(airportId);
if (DEBUG) {
out.println("airportId=" + airportId);
if (file == null) {
out.println("** NOT FOUND**");
} else if (!airportId.equals(lastAirport)) {
out.println(file);
lastAirport = airportId;
}
}
} else {
airportId = null;
airportLoc = null;
file = null;
}
fmsWaypoints = getFmsWaypoints();
clearLegs(null);
}
/**
* ApproachState
*/
ApproachState(ApproachState state) {
this(state.mm, state.fingerPrint);
}
/**
* getLastFmsWaypoint
*/
private FMSEntry getLastFmsWaypoint() {
FMSEntry wp = mm.avionics.get_fms().get_last_waypoint();
return (wp != null && wp.type == FMSEntry.ARPT) ? wp : null;
}
/**
* getWaypoints()
*/
private HashSet<String> getFmsWaypoints() {
HashSet<String> set = new HashSet<String>();
boolean flown = true;
int count = mm.fms.get_nb_of_entries();
for (int i = 0 ; i < count ; i++) {
FMSEntry entry = mm.fms.get_entry(i);
if (entry != null &&entry.type != FMSEntry.ARPT) {
set.add(entry.name);
}
}
return set;
}
// ------------------------------------------------------------------------
// Leg management
// ------------------------------------------------------------------------
/**
* Leg
*/
class Leg {
final String navId;
private float[] location;
final boolean isCertain;
final boolean calculate;
final boolean missed;
/**
* Leg
*/
Leg(String navId, float[] location, boolean certain, boolean calculate) {
this.navId = navId.toUpperCase();
this.location = location;
this.isCertain = certain;
this.calculate = calculate;
this.missed = navId.length() > 0 && Character.isLowerCase(navId.charAt(0));
}
/**
* getLocation
*/
float[] getLocation(boolean legIsActive) {
if (calculate && legIsActive) {
location = getCurrentNavPosition(); // Later calls get more accurate so keep calling...
}
return location;
}
/**
* toString
*/
public String toString() {
String locStr = (location == null) ? "" : " location=[" + location[0] + "," + location[1] + "]";
return "{navId=" + navId + locStr + " isCertain=" + isCertain + "}";
}
}
/**
* getLeg
<SUF>*/
private ArrayList<ApproachState.Leg> getPath(String navId) {
boolean setup = false;
if (legs.size() > 1) {
boolean navIdEqualsAirport = navId.equals(airportId);
for (int i = currentLeg ; i < legs.size() ; i++) {
String id = legs.get(i).navId;
if (id.equals(navId) || (navIdEqualsAirport && id.startsWith("RW"))) {
currentLeg = i;
return legs;
}
}
/*
* If the navId cannot be found in the ProcFile data then it must be a
* special waypoint inserted by the GPS simulatlor so just insert it
* in the list. Otherwise it is time to reevaluate the path that
* is being used.
*/
float[] posn = file.getLatLon(navId);
if (posn == null) {
legs.add(++currentLeg, new Leg(navId, getCurrentNavPosition(), true, true));
if (DEBUG) {
out.println("+++ appended new leg currentLeg=" + currentLeg);
}
} else {
/*
* It is impossible to know if a new point appears because of a direct-to or an
* activate-leg operation. Here the assumptioon is made that it is the former if the
* current leg was uncertain, othersize it is assumed to be a direct-to. The
* difference is only in where the red line will origionate.
*/
Leg old = legs.get(currentLeg);
setupLegs(navId, false, (old.isCertain) ? null : old);
}
} else if (!navId.equals(lastNavId)) {
setupLegs(navId, false, null);
}
return (legs.size() <= 1) ? null : legs;
}
/**
* clearLegs
*/
private void clearLegs(Leg oldLeg) {
legs.clear();
Leg start = (oldLeg != null) ? oldLeg : new Leg("", new float[] {mm.center_lat, mm.center_lon}, true, false);
legs.add(start);
currentLeg = 1;
}
/**
* setupLegs
*/
private void setupLegs(String navId, boolean missedApproach, Leg oldLeg) {
if (DEBUG) {
out.println("+++ setupLegs navId = " + navId + " missedApproach=" + missedApproach + " oldLeg=" + oldLeg);
}
clearLegs(oldLeg);
lastNavId = navId;
if (file != null && navId != null) {
HashSet<String> navSet = findPaths(navId, missedApproach);
if (navSet != null) {
/*
* If oldLeg is non-null see if a smaller set can be found by staring from
* there and removing all the entries that do not start with navId. (A better
* approach would be to carry on like this beyond just the first two waypoints
* but just this works out pretty well.)
*/
if (navSet.size() > 1 && oldLeg != null) {
HashSet<String> oldSet = findPaths(oldLeg.navId, missedApproach);
if (oldSet != null) {
HashSet<String> possibles = new HashSet<String>();
String pref = navId + " ";
for (String str : oldSet) {
if (str.startsWith(pref)) {
possibles.add(str.substring(pref.length()));
}
}
if (possibles.size() != 0 && possibles.size() < navSet.size()) {
if (DEBUG) {
out.println("+++ setupLegs possibles reduced from " + navSet.size() + " to " + possibles.size());
}
navSet = possibles;
}
}
}
addPathLegs(navId, navSet);
}
}
}
/**
* findPaths
*/
HashSet<String> findPaths(String navId, boolean missedApproach) {
HashSet<String> pathSet = missedApproach ? null : file.getApproachPaths(navId);
return (pathSet != null) ? pathSet : file.getMissedPaths(navId);
}
/**
* addPathLegs
*/
private void addPathLegs(String navId, HashSet<String> pathSet) {
/*
* Always add the current navId because this is never in doubt.
*/
addLeg(navId);
/*
* Get the set of possible paths from this point forward. If there is only
* one (a common case) then just add the legs for this path. Otherwise try
* to deal with the more complex multi-path scenario.
*/
String[] paths = pathSet.toArray(new String[0]);
if (paths.length == 1) {
if (DEBUG) {
out.println("+++ addPathLegs single navId = " + navId + " path =" + paths[0]);
}
for (String id : paths[0].split("\\s+")) {
addLeg(id);
}
} else {
addMultiPathLegs(paths);
}
}
/**
* addMultiPathLegs
*/
private void addMultiPathLegs(String[] paths) {
if (DEBUG) {
for (String path : paths) {
out.println("path="+path);
}
}
/*
* First find out if all the paths lead to the same runway.
*/
String[][] pathParts = new String[paths.length][];
String[] runways = new String[pathParts.length];
String runway = "";
int minj = Integer.MAX_VALUE;
for (int i = 0 ; i < paths.length ; i++) {
pathParts[i] = paths[i].split("\\s+");
minj = Math.min(minj, pathParts[i].length);
for (int j = 0 ; j < pathParts[i].length ; j++) {
if (pathParts[i][j].startsWith("RW")) {
runway = pathParts[i][j];
runways[i] = runway;
}
}
}
/*
* If they do not then note this so an uncertain line to the airport.will be written.
* When the next waypoint is reached, it should be found in the ProcFile and
* this will trigger a re-evaluation of the approach which will eventually lead
* to a single unambigious runway (and evevtually a single unambigious path).
*/
for (String rw : runways) {
if (!runway.equals(rw)) {
if (DEBUG) {
out.println("different runways runway="+runway+" rw="+rw);
}
runway = null;
break;
}
}
if (DEBUG) {
out.println(" runway="+runway+" minj="+minj);
}
/*
* Add all the common legs (if any) before the runway
*/
boolean runwayLegAdded = false;
jloop: for (int j = 0 ; j < minj; j++) {
String str = pathParts[0][j];
for (int i = 1 ; i < pathParts.length ; i++) {
if (!str.equals(pathParts[i][j])) {
break jloop;
}
}
addLeg(str);
if (str.startsWith("RW")) {
runwayLegAdded = true;
break jloop;
}
}
/*
* If the runway was not reached then either add an uncertain leg to the
* airport (because the runways are different) or add an uncertain leg to it.
*/
if (!runwayLegAdded) {
if (runway == null) {
legs.add(new Leg(airportId, airportLoc, false, false));
} else {
addLeg(runway, false);
}
}
/*
* Now look to see if there is a common ending to the paths. This appears to be
* fairly common. as it seems that quite often one path will differ from another
* by just having one extra waypoint directly after the runway (this also seems
* to occur frequently before the runway as well). In these isolated subset cases
* a single uncertain leg can act as a "catch all," If not, all the missied approach
* waypoints are omitted (here again, a simpler path will after the missed approach).
*/
ArrayList<String> ends = new ArrayList<String>();
boolean certain = false;
kloop: for (int k = -1 ;; --k) {
String str = pathParts[0][pathParts[0].length + k];
for (int i = 1 ; i < pathParts.length ; i++) {
String str2 = pathParts[i][pathParts[i].length + k];
if (!str.equals(str2)) {
break kloop;
} else if (str.startsWith("RW")) {
certain = true;
break kloop;
}
}
ends.add(0, str);
}
for (String end : ends) {
addLeg(end, certain);
certain = true;
}
}
/**
* addLeg
*/
private void addLeg(String navId) {
addLeg(navId, true);
}
/**
* addLeg
*/
private void addLeg(String navId, boolean certain) {
/*
* Occasionally a path entry is synthesized (in ProcFile.java) for runways when
* they are missing (at least explicitly) from a FINAL section. The location is
* often known becasue the runway may be explicitly discribed in another FINAL
* section. However, this is not always case and so the fallback used
* here is to use the airport location instead (which is known), but also to
* mark the leg as one that must have the location calculated when it becomes
* active. This works because a lat/log can be calculated from the a/c position
* and the direction and distance to the GPS nav target (when the nav id is equal
* to the FMS entry name). This will always be the near end of the target runway.
* (It can be a little inaccurate to start with, but after a short time a nice
* average position can be calculated.)
*/
float[] posn = file.getLatLon(navId);
legs.add(new Leg(navId, (posn == null) ? airportLoc : posn, certain, posn == null));
}
// ------------------------------------------------------------------------
// Lat / Lon reconstruction
// ------------------------------------------------------------------------
/**
* getCurrentNavPosition
*/
float[] getCurrentNavPosition() {
NavigationObject nobj = mm.nor.get_nav_object(avionics.gps_nav_id()); // (Note: This facility is currently disabled)
if (nobj != null) {
return new float[] {nobj.lat, nobj.lon};
} else {
return getAveragedNavPositionFromGpsData();
}
}
/*
* The data derived from getCurrentNavPositionFromGpsData() is not always accurate. This is especially
* true just after a new waypoint is selected by the X-Plane Garmin GPS where lat/lon errors as large
* as 0.25 degrees can be seen. This only appears to be for the first few (or maybe just one) call
* but it seems prudent to skip though a few. This is what happens below, after which an average value
* is calculated.
*/
private final static int CALC_SKIP = 10;
private final static int CALC_COUNT = 10;
String navCalcLast;
int navCalcCount;
float[] navCalcFirst;
float[] navCalcTotals;
float[] navCalcAverage;
/**
* getAveragedNavPositionFromGpsData
*/
float[] getAveragedNavPositionFromGpsData() {
String navId = avionics.gps_nav_id();
if (!navId.equals(navCalcLast)) {
navCalcLast = navId;
navCalcCount = 0;
navCalcTotals = null;
navCalcAverage = null;
}
if(navCalcAverage != null) {
return navCalcAverage;
} else {
float[] res = getCurrentNavPositionFromGpsData();
navCalcCount++;
if (navCalcFirst == null) {
navCalcFirst = res;
}
if (navCalcCount == CALC_SKIP) {
navCalcTotals = new float[2];
}
if (navCalcTotals != null) {
navCalcTotals[0] += res[0];
navCalcTotals[1] += res[1];
}
if (navCalcCount == CALC_SKIP+CALC_COUNT-1) {
navCalcAverage = new float[] {navCalcTotals[0] / CALC_COUNT, navCalcTotals[1] / CALC_COUNT};
navCalcTotals = null;
//System.out.println("navCalc first=" + navCalcFirst[0] + ","+navCalcFirst[1] + " last=" + res[0] + "," + res[1] + " average=" + navCalcAverage[0] + "," + navCalcAverage[1]);
return navCalcAverage;
} else {
return navCalcFirst; // Use first until average is calculated then switch to that
}
}
}
/**
* getCurrentNavPositionFromGpsData
*/
float[] getCurrentNavPositionFromGpsData() {
double dir = Math.toRadians(aircraft.heading() - aircraft.magnetic_variation() + avionics.get_gps_radio().get_rel_bearing());
double dis = CoordinateSystem.nm_to_radians(avionics.get_gps_radio().get_distance());
MovingMap.Geo p0 = MovingMap.Geo.makeGeoDegrees(mm.center_lat, mm.center_lon);
MovingMap.Geo p1 = p0.offset(dis, dir);
//System.out.print("getCurrentNavPosition for "+navId+" = " + p1.getLatitude() + ", " + p1.getLongitude());
//System.out.print(" dist="+avionics.get_gps_radio().get_distance()+" course= " + avionics.get_gps_radio().get_course());
//System.out.println(" center_lat= " + center_lat + " center_lon=" + center_lon);
return new float[] {(float)p1.getLatitude(), (float)p1.getLongitude()};
}
}
// ------------------------------------------------------------------------
// Debugging Support
// ------------------------------------------------------------------------
/**
* lastString
*/
private String lastString;
/**
* done
*/
void done() {
String res = out.toString();
if (!res.equals(lastString)) {
if (res.length() > 0) {
System.out.println(res);
System.out.println("--------------------------------------------------------");
}
lastString = res;
}
}
/**
* Prt
*/
static class Prt {
StringBuilder sb = new StringBuilder();
Prt print(Object obj) {
return print(obj, false);
}
Prt println(Object obj) {
return print(obj, true);
}
Prt println() {
return print("", true);
}
private Prt print(Object obj, boolean nl) {
if (obj instanceof float[]) {
float[] fx = (float[]) obj;
if (fx.length == 0) {
sb.append("[]");
} else {
sb.append('[');
int i = 0;
for (; i < fx.length - 1; i++) {
sb.append(fx[i]);
sb.append(',');
}
sb.append(fx[i]);
sb.append(']');
}
} else {
sb.append(obj);
}
if (nl) {
sb.append('\n');
}
if (sb.length() > (1024*1024)) { // Don't run the VM out of memory if prog is stuck in a loop
System.out.print(toString());
}
return this;
}
public String toString() {
if (sb.length() == 0) {
return "";
} else {
String res = sb.toString();
sb = new StringBuilder();
return res;
}
}
}
/**
* out
*/
static Prt out = new Prt();
}
|
112605_31 | /**
* Copyright 2005-2019 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.widget;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.uif.component.BindingInfo;
import org.kuali.rice.krad.uif.component.MethodInvokerConfig;
import org.kuali.rice.krad.uif.field.AttributeQuery;
import org.kuali.rice.krad.uif.field.InputField;
import org.kuali.rice.krad.uif.lifecycle.ViewLifecycle;
import org.kuali.rice.krad.uif.util.LifecycleElement;
import org.kuali.rice.krad.uif.util.ScriptUtils;
import org.kuali.rice.krad.uif.view.View;
/**
* Widget that provides dynamic select options to the user as they are entering the value (also known
* as auto-complete).
*
* <p>Widget is backed by an {@link org.kuali.rice.krad.uif.field.AttributeQuery} that provides the configuration
* for executing a query server side that will retrieve the valid option values.</p>
*
* @author Kuali Rice Team ([email protected])
*/
@BeanTag(name = "suggest", parent = "Uif-Suggest")
public class Suggest extends WidgetBase {
private static final long serialVersionUID = 7373706855319347225L;
private AttributeQuery suggestQuery;
private String valuePropertyName;
private String labelPropertyName;
private List<String> additionalPropertiesToReturn;
private boolean returnFullQueryObject;
private boolean retrieveAllSuggestions;
private List<Object> suggestOptions;
private String suggestOptionsJsString;
public Suggest() {
super();
}
/**
* The following updates are done here:
*
* <ul>
* <li>Invoke expression evaluation on the suggestQuery</li>
* </ul>
*
* {@inheritDoc}
*/
public void performApplyModel(Object model, LifecycleElement parent) {
super.performApplyModel(model, parent);
if (suggestQuery != null) {
ViewLifecycle.getExpressionEvaluator().evaluateExpressionsOnConfigurable(ViewLifecycle.getView(),
suggestQuery, getContext());
}
}
/**
* The following actions are performed:
*
* <ul>
* <li>Adjusts the query field mappings on the query based on the binding configuration of the field</li>
* <li>TODO: determine query if render is true and query is not set</li>
* </ul>
*
* {@inheritDoc}
*/
@Override
public void performFinalize(Object model, LifecycleElement parent) {
super.performFinalize(model, parent);
// check for necessary configuration
if (!isSuggestConfigured()) {
setRender(false);
}
if (!isRender()) {
return;
}
if (retrieveAllSuggestions) {
if (suggestOptions == null || suggestOptions.isEmpty()) {
// execute query method to retrieve up front suggestions
if (suggestQuery.hasConfiguredMethod()) {
retrieveSuggestOptions(ViewLifecycle.getView());
}
} else {
suggestOptionsJsString = ScriptUtils.translateValue(suggestOptions);
}
} else {
// adjust from side on query field mapping to match parent fields path
InputField field = (InputField) parent;
BindingInfo bindingInfo = field.getBindingInfo();
suggestQuery.updateQueryFieldMapping(bindingInfo);
if (suggestQuery != null) {
suggestQuery.defaultQueryTarget(ViewLifecycle.getHelper());
}
}
}
/**
* Indicates whether the suggest widget has the necessary configuration to render
*
* @return true if the necessary configuration is present, false if not
*/
public boolean isSuggestConfigured() {
if (StringUtils.isNotBlank(valuePropertyName) || suggestQuery.hasConfiguredMethod() ||
(suggestOptions != null && !suggestOptions.isEmpty())) {
return true;
}
return false;
}
/**
* Invokes the configured query method and sets the returned method value as the suggest options or
* suggest options JS string
*
* @param view view instance the suggest belongs to, used to get the view helper service if needed
*/
protected void retrieveSuggestOptions(View view) {
String queryMethodToCall = suggestQuery.getQueryMethodToCall();
MethodInvokerConfig queryMethodInvoker = suggestQuery.getQueryMethodInvokerConfig();
if (queryMethodInvoker == null) {
queryMethodInvoker = new MethodInvokerConfig();
}
// if method not set on invoker, use queryMethodToCall, note staticMethod could be set(don't know since
// there is not a getter), if so it will override the target method in prepare
if (StringUtils.isBlank(queryMethodInvoker.getTargetMethod())) {
queryMethodInvoker.setTargetMethod(queryMethodToCall);
}
// if target class or object not set, use view helper service
if ((queryMethodInvoker.getTargetClass() == null) && (queryMethodInvoker.getTargetObject() == null)) {
queryMethodInvoker.setTargetObject(view.getViewHelperService());
}
try {
queryMethodInvoker.prepare();
Object methodResult = queryMethodInvoker.invoke();
if (methodResult instanceof String) {
suggestOptionsJsString = (String) methodResult;
} else if (methodResult instanceof List) {
suggestOptions = (List<Object>) methodResult;
suggestOptionsJsString = ScriptUtils.translateValue(suggestOptions);
} else {
throw new RuntimeException("Suggest query method did not return List<String> for suggestions");
}
} catch (Exception e) {
throw new RuntimeException("Unable to invoke query method: " + queryMethodInvoker.getTargetMethod(), e);
}
}
/**
* Returns object containing post data to store for the suggest request.
*
* @return suggest post data instance
*/
public SuggestPostData getPostData() {
return new SuggestPostData(this);
}
/**
* Attribute query instance the will be executed to provide
* the suggest options
*
* @return AttributeQuery
*/
@BeanTagAttribute(type = BeanTagAttribute.AttributeType.DIRECTORBYTYPE)
public AttributeQuery getSuggestQuery() {
return suggestQuery;
}
/**
* Setter for the suggest attribute query
*
* @param suggestQuery
*/
public void setSuggestQuery(AttributeQuery suggestQuery) {
this.suggestQuery = suggestQuery;
}
/**
* Name of the property on the query result object that provides
* the options for the suggest, values from this field will be
* collected and sent back on the result to provide as suggest options.
*
* <p>If a labelPropertyName is also set,
* the property specified by it will be used as the label the user selects (the suggestion), but the value will
* be the value retrieved by this property. If only one of labelPropertyName or valuePropertyName is set,
* the property's value on the object will be used for both the value inserted on selection and the suggestion
* text (most default cases only a valuePropertyName would be set).</p>
*
* @return source property name
*/
@BeanTagAttribute
public String getValuePropertyName() {
return valuePropertyName;
}
/**
* Setter for the value property name
*
* @param valuePropertyName
*/
public void setValuePropertyName(String valuePropertyName) {
this.valuePropertyName = valuePropertyName;
}
/**
* Name of the property on the query result object that provides the label for the suggestion.
*
* <p>This should
* be set when the label that the user selects is different from the value that is inserted when a user selects a
* suggestion. If only one of labelPropertyName or valuePropertyName is set,
* the property's value on the object will be used for both the value inserted on selection and the suggestion
* text (most default cases only a valuePropertyName would be set).</p>
*
* @return labelPropertyName representing the property to use for the suggestion label of the item
*/
@BeanTagAttribute
public String getLabelPropertyName() {
return labelPropertyName;
}
/**
* Set the labelPropertyName
*
* @param labelPropertyName
*/
public void setLabelPropertyName(String labelPropertyName) {
this.labelPropertyName = labelPropertyName;
}
/**
* List of additional properties to return in the result objects to the plugin's success callback.
*
* <p>In most cases, this should not be set. The main use case
* of setting this list is to use additional properties in the select function on the plugin's options, so
* it is only recommended that this property be set when doing heavy customization to the select function.
* This list is not used if the full result object is already being returned.</p>
*
* @return the list of additional properties to send back
*/
@BeanTagAttribute
public List<String> getAdditionalPropertiesToReturn() {
return additionalPropertiesToReturn;
}
/**
* Set the list of additional properties to return to the plugin success callback results
*
* @param additionalPropertiesToReturn
*/
public void setAdditionalPropertiesToReturn(List<String> additionalPropertiesToReturn) {
this.additionalPropertiesToReturn = additionalPropertiesToReturn;
}
/**
* When set to true the results of a query method will be sent back as-is (in translated form) with all properties
* intact.
*
* <p>
* Note this is not supported for highly complex objects (ie, most auto-query objects - will throw exception).
* Intended usage of this flag is with custom query methods which return simple data objects.
* The query method can return a list of Strings which will be used for the suggestions, a list of objects
* with 'label' and 'value' properties, or a custom object. In the case of using a customObject
* labelPropertyName or valuePropertyName MUST be specified (or both) OR the custom object must contain a
* property named "label" or "value" (or both) for the suggestions to appear. In cases where this is not used,
* the data sent back represents a slim subset of the properties on the object.
* </p>
*
* @return true if the query method results should be used as the suggestions, false to assume
* objects are returned and suggestions are formed using the source property name
*/
@BeanTagAttribute
public boolean isReturnFullQueryObject() {
return returnFullQueryObject;
}
/**
* Setter for the for returning the full object of the query
*
* @param returnFullQueryObject
*/
public void setReturnFullQueryObject(boolean returnFullQueryObject) {
this.returnFullQueryObject = returnFullQueryObject;
}
/**
* Indicates whether all suggest options should be retrieved up front and provide to the suggest
* widget as options locally
*
* <p>
* Use this for a small list of options to improve performance. The query will be performed on the client
* to filter the provider options based on the users input instead of doing a query each time
* </p>
*
* <p>
* When a query method is configured and this option set to true the method will be invoked to set the
* options. The query method should not take any arguments and should return the suggestion options
* List or the JS String as a result. If a query method is not configured the suggest options can be
* set through configuration or a view helper method (for example a component finalize method)
* </p>
*
* @return true to provide the suggest options initially, false to use ajax retrieval based on the
* user's input
*/
@BeanTagAttribute
public boolean isRetrieveAllSuggestions() {
return retrieveAllSuggestions;
}
/**
* Setter for the retrieve all suggestions indicator
*
* @param retrieveAllSuggestions
*/
public void setRetrieveAllSuggestions(boolean retrieveAllSuggestions) {
this.retrieveAllSuggestions = retrieveAllSuggestions;
}
/**
* When {@link #isRetrieveAllSuggestions()} is true, this list provides the full list of suggestions
*
* <p>
* If a query method is configured that method will be invoked to populate this list, otherwise the
* list should be populated through configuration or the view helper
* </p>
*
* <p>
* The suggest options can either be a list of Strings, in which case the strings will be the suggested
* values. Or a list of objects. If the object does not have 'label' and 'value' properties, a custom render
* and select method must be provided
* </p>
*
* @return list of suggest options
*/
@BeanTagAttribute
public List<Object> getSuggestOptions() {
return suggestOptions;
}
/**
* Setter for the list of suggest options
*
* @param suggestOptions
*/
public void setSuggestOptions(List<Object> suggestOptions) {
this.suggestOptions = suggestOptions;
}
/**
* Returns the suggest options as a JS String (set by the framework from method invocation)
*
* @return suggest options JS string
*/
public String getSuggestOptionsJsString() {
if (StringUtils.isNotBlank(suggestOptionsJsString)) {
return this.suggestOptionsJsString;
}
return "null";
}
/**
* Sets suggest options javascript string
*
* @param suggestOptionsJsString
*/
public void setSuggestOptionsJsString(String suggestOptionsJsString) {
this.suggestOptionsJsString = suggestOptionsJsString;
}
/**
* Holds post data for the suggest component.
*/
public static class SuggestPostData implements Serializable {
private static final long serialVersionUID = 997780560864981128L;
private String id;
private AttributeQuery suggestQuery;
private String valuePropertyName;
private String labelPropertyName;
private List<String> additionalPropertiesToReturn;
private boolean returnFullQueryObject;
private boolean retrieveAllSuggestions;
/**
* Constructor taking suggest widget to pull post data from.
*
* @param suggest component instance to pull data
*/
public SuggestPostData(Suggest suggest) {
this.id = suggest.getId();
this.suggestQuery = suggest.getSuggestQuery();
this.valuePropertyName = suggest.getValuePropertyName();
this.labelPropertyName = suggest.getLabelPropertyName();
this.additionalPropertiesToReturn = suggest.getAdditionalPropertiesToReturn();
this.returnFullQueryObject = suggest.isReturnFullQueryObject();
this.retrieveAllSuggestions = suggest.isRetrieveAllSuggestions();
}
/**
* @see org.kuali.rice.krad.uif.util.LifecycleElement#getId()
*/
public String getId() {
return id;
}
/**
* @see Suggest#getSuggestQuery()
*/
public AttributeQuery getSuggestQuery() {
return suggestQuery;
}
/**
* @see Suggest#getValuePropertyName()
*/
public String getValuePropertyName() {
return valuePropertyName;
}
/**
* @see Suggest#getLabelPropertyName()
*/
public String getLabelPropertyName() {
return labelPropertyName;
}
/**
* @see Suggest#getAdditionalPropertiesToReturn()
*/
public List<String> getAdditionalPropertiesToReturn() {
return additionalPropertiesToReturn;
}
/**
* @see Suggest#isReturnFullQueryObject()
*/
public boolean isReturnFullQueryObject() {
return returnFullQueryObject;
}
/**
* @see Suggest#isRetrieveAllSuggestions()
*/
public boolean isRetrieveAllSuggestions() {
return retrieveAllSuggestions;
}
}
}
| KualiCo/rice | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/widget/Suggest.java | 4,696 | /**
* @see org.kuali.rice.krad.uif.util.LifecycleElement#getId()
*/ | block_comment | nl | /**
* Copyright 2005-2019 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.widget;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.uif.component.BindingInfo;
import org.kuali.rice.krad.uif.component.MethodInvokerConfig;
import org.kuali.rice.krad.uif.field.AttributeQuery;
import org.kuali.rice.krad.uif.field.InputField;
import org.kuali.rice.krad.uif.lifecycle.ViewLifecycle;
import org.kuali.rice.krad.uif.util.LifecycleElement;
import org.kuali.rice.krad.uif.util.ScriptUtils;
import org.kuali.rice.krad.uif.view.View;
/**
* Widget that provides dynamic select options to the user as they are entering the value (also known
* as auto-complete).
*
* <p>Widget is backed by an {@link org.kuali.rice.krad.uif.field.AttributeQuery} that provides the configuration
* for executing a query server side that will retrieve the valid option values.</p>
*
* @author Kuali Rice Team ([email protected])
*/
@BeanTag(name = "suggest", parent = "Uif-Suggest")
public class Suggest extends WidgetBase {
private static final long serialVersionUID = 7373706855319347225L;
private AttributeQuery suggestQuery;
private String valuePropertyName;
private String labelPropertyName;
private List<String> additionalPropertiesToReturn;
private boolean returnFullQueryObject;
private boolean retrieveAllSuggestions;
private List<Object> suggestOptions;
private String suggestOptionsJsString;
public Suggest() {
super();
}
/**
* The following updates are done here:
*
* <ul>
* <li>Invoke expression evaluation on the suggestQuery</li>
* </ul>
*
* {@inheritDoc}
*/
public void performApplyModel(Object model, LifecycleElement parent) {
super.performApplyModel(model, parent);
if (suggestQuery != null) {
ViewLifecycle.getExpressionEvaluator().evaluateExpressionsOnConfigurable(ViewLifecycle.getView(),
suggestQuery, getContext());
}
}
/**
* The following actions are performed:
*
* <ul>
* <li>Adjusts the query field mappings on the query based on the binding configuration of the field</li>
* <li>TODO: determine query if render is true and query is not set</li>
* </ul>
*
* {@inheritDoc}
*/
@Override
public void performFinalize(Object model, LifecycleElement parent) {
super.performFinalize(model, parent);
// check for necessary configuration
if (!isSuggestConfigured()) {
setRender(false);
}
if (!isRender()) {
return;
}
if (retrieveAllSuggestions) {
if (suggestOptions == null || suggestOptions.isEmpty()) {
// execute query method to retrieve up front suggestions
if (suggestQuery.hasConfiguredMethod()) {
retrieveSuggestOptions(ViewLifecycle.getView());
}
} else {
suggestOptionsJsString = ScriptUtils.translateValue(suggestOptions);
}
} else {
// adjust from side on query field mapping to match parent fields path
InputField field = (InputField) parent;
BindingInfo bindingInfo = field.getBindingInfo();
suggestQuery.updateQueryFieldMapping(bindingInfo);
if (suggestQuery != null) {
suggestQuery.defaultQueryTarget(ViewLifecycle.getHelper());
}
}
}
/**
* Indicates whether the suggest widget has the necessary configuration to render
*
* @return true if the necessary configuration is present, false if not
*/
public boolean isSuggestConfigured() {
if (StringUtils.isNotBlank(valuePropertyName) || suggestQuery.hasConfiguredMethod() ||
(suggestOptions != null && !suggestOptions.isEmpty())) {
return true;
}
return false;
}
/**
* Invokes the configured query method and sets the returned method value as the suggest options or
* suggest options JS string
*
* @param view view instance the suggest belongs to, used to get the view helper service if needed
*/
protected void retrieveSuggestOptions(View view) {
String queryMethodToCall = suggestQuery.getQueryMethodToCall();
MethodInvokerConfig queryMethodInvoker = suggestQuery.getQueryMethodInvokerConfig();
if (queryMethodInvoker == null) {
queryMethodInvoker = new MethodInvokerConfig();
}
// if method not set on invoker, use queryMethodToCall, note staticMethod could be set(don't know since
// there is not a getter), if so it will override the target method in prepare
if (StringUtils.isBlank(queryMethodInvoker.getTargetMethod())) {
queryMethodInvoker.setTargetMethod(queryMethodToCall);
}
// if target class or object not set, use view helper service
if ((queryMethodInvoker.getTargetClass() == null) && (queryMethodInvoker.getTargetObject() == null)) {
queryMethodInvoker.setTargetObject(view.getViewHelperService());
}
try {
queryMethodInvoker.prepare();
Object methodResult = queryMethodInvoker.invoke();
if (methodResult instanceof String) {
suggestOptionsJsString = (String) methodResult;
} else if (methodResult instanceof List) {
suggestOptions = (List<Object>) methodResult;
suggestOptionsJsString = ScriptUtils.translateValue(suggestOptions);
} else {
throw new RuntimeException("Suggest query method did not return List<String> for suggestions");
}
} catch (Exception e) {
throw new RuntimeException("Unable to invoke query method: " + queryMethodInvoker.getTargetMethod(), e);
}
}
/**
* Returns object containing post data to store for the suggest request.
*
* @return suggest post data instance
*/
public SuggestPostData getPostData() {
return new SuggestPostData(this);
}
/**
* Attribute query instance the will be executed to provide
* the suggest options
*
* @return AttributeQuery
*/
@BeanTagAttribute(type = BeanTagAttribute.AttributeType.DIRECTORBYTYPE)
public AttributeQuery getSuggestQuery() {
return suggestQuery;
}
/**
* Setter for the suggest attribute query
*
* @param suggestQuery
*/
public void setSuggestQuery(AttributeQuery suggestQuery) {
this.suggestQuery = suggestQuery;
}
/**
* Name of the property on the query result object that provides
* the options for the suggest, values from this field will be
* collected and sent back on the result to provide as suggest options.
*
* <p>If a labelPropertyName is also set,
* the property specified by it will be used as the label the user selects (the suggestion), but the value will
* be the value retrieved by this property. If only one of labelPropertyName or valuePropertyName is set,
* the property's value on the object will be used for both the value inserted on selection and the suggestion
* text (most default cases only a valuePropertyName would be set).</p>
*
* @return source property name
*/
@BeanTagAttribute
public String getValuePropertyName() {
return valuePropertyName;
}
/**
* Setter for the value property name
*
* @param valuePropertyName
*/
public void setValuePropertyName(String valuePropertyName) {
this.valuePropertyName = valuePropertyName;
}
/**
* Name of the property on the query result object that provides the label for the suggestion.
*
* <p>This should
* be set when the label that the user selects is different from the value that is inserted when a user selects a
* suggestion. If only one of labelPropertyName or valuePropertyName is set,
* the property's value on the object will be used for both the value inserted on selection and the suggestion
* text (most default cases only a valuePropertyName would be set).</p>
*
* @return labelPropertyName representing the property to use for the suggestion label of the item
*/
@BeanTagAttribute
public String getLabelPropertyName() {
return labelPropertyName;
}
/**
* Set the labelPropertyName
*
* @param labelPropertyName
*/
public void setLabelPropertyName(String labelPropertyName) {
this.labelPropertyName = labelPropertyName;
}
/**
* List of additional properties to return in the result objects to the plugin's success callback.
*
* <p>In most cases, this should not be set. The main use case
* of setting this list is to use additional properties in the select function on the plugin's options, so
* it is only recommended that this property be set when doing heavy customization to the select function.
* This list is not used if the full result object is already being returned.</p>
*
* @return the list of additional properties to send back
*/
@BeanTagAttribute
public List<String> getAdditionalPropertiesToReturn() {
return additionalPropertiesToReturn;
}
/**
* Set the list of additional properties to return to the plugin success callback results
*
* @param additionalPropertiesToReturn
*/
public void setAdditionalPropertiesToReturn(List<String> additionalPropertiesToReturn) {
this.additionalPropertiesToReturn = additionalPropertiesToReturn;
}
/**
* When set to true the results of a query method will be sent back as-is (in translated form) with all properties
* intact.
*
* <p>
* Note this is not supported for highly complex objects (ie, most auto-query objects - will throw exception).
* Intended usage of this flag is with custom query methods which return simple data objects.
* The query method can return a list of Strings which will be used for the suggestions, a list of objects
* with 'label' and 'value' properties, or a custom object. In the case of using a customObject
* labelPropertyName or valuePropertyName MUST be specified (or both) OR the custom object must contain a
* property named "label" or "value" (or both) for the suggestions to appear. In cases where this is not used,
* the data sent back represents a slim subset of the properties on the object.
* </p>
*
* @return true if the query method results should be used as the suggestions, false to assume
* objects are returned and suggestions are formed using the source property name
*/
@BeanTagAttribute
public boolean isReturnFullQueryObject() {
return returnFullQueryObject;
}
/**
* Setter for the for returning the full object of the query
*
* @param returnFullQueryObject
*/
public void setReturnFullQueryObject(boolean returnFullQueryObject) {
this.returnFullQueryObject = returnFullQueryObject;
}
/**
* Indicates whether all suggest options should be retrieved up front and provide to the suggest
* widget as options locally
*
* <p>
* Use this for a small list of options to improve performance. The query will be performed on the client
* to filter the provider options based on the users input instead of doing a query each time
* </p>
*
* <p>
* When a query method is configured and this option set to true the method will be invoked to set the
* options. The query method should not take any arguments and should return the suggestion options
* List or the JS String as a result. If a query method is not configured the suggest options can be
* set through configuration or a view helper method (for example a component finalize method)
* </p>
*
* @return true to provide the suggest options initially, false to use ajax retrieval based on the
* user's input
*/
@BeanTagAttribute
public boolean isRetrieveAllSuggestions() {
return retrieveAllSuggestions;
}
/**
* Setter for the retrieve all suggestions indicator
*
* @param retrieveAllSuggestions
*/
public void setRetrieveAllSuggestions(boolean retrieveAllSuggestions) {
this.retrieveAllSuggestions = retrieveAllSuggestions;
}
/**
* When {@link #isRetrieveAllSuggestions()} is true, this list provides the full list of suggestions
*
* <p>
* If a query method is configured that method will be invoked to populate this list, otherwise the
* list should be populated through configuration or the view helper
* </p>
*
* <p>
* The suggest options can either be a list of Strings, in which case the strings will be the suggested
* values. Or a list of objects. If the object does not have 'label' and 'value' properties, a custom render
* and select method must be provided
* </p>
*
* @return list of suggest options
*/
@BeanTagAttribute
public List<Object> getSuggestOptions() {
return suggestOptions;
}
/**
* Setter for the list of suggest options
*
* @param suggestOptions
*/
public void setSuggestOptions(List<Object> suggestOptions) {
this.suggestOptions = suggestOptions;
}
/**
* Returns the suggest options as a JS String (set by the framework from method invocation)
*
* @return suggest options JS string
*/
public String getSuggestOptionsJsString() {
if (StringUtils.isNotBlank(suggestOptionsJsString)) {
return this.suggestOptionsJsString;
}
return "null";
}
/**
* Sets suggest options javascript string
*
* @param suggestOptionsJsString
*/
public void setSuggestOptionsJsString(String suggestOptionsJsString) {
this.suggestOptionsJsString = suggestOptionsJsString;
}
/**
* Holds post data for the suggest component.
*/
public static class SuggestPostData implements Serializable {
private static final long serialVersionUID = 997780560864981128L;
private String id;
private AttributeQuery suggestQuery;
private String valuePropertyName;
private String labelPropertyName;
private List<String> additionalPropertiesToReturn;
private boolean returnFullQueryObject;
private boolean retrieveAllSuggestions;
/**
* Constructor taking suggest widget to pull post data from.
*
* @param suggest component instance to pull data
*/
public SuggestPostData(Suggest suggest) {
this.id = suggest.getId();
this.suggestQuery = suggest.getSuggestQuery();
this.valuePropertyName = suggest.getValuePropertyName();
this.labelPropertyName = suggest.getLabelPropertyName();
this.additionalPropertiesToReturn = suggest.getAdditionalPropertiesToReturn();
this.returnFullQueryObject = suggest.isReturnFullQueryObject();
this.retrieveAllSuggestions = suggest.isRetrieveAllSuggestions();
}
/**
* @see org.kuali.rice.krad.uif.util.LifecycleElement#getId()
<SUF>*/
public String getId() {
return id;
}
/**
* @see Suggest#getSuggestQuery()
*/
public AttributeQuery getSuggestQuery() {
return suggestQuery;
}
/**
* @see Suggest#getValuePropertyName()
*/
public String getValuePropertyName() {
return valuePropertyName;
}
/**
* @see Suggest#getLabelPropertyName()
*/
public String getLabelPropertyName() {
return labelPropertyName;
}
/**
* @see Suggest#getAdditionalPropertiesToReturn()
*/
public List<String> getAdditionalPropertiesToReturn() {
return additionalPropertiesToReturn;
}
/**
* @see Suggest#isReturnFullQueryObject()
*/
public boolean isReturnFullQueryObject() {
return returnFullQueryObject;
}
/**
* @see Suggest#isRetrieveAllSuggestions()
*/
public boolean isRetrieveAllSuggestions() {
return retrieveAllSuggestions;
}
}
}
|
164976_1 | package duplicates;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PersonServiceTest {
/**
* De PersonService zou alleen de unieke personen moeten toevoegen en duplicaten negeren.
*/
// Ik heb de fix en de uitleg hiervan in de PersonService class gezet
@Test
void testPersonService(){
PersonService personService = new PersonService();
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
personService.addPerson(new Person("David Davis", 50, 1.90, 85));
personService.addPerson(new Person("Eve Evans", 55, 1.60, 55));
personService.addPerson(new Person("Frank Foster", 60, 1.95, 90));
personService.addPerson(new Person("Grace Green", 65, 1.55, 50));
personService.addPerson(new Person("Harry Hall", 70, 2.00, 95));
personService.addPerson(new Person("Ivy Irving", 75, 1.50, 45));
personService.addPerson(new Person("Jack Jackson", 80, 2.05, 100));
personService.addPerson(new Person("Kathy King", 85, 1.45, 40));
personService.addPerson(new Person("Larry Lewis", 90, 2.10, 105));
personService.addPerson(new Person("Molly Moore", 95, 1.40, 35));
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
assertEquals(15, personService.size());
}
} | KumaSan9319/Week18BadCode | src/BadCode/src/test/java/duplicates/PersonServiceTest.java | 654 | // Ik heb de fix en de uitleg hiervan in de PersonService class gezet | line_comment | nl | package duplicates;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PersonServiceTest {
/**
* De PersonService zou alleen de unieke personen moeten toevoegen en duplicaten negeren.
*/
// Ik heb<SUF>
@Test
void testPersonService(){
PersonService personService = new PersonService();
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
personService.addPerson(new Person("David Davis", 50, 1.90, 85));
personService.addPerson(new Person("Eve Evans", 55, 1.60, 55));
personService.addPerson(new Person("Frank Foster", 60, 1.95, 90));
personService.addPerson(new Person("Grace Green", 65, 1.55, 50));
personService.addPerson(new Person("Harry Hall", 70, 2.00, 95));
personService.addPerson(new Person("Ivy Irving", 75, 1.50, 45));
personService.addPerson(new Person("Jack Jackson", 80, 2.05, 100));
personService.addPerson(new Person("Kathy King", 85, 1.45, 40));
personService.addPerson(new Person("Larry Lewis", 90, 2.10, 105));
personService.addPerson(new Person("Molly Moore", 95, 1.40, 35));
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
assertEquals(15, personService.size());
}
} |
165371_3 | /*
* Copyright 2011 Witoslaw Koczewsi <[email protected]>, Artjom Kochtchi
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package ilarkesto.persistence;
import ilarkesto.base.OverrideExpectedException;
import ilarkesto.core.base.Str;
import ilarkesto.core.search.SearchText;
import ilarkesto.core.search.Searchable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Base class for classes with persistent data.
*/
public abstract class ADatob implements Datob, Searchable {
private transient AEntity entity;
public ADatob(ADatob template) {}
final void bind(AEntity entity) {
this.entity = entity;
}
public void updateProperties(Map<String, String> properties) {}
public final HashMap<String, String> createPropertiesMap() {
HashMap<String, String> properties = new HashMap<String, String>();
storeProperties(properties);
return properties;
}
protected void storeProperties(Map<String, String> properties) {
properties.put("@type", Str.getSimpleName(getClass()));
}
protected void updateLastModified() {
if (entity == null) return;
entity.updateLastModified();
}
protected void fireModified(String field, String value) {
if (entity == null) return;
entity.fireModified(getClass().getSimpleName() + "." + field, value);
}
protected final void repairMissingMaster() {
if (entity == null) return;
throw new OverrideExpectedException();
}
@Override
public boolean matches(SearchText searchText) {
return false;
}
protected void repairDeadReferences(String entityId) {}
public void ensureIntegrity() {}
public boolean isPersisted() {
if (entity == null) return false;
return entity.isPersisted();
}
@Override
public String toString() {
return getClass().getSimpleName();
}
// --- properties as map ---
// --- helper ---
protected static void repairDeadReferencesOfValueObjects(Collection<? extends ADatob> valueObjects, String entityId) {
for (ADatob vo : valueObjects)
vo.repairDeadReferences(entityId);
}
protected final <S extends ADatob> Set<S> cloneValueObjects(Collection<S> strucktures) {
Set<S> ret = new HashSet<S>();
for (S s : strucktures) {
ret.add((S) s.clone());
}
return ret;
}
protected static Set<String> getIdsAsSet(Collection<? extends AEntity> entities) {
Set<String> result = new HashSet<String>(entities.size());
for (AEntity entity : entities)
result.add(entity.getId());
return result;
}
protected static List<String> getIdsAsList(Collection<? extends AEntity> entities) {
List<String> result = new ArrayList<String>(entities.size());
for (AEntity entity : entities)
result.add(entity.getId());
return result;
}
protected static boolean matchesKey(String s, String key) {
if (s == null) return false;
return s.toLowerCase().contains(key);
}
protected void repairDeadDatob(ADatob datob) {
throw new OverrideExpectedException();
}
@Override
public final ADatob clone() {
ADatob result;
try {
result = getClass().getConstructor(new Class[] { getClass() }).newInstance(new Object[] { this });
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Missing copy constructor in " + getClass(), ex);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
return result;
}
}
| Kunagi/ilarkesto | src/main/java/ilarkesto/persistence/ADatob.java | 1,190 | // --- helper --- | line_comment | nl | /*
* Copyright 2011 Witoslaw Koczewsi <[email protected]>, Artjom Kochtchi
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package ilarkesto.persistence;
import ilarkesto.base.OverrideExpectedException;
import ilarkesto.core.base.Str;
import ilarkesto.core.search.SearchText;
import ilarkesto.core.search.Searchable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Base class for classes with persistent data.
*/
public abstract class ADatob implements Datob, Searchable {
private transient AEntity entity;
public ADatob(ADatob template) {}
final void bind(AEntity entity) {
this.entity = entity;
}
public void updateProperties(Map<String, String> properties) {}
public final HashMap<String, String> createPropertiesMap() {
HashMap<String, String> properties = new HashMap<String, String>();
storeProperties(properties);
return properties;
}
protected void storeProperties(Map<String, String> properties) {
properties.put("@type", Str.getSimpleName(getClass()));
}
protected void updateLastModified() {
if (entity == null) return;
entity.updateLastModified();
}
protected void fireModified(String field, String value) {
if (entity == null) return;
entity.fireModified(getClass().getSimpleName() + "." + field, value);
}
protected final void repairMissingMaster() {
if (entity == null) return;
throw new OverrideExpectedException();
}
@Override
public boolean matches(SearchText searchText) {
return false;
}
protected void repairDeadReferences(String entityId) {}
public void ensureIntegrity() {}
public boolean isPersisted() {
if (entity == null) return false;
return entity.isPersisted();
}
@Override
public String toString() {
return getClass().getSimpleName();
}
// --- properties as map ---
// --- helper<SUF>
protected static void repairDeadReferencesOfValueObjects(Collection<? extends ADatob> valueObjects, String entityId) {
for (ADatob vo : valueObjects)
vo.repairDeadReferences(entityId);
}
protected final <S extends ADatob> Set<S> cloneValueObjects(Collection<S> strucktures) {
Set<S> ret = new HashSet<S>();
for (S s : strucktures) {
ret.add((S) s.clone());
}
return ret;
}
protected static Set<String> getIdsAsSet(Collection<? extends AEntity> entities) {
Set<String> result = new HashSet<String>(entities.size());
for (AEntity entity : entities)
result.add(entity.getId());
return result;
}
protected static List<String> getIdsAsList(Collection<? extends AEntity> entities) {
List<String> result = new ArrayList<String>(entities.size());
for (AEntity entity : entities)
result.add(entity.getId());
return result;
}
protected static boolean matchesKey(String s, String key) {
if (s == null) return false;
return s.toLowerCase().contains(key);
}
protected void repairDeadDatob(ADatob datob) {
throw new OverrideExpectedException();
}
@Override
public final ADatob clone() {
ADatob result;
try {
result = getClass().getConstructor(new Class[] { getClass() }).newInstance(new Object[] { this });
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Missing copy constructor in " + getClass(), ex);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
return result;
}
}
|
165375_1 | /*
* Copyright 2011 Witoslaw Koczewsi <[email protected]>, Artjom Kochtchi
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package scrum.client.wiki;
import ilarkesto.core.base.Str;
import java.util.HashMap;
import java.util.Map;
import scrum.client.ScrumGwt;
/**
* http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet http://en.wikipedia.org/wiki/Help:Wiki_markup
*/
public class WikiParser {
private String input;
private WikiModel model;
private boolean oneliner;
private Map<String, Integer> listIdentifierValues;
public WikiParser(String input) {
assert input != null;
this.input = input;
}
private void appendWord(Paragraph p, String word) {
if (isUrl(word)) {
p.add(new Link(word));
return;
}
if (word.length() > 1 && isIgnorableWordPrefix(word.charAt(0))) {
p.add(new Text(word.substring(0, 1)));
word = word.substring(1);
}
StringBuilder suffix = null;
for (int i = word.length() - 1; i >= 0; i--) {
if (isIgnorableWordSuffix(word.charAt(i))) {
if (suffix == null) suffix = new StringBuilder();
suffix.insert(0, word.charAt(i));
} else {
break;
}
}
if (suffix != null) word = word.substring(0, word.length() - suffix.length());
if (ScrumGwt.isEntityReference(word)) {
p.add(new EntityReference(word));
if (suffix != null) p.add(new Text(suffix.toString()));
return;
}
p.add(new Text(word));
if (suffix != null) p.add(new Text(suffix.toString()));
}
private Paragraph appendText(Paragraph p, String text) {
int begin;
// code
begin = text.indexOf("<code>");
if (begin >= 0 && begin < text.length() - 7) {
int end = text.indexOf("</code>", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 6, end);
String suffix = text.substring(end + 7);
if (content.trim().length() > 0) {
appendText(p, prefix);
p.add(new Code(content, false));
appendText(p, suffix);
return p;
}
}
}
// nowiki
begin = text.indexOf("<nowiki>");
if (begin >= 0 && begin < text.length() - 9) {
int end = text.indexOf("</nowiki>", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 8, end);
String suffix = text.substring(end + 9);
if (content.trim().length() > 0) {
appendText(p, prefix);
p.add(new Text(content));
appendText(p, suffix);
return p;
}
}
}
begin = text.indexOf('\n');
if (begin > 0) {
String prefix = text.substring(0, begin);
String suffix = text.substring(begin + 1);
appendText(p, prefix);
p.add(new LineBreak());
appendText(p, suffix);
return p;
}
// internal links
begin = text.indexOf("[[");
if (begin >= 0 && begin < text.length() - 4) {
int end = text.indexOf("]]", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 2, end);
String suffix = text.substring(end + 2);
if (content.trim().length() > 0) {
appendText(p, prefix);
if (content.startsWith("Image:")) {
createImage(p, content.substring(6));
} else {
createEntityReference(p, content);
}
appendText(p, suffix);
return p;
}
}
}
// external links
begin = text.indexOf("[");
if (begin >= 0 && begin < text.length() - 3) {
if (text.charAt(begin + 1) != '[') {
int end = text.indexOf("]", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String link = text.substring(begin + 1, end);
String suffix = text.substring(end + 1);
appendText(p, prefix);
int spaceIdx = link.indexOf(' ');
if (spaceIdx > 0) {
String href = link.substring(0, spaceIdx);
String label = link.substring(spaceIdx + 1);
p.add(new Link(href, label));
} else {
p.add(new Link(link));
}
appendText(p, suffix);
return p;
}
}
}
// strong end emph
begin = text.indexOf("'''''");
if (begin >= 0 && begin < text.length() - 5) {
int end = text.indexOf("'''''", begin + 5);
if (end >= 0) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 5, end);
String suffix = text.substring(end + 5);
if (content.trim().length() > 0) {
appendText(p, prefix);
Highlight h = new Highlight(true, true);
appendText(h, content);
p.add(h);
appendText(p, suffix);
return p;
}
}
} else {
begin = text.indexOf("'''");
if (begin >= 0 && begin < text.length() - 3) {
int end = text.indexOf("'''", begin + 3);
if (end >= 0) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 3, end);
String suffix = text.substring(end + 3);
if (content.trim().length() > 0) {
appendText(p, prefix);
Highlight h = new Highlight(false, true);
appendText(h, content);
p.add(h);
appendText(p, suffix);
return p;
}
}
} else {
begin = text.indexOf("''");
if (begin >= 0 && begin < text.length() - 2) {
int end = text.indexOf("''", begin + 2);
if (end >= 0) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 2, end);
String suffix = text.substring(end + 2);
if (content.trim().length() > 0) {
appendText(p, prefix);
Highlight h = new Highlight(true, false);
appendText(h, content);
p.add(h);
appendText(p, suffix);
return p;
}
}
}
}
}
while (text.length() > 0) {
int idx = text.indexOf(' ');
if (idx < 0) {
appendWord(p, text);
text = "";
} else {
appendWord(p, text.substring(0, idx));
p.add(Text.SPACE);
text = text.substring(idx + 1);
}
}
p.add(new Text(text));
return p;
}
private void createImage(Paragraph p, String code) {
String options = null;
int optionsIdx = code.indexOf('|');
if (optionsIdx > 0) {
options = code.substring(optionsIdx);
code = code.substring(0, optionsIdx).trim();
}
boolean thumb = options != null && options.contains("thumb");
boolean left = options != null && options.contains("left");
p.add(new Image(code, thumb, left));
}
private void createEntityReference(Paragraph p, String code) {
int sepIdx = code.indexOf('|');
if (sepIdx > 0) {
String name = code.substring(0, sepIdx);
String label = code.substring(sepIdx + 1);
p.add(new EntityReference("[[" + name + "]]", label));
} else {
p.add(new EntityReference("[[" + code + "]]", code));
}
}
private void nextPart() {
nextLine = null;
// empty
if (input.length() == 0) {
input = null;
return;
}
// empty lines
if (input.startsWith("\n")) {
String line = getNextLine();
while (line.trim().length() == 0 && input.length() > 0) {
burn(line.length() + 1);
line = getNextLine();
}
return;
}
// h1
if (input.startsWith("= ")) {
String line = getNextLine();
if (line.length() > 4 && line.endsWith(" =")) {
model.add(new Header(line.substring(2, line.length() - 2), 1));
burn(line.length() + 1);
return;
}
}
// h2
if (input.startsWith("== ")) {
String line = getNextLine();
if (line.length() > 6 && line.endsWith(" ==")) {
model.add(new Header(line.substring(3, line.length() - 3), 2));
burn(line.length() + 1);
return;
}
}
// h3
if (input.startsWith("=== ")) {
String line = getNextLine();
if (line.length() > 8 && line.endsWith(" ===")) {
model.add(new Header(line.substring(4, line.length() - 4), 3));
burn(line.length() + 1);
return;
}
}
// h4
if (input.startsWith("==== ")) {
String line = getNextLine();
if (line.length() > 10 && line.endsWith(" ====")) {
model.add(new Header(line.substring(5, line.length() - 5), 4));
burn(line.length() + 1);
return;
}
}
// code
if (input.startsWith("<code>")) {
int endIdx = input.indexOf("</code>");
if (endIdx > 0) {
String code = input.substring(6, endIdx);
Paragraph p = new Paragraph(true);
p.add(new Code(code, true));
model.add(p);
burn(endIdx + 8);
return;
}
}
// nowiki
if (input.startsWith("<nowiki>")) {
int endIdx = input.indexOf("</nowiki>");
if (endIdx > 0) {
String content = input.substring(8, endIdx);
Paragraph p = new Paragraph(true);
p.add(new Text(content));
model.add(p);
burn(endIdx + 10);
return;
}
}
// pre
if (input.startsWith(" ")) {
StringBuilder sb = new StringBuilder();
String line = getNextLine();
boolean first = true;
while (line.startsWith(" ")) {
if (first) {
first = false;
} else {
sb.append("\n");
}
sb.append(line);
burn(line.length() + 1);
line = getNextLine();
}
model.add(new Pre(sb.toString()));
return;
}
// list
if (input.startsWith("* ") || input.startsWith("# ") || input.startsWith("#=")) {
boolean ordered = input.startsWith("#");
int numberValue = -1;
String line = getNextLine();
String leadingSpaces = Str.getLeadingSpaces(line);
ItemList list = new ItemList(ordered, leadingSpaces.length());
Paragraph item = null;
String lineTrimmed = leadingSpaces.length() == 0 ? line : line.substring(leadingSpaces.length());
String currentListIdentifier = null;
while (!line.startsWith("\n") && line.length() > 0) {
if (lineTrimmed.startsWith("# ") || lineTrimmed.startsWith("#=") || lineTrimmed.startsWith("* ")) {
item = new Paragraph(false);
if (ordered) {
if (input.startsWith("#=")) {
String enumValueString = Str.cutFromTo(input, "#=", " ");
try {
if (!Str.isBlank(enumValueString)) {
numberValue = Integer.parseInt(enumValueString);
}
} catch (NumberFormatException e) {
if (listIdentifierValues == null)
listIdentifierValues = new HashMap<String, Integer>();
if (listIdentifierValues.containsKey(enumValueString)) {
numberValue = listIdentifierValues.get(enumValueString);
} else {
listIdentifierValues.put(enumValueString, 1);
}
currentListIdentifier = enumValueString;
}
}
}
appendText(item, Str.cutFrom(lineTrimmed, " "));
list.add(item, leadingSpaces, lineTrimmed.startsWith("#"), numberValue);
} else {
item.add(LineBreak.INSTANCE);
appendText(item, line);
}
if (currentListIdentifier != null)
listIdentifierValues.put(currentListIdentifier,
(numberValue == -1) ? listIdentifierValues.get(currentListIdentifier) + 1 : numberValue + 1);
burn(line.length() + 1);
line = getNextLine();
leadingSpaces = Str.getLeadingSpaces(line);
lineTrimmed = leadingSpaces.length() == 0 ? line : line.substring(leadingSpaces.length());
numberValue = -1;
}
model.add(list);
return;
}
// table
if (input.startsWith("{|")) {
burn(2);
Table table = new Table();
model.add(table);
Paragraph p = null;
boolean header = false;
while (true) {
boolean lastLine = false;
String line = getNextLine();
burn(line.length() + 1);
if (line.length() == 0 && input.length() == 0) return;
int closeTagIndex = line.indexOf("|}");
if (closeTagIndex >= 0) {
line = line.substring(0, closeTagIndex);
lastLine = true;
}
if (line.startsWith("|-")) {
table.addCell(p, header);
table.nextRow();
p = null;
header = false;
continue;
}
if (line.startsWith("|") || line.startsWith("!")) {
table.addCell(p, header);
p = null;
header = line.startsWith("!");
line = line.substring(1);
}
if (line.length() > 0) {
if (p == null) {
p = new Paragraph(false);
} else {
p.add(new Text("\n"));
}
int cellSepIndex = Str.indexOf(line, new String[] { "||", "!!", "!|" }, 0);
while (cellSepIndex >= 0) {
String cellContent = line.substring(0, cellSepIndex);
appendText(p, cellContent);
table.addCell(p, header);
p = new Paragraph(false);
header = line.charAt(cellSepIndex) == '!';
line = line.substring(cellSepIndex + 2);
cellSepIndex = Str.indexOf(line, new String[] { "||", "!!", "!|" }, 0);
}
appendText(p, line);
}
if (lastLine) {
table.addCell(p, header);
return;
}
}
}
// toc
if (input.startsWith("__TOC__")) {
String line = getNextLine();
if (line.equals("__TOC__")) {
burn(line.length() + 1);
model.add(new Toc(model));
return;
}
}
// paragraph
model.add(appendText(new Paragraph(!oneliner), cutParagraph()));
}
public WikiModel parse(boolean onelinerWithoutP) {
model = new WikiModel();
input = input.replace("\r", "");
input = input.replace("\t", " ");
oneliner = onelinerWithoutP && input.indexOf('\n') < 0;
while (input != null) {
nextPart();
}
return model;
}
private boolean isIgnorableWordPrefix(char c) {
return c == '(';
}
private boolean isIgnorableWordSuffix(char c) {
return c == '.' || c == ',' || c == '!' || c == '?' || c == ')' || c == ':' || c == ';';
}
private boolean isUrl(String s) {
if (s.startsWith("http://")) return true;
if (s.startsWith("https://")) return true;
if (s.startsWith("www.")) return true;
if (s.startsWith("ftp://")) return true;
if (s.startsWith("apt://")) return true;
if (s.startsWith("mailto://")) return true;
if (s.startsWith("file://")) return true;
return false;
}
private String cutParagraph() {
StringBuilder sb = new StringBuilder();
boolean first = true;
while (input.length() > 0) {
String line = getNextLine();
if (line.trim().length() == 0) {
break;
}
if (first) {
first = false;
} else {
sb.append('\n');
}
sb.append(line);
burn(line.length() + 1);
}
return sb.toString();
}
private void burn(int length) {
nextLine = null;
if (length >= input.length()) {
input = "";
} else {
input = input.substring(length);
}
}
private String nextLine;
private String getNextLine() {
if (nextLine == null) {
int idx = input.indexOf('\n');
if (idx < 0) return input;
nextLine = input.substring(0, idx);
}
return nextLine;
}
public static final String SYNTAX_INFO_HTML = "<table class='WikiParser-syntax-table' cellpadding='5px'>"
+ "<tr><td><i>Italic text</i></td> <td><code>''italic text''</code></td></tr>"
+ "<tr><td><b>Bold text</b></td> <td><code>'''bold text'''</code></td></tr>"
+ "<tr><td><b><i>Bold and italic</i></b></td> <td><code>'''''bold and italic'''''</td></tr>"
+ "<tr><td>Internal link</td> <td><code>[[Name of page]]<br>[[Name of page|Text to display]]</code></td></tr>"
+ "<tr><td>External link</td> <td><code>[http://servisto.de]<br>[http://servisto.de Text to display]<br>http://servisto.de</code></td></tr>"
+ "<tr><td><h2>Section headings</h2></td> <td><code>= heading 1 =<br>== heading 2 ==<br>=== heading 3 ===<br>==== heading 4 ====</code></td></tr>"
+ "<tr><td>Bulleted list</td> <td><code>* Item 1<br>* Item 2<br>* Item 3</code></td></tr>"
+ "<tr><td>Numbered list</td> <td><code># Item<br># Item 2<br># Item 3</code></td></tr>"
+ "<tr><td>Internal image<br>thumb</td> <td><code>[[Image:fle3]]<br>[[Image:fle3|thumb]]</code></td></tr>"
+ "<tr><td>External image<br>thumb</td> <td><code>[[Image:http://servisto.de/image.jpg]]<br>[[Image:http://servisto.de/image.jpg|thumb|left]]</code></td></tr>"
+ "<tr><td><code>Code</code></td> <td><code><code>Code</code></code></td></tr>"
+ "</table>";
}
| Kunagi/kunagi | src/main/java/scrum/client/wiki/WikiParser.java | 5,957 | /**
* http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet http://en.wikipedia.org/wiki/Help:Wiki_markup
*/ | block_comment | nl | /*
* Copyright 2011 Witoslaw Koczewsi <[email protected]>, Artjom Kochtchi
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package scrum.client.wiki;
import ilarkesto.core.base.Str;
import java.util.HashMap;
import java.util.Map;
import scrum.client.ScrumGwt;
/**
* http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet http://en.wikipedia.org/wiki/Help:Wiki_markup
<SUF>*/
public class WikiParser {
private String input;
private WikiModel model;
private boolean oneliner;
private Map<String, Integer> listIdentifierValues;
public WikiParser(String input) {
assert input != null;
this.input = input;
}
private void appendWord(Paragraph p, String word) {
if (isUrl(word)) {
p.add(new Link(word));
return;
}
if (word.length() > 1 && isIgnorableWordPrefix(word.charAt(0))) {
p.add(new Text(word.substring(0, 1)));
word = word.substring(1);
}
StringBuilder suffix = null;
for (int i = word.length() - 1; i >= 0; i--) {
if (isIgnorableWordSuffix(word.charAt(i))) {
if (suffix == null) suffix = new StringBuilder();
suffix.insert(0, word.charAt(i));
} else {
break;
}
}
if (suffix != null) word = word.substring(0, word.length() - suffix.length());
if (ScrumGwt.isEntityReference(word)) {
p.add(new EntityReference(word));
if (suffix != null) p.add(new Text(suffix.toString()));
return;
}
p.add(new Text(word));
if (suffix != null) p.add(new Text(suffix.toString()));
}
private Paragraph appendText(Paragraph p, String text) {
int begin;
// code
begin = text.indexOf("<code>");
if (begin >= 0 && begin < text.length() - 7) {
int end = text.indexOf("</code>", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 6, end);
String suffix = text.substring(end + 7);
if (content.trim().length() > 0) {
appendText(p, prefix);
p.add(new Code(content, false));
appendText(p, suffix);
return p;
}
}
}
// nowiki
begin = text.indexOf("<nowiki>");
if (begin >= 0 && begin < text.length() - 9) {
int end = text.indexOf("</nowiki>", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 8, end);
String suffix = text.substring(end + 9);
if (content.trim().length() > 0) {
appendText(p, prefix);
p.add(new Text(content));
appendText(p, suffix);
return p;
}
}
}
begin = text.indexOf('\n');
if (begin > 0) {
String prefix = text.substring(0, begin);
String suffix = text.substring(begin + 1);
appendText(p, prefix);
p.add(new LineBreak());
appendText(p, suffix);
return p;
}
// internal links
begin = text.indexOf("[[");
if (begin >= 0 && begin < text.length() - 4) {
int end = text.indexOf("]]", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 2, end);
String suffix = text.substring(end + 2);
if (content.trim().length() > 0) {
appendText(p, prefix);
if (content.startsWith("Image:")) {
createImage(p, content.substring(6));
} else {
createEntityReference(p, content);
}
appendText(p, suffix);
return p;
}
}
}
// external links
begin = text.indexOf("[");
if (begin >= 0 && begin < text.length() - 3) {
if (text.charAt(begin + 1) != '[') {
int end = text.indexOf("]", begin);
if (end > begin) {
String prefix = text.substring(0, begin);
String link = text.substring(begin + 1, end);
String suffix = text.substring(end + 1);
appendText(p, prefix);
int spaceIdx = link.indexOf(' ');
if (spaceIdx > 0) {
String href = link.substring(0, spaceIdx);
String label = link.substring(spaceIdx + 1);
p.add(new Link(href, label));
} else {
p.add(new Link(link));
}
appendText(p, suffix);
return p;
}
}
}
// strong end emph
begin = text.indexOf("'''''");
if (begin >= 0 && begin < text.length() - 5) {
int end = text.indexOf("'''''", begin + 5);
if (end >= 0) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 5, end);
String suffix = text.substring(end + 5);
if (content.trim().length() > 0) {
appendText(p, prefix);
Highlight h = new Highlight(true, true);
appendText(h, content);
p.add(h);
appendText(p, suffix);
return p;
}
}
} else {
begin = text.indexOf("'''");
if (begin >= 0 && begin < text.length() - 3) {
int end = text.indexOf("'''", begin + 3);
if (end >= 0) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 3, end);
String suffix = text.substring(end + 3);
if (content.trim().length() > 0) {
appendText(p, prefix);
Highlight h = new Highlight(false, true);
appendText(h, content);
p.add(h);
appendText(p, suffix);
return p;
}
}
} else {
begin = text.indexOf("''");
if (begin >= 0 && begin < text.length() - 2) {
int end = text.indexOf("''", begin + 2);
if (end >= 0) {
String prefix = text.substring(0, begin);
String content = text.substring(begin + 2, end);
String suffix = text.substring(end + 2);
if (content.trim().length() > 0) {
appendText(p, prefix);
Highlight h = new Highlight(true, false);
appendText(h, content);
p.add(h);
appendText(p, suffix);
return p;
}
}
}
}
}
while (text.length() > 0) {
int idx = text.indexOf(' ');
if (idx < 0) {
appendWord(p, text);
text = "";
} else {
appendWord(p, text.substring(0, idx));
p.add(Text.SPACE);
text = text.substring(idx + 1);
}
}
p.add(new Text(text));
return p;
}
private void createImage(Paragraph p, String code) {
String options = null;
int optionsIdx = code.indexOf('|');
if (optionsIdx > 0) {
options = code.substring(optionsIdx);
code = code.substring(0, optionsIdx).trim();
}
boolean thumb = options != null && options.contains("thumb");
boolean left = options != null && options.contains("left");
p.add(new Image(code, thumb, left));
}
private void createEntityReference(Paragraph p, String code) {
int sepIdx = code.indexOf('|');
if (sepIdx > 0) {
String name = code.substring(0, sepIdx);
String label = code.substring(sepIdx + 1);
p.add(new EntityReference("[[" + name + "]]", label));
} else {
p.add(new EntityReference("[[" + code + "]]", code));
}
}
private void nextPart() {
nextLine = null;
// empty
if (input.length() == 0) {
input = null;
return;
}
// empty lines
if (input.startsWith("\n")) {
String line = getNextLine();
while (line.trim().length() == 0 && input.length() > 0) {
burn(line.length() + 1);
line = getNextLine();
}
return;
}
// h1
if (input.startsWith("= ")) {
String line = getNextLine();
if (line.length() > 4 && line.endsWith(" =")) {
model.add(new Header(line.substring(2, line.length() - 2), 1));
burn(line.length() + 1);
return;
}
}
// h2
if (input.startsWith("== ")) {
String line = getNextLine();
if (line.length() > 6 && line.endsWith(" ==")) {
model.add(new Header(line.substring(3, line.length() - 3), 2));
burn(line.length() + 1);
return;
}
}
// h3
if (input.startsWith("=== ")) {
String line = getNextLine();
if (line.length() > 8 && line.endsWith(" ===")) {
model.add(new Header(line.substring(4, line.length() - 4), 3));
burn(line.length() + 1);
return;
}
}
// h4
if (input.startsWith("==== ")) {
String line = getNextLine();
if (line.length() > 10 && line.endsWith(" ====")) {
model.add(new Header(line.substring(5, line.length() - 5), 4));
burn(line.length() + 1);
return;
}
}
// code
if (input.startsWith("<code>")) {
int endIdx = input.indexOf("</code>");
if (endIdx > 0) {
String code = input.substring(6, endIdx);
Paragraph p = new Paragraph(true);
p.add(new Code(code, true));
model.add(p);
burn(endIdx + 8);
return;
}
}
// nowiki
if (input.startsWith("<nowiki>")) {
int endIdx = input.indexOf("</nowiki>");
if (endIdx > 0) {
String content = input.substring(8, endIdx);
Paragraph p = new Paragraph(true);
p.add(new Text(content));
model.add(p);
burn(endIdx + 10);
return;
}
}
// pre
if (input.startsWith(" ")) {
StringBuilder sb = new StringBuilder();
String line = getNextLine();
boolean first = true;
while (line.startsWith(" ")) {
if (first) {
first = false;
} else {
sb.append("\n");
}
sb.append(line);
burn(line.length() + 1);
line = getNextLine();
}
model.add(new Pre(sb.toString()));
return;
}
// list
if (input.startsWith("* ") || input.startsWith("# ") || input.startsWith("#=")) {
boolean ordered = input.startsWith("#");
int numberValue = -1;
String line = getNextLine();
String leadingSpaces = Str.getLeadingSpaces(line);
ItemList list = new ItemList(ordered, leadingSpaces.length());
Paragraph item = null;
String lineTrimmed = leadingSpaces.length() == 0 ? line : line.substring(leadingSpaces.length());
String currentListIdentifier = null;
while (!line.startsWith("\n") && line.length() > 0) {
if (lineTrimmed.startsWith("# ") || lineTrimmed.startsWith("#=") || lineTrimmed.startsWith("* ")) {
item = new Paragraph(false);
if (ordered) {
if (input.startsWith("#=")) {
String enumValueString = Str.cutFromTo(input, "#=", " ");
try {
if (!Str.isBlank(enumValueString)) {
numberValue = Integer.parseInt(enumValueString);
}
} catch (NumberFormatException e) {
if (listIdentifierValues == null)
listIdentifierValues = new HashMap<String, Integer>();
if (listIdentifierValues.containsKey(enumValueString)) {
numberValue = listIdentifierValues.get(enumValueString);
} else {
listIdentifierValues.put(enumValueString, 1);
}
currentListIdentifier = enumValueString;
}
}
}
appendText(item, Str.cutFrom(lineTrimmed, " "));
list.add(item, leadingSpaces, lineTrimmed.startsWith("#"), numberValue);
} else {
item.add(LineBreak.INSTANCE);
appendText(item, line);
}
if (currentListIdentifier != null)
listIdentifierValues.put(currentListIdentifier,
(numberValue == -1) ? listIdentifierValues.get(currentListIdentifier) + 1 : numberValue + 1);
burn(line.length() + 1);
line = getNextLine();
leadingSpaces = Str.getLeadingSpaces(line);
lineTrimmed = leadingSpaces.length() == 0 ? line : line.substring(leadingSpaces.length());
numberValue = -1;
}
model.add(list);
return;
}
// table
if (input.startsWith("{|")) {
burn(2);
Table table = new Table();
model.add(table);
Paragraph p = null;
boolean header = false;
while (true) {
boolean lastLine = false;
String line = getNextLine();
burn(line.length() + 1);
if (line.length() == 0 && input.length() == 0) return;
int closeTagIndex = line.indexOf("|}");
if (closeTagIndex >= 0) {
line = line.substring(0, closeTagIndex);
lastLine = true;
}
if (line.startsWith("|-")) {
table.addCell(p, header);
table.nextRow();
p = null;
header = false;
continue;
}
if (line.startsWith("|") || line.startsWith("!")) {
table.addCell(p, header);
p = null;
header = line.startsWith("!");
line = line.substring(1);
}
if (line.length() > 0) {
if (p == null) {
p = new Paragraph(false);
} else {
p.add(new Text("\n"));
}
int cellSepIndex = Str.indexOf(line, new String[] { "||", "!!", "!|" }, 0);
while (cellSepIndex >= 0) {
String cellContent = line.substring(0, cellSepIndex);
appendText(p, cellContent);
table.addCell(p, header);
p = new Paragraph(false);
header = line.charAt(cellSepIndex) == '!';
line = line.substring(cellSepIndex + 2);
cellSepIndex = Str.indexOf(line, new String[] { "||", "!!", "!|" }, 0);
}
appendText(p, line);
}
if (lastLine) {
table.addCell(p, header);
return;
}
}
}
// toc
if (input.startsWith("__TOC__")) {
String line = getNextLine();
if (line.equals("__TOC__")) {
burn(line.length() + 1);
model.add(new Toc(model));
return;
}
}
// paragraph
model.add(appendText(new Paragraph(!oneliner), cutParagraph()));
}
public WikiModel parse(boolean onelinerWithoutP) {
model = new WikiModel();
input = input.replace("\r", "");
input = input.replace("\t", " ");
oneliner = onelinerWithoutP && input.indexOf('\n') < 0;
while (input != null) {
nextPart();
}
return model;
}
private boolean isIgnorableWordPrefix(char c) {
return c == '(';
}
private boolean isIgnorableWordSuffix(char c) {
return c == '.' || c == ',' || c == '!' || c == '?' || c == ')' || c == ':' || c == ';';
}
private boolean isUrl(String s) {
if (s.startsWith("http://")) return true;
if (s.startsWith("https://")) return true;
if (s.startsWith("www.")) return true;
if (s.startsWith("ftp://")) return true;
if (s.startsWith("apt://")) return true;
if (s.startsWith("mailto://")) return true;
if (s.startsWith("file://")) return true;
return false;
}
private String cutParagraph() {
StringBuilder sb = new StringBuilder();
boolean first = true;
while (input.length() > 0) {
String line = getNextLine();
if (line.trim().length() == 0) {
break;
}
if (first) {
first = false;
} else {
sb.append('\n');
}
sb.append(line);
burn(line.length() + 1);
}
return sb.toString();
}
private void burn(int length) {
nextLine = null;
if (length >= input.length()) {
input = "";
} else {
input = input.substring(length);
}
}
private String nextLine;
private String getNextLine() {
if (nextLine == null) {
int idx = input.indexOf('\n');
if (idx < 0) return input;
nextLine = input.substring(0, idx);
}
return nextLine;
}
public static final String SYNTAX_INFO_HTML = "<table class='WikiParser-syntax-table' cellpadding='5px'>"
+ "<tr><td><i>Italic text</i></td> <td><code>''italic text''</code></td></tr>"
+ "<tr><td><b>Bold text</b></td> <td><code>'''bold text'''</code></td></tr>"
+ "<tr><td><b><i>Bold and italic</i></b></td> <td><code>'''''bold and italic'''''</td></tr>"
+ "<tr><td>Internal link</td> <td><code>[[Name of page]]<br>[[Name of page|Text to display]]</code></td></tr>"
+ "<tr><td>External link</td> <td><code>[http://servisto.de]<br>[http://servisto.de Text to display]<br>http://servisto.de</code></td></tr>"
+ "<tr><td><h2>Section headings</h2></td> <td><code>= heading 1 =<br>== heading 2 ==<br>=== heading 3 ===<br>==== heading 4 ====</code></td></tr>"
+ "<tr><td>Bulleted list</td> <td><code>* Item 1<br>* Item 2<br>* Item 3</code></td></tr>"
+ "<tr><td>Numbered list</td> <td><code># Item<br># Item 2<br># Item 3</code></td></tr>"
+ "<tr><td>Internal image<br>thumb</td> <td><code>[[Image:fle3]]<br>[[Image:fle3|thumb]]</code></td></tr>"
+ "<tr><td>External image<br>thumb</td> <td><code>[[Image:http://servisto.de/image.jpg]]<br>[[Image:http://servisto.de/image.jpg|thumb|left]]</code></td></tr>"
+ "<tr><td><code>Code</code></td> <td><code><code>Code</code></code></td></tr>"
+ "</table>";
}
|
55411_4 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fontys.time;
import com.oracle.jrockit.jfr.InvalidValueException;
import com.sun.media.jfxmedia.logging.Logger;
/**
*
* @author Ryan-KuroTenshi
*/
public class Period implements IPeriod{
ITime bt = null;
ITime et = null;
/**
*
creation of a period with begin time bt and end time et
* @param bt begin time bt must be earlier than end time et
* @param et
*/
public Period(ITime bt, ITime et)
{
if(bt.difference(et) < 0 )
{
this.bt = bt;
this.et = et;
}
}
@Override
public ITime getBeginTime() {
return this.bt;
}
@Override
public ITime getEndTime() {
return this.et;
}
@Override
public int length() {
return Math.abs(bt.difference(et));
}
@Override
public void setBeginTime(ITime beginTime) {
try
{
validateSetBeginTime(beginTime.difference(this.et));
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
this.bt = beginTime;
}
}
public void validateSetBeginTime(int i) throws InvalidValueException
{
if(i > 0)
{
throw new InvalidValueException("Begin time is before end time");
}
}
@Override
public void setEndTime(ITime endTime) {
this.et = endTime;
}
@Override
public void move(int minutes) {
this.et = this.et.plus(minutes);
this.bt = this.bt.plus(minutes);
}
@Override
public void changeLengthWith(int minutes) {
if(Math.abs(minutes) == minutes)
this.et = this.et.plus(Math.abs(minutes));
else
Logger.logMsg(0, "Not allowed to add negative values");
}
@Override
public boolean isPartOf(IPeriod period) {
if( (bt.compareTo(period.getBeginTime()) > 0 &&
et.compareTo(period.getEndTime()) < 0 )
||
(et.compareTo(period.getEndTime()) > 0 &&
bt.compareTo(period.getBeginTime()) < 0 )
)
{
return true;
}
return false;
}
@Override
public IPeriod unionWith(IPeriod period) {
ITime bt1 = this.bt;
ITime bt2 = period.getBeginTime();
ITime et1 = this.et;
ITime et2 = period.getEndTime();
Boolean bt1First = true;
Boolean isMergable = false;
Period pResult = null;
if(bt1.compareTo(bt2) > 0)
bt1First = true;
else
bt1First = false;
if(bt1First)
{
if(et1.equals(bt2))
{
pResult = new Period(bt1, et2);
}
if(et1.compareTo(bt2) > 0 && et1.compareTo(et2) < 0)
{
pResult = new Period(bt1, et2);
}
}
else
{
if(et2.equals(bt1))
{
pResult = new Period(bt2, et1);
}
if(et2.compareTo(bt1) < 0 && et2.compareTo(et1) > 0)
{
pResult = new Period(bt2, et1);
}
}
return pResult;
}
@Override
public IPeriod intersectionWith(IPeriod period) {
ITime bt1 = this.bt;
ITime bt2 = period.getBeginTime();
ITime et1 = this.et;
ITime et2 = period.getEndTime();
Boolean bt1First = true;
Period pResult = null;
if(bt1.compareTo(bt2) > 0)
bt1First = true;
else
bt1First = false;
if(bt1First)
{
if(et1.equals(bt2))
{
pResult = new Period(et1, bt2);
}
if(et1.compareTo(bt2) > 0 && et1.compareTo(et2) < 0)
{
pResult = new Period(et1, bt2);
}
}
else
{
if(et2.equals(bt1))
{
pResult = new Period(et2, bt1);
}
if(et2.compareTo(bt1) > 0 && et2.compareTo(et1) < 0)
{
pResult = new Period(et2, bt1);
}
}
return pResult;
}
/*intersection = doorsnede | tussen 2 periodes | = gemeenschappelijk del van 2 periodes / overlap = intersection
|_____________|bt1___________|BT2___(overlap)___|et1___________|ET2______________|
| bt1 < bt2 |
| et2 > et1 |
| [et1 > bt2 = has overlap] | [bt2, et1] result /// if no overlap ret null;
p1.intersectwith(p2);
*/
/*
union = totale aangeslote periode als je 2 periodes samenneemt ... IF overlap Tenzij begin2 = eind1 en visa versa;
result is bt1 t/m et2 orz...;
*/
}
| KuroPSPiso/GSO31Time | src/fontys/time/Period.java | 1,625 | /*
union = totale aangeslote periode als je 2 periodes samenneemt ... IF overlap Tenzij begin2 = eind1 en visa versa;
result is bt1 t/m et2 orz...;
*/ | block_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fontys.time;
import com.oracle.jrockit.jfr.InvalidValueException;
import com.sun.media.jfxmedia.logging.Logger;
/**
*
* @author Ryan-KuroTenshi
*/
public class Period implements IPeriod{
ITime bt = null;
ITime et = null;
/**
*
creation of a period with begin time bt and end time et
* @param bt begin time bt must be earlier than end time et
* @param et
*/
public Period(ITime bt, ITime et)
{
if(bt.difference(et) < 0 )
{
this.bt = bt;
this.et = et;
}
}
@Override
public ITime getBeginTime() {
return this.bt;
}
@Override
public ITime getEndTime() {
return this.et;
}
@Override
public int length() {
return Math.abs(bt.difference(et));
}
@Override
public void setBeginTime(ITime beginTime) {
try
{
validateSetBeginTime(beginTime.difference(this.et));
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
this.bt = beginTime;
}
}
public void validateSetBeginTime(int i) throws InvalidValueException
{
if(i > 0)
{
throw new InvalidValueException("Begin time is before end time");
}
}
@Override
public void setEndTime(ITime endTime) {
this.et = endTime;
}
@Override
public void move(int minutes) {
this.et = this.et.plus(minutes);
this.bt = this.bt.plus(minutes);
}
@Override
public void changeLengthWith(int minutes) {
if(Math.abs(minutes) == minutes)
this.et = this.et.plus(Math.abs(minutes));
else
Logger.logMsg(0, "Not allowed to add negative values");
}
@Override
public boolean isPartOf(IPeriod period) {
if( (bt.compareTo(period.getBeginTime()) > 0 &&
et.compareTo(period.getEndTime()) < 0 )
||
(et.compareTo(period.getEndTime()) > 0 &&
bt.compareTo(period.getBeginTime()) < 0 )
)
{
return true;
}
return false;
}
@Override
public IPeriod unionWith(IPeriod period) {
ITime bt1 = this.bt;
ITime bt2 = period.getBeginTime();
ITime et1 = this.et;
ITime et2 = period.getEndTime();
Boolean bt1First = true;
Boolean isMergable = false;
Period pResult = null;
if(bt1.compareTo(bt2) > 0)
bt1First = true;
else
bt1First = false;
if(bt1First)
{
if(et1.equals(bt2))
{
pResult = new Period(bt1, et2);
}
if(et1.compareTo(bt2) > 0 && et1.compareTo(et2) < 0)
{
pResult = new Period(bt1, et2);
}
}
else
{
if(et2.equals(bt1))
{
pResult = new Period(bt2, et1);
}
if(et2.compareTo(bt1) < 0 && et2.compareTo(et1) > 0)
{
pResult = new Period(bt2, et1);
}
}
return pResult;
}
@Override
public IPeriod intersectionWith(IPeriod period) {
ITime bt1 = this.bt;
ITime bt2 = period.getBeginTime();
ITime et1 = this.et;
ITime et2 = period.getEndTime();
Boolean bt1First = true;
Period pResult = null;
if(bt1.compareTo(bt2) > 0)
bt1First = true;
else
bt1First = false;
if(bt1First)
{
if(et1.equals(bt2))
{
pResult = new Period(et1, bt2);
}
if(et1.compareTo(bt2) > 0 && et1.compareTo(et2) < 0)
{
pResult = new Period(et1, bt2);
}
}
else
{
if(et2.equals(bt1))
{
pResult = new Period(et2, bt1);
}
if(et2.compareTo(bt1) > 0 && et2.compareTo(et1) < 0)
{
pResult = new Period(et2, bt1);
}
}
return pResult;
}
/*intersection = doorsnede | tussen 2 periodes | = gemeenschappelijk del van 2 periodes / overlap = intersection
|_____________|bt1___________|BT2___(overlap)___|et1___________|ET2______________|
| bt1 < bt2 |
| et2 > et1 |
| [et1 > bt2 = has overlap] | [bt2, et1] result /// if no overlap ret null;
p1.intersectwith(p2);
*/
/*
union = totale<SUF>*/
}
|
69615_0 | package com.molvenolakeresort.restaurant.order;
import com.molvenolakeresort.restaurant.menu.MenuItem;
public class OrderItem {
// MenuItem
// Quantity
// dictionary zou hier al voldoen, maar met oog op de toekomst is dit beter
}
| KuroPSPiso/molveno | src/main/java/com/molvenolakeresort/restaurant/order/OrderItem.java | 81 | // dictionary zou hier al voldoen, maar met oog op de toekomst is dit beter | line_comment | nl | package com.molvenolakeresort.restaurant.order;
import com.molvenolakeresort.restaurant.menu.MenuItem;
public class OrderItem {
// MenuItem
// Quantity
// dictionary zou<SUF>
}
|
196618_17 | /*
* L2jOrion Project - www.l2jorion.com
*
* 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 l2jorion.game.managers;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
import javolution.util.FastList;
import l2jorion.Config;
import l2jorion.game.datatables.sql.ItemTable;
import l2jorion.game.datatables.sql.NpcTable;
import l2jorion.game.datatables.sql.SpawnTable;
import l2jorion.game.idfactory.IdFactory;
import l2jorion.game.model.L2Attackable;
import l2jorion.game.model.L2Object;
import l2jorion.game.model.L2World;
import l2jorion.game.model.actor.instance.L2ItemInstance;
import l2jorion.game.model.actor.instance.L2NpcInstance;
import l2jorion.game.model.actor.instance.L2PcInstance;
import l2jorion.game.model.entity.Announcements;
import l2jorion.game.model.spawn.L2Spawn;
import l2jorion.game.network.SystemMessageId;
import l2jorion.game.network.serverpackets.CreatureSay;
import l2jorion.game.network.serverpackets.SystemMessage;
import l2jorion.game.templates.L2NpcTemplate;
import l2jorion.game.thread.ThreadPoolManager;
import l2jorion.logger.Logger;
import l2jorion.logger.LoggerFactory;
/**
* control for sequence of Christmas.
* @version 1.00
* @author Darki699
*/
public class ChristmasManager
{
private static final Logger LOG = LoggerFactory.getLogger(ChristmasManager.class);
protected List<L2NpcInstance> objectQueue = new FastList<>();
protected Random rand = new Random();
// X-Mas message list
protected String[] message =
{
"Ho Ho Ho... Merry Christmas!",
"God is Love...",
"Christmas is all about love...",
"Christmas is thus about God and Love...",
"Love is the key to peace among all Lineage creature kind..",
"Love is the key to peace and happiness within all creation...",
"Love needs to be practiced - Love needs to flow - Love needs to make happy...",
"Love starts with your partner, children and family and expands to all world.",
"God bless all kind.",
"God bless Lineage.",
"Forgive all.",
"Ask for forgiveness even from all the \"past away\" ones.",
"Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".",
"Enhance the feeling within yourself of being a member of a far larger family than your physical family",
"MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!",
"Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.",
"Take it easy. Relax these coming days.",
"Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !",
"Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.",
"What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!",
"Divine bliss and love NEVER can be stored and received later.",
"There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET",
"Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.",
"Beloved children of God",
"Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.",
"The holy spirit of Christmas is the holy spirit of God and God's love for all days.",
"When the Christmas spirit lives on and on...",
"When the power of love created during the pre-Christmas days is kept alive and growing.",
"Peace among all mankind is growing as well =)",
"The holy gift of love is an eternal gift of love put into your heart like a seed.",
"Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.",
"What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.",
"It only is your now decision that makes the difference !",
"It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.",
"The decision of love, peace and happiness is the right one.",
"Whatever you focus on is filling your mind and subsequently filling your heart.",
"No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.",
"God's love is always present.",
"God's Love has always been in same power and purity and quantity available to all of you.",
"Expand the spirit of Christmas love and Christmas joy to span all year of your life...",
"Do all year long what is creating this special Christmas feeling of love joy and happiness.",
"Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ",
"Expand the power of love over more and more days.",
"Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.",
"Remember the people and surrounding you had when feeling most happy, most loved, most magic",
"People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...",
"The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...",
"Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.",
"Songs can fine tune and open our heart for love from God and our loved ones.",
"Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity",
"Enjoy your love for ever!",
"Christmas can be every day - As soon as you truly love every day =)",
"Christmas is when you love all and are loved by all.",
"Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.",
"Secret in God's creation is that no single person can truly love without ignition of his love.",
"You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ",
"God created many and all are made of love and all are made to love...",
"The miracle of love only works if you want to become a fully loving member of the family of divine love.",
"Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !",
"May all have a happy time on Christmas each year. Merry Christmas!",
"Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.",
"Have a wonderful Christmas. May god bless our family. I love you all.",
"Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.",
"Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.",
"Merry Xmas!",
"May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.",
"Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.",
"I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.",
"May you have the best of Christmas this year and all your dreams come true.",
"May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!"
},
sender =
{
"Santa Claus",
"Papai Noel",
"Shengdan Laoren",
"Santa",
"Viejo Pascuero",
"Sinter Klaas",
"Father Christmas",
"Saint Nicholas",
"Joulupukki",
"Pere Noel",
"Saint Nikolaus",
"Kanakaloka",
"De Kerstman",
"Winter grandfather",
"Babbo Natale",
"Hoteiosho",
"Kaledu Senelis",
"Black Peter",
"Kerstman",
"Julenissen",
"Swiety Mikolaj",
"Ded Moroz",
"Julenisse",
"El Nino Jesus",
"Jultomten",
"Reindeer Dasher",
"Reindeer Dancer",
"Christmas Spirit",
"Reindeer Prancer",
"Reindeer Vixen",
"Reindeer Comet",
"Reindeer Cupid",
"Reindeer Donner",
"Reindeer Donder",
"Reindeer Dunder",
"Reindeer Blitzen",
"Reindeer Bliksem",
"Reindeer Blixem",
"Reindeer Rudolf",
"Christmas Elf"
};
// Presents List:
protected int[] presents =
{
5560,
5560,
5560,
5560,
5560, /* x-mas tree */
5560,
5560,
5560,
5560,
5560,
5561,
5561,
5561,
5561,
5561, /* special x-mas tree */
5562,
5562,
5562,
5562, /* 1st Carol */
5563,
5563,
5563,
5563, /* 2nd Carol */
5564,
5564,
5564,
5564, /* 3rd Carol */
5565,
5565,
5565,
5565, /* 4th Carol */
5566,
5566,
5566,
5566, /* 5th Carol */
5583,
5583, /* 6th Carol */
5584,
5584, /* 7th Carol */
5585,
5585, /* 8th Carol */
5586,
5586, /* 9th Carol */
5587,
5587, /* 10th Carol */
6403,
6403,
6403,
6403, /* Star Shard */
6403,
6403,
6403,
6403,
6406,
6406,
6406,
6406, /* FireWorks */
6407,
6407, /* Large FireWorks */
5555, /* Token of Love */
7836, /* Santa Hat #1 */
9138, /* Santa Hat #2 */
8936, /* Santa's Antlers Hat */
6394, /* Red Party Mask */
5808
/* Black Party Mask */
};
// The message task sent at fixed rate
protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null;
// Manager should only be Initialized once:
protected int isManagerInit = 0;
// Interval of Christmas actions:
protected long _IntervalOfChristmas = 600000; // 10 minutes
private final int first = 25000, last = 73099;
/************************************** Initial Functions **************************************/
/**
* Empty constructor Does nothing
*/
public ChristmasManager()
{
//
}
/**
* @return an instance of <b>this</b> InstanceManager.
*/
public static ChristmasManager getInstance()
{
return SingletonHolder._instance;
}
/**
* initialize <b>this</b> ChristmasManager
* @param activeChar
*/
public void init(final L2PcInstance activeChar)
{
if (isManagerInit > 0)
{
activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient....");
return;
}
activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate.");
// Tasks:
spawnTrees();
startFestiveMessagesAtFixedRate();
isManagerInit++;
givePresentsAtFixedRate();
isManagerInit++;
checkIfOkToAnnounce();
}
/**
* ends <b>this</b> ChristmasManager
* @param activeChar
*/
public void end(final L2PcInstance activeChar)
{
if (isManagerInit < 4)
{
if (activeChar != null)
{
activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing....");
}
return;
}
if (activeChar != null)
{
activeChar.sendMessage("Terminating! This may take a while, please be patient...");
}
// Tasks:
ThreadPoolManager.getInstance().executeTask(new DeleteSpawns());
endFestiveMessagesAtFixedRate();
isManagerInit--;
endPresentGivingAtFixedRate();
isManagerInit--;
checkIfOkToAnnounce();
}
/************************************ - Tree management - *************************************/
/**
* Main function - spawns all trees.
*/
public void spawnTrees()
{
GetTreePos gtp = new GetTreePos(first);
ThreadPoolManager.getInstance().executeTask(gtp);
gtp = null;
}
/**
* returns a random X-Mas tree Npc Id.
* @return int tree Npc Id.
*/
protected int getTreeId()
{
final int[] ids =
{
13006,
13007
};
return ids[rand.nextInt(ids.length)];
}
/**
* gets random world positions according to spawned world objects and spawns x-mas trees around them...
*/
public class GetTreePos implements Runnable
{
private int _iterator;
private Future<?> _task;
public GetTreePos(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
if (rand.nextInt(100) > 10)
{
obj = null;
}
}
if (rand.nextInt(100) > 50)
{
spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
return;
}
_iterator++;
GetTreePos gtp = new GetTreePos(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300);
gtp.setTask(_task);
gtp = null;
}
}
/**
* Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue.
*/
public class DeleteSpawns implements Runnable
{
@Override
public void run()
{
if (objectQueue == null || objectQueue.isEmpty())
return;
for (final L2NpcInstance deleted : objectQueue)
{
if (deleted == null)
{
continue;
}
try
{
L2World.getInstance().removeObject(deleted);
deleted.decayMe();
deleted.deleteMe();
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
continue;
}
}
objectQueue.clear();
objectQueue = null;
isManagerInit = isManagerInit - 2;
checkIfOkToAnnounce();
}
}
/**
* Spawns one x-mas tree at a given location x,y,z
* @param id - int tree npc id.
* @param x - int loc x
* @param y - int loc y
* @param z - int loc z
*/
protected void spawnOneTree(final int id, final int x, final int y, final int z)
{
try
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
L2Spawn spawn = new L2Spawn(template1);
template1 = null;
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setLocx(x);
spawn.setLocy(y);
spawn.setLocz(z);
L2NpcInstance tree = spawn.spawnOne();
L2World.getInstance().storeObject(tree);
objectQueue.add(tree);
spawn = null;
tree = null;
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
/**************************** - send players festive messages - *****************************/
/**
* Ends X-Mas messages sent to players, and terminates the thread.
*/
private void endFestiveMessagesAtFixedRate()
{
if (_XMasMessageTask != null)
{
_XMasMessageTask.cancel(true);
_XMasMessageTask = null;
}
}
/**
* Starts X-Mas messages sent to all players, and initialize the thread.
*/
private void startFestiveMessagesAtFixedRate()
{
SendXMasMessage XMasMessage = new SendXMasMessage();
_XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas);
XMasMessage = null;
}
/**
* Sends X-Mas messages to all world players.
* @author Darki699
*/
class SendXMasMessage implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
pc.sendPacket(getXMasMessage());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
/**
* Returns a random X-Mas message.
* @return CreatureSay message
*/
protected CreatureSay getXMasMessage()
{
final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage());
return cs;
}
/**
* Returns a random name of the X-Mas message sender, sent to players
* @return String of the message sender's name
*/
private String getRandomSender()
{
return sender[rand.nextInt(sender.length)];
}
/**
* Returns a random X-Mas message String
* @return String containing the random message.
*/
private String getRandomXMasMessage()
{
return message[rand.nextInt(message.length)];
}
/******************************* - give special items trees - ********************************/
// Trees , Carols , Tokens of love, Fireworks, Santa Hats.
/**
* Starts X-Mas Santa presents sent to all players, and initialize the thread.
*/
private void givePresentsAtFixedRate()
{
final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask();
_XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3);
}
class XMasPresentGivingTask implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
else if (pc.getInventoryLimit() <= pc.getInventory().getSize())
{
pc.sendMessage("Santa wanted to give you a Present but your inventory was full :(");
continue;
}
else if (rand.nextInt(100) < 50)
{
final int itemId = getSantaRandomPresent();
L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc);
pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc);
String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
item = null;
SystemMessage sm;
sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
sm.addString(itemName + " from Santa's Present Bag...");
pc.broadcastPacket(sm);
itemName = null;
sm = null;
}
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
protected int getSantaRandomPresent()
{
return presents[rand.nextInt(presents.length)];
}
/**
* Ends X-Mas present giving to players, and terminates the thread.
*/
private void endPresentGivingAtFixedRate()
{
if (_XMasPresentsTask != null)
{
_XMasPresentsTask.cancel(true);
_XMasPresentsTask = null;
}
}
/************************************ - spawn NPCs in towns - ***************************************/
// NPC Ids: 31863 , 31864
public class SpawnSantaNPCs implements Runnable
{
private int _iterator;
private Future<?> _task;
public SpawnSantaNPCs(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
obj = null;
}
}
if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance)
{
spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
checkIfOkToAnnounce();
return;
}
_iterator++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
}
}
protected int getSantaId()
{
return rand.nextInt(100) < 50 ? 31863 : 31864;
}
protected void checkIfOkToAnnounce()
{
if (isManagerInit == 4)
{
Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year.");
Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours.");
LOG.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday.");
final EndEvent ee = new EndEvent();
Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000);
ee.setTask(task);
task = null;
isManagerInit = 5;
}
if (isManagerInit == 0)
{
Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities.");
LOG.info("ChristmasManager:Terminated ChristmasManager.");
isManagerInit = -1;
}
}
public class EndEvent implements Runnable
{
private Future<?> _task;
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
end(null);
}
}
private static class SingletonHolder
{
protected static final ChristmasManager _instance = new ChristmasManager();
}
}
| L2Customs/L2jOrion_Interlude_C6 | L2jOrion_SourceCode/src/l2jorion/game/managers/ChristmasManager.java | 7,589 | /************************************ - Tree management - *************************************/ | block_comment | nl | /*
* L2jOrion Project - www.l2jorion.com
*
* 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 l2jorion.game.managers;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Future;
import javolution.util.FastList;
import l2jorion.Config;
import l2jorion.game.datatables.sql.ItemTable;
import l2jorion.game.datatables.sql.NpcTable;
import l2jorion.game.datatables.sql.SpawnTable;
import l2jorion.game.idfactory.IdFactory;
import l2jorion.game.model.L2Attackable;
import l2jorion.game.model.L2Object;
import l2jorion.game.model.L2World;
import l2jorion.game.model.actor.instance.L2ItemInstance;
import l2jorion.game.model.actor.instance.L2NpcInstance;
import l2jorion.game.model.actor.instance.L2PcInstance;
import l2jorion.game.model.entity.Announcements;
import l2jorion.game.model.spawn.L2Spawn;
import l2jorion.game.network.SystemMessageId;
import l2jorion.game.network.serverpackets.CreatureSay;
import l2jorion.game.network.serverpackets.SystemMessage;
import l2jorion.game.templates.L2NpcTemplate;
import l2jorion.game.thread.ThreadPoolManager;
import l2jorion.logger.Logger;
import l2jorion.logger.LoggerFactory;
/**
* control for sequence of Christmas.
* @version 1.00
* @author Darki699
*/
public class ChristmasManager
{
private static final Logger LOG = LoggerFactory.getLogger(ChristmasManager.class);
protected List<L2NpcInstance> objectQueue = new FastList<>();
protected Random rand = new Random();
// X-Mas message list
protected String[] message =
{
"Ho Ho Ho... Merry Christmas!",
"God is Love...",
"Christmas is all about love...",
"Christmas is thus about God and Love...",
"Love is the key to peace among all Lineage creature kind..",
"Love is the key to peace and happiness within all creation...",
"Love needs to be practiced - Love needs to flow - Love needs to make happy...",
"Love starts with your partner, children and family and expands to all world.",
"God bless all kind.",
"God bless Lineage.",
"Forgive all.",
"Ask for forgiveness even from all the \"past away\" ones.",
"Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".",
"Enhance the feeling within yourself of being a member of a far larger family than your physical family",
"MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!",
"Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.",
"Take it easy. Relax these coming days.",
"Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !",
"Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.",
"What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!",
"Divine bliss and love NEVER can be stored and received later.",
"There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET",
"Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.",
"Beloved children of God",
"Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.",
"The holy spirit of Christmas is the holy spirit of God and God's love for all days.",
"When the Christmas spirit lives on and on...",
"When the power of love created during the pre-Christmas days is kept alive and growing.",
"Peace among all mankind is growing as well =)",
"The holy gift of love is an eternal gift of love put into your heart like a seed.",
"Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.",
"What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.",
"It only is your now decision that makes the difference !",
"It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.",
"The decision of love, peace and happiness is the right one.",
"Whatever you focus on is filling your mind and subsequently filling your heart.",
"No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.",
"God's love is always present.",
"God's Love has always been in same power and purity and quantity available to all of you.",
"Expand the spirit of Christmas love and Christmas joy to span all year of your life...",
"Do all year long what is creating this special Christmas feeling of love joy and happiness.",
"Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ",
"Expand the power of love over more and more days.",
"Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.",
"Remember the people and surrounding you had when feeling most happy, most loved, most magic",
"People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...",
"The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...",
"Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.",
"Songs can fine tune and open our heart for love from God and our loved ones.",
"Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity",
"Enjoy your love for ever!",
"Christmas can be every day - As soon as you truly love every day =)",
"Christmas is when you love all and are loved by all.",
"Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.",
"Secret in God's creation is that no single person can truly love without ignition of his love.",
"You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ",
"God created many and all are made of love and all are made to love...",
"The miracle of love only works if you want to become a fully loving member of the family of divine love.",
"Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !",
"May all have a happy time on Christmas each year. Merry Christmas!",
"Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.",
"Have a wonderful Christmas. May god bless our family. I love you all.",
"Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.",
"Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.",
"Merry Xmas!",
"May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.",
"Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.",
"I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.",
"May you have the best of Christmas this year and all your dreams come true.",
"May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!"
},
sender =
{
"Santa Claus",
"Papai Noel",
"Shengdan Laoren",
"Santa",
"Viejo Pascuero",
"Sinter Klaas",
"Father Christmas",
"Saint Nicholas",
"Joulupukki",
"Pere Noel",
"Saint Nikolaus",
"Kanakaloka",
"De Kerstman",
"Winter grandfather",
"Babbo Natale",
"Hoteiosho",
"Kaledu Senelis",
"Black Peter",
"Kerstman",
"Julenissen",
"Swiety Mikolaj",
"Ded Moroz",
"Julenisse",
"El Nino Jesus",
"Jultomten",
"Reindeer Dasher",
"Reindeer Dancer",
"Christmas Spirit",
"Reindeer Prancer",
"Reindeer Vixen",
"Reindeer Comet",
"Reindeer Cupid",
"Reindeer Donner",
"Reindeer Donder",
"Reindeer Dunder",
"Reindeer Blitzen",
"Reindeer Bliksem",
"Reindeer Blixem",
"Reindeer Rudolf",
"Christmas Elf"
};
// Presents List:
protected int[] presents =
{
5560,
5560,
5560,
5560,
5560, /* x-mas tree */
5560,
5560,
5560,
5560,
5560,
5561,
5561,
5561,
5561,
5561, /* special x-mas tree */
5562,
5562,
5562,
5562, /* 1st Carol */
5563,
5563,
5563,
5563, /* 2nd Carol */
5564,
5564,
5564,
5564, /* 3rd Carol */
5565,
5565,
5565,
5565, /* 4th Carol */
5566,
5566,
5566,
5566, /* 5th Carol */
5583,
5583, /* 6th Carol */
5584,
5584, /* 7th Carol */
5585,
5585, /* 8th Carol */
5586,
5586, /* 9th Carol */
5587,
5587, /* 10th Carol */
6403,
6403,
6403,
6403, /* Star Shard */
6403,
6403,
6403,
6403,
6406,
6406,
6406,
6406, /* FireWorks */
6407,
6407, /* Large FireWorks */
5555, /* Token of Love */
7836, /* Santa Hat #1 */
9138, /* Santa Hat #2 */
8936, /* Santa's Antlers Hat */
6394, /* Red Party Mask */
5808
/* Black Party Mask */
};
// The message task sent at fixed rate
protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null;
// Manager should only be Initialized once:
protected int isManagerInit = 0;
// Interval of Christmas actions:
protected long _IntervalOfChristmas = 600000; // 10 minutes
private final int first = 25000, last = 73099;
/************************************** Initial Functions **************************************/
/**
* Empty constructor Does nothing
*/
public ChristmasManager()
{
//
}
/**
* @return an instance of <b>this</b> InstanceManager.
*/
public static ChristmasManager getInstance()
{
return SingletonHolder._instance;
}
/**
* initialize <b>this</b> ChristmasManager
* @param activeChar
*/
public void init(final L2PcInstance activeChar)
{
if (isManagerInit > 0)
{
activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient....");
return;
}
activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate.");
// Tasks:
spawnTrees();
startFestiveMessagesAtFixedRate();
isManagerInit++;
givePresentsAtFixedRate();
isManagerInit++;
checkIfOkToAnnounce();
}
/**
* ends <b>this</b> ChristmasManager
* @param activeChar
*/
public void end(final L2PcInstance activeChar)
{
if (isManagerInit < 4)
{
if (activeChar != null)
{
activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing....");
}
return;
}
if (activeChar != null)
{
activeChar.sendMessage("Terminating! This may take a while, please be patient...");
}
// Tasks:
ThreadPoolManager.getInstance().executeTask(new DeleteSpawns());
endFestiveMessagesAtFixedRate();
isManagerInit--;
endPresentGivingAtFixedRate();
isManagerInit--;
checkIfOkToAnnounce();
}
/************************************ - Tree management<SUF>*/
/**
* Main function - spawns all trees.
*/
public void spawnTrees()
{
GetTreePos gtp = new GetTreePos(first);
ThreadPoolManager.getInstance().executeTask(gtp);
gtp = null;
}
/**
* returns a random X-Mas tree Npc Id.
* @return int tree Npc Id.
*/
protected int getTreeId()
{
final int[] ids =
{
13006,
13007
};
return ids[rand.nextInt(ids.length)];
}
/**
* gets random world positions according to spawned world objects and spawns x-mas trees around them...
*/
public class GetTreePos implements Runnable
{
private int _iterator;
private Future<?> _task;
public GetTreePos(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
if (rand.nextInt(100) > 10)
{
obj = null;
}
}
if (rand.nextInt(100) > 50)
{
spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
return;
}
_iterator++;
GetTreePos gtp = new GetTreePos(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300);
gtp.setTask(_task);
gtp = null;
}
}
/**
* Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue.
*/
public class DeleteSpawns implements Runnable
{
@Override
public void run()
{
if (objectQueue == null || objectQueue.isEmpty())
return;
for (final L2NpcInstance deleted : objectQueue)
{
if (deleted == null)
{
continue;
}
try
{
L2World.getInstance().removeObject(deleted);
deleted.decayMe();
deleted.deleteMe();
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
continue;
}
}
objectQueue.clear();
objectQueue = null;
isManagerInit = isManagerInit - 2;
checkIfOkToAnnounce();
}
}
/**
* Spawns one x-mas tree at a given location x,y,z
* @param id - int tree npc id.
* @param x - int loc x
* @param y - int loc y
* @param z - int loc z
*/
protected void spawnOneTree(final int id, final int x, final int y, final int z)
{
try
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
L2Spawn spawn = new L2Spawn(template1);
template1 = null;
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setLocx(x);
spawn.setLocy(y);
spawn.setLocz(z);
L2NpcInstance tree = spawn.spawnOne();
L2World.getInstance().storeObject(tree);
objectQueue.add(tree);
spawn = null;
tree = null;
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
/**************************** - send players festive messages - *****************************/
/**
* Ends X-Mas messages sent to players, and terminates the thread.
*/
private void endFestiveMessagesAtFixedRate()
{
if (_XMasMessageTask != null)
{
_XMasMessageTask.cancel(true);
_XMasMessageTask = null;
}
}
/**
* Starts X-Mas messages sent to all players, and initialize the thread.
*/
private void startFestiveMessagesAtFixedRate()
{
SendXMasMessage XMasMessage = new SendXMasMessage();
_XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas);
XMasMessage = null;
}
/**
* Sends X-Mas messages to all world players.
* @author Darki699
*/
class SendXMasMessage implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
pc.sendPacket(getXMasMessage());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
/**
* Returns a random X-Mas message.
* @return CreatureSay message
*/
protected CreatureSay getXMasMessage()
{
final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage());
return cs;
}
/**
* Returns a random name of the X-Mas message sender, sent to players
* @return String of the message sender's name
*/
private String getRandomSender()
{
return sender[rand.nextInt(sender.length)];
}
/**
* Returns a random X-Mas message String
* @return String containing the random message.
*/
private String getRandomXMasMessage()
{
return message[rand.nextInt(message.length)];
}
/******************************* - give special items trees - ********************************/
// Trees , Carols , Tokens of love, Fireworks, Santa Hats.
/**
* Starts X-Mas Santa presents sent to all players, and initialize the thread.
*/
private void givePresentsAtFixedRate()
{
final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask();
_XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3);
}
class XMasPresentGivingTask implements Runnable
{
@Override
public void run()
{
try
{
for (final L2PcInstance pc : L2World.getInstance().getAllPlayers().values())
{
if (pc == null)
{
continue;
}
else if (pc.isOnline() == 0)
{
continue;
}
else if (pc.getInventoryLimit() <= pc.getInventory().getSize())
{
pc.sendMessage("Santa wanted to give you a Present but your inventory was full :(");
continue;
}
else if (rand.nextInt(100) < 50)
{
final int itemId = getSantaRandomPresent();
L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc);
pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc);
String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
item = null;
SystemMessage sm;
sm = new SystemMessage(SystemMessageId.EARNED_ITEM);
sm.addString(itemName + " from Santa's Present Bag...");
pc.broadcastPacket(sm);
itemName = null;
sm = null;
}
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
}
}
protected int getSantaRandomPresent()
{
return presents[rand.nextInt(presents.length)];
}
/**
* Ends X-Mas present giving to players, and terminates the thread.
*/
private void endPresentGivingAtFixedRate()
{
if (_XMasPresentsTask != null)
{
_XMasPresentsTask.cancel(true);
_XMasPresentsTask = null;
}
}
/************************************ - spawn NPCs in towns - ***************************************/
// NPC Ids: 31863 , 31864
public class SpawnSantaNPCs implements Runnable
{
private int _iterator;
private Future<?> _task;
public SpawnSantaNPCs(final int iter)
{
_iterator = iter;
}
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
try
{
L2Object obj = null;
while (obj == null)
{
obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn();
_iterator++;
if (obj != null && obj instanceof L2Attackable)
{
obj = null;
}
}
if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance)
{
spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ());
}
}
catch (final Throwable t)
{
if (Config.ENABLE_ALL_EXCEPTIONS)
t.printStackTrace();
}
if (_iterator >= last)
{
isManagerInit++;
checkIfOkToAnnounce();
return;
}
_iterator++;
SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator);
_task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300);
ssNPCs.setTask(_task);
ssNPCs = null;
}
}
protected int getSantaId()
{
return rand.nextInt(100) < 50 ? 31863 : 31864;
}
protected void checkIfOkToAnnounce()
{
if (isManagerInit == 4)
{
Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year.");
Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours.");
LOG.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday.");
final EndEvent ee = new EndEvent();
Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000);
ee.setTask(task);
task = null;
isManagerInit = 5;
}
if (isManagerInit == 0)
{
Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities.");
LOG.info("ChristmasManager:Terminated ChristmasManager.");
isManagerInit = -1;
}
}
public class EndEvent implements Runnable
{
private Future<?> _task;
public void setTask(final Future<?> task)
{
_task = task;
}
@Override
public void run()
{
if (_task != null)
{
_task.cancel(true);
_task = null;
}
end(null);
}
}
private static class SingletonHolder
{
protected static final ChristmasManager _instance = new ChristmasManager();
}
}
|
191096_11 | /*
* 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.eureka;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.DynamicStringSetProperty;
import com.netflix.eureka.aws.AwsBindingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* A default implementation of eureka server configuration as required by
* {@link EurekaServerConfig}.
*
* <p>
* The information required for configuring eureka server is provided in a
* configuration file.The configuration file is searched for in the classpath
* with the name specified by the property <em>eureka.server.props</em> and with
* the suffix <em>.properties</em>. If the property is not specified,
* <em>eureka-server.properties</em> is assumed as the default.The properties
* that are looked up uses the <em>namespace</em> passed on to this class.
* </p>
*
* <p>
* If the <em>eureka.environment</em> property is specified, additionally
* <em>eureka-server-<eureka.environment>.properties</em> is loaded in addition
* to <em>eureka-server.properties</em>.
* </p>
*
* @author Karthik Ranganathan
*
*/
@Singleton
public class DefaultEurekaServerConfig implements EurekaServerConfig {
private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment";
private static final String TEST = "test";
private static final String EUREKA_ENVIRONMENT = "eureka.environment";
private static final Logger logger = LoggerFactory
.getLogger(DefaultEurekaServerConfig.class);
private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory
.getInstance();
private static final DynamicStringProperty EUREKA_PROPS_FILE = DynamicPropertyFactory
.getInstance().getStringProperty("eureka.server.props",
"eureka-server");
private static final int TIME_TO_WAIT_FOR_REPLICATION = 30000;
private String namespace = "eureka.";
// These counters are checked for each HTTP request. Instantiating them per request like for the other
// properties would be too costly.
private final DynamicStringSetProperty rateLimiterPrivilegedClients =
new DynamicStringSetProperty(namespace + "rateLimiter.privilegedClients", Collections.<String>emptySet());
private final DynamicBooleanProperty rateLimiterEnabled = configInstance.getBooleanProperty(namespace + "rateLimiter.enabled", false);
private final DynamicBooleanProperty rateLimiterThrottleStandardClients = configInstance.getBooleanProperty(namespace + "rateLimiter.throttleStandardClients", false);
private final DynamicIntProperty rateLimiterBurstSize = configInstance.getIntProperty(namespace + "rateLimiter.burstSize", 10);
private final DynamicIntProperty rateLimiterRegistryFetchAverageRate = configInstance.getIntProperty(namespace + "rateLimiter.registryFetchAverageRate", 500);
private final DynamicIntProperty rateLimiterFullFetchAverageRate = configInstance.getIntProperty(namespace + "rateLimiter.fullFetchAverageRate", 100);
private final DynamicStringProperty listAutoScalingGroupsRoleName =
configInstance.getStringProperty(namespace + "listAutoScalingGroupsRoleName", "ListAutoScalingGroups");
private final DynamicStringProperty myUrl = configInstance.getStringProperty(namespace + "myUrl", null);
public DefaultEurekaServerConfig() {
init();
}
public DefaultEurekaServerConfig(String namespace) {
this.namespace = namespace;
init();
}
private void init() {
String env = ConfigurationManager.getConfigInstance().getString(
EUREKA_ENVIRONMENT, TEST);
ConfigurationManager.getConfigInstance().setProperty(
ARCHAIUS_DEPLOYMENT_ENVIRONMENT, env);
String eurekaPropsFile = EUREKA_PROPS_FILE.get();
try {
// ConfigurationManager
// .loadPropertiesFromResources(eurekaPropsFile);
ConfigurationManager
.loadCascadedPropertiesFromResources(eurekaPropsFile);
} catch (IOException e) {
logger.warn(
"Cannot find the properties specified : {}. This may be okay if there are other environment "
+ "specific properties or the configuration is installed with a different mechanism.",
eurekaPropsFile);
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getAWSAccessId()
*/
@Override
public String getAWSAccessId() {
String aWSAccessId = configInstance.getStringProperty(
namespace + "awsAccessId", null).get();
if (null != aWSAccessId) {
return aWSAccessId.trim();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getAWSAccessId()
*/
@Override
public String getAWSSecretKey() {
String aWSSecretKey = configInstance.getStringProperty(
namespace + "awsSecretKey", null).get();
if (null != aWSSecretKey) {
return aWSSecretKey.trim();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindRebindRetries()
*/
@Override
public int getEIPBindRebindRetries() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetries", 3).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindingRetryInterval()
*/
@Override
public int getEIPBindingRetryIntervalMsWhenUnbound() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetryIntervalMsWhenUnbound", (1 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindingRetryInterval()
*/
@Override
public int getEIPBindingRetryIntervalMs() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetryIntervalMs", (5 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#shouldEnableSelfPreservation()
*/
@Override
public boolean shouldEnableSelfPreservation() {
return configInstance.getBooleanProperty(
namespace + "enableSelfPreservation", true).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.eureka.EurekaServerConfig#getPeerEurekaNodesUpdateInterval()
*/
@Override
public int getPeerEurekaNodesUpdateIntervalMs() {
return configInstance
.getIntProperty(namespace + "peerEurekaNodesUpdateIntervalMs",
(10 * 60 * 1000)).get();
}
@Override
public int getRenewalThresholdUpdateIntervalMs() {
return configInstance.getIntProperty(
namespace + "renewalThresholdUpdateIntervalMs",
(15 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.eureka.EurekaServerConfig#getExpectedClientRenewalIntervalSeconds()
*/
@Override
public int getExpectedClientRenewalIntervalSeconds() {
final int configured = configInstance.getIntProperty(
namespace + "expectedClientRenewalIntervalSeconds",
30).get();
return configured > 0 ? configured : 30;
}
@Override
public double getRenewalPercentThreshold() {
return configInstance.getDoubleProperty(
namespace + "renewalPercentThreshold", 0.85).get();
}
@Override
public boolean shouldEnableReplicatedRequestCompression() {
return configInstance.getBooleanProperty(
namespace + "enableReplicatedRequestCompression", false).get();
}
@Override
public int getNumberOfReplicationRetries() {
return configInstance.getIntProperty(
namespace + "numberOfReplicationRetries", 5).get();
}
@Override
public int getPeerEurekaStatusRefreshTimeIntervalMs() {
return configInstance.getIntProperty(
namespace + "peerEurekaStatusRefreshTimeIntervalMs",
(30 * 1000)).get();
}
@Override
public int getWaitTimeInMsWhenSyncEmpty() {
return configInstance.getIntProperty(
namespace + "waitTimeInMsWhenSyncEmpty", (1000 * 60 * 5)).get();
}
@Override
public int getPeerNodeConnectTimeoutMs() {
return configInstance.getIntProperty(
namespace + "peerNodeConnectTimeoutMs", 1000).get();
}
@Override
public int getPeerNodeReadTimeoutMs() {
return configInstance.getIntProperty(
namespace + "peerNodeReadTimeoutMs", 5000).get();
}
@Override
public int getPeerNodeTotalConnections() {
return configInstance.getIntProperty(
namespace + "peerNodeTotalConnections", 1000).get();
}
@Override
public int getPeerNodeTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + "peerNodeTotalConnectionsPerHost", 500).get();
}
@Override
public int getPeerNodeConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + "peerNodeConnectionIdleTimeoutSeconds", 30).get();
}
@Override
public long getRetentionTimeInMSInDeltaQueue() {
return configInstance.getLongProperty(
namespace + "retentionTimeInMSInDeltaQueue", (3 * 60 * 1000))
.get();
}
@Override
public long getDeltaRetentionTimerIntervalInMs() {
return configInstance.getLongProperty(
namespace + "deltaRetentionTimerIntervalInMs", (30 * 1000))
.get();
}
@Override
public long getEvictionIntervalTimerInMs() {
return configInstance.getLongProperty(
namespace + "evictionIntervalTimerInMs", (60 * 1000)).get();
}
@Override
public boolean shouldUseAwsAsgApi() {
return configInstance.getBooleanProperty(namespace + "shouldUseAwsAsgApi", true).get();
}
@Override
public int getASGQueryTimeoutMs() {
return configInstance.getIntProperty(namespace + "asgQueryTimeoutMs",
300).get();
}
@Override
public long getASGUpdateIntervalMs() {
return configInstance.getIntProperty(namespace + "asgUpdateIntervalMs",
(5 * 60 * 1000)).get();
}
@Override
public long getASGCacheExpiryTimeoutMs() {
return configInstance.getIntProperty(namespace + "asgCacheExpiryTimeoutMs",
(10 * 60 * 1000)).get(); // defaults to longer than the asg update interval
}
@Override
public long getResponseCacheAutoExpirationInSeconds() {
return configInstance.getIntProperty(
namespace + "responseCacheAutoExpirationInSeconds", 180).get();
}
@Override
public long getResponseCacheUpdateIntervalMs() {
return configInstance.getIntProperty(
namespace + "responseCacheUpdateIntervalMs", (30 * 1000)).get();
}
@Override
public boolean shouldUseReadOnlyResponseCache() {
return configInstance.getBooleanProperty(
namespace + "shouldUseReadOnlyResponseCache", true).get();
}
@Override
public boolean shouldDisableDelta() {
return configInstance.getBooleanProperty(namespace + "disableDelta",
false).get();
}
@Override
public long getMaxIdleThreadInMinutesAgeForStatusReplication() {
return configInstance
.getLongProperty(
namespace + "maxIdleThreadAgeInMinutesForStatusReplication",
10).get();
}
@Override
public int getMinThreadsForStatusReplication() {
return configInstance.getIntProperty(
namespace + "minThreadsForStatusReplication", 1).get();
}
@Override
public int getMaxThreadsForStatusReplication() {
return configInstance.getIntProperty(
namespace + "maxThreadsForStatusReplication", 1).get();
}
@Override
public int getMaxElementsInStatusReplicationPool() {
return configInstance.getIntProperty(
namespace + "maxElementsInStatusReplicationPool", 10000).get();
}
@Override
public boolean shouldSyncWhenTimestampDiffers() {
return configInstance.getBooleanProperty(
namespace + "syncWhenTimestampDiffers", true).get();
}
@Override
public int getRegistrySyncRetries() {
return configInstance.getIntProperty(
namespace + "numberRegistrySyncRetries", 5).get();
}
@Override
public long getRegistrySyncRetryWaitMs() {
return configInstance.getIntProperty(
namespace + "registrySyncRetryWaitMs", 30 * 1000).get();
}
@Override
public int getMaxElementsInPeerReplicationPool() {
return configInstance.getIntProperty(
namespace + "maxElementsInPeerReplicationPool", 10000).get();
}
@Override
public long getMaxIdleThreadAgeInMinutesForPeerReplication() {
return configInstance.getIntProperty(
namespace + "maxIdleThreadAgeInMinutesForPeerReplication", 15)
.get();
}
@Override
public int getMinThreadsForPeerReplication() {
return configInstance.getIntProperty(
namespace + "minThreadsForPeerReplication", 5).get();
}
@Override
public int getMaxThreadsForPeerReplication() {
return configInstance.getIntProperty(
namespace + "maxThreadsForPeerReplication", 20).get();
}
@Override
public int getMaxTimeForReplication() {
return configInstance.getIntProperty(
namespace + "maxTimeForReplication",
TIME_TO_WAIT_FOR_REPLICATION).get();
}
@Override
public boolean shouldPrimeAwsReplicaConnections() {
return configInstance.getBooleanProperty(
namespace + "primeAwsReplicaConnections", true).get();
}
@Override
public boolean shouldDisableDeltaForRemoteRegions() {
return configInstance.getBooleanProperty(
namespace + "disableDeltaForRemoteRegions", false).get();
}
@Override
public int getRemoteRegionConnectTimeoutMs() {
return configInstance.getIntProperty(
namespace + "remoteRegionConnectTimeoutMs", 2000).get();
}
@Override
public int getRemoteRegionReadTimeoutMs() {
return configInstance.getIntProperty(
namespace + "remoteRegionReadTimeoutMs", 5000).get();
}
@Override
public int getRemoteRegionTotalConnections() {
return configInstance.getIntProperty(
namespace + "remoteRegionTotalConnections", 1000).get();
}
@Override
public int getRemoteRegionTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + "remoteRegionTotalConnectionsPerHost", 500).get();
}
@Override
public int getRemoteRegionConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + "remoteRegionConnectionIdleTimeoutSeconds", 30)
.get();
}
@Override
public boolean shouldGZipContentFromRemoteRegion() {
return configInstance.getBooleanProperty(
namespace + "remoteRegion.gzipContent", true).get();
}
/**
* Expects a property with name: [eureka-namespace].remoteRegionUrlsWithName and a value being a comma separated
* list of region name & remote url pairs, separated with a ";". <br/>
* So, if you wish to specify two regions with name region1 & region2, the property value will be:
<PRE>
eureka.remoteRegionUrlsWithName=region1;http://region1host/eureka/v2,region2;http://region2host/eureka/v2
</PRE>
* The above property will result in the following map:
<PRE>
region1->"http://region1host/eureka/v2"
region2->"http://region2host/eureka/v2"
</PRE>
* @return A map of region name to remote region URL parsed from the property specified above. If there is no
* property available, then an empty map is returned.
*/
@Override
public Map<String, String> getRemoteRegionUrlsWithName() {
String propName = namespace + "remoteRegionUrlsWithName";
String remoteRegionUrlWithNameString = configInstance.getStringProperty(propName, null).get();
if (null == remoteRegionUrlWithNameString) {
return Collections.emptyMap();
}
String[] remoteRegionUrlWithNamePairs = remoteRegionUrlWithNameString.split(",");
Map<String, String> toReturn = new HashMap<String, String>(remoteRegionUrlWithNamePairs.length);
final String pairSplitChar = ";";
for (String remoteRegionUrlWithNamePair : remoteRegionUrlWithNamePairs) {
String[] pairSplit = remoteRegionUrlWithNamePair.split(pairSplitChar);
if (pairSplit.length < 2) {
logger.error("Error reading eureka remote region urls from property {}. "
+ "Invalid entry {} for remote region url. The entry must contain region name and url "
+ "separated by a {}. Ignoring this entry.",
propName, remoteRegionUrlWithNamePair, pairSplitChar);
} else {
String regionName = pairSplit[0];
String regionUrl = pairSplit[1];
if (pairSplit.length > 2) {
StringBuilder regionUrlAssembler = new StringBuilder();
for (int i = 1; i < pairSplit.length; i++) {
if (regionUrlAssembler.length() != 0) {
regionUrlAssembler.append(pairSplitChar);
}
regionUrlAssembler.append(pairSplit[i]);
}
regionUrl = regionUrlAssembler.toString();
}
toReturn.put(regionName, regionUrl);
}
}
return toReturn;
}
@Override
public String[] getRemoteRegionUrls() {
String remoteRegionUrlString = configInstance.getStringProperty(
namespace + "remoteRegionUrls", null).get();
String[] remoteRegionUrl = null;
if (remoteRegionUrlString != null) {
remoteRegionUrl = remoteRegionUrlString.split(",");
}
return remoteRegionUrl;
}
@Nullable
@Override
public Set<String> getRemoteRegionAppWhitelist(@Nullable String regionName) {
if (null == regionName) {
regionName = "global";
} else {
regionName = regionName.trim().toLowerCase();
}
DynamicStringProperty appWhiteListProp =
configInstance.getStringProperty(namespace + "remoteRegion." + regionName + ".appWhiteList", null);
if (null == appWhiteListProp || null == appWhiteListProp.get()) {
return null;
} else {
String appWhiteListStr = appWhiteListProp.get();
String[] whitelistEntries = appWhiteListStr.split(",");
return new HashSet<String>(Arrays.asList(whitelistEntries));
}
}
@Override
public int getRemoteRegionRegistryFetchInterval() {
return configInstance.getIntProperty(
namespace + "remoteRegion.registryFetchIntervalInSeconds", 30)
.get();
}
@Override
public int getRemoteRegionFetchThreadPoolSize() {
return configInstance.getIntProperty(
namespace + "remoteRegion.fetchThreadPoolSize", 20)
.get();
}
@Override
public String getRemoteRegionTrustStore() {
return configInstance.getStringProperty(
namespace + "remoteRegion.trustStoreFileName", "").get();
}
@Override
public String getRemoteRegionTrustStorePassword() {
return configInstance.getStringProperty(
namespace + "remoteRegion.trustStorePassword", "changeit")
.get();
}
@Override
public boolean disableTransparentFallbackToOtherRegion() {
return configInstance.getBooleanProperty(namespace + "remoteRegion.disable.transparent.fallback", false).get();
}
@Override
public boolean shouldBatchReplication() {
return configInstance.getBooleanProperty(namespace + "shouldBatchReplication", false).get();
}
@Override
public String getMyUrl() {
return myUrl.get();
}
@Override
public boolean shouldLogIdentityHeaders() {
return configInstance.getBooleanProperty(namespace + "auth.shouldLogIdentityHeaders", true).get();
}
@Override
public String getJsonCodecName() {
return configInstance.getStringProperty(
namespace + "jsonCodecName", null).get();
}
@Override
public String getXmlCodecName() {
return configInstance.getStringProperty(
namespace + "xmlCodecName", null).get();
}
@Override
public boolean isRateLimiterEnabled() {
return rateLimiterEnabled.get();
}
@Override
public boolean isRateLimiterThrottleStandardClients() {
return rateLimiterThrottleStandardClients.get();
}
@Override
public Set<String> getRateLimiterPrivilegedClients() {
return rateLimiterPrivilegedClients.get();
}
@Override
public int getRateLimiterBurstSize() {
return rateLimiterBurstSize.get();
}
@Override
public int getRateLimiterRegistryFetchAverageRate() {
return rateLimiterRegistryFetchAverageRate.get();
}
@Override
public int getRateLimiterFullFetchAverageRate() {
return rateLimiterFullFetchAverageRate.get();
}
@Override
public String getListAutoScalingGroupsRoleName() {
return listAutoScalingGroupsRoleName.get();
}
@Override
public int getRoute53BindRebindRetries() {
return configInstance.getIntProperty(
namespace + "route53BindRebindRetries", 3).get();
}
@Override
public int getRoute53BindingRetryIntervalMs() {
return configInstance.getIntProperty(
namespace + "route53BindRebindRetryIntervalMs", (5 * 60 * 1000))
.get();
}
@Override
public long getRoute53DomainTTL() {
return configInstance.getLongProperty(
namespace + "route53DomainTTL", 30l)
.get();
}
@Override
public AwsBindingStrategy getBindingStrategy() {
return AwsBindingStrategy.valueOf(configInstance.getStringProperty(namespace + "awsBindingStrategy", AwsBindingStrategy.EIP.name()).get().toUpperCase());
}
@Override
public String getExperimental(String name) {
return configInstance.getStringProperty(namespace + "experimental." + name, null).get();
}
@Override
public int getHealthStatusMinNumberOfAvailablePeers() {
return configInstance.getIntProperty(
namespace + "minAvailableInstancesForPeerReplication", -1).get();
}
@Override
public int getInitialCapacityOfResponseCache() {
return configInstance.getIntProperty(namespace + "initialCapacityOfResponseCache", 1000).get();
}
}
| LCB14/eureka | eureka-core/src/main/java/com/netflix/eureka/DefaultEurekaServerConfig.java | 6,624 | /*
* (non-Javadoc)
*
* @see
* com.netflix.eureka.EurekaServerConfig#getExpectedClientRenewalIntervalSeconds()
*/ | block_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.eureka;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.DynamicStringSetProperty;
import com.netflix.eureka.aws.AwsBindingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* A default implementation of eureka server configuration as required by
* {@link EurekaServerConfig}.
*
* <p>
* The information required for configuring eureka server is provided in a
* configuration file.The configuration file is searched for in the classpath
* with the name specified by the property <em>eureka.server.props</em> and with
* the suffix <em>.properties</em>. If the property is not specified,
* <em>eureka-server.properties</em> is assumed as the default.The properties
* that are looked up uses the <em>namespace</em> passed on to this class.
* </p>
*
* <p>
* If the <em>eureka.environment</em> property is specified, additionally
* <em>eureka-server-<eureka.environment>.properties</em> is loaded in addition
* to <em>eureka-server.properties</em>.
* </p>
*
* @author Karthik Ranganathan
*
*/
@Singleton
public class DefaultEurekaServerConfig implements EurekaServerConfig {
private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment";
private static final String TEST = "test";
private static final String EUREKA_ENVIRONMENT = "eureka.environment";
private static final Logger logger = LoggerFactory
.getLogger(DefaultEurekaServerConfig.class);
private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory
.getInstance();
private static final DynamicStringProperty EUREKA_PROPS_FILE = DynamicPropertyFactory
.getInstance().getStringProperty("eureka.server.props",
"eureka-server");
private static final int TIME_TO_WAIT_FOR_REPLICATION = 30000;
private String namespace = "eureka.";
// These counters are checked for each HTTP request. Instantiating them per request like for the other
// properties would be too costly.
private final DynamicStringSetProperty rateLimiterPrivilegedClients =
new DynamicStringSetProperty(namespace + "rateLimiter.privilegedClients", Collections.<String>emptySet());
private final DynamicBooleanProperty rateLimiterEnabled = configInstance.getBooleanProperty(namespace + "rateLimiter.enabled", false);
private final DynamicBooleanProperty rateLimiterThrottleStandardClients = configInstance.getBooleanProperty(namespace + "rateLimiter.throttleStandardClients", false);
private final DynamicIntProperty rateLimiterBurstSize = configInstance.getIntProperty(namespace + "rateLimiter.burstSize", 10);
private final DynamicIntProperty rateLimiterRegistryFetchAverageRate = configInstance.getIntProperty(namespace + "rateLimiter.registryFetchAverageRate", 500);
private final DynamicIntProperty rateLimiterFullFetchAverageRate = configInstance.getIntProperty(namespace + "rateLimiter.fullFetchAverageRate", 100);
private final DynamicStringProperty listAutoScalingGroupsRoleName =
configInstance.getStringProperty(namespace + "listAutoScalingGroupsRoleName", "ListAutoScalingGroups");
private final DynamicStringProperty myUrl = configInstance.getStringProperty(namespace + "myUrl", null);
public DefaultEurekaServerConfig() {
init();
}
public DefaultEurekaServerConfig(String namespace) {
this.namespace = namespace;
init();
}
private void init() {
String env = ConfigurationManager.getConfigInstance().getString(
EUREKA_ENVIRONMENT, TEST);
ConfigurationManager.getConfigInstance().setProperty(
ARCHAIUS_DEPLOYMENT_ENVIRONMENT, env);
String eurekaPropsFile = EUREKA_PROPS_FILE.get();
try {
// ConfigurationManager
// .loadPropertiesFromResources(eurekaPropsFile);
ConfigurationManager
.loadCascadedPropertiesFromResources(eurekaPropsFile);
} catch (IOException e) {
logger.warn(
"Cannot find the properties specified : {}. This may be okay if there are other environment "
+ "specific properties or the configuration is installed with a different mechanism.",
eurekaPropsFile);
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getAWSAccessId()
*/
@Override
public String getAWSAccessId() {
String aWSAccessId = configInstance.getStringProperty(
namespace + "awsAccessId", null).get();
if (null != aWSAccessId) {
return aWSAccessId.trim();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getAWSAccessId()
*/
@Override
public String getAWSSecretKey() {
String aWSSecretKey = configInstance.getStringProperty(
namespace + "awsSecretKey", null).get();
if (null != aWSSecretKey) {
return aWSSecretKey.trim();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindRebindRetries()
*/
@Override
public int getEIPBindRebindRetries() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetries", 3).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindingRetryInterval()
*/
@Override
public int getEIPBindingRetryIntervalMsWhenUnbound() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetryIntervalMsWhenUnbound", (1 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindingRetryInterval()
*/
@Override
public int getEIPBindingRetryIntervalMs() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetryIntervalMs", (5 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#shouldEnableSelfPreservation()
*/
@Override
public boolean shouldEnableSelfPreservation() {
return configInstance.getBooleanProperty(
namespace + "enableSelfPreservation", true).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.eureka.EurekaServerConfig#getPeerEurekaNodesUpdateInterval()
*/
@Override
public int getPeerEurekaNodesUpdateIntervalMs() {
return configInstance
.getIntProperty(namespace + "peerEurekaNodesUpdateIntervalMs",
(10 * 60 * 1000)).get();
}
@Override
public int getRenewalThresholdUpdateIntervalMs() {
return configInstance.getIntProperty(
namespace + "renewalThresholdUpdateIntervalMs",
(15 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
<SUF>*/
@Override
public int getExpectedClientRenewalIntervalSeconds() {
final int configured = configInstance.getIntProperty(
namespace + "expectedClientRenewalIntervalSeconds",
30).get();
return configured > 0 ? configured : 30;
}
@Override
public double getRenewalPercentThreshold() {
return configInstance.getDoubleProperty(
namespace + "renewalPercentThreshold", 0.85).get();
}
@Override
public boolean shouldEnableReplicatedRequestCompression() {
return configInstance.getBooleanProperty(
namespace + "enableReplicatedRequestCompression", false).get();
}
@Override
public int getNumberOfReplicationRetries() {
return configInstance.getIntProperty(
namespace + "numberOfReplicationRetries", 5).get();
}
@Override
public int getPeerEurekaStatusRefreshTimeIntervalMs() {
return configInstance.getIntProperty(
namespace + "peerEurekaStatusRefreshTimeIntervalMs",
(30 * 1000)).get();
}
@Override
public int getWaitTimeInMsWhenSyncEmpty() {
return configInstance.getIntProperty(
namespace + "waitTimeInMsWhenSyncEmpty", (1000 * 60 * 5)).get();
}
@Override
public int getPeerNodeConnectTimeoutMs() {
return configInstance.getIntProperty(
namespace + "peerNodeConnectTimeoutMs", 1000).get();
}
@Override
public int getPeerNodeReadTimeoutMs() {
return configInstance.getIntProperty(
namespace + "peerNodeReadTimeoutMs", 5000).get();
}
@Override
public int getPeerNodeTotalConnections() {
return configInstance.getIntProperty(
namespace + "peerNodeTotalConnections", 1000).get();
}
@Override
public int getPeerNodeTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + "peerNodeTotalConnectionsPerHost", 500).get();
}
@Override
public int getPeerNodeConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + "peerNodeConnectionIdleTimeoutSeconds", 30).get();
}
@Override
public long getRetentionTimeInMSInDeltaQueue() {
return configInstance.getLongProperty(
namespace + "retentionTimeInMSInDeltaQueue", (3 * 60 * 1000))
.get();
}
@Override
public long getDeltaRetentionTimerIntervalInMs() {
return configInstance.getLongProperty(
namespace + "deltaRetentionTimerIntervalInMs", (30 * 1000))
.get();
}
@Override
public long getEvictionIntervalTimerInMs() {
return configInstance.getLongProperty(
namespace + "evictionIntervalTimerInMs", (60 * 1000)).get();
}
@Override
public boolean shouldUseAwsAsgApi() {
return configInstance.getBooleanProperty(namespace + "shouldUseAwsAsgApi", true).get();
}
@Override
public int getASGQueryTimeoutMs() {
return configInstance.getIntProperty(namespace + "asgQueryTimeoutMs",
300).get();
}
@Override
public long getASGUpdateIntervalMs() {
return configInstance.getIntProperty(namespace + "asgUpdateIntervalMs",
(5 * 60 * 1000)).get();
}
@Override
public long getASGCacheExpiryTimeoutMs() {
return configInstance.getIntProperty(namespace + "asgCacheExpiryTimeoutMs",
(10 * 60 * 1000)).get(); // defaults to longer than the asg update interval
}
@Override
public long getResponseCacheAutoExpirationInSeconds() {
return configInstance.getIntProperty(
namespace + "responseCacheAutoExpirationInSeconds", 180).get();
}
@Override
public long getResponseCacheUpdateIntervalMs() {
return configInstance.getIntProperty(
namespace + "responseCacheUpdateIntervalMs", (30 * 1000)).get();
}
@Override
public boolean shouldUseReadOnlyResponseCache() {
return configInstance.getBooleanProperty(
namespace + "shouldUseReadOnlyResponseCache", true).get();
}
@Override
public boolean shouldDisableDelta() {
return configInstance.getBooleanProperty(namespace + "disableDelta",
false).get();
}
@Override
public long getMaxIdleThreadInMinutesAgeForStatusReplication() {
return configInstance
.getLongProperty(
namespace + "maxIdleThreadAgeInMinutesForStatusReplication",
10).get();
}
@Override
public int getMinThreadsForStatusReplication() {
return configInstance.getIntProperty(
namespace + "minThreadsForStatusReplication", 1).get();
}
@Override
public int getMaxThreadsForStatusReplication() {
return configInstance.getIntProperty(
namespace + "maxThreadsForStatusReplication", 1).get();
}
@Override
public int getMaxElementsInStatusReplicationPool() {
return configInstance.getIntProperty(
namespace + "maxElementsInStatusReplicationPool", 10000).get();
}
@Override
public boolean shouldSyncWhenTimestampDiffers() {
return configInstance.getBooleanProperty(
namespace + "syncWhenTimestampDiffers", true).get();
}
@Override
public int getRegistrySyncRetries() {
return configInstance.getIntProperty(
namespace + "numberRegistrySyncRetries", 5).get();
}
@Override
public long getRegistrySyncRetryWaitMs() {
return configInstance.getIntProperty(
namespace + "registrySyncRetryWaitMs", 30 * 1000).get();
}
@Override
public int getMaxElementsInPeerReplicationPool() {
return configInstance.getIntProperty(
namespace + "maxElementsInPeerReplicationPool", 10000).get();
}
@Override
public long getMaxIdleThreadAgeInMinutesForPeerReplication() {
return configInstance.getIntProperty(
namespace + "maxIdleThreadAgeInMinutesForPeerReplication", 15)
.get();
}
@Override
public int getMinThreadsForPeerReplication() {
return configInstance.getIntProperty(
namespace + "minThreadsForPeerReplication", 5).get();
}
@Override
public int getMaxThreadsForPeerReplication() {
return configInstance.getIntProperty(
namespace + "maxThreadsForPeerReplication", 20).get();
}
@Override
public int getMaxTimeForReplication() {
return configInstance.getIntProperty(
namespace + "maxTimeForReplication",
TIME_TO_WAIT_FOR_REPLICATION).get();
}
@Override
public boolean shouldPrimeAwsReplicaConnections() {
return configInstance.getBooleanProperty(
namespace + "primeAwsReplicaConnections", true).get();
}
@Override
public boolean shouldDisableDeltaForRemoteRegions() {
return configInstance.getBooleanProperty(
namespace + "disableDeltaForRemoteRegions", false).get();
}
@Override
public int getRemoteRegionConnectTimeoutMs() {
return configInstance.getIntProperty(
namespace + "remoteRegionConnectTimeoutMs", 2000).get();
}
@Override
public int getRemoteRegionReadTimeoutMs() {
return configInstance.getIntProperty(
namespace + "remoteRegionReadTimeoutMs", 5000).get();
}
@Override
public int getRemoteRegionTotalConnections() {
return configInstance.getIntProperty(
namespace + "remoteRegionTotalConnections", 1000).get();
}
@Override
public int getRemoteRegionTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + "remoteRegionTotalConnectionsPerHost", 500).get();
}
@Override
public int getRemoteRegionConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + "remoteRegionConnectionIdleTimeoutSeconds", 30)
.get();
}
@Override
public boolean shouldGZipContentFromRemoteRegion() {
return configInstance.getBooleanProperty(
namespace + "remoteRegion.gzipContent", true).get();
}
/**
* Expects a property with name: [eureka-namespace].remoteRegionUrlsWithName and a value being a comma separated
* list of region name & remote url pairs, separated with a ";". <br/>
* So, if you wish to specify two regions with name region1 & region2, the property value will be:
<PRE>
eureka.remoteRegionUrlsWithName=region1;http://region1host/eureka/v2,region2;http://region2host/eureka/v2
</PRE>
* The above property will result in the following map:
<PRE>
region1->"http://region1host/eureka/v2"
region2->"http://region2host/eureka/v2"
</PRE>
* @return A map of region name to remote region URL parsed from the property specified above. If there is no
* property available, then an empty map is returned.
*/
@Override
public Map<String, String> getRemoteRegionUrlsWithName() {
String propName = namespace + "remoteRegionUrlsWithName";
String remoteRegionUrlWithNameString = configInstance.getStringProperty(propName, null).get();
if (null == remoteRegionUrlWithNameString) {
return Collections.emptyMap();
}
String[] remoteRegionUrlWithNamePairs = remoteRegionUrlWithNameString.split(",");
Map<String, String> toReturn = new HashMap<String, String>(remoteRegionUrlWithNamePairs.length);
final String pairSplitChar = ";";
for (String remoteRegionUrlWithNamePair : remoteRegionUrlWithNamePairs) {
String[] pairSplit = remoteRegionUrlWithNamePair.split(pairSplitChar);
if (pairSplit.length < 2) {
logger.error("Error reading eureka remote region urls from property {}. "
+ "Invalid entry {} for remote region url. The entry must contain region name and url "
+ "separated by a {}. Ignoring this entry.",
propName, remoteRegionUrlWithNamePair, pairSplitChar);
} else {
String regionName = pairSplit[0];
String regionUrl = pairSplit[1];
if (pairSplit.length > 2) {
StringBuilder regionUrlAssembler = new StringBuilder();
for (int i = 1; i < pairSplit.length; i++) {
if (regionUrlAssembler.length() != 0) {
regionUrlAssembler.append(pairSplitChar);
}
regionUrlAssembler.append(pairSplit[i]);
}
regionUrl = regionUrlAssembler.toString();
}
toReturn.put(regionName, regionUrl);
}
}
return toReturn;
}
@Override
public String[] getRemoteRegionUrls() {
String remoteRegionUrlString = configInstance.getStringProperty(
namespace + "remoteRegionUrls", null).get();
String[] remoteRegionUrl = null;
if (remoteRegionUrlString != null) {
remoteRegionUrl = remoteRegionUrlString.split(",");
}
return remoteRegionUrl;
}
@Nullable
@Override
public Set<String> getRemoteRegionAppWhitelist(@Nullable String regionName) {
if (null == regionName) {
regionName = "global";
} else {
regionName = regionName.trim().toLowerCase();
}
DynamicStringProperty appWhiteListProp =
configInstance.getStringProperty(namespace + "remoteRegion." + regionName + ".appWhiteList", null);
if (null == appWhiteListProp || null == appWhiteListProp.get()) {
return null;
} else {
String appWhiteListStr = appWhiteListProp.get();
String[] whitelistEntries = appWhiteListStr.split(",");
return new HashSet<String>(Arrays.asList(whitelistEntries));
}
}
@Override
public int getRemoteRegionRegistryFetchInterval() {
return configInstance.getIntProperty(
namespace + "remoteRegion.registryFetchIntervalInSeconds", 30)
.get();
}
@Override
public int getRemoteRegionFetchThreadPoolSize() {
return configInstance.getIntProperty(
namespace + "remoteRegion.fetchThreadPoolSize", 20)
.get();
}
@Override
public String getRemoteRegionTrustStore() {
return configInstance.getStringProperty(
namespace + "remoteRegion.trustStoreFileName", "").get();
}
@Override
public String getRemoteRegionTrustStorePassword() {
return configInstance.getStringProperty(
namespace + "remoteRegion.trustStorePassword", "changeit")
.get();
}
@Override
public boolean disableTransparentFallbackToOtherRegion() {
return configInstance.getBooleanProperty(namespace + "remoteRegion.disable.transparent.fallback", false).get();
}
@Override
public boolean shouldBatchReplication() {
return configInstance.getBooleanProperty(namespace + "shouldBatchReplication", false).get();
}
@Override
public String getMyUrl() {
return myUrl.get();
}
@Override
public boolean shouldLogIdentityHeaders() {
return configInstance.getBooleanProperty(namespace + "auth.shouldLogIdentityHeaders", true).get();
}
@Override
public String getJsonCodecName() {
return configInstance.getStringProperty(
namespace + "jsonCodecName", null).get();
}
@Override
public String getXmlCodecName() {
return configInstance.getStringProperty(
namespace + "xmlCodecName", null).get();
}
@Override
public boolean isRateLimiterEnabled() {
return rateLimiterEnabled.get();
}
@Override
public boolean isRateLimiterThrottleStandardClients() {
return rateLimiterThrottleStandardClients.get();
}
@Override
public Set<String> getRateLimiterPrivilegedClients() {
return rateLimiterPrivilegedClients.get();
}
@Override
public int getRateLimiterBurstSize() {
return rateLimiterBurstSize.get();
}
@Override
public int getRateLimiterRegistryFetchAverageRate() {
return rateLimiterRegistryFetchAverageRate.get();
}
@Override
public int getRateLimiterFullFetchAverageRate() {
return rateLimiterFullFetchAverageRate.get();
}
@Override
public String getListAutoScalingGroupsRoleName() {
return listAutoScalingGroupsRoleName.get();
}
@Override
public int getRoute53BindRebindRetries() {
return configInstance.getIntProperty(
namespace + "route53BindRebindRetries", 3).get();
}
@Override
public int getRoute53BindingRetryIntervalMs() {
return configInstance.getIntProperty(
namespace + "route53BindRebindRetryIntervalMs", (5 * 60 * 1000))
.get();
}
@Override
public long getRoute53DomainTTL() {
return configInstance.getLongProperty(
namespace + "route53DomainTTL", 30l)
.get();
}
@Override
public AwsBindingStrategy getBindingStrategy() {
return AwsBindingStrategy.valueOf(configInstance.getStringProperty(namespace + "awsBindingStrategy", AwsBindingStrategy.EIP.name()).get().toUpperCase());
}
@Override
public String getExperimental(String name) {
return configInstance.getStringProperty(namespace + "experimental." + name, null).get();
}
@Override
public int getHealthStatusMinNumberOfAvailablePeers() {
return configInstance.getIntProperty(
namespace + "minAvailableInstancesForPeerReplication", -1).get();
}
@Override
public int getInitialCapacityOfResponseCache() {
return configInstance.getIntProperty(namespace + "initialCapacityOfResponseCache", 1000).get();
}
}
|
10050_0 | package wepresent.wepresent;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import wepresent.wepresent.mappers.AsyncTaskReport;
import wepresent.wepresent.mappers.Mapper;
import wepresent.wepresent.mappers.SlidesMapper;
public class SlidesActivity extends Fragment implements AsyncTaskReport {
private LinearLayout linLayout;
private SlidesMapper slidesMapper;
private int sessionId;
private ArrayList<Map<String, String>> slides;
SharedPreferences sharedpreferences;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_slides, container, false);
}
public void done(Mapper.MapperSort mapper) {
if(slidesMapper.isSlidesSuccesful()) {
slides = slidesMapper.getSlides();
displaySlides();
} else { //TODO hij kan ze heus wel vinden, hij moet gewoon niet zo zeuren
if (sessionId>0) {
Toast.makeText(getActivity().getApplicationContext(), "Slides not available for this session", Toast.LENGTH_LONG).show();
}
}
}
public void onResume(){
sharedpreferences = this.getActivity().getSharedPreferences("appData", Context.MODE_PRIVATE);
super.onResume();
//TODO zorg dat je al gecachede plaatjes displayed inplaats van alles gewoon weer opnieuw op te halen
if(slidesMapper == null) {
Bundle b = getArguments();
sessionId = sharedpreferences.getInt("SessionID", 0);
slidesMapper = new SlidesMapper(this);
slidesMapper.start(sessionId);
}
}
private void displaySlides() {
//TODO Misschien niet het geheugen van de telefoon gebruiken om de slides te cachen, but then again; I DON'T CARE
// Get where the images should go
linLayout = (LinearLayout) getView().findViewById(R.id.linearLayout);
// For each slide
for ( Map<String, String> slide : slides ) {
//Create the image loader
ImageLoader.ImageCache imageCache = new BitmapLruCache();
ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(getView().getContext()), imageCache);
//Set the image
NetworkImageView image = new NetworkImageView(getView().getContext());
image.setImageUrl(slide.get("SlideURL"), imageLoader);
image.setId(Integer.parseInt(slide.get("id")));
image.setAdjustViewBounds(true);
// Add it to the view
linLayout.addView(image);
// Add a listener
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Go to the slideView activity
Intent intent = new Intent(getActivity(), SlideViewActivity.class);
intent.putExtra("SlideID", v.getId());
startActivity(intent);
}
});
}
}
public static Bundle createBundle(String s) {
Bundle bundle = new Bundle();
//bundle.putString( EXTRA_TITLE, title );
return bundle;
}
}
| LHagendoorn/wePresent | Project/app/src/main/java/wepresent/wepresent/SlidesActivity.java | 1,190 | //TODO hij kan ze heus wel vinden, hij moet gewoon niet zo zeuren | line_comment | nl | package wepresent.wepresent;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import wepresent.wepresent.mappers.AsyncTaskReport;
import wepresent.wepresent.mappers.Mapper;
import wepresent.wepresent.mappers.SlidesMapper;
public class SlidesActivity extends Fragment implements AsyncTaskReport {
private LinearLayout linLayout;
private SlidesMapper slidesMapper;
private int sessionId;
private ArrayList<Map<String, String>> slides;
SharedPreferences sharedpreferences;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_slides, container, false);
}
public void done(Mapper.MapperSort mapper) {
if(slidesMapper.isSlidesSuccesful()) {
slides = slidesMapper.getSlides();
displaySlides();
} else { //TODO hij<SUF>
if (sessionId>0) {
Toast.makeText(getActivity().getApplicationContext(), "Slides not available for this session", Toast.LENGTH_LONG).show();
}
}
}
public void onResume(){
sharedpreferences = this.getActivity().getSharedPreferences("appData", Context.MODE_PRIVATE);
super.onResume();
//TODO zorg dat je al gecachede plaatjes displayed inplaats van alles gewoon weer opnieuw op te halen
if(slidesMapper == null) {
Bundle b = getArguments();
sessionId = sharedpreferences.getInt("SessionID", 0);
slidesMapper = new SlidesMapper(this);
slidesMapper.start(sessionId);
}
}
private void displaySlides() {
//TODO Misschien niet het geheugen van de telefoon gebruiken om de slides te cachen, but then again; I DON'T CARE
// Get where the images should go
linLayout = (LinearLayout) getView().findViewById(R.id.linearLayout);
// For each slide
for ( Map<String, String> slide : slides ) {
//Create the image loader
ImageLoader.ImageCache imageCache = new BitmapLruCache();
ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(getView().getContext()), imageCache);
//Set the image
NetworkImageView image = new NetworkImageView(getView().getContext());
image.setImageUrl(slide.get("SlideURL"), imageLoader);
image.setId(Integer.parseInt(slide.get("id")));
image.setAdjustViewBounds(true);
// Add it to the view
linLayout.addView(image);
// Add a listener
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Go to the slideView activity
Intent intent = new Intent(getActivity(), SlideViewActivity.class);
intent.putExtra("SlideID", v.getId());
startActivity(intent);
}
});
}
}
public static Bundle createBundle(String s) {
Bundle bundle = new Bundle();
//bundle.putString( EXTRA_TITLE, title );
return bundle;
}
}
|
185423_22 | package GUI;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalTime;
import bunky.FormattedDateTableCell;
import bunky.FormattedDoubleTableCell;
import bunky.FormattedPositionTableCell;
import bunky.FormattedTimeTableCell;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.property.ListProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import model.Aktivita;
import model.DataModel;
import model.TypAktivity;
import model.Zavod;
import utils.Ctenar;
import utils.Message;
/**
* @author Lukas Runt
* @version 2.0 (2021-05-31)
*/
public class Main extends Application{
private static final String OBSAH_TITULKU = "Semestralni prace - Lukas Runt - A20B0226P";
private static TableView<Aktivita> tabulka;
private TableView<Zavod> tabulkaZ;
private static TreeView<String> treeView;
private GuiManual okno = new GuiManual();
private GuiAktivita zobrazeniAktivity = new GuiAktivita();
public static DataModel model = new DataModel();
public static Message zprava = new Message();
private Stage soubor;
private Ctenar ctenar = new Ctenar();
private Stage myStage = new Stage();
private DatePicker datumDP;
private TextField nazevTF;
private TextField umisteniTF;
private String[] zkratkyMesicu = {"led", "uno", "bre", "dub", "kve", "cvn", "cvc", "srp", "zar", "rij", "lis", "pro"};
public static Aktivita vybranaAktivita;
/**
* Inicializace po spusteni
*/
public void init() {
System.out.println("Inicializace");
model.initializeModel();
}
/**
* Pred vypnutim aplikace se ulozi data
*/
@Override
public void stop() throws Exception {
System.out.println("Saving data");
model.saveData();
super.stop();
}
/**
* Vstupni bod programu
* @param args
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
this.myStage = primaryStage;
myStage.setTitle(OBSAH_TITULKU);
myStage.setMinHeight(400);
myStage.setMinWidth(600);
//myStage.setHeight(600);
//myStage.setWidth(1000);
myStage.setScene(getScene());
primaryStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
primaryStage.show();
primaryStage.setOnCloseRequest(e -> {Platform.exit();});
}
private Scene getScene() {
Scene scene = new Scene(getRoot());
return scene;
}
private Parent getRoot() {
BorderPane rootBorderPane = new BorderPane();
rootBorderPane.setTop(getMenu());
rootBorderPane.setCenter(getSplitPane());
rootBorderPane.setPrefSize(myStage.getWidth() - 15, myStage.getHeight() - 38);
return rootBorderPane;
}
private Node getSplitPane() {
SplitPane splitPane = new SplitPane();
splitPane.getItems().addAll(getTreeView(), getTabulka());
//splitPane.setPadding(new Insets(5));
return splitPane;
}
/**
* Menubar, menu v horni casti obrazovky
* @return MenuBar
*/
private Node getMenu() {
MenuBar menu = new MenuBar();
Menu soubor = new Menu("Nova aktivita");
MenuItem manual = new MenuItem("Manualne");
manual.setOnAction(e -> {
try {
okno.showDialog();
} catch (Exception ex) {
ex.printStackTrace();
}
});
MenuItem file = new MenuItem("Souborem");
file.setOnAction(e -> nactiNovaData(e));
soubor.getItems().addAll(manual, file);
Label homeLB = new Label("Home");
homeLB.setOnMouseClicked(e -> prepniNaDomObrazovku(e));
Menu home = new Menu("", homeLB);
Label statistikyLB = new Label("Statistiky");
statistikyLB.setOnMouseClicked(e -> prepniNaStatistiky(e));
Menu statistiky = new Menu("", statistikyLB);
Label zavodLB = new Label("Zavody");
zavodLB.setOnMouseClicked(e -> prepniNaZavod(e));
Menu zavod = new Menu("", zavodLB);
menu.getMenus().addAll(soubor, home, statistiky, zavod);
return menu;
}
/**
* Prepinani na statistiky
* @param e kliknuti na menuItem - statistiky
*/
private void prepniNaStatistiky(MouseEvent e) {
myStage.setScene(statisikyScene());
myStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
}
/**
* Prepinani na domovskou obrazovku
* @param e kliknuti na menuItem - home
*/
private void prepniNaDomObrazovku(MouseEvent e) {
myStage.setScene(getScene());
myStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
}
/**
* Prarinani na tabulku se zavody
* @param e kliknuti na menuItem - zavody
*/
private void prepniNaZavod(MouseEvent e) {
myStage.setScene(zavodScene());
myStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
}
/**
* Scena statistik
* @return scena satatistik
*/
private Scene statisikyScene() {
Scene scene = new Scene(getStatistikyRoot());
return scene;
}
/**
* Scena se zavody
* @return scena zavodu
*/
private Scene zavodScene() {
Scene scene = new Scene(getZavodRoot());
return scene;
}
/**
* BorderPane statistik
* @return borderPane statistik
*/
private Parent getStatistikyRoot() {
BorderPane rootBorderPane = new BorderPane();
rootBorderPane.setTop(getMenu());
rootBorderPane.setCenter(getGraf());
rootBorderPane.setPrefSize(myStage.getWidth() - 15, myStage.getHeight() - 38);
return rootBorderPane;
}
/**
* Metoda se stara o vytvoreni grafu
* @return graf
*/
private Node getGraf() {
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Mesice");
yAxis.setLabel("Kilometry");
LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);
lineChart.setTitle("Najete kilometry v jednotlivych mesicich");
String[] roky = model.getYears();
for(int i = 0; i < roky.length; i++) {
final int p = i;
Series<String, Number> series = new XYChart.Series<>();
series.setName(roky[i]);
for(int j = 0; j < 12; j++) {
final int m = j + 1;
Double sum = model.aktivity.stream().filter(a -> a.getDatum().getYear() == Integer.parseInt(roky[p]))
.filter(a -> a.getDatum().getMonthValue() == m)
.map(a -> a.getVzdalenost())
.reduce(0.0, Double::sum);
series.getData().add(new XYChart.Data<String, Number>(zkratkyMesicu[j], sum));
}
lineChart.getData().add(series);
}
return lineChart;
}
/**
* BorderPane zavodu
* @return borderPane zavodu
*/
private Parent getZavodRoot() {
BorderPane rootBorderPane = new BorderPane();
rootBorderPane.setTop(getMenu());
rootBorderPane.setCenter(getTabulka2());
rootBorderPane.setBottom(getOvladani());
rootBorderPane.setPrefSize(myStage.getWidth() - 15, myStage.getHeight() - 38);
return rootBorderPane;
}
/**
* Ovladani zavoud, pridavani zavodu
* @return ovladani
*/
private Node getOvladani() {
GridPane ovladani = new GridPane();
ovladani.setHgap(10);
ovladani.setVgap(10);
VBox nazev = new VBox();
Label nazevLB = new Label("Nazev");
nazevTF = new TextField();
nazev.getChildren().addAll(nazevLB, nazevTF);
ovladani.add(nazev, 2, 1);
VBox datum = new VBox();
Label datumLB = new Label("Datum");
datumDP = new DatePicker();
datum.getChildren().addAll(datumLB, datumDP);
ovladani.add(datum, 1, 1);
VBox umisteni = new VBox();
Label umisteniLB = new Label("Umisteni");
umisteniTF = new TextField();
umisteni.getChildren().addAll(umisteniLB, umisteniTF);
ovladani.add(umisteni, 3, 1);
Button pridejBT = new Button("Pridej");
pridejBT.setOnAction(e -> pridejZavod(e));
pridejBT.setPrefWidth(100);
ovladani.add(pridejBT, 4, 1);
ovladani.setPadding(new Insets(5));
ovladani.setAlignment(Pos.CENTER);
return ovladani;
}
/**
* Pridani dzavodu do tabulky
* @param e kliknuti na tlacitko pridej
*/
private void pridejZavod(ActionEvent e) {
if(datumDP.getValue() == null || nazevTF.getText() == null || umisteniTF.getText() == null) {
zprava.showErrorDialog("Nejsou vyplneny vsechny udaje pro vytvoreni!");
return;
}
if(umisteniTF.getText().matches(".*[a-z].*") || umisteniTF.getText().matches(".*[A-Z].*") || umisteniTF.getText().matches(".*\\p{Punct}.*")){
if(umisteniTF.getText().contains("-")) {} else {
zprava.showErrorDialog("Umisteni musi byt cislo!\nPro prazdne pole = 0\nPro DNF = -1\nPro DSQ = -2");
return;
}
}
model.zavody.add(new Zavod(datumDP.getValue(), nazevTF.getText(), Integer.parseInt(umisteniTF.getText().trim())));
datumDP.setValue(null);
nazevTF.setText(null);
umisteniTF.setText(null);
}
/**
* Tabulka zavodu
* @return tabulka
*/
@SuppressWarnings("unchecked")
private Node getTabulka2() {
tabulkaZ = new TableView<Zavod>(model.zavody.get());
tabulkaZ.setEditable(true);
//tabulkaZ.setPadding(new Insets(5));
TableColumn<Zavod, String> nazevColumn = new TableColumn<>("Nazev");
nazevColumn.setCellValueFactory(new PropertyValueFactory<>("nazev"));
nazevColumn.setCellFactory(TextFieldTableCell.forTableColumn());
TableColumn<Zavod, LocalDate> datumColumn = new TableColumn<>("Datum");
datumColumn.setCellValueFactory(new PropertyValueFactory<>("datum"));
datumColumn.setCellFactory(cellData -> new FormattedDateTableCell<>());
TableColumn<Zavod, Integer> umisteniColumn = new TableColumn<>("Umisteni");
umisteniColumn.setCellValueFactory(new PropertyValueFactory<>("umisteni"));
umisteniColumn.setCellFactory(cellData -> new FormattedPositionTableCell<>(".") );
tabulkaZ.getColumns().addAll(datumColumn, nazevColumn, umisteniColumn);
tabulkaZ.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
ContextMenu cm = new ContextMenu();
MenuItem smazMI = new MenuItem("Smaz");
cm.getItems().add(smazMI);
smazMI.setOnAction(e -> smaz(e, model.zavody, 2));
tabulkaZ.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
if(event.getButton() == MouseButton.SECONDARY) {
cm.show(tabulkaZ, event.getScreenX(), event.getScreenY());
}
};
});
return tabulkaZ;
}
/**
* Metoda pro nacitani souboru tcx
* @param e event
*/
private void nactiNovaData(ActionEvent e) {
FileChooser chooser = new FileChooser();
chooser.getExtensionFilters().add(new ExtensionFilter("Name","*.tcx"));
File file = chooser.showOpenDialog(soubor);
if (file != null) {
ctenar.read(file);
}
else {
//zprava.showErrorDialog("Soubor je null");
System.out.println("Nebyl vybran soubor.");
}
}
/**
* Strom pro fitrovani aktivit podle mesice nebo roku
* @return TreeView
*/
private Node getTreeView() {
treeView = new TreeView<String>();
treeView.setMaxWidth(150);
treeView.setPrefWidth(100);
createStartItems();
treeView.getSelectionModel().selectedItemProperty().addListener(this::updateFields);
model.aktivity.addListener(this::updateFields);
return treeView;
}
/**
* Metoda vyfiltruje jenom takove aktivity ktere patri to prislusneho roku a mesice
* @param observable
*/
private void updateFields(Observable observable) {
String item = " ";
if (treeView.getSelectionModel().getSelectedItem() != null) {
item = treeView.getSelectionModel().getSelectedItem().getValue().toString();
}
model.zobrazeni.clear();
if(item.equals("All") || item.equals(" ")) {
model.aktivity.stream().forEach(a -> model.zobrazeni.add(a));
} else if(item.matches(".*[0-9].*")){
String zbytecnaPromnenaHehe = item;
model.aktivity.stream().filter(a -> (a.getDatum().getYear() + "").equals(zbytecnaPromnenaHehe))
.forEach(a -> model.zobrazeni.add(a));
} else {
int mesic = getMesic(item);
String parent = treeView.getSelectionModel().getSelectedItem().getParent().getValue().toString();
model.aktivity.stream().filter(a -> a.getDatum().getYear() == Integer.parseInt(parent))
.filter(a -> a.getDatum().getMonthValue() == mesic)
.forEach(a -> model.zobrazeni.add(a));
}
}
/**
* Prirazeni cisla mesici
* @param mesic mesic v roce
* @return cislo mesice
*/
private static int getMesic(String mesic) {
switch (mesic) {
case "Leden":
return 1;
case "Unor":
return 2;
case "Brezen":
return 3;
case "Duben":
return 4;
case "Kveten":
return 5;
case "Cerven":
return 6;
case "Cervenec":
return 7;
case "Srpen":
return 8;
case "Zari":
return 9;
case "Rijen":
return 10;
case "Listopad":
return 11;
case "Prosinec":
return 12;
}
return 0;
}
/**
* Vytvareni polozek v TreeView
*/
public static void createStartItems() {
TreeItem<String> root = new TreeItem<>("All");
String[] roky = model.getYears();
boolean[][] mesice = model.getMesice();
for(int i = roky.length - 1; i >= 0; i--) {
TreeItem<String> datum = new TreeItem<>(roky[i]);
if(mesice[i][0]) {
TreeItem<String> leden = new TreeItem<>("Leden");
datum.getChildren().add(leden);
}
if(mesice[i][1]) {
TreeItem<String> unor = new TreeItem<>("Unor");
datum.getChildren().add(unor);
}
if(mesice[i][2]) {
TreeItem<String> brezen = new TreeItem<>("Brezen");
datum.getChildren().add(brezen);
}
if(mesice[i][3]) {
TreeItem<String> duben = new TreeItem<>("Duben");
datum.getChildren().add(duben);
}
if(mesice[i][4]) {
TreeItem<String> kveten = new TreeItem<>("Kveten");
datum.getChildren().add(kveten);
}
if(mesice[i][5]) {
TreeItem<String> cerven = new TreeItem<>("Cerven");
datum.getChildren().add(cerven);
}
if(mesice[i][6]) {
TreeItem<String> cervenec = new TreeItem<>("Cervenec");
datum.getChildren().add(cervenec);
}
if(mesice[i][7]) {
TreeItem<String> srpen = new TreeItem<>("Srpen");
datum.getChildren().add(srpen);
}
if(mesice[i][8]) {
TreeItem<String> zari = new TreeItem<>("Zari");
datum.getChildren().add(zari);
}
if(mesice[i][9]) {
TreeItem<String> rijen = new TreeItem<>("Rijen");
datum.getChildren().add(rijen);
}
if(mesice[i][10]) {
TreeItem<String> listopad = new TreeItem<>("Listopad");
datum.getChildren().add(listopad);
}
if(mesice[i][11]) {
TreeItem<String> prosinec = new TreeItem<>("Prosinec");
datum.getChildren().add(prosinec);
}
//datum.getChildren().addAll(leden, unor, brezen, duben, kveten, cerven, cervenec, srpen, zari, rijen, listopad, prosinec);
root.getChildren().add(datum);
}
treeView.setRoot(root);
}
/**
* Tabulka aktivit, editovatelna, filtrovatelna
* @return tabulka aktivit na uvodni obrazovce
*/
@SuppressWarnings("unchecked")
private Node getTabulka() {
tabulka = new TableView<Aktivita>(model.zobrazeni.get());
tabulka.setEditable(true);
TableColumn<Aktivita, LocalDate> datumColumn = new TableColumn<>("Datum");
datumColumn.setCellValueFactory(new PropertyValueFactory<>("datum"));
datumColumn.setCellFactory(cellData -> new FormattedDateTableCell<>());
TableColumn<Aktivita, String> nazevColumn = new TableColumn<>("Nazev");
nazevColumn.setCellValueFactory(new PropertyValueFactory<Aktivita, String>("nazev"));
nazevColumn.setCellFactory(TextFieldTableCell.forTableColumn());
TableColumn<Aktivita, Double> vzdalenostColumn = new TableColumn<>("Vzdalenost");
vzdalenostColumn.setCellValueFactory(new PropertyValueFactory<>("vzdalenost"));
vzdalenostColumn.setCellFactory(cellData -> new FormattedDoubleTableCell<>(" km"));
TableColumn<Aktivita, TypAktivity> typColumn = new TableColumn<>("Typ aktivity");
typColumn.setCellValueFactory(new PropertyValueFactory<>("typ"));
typColumn.setCellFactory(ComboBoxTableCell.forTableColumn(TypAktivity.values()));
TableColumn<Aktivita, LocalTime> casColumn = new TableColumn<>("Cas");
casColumn.setCellValueFactory(new PropertyValueFactory<>("cas"));
casColumn.setCellFactory(cellData -> new FormattedTimeTableCell<>());
//---------------------------prumerna-rychlost-----------------------------------------
TableColumn<Aktivita, Double> rychlostColumn = new TableColumn<>("Prum. rychlost");
rychlostColumn.setCellValueFactory(cellData -> cellData.getValue().prumernaRychlostProperty());
rychlostColumn.setCellFactory(cellData -> new FormattedDoubleTableCell<>(" km/h"));
rychlostColumn.setEditable(false);
ContextMenu cm = new ContextMenu();
MenuItem zobrazMI = new MenuItem("Zobraz");
MenuItem smazMI = new MenuItem("Smaz");
MenuItem pridejMI = new MenuItem("Pridej");
cm.getItems().add(zobrazMI);
zobrazMI.setOnAction(e -> zobraz(e));
cm.getItems().add(smazMI);
smazMI.setOnAction(e -> smaz(e, model.aktivity, 1));
cm.getItems().add(pridejMI);
pridejMI.setOnAction(e -> {
try {
okno.showDialog();
} catch (Exception e1) {
System.out.println("Doslo k chybe pri otevirani okna pro manualni vstup");
}
});
tabulka.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
if(event.getButton() == MouseButton.SECONDARY) {
cm.show(tabulka, event.getScreenX(), event.getScreenY());
}
};
});
tabulka.getColumns().addAll(datumColumn, typColumn, casColumn, vzdalenostColumn, rychlostColumn);
tabulka.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return tabulka;
}
/**
* Zaborazeni okna aktivity
* @param e kliknuti na MenuItem zobraz
*/
private void zobraz(ActionEvent e) {
int index = tabulka.getSelectionModel().getSelectedIndex();
if(index < 0) {
zprava.showErrorDialog("Neni vybran prvek k zobrazeni.");
}
else {
vybranaAktivita = tabulka.getSelectionModel().getSelectedItem();
try {
zobrazeniAktivity.showDialog();
} catch (Exception ex) {
System.out.println("nepodarilo se otevrit okno s aktivitou" + ex.getMessage());
}
}
}
/**
* Smazani zadane polozky
* @param e kliknuti an MeniItem
* @param list list ve kterem se bude mazat polozka
* @param volba volba jestli je mazani v tabulce se zavody
*/
private void smaz(ActionEvent e, ListProperty<?> list, int volba) {
int index;
if(volba == 1) {
index = tabulka.getSelectionModel().getSelectedIndex();
} else {
index = tabulkaZ.getSelectionModel().getSelectedIndex();
}
if(index < 0) {
zprava.showErrorDialog("Neni vybran prvek ke smazani!");
}
else {
if(zprava.showVyberDialog("Opravdu chcete smazat tuto aktivitu?")){
if(volba == 1) {
Aktivita vybrana = tabulka.getSelectionModel().getSelectedItem();
try {
list.stream().filter(a -> a == vybrana).forEach(a -> list.remove(a));
}
catch(Exception ex) {
createStartItems();
}
} else {
list.remove(index);
}
}
tabulka.getSelectionModel().clearSelection();
}
}
public static TableView<Aktivita> getTabulkares(){
return tabulka;
}
}
| LRunt/UUR-Semestralni-prace | src/GUI/Main.java | 7,651 | //datum.getChildren().addAll(leden, unor, brezen, duben, kveten, cerven, cervenec, srpen, zari, rijen, listopad, prosinec); | line_comment | nl | package GUI;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalTime;
import bunky.FormattedDateTableCell;
import bunky.FormattedDoubleTableCell;
import bunky.FormattedPositionTableCell;
import bunky.FormattedTimeTableCell;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.property.ListProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import model.Aktivita;
import model.DataModel;
import model.TypAktivity;
import model.Zavod;
import utils.Ctenar;
import utils.Message;
/**
* @author Lukas Runt
* @version 2.0 (2021-05-31)
*/
public class Main extends Application{
private static final String OBSAH_TITULKU = "Semestralni prace - Lukas Runt - A20B0226P";
private static TableView<Aktivita> tabulka;
private TableView<Zavod> tabulkaZ;
private static TreeView<String> treeView;
private GuiManual okno = new GuiManual();
private GuiAktivita zobrazeniAktivity = new GuiAktivita();
public static DataModel model = new DataModel();
public static Message zprava = new Message();
private Stage soubor;
private Ctenar ctenar = new Ctenar();
private Stage myStage = new Stage();
private DatePicker datumDP;
private TextField nazevTF;
private TextField umisteniTF;
private String[] zkratkyMesicu = {"led", "uno", "bre", "dub", "kve", "cvn", "cvc", "srp", "zar", "rij", "lis", "pro"};
public static Aktivita vybranaAktivita;
/**
* Inicializace po spusteni
*/
public void init() {
System.out.println("Inicializace");
model.initializeModel();
}
/**
* Pred vypnutim aplikace se ulozi data
*/
@Override
public void stop() throws Exception {
System.out.println("Saving data");
model.saveData();
super.stop();
}
/**
* Vstupni bod programu
* @param args
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
this.myStage = primaryStage;
myStage.setTitle(OBSAH_TITULKU);
myStage.setMinHeight(400);
myStage.setMinWidth(600);
//myStage.setHeight(600);
//myStage.setWidth(1000);
myStage.setScene(getScene());
primaryStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
primaryStage.show();
primaryStage.setOnCloseRequest(e -> {Platform.exit();});
}
private Scene getScene() {
Scene scene = new Scene(getRoot());
return scene;
}
private Parent getRoot() {
BorderPane rootBorderPane = new BorderPane();
rootBorderPane.setTop(getMenu());
rootBorderPane.setCenter(getSplitPane());
rootBorderPane.setPrefSize(myStage.getWidth() - 15, myStage.getHeight() - 38);
return rootBorderPane;
}
private Node getSplitPane() {
SplitPane splitPane = new SplitPane();
splitPane.getItems().addAll(getTreeView(), getTabulka());
//splitPane.setPadding(new Insets(5));
return splitPane;
}
/**
* Menubar, menu v horni casti obrazovky
* @return MenuBar
*/
private Node getMenu() {
MenuBar menu = new MenuBar();
Menu soubor = new Menu("Nova aktivita");
MenuItem manual = new MenuItem("Manualne");
manual.setOnAction(e -> {
try {
okno.showDialog();
} catch (Exception ex) {
ex.printStackTrace();
}
});
MenuItem file = new MenuItem("Souborem");
file.setOnAction(e -> nactiNovaData(e));
soubor.getItems().addAll(manual, file);
Label homeLB = new Label("Home");
homeLB.setOnMouseClicked(e -> prepniNaDomObrazovku(e));
Menu home = new Menu("", homeLB);
Label statistikyLB = new Label("Statistiky");
statistikyLB.setOnMouseClicked(e -> prepniNaStatistiky(e));
Menu statistiky = new Menu("", statistikyLB);
Label zavodLB = new Label("Zavody");
zavodLB.setOnMouseClicked(e -> prepniNaZavod(e));
Menu zavod = new Menu("", zavodLB);
menu.getMenus().addAll(soubor, home, statistiky, zavod);
return menu;
}
/**
* Prepinani na statistiky
* @param e kliknuti na menuItem - statistiky
*/
private void prepniNaStatistiky(MouseEvent e) {
myStage.setScene(statisikyScene());
myStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
}
/**
* Prepinani na domovskou obrazovku
* @param e kliknuti na menuItem - home
*/
private void prepniNaDomObrazovku(MouseEvent e) {
myStage.setScene(getScene());
myStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
}
/**
* Prarinani na tabulku se zavody
* @param e kliknuti na menuItem - zavody
*/
private void prepniNaZavod(MouseEvent e) {
myStage.setScene(zavodScene());
myStage.getScene().getStylesheets().add("/vzhled/basicStyle.css");
}
/**
* Scena statistik
* @return scena satatistik
*/
private Scene statisikyScene() {
Scene scene = new Scene(getStatistikyRoot());
return scene;
}
/**
* Scena se zavody
* @return scena zavodu
*/
private Scene zavodScene() {
Scene scene = new Scene(getZavodRoot());
return scene;
}
/**
* BorderPane statistik
* @return borderPane statistik
*/
private Parent getStatistikyRoot() {
BorderPane rootBorderPane = new BorderPane();
rootBorderPane.setTop(getMenu());
rootBorderPane.setCenter(getGraf());
rootBorderPane.setPrefSize(myStage.getWidth() - 15, myStage.getHeight() - 38);
return rootBorderPane;
}
/**
* Metoda se stara o vytvoreni grafu
* @return graf
*/
private Node getGraf() {
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Mesice");
yAxis.setLabel("Kilometry");
LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);
lineChart.setTitle("Najete kilometry v jednotlivych mesicich");
String[] roky = model.getYears();
for(int i = 0; i < roky.length; i++) {
final int p = i;
Series<String, Number> series = new XYChart.Series<>();
series.setName(roky[i]);
for(int j = 0; j < 12; j++) {
final int m = j + 1;
Double sum = model.aktivity.stream().filter(a -> a.getDatum().getYear() == Integer.parseInt(roky[p]))
.filter(a -> a.getDatum().getMonthValue() == m)
.map(a -> a.getVzdalenost())
.reduce(0.0, Double::sum);
series.getData().add(new XYChart.Data<String, Number>(zkratkyMesicu[j], sum));
}
lineChart.getData().add(series);
}
return lineChart;
}
/**
* BorderPane zavodu
* @return borderPane zavodu
*/
private Parent getZavodRoot() {
BorderPane rootBorderPane = new BorderPane();
rootBorderPane.setTop(getMenu());
rootBorderPane.setCenter(getTabulka2());
rootBorderPane.setBottom(getOvladani());
rootBorderPane.setPrefSize(myStage.getWidth() - 15, myStage.getHeight() - 38);
return rootBorderPane;
}
/**
* Ovladani zavoud, pridavani zavodu
* @return ovladani
*/
private Node getOvladani() {
GridPane ovladani = new GridPane();
ovladani.setHgap(10);
ovladani.setVgap(10);
VBox nazev = new VBox();
Label nazevLB = new Label("Nazev");
nazevTF = new TextField();
nazev.getChildren().addAll(nazevLB, nazevTF);
ovladani.add(nazev, 2, 1);
VBox datum = new VBox();
Label datumLB = new Label("Datum");
datumDP = new DatePicker();
datum.getChildren().addAll(datumLB, datumDP);
ovladani.add(datum, 1, 1);
VBox umisteni = new VBox();
Label umisteniLB = new Label("Umisteni");
umisteniTF = new TextField();
umisteni.getChildren().addAll(umisteniLB, umisteniTF);
ovladani.add(umisteni, 3, 1);
Button pridejBT = new Button("Pridej");
pridejBT.setOnAction(e -> pridejZavod(e));
pridejBT.setPrefWidth(100);
ovladani.add(pridejBT, 4, 1);
ovladani.setPadding(new Insets(5));
ovladani.setAlignment(Pos.CENTER);
return ovladani;
}
/**
* Pridani dzavodu do tabulky
* @param e kliknuti na tlacitko pridej
*/
private void pridejZavod(ActionEvent e) {
if(datumDP.getValue() == null || nazevTF.getText() == null || umisteniTF.getText() == null) {
zprava.showErrorDialog("Nejsou vyplneny vsechny udaje pro vytvoreni!");
return;
}
if(umisteniTF.getText().matches(".*[a-z].*") || umisteniTF.getText().matches(".*[A-Z].*") || umisteniTF.getText().matches(".*\\p{Punct}.*")){
if(umisteniTF.getText().contains("-")) {} else {
zprava.showErrorDialog("Umisteni musi byt cislo!\nPro prazdne pole = 0\nPro DNF = -1\nPro DSQ = -2");
return;
}
}
model.zavody.add(new Zavod(datumDP.getValue(), nazevTF.getText(), Integer.parseInt(umisteniTF.getText().trim())));
datumDP.setValue(null);
nazevTF.setText(null);
umisteniTF.setText(null);
}
/**
* Tabulka zavodu
* @return tabulka
*/
@SuppressWarnings("unchecked")
private Node getTabulka2() {
tabulkaZ = new TableView<Zavod>(model.zavody.get());
tabulkaZ.setEditable(true);
//tabulkaZ.setPadding(new Insets(5));
TableColumn<Zavod, String> nazevColumn = new TableColumn<>("Nazev");
nazevColumn.setCellValueFactory(new PropertyValueFactory<>("nazev"));
nazevColumn.setCellFactory(TextFieldTableCell.forTableColumn());
TableColumn<Zavod, LocalDate> datumColumn = new TableColumn<>("Datum");
datumColumn.setCellValueFactory(new PropertyValueFactory<>("datum"));
datumColumn.setCellFactory(cellData -> new FormattedDateTableCell<>());
TableColumn<Zavod, Integer> umisteniColumn = new TableColumn<>("Umisteni");
umisteniColumn.setCellValueFactory(new PropertyValueFactory<>("umisteni"));
umisteniColumn.setCellFactory(cellData -> new FormattedPositionTableCell<>(".") );
tabulkaZ.getColumns().addAll(datumColumn, nazevColumn, umisteniColumn);
tabulkaZ.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
ContextMenu cm = new ContextMenu();
MenuItem smazMI = new MenuItem("Smaz");
cm.getItems().add(smazMI);
smazMI.setOnAction(e -> smaz(e, model.zavody, 2));
tabulkaZ.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
if(event.getButton() == MouseButton.SECONDARY) {
cm.show(tabulkaZ, event.getScreenX(), event.getScreenY());
}
};
});
return tabulkaZ;
}
/**
* Metoda pro nacitani souboru tcx
* @param e event
*/
private void nactiNovaData(ActionEvent e) {
FileChooser chooser = new FileChooser();
chooser.getExtensionFilters().add(new ExtensionFilter("Name","*.tcx"));
File file = chooser.showOpenDialog(soubor);
if (file != null) {
ctenar.read(file);
}
else {
//zprava.showErrorDialog("Soubor je null");
System.out.println("Nebyl vybran soubor.");
}
}
/**
* Strom pro fitrovani aktivit podle mesice nebo roku
* @return TreeView
*/
private Node getTreeView() {
treeView = new TreeView<String>();
treeView.setMaxWidth(150);
treeView.setPrefWidth(100);
createStartItems();
treeView.getSelectionModel().selectedItemProperty().addListener(this::updateFields);
model.aktivity.addListener(this::updateFields);
return treeView;
}
/**
* Metoda vyfiltruje jenom takove aktivity ktere patri to prislusneho roku a mesice
* @param observable
*/
private void updateFields(Observable observable) {
String item = " ";
if (treeView.getSelectionModel().getSelectedItem() != null) {
item = treeView.getSelectionModel().getSelectedItem().getValue().toString();
}
model.zobrazeni.clear();
if(item.equals("All") || item.equals(" ")) {
model.aktivity.stream().forEach(a -> model.zobrazeni.add(a));
} else if(item.matches(".*[0-9].*")){
String zbytecnaPromnenaHehe = item;
model.aktivity.stream().filter(a -> (a.getDatum().getYear() + "").equals(zbytecnaPromnenaHehe))
.forEach(a -> model.zobrazeni.add(a));
} else {
int mesic = getMesic(item);
String parent = treeView.getSelectionModel().getSelectedItem().getParent().getValue().toString();
model.aktivity.stream().filter(a -> a.getDatum().getYear() == Integer.parseInt(parent))
.filter(a -> a.getDatum().getMonthValue() == mesic)
.forEach(a -> model.zobrazeni.add(a));
}
}
/**
* Prirazeni cisla mesici
* @param mesic mesic v roce
* @return cislo mesice
*/
private static int getMesic(String mesic) {
switch (mesic) {
case "Leden":
return 1;
case "Unor":
return 2;
case "Brezen":
return 3;
case "Duben":
return 4;
case "Kveten":
return 5;
case "Cerven":
return 6;
case "Cervenec":
return 7;
case "Srpen":
return 8;
case "Zari":
return 9;
case "Rijen":
return 10;
case "Listopad":
return 11;
case "Prosinec":
return 12;
}
return 0;
}
/**
* Vytvareni polozek v TreeView
*/
public static void createStartItems() {
TreeItem<String> root = new TreeItem<>("All");
String[] roky = model.getYears();
boolean[][] mesice = model.getMesice();
for(int i = roky.length - 1; i >= 0; i--) {
TreeItem<String> datum = new TreeItem<>(roky[i]);
if(mesice[i][0]) {
TreeItem<String> leden = new TreeItem<>("Leden");
datum.getChildren().add(leden);
}
if(mesice[i][1]) {
TreeItem<String> unor = new TreeItem<>("Unor");
datum.getChildren().add(unor);
}
if(mesice[i][2]) {
TreeItem<String> brezen = new TreeItem<>("Brezen");
datum.getChildren().add(brezen);
}
if(mesice[i][3]) {
TreeItem<String> duben = new TreeItem<>("Duben");
datum.getChildren().add(duben);
}
if(mesice[i][4]) {
TreeItem<String> kveten = new TreeItem<>("Kveten");
datum.getChildren().add(kveten);
}
if(mesice[i][5]) {
TreeItem<String> cerven = new TreeItem<>("Cerven");
datum.getChildren().add(cerven);
}
if(mesice[i][6]) {
TreeItem<String> cervenec = new TreeItem<>("Cervenec");
datum.getChildren().add(cervenec);
}
if(mesice[i][7]) {
TreeItem<String> srpen = new TreeItem<>("Srpen");
datum.getChildren().add(srpen);
}
if(mesice[i][8]) {
TreeItem<String> zari = new TreeItem<>("Zari");
datum.getChildren().add(zari);
}
if(mesice[i][9]) {
TreeItem<String> rijen = new TreeItem<>("Rijen");
datum.getChildren().add(rijen);
}
if(mesice[i][10]) {
TreeItem<String> listopad = new TreeItem<>("Listopad");
datum.getChildren().add(listopad);
}
if(mesice[i][11]) {
TreeItem<String> prosinec = new TreeItem<>("Prosinec");
datum.getChildren().add(prosinec);
}
//datum.getChildren().addAll(leden, unor,<SUF>
root.getChildren().add(datum);
}
treeView.setRoot(root);
}
/**
* Tabulka aktivit, editovatelna, filtrovatelna
* @return tabulka aktivit na uvodni obrazovce
*/
@SuppressWarnings("unchecked")
private Node getTabulka() {
tabulka = new TableView<Aktivita>(model.zobrazeni.get());
tabulka.setEditable(true);
TableColumn<Aktivita, LocalDate> datumColumn = new TableColumn<>("Datum");
datumColumn.setCellValueFactory(new PropertyValueFactory<>("datum"));
datumColumn.setCellFactory(cellData -> new FormattedDateTableCell<>());
TableColumn<Aktivita, String> nazevColumn = new TableColumn<>("Nazev");
nazevColumn.setCellValueFactory(new PropertyValueFactory<Aktivita, String>("nazev"));
nazevColumn.setCellFactory(TextFieldTableCell.forTableColumn());
TableColumn<Aktivita, Double> vzdalenostColumn = new TableColumn<>("Vzdalenost");
vzdalenostColumn.setCellValueFactory(new PropertyValueFactory<>("vzdalenost"));
vzdalenostColumn.setCellFactory(cellData -> new FormattedDoubleTableCell<>(" km"));
TableColumn<Aktivita, TypAktivity> typColumn = new TableColumn<>("Typ aktivity");
typColumn.setCellValueFactory(new PropertyValueFactory<>("typ"));
typColumn.setCellFactory(ComboBoxTableCell.forTableColumn(TypAktivity.values()));
TableColumn<Aktivita, LocalTime> casColumn = new TableColumn<>("Cas");
casColumn.setCellValueFactory(new PropertyValueFactory<>("cas"));
casColumn.setCellFactory(cellData -> new FormattedTimeTableCell<>());
//---------------------------prumerna-rychlost-----------------------------------------
TableColumn<Aktivita, Double> rychlostColumn = new TableColumn<>("Prum. rychlost");
rychlostColumn.setCellValueFactory(cellData -> cellData.getValue().prumernaRychlostProperty());
rychlostColumn.setCellFactory(cellData -> new FormattedDoubleTableCell<>(" km/h"));
rychlostColumn.setEditable(false);
ContextMenu cm = new ContextMenu();
MenuItem zobrazMI = new MenuItem("Zobraz");
MenuItem smazMI = new MenuItem("Smaz");
MenuItem pridejMI = new MenuItem("Pridej");
cm.getItems().add(zobrazMI);
zobrazMI.setOnAction(e -> zobraz(e));
cm.getItems().add(smazMI);
smazMI.setOnAction(e -> smaz(e, model.aktivity, 1));
cm.getItems().add(pridejMI);
pridejMI.setOnAction(e -> {
try {
okno.showDialog();
} catch (Exception e1) {
System.out.println("Doslo k chybe pri otevirani okna pro manualni vstup");
}
});
tabulka.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
if(event.getButton() == MouseButton.SECONDARY) {
cm.show(tabulka, event.getScreenX(), event.getScreenY());
}
};
});
tabulka.getColumns().addAll(datumColumn, typColumn, casColumn, vzdalenostColumn, rychlostColumn);
tabulka.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return tabulka;
}
/**
* Zaborazeni okna aktivity
* @param e kliknuti na MenuItem zobraz
*/
private void zobraz(ActionEvent e) {
int index = tabulka.getSelectionModel().getSelectedIndex();
if(index < 0) {
zprava.showErrorDialog("Neni vybran prvek k zobrazeni.");
}
else {
vybranaAktivita = tabulka.getSelectionModel().getSelectedItem();
try {
zobrazeniAktivity.showDialog();
} catch (Exception ex) {
System.out.println("nepodarilo se otevrit okno s aktivitou" + ex.getMessage());
}
}
}
/**
* Smazani zadane polozky
* @param e kliknuti an MeniItem
* @param list list ve kterem se bude mazat polozka
* @param volba volba jestli je mazani v tabulce se zavody
*/
private void smaz(ActionEvent e, ListProperty<?> list, int volba) {
int index;
if(volba == 1) {
index = tabulka.getSelectionModel().getSelectedIndex();
} else {
index = tabulkaZ.getSelectionModel().getSelectedIndex();
}
if(index < 0) {
zprava.showErrorDialog("Neni vybran prvek ke smazani!");
}
else {
if(zprava.showVyberDialog("Opravdu chcete smazat tuto aktivitu?")){
if(volba == 1) {
Aktivita vybrana = tabulka.getSelectionModel().getSelectedItem();
try {
list.stream().filter(a -> a == vybrana).forEach(a -> list.remove(a));
}
catch(Exception ex) {
createStartItems();
}
} else {
list.remove(index);
}
}
tabulka.getSelectionModel().clearSelection();
}
}
public static TableView<Aktivita> getTabulkares(){
return tabulka;
}
}
|
193078_13 | /*
* Copyright (c) 2004-2023 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* Modified European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the Modified EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://github.com/LSTS/neptus/blob/develop/LICENSE.md
* and http://ec.europa.eu/idabc/eupl.html.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author:
* Apr 29, 2005
*/
package pt.lsts.neptus.renderer2d;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import pt.lsts.neptus.types.coord.LocationType;
/**
* @author zecarlos
*/
@LayerPriority(priority=100)
public class MapLegend implements Renderer2DPainter {
private double zoomValue = 1;
private LocationType centerLocation = new LocationType();
private double mapRotation = 0;
private int width = 70, height = 80;
private NumberFormat nf;
public MapLegend() {
nf = DecimalFormat.getInstance(Locale.US);
nf.setGroupingUsed(false);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
}
public void paint(Graphics2D g, StateRenderer2D renderer) {
int screenWidth = renderer.getWidth();
int screenHeight = renderer.getHeight();
zoomValue = renderer.getZoom();
centerLocation = renderer.getCenter();
setMapRotation(renderer.getRotation());
paint(g, screenWidth, screenHeight, false);
}
public void paint(Graphics2D g, int screenWidth, int screenHeight, boolean simple) {
AffineTransform identity = g.getTransform();
int cornerX = screenWidth - 10 - width;
int cornerY = 10;
double realWidth = (width - 20) / getZoomValue();
String units = "m";
if (realWidth < 1) {
units = "cm";
realWidth *= 100;
}
else {
if (realWidth > 1000) {
units = "Km";
realWidth /= 1000;
}
}
String text = nf.format(realWidth) +" "+units;
// Reinicializa a transformação
//g.setTransform(new AffineTransform());
if (!simple) {
// Desenha o rectangulo de fundo da legenda
g.setColor(new Color(255,255,255,100));
g.fillRect(cornerX, cornerY, width, height);
g.setColor(Color.BLACK);
g.drawRect(cornerX, cornerY, width, height);
}
else
g.setColor(Color.BLACK);
// Desenha a linha de orientacao da legenda: |-----|
g.drawLine(cornerX + 10, cornerY + 10, cornerX + width - 10, cornerY + 10);
g.drawLine(cornerX + 10, cornerY + 5, cornerX + 10, cornerY + 15);
g.drawLine(cornerX + width - 10, cornerY + 5, cornerX + width - 10, cornerY + 15);
// Desenha uma String com a distancia ocupada pela linha desenhada anteriormente
Rectangle2D stringBounds = g.getFontMetrics().getStringBounds(text, g);
// Se a String for maior que a legenda, escala-a
if (stringBounds.getWidth() >= width - 20) {
g.translate(cornerX + 10, cornerY + 25);
g.scale((double)(width-20)/(double)stringBounds.getWidth(),
(double)(width-20)/(double)stringBounds.getWidth());
g.drawString(text, 0,0);
// depois de desenhada a string, volta à escala normal
g.setTransform(identity);
}
else {
// Senão desenha a String centrada no rectangulo da legenda
int advance = (int) (width - 20 - stringBounds.getWidth()) / 2;
g.drawString(text, advance + cornerX + 10, cornerY + 25);
}
if (!simple) {
g.translate(cornerX + width / 2, cornerY + (height)/ 2 + 13);
g.rotate(-getMapRotation());
GeneralPath gp = new GeneralPath();
gp.moveTo(0, -15);
gp.lineTo(-8, 10);
gp.lineTo(0, 7);
gp.lineTo(8, 10);
gp.closePath();
g.setColor(new Color(0,0,0,200));
g.fill(gp);
if (getMapRotation() == 0)
g.setColor(Color.BLACK);
else
g.setColor(Color.red.darker());
g.draw(gp);
/*
g.drawLine(0,-15,0,15);
g.drawLine(-15,0,15,0);
*/
Rectangle2D nBounds = g.getFontMetrics().getStringBounds("N", g);
g.drawString("N", -(int)nBounds.getWidth()/2, -16);
}
}
/**
* @return Returns the centerLocation.
*/
public LocationType getCenterLocation() {
return centerLocation;
}
/**
* @param centerLocation The centerLocation to set.
*/
public void setCenterLocation(LocationType centerLocation) {
this.centerLocation = centerLocation;
}
/**
* @return Returns the zoomValue.
*/
public double getZoomValue() {
return zoomValue;
}
/**
* @param zoomValue The zoomValue to set.
*/
public void setZoomValue(double zoomValue) {
this.zoomValue = zoomValue;
}
public double getMapRotation() {
return mapRotation;
}
public void setMapRotation(double mapRotation) {
this.mapRotation = mapRotation;
}
}
| LSTS/neptus | src/java/pt/lsts/neptus/renderer2d/MapLegend.java | 2,030 | /**
* @param zoomValue The zoomValue to set.
*/ | block_comment | nl | /*
* Copyright (c) 2004-2023 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* Modified European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the Modified EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://github.com/LSTS/neptus/blob/develop/LICENSE.md
* and http://ec.europa.eu/idabc/eupl.html.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author:
* Apr 29, 2005
*/
package pt.lsts.neptus.renderer2d;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import pt.lsts.neptus.types.coord.LocationType;
/**
* @author zecarlos
*/
@LayerPriority(priority=100)
public class MapLegend implements Renderer2DPainter {
private double zoomValue = 1;
private LocationType centerLocation = new LocationType();
private double mapRotation = 0;
private int width = 70, height = 80;
private NumberFormat nf;
public MapLegend() {
nf = DecimalFormat.getInstance(Locale.US);
nf.setGroupingUsed(false);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
}
public void paint(Graphics2D g, StateRenderer2D renderer) {
int screenWidth = renderer.getWidth();
int screenHeight = renderer.getHeight();
zoomValue = renderer.getZoom();
centerLocation = renderer.getCenter();
setMapRotation(renderer.getRotation());
paint(g, screenWidth, screenHeight, false);
}
public void paint(Graphics2D g, int screenWidth, int screenHeight, boolean simple) {
AffineTransform identity = g.getTransform();
int cornerX = screenWidth - 10 - width;
int cornerY = 10;
double realWidth = (width - 20) / getZoomValue();
String units = "m";
if (realWidth < 1) {
units = "cm";
realWidth *= 100;
}
else {
if (realWidth > 1000) {
units = "Km";
realWidth /= 1000;
}
}
String text = nf.format(realWidth) +" "+units;
// Reinicializa a transformação
//g.setTransform(new AffineTransform());
if (!simple) {
// Desenha o rectangulo de fundo da legenda
g.setColor(new Color(255,255,255,100));
g.fillRect(cornerX, cornerY, width, height);
g.setColor(Color.BLACK);
g.drawRect(cornerX, cornerY, width, height);
}
else
g.setColor(Color.BLACK);
// Desenha a linha de orientacao da legenda: |-----|
g.drawLine(cornerX + 10, cornerY + 10, cornerX + width - 10, cornerY + 10);
g.drawLine(cornerX + 10, cornerY + 5, cornerX + 10, cornerY + 15);
g.drawLine(cornerX + width - 10, cornerY + 5, cornerX + width - 10, cornerY + 15);
// Desenha uma String com a distancia ocupada pela linha desenhada anteriormente
Rectangle2D stringBounds = g.getFontMetrics().getStringBounds(text, g);
// Se a String for maior que a legenda, escala-a
if (stringBounds.getWidth() >= width - 20) {
g.translate(cornerX + 10, cornerY + 25);
g.scale((double)(width-20)/(double)stringBounds.getWidth(),
(double)(width-20)/(double)stringBounds.getWidth());
g.drawString(text, 0,0);
// depois de desenhada a string, volta à escala normal
g.setTransform(identity);
}
else {
// Senão desenha a String centrada no rectangulo da legenda
int advance = (int) (width - 20 - stringBounds.getWidth()) / 2;
g.drawString(text, advance + cornerX + 10, cornerY + 25);
}
if (!simple) {
g.translate(cornerX + width / 2, cornerY + (height)/ 2 + 13);
g.rotate(-getMapRotation());
GeneralPath gp = new GeneralPath();
gp.moveTo(0, -15);
gp.lineTo(-8, 10);
gp.lineTo(0, 7);
gp.lineTo(8, 10);
gp.closePath();
g.setColor(new Color(0,0,0,200));
g.fill(gp);
if (getMapRotation() == 0)
g.setColor(Color.BLACK);
else
g.setColor(Color.red.darker());
g.draw(gp);
/*
g.drawLine(0,-15,0,15);
g.drawLine(-15,0,15,0);
*/
Rectangle2D nBounds = g.getFontMetrics().getStringBounds("N", g);
g.drawString("N", -(int)nBounds.getWidth()/2, -16);
}
}
/**
* @return Returns the centerLocation.
*/
public LocationType getCenterLocation() {
return centerLocation;
}
/**
* @param centerLocation The centerLocation to set.
*/
public void setCenterLocation(LocationType centerLocation) {
this.centerLocation = centerLocation;
}
/**
* @return Returns the zoomValue.
*/
public double getZoomValue() {
return zoomValue;
}
/**
* @param zoomValue The<SUF>*/
public void setZoomValue(double zoomValue) {
this.zoomValue = zoomValue;
}
public double getMapRotation() {
return mapRotation;
}
public void setMapRotation(double mapRotation) {
this.mapRotation = mapRotation;
}
}
|
166272_10 | package org.pmobo.packlaborategia7;
public abstract class ParteHartzailea
{
// atributuak
private String izena;
private int puntuazioa;
private int izendapenak;
private ListaParteHartzaileak izendatuenZerrenda;
// eraikitzailea
/**
*
* @param pIzena
* @param pPuntuazioa
* @param pIzendapenak
* post: ParteHartzailea klaseko objektu berri bat abiarazten da: izena pIzena, puntuazioa pPuntuazioa,
* zero izendapen, eta izendapenen zerrenda hutsik dago
*/
protected ParteHartzailea (String pIzena, int pPuntuazioa)
{
this.izena = pIzena;
this.puntuazioa = pPuntuazioa;
this.izendapenak = 0;
this.izendatuenZerrenda = new ListaParteHartzaileak();
}
// beste metodoak
/**
*
* @return parte hartzaileren izena
*/
public String getIzena()
{
return this.izena;
}
/**
*
* @return parte hartzailearen puntuazioa
*/
protected int getPuntuazioa()
{
return this.puntuazioa;
}
/**
*
* @return parte hartzailearen izendatuen zerrenda
*/
protected ListaParteHartzaileak getListaIzendatuak()
{
return this.izendatuenZerrenda;
}
/**
*
* post: parte hartzailearen izendapenak atributua zerora eraman
*/
public void zeroanJarriBereIzendapenak()
{
this.izendapenak = 0;
}
/**
*
* @return parte hartzailearen jasotako izendapenak
*/
public int jasotakoIzendapenKopurua()
{
return this.izendapenak;
}
/**
*
* @param pKantitatea
* post: parte hartzailearen jasotako izendapenei pKantitatea gehitzen zaie.
*/
public void gehituJasotakoIzendapenak (int pKantitatea)
{
this.izendapenak += pKantitatea;
}
/**
* @return Egungo parte hartzailearen izendatuen zerrendan dauden tronularien kopurua.
*/
public int izendatutakoTronularienKopurua()
{
return this.izendatuenZerrenda.tronularienKopurua();
}
/**
* @return Egungo parte hartzailearen izendatuen zerrendan dauden pretendenteen kopurua.
*/
public int izendatutakoPretendenteenKopurua()
{
return this.izendatuenZerrenda.pretendenteenKopurua();
}
/**
* @param pIzendatua
* post: Egungo parte hartzailearen izendatuen zerrendan pIzendatua gehitzen da, salbu eta izendatua dagoeneko zerrendan badago
* edo egungo parte hartzailea bada (hau da, bere burua izendatu duela).
* Bi egoera horietakoren bat gertatzen bada, pantailatik mezu bat agertuko da, eta ez da gehituko egungo parte hartzailearen izendatuen zerrendan.
*/
public void izendatu(ParteHartzailea pIzendatua)
{
if (this.izendatuenZerrenda.baDago(pIzendatua) || this.izena == pIzendatua.izena)
{
System.out.println("Ezin da partehartzailea gehitu, zerrendan dagoelako edo zu zarelako");
return;
}
this.izendatuenZerrenda.gehitu(pIzendatua);
}
/**
* post: parte hartzailearen izendatuen zerrenda errekorritzen da eta bakoitzari dagokion izendapena aplikatzen da.
*
*/
public void izendapenakAplikatu()
{
int i = 0;
this.izendatuenZerrenda.getParteHartzaileaPosizioan(i);
}
/**
* @return Parte Hartzailearen izendatuen zerrendak enuntziatuan zehaztutako arauak betetzen dituen adierazten duen boolearra.
* Metodo abstraktu bat da, ParteHartzailea klasearen azpiklase bakoitzak modu ezberdinean inplemetatzen duelako.
*/
protected abstract boolean baldintzakBeteDitu();
/**
* @param pParteHartzaileIzendatua
* post: Egoeraren arabera, pParteHartzaileIzendatuaren izendapenen kopurua 1, 2 edo 5 handituko da.
* Metodo abstraktu bat da, ParteHartzailea klasearen azpiklase bakoitzak modu ezberdinean inplemetatzen duelako.
*/
protected abstract void izendapenaAplikatu (ParteHartzailea pParteHartzaileIzendatua);
}
| LUC1A05/upv | 1.maila/2.LAUHILEKOA/PMOBO/LABOAK/PMOBO/src/org/pmobo/packlaborategia7/ParteHartzailea.java | 1,639 | /**
* post: parte hartzailearen izendatuen zerrenda errekorritzen da eta bakoitzari dagokion izendapena aplikatzen da.
*
*/ | block_comment | nl | package org.pmobo.packlaborategia7;
public abstract class ParteHartzailea
{
// atributuak
private String izena;
private int puntuazioa;
private int izendapenak;
private ListaParteHartzaileak izendatuenZerrenda;
// eraikitzailea
/**
*
* @param pIzena
* @param pPuntuazioa
* @param pIzendapenak
* post: ParteHartzailea klaseko objektu berri bat abiarazten da: izena pIzena, puntuazioa pPuntuazioa,
* zero izendapen, eta izendapenen zerrenda hutsik dago
*/
protected ParteHartzailea (String pIzena, int pPuntuazioa)
{
this.izena = pIzena;
this.puntuazioa = pPuntuazioa;
this.izendapenak = 0;
this.izendatuenZerrenda = new ListaParteHartzaileak();
}
// beste metodoak
/**
*
* @return parte hartzaileren izena
*/
public String getIzena()
{
return this.izena;
}
/**
*
* @return parte hartzailearen puntuazioa
*/
protected int getPuntuazioa()
{
return this.puntuazioa;
}
/**
*
* @return parte hartzailearen izendatuen zerrenda
*/
protected ListaParteHartzaileak getListaIzendatuak()
{
return this.izendatuenZerrenda;
}
/**
*
* post: parte hartzailearen izendapenak atributua zerora eraman
*/
public void zeroanJarriBereIzendapenak()
{
this.izendapenak = 0;
}
/**
*
* @return parte hartzailearen jasotako izendapenak
*/
public int jasotakoIzendapenKopurua()
{
return this.izendapenak;
}
/**
*
* @param pKantitatea
* post: parte hartzailearen jasotako izendapenei pKantitatea gehitzen zaie.
*/
public void gehituJasotakoIzendapenak (int pKantitatea)
{
this.izendapenak += pKantitatea;
}
/**
* @return Egungo parte hartzailearen izendatuen zerrendan dauden tronularien kopurua.
*/
public int izendatutakoTronularienKopurua()
{
return this.izendatuenZerrenda.tronularienKopurua();
}
/**
* @return Egungo parte hartzailearen izendatuen zerrendan dauden pretendenteen kopurua.
*/
public int izendatutakoPretendenteenKopurua()
{
return this.izendatuenZerrenda.pretendenteenKopurua();
}
/**
* @param pIzendatua
* post: Egungo parte hartzailearen izendatuen zerrendan pIzendatua gehitzen da, salbu eta izendatua dagoeneko zerrendan badago
* edo egungo parte hartzailea bada (hau da, bere burua izendatu duela).
* Bi egoera horietakoren bat gertatzen bada, pantailatik mezu bat agertuko da, eta ez da gehituko egungo parte hartzailearen izendatuen zerrendan.
*/
public void izendatu(ParteHartzailea pIzendatua)
{
if (this.izendatuenZerrenda.baDago(pIzendatua) || this.izena == pIzendatua.izena)
{
System.out.println("Ezin da partehartzailea gehitu, zerrendan dagoelako edo zu zarelako");
return;
}
this.izendatuenZerrenda.gehitu(pIzendatua);
}
/**
* post: parte hartzailearen<SUF>*/
public void izendapenakAplikatu()
{
int i = 0;
this.izendatuenZerrenda.getParteHartzaileaPosizioan(i);
}
/**
* @return Parte Hartzailearen izendatuen zerrendak enuntziatuan zehaztutako arauak betetzen dituen adierazten duen boolearra.
* Metodo abstraktu bat da, ParteHartzailea klasearen azpiklase bakoitzak modu ezberdinean inplemetatzen duelako.
*/
protected abstract boolean baldintzakBeteDitu();
/**
* @param pParteHartzaileIzendatua
* post: Egoeraren arabera, pParteHartzaileIzendatuaren izendapenen kopurua 1, 2 edo 5 handituko da.
* Metodo abstraktu bat da, ParteHartzailea klasearen azpiklase bakoitzak modu ezberdinean inplemetatzen duelako.
*/
protected abstract void izendapenaAplikatu (ParteHartzailea pParteHartzaileIzendatua);
}
|
140761_5 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
/**
* The {@code VK_EXT_debug_marker} extension is a device extension. It introduces concepts of object naming and tagging, for better tracking of Vulkan objects, as well as additional commands for recording annotations of named sections of a workload to aid organization and offline analysis in external tools.
*
* <h5>Examples</h5>
*
* <p><b>Example 1</b></p>
*
* <p>Associate a name with an image, for easier debugging in external tools or with validation layers that can print a friendly name when referring to objects in error messages.</p>
*
* <pre><code>
* extern VkDevice device;
* extern VkImage image;
*
* // Must call extension functions through a function pointer:
* PFN_vkDebugMarkerSetObjectNameEXT pfnDebugMarkerSetObjectNameEXT = (PFN_vkDebugMarkerSetObjectNameEXT)vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT");
*
* // Set a name on the image
* const VkDebugMarkerObjectNameInfoEXT imageNameInfo =
* {
* .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT,
* .pNext = NULL,
* .objectType = VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
* .object = (uint64_t)image,
* .pObjectName = "Brick Diffuse Texture",
* };
*
* pfnDebugMarkerSetObjectNameEXT(device, &imageNameInfo);
*
* // A subsequent error might print:
* // Image 'Brick Diffuse Texture' (0xc0dec0dedeadbeef) is used in a
* // command buffer with no memory bound to it.</code></pre>
*
* <p><b>Example 2</b></p>
*
* <p>Annotating regions of a workload with naming information so that offline analysis tools can display a more usable visualization of the commands submitted.</p>
*
* <pre><code>
* extern VkDevice device;
* extern VkCommandBuffer commandBuffer;
*
* // Must call extension functions through a function pointer:
* PFN_vkCmdDebugMarkerBeginEXT pfnCmdDebugMarkerBeginEXT = (PFN_vkCmdDebugMarkerBeginEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT");
* PFN_vkCmdDebugMarkerEndEXT pfnCmdDebugMarkerEndEXT = (PFN_vkCmdDebugMarkerEndEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT");
* PFN_vkCmdDebugMarkerInsertEXT pfnCmdDebugMarkerInsertEXT = (PFN_vkCmdDebugMarkerInsertEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT");
*
* // Describe the area being rendered
* const VkDebugMarkerMarkerInfoEXT houseMarker =
* {
* .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT,
* .pNext = NULL,
* .pMarkerName = "Brick House",
* .color = { 1.0f, 0.0f, 0.0f, 1.0f },
* };
*
* // Start an annotated group of calls under the 'Brick House' name
* pfnCmdDebugMarkerBeginEXT(commandBuffer, &houseMarker);
* {
* // A mutable structure for each part being rendered
* VkDebugMarkerMarkerInfoEXT housePartMarker =
* {
* .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT,
* .pNext = NULL,
* .pMarkerName = NULL,
* .color = { 0.0f, 0.0f, 0.0f, 0.0f },
* };
*
* // Set the name and insert the marker
* housePartMarker.pMarkerName = "Walls";
* pfnCmdDebugMarkerInsertEXT(commandBuffer, &housePartMarker);
*
* // Insert the drawcall for the walls
* vkCmdDrawIndexed(commandBuffer, 1000, 1, 0, 0, 0);
*
* // Insert a recursive region for two sets of windows
* housePartMarker.pMarkerName = "Windows";
* pfnCmdDebugMarkerBeginEXT(commandBuffer, &housePartMarker);
* {
* vkCmdDrawIndexed(commandBuffer, 75, 6, 1000, 0, 0);
* vkCmdDrawIndexed(commandBuffer, 100, 2, 1450, 0, 0);
* }
* pfnCmdDebugMarkerEndEXT(commandBuffer);
*
* housePartMarker.pMarkerName = "Front Door";
* pfnCmdDebugMarkerInsertEXT(commandBuffer, &housePartMarker);
*
* vkCmdDrawIndexed(commandBuffer, 350, 1, 1650, 0, 0);
*
* housePartMarker.pMarkerName = "Roof";
* pfnCmdDebugMarkerInsertEXT(commandBuffer, &housePartMarker);
*
* vkCmdDrawIndexed(commandBuffer, 500, 1, 2000, 0, 0);
* }
* // End the house annotation started above
* pfnCmdDebugMarkerEndEXT(commandBuffer);</code></pre>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_EXT_debug_marker}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>23</dd>
* <dt><b>Revision</b></dt>
* <dd>4</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link EXTDebugReport VK_EXT_debug_report}</dd>
* <dt><b>Deprecation State</b></dt>
* <dd><ul>
* <li><em>Promoted</em> to {@link EXTDebugUtils VK_EXT_debug_utils} extension</li>
* </ul></dd>
* <dt><b>Special Use</b></dt>
* <dd><ul>
* <li><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse">Debugging tools</a></li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Baldur Karlsson <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_debug_marker]%20@baldurk%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_debug_marker%20extension*">baldurk</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-01-31</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Baldur Karlsson</li>
* <li>Dan Ginsburg, Valve</li>
* <li>Jon Ashburn, LunarG</li>
* <li>Kyle Spagnoli, NVIDIA</li>
* </ul></dd>
* </dl>
*/
public class EXTDebugMarker {
/** The extension specification version. */
public static final int VK_EXT_DEBUG_MARKER_SPEC_VERSION = 4;
/** The extension name. */
public static final String VK_EXT_DEBUG_MARKER_EXTENSION_NAME = "VK_EXT_debug_marker";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT = 1000022000,
VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT = 1000022001,
VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT = 1000022002;
protected EXTDebugMarker() {
throw new UnsupportedOperationException();
}
// --- [ vkDebugMarkerSetObjectTagEXT ] ---
/** Unsafe version of: {@link #vkDebugMarkerSetObjectTagEXT DebugMarkerSetObjectTagEXT} */
public static int nvkDebugMarkerSetObjectTagEXT(VkDevice device, long pTagInfo) {
long __functionAddress = device.getCapabilities().vkDebugMarkerSetObjectTagEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerObjectTagInfoEXT.validate(pTagInfo);
}
return callPPI(device.address(), pTagInfo, __functionAddress);
}
/**
* Attach arbitrary data to an object.
*
* <h5>C Specification</h5>
*
* <p>In addition to setting a name for an object, debugging and validation layers may have uses for additional binary data on a per-object basis that has no other place in the Vulkan API. For example, a {@code VkShaderModule} could have additional debugging data attached to it to aid in offline shader tracing. To attach data to an object, call:</p>
*
* <pre><code>
* VkResult vkDebugMarkerSetObjectTagEXT(
* VkDevice device,
* const VkDebugMarkerObjectTagInfoEXT* pTagInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pTagInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerObjectTagInfoEXT} structure</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code pTagInfo→object} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerObjectTagInfoEXT}</p>
*
* @param device the device that created the object.
* @param pTagInfo a pointer to a {@link VkDebugMarkerObjectTagInfoEXT} structure specifying the parameters of the tag to attach to the object.
*/
@NativeType("VkResult")
public static int vkDebugMarkerSetObjectTagEXT(VkDevice device, @NativeType("VkDebugMarkerObjectTagInfoEXT const *") VkDebugMarkerObjectTagInfoEXT pTagInfo) {
return nvkDebugMarkerSetObjectTagEXT(device, pTagInfo.address());
}
// --- [ vkDebugMarkerSetObjectNameEXT ] ---
/** Unsafe version of: {@link #vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectNameEXT} */
public static int nvkDebugMarkerSetObjectNameEXT(VkDevice device, long pNameInfo) {
long __functionAddress = device.getCapabilities().vkDebugMarkerSetObjectNameEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerObjectNameInfoEXT.validate(pNameInfo);
}
return callPPI(device.address(), pNameInfo, __functionAddress);
}
/**
* Give a user-friendly name to an object.
*
* <h5>C Specification</h5>
*
* <p>An object can be given a user-friendly name by calling:</p>
*
* <pre><code>
* VkResult vkDebugMarkerSetObjectNameEXT(
* VkDevice device,
* const VkDebugMarkerObjectNameInfoEXT* pNameInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pNameInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerObjectNameInfoEXT} structure</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code pNameInfo→object} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerObjectNameInfoEXT}</p>
*
* @param device the device that created the object.
* @param pNameInfo a pointer to a {@link VkDebugMarkerObjectNameInfoEXT} structure specifying the parameters of the name to set on the object.
*/
@NativeType("VkResult")
public static int vkDebugMarkerSetObjectNameEXT(VkDevice device, @NativeType("VkDebugMarkerObjectNameInfoEXT const *") VkDebugMarkerObjectNameInfoEXT pNameInfo) {
return nvkDebugMarkerSetObjectNameEXT(device, pNameInfo.address());
}
// --- [ vkCmdDebugMarkerBeginEXT ] ---
/** Unsafe version of: {@link #vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT} */
public static void nvkCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, long pMarkerInfo) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDebugMarkerBeginEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerMarkerInfoEXT.validate(pMarkerInfo);
}
callPPV(commandBuffer.address(), pMarkerInfo, __functionAddress);
}
/**
* Open a command buffer marker region.
*
* <h5>C Specification</h5>
*
* <p>A marker region can be opened by calling:</p>
*
* <pre><code>
* void vkCmdDebugMarkerBeginEXT(
* VkCommandBuffer commandBuffer,
* const VkDebugMarkerMarkerInfoEXT* pMarkerInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code pMarkerInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerMarkerInfoEXT} structure</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, or compute operations</li>
* <li>This command <b>must</b> only be called outside of a video coding scope</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Outside</td><td>Graphics Compute</td><td>Action</td></tr></tbody>
* </table>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerMarkerInfoEXT}</p>
*
* @param commandBuffer the command buffer into which the command is recorded.
* @param pMarkerInfo a pointer to a {@link VkDebugMarkerMarkerInfoEXT} structure specifying the parameters of the marker region to open.
*/
public static void vkCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, @NativeType("VkDebugMarkerMarkerInfoEXT const *") VkDebugMarkerMarkerInfoEXT pMarkerInfo) {
nvkCmdDebugMarkerBeginEXT(commandBuffer, pMarkerInfo.address());
}
// --- [ vkCmdDebugMarkerEndEXT ] ---
/**
* Close a command buffer marker region.
*
* <h5>C Specification</h5>
*
* <p>A marker region can be closed by calling:</p>
*
* <pre><code>
* void vkCmdDebugMarkerEndEXT(
* VkCommandBuffer commandBuffer);</code></pre>
*
* <h5>Description</h5>
*
* <p>An application <b>may</b> open a marker region in one command buffer and close it in another, or otherwise split marker regions across multiple command buffers or multiple queue submissions. When viewed from the linear series of submissions to a single queue, the calls to {@code vkCmdDebugMarkerBeginEXT} and {@code vkCmdDebugMarkerEndEXT} <b>must</b> be matched and balanced.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>There <b>must</b> be an outstanding {@link #vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT} command prior to the {@code vkCmdDebugMarkerEndEXT} on the queue that {@code commandBuffer} is submitted to</li>
* <li>If {@code commandBuffer} is a secondary command buffer, there <b>must</b> be an outstanding {@link #vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT} command recorded to {@code commandBuffer} that has not previously been ended by a call to {@link #vkCmdDebugMarkerEndEXT CmdDebugMarkerEndEXT}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, or compute operations</li>
* <li>This command <b>must</b> only be called outside of a video coding scope</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Outside</td><td>Graphics Compute</td><td>Action</td></tr></tbody>
* </table>
*
* @param commandBuffer the command buffer into which the command is recorded.
*/
public static void vkCmdDebugMarkerEndEXT(VkCommandBuffer commandBuffer) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDebugMarkerEndEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), __functionAddress);
}
// --- [ vkCmdDebugMarkerInsertEXT ] ---
/** Unsafe version of: {@link #vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsertEXT} */
public static void nvkCmdDebugMarkerInsertEXT(VkCommandBuffer commandBuffer, long pMarkerInfo) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDebugMarkerInsertEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerMarkerInfoEXT.validate(pMarkerInfo);
}
callPPV(commandBuffer.address(), pMarkerInfo, __functionAddress);
}
/**
* Insert a marker label into a command buffer.
*
* <h5>C Specification</h5>
*
* <p>A single marker label can be inserted into a command buffer by calling:</p>
*
* <pre><code>
* void vkCmdDebugMarkerInsertEXT(
* VkCommandBuffer commandBuffer,
* const VkDebugMarkerMarkerInfoEXT* pMarkerInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code pMarkerInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerMarkerInfoEXT} structure</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, or compute operations</li>
* <li>This command <b>must</b> only be called outside of a video coding scope</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Outside</td><td>Graphics Compute</td><td>Action</td></tr></tbody>
* </table>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerMarkerInfoEXT}</p>
*
* @param commandBuffer the command buffer into which the command is recorded.
* @param pMarkerInfo a pointer to a {@link VkDebugMarkerMarkerInfoEXT} structure specifying the parameters of the marker to insert.
*/
public static void vkCmdDebugMarkerInsertEXT(VkCommandBuffer commandBuffer, @NativeType("VkDebugMarkerMarkerInfoEXT const *") VkDebugMarkerMarkerInfoEXT pMarkerInfo) {
nvkCmdDebugMarkerInsertEXT(commandBuffer, pMarkerInfo.address());
}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/EXTDebugMarker.java | 7,347 | // --- [ vkDebugMarkerSetObjectTagEXT ] --- | line_comment | nl | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
/**
* The {@code VK_EXT_debug_marker} extension is a device extension. It introduces concepts of object naming and tagging, for better tracking of Vulkan objects, as well as additional commands for recording annotations of named sections of a workload to aid organization and offline analysis in external tools.
*
* <h5>Examples</h5>
*
* <p><b>Example 1</b></p>
*
* <p>Associate a name with an image, for easier debugging in external tools or with validation layers that can print a friendly name when referring to objects in error messages.</p>
*
* <pre><code>
* extern VkDevice device;
* extern VkImage image;
*
* // Must call extension functions through a function pointer:
* PFN_vkDebugMarkerSetObjectNameEXT pfnDebugMarkerSetObjectNameEXT = (PFN_vkDebugMarkerSetObjectNameEXT)vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT");
*
* // Set a name on the image
* const VkDebugMarkerObjectNameInfoEXT imageNameInfo =
* {
* .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT,
* .pNext = NULL,
* .objectType = VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,
* .object = (uint64_t)image,
* .pObjectName = "Brick Diffuse Texture",
* };
*
* pfnDebugMarkerSetObjectNameEXT(device, &imageNameInfo);
*
* // A subsequent error might print:
* // Image 'Brick Diffuse Texture' (0xc0dec0dedeadbeef) is used in a
* // command buffer with no memory bound to it.</code></pre>
*
* <p><b>Example 2</b></p>
*
* <p>Annotating regions of a workload with naming information so that offline analysis tools can display a more usable visualization of the commands submitted.</p>
*
* <pre><code>
* extern VkDevice device;
* extern VkCommandBuffer commandBuffer;
*
* // Must call extension functions through a function pointer:
* PFN_vkCmdDebugMarkerBeginEXT pfnCmdDebugMarkerBeginEXT = (PFN_vkCmdDebugMarkerBeginEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT");
* PFN_vkCmdDebugMarkerEndEXT pfnCmdDebugMarkerEndEXT = (PFN_vkCmdDebugMarkerEndEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT");
* PFN_vkCmdDebugMarkerInsertEXT pfnCmdDebugMarkerInsertEXT = (PFN_vkCmdDebugMarkerInsertEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT");
*
* // Describe the area being rendered
* const VkDebugMarkerMarkerInfoEXT houseMarker =
* {
* .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT,
* .pNext = NULL,
* .pMarkerName = "Brick House",
* .color = { 1.0f, 0.0f, 0.0f, 1.0f },
* };
*
* // Start an annotated group of calls under the 'Brick House' name
* pfnCmdDebugMarkerBeginEXT(commandBuffer, &houseMarker);
* {
* // A mutable structure for each part being rendered
* VkDebugMarkerMarkerInfoEXT housePartMarker =
* {
* .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT,
* .pNext = NULL,
* .pMarkerName = NULL,
* .color = { 0.0f, 0.0f, 0.0f, 0.0f },
* };
*
* // Set the name and insert the marker
* housePartMarker.pMarkerName = "Walls";
* pfnCmdDebugMarkerInsertEXT(commandBuffer, &housePartMarker);
*
* // Insert the drawcall for the walls
* vkCmdDrawIndexed(commandBuffer, 1000, 1, 0, 0, 0);
*
* // Insert a recursive region for two sets of windows
* housePartMarker.pMarkerName = "Windows";
* pfnCmdDebugMarkerBeginEXT(commandBuffer, &housePartMarker);
* {
* vkCmdDrawIndexed(commandBuffer, 75, 6, 1000, 0, 0);
* vkCmdDrawIndexed(commandBuffer, 100, 2, 1450, 0, 0);
* }
* pfnCmdDebugMarkerEndEXT(commandBuffer);
*
* housePartMarker.pMarkerName = "Front Door";
* pfnCmdDebugMarkerInsertEXT(commandBuffer, &housePartMarker);
*
* vkCmdDrawIndexed(commandBuffer, 350, 1, 1650, 0, 0);
*
* housePartMarker.pMarkerName = "Roof";
* pfnCmdDebugMarkerInsertEXT(commandBuffer, &housePartMarker);
*
* vkCmdDrawIndexed(commandBuffer, 500, 1, 2000, 0, 0);
* }
* // End the house annotation started above
* pfnCmdDebugMarkerEndEXT(commandBuffer);</code></pre>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_EXT_debug_marker}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>23</dd>
* <dt><b>Revision</b></dt>
* <dd>4</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link EXTDebugReport VK_EXT_debug_report}</dd>
* <dt><b>Deprecation State</b></dt>
* <dd><ul>
* <li><em>Promoted</em> to {@link EXTDebugUtils VK_EXT_debug_utils} extension</li>
* </ul></dd>
* <dt><b>Special Use</b></dt>
* <dd><ul>
* <li><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse">Debugging tools</a></li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Baldur Karlsson <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_debug_marker]%20@baldurk%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_debug_marker%20extension*">baldurk</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-01-31</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Baldur Karlsson</li>
* <li>Dan Ginsburg, Valve</li>
* <li>Jon Ashburn, LunarG</li>
* <li>Kyle Spagnoli, NVIDIA</li>
* </ul></dd>
* </dl>
*/
public class EXTDebugMarker {
/** The extension specification version. */
public static final int VK_EXT_DEBUG_MARKER_SPEC_VERSION = 4;
/** The extension name. */
public static final String VK_EXT_DEBUG_MARKER_EXTENSION_NAME = "VK_EXT_debug_marker";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT = 1000022000,
VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT = 1000022001,
VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT = 1000022002;
protected EXTDebugMarker() {
throw new UnsupportedOperationException();
}
// --- [<SUF>
/** Unsafe version of: {@link #vkDebugMarkerSetObjectTagEXT DebugMarkerSetObjectTagEXT} */
public static int nvkDebugMarkerSetObjectTagEXT(VkDevice device, long pTagInfo) {
long __functionAddress = device.getCapabilities().vkDebugMarkerSetObjectTagEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerObjectTagInfoEXT.validate(pTagInfo);
}
return callPPI(device.address(), pTagInfo, __functionAddress);
}
/**
* Attach arbitrary data to an object.
*
* <h5>C Specification</h5>
*
* <p>In addition to setting a name for an object, debugging and validation layers may have uses for additional binary data on a per-object basis that has no other place in the Vulkan API. For example, a {@code VkShaderModule} could have additional debugging data attached to it to aid in offline shader tracing. To attach data to an object, call:</p>
*
* <pre><code>
* VkResult vkDebugMarkerSetObjectTagEXT(
* VkDevice device,
* const VkDebugMarkerObjectTagInfoEXT* pTagInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pTagInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerObjectTagInfoEXT} structure</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code pTagInfo→object} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerObjectTagInfoEXT}</p>
*
* @param device the device that created the object.
* @param pTagInfo a pointer to a {@link VkDebugMarkerObjectTagInfoEXT} structure specifying the parameters of the tag to attach to the object.
*/
@NativeType("VkResult")
public static int vkDebugMarkerSetObjectTagEXT(VkDevice device, @NativeType("VkDebugMarkerObjectTagInfoEXT const *") VkDebugMarkerObjectTagInfoEXT pTagInfo) {
return nvkDebugMarkerSetObjectTagEXT(device, pTagInfo.address());
}
// --- [ vkDebugMarkerSetObjectNameEXT ] ---
/** Unsafe version of: {@link #vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectNameEXT} */
public static int nvkDebugMarkerSetObjectNameEXT(VkDevice device, long pNameInfo) {
long __functionAddress = device.getCapabilities().vkDebugMarkerSetObjectNameEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerObjectNameInfoEXT.validate(pNameInfo);
}
return callPPI(device.address(), pNameInfo, __functionAddress);
}
/**
* Give a user-friendly name to an object.
*
* <h5>C Specification</h5>
*
* <p>An object can be given a user-friendly name by calling:</p>
*
* <pre><code>
* VkResult vkDebugMarkerSetObjectNameEXT(
* VkDevice device,
* const VkDebugMarkerObjectNameInfoEXT* pNameInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pNameInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerObjectNameInfoEXT} structure</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code pNameInfo→object} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerObjectNameInfoEXT}</p>
*
* @param device the device that created the object.
* @param pNameInfo a pointer to a {@link VkDebugMarkerObjectNameInfoEXT} structure specifying the parameters of the name to set on the object.
*/
@NativeType("VkResult")
public static int vkDebugMarkerSetObjectNameEXT(VkDevice device, @NativeType("VkDebugMarkerObjectNameInfoEXT const *") VkDebugMarkerObjectNameInfoEXT pNameInfo) {
return nvkDebugMarkerSetObjectNameEXT(device, pNameInfo.address());
}
// --- [ vkCmdDebugMarkerBeginEXT ] ---
/** Unsafe version of: {@link #vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT} */
public static void nvkCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, long pMarkerInfo) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDebugMarkerBeginEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerMarkerInfoEXT.validate(pMarkerInfo);
}
callPPV(commandBuffer.address(), pMarkerInfo, __functionAddress);
}
/**
* Open a command buffer marker region.
*
* <h5>C Specification</h5>
*
* <p>A marker region can be opened by calling:</p>
*
* <pre><code>
* void vkCmdDebugMarkerBeginEXT(
* VkCommandBuffer commandBuffer,
* const VkDebugMarkerMarkerInfoEXT* pMarkerInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code pMarkerInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerMarkerInfoEXT} structure</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, or compute operations</li>
* <li>This command <b>must</b> only be called outside of a video coding scope</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Outside</td><td>Graphics Compute</td><td>Action</td></tr></tbody>
* </table>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerMarkerInfoEXT}</p>
*
* @param commandBuffer the command buffer into which the command is recorded.
* @param pMarkerInfo a pointer to a {@link VkDebugMarkerMarkerInfoEXT} structure specifying the parameters of the marker region to open.
*/
public static void vkCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, @NativeType("VkDebugMarkerMarkerInfoEXT const *") VkDebugMarkerMarkerInfoEXT pMarkerInfo) {
nvkCmdDebugMarkerBeginEXT(commandBuffer, pMarkerInfo.address());
}
// --- [ vkCmdDebugMarkerEndEXT ] ---
/**
* Close a command buffer marker region.
*
* <h5>C Specification</h5>
*
* <p>A marker region can be closed by calling:</p>
*
* <pre><code>
* void vkCmdDebugMarkerEndEXT(
* VkCommandBuffer commandBuffer);</code></pre>
*
* <h5>Description</h5>
*
* <p>An application <b>may</b> open a marker region in one command buffer and close it in another, or otherwise split marker regions across multiple command buffers or multiple queue submissions. When viewed from the linear series of submissions to a single queue, the calls to {@code vkCmdDebugMarkerBeginEXT} and {@code vkCmdDebugMarkerEndEXT} <b>must</b> be matched and balanced.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>There <b>must</b> be an outstanding {@link #vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT} command prior to the {@code vkCmdDebugMarkerEndEXT} on the queue that {@code commandBuffer} is submitted to</li>
* <li>If {@code commandBuffer} is a secondary command buffer, there <b>must</b> be an outstanding {@link #vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT} command recorded to {@code commandBuffer} that has not previously been ended by a call to {@link #vkCmdDebugMarkerEndEXT CmdDebugMarkerEndEXT}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, or compute operations</li>
* <li>This command <b>must</b> only be called outside of a video coding scope</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Outside</td><td>Graphics Compute</td><td>Action</td></tr></tbody>
* </table>
*
* @param commandBuffer the command buffer into which the command is recorded.
*/
public static void vkCmdDebugMarkerEndEXT(VkCommandBuffer commandBuffer) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDebugMarkerEndEXT;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), __functionAddress);
}
// --- [ vkCmdDebugMarkerInsertEXT ] ---
/** Unsafe version of: {@link #vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsertEXT} */
public static void nvkCmdDebugMarkerInsertEXT(VkCommandBuffer commandBuffer, long pMarkerInfo) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDebugMarkerInsertEXT;
if (CHECKS) {
check(__functionAddress);
VkDebugMarkerMarkerInfoEXT.validate(pMarkerInfo);
}
callPPV(commandBuffer.address(), pMarkerInfo, __functionAddress);
}
/**
* Insert a marker label into a command buffer.
*
* <h5>C Specification</h5>
*
* <p>A single marker label can be inserted into a command buffer by calling:</p>
*
* <pre><code>
* void vkCmdDebugMarkerInsertEXT(
* VkCommandBuffer commandBuffer,
* const VkDebugMarkerMarkerInfoEXT* pMarkerInfo);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code pMarkerInfo} <b>must</b> be a valid pointer to a valid {@link VkDebugMarkerMarkerInfoEXT} structure</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, or compute operations</li>
* <li>This command <b>must</b> only be called outside of a video coding scope</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR">Video Coding Scope</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th><th><a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#fundamentals-queueoperation-command-types">Command Type</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Outside</td><td>Graphics Compute</td><td>Action</td></tr></tbody>
* </table>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugMarkerMarkerInfoEXT}</p>
*
* @param commandBuffer the command buffer into which the command is recorded.
* @param pMarkerInfo a pointer to a {@link VkDebugMarkerMarkerInfoEXT} structure specifying the parameters of the marker to insert.
*/
public static void vkCmdDebugMarkerInsertEXT(VkCommandBuffer commandBuffer, @NativeType("VkDebugMarkerMarkerInfoEXT const *") VkDebugMarkerMarkerInfoEXT pMarkerInfo) {
nvkCmdDebugMarkerInsertEXT(commandBuffer, pMarkerInfo.address());
}
} |
29882_3 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.demo.opengl.textures;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.demo.util.WavefrontMeshLoader;
import org.lwjgl.demo.util.WavefrontMeshLoader.Mesh;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.system.*;
import org.joml.Matrix4f;
import org.joml.Matrix4x3f;
import org.joml.Vector3f;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static org.lwjgl.opengl.ARBShaderObjects.*;
import static org.lwjgl.opengl.ARBVertexShader.*;
import static org.lwjgl.opengl.ARBVertexBufferObject.*;
import static org.lwjgl.opengl.ARBFragmentShader.*;
import static org.lwjgl.demo.util.IOUtils.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.stb.STBImage.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Just like {@link EnvironmentDemo}, but also adds a reflective teapot.
*
* @author Kai Burjack
*/
public class EnvironmentTeapotDemo {
long window;
int width = 1024;
int height = 768;
int fbWidth = 1024;
int fbHeight = 768;
float fov = 60, rotX, rotY;
int environmentProgram;
int teapotProgram;
int invViewProjUniform;
int viewProjUniform;
int cameraPositionUniform;
Matrix4f projectionMatrix = new Matrix4f();
Matrix4x3f viewMatrix = new Matrix4x3f();
Matrix4f viewProjMatrix = new Matrix4f();
Matrix4f invViewProjMatrix = new Matrix4f();
Vector3f cameraPosition = new Vector3f();
FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);
Mesh mesh;
int numVertices;
long normalsOffset;
int teapotVbo;
int fullscreenVbo;
GLCapabilities caps;
GLFWKeyCallback keyCallback;
GLFWFramebufferSizeCallback fbCallback;
GLFWCursorPosCallback cpCallback;
GLFWScrollCallback sCallback;
Callback debugProc;
void init() throws IOException {
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(width, height, "Spherical environment mapping with teapot demo", NULL, NULL);
if (window == NULL)
throw new AssertionError("Failed to create the GLFW window");
System.out.println("Move the mouse to look around");
System.out.println("Zoom in/out with mouse wheel");
glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
if (width > 0 && height > 0 && (EnvironmentTeapotDemo.this.fbWidth != width || EnvironmentTeapotDemo.this.fbHeight != height)) {
EnvironmentTeapotDemo.this.fbWidth = width;
EnvironmentTeapotDemo.this.fbHeight = height;
}
}
});
glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if (action != GLFW_RELEASE)
return;
if (key == GLFW_KEY_ESCAPE) {
glfwSetWindowShouldClose(window, true);
}
}
});
glfwSetCursorPosCallback(window, cpCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double x, double y) {
float nx = (float) x / width * 2.0f - 1.0f;
float ny = (float) y / height * 2.0f - 1.0f;
rotX = ny * (float)Math.PI * 0.5f;
rotY = nx * (float)Math.PI;
}
});
glfwSetScrollCallback(window, sCallback = new GLFWScrollCallback() {
@Override
public void invoke(long window, double xoffset, double yoffset) {
if (yoffset < 0)
fov *= 1.05f;
else
fov *= 1f/1.05f;
if (fov < 10.0f)
fov = 10.0f;
else if (fov > 120.0f)
fov = 120.0f;
}
});
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
glfwShowWindow(window);
glfwSetCursorPos(window, width / 2, height / 2);
try (MemoryStack frame = MemoryStack.stackPush()) {
IntBuffer framebufferSize = frame.mallocInt(2);
nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
width = framebufferSize.get(0);
height = framebufferSize.get(1);
}
caps = GL.createCapabilities();
if (!caps.GL_ARB_shader_objects)
throw new AssertionError("This demo requires the ARB_shader_objects extension.");
if (!caps.GL_ARB_vertex_shader)
throw new AssertionError("This demo requires the ARB_vertex_shader extension.");
if (!caps.GL_ARB_fragment_shader)
throw new AssertionError("This demo requires the ARB_fragment_shader extension.");
debugProc = GLUtil.setupDebugMessageCallback();
/* Create all needed GL resources */
loadMesh();
createTexture();
createFullScreenQuad();
createTeapotProgram();
createEnvironmentProgram();
}
void loadMesh() throws IOException {
mesh = new WavefrontMeshLoader().loadMesh("org/lwjgl/demo/opengl/models/teapot.obj.zip");
this.numVertices = mesh.numVertices;
long bufferSize = 4 * (3 + 3) * mesh.numVertices;
this.normalsOffset = 4L * 3 * mesh.numVertices;
this.teapotVbo = glGenBuffersARB();
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.teapotVbo);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, bufferSize, GL_STATIC_DRAW_ARB);
glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, 0L, mesh.positions);
glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, normalsOffset, mesh.normals);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
}
void createFullScreenQuad() {
ByteBuffer vertices = BufferUtils.createByteBuffer(4 * 2 * 6);
FloatBuffer fv = vertices.asFloatBuffer();
fv.put(-1.0f).put(-1.0f);
fv.put( 1.0f).put(-1.0f);
fv.put( 1.0f).put( 1.0f);
fv.put( 1.0f).put( 1.0f);
fv.put(-1.0f).put( 1.0f);
fv.put(-1.0f).put(-1.0f);
this.fullscreenVbo = glGenBuffersARB();
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.fullscreenVbo);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, vertices, GL_STATIC_DRAW_ARB);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
}
static int createShader(String resource, int type) throws IOException {
int shader = glCreateShaderObjectARB(type);
ByteBuffer source = ioResourceToByteBuffer(resource, 1024);
PointerBuffer strings = BufferUtils.createPointerBuffer(1);
IntBuffer lengths = BufferUtils.createIntBuffer(1);
strings.put(0, source);
lengths.put(0, source.remaining());
glShaderSourceARB(shader, strings, lengths);
glCompileShaderARB(shader);
int compiled = glGetObjectParameteriARB(shader, GL_OBJECT_COMPILE_STATUS_ARB);
String shaderLog = glGetInfoLogARB(shader);
if (shaderLog.trim().length() > 0) {
System.err.println(shaderLog);
}
if (compiled == 0) {
throw new AssertionError("Could not compile shader");
}
return shader;
}
void createEnvironmentProgram() throws IOException {
int program = glCreateProgramObjectARB();
int vshader = createShader("org/lwjgl/demo/opengl/textures/environment.vs", GL_VERTEX_SHADER_ARB);
int fshader = createShader("org/lwjgl/demo/opengl/textures/environment.fs", GL_FRAGMENT_SHADER_ARB);
glAttachObjectARB(program, vshader);
glAttachObjectARB(program, fshader);
glLinkProgramARB(program);
int linked = glGetObjectParameteriARB(program, GL_OBJECT_LINK_STATUS_ARB);
String programLog = glGetInfoLogARB(program);
if (programLog.trim().length() > 0) {
System.err.println(programLog);
}
if (linked == 0) {
throw new AssertionError("Could not link program");
}
glUseProgramObjectARB(program);
int texLocation = glGetUniformLocationARB(program, "tex");
glUniform1iARB(texLocation, 0);
invViewProjUniform = glGetUniformLocationARB(program, "invViewProj");
this.environmentProgram = program;
}
void createTeapotProgram() throws IOException {
int program = glCreateProgramObjectARB();
int vshader = createShader("org/lwjgl/demo/opengl/textures/teapot.vs", GL_VERTEX_SHADER_ARB);
int fshader = createShader("org/lwjgl/demo/opengl/textures/teapot.fs", GL_FRAGMENT_SHADER_ARB);
glAttachObjectARB(program, vshader);
glAttachObjectARB(program, fshader);
glLinkProgramARB(program);
int linked = glGetObjectParameteriARB(program, GL_OBJECT_LINK_STATUS_ARB);
String programLog = glGetInfoLogARB(program);
if (programLog.trim().length() > 0) {
System.err.println(programLog);
}
if (linked == 0) {
throw new AssertionError("Could not link program");
}
glUseProgramObjectARB(program);
viewProjUniform = glGetUniformLocationARB(program, "viewProj");
cameraPositionUniform = glGetUniformLocationARB(program, "cameraPosition");
this.teapotProgram = program;
}
static void createTexture() throws IOException {
int tex = glGenTextures();
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
ByteBuffer imageBuffer;
IntBuffer w = BufferUtils.createIntBuffer(1);
IntBuffer h = BufferUtils.createIntBuffer(1);
IntBuffer comp = BufferUtils.createIntBuffer(1);
ByteBuffer image;
imageBuffer = ioResourceToByteBuffer("org/lwjgl/demo/opengl/textures/environment.jpg", 8 * 1024);
if (!stbi_info_from_memory(imageBuffer, w, h, comp))
throw new IOException("Failed to read image information: " + stbi_failure_reason());
image = stbi_load_from_memory(imageBuffer, w, h, comp, 3);
if (image == null)
throw new IOException("Failed to load image: " + stbi_failure_reason());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, w.get(0), h.get(0), 0, GL_RGB, GL_UNSIGNED_BYTE, image);
stbi_image_free(image);
}
void update() {
projectionMatrix.setPerspective((float) Math.toRadians(fov), (float) width / height, 0.01f, 100.0f);
viewMatrix.translation(0, 0, -10.0f)
.rotateX(rotX)
.rotateY(rotY);
viewMatrix.origin(cameraPosition);
projectionMatrix.mulPerspectiveAffine(viewMatrix, viewProjMatrix).invert(invViewProjMatrix);
glUseProgramObjectARB(environmentProgram);
glUniformMatrix4fvARB(invViewProjUniform, false, invViewProjMatrix.get(matrixBuffer));
glUseProgramObjectARB(teapotProgram);
glUniformMatrix4fvARB(viewProjUniform, false, viewProjMatrix.get(matrixBuffer));
glUniform3fARB(cameraPositionUniform, cameraPosition.x, cameraPosition.y, cameraPosition.z);
}
void render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Render environment map */
glDisable(GL_DEPTH_TEST);
glUseProgramObjectARB(environmentProgram);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.fullscreenVbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, 0L);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
/* Render teapot */
glEnable(GL_DEPTH_TEST);
glUseProgramObjectARB(teapotProgram);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.teapotProgram);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 3 * 4, 0L);
glNormalPointer(GL_FLOAT, 3 * 4, normalsOffset);
glDrawArrays(GL_TRIANGLES, 0, numVertices);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
void loop() {
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glViewport(0, 0, fbWidth, fbHeight);
update();
render();
glfwSwapBuffers(window);
}
}
void run() {
try {
init();
loop();
if (debugProc != null) {
debugProc.free();
}
cpCallback.free();
keyCallback.free();
fbCallback.free();
glfwDestroyWindow(window);
} catch (Throwable t) {
t.printStackTrace();
} finally {
glfwTerminate();
}
}
public static void main(String[] args) {
new EnvironmentTeapotDemo().run();
}
} | LWJGL/lwjgl3-demos | src/org/lwjgl/demo/opengl/textures/EnvironmentTeapotDemo.java | 4,488 | /* Render environment map */ | block_comment | nl | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.demo.opengl.textures;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.demo.util.WavefrontMeshLoader;
import org.lwjgl.demo.util.WavefrontMeshLoader.Mesh;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.system.*;
import org.joml.Matrix4f;
import org.joml.Matrix4x3f;
import org.joml.Vector3f;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static org.lwjgl.opengl.ARBShaderObjects.*;
import static org.lwjgl.opengl.ARBVertexShader.*;
import static org.lwjgl.opengl.ARBVertexBufferObject.*;
import static org.lwjgl.opengl.ARBFragmentShader.*;
import static org.lwjgl.demo.util.IOUtils.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.stb.STBImage.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Just like {@link EnvironmentDemo}, but also adds a reflective teapot.
*
* @author Kai Burjack
*/
public class EnvironmentTeapotDemo {
long window;
int width = 1024;
int height = 768;
int fbWidth = 1024;
int fbHeight = 768;
float fov = 60, rotX, rotY;
int environmentProgram;
int teapotProgram;
int invViewProjUniform;
int viewProjUniform;
int cameraPositionUniform;
Matrix4f projectionMatrix = new Matrix4f();
Matrix4x3f viewMatrix = new Matrix4x3f();
Matrix4f viewProjMatrix = new Matrix4f();
Matrix4f invViewProjMatrix = new Matrix4f();
Vector3f cameraPosition = new Vector3f();
FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);
Mesh mesh;
int numVertices;
long normalsOffset;
int teapotVbo;
int fullscreenVbo;
GLCapabilities caps;
GLFWKeyCallback keyCallback;
GLFWFramebufferSizeCallback fbCallback;
GLFWCursorPosCallback cpCallback;
GLFWScrollCallback sCallback;
Callback debugProc;
void init() throws IOException {
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(width, height, "Spherical environment mapping with teapot demo", NULL, NULL);
if (window == NULL)
throw new AssertionError("Failed to create the GLFW window");
System.out.println("Move the mouse to look around");
System.out.println("Zoom in/out with mouse wheel");
glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
if (width > 0 && height > 0 && (EnvironmentTeapotDemo.this.fbWidth != width || EnvironmentTeapotDemo.this.fbHeight != height)) {
EnvironmentTeapotDemo.this.fbWidth = width;
EnvironmentTeapotDemo.this.fbHeight = height;
}
}
});
glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if (action != GLFW_RELEASE)
return;
if (key == GLFW_KEY_ESCAPE) {
glfwSetWindowShouldClose(window, true);
}
}
});
glfwSetCursorPosCallback(window, cpCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double x, double y) {
float nx = (float) x / width * 2.0f - 1.0f;
float ny = (float) y / height * 2.0f - 1.0f;
rotX = ny * (float)Math.PI * 0.5f;
rotY = nx * (float)Math.PI;
}
});
glfwSetScrollCallback(window, sCallback = new GLFWScrollCallback() {
@Override
public void invoke(long window, double xoffset, double yoffset) {
if (yoffset < 0)
fov *= 1.05f;
else
fov *= 1f/1.05f;
if (fov < 10.0f)
fov = 10.0f;
else if (fov > 120.0f)
fov = 120.0f;
}
});
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
glfwShowWindow(window);
glfwSetCursorPos(window, width / 2, height / 2);
try (MemoryStack frame = MemoryStack.stackPush()) {
IntBuffer framebufferSize = frame.mallocInt(2);
nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
width = framebufferSize.get(0);
height = framebufferSize.get(1);
}
caps = GL.createCapabilities();
if (!caps.GL_ARB_shader_objects)
throw new AssertionError("This demo requires the ARB_shader_objects extension.");
if (!caps.GL_ARB_vertex_shader)
throw new AssertionError("This demo requires the ARB_vertex_shader extension.");
if (!caps.GL_ARB_fragment_shader)
throw new AssertionError("This demo requires the ARB_fragment_shader extension.");
debugProc = GLUtil.setupDebugMessageCallback();
/* Create all needed GL resources */
loadMesh();
createTexture();
createFullScreenQuad();
createTeapotProgram();
createEnvironmentProgram();
}
void loadMesh() throws IOException {
mesh = new WavefrontMeshLoader().loadMesh("org/lwjgl/demo/opengl/models/teapot.obj.zip");
this.numVertices = mesh.numVertices;
long bufferSize = 4 * (3 + 3) * mesh.numVertices;
this.normalsOffset = 4L * 3 * mesh.numVertices;
this.teapotVbo = glGenBuffersARB();
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.teapotVbo);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, bufferSize, GL_STATIC_DRAW_ARB);
glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, 0L, mesh.positions);
glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, normalsOffset, mesh.normals);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
}
void createFullScreenQuad() {
ByteBuffer vertices = BufferUtils.createByteBuffer(4 * 2 * 6);
FloatBuffer fv = vertices.asFloatBuffer();
fv.put(-1.0f).put(-1.0f);
fv.put( 1.0f).put(-1.0f);
fv.put( 1.0f).put( 1.0f);
fv.put( 1.0f).put( 1.0f);
fv.put(-1.0f).put( 1.0f);
fv.put(-1.0f).put(-1.0f);
this.fullscreenVbo = glGenBuffersARB();
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.fullscreenVbo);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, vertices, GL_STATIC_DRAW_ARB);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
}
static int createShader(String resource, int type) throws IOException {
int shader = glCreateShaderObjectARB(type);
ByteBuffer source = ioResourceToByteBuffer(resource, 1024);
PointerBuffer strings = BufferUtils.createPointerBuffer(1);
IntBuffer lengths = BufferUtils.createIntBuffer(1);
strings.put(0, source);
lengths.put(0, source.remaining());
glShaderSourceARB(shader, strings, lengths);
glCompileShaderARB(shader);
int compiled = glGetObjectParameteriARB(shader, GL_OBJECT_COMPILE_STATUS_ARB);
String shaderLog = glGetInfoLogARB(shader);
if (shaderLog.trim().length() > 0) {
System.err.println(shaderLog);
}
if (compiled == 0) {
throw new AssertionError("Could not compile shader");
}
return shader;
}
void createEnvironmentProgram() throws IOException {
int program = glCreateProgramObjectARB();
int vshader = createShader("org/lwjgl/demo/opengl/textures/environment.vs", GL_VERTEX_SHADER_ARB);
int fshader = createShader("org/lwjgl/demo/opengl/textures/environment.fs", GL_FRAGMENT_SHADER_ARB);
glAttachObjectARB(program, vshader);
glAttachObjectARB(program, fshader);
glLinkProgramARB(program);
int linked = glGetObjectParameteriARB(program, GL_OBJECT_LINK_STATUS_ARB);
String programLog = glGetInfoLogARB(program);
if (programLog.trim().length() > 0) {
System.err.println(programLog);
}
if (linked == 0) {
throw new AssertionError("Could not link program");
}
glUseProgramObjectARB(program);
int texLocation = glGetUniformLocationARB(program, "tex");
glUniform1iARB(texLocation, 0);
invViewProjUniform = glGetUniformLocationARB(program, "invViewProj");
this.environmentProgram = program;
}
void createTeapotProgram() throws IOException {
int program = glCreateProgramObjectARB();
int vshader = createShader("org/lwjgl/demo/opengl/textures/teapot.vs", GL_VERTEX_SHADER_ARB);
int fshader = createShader("org/lwjgl/demo/opengl/textures/teapot.fs", GL_FRAGMENT_SHADER_ARB);
glAttachObjectARB(program, vshader);
glAttachObjectARB(program, fshader);
glLinkProgramARB(program);
int linked = glGetObjectParameteriARB(program, GL_OBJECT_LINK_STATUS_ARB);
String programLog = glGetInfoLogARB(program);
if (programLog.trim().length() > 0) {
System.err.println(programLog);
}
if (linked == 0) {
throw new AssertionError("Could not link program");
}
glUseProgramObjectARB(program);
viewProjUniform = glGetUniformLocationARB(program, "viewProj");
cameraPositionUniform = glGetUniformLocationARB(program, "cameraPosition");
this.teapotProgram = program;
}
static void createTexture() throws IOException {
int tex = glGenTextures();
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
ByteBuffer imageBuffer;
IntBuffer w = BufferUtils.createIntBuffer(1);
IntBuffer h = BufferUtils.createIntBuffer(1);
IntBuffer comp = BufferUtils.createIntBuffer(1);
ByteBuffer image;
imageBuffer = ioResourceToByteBuffer("org/lwjgl/demo/opengl/textures/environment.jpg", 8 * 1024);
if (!stbi_info_from_memory(imageBuffer, w, h, comp))
throw new IOException("Failed to read image information: " + stbi_failure_reason());
image = stbi_load_from_memory(imageBuffer, w, h, comp, 3);
if (image == null)
throw new IOException("Failed to load image: " + stbi_failure_reason());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, w.get(0), h.get(0), 0, GL_RGB, GL_UNSIGNED_BYTE, image);
stbi_image_free(image);
}
void update() {
projectionMatrix.setPerspective((float) Math.toRadians(fov), (float) width / height, 0.01f, 100.0f);
viewMatrix.translation(0, 0, -10.0f)
.rotateX(rotX)
.rotateY(rotY);
viewMatrix.origin(cameraPosition);
projectionMatrix.mulPerspectiveAffine(viewMatrix, viewProjMatrix).invert(invViewProjMatrix);
glUseProgramObjectARB(environmentProgram);
glUniformMatrix4fvARB(invViewProjUniform, false, invViewProjMatrix.get(matrixBuffer));
glUseProgramObjectARB(teapotProgram);
glUniformMatrix4fvARB(viewProjUniform, false, viewProjMatrix.get(matrixBuffer));
glUniform3fARB(cameraPositionUniform, cameraPosition.x, cameraPosition.y, cameraPosition.z);
}
void render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Render environment map<SUF>*/
glDisable(GL_DEPTH_TEST);
glUseProgramObjectARB(environmentProgram);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.fullscreenVbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, 0L);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
/* Render teapot */
glEnable(GL_DEPTH_TEST);
glUseProgramObjectARB(teapotProgram);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, this.teapotProgram);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 3 * 4, 0L);
glNormalPointer(GL_FLOAT, 3 * 4, normalsOffset);
glDrawArrays(GL_TRIANGLES, 0, numVertices);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
void loop() {
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glViewport(0, 0, fbWidth, fbHeight);
update();
render();
glfwSwapBuffers(window);
}
}
void run() {
try {
init();
loop();
if (debugProc != null) {
debugProc.free();
}
cpCallback.free();
keyCallback.free();
fbCallback.free();
glfwDestroyWindow(window);
} catch (Throwable t) {
t.printStackTrace();
} finally {
glfwTerminate();
}
}
public static void main(String[] args) {
new EnvironmentTeapotDemo().run();
}
} |
73831_11 | package domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import exceptions.foutAantalSpelersException;
public class Spel {
private DomeinController dc;
private List<Speler> spelers = new ArrayList<Speler>();
private SpelBord spelBord;
private SteentjesPot sp;
private int beurtTeller = 0;
private int aantalSpelers;
private Steen[] getrokkenSteentjes;
private List<int[]> vakjesGeklikt;
private Steen inHand;
private boolean eersteZet = true;
private boolean eersteBeurt = true;
private Speler spelerAanDeBeurt;
public Spel(List<Speler> spelers, DomeinController dc, SpelBord bord) {
this.dc = dc;
aantalSpelers = spelers.size();
setSpelers(spelers);
bereidSpelersVoor();
this.spelBord = bord;
vakjesGeklikt = new ArrayList<>();
sp = new SteentjesPot();
Collections.shuffle(spelers);
}
public void speelBeurt(boolean volgende) {// true als een de volgende speler mag beginnen
if (volgende) {
beurtTeller++;
if (beurtTeller == aantalSpelers)
beurtTeller = 0;
vakjesGeklikt = new ArrayList<>();
getrokkenSteentjes = sp.geefSteentjes(eersteZet ? 3 : 2);
if (getrokkenSteentjes == null)
eindeSpel();
this.spelerAanDeBeurt = spelers.get(beurtTeller);
}
dc.updateBeurt(getrokkenSteentjes, spelerAanDeBeurt);
}
public void opVakjeGeklikt(int x, int y) {
boolean validatieOK = true;
if (inHand != null) {// er is een steentje geselecteerd
if (eersteZet) {// het is de eerste beurt
if (x != 7 || y != 7) {// eerste zet is niet ok
validatieOK = false;
eersteZet = true;
}
}
if (!eersteZet) {
if (!spelBord.validatie1(x, y)) {// validatie 1 is niet ok
validatieOK = false;
}
}
if (!eersteBeurt) {
if (!spelBord.validatie2(x, y, vakjesGeklikt)) {// validatie 4 is niet ok
validatieOK = false;
}
}
if (!eersteZet) {
if (!spelBord.validatie3(x, y, inHand.getWaarde())) {// validatie 2 is niet ok
validatieOK = false;
}
}
if (validatieOK) {// als alles ok is
registreerSteentje(x, y);
} else {// speler moet een beurt opnieuw spelen als niet alles ok is
speelBeurt(false);
}
if (getrokkenSteentjesOp()) {// als getrokken steentjes op zijn
Collections.reverse(vakjesGeklikt);
spelBord.validatie4(vakjesGeklikt, spelerAanDeBeurt.getScoreBlad());
speelBeurt(true);
eersteBeurt = false;
}
}
}
private void registreerSteentje(int x, int y) {
vakjesGeklikt.add(new int[] { x, y, inHand.getWaarde() });
spelBord.legSteentjeOpVakje(x, y, inHand);
verwijderSteentjeInHand();
inHand = null;
dc.updateBeurt(getrokkenSteentjes, this.spelerAanDeBeurt);
if (eersteZet)
eersteZet = false;
}
private boolean getrokkenSteentjesOp() {
return getrokkenSteentjes[0].getWaarde() == 0 && getrokkenSteentjes[1].getWaarde() == 0
&& getrokkenSteentjes[2].getWaarde() == 0;
}
private void verwijderSteentjeInHand() {
getrokkenSteentjes[Arrays.asList(getrokkenSteentjes).indexOf(inHand)] = new Steen(0);
}
public void getrokkenSteentjeClick(int button) {
inHand = getrokkenSteentjes[button - 1];
}
private void bereidSpelersVoor() {
for (Speler speler : spelers) {
speler.setScoreBlad(new ScoreBlad());// geeft alle spelers een scoreblad
dc.veranderSpeelKansenSpeler(speler, -1);// verminderd speelkansen met 1
}
}
private void setSpelers(List<Speler> spelers) {
if (aantalSpelers < 2 || aantalSpelers > 4)
throw new foutAantalSpelersException();
this.spelers = spelers;
}
private void eindeSpel() {
dc.eindeSpel(vindWinnaar().getGebruikersNaam());
}
private Speler vindWinnaar() {
Speler winnaar = spelers.get(0);
int hoogsteScore = 0;
for (Speler speler : spelers) {
if (speler.getScoreBlad().getTotaal() > hoogsteScore) {
winnaar = speler;
hoogsteScore = speler.getScoreBlad().getTotaal();
}
}
return winnaar;
}
}
| LanderDK/2022-java-zatre | src/domein/Spel.java | 1,568 | // verminderd speelkansen met 1 | line_comment | nl | package domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import exceptions.foutAantalSpelersException;
public class Spel {
private DomeinController dc;
private List<Speler> spelers = new ArrayList<Speler>();
private SpelBord spelBord;
private SteentjesPot sp;
private int beurtTeller = 0;
private int aantalSpelers;
private Steen[] getrokkenSteentjes;
private List<int[]> vakjesGeklikt;
private Steen inHand;
private boolean eersteZet = true;
private boolean eersteBeurt = true;
private Speler spelerAanDeBeurt;
public Spel(List<Speler> spelers, DomeinController dc, SpelBord bord) {
this.dc = dc;
aantalSpelers = spelers.size();
setSpelers(spelers);
bereidSpelersVoor();
this.spelBord = bord;
vakjesGeklikt = new ArrayList<>();
sp = new SteentjesPot();
Collections.shuffle(spelers);
}
public void speelBeurt(boolean volgende) {// true als een de volgende speler mag beginnen
if (volgende) {
beurtTeller++;
if (beurtTeller == aantalSpelers)
beurtTeller = 0;
vakjesGeklikt = new ArrayList<>();
getrokkenSteentjes = sp.geefSteentjes(eersteZet ? 3 : 2);
if (getrokkenSteentjes == null)
eindeSpel();
this.spelerAanDeBeurt = spelers.get(beurtTeller);
}
dc.updateBeurt(getrokkenSteentjes, spelerAanDeBeurt);
}
public void opVakjeGeklikt(int x, int y) {
boolean validatieOK = true;
if (inHand != null) {// er is een steentje geselecteerd
if (eersteZet) {// het is de eerste beurt
if (x != 7 || y != 7) {// eerste zet is niet ok
validatieOK = false;
eersteZet = true;
}
}
if (!eersteZet) {
if (!spelBord.validatie1(x, y)) {// validatie 1 is niet ok
validatieOK = false;
}
}
if (!eersteBeurt) {
if (!spelBord.validatie2(x, y, vakjesGeklikt)) {// validatie 4 is niet ok
validatieOK = false;
}
}
if (!eersteZet) {
if (!spelBord.validatie3(x, y, inHand.getWaarde())) {// validatie 2 is niet ok
validatieOK = false;
}
}
if (validatieOK) {// als alles ok is
registreerSteentje(x, y);
} else {// speler moet een beurt opnieuw spelen als niet alles ok is
speelBeurt(false);
}
if (getrokkenSteentjesOp()) {// als getrokken steentjes op zijn
Collections.reverse(vakjesGeklikt);
spelBord.validatie4(vakjesGeklikt, spelerAanDeBeurt.getScoreBlad());
speelBeurt(true);
eersteBeurt = false;
}
}
}
private void registreerSteentje(int x, int y) {
vakjesGeklikt.add(new int[] { x, y, inHand.getWaarde() });
spelBord.legSteentjeOpVakje(x, y, inHand);
verwijderSteentjeInHand();
inHand = null;
dc.updateBeurt(getrokkenSteentjes, this.spelerAanDeBeurt);
if (eersteZet)
eersteZet = false;
}
private boolean getrokkenSteentjesOp() {
return getrokkenSteentjes[0].getWaarde() == 0 && getrokkenSteentjes[1].getWaarde() == 0
&& getrokkenSteentjes[2].getWaarde() == 0;
}
private void verwijderSteentjeInHand() {
getrokkenSteentjes[Arrays.asList(getrokkenSteentjes).indexOf(inHand)] = new Steen(0);
}
public void getrokkenSteentjeClick(int button) {
inHand = getrokkenSteentjes[button - 1];
}
private void bereidSpelersVoor() {
for (Speler speler : spelers) {
speler.setScoreBlad(new ScoreBlad());// geeft alle spelers een scoreblad
dc.veranderSpeelKansenSpeler(speler, -1);// verminderd speelkansen<SUF>
}
}
private void setSpelers(List<Speler> spelers) {
if (aantalSpelers < 2 || aantalSpelers > 4)
throw new foutAantalSpelersException();
this.spelers = spelers;
}
private void eindeSpel() {
dc.eindeSpel(vindWinnaar().getGebruikersNaam());
}
private Speler vindWinnaar() {
Speler winnaar = spelers.get(0);
int hoogsteScore = 0;
for (Speler speler : spelers) {
if (speler.getScoreBlad().getTotaal() > hoogsteScore) {
winnaar = speler;
hoogsteScore = speler.getScoreBlad().getTotaal();
}
}
return winnaar;
}
}
|
35822_23 | package dataLaag;
import javafx.scene.image.Image;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.eclipse.persistence.jpa.jpql.parser.DateTime;
import domein.Aankoper;
import domein.Barcode;
import domein.BedrijfsBestelling;
import domein.BedrijfsDoos;
import domein.BedrijfsKlant;
import domein.BedrijfsProduct;
import domein.BedrijfsProductBestelling;
import domein.Doos;
import domein.ProductBestelling;
import domein.Status;
import domein.StatusEntity;
import domein.Type;
import domein.BedrijfsTransportdienst;
import domein.BedrijfsUser;
import util.BCrypt;
import util.JPAUtil;
public class DataClass {
public static EntityManagerFactory emf = JPAUtil.getEntityManagerFactory();
public static EntityManager em = emf.createEntityManager();
private List<String> emailContactPersonen = new ArrayList<>();
private List<String> telefoonNrContactPersonen = new ArrayList<>();
public void aanmaakData() {
List<Aankoper> aankoperLijst1 = new ArrayList<Aankoper>();
List<Aankoper> aankoperLijst2 = new ArrayList<Aankoper>();
List<Aankoper> aankoperLijst3 = new ArrayList<Aankoper>();
List<Aankoper> aankoperLijst4 = new ArrayList<Aankoper>();
Aankoper a1 = new Aankoper("a49f400e-b0f6-4aaf-8a56-cf78fe2ad6be","Pol", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"8742136590", 1);
Aankoper a2 = new Aankoper("141d7f71-622a-4acc-abad-8b301955472d","Jos", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"2468013579", 2);
Aankoper a3 = new Aankoper("906c6853-0353-45b5-84bf-4261a2a19e20","kevin", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"5907641823", 1);
Aankoper a4 = new Aankoper("46908591-3160-4e60-bcd9-a2623fdf9a29","piet", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null, "9876543210", 2);
Aankoper a5 = new Aankoper("22323232-4545-6e67-efg8-c34343434343","Jan", "[email protected]", BCrypt.hashpw("Passw0rd!", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"5647382910", 1);
Aankoper a6 = new Aankoper("77777777-8888-9999-abcd-1234567890ab","Sarah", "[email protected]", BCrypt.hashpw("Pa$$word123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"3847261590", 2);
Aankoper a7 = new Aankoper("a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6","John", "[email protected]", BCrypt.hashpw("Qwerty123!", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"7319054682", 1);
Aankoper a8 = new Aankoper("xy12z34a-56b7-89cd-efg0-hi12j3kl4m5n","Samantha", "[email protected]", BCrypt.hashpw("Password123$", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"1568904723", 2);
Aankoper a9 = new Aankoper("pqr5s6t7-u8v9-wx1y2z3a-4b5c6d7e8f9g","Michael", "[email protected]", BCrypt.hashpw("Summer2023", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"8021354976", 1);
Aankoper a10 = new Aankoper("11111111-2222-3333-4444-555555555555","Anna", "[email protected]", BCrypt.hashpw("Winter2022!", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null, "6452901837", 2);
aankoperLijst1.add(a1);
aankoperLijst1.add(a2);
aankoperLijst1.add(a3);
aankoperLijst1.add(a4);
aankoperLijst2.add(a5);
aankoperLijst2.add(a6);
aankoperLijst3.add(a10);
aankoperLijst4.add(a7);
aankoperLijst4.add(a8);
aankoperLijst4.add(a9);
StatusEntity se3 = new StatusEntity("InBehandeling");
StatusEntity se1 = new StatusEntity("Verwerkt");
StatusEntity se2 = new StatusEntity("Geplaatst");
StatusEntity se4 = new StatusEntity("Geleverd");
StatusEntity se5 = new StatusEntity("Geannuleerd");
BedrijfsUser u1 = new BedrijfsUser("Admin1", "Lander", "De Kesel", "Mclaren123", "Imkerstraat 8", "0479583092",
"0951445297", "[email protected]", "Admin");
BedrijfsUser u2 = new BedrijfsUser("Magazijnier1", "Casper", "De Bock", "Mclaren123", "Straat 0", "0446555555",
"0971448997", "[email protected]", "Magazijnier");
Barcode br1 = new Barcode(4, true, "VOL");
Barcode br2 = new Barcode(5, false, "MAN");
Barcode br3 = new Barcode(6, true, "MER");
Barcode br4 = new Barcode(3, false, "REN");
Barcode br5 = new Barcode(6, false, "SCA");
InputStream streamBlis = getClass().getResourceAsStream("../resources/blissfulbites.png");
Image blisLogo = new Image(streamBlis);
InputStream streamHappy = getClass().getResourceAsStream("../resources/happyTails.png");
Image happyLogo = new Image(streamHappy);
BedrijfsKlant k1 = new BedrijfsKlant("Blissful Bites", "[email protected]", "BlissfulBites",
"0487679271", aankoperLijst1, "Stratem 5 9000 Gent", blisLogo);
BedrijfsKlant k2 = new BedrijfsKlant("Happy Tails", "[email protected]", "HappyTails", "0487679271",
aankoperLijst2, "Poortstraat 7 2000 Antwerpen", happyLogo);
emailContactPersonen.add("[email protected]");
emailContactPersonen.add("[email protected]");
emailContactPersonen.add("[email protected]");
telefoonNrContactPersonen.add("0475124798");
telefoonNrContactPersonen.add("0456324798");
telefoonNrContactPersonen.add("0497458738");
BedrijfsTransportdienst td1 = new BedrijfsTransportdienst("VOLVO Camion", "Stationstraat 1",
emailContactPersonen, telefoonNrContactPersonen, Status.Actief, br1);
BedrijfsTransportdienst td2 = new BedrijfsTransportdienst("MAN Camion", "Stationstraat 2", emailContactPersonen,
telefoonNrContactPersonen, Status.Actief, br2);
BedrijfsTransportdienst td3 = new BedrijfsTransportdienst("MERCEDES Camion", "Stationstraat 3",
emailContactPersonen, telefoonNrContactPersonen, Status.Actief, br3);
BedrijfsTransportdienst td4 = new BedrijfsTransportdienst("RENAULT Camion", "Stationstraat 4",
emailContactPersonen, telefoonNrContactPersonen, Status.Inactief, br4);
BedrijfsTransportdienst td5 = new BedrijfsTransportdienst("SCANIA Camion", "Stationstraat 5",
emailContactPersonen, telefoonNrContactPersonen, Status.Inactief, br5);
BedrijfsDoos d3 = new BedrijfsDoos("Kartonnen Doos S", Type.Custom, "30,5x21x4,8cm", 0.68, Status.Actief);
BedrijfsDoos d2 = new BedrijfsDoos("Kartonnen Doos M", Type.Standaard, "40,5x36x5,8cm", 0.90, Status.Inactief);
BedrijfsDoos d1 = new BedrijfsDoos("Kartonnen Doos L", Type.Standaard, "48,5x40x6,8cm", 1.00, Status.Actief);
BedrijfsBestelling b1 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 10 9880 Aalter", Status.Verwerkt, d2,
td1, "VOL-1234-4");
BedrijfsBestelling b2 = new BedrijfsBestelling(k2, LocalDateTime.now(), "Stationstraat 11 9880 Aalter", Status.Verwerkt, d1,
td2, "MAN-4A51B-2");
BedrijfsBestelling b3 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 12 9880 Aalter", Status.Verwerkt, d3,
td3, "MER-123456-1");
BedrijfsBestelling b4 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 13 9880 Aalter", Status.Geplaatst, d3,
null, null);
BedrijfsBestelling b5 = new BedrijfsBestelling(k2, LocalDateTime.now(), "Stationstraat 14 9880 Aalter", Status.Verwerkt, d3,
td3, "MER-789012-5");
BedrijfsBestelling b6 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 15 9880 Aalter", Status.Geplaatst, d3,
null, null);
BedrijfsProduct p1 = new BedrijfsProduct("Kamerplant Leep","https://www.freepnglogos.com/uploads/plant-png/plant-png-transparent-plant-images-pluspng-26.png", "Dit is een groene leep kamerplant", 20.48, 25, "2 dagen", 3);
BedrijfsProduct p2 = new BedrijfsProduct("Metalen kruk", "https://www.gewoonstijl.nl/media/catalog/product/d/s/dsc00266_bewerkt_440b.png", "Dit is een metalen kruk", 12.99, 50, "7 dagen", 1);
BedrijfsProduct p3 = new BedrijfsProduct("Witte Stoel", "https://www.freeiconspng.com/uploads/white-chair-png-31.png", "Dit is een witte stoel van 35cm bij 90cm", 18.99, 100, "3 dagen", 1);
BedrijfsProduct p4 = new BedrijfsProduct("Zwarte bank", "https://crm.eland.be/storage/media/8668/604B-Kubide-Bank-Links-200-Zwart.png", "Dit is een zwarte bank van 1 meter bij 90cm", 9.99, 200, "1 dag", 4);
BedrijfsProduct p5 = new BedrijfsProduct("Glazen salon tafel", "https://www.ygo.be/thumbnail/6e/d3/0e/1674225807/63caa88f04295-29c85a53e054d2eb147fec03b95f2747e0112d60_Y15150004505__media_packshots__marco_1__e_commerce_channel_1920x1920.png", "Dit is een dubbele glazen salon tafel met zwart metaal", 39.99, 50, "2 dagen", 2);
BedrijfsProduct p6 = new BedrijfsProduct("Houten eettafel", "https://static.vecteezy.com/system/resources/previews/019/922/490/non_2x/3d-wooden-table-png.png", "Een houten eet tafel gemaakt uit eiken hout", 29.99, 75, "3 dagen", 2);
BedrijfsProduct p7 = new BedrijfsProduct("Houten stoel", "https://www.gewoonstijl.nl/media/catalog/product/a/c/act.30407_0_lisomme_jade_houten_eetkamerstoel_naturel_8f45.png", "Een houten stoel gemaakt van eikenhoud", 19.99, 100, "1 dag", 1);
BedrijfsProduct p8 = new BedrijfsProduct("Stoffen poef", "https://www.marie-marie.com/media/0d/ee/10/1644938463/0b270bb791a144428fc3d4d569f43902f252F9252F3252Fa252Ff93aa0e73ee55a81ccce2a2b0f7c0ae931cfbdd5_poef_coomba_21.png", "Stoffen poef gemaakt om te rusten", 14.99, 150, "2 dagen", 4);
BedrijfsProduct p9 = new BedrijfsProduct("Leren zetel", "https://www.femat.be/ftp/ITEMS/small/1094.PNG", "Leren zetel gemaakt uit italiaans leer", 24.99, 50, "7 dagen", 4);
BedrijfsProduct p10 = new BedrijfsProduct("Vintage eetkamerstoel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/bistrostoel-van-rotan-en-eikenhout-1000-7-36-111884_10.jpg", "Vintage eetkamerstoel met armleuningen, gemaakt van gerecycled hout", 27.99, 80, "3 dagen", 1);
BedrijfsProduct p11 = new BedrijfsProduct("Roze fluwelen kruk", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/poef-met-roze-en-goudkleurig-velourseffect-1000-4-20-194688_1.jpg", "Roze fluwelen kruk met gouden metalen poten", 16.99, 60, "2 dagen", 1);
BedrijfsProduct p12 = new BedrijfsProduct("Lamp met houten poot", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/kastanjebruine-driepotige-lamp-met-ecru-lampenkap-1000-10-7-211116_1.jpg", "Lamp met gouden kap en houten poot", 32.99, 40, "4 dagen", 7);
BedrijfsProduct p13 = new BedrijfsProduct("Kunstplant palmboom", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/groene-en-bruine-kunstpalmboom-1000-6-29-232991_1.jpg", "Kunstplant van een palmboom met een natuurlijke uitstraling", 18.99, 100, "7 dagen", 3);
BedrijfsProduct p14 = new BedrijfsProduct("Lounge stoel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/beige-fauteuil-met-vergulde-metalen-poten-1000-10-10-216080_1.jpg", "Comfortabele lounge stoel met bruin leer en een houten onderstel", 64.99, 30, "7 dagen", 4);
BedrijfsProduct p15 = new BedrijfsProduct("Gouden bijzettafel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/rond-bijzettafeltje-van-mat-goudkleurig-metaal-1000-11-30-191295_1.jpg", "Gouden bijzettafel met een marmeren blad", 49.99, 20, "2 dagen", 2);
BedrijfsProduct p16 = new BedrijfsProduct("Industriële barkruk", "https://media.s-bol.com/7DVGo6EB8PvB/lOwxAQ7/550x551.jpg", "Industriële barkruk met een houten zitting en een metalen onderstel", 21.99, 70, "7 dagen", 1);
BedrijfsProduct p17 = new BedrijfsProduct("Zwarte bureaustoel", "https://www.ygo.be/thumbnail/0c/e2/9c/1680871030/64300e756f6f2-718f1ea28aa4406f0fabe809e6307d8ba1e458e7_Y15250008105__media_packshots__plats_1__e_commerce_channel_1920x1920.png", "Dit is een comfortabele zwarte bureaustoel met een verstelbare rugleuning", 34.99, 75, "2 dagen", 1);
BedrijfsProduct p18 = new BedrijfsProduct("Witte plantenbak", "https://action.com/hostedassets/CMSArticleImages/99/69/2574080_8714075045607-111_02.png", "Dit is een witte plantenbak van keramiek, geschikt voor binnen en buiten", 22.99, 100, "7 dagen", 3);
BedrijfsProduct p19 = new BedrijfsProduct("Gele fauteuil", "https://cdn.sofacompany.com/media/catalog/product/6/4/64195ce11a1db.jpg?width=800&height=800&store=be&image-type=small_image", "Dit is een gele fauteuil met een hoge rugleuning, perfect voor ontspanning", 299.99, 10, "2 dagen", 4);
BedrijfsProduct p20 = new BedrijfsProduct("Zwarte metalen kast", "https://production-beheer.povag.nl/storage/configurationoptions-media/14647/responsive-images/media-libraryiE7Kj0___webp_576_576.webp", "Dit is een zwarte metalen kast met twee deuren en vier laden, ideaal voor opbergruimte", 169.99, 25, "7 dagen", 5);
BedrijfsProduct p21 = new BedrijfsProduct("Houten opbergkist", "https://nl.vidaxl.be/dw/image/v2/BFNS_PRD/on/demandware.static/-/Sites-vidaxl-catalog-master-sku/default/dwb315ceea/hi-res/436/6356/4205/289641/image_1_289641.jpg?sw=400", "Dit is een houten opbergkist met een deksel en handvatten aan beide zijden", 226.99, 100, "3 dagen", 5);
BedrijfsProduct p22 = new BedrijfsProduct("Zwarte bureautafel", "https://production-beheer.povag.nl/storage/products-media/17969/responsive-images/media-libraryBycJPa___webp_576_576.webp", "Dit is een zwarte bureautafel met een lade en opbergruimte aan beide zijden", 88.00, 50, "7 dagen", 2);
BedrijfsProduct p23 = new BedrijfsProduct("Houten plantenrek", "https://action.com/hostedassets/CMSArticleImages/51/88/3004800_8717582167268-110_01.png", "Dit is een houten plantenrek met drie planken, perfect om je planten op te zetten", 29.99, 75, "2 dagen", 3);
BedrijfsProduct p24 = new BedrijfsProduct("Laptop stand", "https://image.coolblue.be/max/500x500/products/1608594", "Ergonomische laptop stand om nekklachten te voorkomen", 14.99, 50, "2 dagen", 7);
BedrijfsProduct p25 = new BedrijfsProduct("Zwarte kast", "https://nl.vidaxl.be/dw/image/v2/BFNS_PRD/on/demandware.static/-/Sites-vidaxl-catalog-master-sku/default/dwc7b17730/hi-res/436/464/465/800154/image_2_800154.jpg?sw=400", "Grote zwarte kast met meerdere opbergvakken", 39.99, 25, "1 dag", 5);
BedrijfsProduct p26 = new BedrijfsProduct("Witte boekenkast", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/witte-asymmetrisch-boekenkast-1000-10-1-150307_0.jpg", "Moderne witte boekenkast met vijf planken", 49.99, 20, "2 dagen", 5);
BedrijfsProduct p27 = new BedrijfsProduct("Houten spiegel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/lichte-spiegel-uit-paulowniahout-105-x-181-cm-1000-1-1-211192_1.jpg", "Grote houten spiegel voor in de slaapkamer", 24.99, 15, "1 dag", 6);
BedrijfsProduct p28 = new BedrijfsProduct("Kleurrijke poster", "https://cdn1.home24.net/images/media/catalog/product/455x455/png/-/1/-1000291929-210923-11292500756-IMAGE-P000000001000291929.webp", "Moderne muurdecoratie met verschillende kleuren", 19.99, 50, "3 dagen", 6);
BedrijfsProduct p29 = new BedrijfsProduct("Bureaustoel", "https://image.coolblue.be/max/500x500/products/1872342", "Comfortabele bureaustoel met verstelbare armleuningen", 79.99, 10, "1 dag", 1);
BedrijfsProduct p30 = new BedrijfsProduct("Opbergboxen", "https://raja.scene7.com/is/image/Raja/products/voordelige-opbergbox-39-x-30-x-36-cm_QLINE52.jpg?template=withpicto410&$image=M_QLINE52_S_FR&$picto=NoPicto&hei=410&wid=410&fmt=jpg&qlt=85,0&resMode=sharp2&op_usm=1.75,0.3,2,0", "Set van drie opbergboxen in verschillende maten", 14.99, 30, "2 dagen", 5);
BedrijfsProduct p31 = new BedrijfsProduct("Plantenbak", "https://dc94gqcjteixu.cloudfront.net/14159/original/11184.jpg?browser-cache=2023-04-28_15:14:15", "Moderne plantenbak voor binnen of buiten", 34.99, 15, "3 dagen", 3);
BedrijfsProductBestelling pb1 = new BedrijfsProductBestelling(p1, b3, 6);
BedrijfsProductBestelling pb2 = new BedrijfsProductBestelling(p2, b3, 15);
BedrijfsProductBestelling pb3 = new BedrijfsProductBestelling(p1, b1, 20);
BedrijfsProductBestelling pb4 = new BedrijfsProductBestelling(p7, b1, 1);
BedrijfsProductBestelling pb5 = new BedrijfsProductBestelling(p4, b6, 3);
BedrijfsProductBestelling pb6 = new BedrijfsProductBestelling(p8, b2, 24);
BedrijfsProductBestelling pb7 = new BedrijfsProductBestelling(p9, b5, 24);
BedrijfsProductBestelling pb8 = new BedrijfsProductBestelling(p5, b3, 24);
BedrijfsProductBestelling pb9 = new BedrijfsProductBestelling(p1, b4, 24);
em.getTransaction().begin();
em.persist(a1);
em.persist(a2);
em.persist(a3);
em.persist(a4);
em.persist(a5);
em.persist(a6);
em.persist(a7);
em.persist(a8);
em.persist(a9);
em.persist(a10);
em.persist(k1);
em.persist(d1);
em.persist(d2);
em.persist(se3);
em.persist(se1);
em.persist(se2);
em.persist(se4);
em.persist(se5);
em.persist(d3);
em.persist(b1);
em.persist(b2);
em.persist(b3);
em.persist(b4);
em.persist(b5);
em.persist(b6);
em.persist(br1);
em.persist(br2);
em.persist(br3);
em.persist(br4);
em.persist(br5);
em.persist(u1);
em.persist(u2);
em.persist(td1);
em.persist(td2);
em.persist(td3);
em.persist(td4);
em.persist(td5);
em.persist(k1);
em.persist(k2);
em.persist(p1);
em.persist(p2);
em.persist(p3);
em.persist(p4);
em.persist(p5);
em.persist(p6);
em.persist(p7);
em.persist(p8);
em.persist(p9);
em.persist(p10);
em.persist(p11);
em.persist(p12);
em.persist(p13);
em.persist(p14);
em.persist(p15);
em.persist(p16);
em.persist(p17);
em.persist(p18);
em.persist(p19);
em.persist(p20);
em.persist(p21);
em.persist(p22);
em.persist(p23);
em.persist(p24);
em.persist(p25);
em.persist(p26);
em.persist(p27);
em.persist(p28);
em.persist(p29);
em.persist(p30);
em.persist(p31);
em.persist(pb1);
em.persist(pb2);
em.persist(pb3);
em.persist(pb4);
em.persist(pb5);
em.persist(pb6);
em.persist(pb7);
em.persist(pb8);
em.persist(pb9);
em.getTransaction().commit();
}
} | LanderDK/2023-java-delaware | src/dataLaag/DataClass.java | 7,564 | //image.coolblue.be/max/500x500/products/1608594", "Ergonomische laptop stand om nekklachten te voorkomen", 14.99, 50, "2 dagen", 7); | line_comment | nl | package dataLaag;
import javafx.scene.image.Image;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.eclipse.persistence.jpa.jpql.parser.DateTime;
import domein.Aankoper;
import domein.Barcode;
import domein.BedrijfsBestelling;
import domein.BedrijfsDoos;
import domein.BedrijfsKlant;
import domein.BedrijfsProduct;
import domein.BedrijfsProductBestelling;
import domein.Doos;
import domein.ProductBestelling;
import domein.Status;
import domein.StatusEntity;
import domein.Type;
import domein.BedrijfsTransportdienst;
import domein.BedrijfsUser;
import util.BCrypt;
import util.JPAUtil;
public class DataClass {
public static EntityManagerFactory emf = JPAUtil.getEntityManagerFactory();
public static EntityManager em = emf.createEntityManager();
private List<String> emailContactPersonen = new ArrayList<>();
private List<String> telefoonNrContactPersonen = new ArrayList<>();
public void aanmaakData() {
List<Aankoper> aankoperLijst1 = new ArrayList<Aankoper>();
List<Aankoper> aankoperLijst2 = new ArrayList<Aankoper>();
List<Aankoper> aankoperLijst3 = new ArrayList<Aankoper>();
List<Aankoper> aankoperLijst4 = new ArrayList<Aankoper>();
Aankoper a1 = new Aankoper("a49f400e-b0f6-4aaf-8a56-cf78fe2ad6be","Pol", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"8742136590", 1);
Aankoper a2 = new Aankoper("141d7f71-622a-4acc-abad-8b301955472d","Jos", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"2468013579", 2);
Aankoper a3 = new Aankoper("906c6853-0353-45b5-84bf-4261a2a19e20","kevin", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"5907641823", 1);
Aankoper a4 = new Aankoper("46908591-3160-4e60-bcd9-a2623fdf9a29","piet", "[email protected]", BCrypt.hashpw("Mclaren123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null, "9876543210", 2);
Aankoper a5 = new Aankoper("22323232-4545-6e67-efg8-c34343434343","Jan", "[email protected]", BCrypt.hashpw("Passw0rd!", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"5647382910", 1);
Aankoper a6 = new Aankoper("77777777-8888-9999-abcd-1234567890ab","Sarah", "[email protected]", BCrypt.hashpw("Pa$$word123", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"3847261590", 2);
Aankoper a7 = new Aankoper("a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6","John", "[email protected]", BCrypt.hashpw("Qwerty123!", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"7319054682", 1);
Aankoper a8 = new Aankoper("xy12z34a-56b7-89cd-efg0-hi12j3kl4m5n","Samantha", "[email protected]", BCrypt.hashpw("Password123$", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"1568904723", 2);
Aankoper a9 = new Aankoper("pqr5s6t7-u8v9-wx1y2z3a-4b5c6d7e8f9g","Michael", "[email protected]", BCrypt.hashpw("Summer2023", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null,"8021354976", 1);
Aankoper a10 = new Aankoper("11111111-2222-3333-4444-555555555555","Anna", "[email protected]", BCrypt.hashpw("Winter2022!", BCrypt.gensalt(10)), LocalDateTime.now(), "Aankoper", null, "6452901837", 2);
aankoperLijst1.add(a1);
aankoperLijst1.add(a2);
aankoperLijst1.add(a3);
aankoperLijst1.add(a4);
aankoperLijst2.add(a5);
aankoperLijst2.add(a6);
aankoperLijst3.add(a10);
aankoperLijst4.add(a7);
aankoperLijst4.add(a8);
aankoperLijst4.add(a9);
StatusEntity se3 = new StatusEntity("InBehandeling");
StatusEntity se1 = new StatusEntity("Verwerkt");
StatusEntity se2 = new StatusEntity("Geplaatst");
StatusEntity se4 = new StatusEntity("Geleverd");
StatusEntity se5 = new StatusEntity("Geannuleerd");
BedrijfsUser u1 = new BedrijfsUser("Admin1", "Lander", "De Kesel", "Mclaren123", "Imkerstraat 8", "0479583092",
"0951445297", "[email protected]", "Admin");
BedrijfsUser u2 = new BedrijfsUser("Magazijnier1", "Casper", "De Bock", "Mclaren123", "Straat 0", "0446555555",
"0971448997", "[email protected]", "Magazijnier");
Barcode br1 = new Barcode(4, true, "VOL");
Barcode br2 = new Barcode(5, false, "MAN");
Barcode br3 = new Barcode(6, true, "MER");
Barcode br4 = new Barcode(3, false, "REN");
Barcode br5 = new Barcode(6, false, "SCA");
InputStream streamBlis = getClass().getResourceAsStream("../resources/blissfulbites.png");
Image blisLogo = new Image(streamBlis);
InputStream streamHappy = getClass().getResourceAsStream("../resources/happyTails.png");
Image happyLogo = new Image(streamHappy);
BedrijfsKlant k1 = new BedrijfsKlant("Blissful Bites", "[email protected]", "BlissfulBites",
"0487679271", aankoperLijst1, "Stratem 5 9000 Gent", blisLogo);
BedrijfsKlant k2 = new BedrijfsKlant("Happy Tails", "[email protected]", "HappyTails", "0487679271",
aankoperLijst2, "Poortstraat 7 2000 Antwerpen", happyLogo);
emailContactPersonen.add("[email protected]");
emailContactPersonen.add("[email protected]");
emailContactPersonen.add("[email protected]");
telefoonNrContactPersonen.add("0475124798");
telefoonNrContactPersonen.add("0456324798");
telefoonNrContactPersonen.add("0497458738");
BedrijfsTransportdienst td1 = new BedrijfsTransportdienst("VOLVO Camion", "Stationstraat 1",
emailContactPersonen, telefoonNrContactPersonen, Status.Actief, br1);
BedrijfsTransportdienst td2 = new BedrijfsTransportdienst("MAN Camion", "Stationstraat 2", emailContactPersonen,
telefoonNrContactPersonen, Status.Actief, br2);
BedrijfsTransportdienst td3 = new BedrijfsTransportdienst("MERCEDES Camion", "Stationstraat 3",
emailContactPersonen, telefoonNrContactPersonen, Status.Actief, br3);
BedrijfsTransportdienst td4 = new BedrijfsTransportdienst("RENAULT Camion", "Stationstraat 4",
emailContactPersonen, telefoonNrContactPersonen, Status.Inactief, br4);
BedrijfsTransportdienst td5 = new BedrijfsTransportdienst("SCANIA Camion", "Stationstraat 5",
emailContactPersonen, telefoonNrContactPersonen, Status.Inactief, br5);
BedrijfsDoos d3 = new BedrijfsDoos("Kartonnen Doos S", Type.Custom, "30,5x21x4,8cm", 0.68, Status.Actief);
BedrijfsDoos d2 = new BedrijfsDoos("Kartonnen Doos M", Type.Standaard, "40,5x36x5,8cm", 0.90, Status.Inactief);
BedrijfsDoos d1 = new BedrijfsDoos("Kartonnen Doos L", Type.Standaard, "48,5x40x6,8cm", 1.00, Status.Actief);
BedrijfsBestelling b1 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 10 9880 Aalter", Status.Verwerkt, d2,
td1, "VOL-1234-4");
BedrijfsBestelling b2 = new BedrijfsBestelling(k2, LocalDateTime.now(), "Stationstraat 11 9880 Aalter", Status.Verwerkt, d1,
td2, "MAN-4A51B-2");
BedrijfsBestelling b3 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 12 9880 Aalter", Status.Verwerkt, d3,
td3, "MER-123456-1");
BedrijfsBestelling b4 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 13 9880 Aalter", Status.Geplaatst, d3,
null, null);
BedrijfsBestelling b5 = new BedrijfsBestelling(k2, LocalDateTime.now(), "Stationstraat 14 9880 Aalter", Status.Verwerkt, d3,
td3, "MER-789012-5");
BedrijfsBestelling b6 = new BedrijfsBestelling(k1, LocalDateTime.now(), "Stationstraat 15 9880 Aalter", Status.Geplaatst, d3,
null, null);
BedrijfsProduct p1 = new BedrijfsProduct("Kamerplant Leep","https://www.freepnglogos.com/uploads/plant-png/plant-png-transparent-plant-images-pluspng-26.png", "Dit is een groene leep kamerplant", 20.48, 25, "2 dagen", 3);
BedrijfsProduct p2 = new BedrijfsProduct("Metalen kruk", "https://www.gewoonstijl.nl/media/catalog/product/d/s/dsc00266_bewerkt_440b.png", "Dit is een metalen kruk", 12.99, 50, "7 dagen", 1);
BedrijfsProduct p3 = new BedrijfsProduct("Witte Stoel", "https://www.freeiconspng.com/uploads/white-chair-png-31.png", "Dit is een witte stoel van 35cm bij 90cm", 18.99, 100, "3 dagen", 1);
BedrijfsProduct p4 = new BedrijfsProduct("Zwarte bank", "https://crm.eland.be/storage/media/8668/604B-Kubide-Bank-Links-200-Zwart.png", "Dit is een zwarte bank van 1 meter bij 90cm", 9.99, 200, "1 dag", 4);
BedrijfsProduct p5 = new BedrijfsProduct("Glazen salon tafel", "https://www.ygo.be/thumbnail/6e/d3/0e/1674225807/63caa88f04295-29c85a53e054d2eb147fec03b95f2747e0112d60_Y15150004505__media_packshots__marco_1__e_commerce_channel_1920x1920.png", "Dit is een dubbele glazen salon tafel met zwart metaal", 39.99, 50, "2 dagen", 2);
BedrijfsProduct p6 = new BedrijfsProduct("Houten eettafel", "https://static.vecteezy.com/system/resources/previews/019/922/490/non_2x/3d-wooden-table-png.png", "Een houten eet tafel gemaakt uit eiken hout", 29.99, 75, "3 dagen", 2);
BedrijfsProduct p7 = new BedrijfsProduct("Houten stoel", "https://www.gewoonstijl.nl/media/catalog/product/a/c/act.30407_0_lisomme_jade_houten_eetkamerstoel_naturel_8f45.png", "Een houten stoel gemaakt van eikenhoud", 19.99, 100, "1 dag", 1);
BedrijfsProduct p8 = new BedrijfsProduct("Stoffen poef", "https://www.marie-marie.com/media/0d/ee/10/1644938463/0b270bb791a144428fc3d4d569f43902f252F9252F3252Fa252Ff93aa0e73ee55a81ccce2a2b0f7c0ae931cfbdd5_poef_coomba_21.png", "Stoffen poef gemaakt om te rusten", 14.99, 150, "2 dagen", 4);
BedrijfsProduct p9 = new BedrijfsProduct("Leren zetel", "https://www.femat.be/ftp/ITEMS/small/1094.PNG", "Leren zetel gemaakt uit italiaans leer", 24.99, 50, "7 dagen", 4);
BedrijfsProduct p10 = new BedrijfsProduct("Vintage eetkamerstoel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/bistrostoel-van-rotan-en-eikenhout-1000-7-36-111884_10.jpg", "Vintage eetkamerstoel met armleuningen, gemaakt van gerecycled hout", 27.99, 80, "3 dagen", 1);
BedrijfsProduct p11 = new BedrijfsProduct("Roze fluwelen kruk", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/poef-met-roze-en-goudkleurig-velourseffect-1000-4-20-194688_1.jpg", "Roze fluwelen kruk met gouden metalen poten", 16.99, 60, "2 dagen", 1);
BedrijfsProduct p12 = new BedrijfsProduct("Lamp met houten poot", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/kastanjebruine-driepotige-lamp-met-ecru-lampenkap-1000-10-7-211116_1.jpg", "Lamp met gouden kap en houten poot", 32.99, 40, "4 dagen", 7);
BedrijfsProduct p13 = new BedrijfsProduct("Kunstplant palmboom", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/groene-en-bruine-kunstpalmboom-1000-6-29-232991_1.jpg", "Kunstplant van een palmboom met een natuurlijke uitstraling", 18.99, 100, "7 dagen", 3);
BedrijfsProduct p14 = new BedrijfsProduct("Lounge stoel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/beige-fauteuil-met-vergulde-metalen-poten-1000-10-10-216080_1.jpg", "Comfortabele lounge stoel met bruin leer en een houten onderstel", 64.99, 30, "7 dagen", 4);
BedrijfsProduct p15 = new BedrijfsProduct("Gouden bijzettafel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/rond-bijzettafeltje-van-mat-goudkleurig-metaal-1000-11-30-191295_1.jpg", "Gouden bijzettafel met een marmeren blad", 49.99, 20, "2 dagen", 2);
BedrijfsProduct p16 = new BedrijfsProduct("Industriële barkruk", "https://media.s-bol.com/7DVGo6EB8PvB/lOwxAQ7/550x551.jpg", "Industriële barkruk met een houten zitting en een metalen onderstel", 21.99, 70, "7 dagen", 1);
BedrijfsProduct p17 = new BedrijfsProduct("Zwarte bureaustoel", "https://www.ygo.be/thumbnail/0c/e2/9c/1680871030/64300e756f6f2-718f1ea28aa4406f0fabe809e6307d8ba1e458e7_Y15250008105__media_packshots__plats_1__e_commerce_channel_1920x1920.png", "Dit is een comfortabele zwarte bureaustoel met een verstelbare rugleuning", 34.99, 75, "2 dagen", 1);
BedrijfsProduct p18 = new BedrijfsProduct("Witte plantenbak", "https://action.com/hostedassets/CMSArticleImages/99/69/2574080_8714075045607-111_02.png", "Dit is een witte plantenbak van keramiek, geschikt voor binnen en buiten", 22.99, 100, "7 dagen", 3);
BedrijfsProduct p19 = new BedrijfsProduct("Gele fauteuil", "https://cdn.sofacompany.com/media/catalog/product/6/4/64195ce11a1db.jpg?width=800&height=800&store=be&image-type=small_image", "Dit is een gele fauteuil met een hoge rugleuning, perfect voor ontspanning", 299.99, 10, "2 dagen", 4);
BedrijfsProduct p20 = new BedrijfsProduct("Zwarte metalen kast", "https://production-beheer.povag.nl/storage/configurationoptions-media/14647/responsive-images/media-libraryiE7Kj0___webp_576_576.webp", "Dit is een zwarte metalen kast met twee deuren en vier laden, ideaal voor opbergruimte", 169.99, 25, "7 dagen", 5);
BedrijfsProduct p21 = new BedrijfsProduct("Houten opbergkist", "https://nl.vidaxl.be/dw/image/v2/BFNS_PRD/on/demandware.static/-/Sites-vidaxl-catalog-master-sku/default/dwb315ceea/hi-res/436/6356/4205/289641/image_1_289641.jpg?sw=400", "Dit is een houten opbergkist met een deksel en handvatten aan beide zijden", 226.99, 100, "3 dagen", 5);
BedrijfsProduct p22 = new BedrijfsProduct("Zwarte bureautafel", "https://production-beheer.povag.nl/storage/products-media/17969/responsive-images/media-libraryBycJPa___webp_576_576.webp", "Dit is een zwarte bureautafel met een lade en opbergruimte aan beide zijden", 88.00, 50, "7 dagen", 2);
BedrijfsProduct p23 = new BedrijfsProduct("Houten plantenrek", "https://action.com/hostedassets/CMSArticleImages/51/88/3004800_8717582167268-110_01.png", "Dit is een houten plantenrek met drie planken, perfect om je planten op te zetten", 29.99, 75, "2 dagen", 3);
BedrijfsProduct p24 = new BedrijfsProduct("Laptop stand", "https://image.coolblue.be/max/500x500/products/1608594", "Ergonomische<SUF>
BedrijfsProduct p25 = new BedrijfsProduct("Zwarte kast", "https://nl.vidaxl.be/dw/image/v2/BFNS_PRD/on/demandware.static/-/Sites-vidaxl-catalog-master-sku/default/dwc7b17730/hi-res/436/464/465/800154/image_2_800154.jpg?sw=400", "Grote zwarte kast met meerdere opbergvakken", 39.99, 25, "1 dag", 5);
BedrijfsProduct p26 = new BedrijfsProduct("Witte boekenkast", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/witte-asymmetrisch-boekenkast-1000-10-1-150307_0.jpg", "Moderne witte boekenkast met vijf planken", 49.99, 20, "2 dagen", 5);
BedrijfsProduct p27 = new BedrijfsProduct("Houten spiegel", "https://medias.maisonsdumonde.com/image/upload/q_auto,f_auto/w_2000/img/lichte-spiegel-uit-paulowniahout-105-x-181-cm-1000-1-1-211192_1.jpg", "Grote houten spiegel voor in de slaapkamer", 24.99, 15, "1 dag", 6);
BedrijfsProduct p28 = new BedrijfsProduct("Kleurrijke poster", "https://cdn1.home24.net/images/media/catalog/product/455x455/png/-/1/-1000291929-210923-11292500756-IMAGE-P000000001000291929.webp", "Moderne muurdecoratie met verschillende kleuren", 19.99, 50, "3 dagen", 6);
BedrijfsProduct p29 = new BedrijfsProduct("Bureaustoel", "https://image.coolblue.be/max/500x500/products/1872342", "Comfortabele bureaustoel met verstelbare armleuningen", 79.99, 10, "1 dag", 1);
BedrijfsProduct p30 = new BedrijfsProduct("Opbergboxen", "https://raja.scene7.com/is/image/Raja/products/voordelige-opbergbox-39-x-30-x-36-cm_QLINE52.jpg?template=withpicto410&$image=M_QLINE52_S_FR&$picto=NoPicto&hei=410&wid=410&fmt=jpg&qlt=85,0&resMode=sharp2&op_usm=1.75,0.3,2,0", "Set van drie opbergboxen in verschillende maten", 14.99, 30, "2 dagen", 5);
BedrijfsProduct p31 = new BedrijfsProduct("Plantenbak", "https://dc94gqcjteixu.cloudfront.net/14159/original/11184.jpg?browser-cache=2023-04-28_15:14:15", "Moderne plantenbak voor binnen of buiten", 34.99, 15, "3 dagen", 3);
BedrijfsProductBestelling pb1 = new BedrijfsProductBestelling(p1, b3, 6);
BedrijfsProductBestelling pb2 = new BedrijfsProductBestelling(p2, b3, 15);
BedrijfsProductBestelling pb3 = new BedrijfsProductBestelling(p1, b1, 20);
BedrijfsProductBestelling pb4 = new BedrijfsProductBestelling(p7, b1, 1);
BedrijfsProductBestelling pb5 = new BedrijfsProductBestelling(p4, b6, 3);
BedrijfsProductBestelling pb6 = new BedrijfsProductBestelling(p8, b2, 24);
BedrijfsProductBestelling pb7 = new BedrijfsProductBestelling(p9, b5, 24);
BedrijfsProductBestelling pb8 = new BedrijfsProductBestelling(p5, b3, 24);
BedrijfsProductBestelling pb9 = new BedrijfsProductBestelling(p1, b4, 24);
em.getTransaction().begin();
em.persist(a1);
em.persist(a2);
em.persist(a3);
em.persist(a4);
em.persist(a5);
em.persist(a6);
em.persist(a7);
em.persist(a8);
em.persist(a9);
em.persist(a10);
em.persist(k1);
em.persist(d1);
em.persist(d2);
em.persist(se3);
em.persist(se1);
em.persist(se2);
em.persist(se4);
em.persist(se5);
em.persist(d3);
em.persist(b1);
em.persist(b2);
em.persist(b3);
em.persist(b4);
em.persist(b5);
em.persist(b6);
em.persist(br1);
em.persist(br2);
em.persist(br3);
em.persist(br4);
em.persist(br5);
em.persist(u1);
em.persist(u2);
em.persist(td1);
em.persist(td2);
em.persist(td3);
em.persist(td4);
em.persist(td5);
em.persist(k1);
em.persist(k2);
em.persist(p1);
em.persist(p2);
em.persist(p3);
em.persist(p4);
em.persist(p5);
em.persist(p6);
em.persist(p7);
em.persist(p8);
em.persist(p9);
em.persist(p10);
em.persist(p11);
em.persist(p12);
em.persist(p13);
em.persist(p14);
em.persist(p15);
em.persist(p16);
em.persist(p17);
em.persist(p18);
em.persist(p19);
em.persist(p20);
em.persist(p21);
em.persist(p22);
em.persist(p23);
em.persist(p24);
em.persist(p25);
em.persist(p26);
em.persist(p27);
em.persist(p28);
em.persist(p29);
em.persist(p30);
em.persist(p31);
em.persist(pb1);
em.persist(pb2);
em.persist(pb3);
em.persist(pb4);
em.persist(pb5);
em.persist(pb6);
em.persist(pb7);
em.persist(pb8);
em.persist(pb9);
em.getTransaction().commit();
}
} |
43942_0 | package com.springBoot.Bibliotheek;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;
import domain.Boek;
import domain.Users;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import repository.BoekRepository;
import repository.UserRepository;
@Slf4j
@Controller
@RequestMapping("/favorieten")
public class FavController {
@Autowired
private BoekRepository br;
@Autowired
private UserRepository ur;
@GetMapping(value = "/add/{id}")
public String addFav(@PathVariable("id") Integer boekID, Model model, Authentication authentication) {
log.info("Add fav");
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String username = userDetails.getUsername();
Optional<Users> user = ur.findByUsername(username);
Users u = null;
if (user.isPresent())
u = user.get();
List<String> listRoles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
model.addAttribute("user", u);
model.addAttribute("userListRoles", listRoles);
//check als je max aantal favorieten hebt bereikt --> NIET COMPLEET -> mooie melding tonen
if (u.getFavorieten().size() == u.getMaxAantalFavs())
return "redirect:/bibliotheek/list";
List<Integer> favs = u.getFavorieten();
favs.add(boekID);
u.setFavorieten(favs);
ur.save(u);
Boek b;
Optional<Boek> boek = br.findByBoekID(boekID);
if (!boek.isPresent()) {
return "redirect:/bibliotheek/list";
}
else {
b = boek.get();
b.setAantalSterren(b.getAantalSterren() + 1);
br.save(b);
}
return "redirect:/bibliotheek/list";
}
@GetMapping(value = "/remove/{id}")
public String removeFav(@PathVariable("id") Integer boekID, Model model, Authentication authentication) {
log.info("Remove fav");
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String username = userDetails.getUsername();
Optional<Users> user = ur.findByUsername(username);
Users u = null;
if (user.isPresent())
u = user.get();
List<String> listRoles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
model.addAttribute("user", u);
model.addAttribute("userListRoles", listRoles);
List<Integer> favs = u.getFavorieten();
favs.remove(boekID);
u.setFavorieten(favs);
ur.save(u);
Boek b;
Optional<Boek> boek = br.findByBoekID(boekID);
if (!boek.isPresent()) {
return "redirect:/bibliotheek/list";
}
else {
b = boek.get();
b.setAantalSterren(b.getAantalSterren() - 1);
br.save(b);
}
return "redirect:/bibliotheek/list";
}
}
| LanderDK/Bibliotheek_ExamenOpdracht | src/main/java/com/springBoot/Bibliotheek/FavController.java | 1,114 | //check als je max aantal favorieten hebt bereikt --> NIET COMPLEET -> mooie melding tonen | line_comment | nl | package com.springBoot.Bibliotheek;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;
import domain.Boek;
import domain.Users;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import repository.BoekRepository;
import repository.UserRepository;
@Slf4j
@Controller
@RequestMapping("/favorieten")
public class FavController {
@Autowired
private BoekRepository br;
@Autowired
private UserRepository ur;
@GetMapping(value = "/add/{id}")
public String addFav(@PathVariable("id") Integer boekID, Model model, Authentication authentication) {
log.info("Add fav");
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String username = userDetails.getUsername();
Optional<Users> user = ur.findByUsername(username);
Users u = null;
if (user.isPresent())
u = user.get();
List<String> listRoles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
model.addAttribute("user", u);
model.addAttribute("userListRoles", listRoles);
//check als<SUF>
if (u.getFavorieten().size() == u.getMaxAantalFavs())
return "redirect:/bibliotheek/list";
List<Integer> favs = u.getFavorieten();
favs.add(boekID);
u.setFavorieten(favs);
ur.save(u);
Boek b;
Optional<Boek> boek = br.findByBoekID(boekID);
if (!boek.isPresent()) {
return "redirect:/bibliotheek/list";
}
else {
b = boek.get();
b.setAantalSterren(b.getAantalSterren() + 1);
br.save(b);
}
return "redirect:/bibliotheek/list";
}
@GetMapping(value = "/remove/{id}")
public String removeFav(@PathVariable("id") Integer boekID, Model model, Authentication authentication) {
log.info("Remove fav");
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String username = userDetails.getUsername();
Optional<Users> user = ur.findByUsername(username);
Users u = null;
if (user.isPresent())
u = user.get();
List<String> listRoles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
model.addAttribute("user", u);
model.addAttribute("userListRoles", listRoles);
List<Integer> favs = u.getFavorieten();
favs.remove(boekID);
u.setFavorieten(favs);
ur.save(u);
Boek b;
Optional<Boek> boek = br.findByBoekID(boekID);
if (!boek.isPresent()) {
return "redirect:/bibliotheek/list";
}
else {
b = boek.get();
b.setAantalSterren(b.getAantalSterren() - 1);
br.save(b);
}
return "redirect:/bibliotheek/list";
}
}
|
151820_11 | package inholland.nl.eindopdrachtjavafx.DAL;
import inholland.nl.eindopdrachtjavafx.Models.Item;
import inholland.nl.eindopdrachtjavafx.Models.Member;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Database {
private List<Member> members;
private List<Item> items;
public Database() {
this.members = new ArrayList<>();
this.items = new ArrayList<>();
try {
loadDataForMembers();
loadDataForItems();
} catch (IOException e) {
// add users to collection
this.members.add(new Member(1, "Lars","Lars", "H", "Lars H", LocalDate.of(1990, 1, 1), "1234"));
this.members.add(new Member(2, "Test","Jane", "Doe", "Jane Doe", LocalDate.of(1994, 6, 15), "0000"));
this.members.add(new Member(3, "John","John", "Smith", "John Smith", LocalDate.of(1992, 3, 12), "1234"));
this.members.add(new Member(4, "Jane2","Jane", "Smith", "Jane Smith", LocalDate.of(1995, 8, 23), "5678"));
this.members.add(new Member(5, "John2","John", "Doe", "John Doe", LocalDate.of(1990, 1, 1), "2378"));
// add items to collection
this.items.add(new Item(1, true, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", LocalDate.of(1997, 6, 26)));
this.items.add(new Item(2, true, "Harry Potter and the Chamber of Secrets", "J.K. Rowling", LocalDate.of(1998, 7, 2)));
this.items.add(new Item(3, true, "Harry Potter and the Prisoner of Azkaban", "J.K. Rowling", LocalDate.of(1999, 7, 8)));
this.items.add(new Item(4, true, "Harry Potter and the Goblet of Fire", "J.K. Rowling", LocalDate.of(2000, 7, 8)));
this.items.add(new Item(5, true, "Harry Potter and the Order of the Phoenix", "J.K. Rowling", LocalDate.of(2003, 6, 21)));
this.items.add(new Item(6, true, "Harry Potter and the Half-Blood Prince", "J.K. Rowling", LocalDate.of(2005, 7, 16)));
this.items.add(new Item(7, true, "Harry Potter and the Deathly Hallows", "J.K. Rowling", LocalDate.of(2007, 7, 21)));
}
}
// return collection of users
public List<Member> getMember() {
return members;
}
public List<Item> getAllItems() {
return items;
}
public List<Member> getAllMembers(){
return members;
}
public Item getItem(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return item;
}
}
return null;
}
// make method to check if itemcode and member are in database
public boolean checkItemCodeAndMember(int itemCode, int memberID) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
// check if member is in database
for (Member existingMember : members) {
if (existingMember.getMemberID() == memberID) {
return true;
}
}
}
}
return false;
}
// make method to check if itemcode is in database
public boolean checkItemCode(int itemCode) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return true;
}
}
return false;
}
// make method to calculate overdue days
public int calculateOverdueDays(int itemCode) {
// get lending date
LocalDate lendingDate = null;
for (Item item : items) {
if (item.getItemCode() == itemCode) {
lendingDate = item.getLendingDate();
}
}
// calculate overdue days
LocalDate today = LocalDate.now();
return today.getDayOfYear() - lendingDate.getDayOfYear();
}
public void lentItem (int itemCode, int memberID) {
if (checkItemCodeAndMember(itemCode, memberID)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(false);
item.setLendingDate(LocalDate.now());
return;
}
}
}
}
public boolean receivedItem(int itemCode) {
if (checkItemCode(itemCode)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(true);
/* item.setLendingDate(null);*/ // dit moet nog worden aangepast, als dat mogelijk is. Null veroorzaakt error.
return true;
}
}
}
return false;
}
//check if item is already lent
public boolean checkIfItemIsAlreadyLent(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && !item.getAvailability()) {
return true;
}
}
return false;
}
// check if item is already received
public boolean checkIfItemIsAlreadyReceived(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && item.getAvailability()) {
return true;
}
}
return false;
}
// add new item to database
public void addItem(Item item) {
item.setItemCode(this.generateItemCode());
items.add(item);
}
public void addMember(Member member) {
member.setMemberID(this.generateMemberID());
members.add(member);
}
public void editItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
existingItem.setTitle(item.getTitle());
existingItem.setAuthor(item.getAuthor());
}
}
}
public void editMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
existingMember.setFirstname(member.getFirstname());
existingMember.setLastname(member.getLastname());
existingMember.setDateOfBirth(member.getDateOfBirth());
}
}
}
// delete item from database
public void deleteItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
items.remove(existingItem);
return;
}
}
}
public void deleteMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
members.remove(existingMember);
return;
}
}
}
// auto generated itemcode
public int generateItemCode() {
int itemCode = 0;
for (Item item : items) {
if (item.getItemCode() > itemCode) {
itemCode = item.getItemCode();
}
}
return itemCode + 1;
//return items.size() + 1;
}
public int generateMemberID() {
int memberID = 0;
for (Member member : members) {
if (member.getMemberID() > memberID) {
memberID = member.getMemberID();
}
}
return memberID + 1;
}
// save data for items
private void saveDataForItems() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("items.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all items
for (Item item : items) {
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// save data for members and serialize
private void saveDataForMembers() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("members.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all members
for (Member member : members) {
objectOutputStream.writeObject(member);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveData() {
saveDataForItems();
saveDataForMembers();
}
// load data for items
public void loadDataForItems() throws IOException{
try {
FileInputStream fileInputStream = new FileInputStream("items.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all items
while (true) {
try {
Item item = (Item) objectInputStream.readObject();
items.add(item);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
// load data for members
public void loadDataForMembers() throws IOException {
try {
FileInputStream fileInputStream = new FileInputStream("members.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all members
while (true) {
try {
Member member = (Member) objectInputStream.readObject();
members.add(member);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| LarsHartendorp/JavaEindopdracht | eindOpdrachtJavaFX/src/main/java/inholland/nl/eindopdrachtjavafx/DAL/Database.java | 2,783 | // dit moet nog worden aangepast, als dat mogelijk is. Null veroorzaakt error. | line_comment | nl | package inholland.nl.eindopdrachtjavafx.DAL;
import inholland.nl.eindopdrachtjavafx.Models.Item;
import inholland.nl.eindopdrachtjavafx.Models.Member;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Database {
private List<Member> members;
private List<Item> items;
public Database() {
this.members = new ArrayList<>();
this.items = new ArrayList<>();
try {
loadDataForMembers();
loadDataForItems();
} catch (IOException e) {
// add users to collection
this.members.add(new Member(1, "Lars","Lars", "H", "Lars H", LocalDate.of(1990, 1, 1), "1234"));
this.members.add(new Member(2, "Test","Jane", "Doe", "Jane Doe", LocalDate.of(1994, 6, 15), "0000"));
this.members.add(new Member(3, "John","John", "Smith", "John Smith", LocalDate.of(1992, 3, 12), "1234"));
this.members.add(new Member(4, "Jane2","Jane", "Smith", "Jane Smith", LocalDate.of(1995, 8, 23), "5678"));
this.members.add(new Member(5, "John2","John", "Doe", "John Doe", LocalDate.of(1990, 1, 1), "2378"));
// add items to collection
this.items.add(new Item(1, true, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", LocalDate.of(1997, 6, 26)));
this.items.add(new Item(2, true, "Harry Potter and the Chamber of Secrets", "J.K. Rowling", LocalDate.of(1998, 7, 2)));
this.items.add(new Item(3, true, "Harry Potter and the Prisoner of Azkaban", "J.K. Rowling", LocalDate.of(1999, 7, 8)));
this.items.add(new Item(4, true, "Harry Potter and the Goblet of Fire", "J.K. Rowling", LocalDate.of(2000, 7, 8)));
this.items.add(new Item(5, true, "Harry Potter and the Order of the Phoenix", "J.K. Rowling", LocalDate.of(2003, 6, 21)));
this.items.add(new Item(6, true, "Harry Potter and the Half-Blood Prince", "J.K. Rowling", LocalDate.of(2005, 7, 16)));
this.items.add(new Item(7, true, "Harry Potter and the Deathly Hallows", "J.K. Rowling", LocalDate.of(2007, 7, 21)));
}
}
// return collection of users
public List<Member> getMember() {
return members;
}
public List<Item> getAllItems() {
return items;
}
public List<Member> getAllMembers(){
return members;
}
public Item getItem(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return item;
}
}
return null;
}
// make method to check if itemcode and member are in database
public boolean checkItemCodeAndMember(int itemCode, int memberID) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
// check if member is in database
for (Member existingMember : members) {
if (existingMember.getMemberID() == memberID) {
return true;
}
}
}
}
return false;
}
// make method to check if itemcode is in database
public boolean checkItemCode(int itemCode) {
// check if itemcode is in database
for (Item item : items) {
if (item.getItemCode() == itemCode) {
return true;
}
}
return false;
}
// make method to calculate overdue days
public int calculateOverdueDays(int itemCode) {
// get lending date
LocalDate lendingDate = null;
for (Item item : items) {
if (item.getItemCode() == itemCode) {
lendingDate = item.getLendingDate();
}
}
// calculate overdue days
LocalDate today = LocalDate.now();
return today.getDayOfYear() - lendingDate.getDayOfYear();
}
public void lentItem (int itemCode, int memberID) {
if (checkItemCodeAndMember(itemCode, memberID)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(false);
item.setLendingDate(LocalDate.now());
return;
}
}
}
}
public boolean receivedItem(int itemCode) {
if (checkItemCode(itemCode)) {
for (Item item : items) {
if (item.getItemCode() == itemCode) {
item.setAvailability(true);
/* item.setLendingDate(null);*/ // dit moet<SUF>
return true;
}
}
}
return false;
}
//check if item is already lent
public boolean checkIfItemIsAlreadyLent(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && !item.getAvailability()) {
return true;
}
}
return false;
}
// check if item is already received
public boolean checkIfItemIsAlreadyReceived(int itemCode) {
for (Item item : items) {
if (item.getItemCode() == itemCode && item.getAvailability()) {
return true;
}
}
return false;
}
// add new item to database
public void addItem(Item item) {
item.setItemCode(this.generateItemCode());
items.add(item);
}
public void addMember(Member member) {
member.setMemberID(this.generateMemberID());
members.add(member);
}
public void editItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
existingItem.setTitle(item.getTitle());
existingItem.setAuthor(item.getAuthor());
}
}
}
public void editMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
existingMember.setFirstname(member.getFirstname());
existingMember.setLastname(member.getLastname());
existingMember.setDateOfBirth(member.getDateOfBirth());
}
}
}
// delete item from database
public void deleteItem(Item item) {
for (Item existingItem : items) {
if (existingItem.getItemCode() == item.getItemCode()) {
items.remove(existingItem);
return;
}
}
}
public void deleteMember(Member member) {
for (Member existingMember : members) {
if (existingMember.getMemberID() == member.getMemberID()) {
members.remove(existingMember);
return;
}
}
}
// auto generated itemcode
public int generateItemCode() {
int itemCode = 0;
for (Item item : items) {
if (item.getItemCode() > itemCode) {
itemCode = item.getItemCode();
}
}
return itemCode + 1;
//return items.size() + 1;
}
public int generateMemberID() {
int memberID = 0;
for (Member member : members) {
if (member.getMemberID() > memberID) {
memberID = member.getMemberID();
}
}
return memberID + 1;
}
// save data for items
private void saveDataForItems() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("items.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all items
for (Item item : items) {
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// save data for members and serialize
private void saveDataForMembers() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("members.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
// write loop for all members
for (Member member : members) {
objectOutputStream.writeObject(member);
}
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveData() {
saveDataForItems();
saveDataForMembers();
}
// load data for items
public void loadDataForItems() throws IOException{
try {
FileInputStream fileInputStream = new FileInputStream("items.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all items
while (true) {
try {
Item item = (Item) objectInputStream.readObject();
items.add(item);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
// load data for members
public void loadDataForMembers() throws IOException {
try {
FileInputStream fileInputStream = new FileInputStream("members.dat");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// read loop for all members
while (true) {
try {
Member member = (Member) objectInputStream.readObject();
members.add(member);
} catch (EOFException e) {
break;
}
}
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
129168_0 | package net.larsmans.infinitybuttons.block.custom.button;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.larsmans.infinitybuttons.InfinityButtonsInit;
import net.larsmans.infinitybuttons.InfinityButtonsUtil;
import net.larsmans.infinitybuttons.particle.InfinityButtonsParticleTypes;
import net.minecraft.block.BlockState;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Random;
public class DiamondButton extends AbstractSmallButton {
private final boolean large;
public DiamondButton(FabricBlockSettings settings, boolean large) {
super(false, large, settings);
this.large = large;
}
@Override
public int getPressTicks() {
return 20;
}
@Override
protected SoundEvent getClickSound(boolean var1) {
return var1 ? SoundEvents.BLOCK_STONE_BUTTON_CLICK_ON : SoundEvents.BLOCK_STONE_BUTTON_CLICK_OFF;
}
@Override
public void randomDisplayTick(BlockState state, World world, BlockPos pos, Random random) {
if (InfinityButtonsInit.config.diamondParticles && random.nextInt(3) == 0) {
if (large) {
switch (state.get(FACE)) {
case FLOOR -> addParticle(3, 10, 2, 1, 3, 10, world, pos, random);
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(3, 10, 3, 10, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 3, 10, 3, 10, world, pos, random);
case SOUTH -> addParticle(3, 10, 3, 10, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 3, 10, 3, 10, world, pos, random);
}
}
case CEILING -> addParticle(3, 10, 13, 1, 3, 10, world, pos, random);
}
} else {
switch (state.get(FACE)) {
case FLOOR -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 2, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 2, 1, 4, 8, world, pos, random);
}
}
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(4, 8, 5, 6, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 5, 6, 4, 8, world, pos, random);
case SOUTH -> addParticle(4, 8, 5, 6, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 5, 6, 4, 8, world, pos, random);
}
}
case CEILING -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 13, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 13, 1, 4, 8, world, pos, random);
}
}
}
}
}
}
public void addParticle(int x1, int x2, int y1, int y2, int z1, int z2, World world, BlockPos pos, Random random) {
// we kunnen het in de rewrite met een VoxelShape doen en ook draaien enzo :)
world.addParticle(InfinityButtonsParticleTypes.DIAMOND_SPARKLE,
pos.getX() + (double) x1 / 16 + random.nextFloat() * (double) x2 / 16,
pos.getY() + (double) y1 / 16 + random.nextFloat() * (double) y2 / 16,
pos.getZ() + (double) z1 / 16 + random.nextFloat() * (double) z2 / 16,
0, 0, 0);
}
@Override
public void appendTooltip(ItemStack stack, @Nullable BlockView world, List<Text> tooltip, TooltipContext options) {
InfinityButtonsUtil.tooltip(tooltip, "diamond_button");
}
}
| LarsMans64/InfinityButtons1.18.2 | src/main/java/net/larsmans/infinitybuttons/block/custom/button/DiamondButton.java | 1,408 | // we kunnen het in de rewrite met een VoxelShape doen en ook draaien enzo :) | line_comment | nl | package net.larsmans.infinitybuttons.block.custom.button;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.larsmans.infinitybuttons.InfinityButtonsInit;
import net.larsmans.infinitybuttons.InfinityButtonsUtil;
import net.larsmans.infinitybuttons.particle.InfinityButtonsParticleTypes;
import net.minecraft.block.BlockState;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Random;
public class DiamondButton extends AbstractSmallButton {
private final boolean large;
public DiamondButton(FabricBlockSettings settings, boolean large) {
super(false, large, settings);
this.large = large;
}
@Override
public int getPressTicks() {
return 20;
}
@Override
protected SoundEvent getClickSound(boolean var1) {
return var1 ? SoundEvents.BLOCK_STONE_BUTTON_CLICK_ON : SoundEvents.BLOCK_STONE_BUTTON_CLICK_OFF;
}
@Override
public void randomDisplayTick(BlockState state, World world, BlockPos pos, Random random) {
if (InfinityButtonsInit.config.diamondParticles && random.nextInt(3) == 0) {
if (large) {
switch (state.get(FACE)) {
case FLOOR -> addParticle(3, 10, 2, 1, 3, 10, world, pos, random);
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(3, 10, 3, 10, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 3, 10, 3, 10, world, pos, random);
case SOUTH -> addParticle(3, 10, 3, 10, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 3, 10, 3, 10, world, pos, random);
}
}
case CEILING -> addParticle(3, 10, 13, 1, 3, 10, world, pos, random);
}
} else {
switch (state.get(FACE)) {
case FLOOR -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 2, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 2, 1, 4, 8, world, pos, random);
}
}
case WALL -> {
switch (state.get(FACING)) {
case NORTH -> addParticle(4, 8, 5, 6, 13, 1, world, pos, random);
case EAST -> addParticle(2, 1, 5, 6, 4, 8, world, pos, random);
case SOUTH -> addParticle(4, 8, 5, 6, 2, 1, world, pos, random);
case WEST -> addParticle(13, 1, 5, 6, 4, 8, world, pos, random);
}
}
case CEILING -> {
switch (state.get(FACING)) {
case NORTH, SOUTH -> addParticle(4, 8, 13, 1, 5, 6, world, pos, random);
case EAST, WEST -> addParticle(5, 6, 13, 1, 4, 8, world, pos, random);
}
}
}
}
}
}
public void addParticle(int x1, int x2, int y1, int y2, int z1, int z2, World world, BlockPos pos, Random random) {
// we kunnen<SUF>
world.addParticle(InfinityButtonsParticleTypes.DIAMOND_SPARKLE,
pos.getX() + (double) x1 / 16 + random.nextFloat() * (double) x2 / 16,
pos.getY() + (double) y1 / 16 + random.nextFloat() * (double) y2 / 16,
pos.getZ() + (double) z1 / 16 + random.nextFloat() * (double) z2 / 16,
0, 0, 0);
}
@Override
public void appendTooltip(ItemStack stack, @Nullable BlockView world, List<Text> tooltip, TooltipContext options) {
InfinityButtonsUtil.tooltip(tooltip, "diamond_button");
}
}
|
190590_3 | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| Laugslander/fontys-swipe | app/src/main/java/nl/fontys/smpt42_1/fontysswipe/controller/CompareController.java | 1,492 | /**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/ | block_comment | nl | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode<SUF>*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
|
97801_0 | package gui.screens;
import domein.DomeinController;
import gui.company.CompanyCardComponent;
import gui.components.CustomMenu;
import gui.components.LanguageBundle;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXCheckbox;
import io.github.palexdev.materialfx.controls.MFXScrollPane;
import io.github.palexdev.materialfx.controls.MFXSlider;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import resources.ResourceController;
import java.util.Locale;
public class SettingScreen extends MFXScrollPane {
private DomeinController dc;
private ResourceController rs;
private BorderPane root;
private CustomMenu menu;
private VBox pane = new VBox();
private ComboBox<String> languageComboBox;
private static Label title;
private static MFXCheckbox checkbox;
private static Label soundLabel;
private static Label languageLabel;
public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) {
this.dc = dc;
pane.setAlignment(Pos.TOP_CENTER);
pane.setSpacing(200);
this.rs = rs;
this.root = root;
this.menu = menu;
this.setContent(pane);
this.setFitToHeight(true);
this.setFitToWidth(true);
setup();
}
public void setup() {
title = new Label(LanguageBundle.getString("SettingScreen_setting"));
title.getStyleClass().add("title");
soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound"));
VBox layoutBox = new VBox();
MFXSlider slider = new MFXSlider();
slider.setMin(0);
slider.setMax(100);
slider.setValue(rs.getCurrentVolume()*100);
slider.setOnMouseReleased(e -> {
System.out.println(slider.getValue());
rs.changeVolume(slider.getValue());
});
languageLabel = new Label("Language");
languageComboBox = new ComboBox<>();
HBox.setHgrow(languageComboBox, Priority.ALWAYS);
languageComboBox.getItems().addAll("en", "nl");
languageComboBox.setValue("en");
// voeg een listener toe aan de ComboBox om de taal te wijzigen
languageComboBox.setOnAction(e -> switchLanguage());
layoutBox.setAlignment(Pos.CENTER);
checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute"));
checkbox.setSelected(rs.isMute());
checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected()));
layoutBox.setSpacing(20);
layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox);
pane.getChildren().addAll(title, layoutBox);
}
private void switchLanguage() {
Locale selectedLocale;
String selectedLanguage = languageComboBox.getValue();
if (selectedLanguage.equals("en")) {
selectedLocale = new Locale("en");
} else {
selectedLocale = new Locale("nl");
}
// Wijzig de taal in de hele applicatie
LanguageBundle.setLocale(selectedLocale);
//update taal van pagina waarop je staat
updateText();
/*LoginScreen.updateText();
MainScreen.updateText();
CompanyCardComponent.updateText();
NotificationScreen.updateText();
OrderScreen.updateText();
TransportDienstScreen.updateText();
RegisterScreen.updateText();
MyProductsScreen.updateText();*/
}
public static void updateText() {
title.setText(LanguageBundle.getString("SettingScreen_setting"));
checkbox.setText(LanguageBundle.getString("SettingScreen_mute"));
soundLabel.setText(LanguageBundle.getString("SettingScreen_sound"));
}
}
| LaurensDM/Webshop-desktop | src/main/java/gui/screens/SettingScreen.java | 1,144 | // voeg een listener toe aan de ComboBox om de taal te wijzigen | line_comment | nl | package gui.screens;
import domein.DomeinController;
import gui.company.CompanyCardComponent;
import gui.components.CustomMenu;
import gui.components.LanguageBundle;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXCheckbox;
import io.github.palexdev.materialfx.controls.MFXScrollPane;
import io.github.palexdev.materialfx.controls.MFXSlider;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import resources.ResourceController;
import java.util.Locale;
public class SettingScreen extends MFXScrollPane {
private DomeinController dc;
private ResourceController rs;
private BorderPane root;
private CustomMenu menu;
private VBox pane = new VBox();
private ComboBox<String> languageComboBox;
private static Label title;
private static MFXCheckbox checkbox;
private static Label soundLabel;
private static Label languageLabel;
public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) {
this.dc = dc;
pane.setAlignment(Pos.TOP_CENTER);
pane.setSpacing(200);
this.rs = rs;
this.root = root;
this.menu = menu;
this.setContent(pane);
this.setFitToHeight(true);
this.setFitToWidth(true);
setup();
}
public void setup() {
title = new Label(LanguageBundle.getString("SettingScreen_setting"));
title.getStyleClass().add("title");
soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound"));
VBox layoutBox = new VBox();
MFXSlider slider = new MFXSlider();
slider.setMin(0);
slider.setMax(100);
slider.setValue(rs.getCurrentVolume()*100);
slider.setOnMouseReleased(e -> {
System.out.println(slider.getValue());
rs.changeVolume(slider.getValue());
});
languageLabel = new Label("Language");
languageComboBox = new ComboBox<>();
HBox.setHgrow(languageComboBox, Priority.ALWAYS);
languageComboBox.getItems().addAll("en", "nl");
languageComboBox.setValue("en");
// voeg een<SUF>
languageComboBox.setOnAction(e -> switchLanguage());
layoutBox.setAlignment(Pos.CENTER);
checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute"));
checkbox.setSelected(rs.isMute());
checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected()));
layoutBox.setSpacing(20);
layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox);
pane.getChildren().addAll(title, layoutBox);
}
private void switchLanguage() {
Locale selectedLocale;
String selectedLanguage = languageComboBox.getValue();
if (selectedLanguage.equals("en")) {
selectedLocale = new Locale("en");
} else {
selectedLocale = new Locale("nl");
}
// Wijzig de taal in de hele applicatie
LanguageBundle.setLocale(selectedLocale);
//update taal van pagina waarop je staat
updateText();
/*LoginScreen.updateText();
MainScreen.updateText();
CompanyCardComponent.updateText();
NotificationScreen.updateText();
OrderScreen.updateText();
TransportDienstScreen.updateText();
RegisterScreen.updateText();
MyProductsScreen.updateText();*/
}
public static void updateText() {
title.setText(LanguageBundle.getString("SettingScreen_setting"));
checkbox.setText(LanguageBundle.getString("SettingScreen_mute"));
soundLabel.setText(LanguageBundle.getString("SettingScreen_sound"));
}
}
|
45052_11 | package be.khleuven.nieuws;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
public class KHLLoginActivity extends Activity {
/**
* De webview wat gebruikt wordt.
*/
WebView myWebView;
/**
* De url die bijgehouden wordt in de preferences wordt hier in gezet.
*/
String mFeedUrl = null;
public static final String PREFS_NAME = "MyPrefsFile";
/**
* Hierin wordt de url opgeslagen.
*/
static SharedPreferences settings;
/**
* Editor voor aanpassen van data in SharedPreferences.
*/
SharedPreferences.Editor editor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
mFeedUrl = settings.getString("feedUrl", null);
if (mFeedUrl != null) {
openRSS(mFeedUrl);
} else {
/**
* Deze klasse wordt gebruikt als interface tussen de java en
* javascriptcode die gebruikt wordt bij de webview
*
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
class MyJavaScriptInterface {
/**
* Verwerkt de html code en opent dan de KHLNieuwsActivity.
* Wordt aangeroepen vanuit de javascriptcode.
*
* @param html
* De string die de htmlcode van de pagina bevat.
*/
@SuppressWarnings("unused")
public void processHTML(String html) {
String link = fetchLink(html);
editor.putString("feedUrl", link);
editor.commit();
openRSS(link);
}
/**
* Deze functie doorzoekt de htmlcode naar een geldige RSS-link.
*
* @param html
* De string die de htmlcode van de pagina bevat.
* @return De juiste url van de RSS-feed.
*/
private String fetchLink(String html) {
String[] temp;
temp = html.split("\n");
String link = "";
boolean stop = false;
try {
for (String t : temp) {
if (t.contains("<a href=\"http://portaal.khleuven.be/rss.php")) {
link = t;
stop = true;
}
if (stop)
break;
}
} catch (Exception e) {
} finally {
if (link != null) {
String[] parts = link.split("\"");
link = parts[1];
}
}
return link;
}
}
// cookie bijhouden
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
// webview gebruiken voor login
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
// wat doen wanneer pagina geladen is
// checken of ingelogd door te kijken of we terug op de
// portaalsite zitten
public void onPageFinished(WebView view, String url) {
if (view.getUrl().equals("https://portaal.khleuven.be/")) {
view.loadUrl("javascript:window.interfaceName.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (url.equals("https://portaal.khleuven.be/")) {
view.setVisibility(View.INVISIBLE);
ProgressDialog.show(
KHLLoginActivity.this, "",
"Fetching RSS. Please wait...", true);
}
}
});
myWebView.getSettings().setDatabasePath("khl.news");
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.addJavascriptInterface(new MyJavaScriptInterface(),
"interfaceName");
myWebView
.loadUrl("https://portaal.khleuven.be/Shibboleth.sso/WAYF/khleuven?target=https%3A%2F%2Fportaal.khleuven.be%2F");
}
}
private void openRSS(String link) {
Intent intent = new Intent(getApplicationContext(),
KHLNieuwsActivity.class);
intent.putExtra("feedUrl", link);
startActivity(intent);
}
} | LaurentMouha/KHLNieuws | src/be/khleuven/nieuws/KHLLoginActivity.java | 1,583 | // checken of ingelogd door te kijken of we terug op de
| line_comment | nl | package be.khleuven.nieuws;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
public class KHLLoginActivity extends Activity {
/**
* De webview wat gebruikt wordt.
*/
WebView myWebView;
/**
* De url die bijgehouden wordt in de preferences wordt hier in gezet.
*/
String mFeedUrl = null;
public static final String PREFS_NAME = "MyPrefsFile";
/**
* Hierin wordt de url opgeslagen.
*/
static SharedPreferences settings;
/**
* Editor voor aanpassen van data in SharedPreferences.
*/
SharedPreferences.Editor editor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
mFeedUrl = settings.getString("feedUrl", null);
if (mFeedUrl != null) {
openRSS(mFeedUrl);
} else {
/**
* Deze klasse wordt gebruikt als interface tussen de java en
* javascriptcode die gebruikt wordt bij de webview
*
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
class MyJavaScriptInterface {
/**
* Verwerkt de html code en opent dan de KHLNieuwsActivity.
* Wordt aangeroepen vanuit de javascriptcode.
*
* @param html
* De string die de htmlcode van de pagina bevat.
*/
@SuppressWarnings("unused")
public void processHTML(String html) {
String link = fetchLink(html);
editor.putString("feedUrl", link);
editor.commit();
openRSS(link);
}
/**
* Deze functie doorzoekt de htmlcode naar een geldige RSS-link.
*
* @param html
* De string die de htmlcode van de pagina bevat.
* @return De juiste url van de RSS-feed.
*/
private String fetchLink(String html) {
String[] temp;
temp = html.split("\n");
String link = "";
boolean stop = false;
try {
for (String t : temp) {
if (t.contains("<a href=\"http://portaal.khleuven.be/rss.php")) {
link = t;
stop = true;
}
if (stop)
break;
}
} catch (Exception e) {
} finally {
if (link != null) {
String[] parts = link.split("\"");
link = parts[1];
}
}
return link;
}
}
// cookie bijhouden
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
// webview gebruiken voor login
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
// wat doen wanneer pagina geladen is
// checken of<SUF>
// portaalsite zitten
public void onPageFinished(WebView view, String url) {
if (view.getUrl().equals("https://portaal.khleuven.be/")) {
view.loadUrl("javascript:window.interfaceName.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (url.equals("https://portaal.khleuven.be/")) {
view.setVisibility(View.INVISIBLE);
ProgressDialog.show(
KHLLoginActivity.this, "",
"Fetching RSS. Please wait...", true);
}
}
});
myWebView.getSettings().setDatabasePath("khl.news");
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.addJavascriptInterface(new MyJavaScriptInterface(),
"interfaceName");
myWebView
.loadUrl("https://portaal.khleuven.be/Shibboleth.sso/WAYF/khleuven?target=https%3A%2F%2Fportaal.khleuven.be%2F");
}
}
private void openRSS(String link) {
Intent intent = new Intent(getApplicationContext(),
KHLNieuwsActivity.class);
intent.putExtra("feedUrl", link);
startActivity(intent);
}
} |
8913_5 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.android.launcher3.util;
import static android.content.Intent.ACTION_CONFIGURATION_CHANGED;
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
import static com.android.launcher3.LauncherPrefs.TASKBAR_PINNING;
import static com.android.launcher3.Utilities.dpiFromPx;
import static com.android.launcher3.config.FeatureFlags.ENABLE_TASKBAR_PINNING;
import static com.android.launcher3.config.FeatureFlags.ENABLE_TRANSIENT_TASKBAR;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.FlagDebugUtils.appendFlag;
import static com.android.launcher3.util.window.WindowManagerProxy.MIN_TABLET_WIDTH;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
import android.view.Display;
import androidx.annotation.AnyThread;
import androidx.annotation.UiThread;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.Utilities;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.util.window.CachedDisplayInfo;
import com.android.launcher3.util.window.WindowManagerProxy;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
/**
* Utility class to cache properties of default display to avoid a system RPC on
* every call.
*/
@SuppressLint("NewApi")
public class DisplayController implements ComponentCallbacks, SafeCloseable {
private static final String TAG = "DisplayController";
private static final boolean DEBUG = false;
private static boolean sTransientTaskbarStatusForTests;
// TODO(b/254119092) remove all logs with this tag
public static final String TASKBAR_NOT_DESTROYED_TAG = "b/254119092";
public static final MainThreadInitializedObject<DisplayController> INSTANCE = new MainThreadInitializedObject<>(
DisplayController::new);
public static final int CHANGE_ACTIVE_SCREEN = 1 << 0;
public static final int CHANGE_ROTATION = 1 << 1;
public static final int CHANGE_DENSITY = 1 << 2;
public static final int CHANGE_SUPPORTED_BOUNDS = 1 << 3;
public static final int CHANGE_NAVIGATION_MODE = 1 << 4;
public static final int CHANGE_ALL = CHANGE_ACTIVE_SCREEN | CHANGE_ROTATION
| CHANGE_DENSITY | CHANGE_SUPPORTED_BOUNDS | CHANGE_NAVIGATION_MODE;
private static final String ACTION_OVERLAY_CHANGED = "android.intent.action.OVERLAY_CHANGED";
private static final String TARGET_OVERLAY_PACKAGE = "android";
private final Context mContext;
private final DisplayManager mDM;
// Null for SDK < S
private final Context mWindowContext;
// The callback in this listener updates DeviceProfile, which other listeners
// might depend on
private DisplayInfoChangeListener mPriorityListener;
private final ArrayList<DisplayInfoChangeListener> mListeners = new ArrayList<>();
private final SimpleBroadcastReceiver mReceiver = new SimpleBroadcastReceiver(this::onIntent);
private Info mInfo;
private boolean mDestroyed = false;
private final LauncherPrefs mPrefs;
@VisibleForTesting
protected DisplayController(Context context) {
mContext = context;
mDM = context.getSystemService(DisplayManager.class);
mPrefs = LauncherPrefs.get(context);
Display display = mDM.getDisplay(DEFAULT_DISPLAY);
if (Utilities.ATLEAST_S) {
mWindowContext = mContext.createWindowContext(display, TYPE_APPLICATION, null);
mWindowContext.registerComponentCallbacks(this);
} else {
mWindowContext = null;
mReceiver.register(mContext, ACTION_CONFIGURATION_CHANGED);
}
// Initialize navigation mode change listener
mReceiver.registerPkgActions(mContext, TARGET_OVERLAY_PACKAGE, ACTION_OVERLAY_CHANGED);
WindowManagerProxy wmProxy = WindowManagerProxy.INSTANCE.get(context);
Context displayInfoContext = getDisplayInfoContext(display);
mInfo = new Info(displayInfoContext, wmProxy,
wmProxy.estimateInternalDisplayBounds(displayInfoContext));
FileLog.i(TAG, "(CTOR) perDisplayBounds: " + mInfo.mPerDisplayBounds);
}
/**
* Returns the current navigation mode
*/
public static NavigationMode getNavigationMode(Context context) {
return INSTANCE.get(context).getInfo().navigationMode;
}
/**
* Returns whether taskbar is transient.
*/
public static boolean isTransientTaskbar(Context context) {
return INSTANCE.get(context).isTransientTaskbar();
}
/**
* Returns whether taskbar is transient.
*/
public boolean isTransientTaskbar() {
// TODO(b/258604917): When running in test harness, use
// !sTransientTaskbarStatusForTests
// once tests are updated to expect new persistent behavior such as not allowing
// long press
// to stash.
if (!Utilities.isRunningInTestHarness()
&& ENABLE_TASKBAR_PINNING.get()
&& mPrefs.get(TASKBAR_PINNING)) {
return false;
}
return getInfo().navigationMode == NavigationMode.NO_BUTTON
&& (Utilities.isRunningInTestHarness()
? sTransientTaskbarStatusForTests
: ENABLE_TRANSIENT_TASKBAR.get());
}
/**
* Enables transient taskbar status for tests.
*/
@VisibleForTesting
public static void enableTransientTaskbarForTests(boolean enable) {
sTransientTaskbarStatusForTests = enable;
}
@Override
public void close() {
mDestroyed = true;
if (mWindowContext != null) {
mWindowContext.unregisterComponentCallbacks(this);
} else {
// TODO: unregister broadcast receiver
}
}
/**
* Interface for listening for display changes
*/
public interface DisplayInfoChangeListener {
/**
* Invoked when display info has changed.
*
* @param context updated context associated with the display.
* @param info updated display information.
* @param flags bitmask indicating type of change.
*/
void onDisplayInfoChanged(Context context, Info info, int flags);
}
private void onIntent(Intent intent) {
if (mDestroyed) {
return;
}
boolean reconfigure = false;
if (ACTION_OVERLAY_CHANGED.equals(intent.getAction())) {
reconfigure = true;
} else if (ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) {
Configuration config = mContext.getResources().getConfiguration();
reconfigure = mInfo.fontScale != config.fontScale
|| mInfo.densityDpi != config.densityDpi;
}
if (reconfigure) {
Log.d(TAG, "Configuration changed, notifying listeners");
Display display = mDM.getDisplay(DEFAULT_DISPLAY);
if (display != null) {
handleInfoChange(display);
}
}
}
@UiThread
@Override
@TargetApi(Build.VERSION_CODES.S)
public final void onConfigurationChanged(Configuration config) {
Log.d(TASKBAR_NOT_DESTROYED_TAG, "DisplayController#onConfigurationChanged: " + config);
Display display = mWindowContext.getDisplay();
if (config.densityDpi != mInfo.densityDpi
|| config.fontScale != mInfo.fontScale
|| display.getRotation() != mInfo.rotation
|| !mInfo.mScreenSizeDp.equals(
new PortraitSize(config.screenHeightDp, config.screenWidthDp))) {
handleInfoChange(display);
}
}
@Override
public final void onLowMemory() {
}
public void setPriorityListener(DisplayInfoChangeListener listener) {
mPriorityListener = listener;
}
public void addChangeListener(DisplayInfoChangeListener listener) {
mListeners.add(listener);
}
public void removeChangeListener(DisplayInfoChangeListener listener) {
mListeners.remove(listener);
}
public Info getInfo() {
return mInfo;
}
private Context getDisplayInfoContext(Display display) {
return Utilities.ATLEAST_S ? mWindowContext : mContext.createDisplayContext(display);
}
@AnyThread
private void handleInfoChange(Display display) {
WindowManagerProxy wmProxy = WindowManagerProxy.INSTANCE.get(mContext);
Info oldInfo = mInfo;
Context displayInfoContext = getDisplayInfoContext(display);
Info newInfo = new Info(displayInfoContext, wmProxy, oldInfo.mPerDisplayBounds);
if (newInfo.densityDpi != oldInfo.densityDpi || newInfo.fontScale != oldInfo.fontScale
|| newInfo.navigationMode != oldInfo.navigationMode) {
// Cache may not be valid anymore, recreate without cache
newInfo = new Info(displayInfoContext, wmProxy,
wmProxy.estimateInternalDisplayBounds(displayInfoContext));
}
int change = 0;
if (!newInfo.normalizedDisplayInfo.equals(oldInfo.normalizedDisplayInfo)) {
change |= CHANGE_ACTIVE_SCREEN;
}
if (newInfo.rotation != oldInfo.rotation) {
change |= CHANGE_ROTATION;
}
if (newInfo.densityDpi != oldInfo.densityDpi || newInfo.fontScale != oldInfo.fontScale) {
change |= CHANGE_DENSITY;
}
if (newInfo.navigationMode != oldInfo.navigationMode) {
change |= CHANGE_NAVIGATION_MODE;
}
if (!newInfo.supportedBounds.equals(oldInfo.supportedBounds)
|| !newInfo.mPerDisplayBounds.equals(oldInfo.mPerDisplayBounds)) {
change |= CHANGE_SUPPORTED_BOUNDS;
FileLog.w(TAG,
"(CHANGE_SUPPORTED_BOUNDS) perDisplayBounds: " + newInfo.mPerDisplayBounds);
}
if (DEBUG) {
Log.d(TAG, "handleInfoChange - change: " + getChangeFlagsString(change));
}
if (change != 0) {
mInfo = newInfo;
final int flags = change;
MAIN_EXECUTOR.execute(() -> notifyChange(displayInfoContext, flags));
}
}
private void notifyChange(Context context, int flags) {
if (mPriorityListener != null) {
mPriorityListener.onDisplayInfoChanged(context, mInfo, flags);
}
int count = mListeners.size();
for (int i = 0; i < count; i++) {
mListeners.get(i).onDisplayInfoChanged(context, mInfo, flags);
}
}
public static class Info {
// Cached property
public final CachedDisplayInfo normalizedDisplayInfo;
public final int rotation;
public final Point currentSize;
public final Rect cutout;
// Configuration property
public final float fontScale;
private final int densityDpi;
public final NavigationMode navigationMode;
private final PortraitSize mScreenSizeDp;
// WindowBounds
public final WindowBounds realBounds;
public final Set<WindowBounds> supportedBounds = new ArraySet<>();
private final ArrayMap<CachedDisplayInfo, List<WindowBounds>> mPerDisplayBounds = new ArrayMap<>();
public Info(Context displayInfoContext) {
/* don't need system overrides for external displays */
this(displayInfoContext, new WindowManagerProxy(), new ArrayMap<>());
}
// Used for testing
public Info(Context displayInfoContext,
WindowManagerProxy wmProxy,
Map<CachedDisplayInfo, List<WindowBounds>> perDisplayBoundsCache) {
CachedDisplayInfo displayInfo = wmProxy.getDisplayInfo(displayInfoContext);
normalizedDisplayInfo = displayInfo.normalize();
rotation = displayInfo.rotation;
currentSize = displayInfo.size;
cutout = displayInfo.cutout;
Configuration config = displayInfoContext.getResources().getConfiguration();
fontScale = config.fontScale;
densityDpi = config.densityDpi;
mScreenSizeDp = new PortraitSize(config.screenHeightDp, config.screenWidthDp);
navigationMode = wmProxy.getNavigationMode(displayInfoContext);
mPerDisplayBounds.putAll(perDisplayBoundsCache);
List<WindowBounds> cachedValue = mPerDisplayBounds.get(normalizedDisplayInfo);
realBounds = wmProxy.getRealBounds(displayInfoContext, displayInfo);
if (cachedValue == null) {
// Unexpected normalizedDisplayInfo is found, recreate the cache
FileLog.e(TAG, "Unexpected normalizedDisplayInfo found, invalidating cache: "
+ normalizedDisplayInfo);
FileLog.e(TAG, "(Invalid Cache) perDisplayBounds : " + mPerDisplayBounds);
mPerDisplayBounds.clear();
mPerDisplayBounds.putAll(wmProxy.estimateInternalDisplayBounds(displayInfoContext));
cachedValue = mPerDisplayBounds.get(normalizedDisplayInfo);
if (cachedValue == null) {
FileLog.e(TAG, "normalizedDisplayInfo not found in estimation: "
+ normalizedDisplayInfo);
supportedBounds.add(realBounds);
}
}
if (cachedValue != null) {
// Verify that the real bounds are a match
WindowBounds expectedBounds = cachedValue.get(displayInfo.rotation);
if (!realBounds.equals(expectedBounds)) {
List<WindowBounds> clone = new ArrayList<>(cachedValue);
clone.set(displayInfo.rotation, realBounds);
mPerDisplayBounds.put(normalizedDisplayInfo, clone);
}
}
mPerDisplayBounds.values().forEach(supportedBounds::addAll);
if (DEBUG) {
Log.d(TAG, "displayInfo: " + displayInfo);
Log.d(TAG, "realBounds: " + realBounds);
Log.d(TAG, "normalizedDisplayInfo: " + normalizedDisplayInfo);
Log.d(TAG, "perDisplayBounds: " + mPerDisplayBounds);
}
}
/**
* Returns {@code true} if the bounds represent a tablet.
*/
public boolean isTablet(WindowBounds bounds) {
return smallestSizeDp(bounds) >= MIN_TABLET_WIDTH;
}
/**
* Returns smallest size in dp for given bounds.
*/
public float smallestSizeDp(WindowBounds bounds) {
return dpiFromPx(Math.min(bounds.bounds.width(), bounds.bounds.height()), densityDpi);
}
/**
* Returns all displays for the device
*/
public Set<CachedDisplayInfo> getAllDisplays() {
return Collections.unmodifiableSet(mPerDisplayBounds.keySet());
}
public int getDensityDpi() {
return densityDpi;
}
}
/**
* Returns the given binary flags as a human-readable string.
*
* @see #CHANGE_ALL
*/
public String getChangeFlagsString(int change) {
StringJoiner result = new StringJoiner("|");
appendFlag(result, change, CHANGE_ACTIVE_SCREEN, "CHANGE_ACTIVE_SCREEN");
appendFlag(result, change, CHANGE_ROTATION, "CHANGE_ROTATION");
appendFlag(result, change, CHANGE_DENSITY, "CHANGE_DENSITY");
appendFlag(result, change, CHANGE_SUPPORTED_BOUNDS, "CHANGE_SUPPORTED_BOUNDS");
appendFlag(result, change, CHANGE_NAVIGATION_MODE, "CHANGE_NAVIGATION_MODE");
return result.toString();
}
/**
* Dumps the current state information
*/
public void dump(PrintWriter pw) {
Info info = mInfo;
pw.println("DisplayController.Info:");
pw.println(" normalizedDisplayInfo=" + info.normalizedDisplayInfo);
pw.println(" rotation=" + info.rotation);
pw.println(" fontScale=" + info.fontScale);
pw.println(" densityDpi=" + info.densityDpi);
pw.println(" navigationMode=" + info.navigationMode.name());
pw.println(" currentSize=" + info.currentSize);
info.mPerDisplayBounds.forEach((key, value) -> pw.println(
" perDisplayBounds - " + key + ": " + value));
}
/**
* Utility class to hold a size information in an orientation independent way
*/
public static class PortraitSize {
public final int width, height;
public PortraitSize(int w, int h) {
width = Math.min(w, h);
height = Math.max(w, h);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PortraitSize that = (PortraitSize) o;
return width == that.width && height == that.height;
}
@Override
public int hashCode() {
return Objects.hash(width, height);
}
}
}
| LawnchairLauncher/lawnchair | src/com/android/launcher3/util/DisplayController.java | 5,004 | // might depend on | line_comment | nl | /*
* Copyright (C) 2019 The Android Open Source Project
*
* 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.android.launcher3.util;
import static android.content.Intent.ACTION_CONFIGURATION_CHANGED;
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
import static com.android.launcher3.LauncherPrefs.TASKBAR_PINNING;
import static com.android.launcher3.Utilities.dpiFromPx;
import static com.android.launcher3.config.FeatureFlags.ENABLE_TASKBAR_PINNING;
import static com.android.launcher3.config.FeatureFlags.ENABLE_TRANSIENT_TASKBAR;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.FlagDebugUtils.appendFlag;
import static com.android.launcher3.util.window.WindowManagerProxy.MIN_TABLET_WIDTH;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
import android.view.Display;
import androidx.annotation.AnyThread;
import androidx.annotation.UiThread;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.Utilities;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.util.window.CachedDisplayInfo;
import com.android.launcher3.util.window.WindowManagerProxy;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
/**
* Utility class to cache properties of default display to avoid a system RPC on
* every call.
*/
@SuppressLint("NewApi")
public class DisplayController implements ComponentCallbacks, SafeCloseable {
private static final String TAG = "DisplayController";
private static final boolean DEBUG = false;
private static boolean sTransientTaskbarStatusForTests;
// TODO(b/254119092) remove all logs with this tag
public static final String TASKBAR_NOT_DESTROYED_TAG = "b/254119092";
public static final MainThreadInitializedObject<DisplayController> INSTANCE = new MainThreadInitializedObject<>(
DisplayController::new);
public static final int CHANGE_ACTIVE_SCREEN = 1 << 0;
public static final int CHANGE_ROTATION = 1 << 1;
public static final int CHANGE_DENSITY = 1 << 2;
public static final int CHANGE_SUPPORTED_BOUNDS = 1 << 3;
public static final int CHANGE_NAVIGATION_MODE = 1 << 4;
public static final int CHANGE_ALL = CHANGE_ACTIVE_SCREEN | CHANGE_ROTATION
| CHANGE_DENSITY | CHANGE_SUPPORTED_BOUNDS | CHANGE_NAVIGATION_MODE;
private static final String ACTION_OVERLAY_CHANGED = "android.intent.action.OVERLAY_CHANGED";
private static final String TARGET_OVERLAY_PACKAGE = "android";
private final Context mContext;
private final DisplayManager mDM;
// Null for SDK < S
private final Context mWindowContext;
// The callback in this listener updates DeviceProfile, which other listeners
// might depend<SUF>
private DisplayInfoChangeListener mPriorityListener;
private final ArrayList<DisplayInfoChangeListener> mListeners = new ArrayList<>();
private final SimpleBroadcastReceiver mReceiver = new SimpleBroadcastReceiver(this::onIntent);
private Info mInfo;
private boolean mDestroyed = false;
private final LauncherPrefs mPrefs;
@VisibleForTesting
protected DisplayController(Context context) {
mContext = context;
mDM = context.getSystemService(DisplayManager.class);
mPrefs = LauncherPrefs.get(context);
Display display = mDM.getDisplay(DEFAULT_DISPLAY);
if (Utilities.ATLEAST_S) {
mWindowContext = mContext.createWindowContext(display, TYPE_APPLICATION, null);
mWindowContext.registerComponentCallbacks(this);
} else {
mWindowContext = null;
mReceiver.register(mContext, ACTION_CONFIGURATION_CHANGED);
}
// Initialize navigation mode change listener
mReceiver.registerPkgActions(mContext, TARGET_OVERLAY_PACKAGE, ACTION_OVERLAY_CHANGED);
WindowManagerProxy wmProxy = WindowManagerProxy.INSTANCE.get(context);
Context displayInfoContext = getDisplayInfoContext(display);
mInfo = new Info(displayInfoContext, wmProxy,
wmProxy.estimateInternalDisplayBounds(displayInfoContext));
FileLog.i(TAG, "(CTOR) perDisplayBounds: " + mInfo.mPerDisplayBounds);
}
/**
* Returns the current navigation mode
*/
public static NavigationMode getNavigationMode(Context context) {
return INSTANCE.get(context).getInfo().navigationMode;
}
/**
* Returns whether taskbar is transient.
*/
public static boolean isTransientTaskbar(Context context) {
return INSTANCE.get(context).isTransientTaskbar();
}
/**
* Returns whether taskbar is transient.
*/
public boolean isTransientTaskbar() {
// TODO(b/258604917): When running in test harness, use
// !sTransientTaskbarStatusForTests
// once tests are updated to expect new persistent behavior such as not allowing
// long press
// to stash.
if (!Utilities.isRunningInTestHarness()
&& ENABLE_TASKBAR_PINNING.get()
&& mPrefs.get(TASKBAR_PINNING)) {
return false;
}
return getInfo().navigationMode == NavigationMode.NO_BUTTON
&& (Utilities.isRunningInTestHarness()
? sTransientTaskbarStatusForTests
: ENABLE_TRANSIENT_TASKBAR.get());
}
/**
* Enables transient taskbar status for tests.
*/
@VisibleForTesting
public static void enableTransientTaskbarForTests(boolean enable) {
sTransientTaskbarStatusForTests = enable;
}
@Override
public void close() {
mDestroyed = true;
if (mWindowContext != null) {
mWindowContext.unregisterComponentCallbacks(this);
} else {
// TODO: unregister broadcast receiver
}
}
/**
* Interface for listening for display changes
*/
public interface DisplayInfoChangeListener {
/**
* Invoked when display info has changed.
*
* @param context updated context associated with the display.
* @param info updated display information.
* @param flags bitmask indicating type of change.
*/
void onDisplayInfoChanged(Context context, Info info, int flags);
}
private void onIntent(Intent intent) {
if (mDestroyed) {
return;
}
boolean reconfigure = false;
if (ACTION_OVERLAY_CHANGED.equals(intent.getAction())) {
reconfigure = true;
} else if (ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) {
Configuration config = mContext.getResources().getConfiguration();
reconfigure = mInfo.fontScale != config.fontScale
|| mInfo.densityDpi != config.densityDpi;
}
if (reconfigure) {
Log.d(TAG, "Configuration changed, notifying listeners");
Display display = mDM.getDisplay(DEFAULT_DISPLAY);
if (display != null) {
handleInfoChange(display);
}
}
}
@UiThread
@Override
@TargetApi(Build.VERSION_CODES.S)
public final void onConfigurationChanged(Configuration config) {
Log.d(TASKBAR_NOT_DESTROYED_TAG, "DisplayController#onConfigurationChanged: " + config);
Display display = mWindowContext.getDisplay();
if (config.densityDpi != mInfo.densityDpi
|| config.fontScale != mInfo.fontScale
|| display.getRotation() != mInfo.rotation
|| !mInfo.mScreenSizeDp.equals(
new PortraitSize(config.screenHeightDp, config.screenWidthDp))) {
handleInfoChange(display);
}
}
@Override
public final void onLowMemory() {
}
public void setPriorityListener(DisplayInfoChangeListener listener) {
mPriorityListener = listener;
}
public void addChangeListener(DisplayInfoChangeListener listener) {
mListeners.add(listener);
}
public void removeChangeListener(DisplayInfoChangeListener listener) {
mListeners.remove(listener);
}
public Info getInfo() {
return mInfo;
}
private Context getDisplayInfoContext(Display display) {
return Utilities.ATLEAST_S ? mWindowContext : mContext.createDisplayContext(display);
}
@AnyThread
private void handleInfoChange(Display display) {
WindowManagerProxy wmProxy = WindowManagerProxy.INSTANCE.get(mContext);
Info oldInfo = mInfo;
Context displayInfoContext = getDisplayInfoContext(display);
Info newInfo = new Info(displayInfoContext, wmProxy, oldInfo.mPerDisplayBounds);
if (newInfo.densityDpi != oldInfo.densityDpi || newInfo.fontScale != oldInfo.fontScale
|| newInfo.navigationMode != oldInfo.navigationMode) {
// Cache may not be valid anymore, recreate without cache
newInfo = new Info(displayInfoContext, wmProxy,
wmProxy.estimateInternalDisplayBounds(displayInfoContext));
}
int change = 0;
if (!newInfo.normalizedDisplayInfo.equals(oldInfo.normalizedDisplayInfo)) {
change |= CHANGE_ACTIVE_SCREEN;
}
if (newInfo.rotation != oldInfo.rotation) {
change |= CHANGE_ROTATION;
}
if (newInfo.densityDpi != oldInfo.densityDpi || newInfo.fontScale != oldInfo.fontScale) {
change |= CHANGE_DENSITY;
}
if (newInfo.navigationMode != oldInfo.navigationMode) {
change |= CHANGE_NAVIGATION_MODE;
}
if (!newInfo.supportedBounds.equals(oldInfo.supportedBounds)
|| !newInfo.mPerDisplayBounds.equals(oldInfo.mPerDisplayBounds)) {
change |= CHANGE_SUPPORTED_BOUNDS;
FileLog.w(TAG,
"(CHANGE_SUPPORTED_BOUNDS) perDisplayBounds: " + newInfo.mPerDisplayBounds);
}
if (DEBUG) {
Log.d(TAG, "handleInfoChange - change: " + getChangeFlagsString(change));
}
if (change != 0) {
mInfo = newInfo;
final int flags = change;
MAIN_EXECUTOR.execute(() -> notifyChange(displayInfoContext, flags));
}
}
private void notifyChange(Context context, int flags) {
if (mPriorityListener != null) {
mPriorityListener.onDisplayInfoChanged(context, mInfo, flags);
}
int count = mListeners.size();
for (int i = 0; i < count; i++) {
mListeners.get(i).onDisplayInfoChanged(context, mInfo, flags);
}
}
public static class Info {
// Cached property
public final CachedDisplayInfo normalizedDisplayInfo;
public final int rotation;
public final Point currentSize;
public final Rect cutout;
// Configuration property
public final float fontScale;
private final int densityDpi;
public final NavigationMode navigationMode;
private final PortraitSize mScreenSizeDp;
// WindowBounds
public final WindowBounds realBounds;
public final Set<WindowBounds> supportedBounds = new ArraySet<>();
private final ArrayMap<CachedDisplayInfo, List<WindowBounds>> mPerDisplayBounds = new ArrayMap<>();
public Info(Context displayInfoContext) {
/* don't need system overrides for external displays */
this(displayInfoContext, new WindowManagerProxy(), new ArrayMap<>());
}
// Used for testing
public Info(Context displayInfoContext,
WindowManagerProxy wmProxy,
Map<CachedDisplayInfo, List<WindowBounds>> perDisplayBoundsCache) {
CachedDisplayInfo displayInfo = wmProxy.getDisplayInfo(displayInfoContext);
normalizedDisplayInfo = displayInfo.normalize();
rotation = displayInfo.rotation;
currentSize = displayInfo.size;
cutout = displayInfo.cutout;
Configuration config = displayInfoContext.getResources().getConfiguration();
fontScale = config.fontScale;
densityDpi = config.densityDpi;
mScreenSizeDp = new PortraitSize(config.screenHeightDp, config.screenWidthDp);
navigationMode = wmProxy.getNavigationMode(displayInfoContext);
mPerDisplayBounds.putAll(perDisplayBoundsCache);
List<WindowBounds> cachedValue = mPerDisplayBounds.get(normalizedDisplayInfo);
realBounds = wmProxy.getRealBounds(displayInfoContext, displayInfo);
if (cachedValue == null) {
// Unexpected normalizedDisplayInfo is found, recreate the cache
FileLog.e(TAG, "Unexpected normalizedDisplayInfo found, invalidating cache: "
+ normalizedDisplayInfo);
FileLog.e(TAG, "(Invalid Cache) perDisplayBounds : " + mPerDisplayBounds);
mPerDisplayBounds.clear();
mPerDisplayBounds.putAll(wmProxy.estimateInternalDisplayBounds(displayInfoContext));
cachedValue = mPerDisplayBounds.get(normalizedDisplayInfo);
if (cachedValue == null) {
FileLog.e(TAG, "normalizedDisplayInfo not found in estimation: "
+ normalizedDisplayInfo);
supportedBounds.add(realBounds);
}
}
if (cachedValue != null) {
// Verify that the real bounds are a match
WindowBounds expectedBounds = cachedValue.get(displayInfo.rotation);
if (!realBounds.equals(expectedBounds)) {
List<WindowBounds> clone = new ArrayList<>(cachedValue);
clone.set(displayInfo.rotation, realBounds);
mPerDisplayBounds.put(normalizedDisplayInfo, clone);
}
}
mPerDisplayBounds.values().forEach(supportedBounds::addAll);
if (DEBUG) {
Log.d(TAG, "displayInfo: " + displayInfo);
Log.d(TAG, "realBounds: " + realBounds);
Log.d(TAG, "normalizedDisplayInfo: " + normalizedDisplayInfo);
Log.d(TAG, "perDisplayBounds: " + mPerDisplayBounds);
}
}
/**
* Returns {@code true} if the bounds represent a tablet.
*/
public boolean isTablet(WindowBounds bounds) {
return smallestSizeDp(bounds) >= MIN_TABLET_WIDTH;
}
/**
* Returns smallest size in dp for given bounds.
*/
public float smallestSizeDp(WindowBounds bounds) {
return dpiFromPx(Math.min(bounds.bounds.width(), bounds.bounds.height()), densityDpi);
}
/**
* Returns all displays for the device
*/
public Set<CachedDisplayInfo> getAllDisplays() {
return Collections.unmodifiableSet(mPerDisplayBounds.keySet());
}
public int getDensityDpi() {
return densityDpi;
}
}
/**
* Returns the given binary flags as a human-readable string.
*
* @see #CHANGE_ALL
*/
public String getChangeFlagsString(int change) {
StringJoiner result = new StringJoiner("|");
appendFlag(result, change, CHANGE_ACTIVE_SCREEN, "CHANGE_ACTIVE_SCREEN");
appendFlag(result, change, CHANGE_ROTATION, "CHANGE_ROTATION");
appendFlag(result, change, CHANGE_DENSITY, "CHANGE_DENSITY");
appendFlag(result, change, CHANGE_SUPPORTED_BOUNDS, "CHANGE_SUPPORTED_BOUNDS");
appendFlag(result, change, CHANGE_NAVIGATION_MODE, "CHANGE_NAVIGATION_MODE");
return result.toString();
}
/**
* Dumps the current state information
*/
public void dump(PrintWriter pw) {
Info info = mInfo;
pw.println("DisplayController.Info:");
pw.println(" normalizedDisplayInfo=" + info.normalizedDisplayInfo);
pw.println(" rotation=" + info.rotation);
pw.println(" fontScale=" + info.fontScale);
pw.println(" densityDpi=" + info.densityDpi);
pw.println(" navigationMode=" + info.navigationMode.name());
pw.println(" currentSize=" + info.currentSize);
info.mPerDisplayBounds.forEach((key, value) -> pw.println(
" perDisplayBounds - " + key + ": " + value));
}
/**
* Utility class to hold a size information in an orientation independent way
*/
public static class PortraitSize {
public final int width, height;
public PortraitSize(int w, int h) {
width = Math.min(w, h);
height = Math.max(w, h);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PortraitSize that = (PortraitSize) o;
return width == that.width && height == that.height;
}
@Override
public int hashCode() {
return Objects.hash(width, height);
}
}
}
|
65047_0 | package main.java.pattern;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
/*
* Dit is de DataMapPropertyValueFactory deze class is nodig om de DataMap te kunnen gebruiken in de TableView.
* Omdat de DataMap een HashMap is en geen model kan je niet zomaar een propertyValueFactory gebruiken.
* De propertyValueFactory verwacht namelijk een model.
* Ook ondersteund deze class child properties. Bijv: "player.userName"
*
* Voorbeelden hoe het in de gamesList gebruikt kan worden:
* Hiermee wordt het id van de game, de username en score van de turnPlayer, de currentRound en de creationDate van de game opgehaald.
* public ArrayList<DataMap> getGames() {
* return DataMapper.createMultiple(Game.getAll(),"id", "turnPlayer{username,score}", "currentRound", "creationDate");
* }
*
* Hiermee wordt het id uit de DataMap gehaald en in de id column gezet.
* TableColumn<DataMap, Integer> idCol = new TableColumn<>("Id");
* idCol.setCellValueFactory(new DataMapPropertyValueFactory<>("id"));
*
* Hiermee wordt de username van de turnPlayer uit de DataMap gehaald en in de username column gezet.
* TableColumn<DataMap, String> turnPlayerCol = new TableColumn<>("Beurt Speler");
* turnPlayerCol.setCellValueFactory(new DataMapPropertyValueFactory<>("turnPlayer.username"));
*
*/
public class DataMapPropertyValueFactory<S, T> extends PropertyValueFactory<S, T> {
private String propertyKey;
public DataMapPropertyValueFactory(final String propertyKey) {
super(propertyKey);
this.propertyKey = propertyKey;
}
@Override
public ObservableValue<T> call(final TableColumn.CellDataFeatures<S, T> param) {
S value = param.getValue();
if (value instanceof DataMap) {
DataMap dataMap = (DataMap) value;
Object propertyValue = getProperty(dataMap, propertyKey);
@SuppressWarnings("unchecked")
T castedValue = (T) propertyValue;
return new SimpleObjectProperty<>(castedValue);
}
return new SimpleObjectProperty<>();
}
private Object getProperty(final DataMap dataMap, final String propertyKey) {
String[] propertyParts = propertyKey.split("\\.");
Object value = dataMap;
for (String part : propertyParts) {
if (value instanceof DataMap) {
value = ((DataMap) value).get(part);
} else {
return null;
}
}
return value;
}
}
| LegeBeker/sagrada | src/main/java/pattern/DataMapPropertyValueFactory.java | 714 | /*
* Dit is de DataMapPropertyValueFactory deze class is nodig om de DataMap te kunnen gebruiken in de TableView.
* Omdat de DataMap een HashMap is en geen model kan je niet zomaar een propertyValueFactory gebruiken.
* De propertyValueFactory verwacht namelijk een model.
* Ook ondersteund deze class child properties. Bijv: "player.userName"
*
* Voorbeelden hoe het in de gamesList gebruikt kan worden:
* Hiermee wordt het id van de game, de username en score van de turnPlayer, de currentRound en de creationDate van de game opgehaald.
* public ArrayList<DataMap> getGames() {
* return DataMapper.createMultiple(Game.getAll(),"id", "turnPlayer{username,score}", "currentRound", "creationDate");
* }
*
* Hiermee wordt het id uit de DataMap gehaald en in de id column gezet.
* TableColumn<DataMap, Integer> idCol = new TableColumn<>("Id");
* idCol.setCellValueFactory(new DataMapPropertyValueFactory<>("id"));
*
* Hiermee wordt de username van de turnPlayer uit de DataMap gehaald en in de username column gezet.
* TableColumn<DataMap, String> turnPlayerCol = new TableColumn<>("Beurt Speler");
* turnPlayerCol.setCellValueFactory(new DataMapPropertyValueFactory<>("turnPlayer.username"));
*
*/ | block_comment | nl | package main.java.pattern;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
/*
* Dit is de<SUF>*/
public class DataMapPropertyValueFactory<S, T> extends PropertyValueFactory<S, T> {
private String propertyKey;
public DataMapPropertyValueFactory(final String propertyKey) {
super(propertyKey);
this.propertyKey = propertyKey;
}
@Override
public ObservableValue<T> call(final TableColumn.CellDataFeatures<S, T> param) {
S value = param.getValue();
if (value instanceof DataMap) {
DataMap dataMap = (DataMap) value;
Object propertyValue = getProperty(dataMap, propertyKey);
@SuppressWarnings("unchecked")
T castedValue = (T) propertyValue;
return new SimpleObjectProperty<>(castedValue);
}
return new SimpleObjectProperty<>();
}
private Object getProperty(final DataMap dataMap, final String propertyKey) {
String[] propertyParts = propertyKey.split("\\.");
Object value = dataMap;
for (String part : propertyParts) {
if (value instanceof DataMap) {
value = ((DataMap) value).get(part);
} else {
return null;
}
}
return value;
}
}
|
33198_3 | package main.domeinLaag;
import java.util.*;
public class Vlucht
{
private static HashSet<Vlucht> alleVluchten = new HashSet<Vlucht>();
private static int hoogsteVluchtNummer = 1;
private int vluchtNummer;
private Vliegtuig vliegtuig;
private Luchthaven bestemming;
private Luchthaven vertrekpunt;
private Calendar vertrekTijd;
private Calendar aankomstTijd;
private Calendar duur;
public static TreeMap<Integer, Vlucht> geefAlle() {
TreeMap<Integer, Vlucht> alleVluchten = new TreeMap<Integer, Vlucht>();
for (Vlucht vlucht : Vlucht.alleVluchten) {
int vluchtNummer = vlucht.getVluchtNummer();
alleVluchten.put(vluchtNummer, vlucht);
}
return alleVluchten;
}
/** Controleert of het vliegtuig op het meegegeven tijdstip al een vlucht heeft.
* @return True, als vliegtuig bezet. Anders false. */
private static boolean isBezet(Vliegtuig vliegtuig, Calendar d) {
boolean b = false;
for (Iterator<Vlucht> i=alleVluchten.iterator(); i.hasNext();) {
Vlucht v = (Vlucht) i.next();
if (v.vliegtuig.equals(vliegtuig)) {
if (v.getVertrekTijd().before(d) && v.getAankomstTijd().after(d) )
b = true;
}
}
return b;
}
public Vlucht() {
zetVluchtNummer();
}
public Vlucht(Vliegtuig vt, Luchthaven vertrekp, Luchthaven best, Calendar vertrek, Calendar aankomst) {
zetVluchtNummer();
this.vliegtuig = vt;
this.vertrekpunt = vertrekp;
this.bestemming = best;
this.vertrekTijd = (Calendar)vertrek.clone();
this.aankomstTijd = (Calendar) aankomst.clone();
alleVluchten.add(this);
}
public void zetVliegtuig(Vliegtuig vt) {
this.vliegtuig = vt;
}
public void zetVertrekpunt(Luchthaven vertrekpunt) {
this.vertrekpunt = vertrekpunt;
}
/**
* Controleer dat bestemming <> vertrekpunt.
*/
public void zetBestemming(Luchthaven best) {
if (best == null) {
this.bestemming = best;
} else {
if (best != bestemming)
this.bestemming = best;
else
throw new IllegalArgumentException("bestemming en vertrek zijn gelijk");
}
}
/**
* Controleer dat de vertrektijd niet overlapt met een andere vlucht van het toestel.
* @param tijd
*/
public void zetVertrekTijd(Calendar tijd) throws VluchtException {
if (tijd == null) {
vertrekTijd = null;
} else {
Calendar vTijd = tijd;
vTijd.setLenient(false);
// Ter controle of het een juiste datum is. Gebeurt niet bij het zetten, maar bij het getten.
try {
@SuppressWarnings("unused")
Date datum = vTijd.getTime();
} catch (IllegalArgumentException e) {
throw new VluchtException("Geen geldig tijdstip!");
}
if (!Vlucht.isBezet(vliegtuig, vTijd)) {
vertrekTijd = (Calendar) vTijd.clone();
} else
throw new VluchtException("Vliegtuig reeds bezet op " + tijd.getTime());
}
}
public Calendar getVertrekTijd() {
return vertrekTijd;
}
/**
* Controleer dat aankomstTijd > vertrekTijd.
*/
public void zetAankomstTijd(Calendar tijd) throws VluchtException {
if (tijd == null) {
aankomstTijd = null;
} else {
Calendar aTijd = tijd;
aTijd.setLenient(false);
// Ter controle of het een juiste datum is. Gebeurt niet bij het zetten, maar bij het getten.
try {
@SuppressWarnings("unused")
Date datum = aTijd.getTime();
} catch (IllegalArgumentException e) {
throw new VluchtException("Geen geldig tijdstip!");
}
if (aTijd.after(vertrekTijd))
aankomstTijd = (Calendar) aTijd.clone();
else
throw new VluchtException("Aankomsttijd voor vertrektijd");
}
}
public Vliegtuig getVliegtuig() {
return vliegtuig;
}
public Calendar getAankomstTijd() {
return aankomstTijd;
}
/**
* Controleer of alle gegevens gezet zijn. Zo ja, bewaar de vluchtgegevens.
*/
public void bewaar() throws VluchtException {
if(vliegtuig == null)
throw new VluchtException("Geen geldige vliegtuig.");
else if(bestemming == null)
throw new VluchtException("Geen geldige bestemming.");
else if(aankomstTijd == null)
throw new VluchtException("Geen geldige aankomsttijd.");
else if(vertrekTijd == null)
throw new VluchtException("Geen geldige vertrektijd.");
else
alleVluchten.add(this);
}
public Luchthaven getBestemming() {
return bestemming;
}
public Luchthaven getVertrekPunt() {
return vertrekpunt;
}
private void zetVluchtNummer() {
vluchtNummer = hoogsteVluchtNummer;
hoogsteVluchtNummer ++;
}
private int getVluchtNummer() {
return vluchtNummer;
}
@Override
public String toString() {
return "Vlucht [vluchtNummer=" + vluchtNummer + ", vt=" + vliegtuig
+ ", bestemming=" + bestemming + ", vertrekpunt=" + vertrekpunt
+ ", vertrekTijd=" + vertrekTijd + ", aankomstTijd="
+ aankomstTijd + ", duur=" + duur + "]";
}
}
| LegendWolf-Dev/OOAD_Opdracht3 | src/main/domeinLaag/Vlucht.java | 1,919 | // Ter controle of het een juiste datum is. Gebeurt niet bij het zetten, maar bij het getten. | line_comment | nl | package main.domeinLaag;
import java.util.*;
public class Vlucht
{
private static HashSet<Vlucht> alleVluchten = new HashSet<Vlucht>();
private static int hoogsteVluchtNummer = 1;
private int vluchtNummer;
private Vliegtuig vliegtuig;
private Luchthaven bestemming;
private Luchthaven vertrekpunt;
private Calendar vertrekTijd;
private Calendar aankomstTijd;
private Calendar duur;
public static TreeMap<Integer, Vlucht> geefAlle() {
TreeMap<Integer, Vlucht> alleVluchten = new TreeMap<Integer, Vlucht>();
for (Vlucht vlucht : Vlucht.alleVluchten) {
int vluchtNummer = vlucht.getVluchtNummer();
alleVluchten.put(vluchtNummer, vlucht);
}
return alleVluchten;
}
/** Controleert of het vliegtuig op het meegegeven tijdstip al een vlucht heeft.
* @return True, als vliegtuig bezet. Anders false. */
private static boolean isBezet(Vliegtuig vliegtuig, Calendar d) {
boolean b = false;
for (Iterator<Vlucht> i=alleVluchten.iterator(); i.hasNext();) {
Vlucht v = (Vlucht) i.next();
if (v.vliegtuig.equals(vliegtuig)) {
if (v.getVertrekTijd().before(d) && v.getAankomstTijd().after(d) )
b = true;
}
}
return b;
}
public Vlucht() {
zetVluchtNummer();
}
public Vlucht(Vliegtuig vt, Luchthaven vertrekp, Luchthaven best, Calendar vertrek, Calendar aankomst) {
zetVluchtNummer();
this.vliegtuig = vt;
this.vertrekpunt = vertrekp;
this.bestemming = best;
this.vertrekTijd = (Calendar)vertrek.clone();
this.aankomstTijd = (Calendar) aankomst.clone();
alleVluchten.add(this);
}
public void zetVliegtuig(Vliegtuig vt) {
this.vliegtuig = vt;
}
public void zetVertrekpunt(Luchthaven vertrekpunt) {
this.vertrekpunt = vertrekpunt;
}
/**
* Controleer dat bestemming <> vertrekpunt.
*/
public void zetBestemming(Luchthaven best) {
if (best == null) {
this.bestemming = best;
} else {
if (best != bestemming)
this.bestemming = best;
else
throw new IllegalArgumentException("bestemming en vertrek zijn gelijk");
}
}
/**
* Controleer dat de vertrektijd niet overlapt met een andere vlucht van het toestel.
* @param tijd
*/
public void zetVertrekTijd(Calendar tijd) throws VluchtException {
if (tijd == null) {
vertrekTijd = null;
} else {
Calendar vTijd = tijd;
vTijd.setLenient(false);
// Ter controle<SUF>
try {
@SuppressWarnings("unused")
Date datum = vTijd.getTime();
} catch (IllegalArgumentException e) {
throw new VluchtException("Geen geldig tijdstip!");
}
if (!Vlucht.isBezet(vliegtuig, vTijd)) {
vertrekTijd = (Calendar) vTijd.clone();
} else
throw new VluchtException("Vliegtuig reeds bezet op " + tijd.getTime());
}
}
public Calendar getVertrekTijd() {
return vertrekTijd;
}
/**
* Controleer dat aankomstTijd > vertrekTijd.
*/
public void zetAankomstTijd(Calendar tijd) throws VluchtException {
if (tijd == null) {
aankomstTijd = null;
} else {
Calendar aTijd = tijd;
aTijd.setLenient(false);
// Ter controle of het een juiste datum is. Gebeurt niet bij het zetten, maar bij het getten.
try {
@SuppressWarnings("unused")
Date datum = aTijd.getTime();
} catch (IllegalArgumentException e) {
throw new VluchtException("Geen geldig tijdstip!");
}
if (aTijd.after(vertrekTijd))
aankomstTijd = (Calendar) aTijd.clone();
else
throw new VluchtException("Aankomsttijd voor vertrektijd");
}
}
public Vliegtuig getVliegtuig() {
return vliegtuig;
}
public Calendar getAankomstTijd() {
return aankomstTijd;
}
/**
* Controleer of alle gegevens gezet zijn. Zo ja, bewaar de vluchtgegevens.
*/
public void bewaar() throws VluchtException {
if(vliegtuig == null)
throw new VluchtException("Geen geldige vliegtuig.");
else if(bestemming == null)
throw new VluchtException("Geen geldige bestemming.");
else if(aankomstTijd == null)
throw new VluchtException("Geen geldige aankomsttijd.");
else if(vertrekTijd == null)
throw new VluchtException("Geen geldige vertrektijd.");
else
alleVluchten.add(this);
}
public Luchthaven getBestemming() {
return bestemming;
}
public Luchthaven getVertrekPunt() {
return vertrekpunt;
}
private void zetVluchtNummer() {
vluchtNummer = hoogsteVluchtNummer;
hoogsteVluchtNummer ++;
}
private int getVluchtNummer() {
return vluchtNummer;
}
@Override
public String toString() {
return "Vlucht [vluchtNummer=" + vluchtNummer + ", vt=" + vliegtuig
+ ", bestemming=" + bestemming + ", vertrekpunt=" + vertrekpunt
+ ", vertrekTijd=" + vertrekTijd + ", aankomstTijd="
+ aankomstTijd + ", duur=" + duur + "]";
}
}
|
17457_1 | package Week4.Opdracht11;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
import java.io.FileNotFoundException;
import java.io.IOException;
//Het onderstaande tekstbestand bevat van een aantal artikelen de prijs in US Dollars.
// In de file staan de gegevens van één artikel op één regel. Op iedere regel staat een omschrijving van een artikel, dan een spatie, een dubbele punt, en weer een spatie, en dan de prijs van het artikel in dollars.
// Er moet nu een zelfde soort file worden gegenereerd maar dan met de prijs in euro's.
public class PrijsOmzetter {
private File bronBestand;
private File bestemmingBestand;
private double us_DollarWorthInEuro;
public String veranderDollarNaarEuro() {
List<String> txt = new ArrayList<>();
setBronBestand();
setBestemmingBestand();
setWaardeVanUSNaarEuro();
try {
Scanner reader = new Scanner(bronBestand);
while (reader.hasNextLine()) {
txt.add(reader.nextLine());
}
txt = dollarNaarEuro(txt);
try {
FileWriter writer = new FileWriter(bestemmingBestand);
for (int i = 0; i < txt.size(); i++) {
writer.write(txt.get(i)+"\n");
}
writer.close();
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return("Geslaagd check: " + bestemmingBestand);
}
public List<String> dollarNaarEuro(List input){
String string = "";
String string2 = "";
ArrayList output = new ArrayList();
for (int i = 0; i < input.size(); i++) {
string = input.get(i).toString();
string = string.substring(string.indexOf(": "));
string = string.replaceAll("\\D+\\.?\\D+","");
//
double prijs = Double.parseDouble(string);
prijs = prijs * us_DollarWorthInEuro;
string =" "+"€"+String.format("%.2f", prijs);
//
string2 = input.get(i).toString();
int index = string2.indexOf(": ")+1;
string2 = string2.substring(0,index);
string2 += string;
output.add(string2);
}
return (output);
}
public void setBronBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bronbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bronBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBronBestand();
}
}
public void setBestemmingBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bestemmingbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bestemmingBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBestemmingBestand();}
}
public void setWaardeVanUSNaarEuro() {
Scanner st = new Scanner(System.in);
System.out.println("Enter waarde van 1 US dollar in Eurocent: ");
try {
this.us_DollarWorthInEuro = st.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Geen correcte waarde gevonden. Probeer het opnieuw.");
setWaardeVanUSNaarEuro();}
}}
| LegendWolf-Dev/OOP | src/Week4/Opdracht11/PrijsOmzetter.java | 1,119 | // In de file staan de gegevens van één artikel op één regel. Op iedere regel staat een omschrijving van een artikel, dan een spatie, een dubbele punt, en weer een spatie, en dan de prijs van het artikel in dollars. | line_comment | nl | package Week4.Opdracht11;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
import java.io.FileNotFoundException;
import java.io.IOException;
//Het onderstaande tekstbestand bevat van een aantal artikelen de prijs in US Dollars.
// In de<SUF>
// Er moet nu een zelfde soort file worden gegenereerd maar dan met de prijs in euro's.
public class PrijsOmzetter {
private File bronBestand;
private File bestemmingBestand;
private double us_DollarWorthInEuro;
public String veranderDollarNaarEuro() {
List<String> txt = new ArrayList<>();
setBronBestand();
setBestemmingBestand();
setWaardeVanUSNaarEuro();
try {
Scanner reader = new Scanner(bronBestand);
while (reader.hasNextLine()) {
txt.add(reader.nextLine());
}
txt = dollarNaarEuro(txt);
try {
FileWriter writer = new FileWriter(bestemmingBestand);
for (int i = 0; i < txt.size(); i++) {
writer.write(txt.get(i)+"\n");
}
writer.close();
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return("Geslaagd check: " + bestemmingBestand);
}
public List<String> dollarNaarEuro(List input){
String string = "";
String string2 = "";
ArrayList output = new ArrayList();
for (int i = 0; i < input.size(); i++) {
string = input.get(i).toString();
string = string.substring(string.indexOf(": "));
string = string.replaceAll("\\D+\\.?\\D+","");
//
double prijs = Double.parseDouble(string);
prijs = prijs * us_DollarWorthInEuro;
string =" "+"€"+String.format("%.2f", prijs);
//
string2 = input.get(i).toString();
int index = string2.indexOf(": ")+1;
string2 = string2.substring(0,index);
string2 += string;
output.add(string2);
}
return (output);
}
public void setBronBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bronbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bronBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBronBestand();
}
}
public void setBestemmingBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bestemmingbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bestemmingBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBestemmingBestand();}
}
public void setWaardeVanUSNaarEuro() {
Scanner st = new Scanner(System.in);
System.out.println("Enter waarde van 1 US dollar in Eurocent: ");
try {
this.us_DollarWorthInEuro = st.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Geen correcte waarde gevonden. Probeer het opnieuw.");
setWaardeVanUSNaarEuro();}
}}
|
3062_3 | import java.util.ArrayList;
public class Persoon {
private String naam;
private double budget;
private ArrayList<Game> mijnGames;
public Persoon(String naam, double budget) {
this.naam = naam;
this.budget = budget;
this.mijnGames = new ArrayList<Game>();
}
public double getBudget() {
return budget;
}
//koop(g), maar dat kan alleen als hij voldoende budget heeft en als hij die game nog niet bezit
public boolean koop(Game g) {
if (getBudget() >= g.huidigeWaarde()) {
if (mijnGames.contains(g)) {
return false;
} else {
mijnGames.add(g);
budget = budget - g.huidigeWaarde();
return true;
}
}
return false;
}
//verkoop(g, koper), maar alleen als hij die game zelf heeft,
// als de koper de game nog niet heeft en als de koper voldoende budget heeft!
public boolean verkoop(Game g, Persoon koper) {
if (!mijnGames.contains(g)) {
return false;
} else {
if (koper.koop(g)) {
mijnGames.remove(g);
budget = budget + g.huidigeWaarde();
return true;
}else{
return false;
}}}
// Toevoeging Leon voor Practicum 6B
public ArrayList<Game> bepaalGamesNietInBezit(ArrayList<Game> arrayOfGames){
ArrayList<Game> resultingGames = new ArrayList<>();
for (int i = 0; i < arrayOfGames.size(); i++){
if (!mijnGames.contains(arrayOfGames.get(i))){
resultingGames.add(arrayOfGames.get(i));
}
}
return resultingGames;
}
//Einde toevoeging Leon
public String toString() {
String txt = "";
int Count = this.mijnGames.size();
for (Game game : this.mijnGames) {
if (Count > 1) {
txt += game.toString() + "\n";
Count = Count - 1;
} else {
txt += game.toString();
}
}
if (mijnGames.size() == 0) {
return (naam + " heeft een budget van €" + String.format("%.2f", budget) + " en bezit de volgende games:");
} else
return (naam + " heeft een budget van €" + String.format("%.2f", budget) + " en bezit de volgende games:\n" + txt);
}
public Game zoekGameOpNaam(String input) {
for (Game g : this.mijnGames) {
if (g.getNaam().equals(input)) {
return (g);
}
}
return null;
}
} | LegendWolf-Dev/Practicum6 | src/Persoon.java | 797 | // Toevoeging Leon voor Practicum 6B | line_comment | nl | import java.util.ArrayList;
public class Persoon {
private String naam;
private double budget;
private ArrayList<Game> mijnGames;
public Persoon(String naam, double budget) {
this.naam = naam;
this.budget = budget;
this.mijnGames = new ArrayList<Game>();
}
public double getBudget() {
return budget;
}
//koop(g), maar dat kan alleen als hij voldoende budget heeft en als hij die game nog niet bezit
public boolean koop(Game g) {
if (getBudget() >= g.huidigeWaarde()) {
if (mijnGames.contains(g)) {
return false;
} else {
mijnGames.add(g);
budget = budget - g.huidigeWaarde();
return true;
}
}
return false;
}
//verkoop(g, koper), maar alleen als hij die game zelf heeft,
// als de koper de game nog niet heeft en als de koper voldoende budget heeft!
public boolean verkoop(Game g, Persoon koper) {
if (!mijnGames.contains(g)) {
return false;
} else {
if (koper.koop(g)) {
mijnGames.remove(g);
budget = budget + g.huidigeWaarde();
return true;
}else{
return false;
}}}
// Toevoeging Leon<SUF>
public ArrayList<Game> bepaalGamesNietInBezit(ArrayList<Game> arrayOfGames){
ArrayList<Game> resultingGames = new ArrayList<>();
for (int i = 0; i < arrayOfGames.size(); i++){
if (!mijnGames.contains(arrayOfGames.get(i))){
resultingGames.add(arrayOfGames.get(i));
}
}
return resultingGames;
}
//Einde toevoeging Leon
public String toString() {
String txt = "";
int Count = this.mijnGames.size();
for (Game game : this.mijnGames) {
if (Count > 1) {
txt += game.toString() + "\n";
Count = Count - 1;
} else {
txt += game.toString();
}
}
if (mijnGames.size() == 0) {
return (naam + " heeft een budget van €" + String.format("%.2f", budget) + " en bezit de volgende games:");
} else
return (naam + " heeft een budget van €" + String.format("%.2f", budget) + " en bezit de volgende games:\n" + txt);
}
public Game zoekGameOpNaam(String input) {
for (Game g : this.mijnGames) {
if (g.getNaam().equals(input)) {
return (g);
}
}
return null;
}
} |
17836_7 | package Server;
import Classes.*;
import Interfaces.IGameManager;
import Interfaces.IGameObject;
import Interfaces.IUser;
import LibGDXSerialzableClasses.SerializableColor;
import com.badlogic.gdx.math.Vector2;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
/**
* Created by michel on 15-11-2016.
*/
public class ServerGameManger extends UnicastRemoteObject implements IGameManager
{
private String name;
private List<IGameObject> everything;
private Map<String, List<IGameObject>> idObjects; //TODO gebruik list voor het opslaan voor eigen objecten niet voor opslaan van objecten die voor mij bedoelt zijn.
private ArrayList<User> userList;
private ArrayList<String> stringUserList;
private Random r = new Random();
private Level level;
private float matchTime = 5f * 60 * 1000;
private transient Timer matchTimer;
private boolean matchStarted;
private PreGameManager pgm;
public ServerGameManger() throws RemoteException
{
Constructor();
}
public ServerGameManger(String name) throws RemoteException
{
Constructor();
this.name = name;
}
public ServerGameManger(String name, PreGameManager preGameManager) throws RemoteException
{
Constructor();
this.name = name;
pgm = preGameManager;
}
private <T> ArrayList<T> getObjectList(ArrayList<Object> list, Class<T> tocast)
{
ArrayList<T> returnList = new ArrayList<>();
for (Object go : list)
{
try
{
T igo = tocast.cast(go);
returnList.add(igo);
}
catch (ClassCastException e)
{
System.out.println("Cast Error " + e.getMessage());
}
}
return returnList;
}
@Override
public List<IGameObject> GetTick(String id)
{
if (id.equals("Spectator"))
{
return GetEverything();
}
List<IGameObject> allbutmeobject = new ArrayList<>();
for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet())
{
if (!objlist.getKey().equals(id))
{
//System.out.println("Adding from " + objlist.getKey() + " TO " + id);
allbutmeobject.addAll(objlist.getValue());
}
}
allbutmeobject.addAll(everything);
return allbutmeobject;
}
public List<IGameObject> GetEverything()
{
List<IGameObject> alllist = new ArrayList<>();
for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet())
{
alllist.addAll(objlist.getValue());
}
return alllist;
}
@Override
public void SetTick(String id, IGameObject object)
{
//System.out.println("New Object From : " + id);
/*
idObjects.putIfAbsent(id, new ArrayList<>(everything)); //Waaneer id niet bestaat voeg alles toe aan die speler
everything.add(object); // voeg nieuw object toe aan iedereen
idObjects.entrySet().stream().filter(entry -> !entry.getKey().equals(id)).forEach(entry -> entry.getValue().add(object)); //voeg object toe aan iedereen behalve ik
*/
if(!matchStarted){
try
{
startMatch();
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
idObjects.putIfAbsent(id, new ArrayList<>());
idObjects.get(id).add(object);
}
@Override
public void UpdateTick(String id, long objectId, Vector2 newPostion, float newRotation) throws RemoteException
{
for(IGameObject obj : idObjects.get(id))
{
if (obj.getID() == objectId)
{
obj.setPosition(newPostion);
obj.setRotation(newRotation);
break;
}
}
}
@Override
public void UpdateTick(String id, IGameObject object) throws RemoteException
{
//System.out.println("Update Object From : " + id);
/*
//Update de position voor iedereen
for (IGameObject go : everything)
{
if (go.getID() == object.getID())
{
go.setPosition(object.getPosition());
go.setRotation(object.getRotation());
break;
}
}
//Update de position voor iedereen behalve mij
for (Map.Entry<String, List<IGameObject>> entry : idObjects.entrySet())
{
if (!entry.getKey().equals(id))
{
for (IGameObject obj : entry.getValue())
{
if (obj.getID() == object.getID())
{
obj.setPosition(object.getPosition());
obj.setRotation(object.getRotation());
break;
}
}
}
}*/
for(IGameObject obj : idObjects.get(id))
{
if (obj.getID() == object.getID())
{
obj.setPosition(object.getPosition());
obj.setRotation(object.getRotation());
break;
}
}
}
private void AddForEveryOne()
{
}
private void AddForEveryOneButMe()
{
}
private void AddForMe()
{
}
private void RemoveForEveryOne()
{
}
private void RemoveForEveryOneButMe()
{
}
private void RemoveForMe()
{
}
private void Constructor() throws RemoteException
{
everything = new ArrayList<>();
userList = new ArrayList<>();
stringUserList = new ArrayList<>();
idObjects = new HashMap<>(100);
level = new Level();
matchTimer = new Timer();
}
@Override
public void DeleteTick(String id, IGameObject object) throws RemoteException
{
//haald object overal weg waar hij bestaat
//idObjects.entrySet().forEach(stringListEntry -> stringListEntry.getValue().removeIf(gameObject -> gameObject.getID() == object.getID()));
//everything.removeIf(gameObject -> gameObject.getID() == object.getID());
idObjects.get(id).removeIf(obj -> obj.getID() == object.getID());
}
@Override
public void DeleteUser(String id)
{
//delete alles van een user
//idObjects.entrySet().forEach(set -> everything.removeIf(obj -> obj.getID() == ((IGameObject) set.getValue()).getID()));
//idObjects.entrySet().removeIf(keyid -> Objects.equals(keyid.getKey(), id));
/*
if (idObjects.get(id) instanceof User) {
User user = (User) idObjects.get(id);
for (Object object : everything) {
if (object instanceof Player) {
if (user.getName().equals(((Player) object).getName())) {
Player player = (Player) object;
user.UpdateData(player.getKills(), player.getDeaths(), player.getShotsHit(), player.getShots(), player.getKills() >= 10 ? true : false);
}
}
}
}*/
idObjects.remove(id);
userList.removeIf(user -> user.getName().equals(id));
}
@Override
public Level GetLevel() throws RemoteException
{
return level;
}
@Override
public ArrayList<String> getUsers() throws RemoteException
{
stringUserList.clear();
for (User u : userList)
{
stringUserList.add(u.getName());
}
return stringUserList;
}
@Override
public void addUser(IUser user) throws RemoteException
{
userList.add((User) user);
}
@Override
public void startMatch() throws RemoteException
{
System.out.println("Match start");
final ServerGameManger me = this;
matchTimer.schedule(new TimerTask()
{
@Override
public void run()
{
System.out.println("game over bitch!!");
matchTimer.cancel();
try
{
StopGameObject sgo = new StopGameObject();
everything.add(sgo);
}
catch (RemoteException e)
{
e.printStackTrace();
}
pgm.StopLobby(me.getName());
userList.forEach( u -> pgm.getConnectionInstance().UpdateStats(u));
}
},(long) matchTime, (long) matchTime);
matchStarted = true;
}
public IGameObject CreatePlayer(String name) throws RemoteException
{
Player p;
p = new Player(false);
p.setName(name);
p.setColor(SerializableColor.getRandomColor());
return p;
}
public String getName()
{
return name;
}
public void addUser(User user)
{
userList.add(user);
}
}
| Lehcim1995/PTS3-Game | server/src/main/java/Server/ServerGameManger.java | 2,505 | //haald object overal weg waar hij bestaat | line_comment | nl | package Server;
import Classes.*;
import Interfaces.IGameManager;
import Interfaces.IGameObject;
import Interfaces.IUser;
import LibGDXSerialzableClasses.SerializableColor;
import com.badlogic.gdx.math.Vector2;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
/**
* Created by michel on 15-11-2016.
*/
public class ServerGameManger extends UnicastRemoteObject implements IGameManager
{
private String name;
private List<IGameObject> everything;
private Map<String, List<IGameObject>> idObjects; //TODO gebruik list voor het opslaan voor eigen objecten niet voor opslaan van objecten die voor mij bedoelt zijn.
private ArrayList<User> userList;
private ArrayList<String> stringUserList;
private Random r = new Random();
private Level level;
private float matchTime = 5f * 60 * 1000;
private transient Timer matchTimer;
private boolean matchStarted;
private PreGameManager pgm;
public ServerGameManger() throws RemoteException
{
Constructor();
}
public ServerGameManger(String name) throws RemoteException
{
Constructor();
this.name = name;
}
public ServerGameManger(String name, PreGameManager preGameManager) throws RemoteException
{
Constructor();
this.name = name;
pgm = preGameManager;
}
private <T> ArrayList<T> getObjectList(ArrayList<Object> list, Class<T> tocast)
{
ArrayList<T> returnList = new ArrayList<>();
for (Object go : list)
{
try
{
T igo = tocast.cast(go);
returnList.add(igo);
}
catch (ClassCastException e)
{
System.out.println("Cast Error " + e.getMessage());
}
}
return returnList;
}
@Override
public List<IGameObject> GetTick(String id)
{
if (id.equals("Spectator"))
{
return GetEverything();
}
List<IGameObject> allbutmeobject = new ArrayList<>();
for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet())
{
if (!objlist.getKey().equals(id))
{
//System.out.println("Adding from " + objlist.getKey() + " TO " + id);
allbutmeobject.addAll(objlist.getValue());
}
}
allbutmeobject.addAll(everything);
return allbutmeobject;
}
public List<IGameObject> GetEverything()
{
List<IGameObject> alllist = new ArrayList<>();
for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet())
{
alllist.addAll(objlist.getValue());
}
return alllist;
}
@Override
public void SetTick(String id, IGameObject object)
{
//System.out.println("New Object From : " + id);
/*
idObjects.putIfAbsent(id, new ArrayList<>(everything)); //Waaneer id niet bestaat voeg alles toe aan die speler
everything.add(object); // voeg nieuw object toe aan iedereen
idObjects.entrySet().stream().filter(entry -> !entry.getKey().equals(id)).forEach(entry -> entry.getValue().add(object)); //voeg object toe aan iedereen behalve ik
*/
if(!matchStarted){
try
{
startMatch();
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
idObjects.putIfAbsent(id, new ArrayList<>());
idObjects.get(id).add(object);
}
@Override
public void UpdateTick(String id, long objectId, Vector2 newPostion, float newRotation) throws RemoteException
{
for(IGameObject obj : idObjects.get(id))
{
if (obj.getID() == objectId)
{
obj.setPosition(newPostion);
obj.setRotation(newRotation);
break;
}
}
}
@Override
public void UpdateTick(String id, IGameObject object) throws RemoteException
{
//System.out.println("Update Object From : " + id);
/*
//Update de position voor iedereen
for (IGameObject go : everything)
{
if (go.getID() == object.getID())
{
go.setPosition(object.getPosition());
go.setRotation(object.getRotation());
break;
}
}
//Update de position voor iedereen behalve mij
for (Map.Entry<String, List<IGameObject>> entry : idObjects.entrySet())
{
if (!entry.getKey().equals(id))
{
for (IGameObject obj : entry.getValue())
{
if (obj.getID() == object.getID())
{
obj.setPosition(object.getPosition());
obj.setRotation(object.getRotation());
break;
}
}
}
}*/
for(IGameObject obj : idObjects.get(id))
{
if (obj.getID() == object.getID())
{
obj.setPosition(object.getPosition());
obj.setRotation(object.getRotation());
break;
}
}
}
private void AddForEveryOne()
{
}
private void AddForEveryOneButMe()
{
}
private void AddForMe()
{
}
private void RemoveForEveryOne()
{
}
private void RemoveForEveryOneButMe()
{
}
private void RemoveForMe()
{
}
private void Constructor() throws RemoteException
{
everything = new ArrayList<>();
userList = new ArrayList<>();
stringUserList = new ArrayList<>();
idObjects = new HashMap<>(100);
level = new Level();
matchTimer = new Timer();
}
@Override
public void DeleteTick(String id, IGameObject object) throws RemoteException
{
//haald object<SUF>
//idObjects.entrySet().forEach(stringListEntry -> stringListEntry.getValue().removeIf(gameObject -> gameObject.getID() == object.getID()));
//everything.removeIf(gameObject -> gameObject.getID() == object.getID());
idObjects.get(id).removeIf(obj -> obj.getID() == object.getID());
}
@Override
public void DeleteUser(String id)
{
//delete alles van een user
//idObjects.entrySet().forEach(set -> everything.removeIf(obj -> obj.getID() == ((IGameObject) set.getValue()).getID()));
//idObjects.entrySet().removeIf(keyid -> Objects.equals(keyid.getKey(), id));
/*
if (idObjects.get(id) instanceof User) {
User user = (User) idObjects.get(id);
for (Object object : everything) {
if (object instanceof Player) {
if (user.getName().equals(((Player) object).getName())) {
Player player = (Player) object;
user.UpdateData(player.getKills(), player.getDeaths(), player.getShotsHit(), player.getShots(), player.getKills() >= 10 ? true : false);
}
}
}
}*/
idObjects.remove(id);
userList.removeIf(user -> user.getName().equals(id));
}
@Override
public Level GetLevel() throws RemoteException
{
return level;
}
@Override
public ArrayList<String> getUsers() throws RemoteException
{
stringUserList.clear();
for (User u : userList)
{
stringUserList.add(u.getName());
}
return stringUserList;
}
@Override
public void addUser(IUser user) throws RemoteException
{
userList.add((User) user);
}
@Override
public void startMatch() throws RemoteException
{
System.out.println("Match start");
final ServerGameManger me = this;
matchTimer.schedule(new TimerTask()
{
@Override
public void run()
{
System.out.println("game over bitch!!");
matchTimer.cancel();
try
{
StopGameObject sgo = new StopGameObject();
everything.add(sgo);
}
catch (RemoteException e)
{
e.printStackTrace();
}
pgm.StopLobby(me.getName());
userList.forEach( u -> pgm.getConnectionInstance().UpdateStats(u));
}
},(long) matchTime, (long) matchTime);
matchStarted = true;
}
public IGameObject CreatePlayer(String name) throws RemoteException
{
Player p;
p = new Player(false);
p.setName(name);
p.setColor(SerializableColor.getRandomColor());
return p;
}
public String getName()
{
return name;
}
public void addUser(User user)
{
userList.add(user);
}
}
|
208705_2 | package gateway;
import com.google.gson.Gson;
import domain.Verplaatsing;
import services.VerplaatsingsService;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import java.io.Serializable;
@Singleton
@Startup
public class DisplacementReceiverGateway implements IGatewayImplementor {
private Gateway gateway;
private final String senderChannel = "";
private final String receiverChannel = "DISPLACEMENTSYSTEM_DISPLACEMENTREGISTRATOR";
private final Gson gson = new Gson();
@Inject
private VerplaatsingsService service;
public void setService(VerplaatsingsService service) {
this.service = service;
}
@PostConstruct
public void init() {
gateway = new Gateway(this, senderChannel, receiverChannel);
}
// public DisplacementReceiverGateway() {
// gateway = new Gateway(this, senderChannel, receiverChannel);
// }
@Override
public void SendObject(Serializable obj) {
gateway.SendMessage(obj);
}
@Override
public void ProcessReceivedObject(Message message) {
try {
Verplaatsing verplaatsing = gson.fromJson(((TextMessage) message).getText(), Verplaatsing.class);
//Verplaatsing verplaatsing = (Verplaatsing) ((ObjectMessage) message).getObject();
service.create(verplaatsing);
} catch (JMSException e) {
e.printStackTrace();
}
catch (NullPointerException npe)
{
System.out.println("is null mogol");
}
}
} | Lehcim1995/Rekeningrijden | allmodules/verplaatsingsmodule/src/main/java/gateway/DisplacementReceiverGateway.java | 468 | //Verplaatsing verplaatsing = (Verplaatsing) ((ObjectMessage) message).getObject(); | line_comment | nl | package gateway;
import com.google.gson.Gson;
import domain.Verplaatsing;
import services.VerplaatsingsService;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import java.io.Serializable;
@Singleton
@Startup
public class DisplacementReceiverGateway implements IGatewayImplementor {
private Gateway gateway;
private final String senderChannel = "";
private final String receiverChannel = "DISPLACEMENTSYSTEM_DISPLACEMENTREGISTRATOR";
private final Gson gson = new Gson();
@Inject
private VerplaatsingsService service;
public void setService(VerplaatsingsService service) {
this.service = service;
}
@PostConstruct
public void init() {
gateway = new Gateway(this, senderChannel, receiverChannel);
}
// public DisplacementReceiverGateway() {
// gateway = new Gateway(this, senderChannel, receiverChannel);
// }
@Override
public void SendObject(Serializable obj) {
gateway.SendMessage(obj);
}
@Override
public void ProcessReceivedObject(Message message) {
try {
Verplaatsing verplaatsing = gson.fromJson(((TextMessage) message).getText(), Verplaatsing.class);
//Verplaatsing verplaatsing<SUF>
service.create(verplaatsing);
} catch (JMSException e) {
e.printStackTrace();
}
catch (NullPointerException npe)
{
System.out.println("is null mogol");
}
}
} |
197765_12 | /**
*
* @author greg (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* 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.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.SystemResources;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.framework.repo.Category;
import org.myrobotlab.framework.repo.Repo;
import org.myrobotlab.framework.repo.ServiceData;
import org.myrobotlab.image.Util;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.net.BareBonesBrowserLaunch;
import org.myrobotlab.service.Runtime;
import org.myrobotlab.service.SwingGui;
import org.myrobotlab.swing.widget.ImageNameRenderer;
import org.myrobotlab.swing.widget.PossibleServicesRenderer;
import org.myrobotlab.swing.widget.ProgressDialog;
import org.slf4j.Logger;
public class RuntimeGui extends ServiceGui implements ActionListener, ListSelectionListener, KeyListener {
class FilterListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent cmd) {
log.info(cmd.getActionCommand());
if ("all".equals(cmd.getActionCommand())) {
getPossibleServices();
} else {
getPossibleServicesFromCategory(cmd.getActionCommand());
}
}
}
public final static Logger log = LoggerFactory.getLogger(RuntimeGui.class);
static final long serialVersionUID = 1L;
HashMap<String, ServiceInterface> nameToServiceEntry = new HashMap<String, ServiceInterface>();
ArrayList<String> resolveErrors = null;
boolean localRepoChange = false;
int popupRow = 0;
JMenuItem infoMenuItem = null;
JMenuItem installMenuItem = null;
JMenuItem startMenuItem = null;
JMenuItem upgradeMenuItem = null;
JMenuItem releaseMenuItem = null;
String possibleServiceFilter = null;
ProgressDialog progressDialog = null;
JLabel freeMemory = new JLabel();
JLabel usedMemory = new JLabel();
JLabel maxMemory = new JLabel();
JLabel totalMemory = new JLabel();
JLabel totalPhysicalMemory = new JLabel();
JTextField search = new JTextField();
Runtime myRuntime = null;
Repo myRepo = null;
ServiceData serviceData = null;
DefaultListModel<Category> categoriesModel = new DefaultListModel<Category>();
// below should be String NOT ServiceInterface !!!
DefaultListModel<ServiceInterface> currentServicesModel = new DefaultListModel<ServiceInterface>();
JList<Category> categories = new JList<Category>(categoriesModel);
JList<ServiceInterface> runningServices = new JList<ServiceInterface>(currentServicesModel);
ImageNameRenderer imageNameRenderer = new ImageNameRenderer();
FilterListener filterListener = new FilterListener();
JPopupMenu popup = new JPopupMenu();
ServiceInterface releasedTarget = null;
DefaultTableModel possibleServicesModel = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
PossibleServicesRenderer cellRenderer = new PossibleServicesRenderer((Runtime) Runtime.getService(boundServiceName));
JTable possibleServices = new JTable(possibleServicesModel) {
private static final long serialVersionUID = 1L;
@Override
public JToolTip createToolTip() {
JToolTip tooltip = super.createToolTip();
return tooltip;
}
// column returns content type
@Override
public Class<?> getColumnClass(int column) {
Object o = getValueAt(0, column);
if (o == null) {
return new Object().getClass();
}
return o.getClass();
}
};
public RuntimeGui(final String boundServiceName, final SwingGui myService) {
super(boundServiceName, myService);
// required - it "might" be a foreign Runtime...
myRuntime = (Runtime) Runtime.getService(boundServiceName);
myRepo = myRuntime.getRepo();
serviceData = myRuntime.getServiceData();
progressDialog = new ProgressDialog(this);
progressDialog.setVisible(false);
getCurrentServices();
ArrayList<Category> c = serviceData.getCategories();
for (int i = 0; i < c.size(); ++i) {
categoriesModel.addElement(c.get(i));
}
categories.setCellRenderer(imageNameRenderer);
categories.setFixedCellWidth(100);
categories.addListSelectionListener(this);
possibleServicesModel.addColumn("service");
possibleServicesModel.addColumn("status");
// possibleServices.setRowHeight(24);
possibleServices.setIntercellSpacing(new Dimension(0, 0));
// possibleServices.setSize(new Dimension(300, 400));
possibleServices.setShowGrid(false);
possibleServices.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// possibleServices.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
// possibleServices.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// possibleServices.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
// possibleServices.setPreferredSize(new Dimension(200, 200));
JScrollPane possible = new JScrollPane(possibleServices);
possible.setPreferredSize(new Dimension(360, 400));
TableColumnModel cm = possibleServices.getColumnModel();
cm.getColumn(0).setMaxWidth(300);
cm.getColumn(1).setMaxWidth(60);
possibleServices.setDefaultRenderer(ImageIcon.class, cellRenderer);
possibleServices.setDefaultRenderer(ServiceType.class, cellRenderer);
possibleServices.setDefaultRenderer(String.class, cellRenderer);
possibleServices.addMouseListener(new MouseAdapter() {
// isPopupTrigger over OSs - use masks
@Override
public void mouseReleased(MouseEvent e) {
log.debug("mouseReleased");
if (SwingUtilities.isRightMouseButton(e)) {
log.debug("mouseReleased - right");
popUpTrigger(e);
}
}
public void popUpTrigger(MouseEvent e) {
log.info("******************popUpTrigger*********************");
JTable source = (JTable) e.getSource();
popupRow = source.rowAtPoint(e.getPoint());
ServiceType c = (ServiceType) possibleServicesModel.getValueAt(popupRow, 0);
releaseMenuItem.setVisible(false);
infoMenuItem.setVisible(true);
if (!myRepo.isServiceTypeInstalled(c.getName())) {
// need to install it
installMenuItem.setVisible(true);
startMenuItem.setVisible(false);
upgradeMenuItem.setVisible(false);
} else {
// have it
installMenuItem.setVisible(false);
startMenuItem.setVisible(true);
}
int column = source.columnAtPoint(e.getPoint());
if (!source.isRowSelected(popupRow))
source.changeSelection(popupRow, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
runningServices.addMouseListener(new MouseAdapter() {
// isPopupTrigger over OSs - use masks
@Override
public void mouseReleased(MouseEvent e) {
log.debug("mouseReleased");
if (SwingUtilities.isRightMouseButton(e)) {
log.debug("mouseReleased - right");
popUpTrigger(e);
}
}
public void popUpTrigger(MouseEvent e) {
log.info("******************popUpTrigger*********************");
JList source = (JList) e.getSource();
int index = source.locationToIndex(e.getPoint());
if (index >= 0) {
releasedTarget = (ServiceInterface) source.getModel().getElementAt(index);
log.info(String.format("right click on running service %s", releasedTarget.getName()));
releaseMenuItem.setVisible(true);
upgradeMenuItem.setVisible(false);
installMenuItem.setVisible(false);
startMenuItem.setVisible(false);
infoMenuItem.setVisible(false);
}
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
infoMenuItem = new JMenuItem("<html><style type=\"text/css\">a { color: #000000;text-decoration: none}</style><a href=\"http://myrobotlab.org/\">info</a></html>");
infoMenuItem.setActionCommand("info");
infoMenuItem.setIcon(Util.getImageIcon("help.png"));
infoMenuItem.addActionListener(this);
popup.add(infoMenuItem);
installMenuItem = new JMenuItem("install");
installMenuItem.addActionListener(this);
installMenuItem.setIcon(Util.getImageIcon("install.png"));
popup.add(installMenuItem);
startMenuItem = new JMenuItem("start");
startMenuItem.addActionListener(this);
startMenuItem.setIcon(Util.getImageIcon("start.png"));
popup.add(startMenuItem);
upgradeMenuItem = new JMenuItem("upgrade");
upgradeMenuItem.addActionListener(this);
upgradeMenuItem.setIcon(Util.getImageIcon("upgrade.png"));
popup.add(upgradeMenuItem);
releaseMenuItem = new JMenuItem("release");
releaseMenuItem.addActionListener(this);
releaseMenuItem.setIcon(Util.getScaledIcon(Util.getImage("release.png"), 0.50));
popup.add(releaseMenuItem);
setTitle(myRuntime.getPlatform().toString());
JPanel flow = new JPanel();
flow.add(createCategories());
JPanel border = new JPanel(new BorderLayout());
search.addKeyListener(this);
border.add(search, BorderLayout.NORTH);
border.add(possible, BorderLayout.CENTER);
flow.add(border);
flow.add(createRunningServices());
addLine(flow);
// add(categories, possible, runningServices);
addTopLine(createMenuBar());
addBottom("memory physical ", totalPhysicalMemory, " max ", maxMemory, " total ", totalMemory, " free ", freeMemory, " used ", usedMemory);
getPossibleServices();
}
public JPanel createRunningServices() {
GridBagConstraints fgc = new GridBagConstraints();
JPanel panel = new JPanel(new GridBagLayout());
fgc.gridy = 0;
fgc.gridx = 0;
fgc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("running services"), fgc);
++fgc.gridy;
JScrollPane scroll = new JScrollPane(runningServices);
runningServices.setVisibleRowCount(15);
runningServices.setCellRenderer(imageNameRenderer);
runningServices.setFixedCellWidth(100);
panel.add(scroll, fgc);
return panel;
}
public JPanel createCategories() {
GridBagConstraints fgc = new GridBagConstraints();
JPanel panel = new JPanel(new GridBagLayout());
fgc.gridy = 0;
fgc.gridx = 0;
fgc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("categories"), fgc);
++fgc.gridy;
JScrollPane scroll = new JScrollPane(categories);
categories.setVisibleRowCount(15);
categories.setCellRenderer(imageNameRenderer);
categories.setFixedCellWidth(160);
panel.add(scroll, fgc);
return panel;
}
public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu system = new JMenu("system");
menuBar.add(system);
JMenu logging = new JMenu("logging");
menuBar.add(logging);
/*
JMenuItem item = new JMenuItem("check for updates");
item.addActionListener(this);
system.add(item);
*/
JMenuItem item = new JMenuItem("install all");
item.addActionListener(this);
system.add(item);
item = new JMenuItem("record");
item.addActionListener(this);
system.add(item);
item = new JMenuItem("restart");
item.addActionListener(this);
system.add(item);
item = new JMenuItem("exit");
item.addActionListener(this);
system.add(item);
JMenu m1 = new JMenu("level");
logging.add(m1);
buildLogLevelMenu(m1);
return menuBar;
}
// zod
@Override
public void actionPerformed(ActionEvent event) {
ServiceType c = (ServiceType) possibleServicesModel.getValueAt(popupRow, 0);
String cmd = event.getActionCommand();
Object o = event.getSource();
if (releaseMenuItem == o) {
myService.send(boundServiceName, "releaseService", releasedTarget.getName());
return;
}
if ("info".equals(cmd)) {
BareBonesBrowserLaunch.openURL("http://myrobotlab.org/service/" + c.getSimpleName());
} else if ("install".equals(cmd)) {
int selectedRow = possibleServices.getSelectedRow();
ServiceType entry = ((ServiceType) possibleServices.getValueAt(selectedRow, 0));
String n = entry.getName();
Repo repo = myRuntime.getRepo();
if (!repo.isServiceTypeInstalled(n)) {
// dependencies needed !!!
String msg = "<html>This Service has dependencies which are not yet loaded,<br>" + "do you wish to download them now?";
JOptionPane.setRootFrame(myService.getFrame());
int result = JOptionPane.showConfirmDialog(myService.getFrame(), msg, "alert", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.CANCEL_OPTION) {
return;
}
// you say "install", i say "update", repo says "resolve"
myService.send(boundServiceName, "install", n);
} else {
// no unfulfilled dependencies - good to go
addNewService(n);
}
} else if ("start".equals(cmd)) {
int selectedRow = possibleServices.getSelectedRow();
ServiceType entry = ((ServiceType) possibleServices.getValueAt(selectedRow, 0));
addNewService(entry.getName());
} else if ("install all".equals(cmd)) {
send("install");
} else if ("restart".equals(cmd)) {
Runtime.getInstance().restart();
} else if ("exit".equals(cmd)) {
Runtime.shutdown();
} else if ("check for updates".equals(cmd)) {
send("checkForUpdates");
} else if (cmd.equals(Level.DEBUG) || cmd.equals(Level.INFO) || cmd.equals(Level.WARN) || cmd.equals(Level.ERROR) || cmd.equals(Level.FATAL)) {
send("setLogLevel", cmd);/*
Logging logging = LoggingFactory.getInstance();
logging.setLevel(cmd);*/
} /*else if (cmd.equals(Appender.FILE)) {
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.FILE);
} else if (cmd.equals(Appender.CONSOLE)) {
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.CONSOLE);
} else if (cmd.equals(Appender.NONE)) {
Logging logging = LoggingFactory.getInstance();
logging.removeAllAppenders();
}*/ else {
log.error("unknown command " + cmd);
}
// end actionCmd
}
public void addNewService(String newService) {
JFrame frame = new JFrame();
frame.setTitle("add new service");
String name = JOptionPane.showInputDialog(frame, "new service name");
if (name != null && name.length() > 0) {
myService.send(boundServiceName, "createAndStart", name, newService);
}
}
/*
* scheduled event of reporting on system resources
*/
public void onSystemResources(SystemResources resources) {
totalPhysicalMemory.setText(String.format("%d", resources.getTotalPhysicalMemory()));
maxMemory.setText(String.format("%d", resources.getMaxMemory()));
totalMemory.setText(String.format("%d", resources.getTotalMemory()));
freeMemory.setText(String.format("%d", resources.getFreeMemory()));
usedMemory.setText(String.format("%d", resources.getTotalMemory() - resources.getFreeMemory()));
}
@Override
public void subscribeGui() {
subscribe("registered");
subscribe("released");
subscribe("getSystemResources");
subscribe("publishInstallProgress");
}
@Override
public void unsubscribeGui() {
unsubscribe("registered");
unsubscribe("released");
subscribe("getSystemResources");
unsubscribe("publishInstallProgress");
}
/**
* Add all options to the Log Level menu.
*
* @param parentMenu
*/
private void buildLogLevelMenu(JMenu parentMenu) {
ButtonGroup logLevelGroup = new ButtonGroup();
String level = LoggingFactory.getInstance().getLevel();
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(Level.DEBUG);
mi.setSelected(("DEBUG".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.INFO);
mi.setSelected(("INFO".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.WARN);
mi.setSelected(("WARN".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.ERROR);
mi.setSelected(("ERROR".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.FATAL); // TODO - deprecate to WTF
// :)
mi.setSelected(("FATAL".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
}
public void checkingForUpdates() {
// FIXME - if auto update or check on startup - we don't want a silly
// dialog
// we just want to be notified if there "is" an update - and whether or
// not we
// should apply it
// FIXME - bypass is auto
progressDialog.checkingForUpdates();
}
public void failedDependency(String dep) {
JOptionPane.showMessageDialog(null, "<html>Unable to load Service...<br>" + dep + "</html>", "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Add data to the list model for display
*/
public void getCurrentServices() {
// can't be static
Map<String, ServiceInterface> services = Runtime.getRegistry();
Map<String, ServiceInterface> sortedMap = null;
sortedMap = new TreeMap<String, ServiceInterface>(services);
Iterator<String> it = sortedMap.keySet().iterator();
while (it.hasNext()) {
String serviceName = it.next();
ServiceInterface si = Runtime.getService(serviceName);
currentServicesModel.addElement(si);
nameToServiceEntry.put(serviceName, si);
}
}
public void getPossibleServices() {
getPossibleServicesFromCategory(null);
}
public void getPossibleServicesFromName(final String filter) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String filtered = (filter == null) ? "" : filter.trim();
// clear data
for (int i = possibleServicesModel.getRowCount(); i > 0; --i) {
possibleServicesModel.removeRow(i - 1);
}
// populate with serviceData
ArrayList<ServiceType> possibleService = serviceData.getServiceTypes();
for (int i = 0; i < possibleService.size(); ++i) {
ServiceType serviceType = possibleService.get(i);
if (filtered == "" || serviceType.getSimpleName().toLowerCase().indexOf(filtered.toLowerCase()) != -1) {
if (serviceType.isAvailable()) {
possibleServicesModel.addRow(new Object[] { serviceType, "" });
}
}
}
possibleServicesModel.fireTableDataChanged();
possibleServices.invalidate();
}
});
}
/*
* lame - deprecate - refactor - or better yet make webgui FIXME this should
* rarely change .... remove getServiceTypeNames
*/
public void getPossibleServicesFromCategory(final String filter) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// clear data
for (int i = possibleServicesModel.getRowCount(); i > 0; --i) {
possibleServicesModel.removeRow(i - 1);
}
Category category = serviceData.getCategory(filter);
HashSet<String> filtered = null;
if (category != null) {
filtered = new HashSet<String>();
ArrayList<String> f = category.serviceTypes;
for (int i = 0; i < f.size(); ++i) {
filtered.add(f.get(i));
}
}
// populate with serviceData
ArrayList<ServiceType> possibleService = serviceData.getServiceTypes();
for (int i = 0; i < possibleService.size(); ++i) {
ServiceType serviceType = possibleService.get(i);
if (filtered == null || filtered.contains(serviceType.getName())) {
if (serviceType.isAvailable()) {
possibleServicesModel.addRow(new Object[] { serviceType, "" });
}
}
}
possibleServicesModel.fireTableDataChanged();
possibleServices.invalidate();
}
});
}
public void onState(final Runtime runtime) {
myRuntime = runtime;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Platform platform = myRuntime.getPlatform();
SystemResources resources = myRuntime.getSystemResources();
totalMemory.setText(String.format("%d", resources.getTotalMemory()));
freeMemory.setText(String.format("%d", resources.getFreeMemory()));
totalPhysicalMemory.setText(String.format("%d", resources.getTotalPhysicalMemory()));
// FIXME - change to "all" or "" - null is sloppy - system has
// to upcast
myService.pack();
}
});
}
/*
* new Service has been created list it..
*/
public ServiceInterface onRegistered(Service sw) {
currentServicesModel.addElement(sw);
return sw;
}
/*
* a Service of this Runtime has been released
*/
public ServiceInterface onReleased(Service sw) {
currentServicesModel.removeElement(sw);
return sw;
}
/**
* a restart command will be sent to the appropriate runtime
*/
public void restart() {
// send("restart"); TODO - change back to restart - when it works
send("shutdown");
}
public void onInstallProgress(Status status) {
if (Repo.INSTALL_START.equals(status.key)) {
progressDialog.beginUpdates();
} else if (Repo.INSTALL_FINISHED.equals(status.key)) {
progressDialog.finished();
}
progressDialog.addStatus(status);
}
/**
* this is the beginning of the applyUpdates process
*/
public void updatesBegin() {
progressDialog.beginUpdates();
}
@Override
public void valueChanged(ListSelectionEvent e) {
Object o = e.getSource();
if (o == categories && !e.getValueIsAdjusting()) {
Category category = categories.getSelectedValue();
String categoryFilter = null;
if (category != null) {
categoryFilter = categories.getSelectedValue().getName();
log.info("valueChanged {}", categoryFilter);
} else {
log.info("valueChanged null");
}
getPossibleServicesFromCategory(categoryFilter);
}
}
@Override
public void keyTyped(KeyEvent e) {
getPossibleServicesFromName(search.getText() + e.getKeyChar());
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
} | LemaitreC/myrobotlab | src/org/myrobotlab/swing/RuntimeGui.java | 7,775 | // dependencies needed !!!
| line_comment | nl | /**
*
* @author greg (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* 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.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.SystemResources;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.framework.repo.Category;
import org.myrobotlab.framework.repo.Repo;
import org.myrobotlab.framework.repo.ServiceData;
import org.myrobotlab.image.Util;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.net.BareBonesBrowserLaunch;
import org.myrobotlab.service.Runtime;
import org.myrobotlab.service.SwingGui;
import org.myrobotlab.swing.widget.ImageNameRenderer;
import org.myrobotlab.swing.widget.PossibleServicesRenderer;
import org.myrobotlab.swing.widget.ProgressDialog;
import org.slf4j.Logger;
public class RuntimeGui extends ServiceGui implements ActionListener, ListSelectionListener, KeyListener {
class FilterListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent cmd) {
log.info(cmd.getActionCommand());
if ("all".equals(cmd.getActionCommand())) {
getPossibleServices();
} else {
getPossibleServicesFromCategory(cmd.getActionCommand());
}
}
}
public final static Logger log = LoggerFactory.getLogger(RuntimeGui.class);
static final long serialVersionUID = 1L;
HashMap<String, ServiceInterface> nameToServiceEntry = new HashMap<String, ServiceInterface>();
ArrayList<String> resolveErrors = null;
boolean localRepoChange = false;
int popupRow = 0;
JMenuItem infoMenuItem = null;
JMenuItem installMenuItem = null;
JMenuItem startMenuItem = null;
JMenuItem upgradeMenuItem = null;
JMenuItem releaseMenuItem = null;
String possibleServiceFilter = null;
ProgressDialog progressDialog = null;
JLabel freeMemory = new JLabel();
JLabel usedMemory = new JLabel();
JLabel maxMemory = new JLabel();
JLabel totalMemory = new JLabel();
JLabel totalPhysicalMemory = new JLabel();
JTextField search = new JTextField();
Runtime myRuntime = null;
Repo myRepo = null;
ServiceData serviceData = null;
DefaultListModel<Category> categoriesModel = new DefaultListModel<Category>();
// below should be String NOT ServiceInterface !!!
DefaultListModel<ServiceInterface> currentServicesModel = new DefaultListModel<ServiceInterface>();
JList<Category> categories = new JList<Category>(categoriesModel);
JList<ServiceInterface> runningServices = new JList<ServiceInterface>(currentServicesModel);
ImageNameRenderer imageNameRenderer = new ImageNameRenderer();
FilterListener filterListener = new FilterListener();
JPopupMenu popup = new JPopupMenu();
ServiceInterface releasedTarget = null;
DefaultTableModel possibleServicesModel = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
PossibleServicesRenderer cellRenderer = new PossibleServicesRenderer((Runtime) Runtime.getService(boundServiceName));
JTable possibleServices = new JTable(possibleServicesModel) {
private static final long serialVersionUID = 1L;
@Override
public JToolTip createToolTip() {
JToolTip tooltip = super.createToolTip();
return tooltip;
}
// column returns content type
@Override
public Class<?> getColumnClass(int column) {
Object o = getValueAt(0, column);
if (o == null) {
return new Object().getClass();
}
return o.getClass();
}
};
public RuntimeGui(final String boundServiceName, final SwingGui myService) {
super(boundServiceName, myService);
// required - it "might" be a foreign Runtime...
myRuntime = (Runtime) Runtime.getService(boundServiceName);
myRepo = myRuntime.getRepo();
serviceData = myRuntime.getServiceData();
progressDialog = new ProgressDialog(this);
progressDialog.setVisible(false);
getCurrentServices();
ArrayList<Category> c = serviceData.getCategories();
for (int i = 0; i < c.size(); ++i) {
categoriesModel.addElement(c.get(i));
}
categories.setCellRenderer(imageNameRenderer);
categories.setFixedCellWidth(100);
categories.addListSelectionListener(this);
possibleServicesModel.addColumn("service");
possibleServicesModel.addColumn("status");
// possibleServices.setRowHeight(24);
possibleServices.setIntercellSpacing(new Dimension(0, 0));
// possibleServices.setSize(new Dimension(300, 400));
possibleServices.setShowGrid(false);
possibleServices.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// possibleServices.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
// possibleServices.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// possibleServices.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
// possibleServices.setPreferredSize(new Dimension(200, 200));
JScrollPane possible = new JScrollPane(possibleServices);
possible.setPreferredSize(new Dimension(360, 400));
TableColumnModel cm = possibleServices.getColumnModel();
cm.getColumn(0).setMaxWidth(300);
cm.getColumn(1).setMaxWidth(60);
possibleServices.setDefaultRenderer(ImageIcon.class, cellRenderer);
possibleServices.setDefaultRenderer(ServiceType.class, cellRenderer);
possibleServices.setDefaultRenderer(String.class, cellRenderer);
possibleServices.addMouseListener(new MouseAdapter() {
// isPopupTrigger over OSs - use masks
@Override
public void mouseReleased(MouseEvent e) {
log.debug("mouseReleased");
if (SwingUtilities.isRightMouseButton(e)) {
log.debug("mouseReleased - right");
popUpTrigger(e);
}
}
public void popUpTrigger(MouseEvent e) {
log.info("******************popUpTrigger*********************");
JTable source = (JTable) e.getSource();
popupRow = source.rowAtPoint(e.getPoint());
ServiceType c = (ServiceType) possibleServicesModel.getValueAt(popupRow, 0);
releaseMenuItem.setVisible(false);
infoMenuItem.setVisible(true);
if (!myRepo.isServiceTypeInstalled(c.getName())) {
// need to install it
installMenuItem.setVisible(true);
startMenuItem.setVisible(false);
upgradeMenuItem.setVisible(false);
} else {
// have it
installMenuItem.setVisible(false);
startMenuItem.setVisible(true);
}
int column = source.columnAtPoint(e.getPoint());
if (!source.isRowSelected(popupRow))
source.changeSelection(popupRow, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
runningServices.addMouseListener(new MouseAdapter() {
// isPopupTrigger over OSs - use masks
@Override
public void mouseReleased(MouseEvent e) {
log.debug("mouseReleased");
if (SwingUtilities.isRightMouseButton(e)) {
log.debug("mouseReleased - right");
popUpTrigger(e);
}
}
public void popUpTrigger(MouseEvent e) {
log.info("******************popUpTrigger*********************");
JList source = (JList) e.getSource();
int index = source.locationToIndex(e.getPoint());
if (index >= 0) {
releasedTarget = (ServiceInterface) source.getModel().getElementAt(index);
log.info(String.format("right click on running service %s", releasedTarget.getName()));
releaseMenuItem.setVisible(true);
upgradeMenuItem.setVisible(false);
installMenuItem.setVisible(false);
startMenuItem.setVisible(false);
infoMenuItem.setVisible(false);
}
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
infoMenuItem = new JMenuItem("<html><style type=\"text/css\">a { color: #000000;text-decoration: none}</style><a href=\"http://myrobotlab.org/\">info</a></html>");
infoMenuItem.setActionCommand("info");
infoMenuItem.setIcon(Util.getImageIcon("help.png"));
infoMenuItem.addActionListener(this);
popup.add(infoMenuItem);
installMenuItem = new JMenuItem("install");
installMenuItem.addActionListener(this);
installMenuItem.setIcon(Util.getImageIcon("install.png"));
popup.add(installMenuItem);
startMenuItem = new JMenuItem("start");
startMenuItem.addActionListener(this);
startMenuItem.setIcon(Util.getImageIcon("start.png"));
popup.add(startMenuItem);
upgradeMenuItem = new JMenuItem("upgrade");
upgradeMenuItem.addActionListener(this);
upgradeMenuItem.setIcon(Util.getImageIcon("upgrade.png"));
popup.add(upgradeMenuItem);
releaseMenuItem = new JMenuItem("release");
releaseMenuItem.addActionListener(this);
releaseMenuItem.setIcon(Util.getScaledIcon(Util.getImage("release.png"), 0.50));
popup.add(releaseMenuItem);
setTitle(myRuntime.getPlatform().toString());
JPanel flow = new JPanel();
flow.add(createCategories());
JPanel border = new JPanel(new BorderLayout());
search.addKeyListener(this);
border.add(search, BorderLayout.NORTH);
border.add(possible, BorderLayout.CENTER);
flow.add(border);
flow.add(createRunningServices());
addLine(flow);
// add(categories, possible, runningServices);
addTopLine(createMenuBar());
addBottom("memory physical ", totalPhysicalMemory, " max ", maxMemory, " total ", totalMemory, " free ", freeMemory, " used ", usedMemory);
getPossibleServices();
}
public JPanel createRunningServices() {
GridBagConstraints fgc = new GridBagConstraints();
JPanel panel = new JPanel(new GridBagLayout());
fgc.gridy = 0;
fgc.gridx = 0;
fgc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("running services"), fgc);
++fgc.gridy;
JScrollPane scroll = new JScrollPane(runningServices);
runningServices.setVisibleRowCount(15);
runningServices.setCellRenderer(imageNameRenderer);
runningServices.setFixedCellWidth(100);
panel.add(scroll, fgc);
return panel;
}
public JPanel createCategories() {
GridBagConstraints fgc = new GridBagConstraints();
JPanel panel = new JPanel(new GridBagLayout());
fgc.gridy = 0;
fgc.gridx = 0;
fgc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("categories"), fgc);
++fgc.gridy;
JScrollPane scroll = new JScrollPane(categories);
categories.setVisibleRowCount(15);
categories.setCellRenderer(imageNameRenderer);
categories.setFixedCellWidth(160);
panel.add(scroll, fgc);
return panel;
}
public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu system = new JMenu("system");
menuBar.add(system);
JMenu logging = new JMenu("logging");
menuBar.add(logging);
/*
JMenuItem item = new JMenuItem("check for updates");
item.addActionListener(this);
system.add(item);
*/
JMenuItem item = new JMenuItem("install all");
item.addActionListener(this);
system.add(item);
item = new JMenuItem("record");
item.addActionListener(this);
system.add(item);
item = new JMenuItem("restart");
item.addActionListener(this);
system.add(item);
item = new JMenuItem("exit");
item.addActionListener(this);
system.add(item);
JMenu m1 = new JMenu("level");
logging.add(m1);
buildLogLevelMenu(m1);
return menuBar;
}
// zod
@Override
public void actionPerformed(ActionEvent event) {
ServiceType c = (ServiceType) possibleServicesModel.getValueAt(popupRow, 0);
String cmd = event.getActionCommand();
Object o = event.getSource();
if (releaseMenuItem == o) {
myService.send(boundServiceName, "releaseService", releasedTarget.getName());
return;
}
if ("info".equals(cmd)) {
BareBonesBrowserLaunch.openURL("http://myrobotlab.org/service/" + c.getSimpleName());
} else if ("install".equals(cmd)) {
int selectedRow = possibleServices.getSelectedRow();
ServiceType entry = ((ServiceType) possibleServices.getValueAt(selectedRow, 0));
String n = entry.getName();
Repo repo = myRuntime.getRepo();
if (!repo.isServiceTypeInstalled(n)) {
// dependencies needed<SUF>
String msg = "<html>This Service has dependencies which are not yet loaded,<br>" + "do you wish to download them now?";
JOptionPane.setRootFrame(myService.getFrame());
int result = JOptionPane.showConfirmDialog(myService.getFrame(), msg, "alert", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.CANCEL_OPTION) {
return;
}
// you say "install", i say "update", repo says "resolve"
myService.send(boundServiceName, "install", n);
} else {
// no unfulfilled dependencies - good to go
addNewService(n);
}
} else if ("start".equals(cmd)) {
int selectedRow = possibleServices.getSelectedRow();
ServiceType entry = ((ServiceType) possibleServices.getValueAt(selectedRow, 0));
addNewService(entry.getName());
} else if ("install all".equals(cmd)) {
send("install");
} else if ("restart".equals(cmd)) {
Runtime.getInstance().restart();
} else if ("exit".equals(cmd)) {
Runtime.shutdown();
} else if ("check for updates".equals(cmd)) {
send("checkForUpdates");
} else if (cmd.equals(Level.DEBUG) || cmd.equals(Level.INFO) || cmd.equals(Level.WARN) || cmd.equals(Level.ERROR) || cmd.equals(Level.FATAL)) {
send("setLogLevel", cmd);/*
Logging logging = LoggingFactory.getInstance();
logging.setLevel(cmd);*/
} /*else if (cmd.equals(Appender.FILE)) {
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.FILE);
} else if (cmd.equals(Appender.CONSOLE)) {
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.CONSOLE);
} else if (cmd.equals(Appender.NONE)) {
Logging logging = LoggingFactory.getInstance();
logging.removeAllAppenders();
}*/ else {
log.error("unknown command " + cmd);
}
// end actionCmd
}
public void addNewService(String newService) {
JFrame frame = new JFrame();
frame.setTitle("add new service");
String name = JOptionPane.showInputDialog(frame, "new service name");
if (name != null && name.length() > 0) {
myService.send(boundServiceName, "createAndStart", name, newService);
}
}
/*
* scheduled event of reporting on system resources
*/
public void onSystemResources(SystemResources resources) {
totalPhysicalMemory.setText(String.format("%d", resources.getTotalPhysicalMemory()));
maxMemory.setText(String.format("%d", resources.getMaxMemory()));
totalMemory.setText(String.format("%d", resources.getTotalMemory()));
freeMemory.setText(String.format("%d", resources.getFreeMemory()));
usedMemory.setText(String.format("%d", resources.getTotalMemory() - resources.getFreeMemory()));
}
@Override
public void subscribeGui() {
subscribe("registered");
subscribe("released");
subscribe("getSystemResources");
subscribe("publishInstallProgress");
}
@Override
public void unsubscribeGui() {
unsubscribe("registered");
unsubscribe("released");
subscribe("getSystemResources");
unsubscribe("publishInstallProgress");
}
/**
* Add all options to the Log Level menu.
*
* @param parentMenu
*/
private void buildLogLevelMenu(JMenu parentMenu) {
ButtonGroup logLevelGroup = new ButtonGroup();
String level = LoggingFactory.getInstance().getLevel();
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(Level.DEBUG);
mi.setSelected(("DEBUG".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.INFO);
mi.setSelected(("INFO".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.WARN);
mi.setSelected(("WARN".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.ERROR);
mi.setSelected(("ERROR".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
mi = new JRadioButtonMenuItem(Level.FATAL); // TODO - deprecate to WTF
// :)
mi.setSelected(("FATAL".equals(level)));
mi.addActionListener(this);
logLevelGroup.add(mi);
parentMenu.add(mi);
}
public void checkingForUpdates() {
// FIXME - if auto update or check on startup - we don't want a silly
// dialog
// we just want to be notified if there "is" an update - and whether or
// not we
// should apply it
// FIXME - bypass is auto
progressDialog.checkingForUpdates();
}
public void failedDependency(String dep) {
JOptionPane.showMessageDialog(null, "<html>Unable to load Service...<br>" + dep + "</html>", "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Add data to the list model for display
*/
public void getCurrentServices() {
// can't be static
Map<String, ServiceInterface> services = Runtime.getRegistry();
Map<String, ServiceInterface> sortedMap = null;
sortedMap = new TreeMap<String, ServiceInterface>(services);
Iterator<String> it = sortedMap.keySet().iterator();
while (it.hasNext()) {
String serviceName = it.next();
ServiceInterface si = Runtime.getService(serviceName);
currentServicesModel.addElement(si);
nameToServiceEntry.put(serviceName, si);
}
}
public void getPossibleServices() {
getPossibleServicesFromCategory(null);
}
public void getPossibleServicesFromName(final String filter) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String filtered = (filter == null) ? "" : filter.trim();
// clear data
for (int i = possibleServicesModel.getRowCount(); i > 0; --i) {
possibleServicesModel.removeRow(i - 1);
}
// populate with serviceData
ArrayList<ServiceType> possibleService = serviceData.getServiceTypes();
for (int i = 0; i < possibleService.size(); ++i) {
ServiceType serviceType = possibleService.get(i);
if (filtered == "" || serviceType.getSimpleName().toLowerCase().indexOf(filtered.toLowerCase()) != -1) {
if (serviceType.isAvailable()) {
possibleServicesModel.addRow(new Object[] { serviceType, "" });
}
}
}
possibleServicesModel.fireTableDataChanged();
possibleServices.invalidate();
}
});
}
/*
* lame - deprecate - refactor - or better yet make webgui FIXME this should
* rarely change .... remove getServiceTypeNames
*/
public void getPossibleServicesFromCategory(final String filter) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// clear data
for (int i = possibleServicesModel.getRowCount(); i > 0; --i) {
possibleServicesModel.removeRow(i - 1);
}
Category category = serviceData.getCategory(filter);
HashSet<String> filtered = null;
if (category != null) {
filtered = new HashSet<String>();
ArrayList<String> f = category.serviceTypes;
for (int i = 0; i < f.size(); ++i) {
filtered.add(f.get(i));
}
}
// populate with serviceData
ArrayList<ServiceType> possibleService = serviceData.getServiceTypes();
for (int i = 0; i < possibleService.size(); ++i) {
ServiceType serviceType = possibleService.get(i);
if (filtered == null || filtered.contains(serviceType.getName())) {
if (serviceType.isAvailable()) {
possibleServicesModel.addRow(new Object[] { serviceType, "" });
}
}
}
possibleServicesModel.fireTableDataChanged();
possibleServices.invalidate();
}
});
}
public void onState(final Runtime runtime) {
myRuntime = runtime;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Platform platform = myRuntime.getPlatform();
SystemResources resources = myRuntime.getSystemResources();
totalMemory.setText(String.format("%d", resources.getTotalMemory()));
freeMemory.setText(String.format("%d", resources.getFreeMemory()));
totalPhysicalMemory.setText(String.format("%d", resources.getTotalPhysicalMemory()));
// FIXME - change to "all" or "" - null is sloppy - system has
// to upcast
myService.pack();
}
});
}
/*
* new Service has been created list it..
*/
public ServiceInterface onRegistered(Service sw) {
currentServicesModel.addElement(sw);
return sw;
}
/*
* a Service of this Runtime has been released
*/
public ServiceInterface onReleased(Service sw) {
currentServicesModel.removeElement(sw);
return sw;
}
/**
* a restart command will be sent to the appropriate runtime
*/
public void restart() {
// send("restart"); TODO - change back to restart - when it works
send("shutdown");
}
public void onInstallProgress(Status status) {
if (Repo.INSTALL_START.equals(status.key)) {
progressDialog.beginUpdates();
} else if (Repo.INSTALL_FINISHED.equals(status.key)) {
progressDialog.finished();
}
progressDialog.addStatus(status);
}
/**
* this is the beginning of the applyUpdates process
*/
public void updatesBegin() {
progressDialog.beginUpdates();
}
@Override
public void valueChanged(ListSelectionEvent e) {
Object o = e.getSource();
if (o == categories && !e.getValueIsAdjusting()) {
Category category = categories.getSelectedValue();
String categoryFilter = null;
if (category != null) {
categoryFilter = categories.getSelectedValue().getName();
log.info("valueChanged {}", categoryFilter);
} else {
log.info("valueChanged null");
}
getPossibleServicesFromCategory(categoryFilter);
}
}
@Override
public void keyTyped(KeyEvent e) {
getPossibleServicesFromName(search.getText() + e.getKeyChar());
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
} |
22405_2 | package hamhamdash.states;
import hamhamdash.*;
/**
*
* @author Serhan Uygur
*/
public class StatePause extends State
{
private String toDrawImage = "";
// Pause Screens
// [ Main Screen Name ][ Sub Screens ][ Pages ]
private String[][][] pauseScreens =
{
// Item 0, zonder submenu's
{
{"pause_res_game"},
{""},
{""}
},
// Item 1, met submenu's
{
{"pause_help"},
{"game_goal", "game_controls", "game_objects", "game_back"},
{"2", "2", "8", "0"}
},
// Item 2, zonder submenu's
{
{"pause_exit_title"},
{""},
{""}
},
// Item 3, zonder submenu's
{
{"pause_exit_windows"},
{""},
{""}
}
};
// Counters for the screens
private int currentMainScreen = 0;
private int currentSubScreen = 0;
private int currentPage = 0;
// Checkers for sub or not
private boolean inSub = false;
private boolean arePages = false;
public StatePause()
{
super("pauze");
toDrawImage = pauseScreens[0][0][0];
game.stopTimer();
started = true;
}
@Override
public void start()
{
}
@Override
public void doFrame()
{
if(started)
{
if(game.getKey(Game.KeyEsc))
{
game.clearKey(Game.KeyEsc);
if(inSub) //Go back to previous menu
{
inSub = false;
toDrawImage = pauseScreens[1][0][0];
currentSubScreen = 0;
}
else //Exit pause state
{
game.recoverState();
game.startTimer();
game.repaint();
// game.removeGameState("Pause");
}
}
//navigate between options
else if(game.getKey(Game.KeyUp)) // Moves selection up
{
game.clearKey(Game.KeyUp);
currentPage = 1;
prevScreen(pauseScreens);
}
else if(game.getKey(Game.KeyDown)) // Moves selection down
{
game.clearKey(Game.KeyDown);
currentPage = 1;
nextScreen(pauseScreens);
}
else if(game.getKey(Game.KeyEnter)) // Confirm selection
{
game.clearKey(Game.KeyEnter);
if(toDrawImage.equals(pauseScreens[0][0][0]))
{
game.recoverState();
// game.removeGameState("Pause");
}
else if(toDrawImage.equals(pauseScreens[1][0][0])) // Help item has subs
{
inSub = true;
toDrawImage = pauseScreens[1][1][0] + 1; // select 1st sub page
}
else if(toDrawImage.equals(pauseScreens[2][0][0]))
{
game.setCurrentState("Title");
}
else if(toDrawImage.equals(pauseScreens[3][0][0]))
{
game.exitEngine("Thank you for playing!");
}
if(toDrawImage.equals(pauseScreens[1][1][3] + 1))
{
inSub = false;
toDrawImage = pauseScreens[1][0][0];
currentSubScreen = 0;
}
}
//Cycle through pages
else if(game.getKey(Game.KeyRight) && inSub) //Go page forward
{
game.clearKey(Game.KeyRight);
nextPage(pauseScreens);
}
else if(game.getKey(Game.KeyLeft) && inSub) //Go back a page
{
game.clearKey(Game.KeyLeft);
prevPage(pauseScreens);
}
}
}
@Override
public void paintFrame()
{
if(started)
{
game.drawImage(game.viewWidth() / 2 - (256 / 2), game.viewHeight() / 2 - (250 / 2), toDrawImage, false);
}
}
public void nextScreen(String[][][] screens)
{
String toDrawImage = "";
if(!inSub)
{
if(currentMainScreen < screens.length - 1) // -1 because we start with 0
{
currentMainScreen++;
}
toDrawImage = screens[currentMainScreen][0][0];
}
else
{
if(currentSubScreen < screens[currentMainScreen].length)
{
currentSubScreen++;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1;
}
this.toDrawImage = toDrawImage;
}
public void prevScreen(String[][][] screens)
{
String toDrawImage = "";
if(!inSub)
{
if(currentMainScreen > 0)
{
currentMainScreen--;
}
toDrawImage = screens[currentMainScreen][0][0];
}
else
{
if(currentSubScreen > 0)
{
currentSubScreen--;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1;
}
this.toDrawImage = toDrawImage;
}
public void nextPage(String[][][] screens)
{
String toDrawImage = "";
if(currentPage < Integer.parseInt(screens[currentMainScreen][2][currentSubScreen]))
{
currentPage++;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage;
this.toDrawImage = toDrawImage;
}
public void prevPage(String[][][] screens)
{
String toDrawImage = "";
if(currentPage > 1)
{
currentPage--;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage;
this.toDrawImage = toDrawImage;
}
}
| Lenrocexe/HamHamDash | src/hamhamdash/states/StatePause.java | 1,709 | // Item 0, zonder submenu's | line_comment | nl | package hamhamdash.states;
import hamhamdash.*;
/**
*
* @author Serhan Uygur
*/
public class StatePause extends State
{
private String toDrawImage = "";
// Pause Screens
// [ Main Screen Name ][ Sub Screens ][ Pages ]
private String[][][] pauseScreens =
{
// Item 0,<SUF>
{
{"pause_res_game"},
{""},
{""}
},
// Item 1, met submenu's
{
{"pause_help"},
{"game_goal", "game_controls", "game_objects", "game_back"},
{"2", "2", "8", "0"}
},
// Item 2, zonder submenu's
{
{"pause_exit_title"},
{""},
{""}
},
// Item 3, zonder submenu's
{
{"pause_exit_windows"},
{""},
{""}
}
};
// Counters for the screens
private int currentMainScreen = 0;
private int currentSubScreen = 0;
private int currentPage = 0;
// Checkers for sub or not
private boolean inSub = false;
private boolean arePages = false;
public StatePause()
{
super("pauze");
toDrawImage = pauseScreens[0][0][0];
game.stopTimer();
started = true;
}
@Override
public void start()
{
}
@Override
public void doFrame()
{
if(started)
{
if(game.getKey(Game.KeyEsc))
{
game.clearKey(Game.KeyEsc);
if(inSub) //Go back to previous menu
{
inSub = false;
toDrawImage = pauseScreens[1][0][0];
currentSubScreen = 0;
}
else //Exit pause state
{
game.recoverState();
game.startTimer();
game.repaint();
// game.removeGameState("Pause");
}
}
//navigate between options
else if(game.getKey(Game.KeyUp)) // Moves selection up
{
game.clearKey(Game.KeyUp);
currentPage = 1;
prevScreen(pauseScreens);
}
else if(game.getKey(Game.KeyDown)) // Moves selection down
{
game.clearKey(Game.KeyDown);
currentPage = 1;
nextScreen(pauseScreens);
}
else if(game.getKey(Game.KeyEnter)) // Confirm selection
{
game.clearKey(Game.KeyEnter);
if(toDrawImage.equals(pauseScreens[0][0][0]))
{
game.recoverState();
// game.removeGameState("Pause");
}
else if(toDrawImage.equals(pauseScreens[1][0][0])) // Help item has subs
{
inSub = true;
toDrawImage = pauseScreens[1][1][0] + 1; // select 1st sub page
}
else if(toDrawImage.equals(pauseScreens[2][0][0]))
{
game.setCurrentState("Title");
}
else if(toDrawImage.equals(pauseScreens[3][0][0]))
{
game.exitEngine("Thank you for playing!");
}
if(toDrawImage.equals(pauseScreens[1][1][3] + 1))
{
inSub = false;
toDrawImage = pauseScreens[1][0][0];
currentSubScreen = 0;
}
}
//Cycle through pages
else if(game.getKey(Game.KeyRight) && inSub) //Go page forward
{
game.clearKey(Game.KeyRight);
nextPage(pauseScreens);
}
else if(game.getKey(Game.KeyLeft) && inSub) //Go back a page
{
game.clearKey(Game.KeyLeft);
prevPage(pauseScreens);
}
}
}
@Override
public void paintFrame()
{
if(started)
{
game.drawImage(game.viewWidth() / 2 - (256 / 2), game.viewHeight() / 2 - (250 / 2), toDrawImage, false);
}
}
public void nextScreen(String[][][] screens)
{
String toDrawImage = "";
if(!inSub)
{
if(currentMainScreen < screens.length - 1) // -1 because we start with 0
{
currentMainScreen++;
}
toDrawImage = screens[currentMainScreen][0][0];
}
else
{
if(currentSubScreen < screens[currentMainScreen].length)
{
currentSubScreen++;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1;
}
this.toDrawImage = toDrawImage;
}
public void prevScreen(String[][][] screens)
{
String toDrawImage = "";
if(!inSub)
{
if(currentMainScreen > 0)
{
currentMainScreen--;
}
toDrawImage = screens[currentMainScreen][0][0];
}
else
{
if(currentSubScreen > 0)
{
currentSubScreen--;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1;
}
this.toDrawImage = toDrawImage;
}
public void nextPage(String[][][] screens)
{
String toDrawImage = "";
if(currentPage < Integer.parseInt(screens[currentMainScreen][2][currentSubScreen]))
{
currentPage++;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage;
this.toDrawImage = toDrawImage;
}
public void prevPage(String[][][] screens)
{
String toDrawImage = "";
if(currentPage > 1)
{
currentPage--;
}
toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage;
this.toDrawImage = toDrawImage;
}
}
|
37626_20 | package mindustry.entities.comp;
import arc.*;
import arc.func.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.struct.Queue;
import arc.util.*;
import mindustry.*;
import mindustry.annotations.Annotations.*;
import mindustry.content.*;
import mindustry.entities.units.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.gen.*;
import mindustry.graphics.*;
import mindustry.type.*;
import mindustry.world.*;
import mindustry.world.blocks.*;
import mindustry.world.blocks.ConstructBlock.*;
import java.util.*;
import static mindustry.Vars.*;
@Component
abstract class BuilderComp implements Posc, Statusc, Teamc, Rotc{
@Import float x, y, rotation, buildSpeedMultiplier;
@Import UnitType type;
@Import Team team;
@SyncLocal Queue<BuildPlan> plans = new Queue<>(1);
@SyncLocal boolean updateBuilding = true;
private transient float buildCounter;
private transient BuildPlan lastActive;
private transient int lastSize;
transient float buildAlpha = 0f;
public boolean canBuild(){
return type.buildSpeed > 0 && buildSpeedMultiplier > 0;
}
@Override
public void update(){
updateBuildLogic();
}
@Override
public void afterRead(){
//why would this happen?
if(plans == null){
plans = new Queue<>(1);
}
}
public void validatePlans(){
if(plans.size > 0){
Iterator<BuildPlan> it = plans.iterator();
while(it.hasNext()){
BuildPlan plan = it.next();
Tile tile = world.tile(plan.x, plan.y);
boolean isSameDerelict = (tile != null && tile.build != null && tile.block() == plan.block && tile.build.tileX() == plan.x && tile.build.tileY() == plan.y && tile.team() == Team.derelict);
if(tile == null || (plan.breaking && tile.block() == Blocks.air) || (!plan.breaking && ((tile.build != null && tile.build.rotation == plan.rotation && !isSameDerelict) || !plan.block.rotate) &&
//th block must be the same, but not derelict and the same
((tile.block() == plan.block && !isSameDerelict) ||
//same floor or overlay
(plan.block != null && (plan.block.isOverlay() && plan.block == tile.overlay() || (plan.block.isFloor() && plan.block == tile.floor())))))){
it.remove();
}
}
}
}
public void updateBuildLogic(){
if(type.buildSpeed <= 0f) return;
if(!headless){
//visual activity update
if(lastActive != null && buildAlpha <= 0.01f){
lastActive = null;
}
buildAlpha = Mathf.lerpDelta(buildAlpha, activelyBuilding() ? 1f : 0f, 0.15f);
}
validatePlans();
if(!updateBuilding || !canBuild()){
return;
}
float finalPlaceDst = state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange;
boolean infinite = state.rules.infiniteResources || team().rules().infiniteResources;
buildCounter += Time.delta;
if(Float.isNaN(buildCounter) || Float.isInfinite(buildCounter)) buildCounter = 0f;
buildCounter = Math.min(buildCounter, 10f);
boolean instant = state.rules.instantBuild && state.rules.infiniteResources;
//random attempt to fix a freeze that only occurs on Android
int maxPerFrame = instant ? plans.size : 10, count = 0;
var core = core();
if((core == null && !infinite)) return;
while((buildCounter >= 1 || instant) && count++ < maxPerFrame && plans.size > 0){
buildCounter -= 1f;
//find the next build plan
if(plans.size > 1){
int total = 0;
int size = plans.size;
BuildPlan plan;
while((!within((plan = buildPlan()).tile(), finalPlaceDst) || shouldSkip(plan, core)) && total < size){
plans.removeFirst();
plans.addLast(plan);
total++;
}
}
BuildPlan current = buildPlan();
Tile tile = current.tile();
lastActive = current;
buildAlpha = 1f;
if(current.breaking) lastSize = tile.block().size;
if(!within(tile, finalPlaceDst)) continue;
if(!headless){
Vars.control.sound.loop(Sounds.build, tile, 0.15f);
}
if(!(tile.build instanceof ConstructBuild cb)){
if(!current.initialized && !current.breaking && Build.validPlace(current.block, team, current.x, current.y, current.rotation)){
boolean hasAll = infinite || current.isRotation(team) ||
//derelict repair
(tile.team() == Team.derelict && tile.block() == current.block && tile.build != null && tile.block().allowDerelictRepair && state.rules.derelictRepair) ||
//make sure there's at least 1 item of each type first
!Structs.contains(current.block.requirements, i -> core != null && !core.items.has(i.item, Math.min(Mathf.round(i.amount * state.rules.buildCostMultiplier), 1)));
if(hasAll){
Call.beginPlace(self(), current.block, team, current.x, current.y, current.rotation);
}else{
current.stuck = true;
}
}else if(!current.initialized && current.breaking && Build.validBreak(team, current.x, current.y)){
Call.beginBreak(self(), team, current.x, current.y);
}else{
plans.removeFirst();
continue;
}
}else if((tile.team() != team && tile.team() != Team.derelict) || (!current.breaking && (cb.current != current.block || cb.tile != current.tile()))){
plans.removeFirst();
continue;
}
if(tile.build instanceof ConstructBuild && !current.initialized){
Events.fire(new BuildSelectEvent(tile, team, self(), current.breaking));
current.initialized = true;
}
//if there is no core to build with or no build entity, stop building!
if(!(tile.build instanceof ConstructBuild entity)){
continue;
}
float bs = 1f / entity.buildCost * type.buildSpeed * buildSpeedMultiplier * state.rules.buildSpeed(team);
//otherwise, update it.
if(current.breaking){
entity.deconstruct(self(), core, bs);
}else{
entity.construct(self(), core, bs, current.config);
}
current.stuck = Mathf.equal(current.progress, entity.progress);
current.progress = entity.progress;
}
}
/** Draw all current build plans. Does not draw the beam effect, only the positions. */
void drawBuildPlans(){
Boolf<BuildPlan> skip = plan -> plan.progress > 0.01f || (buildPlan() == plan && plan.initialized && (within(plan.x * tilesize, plan.y * tilesize, type.buildRange) || state.isEditor()));
for(int i = 0; i < 2; i++){
for(BuildPlan plan : plans){
if(skip.get(plan)) continue;
if(i == 0){
drawPlan(plan, 1f);
}else{
drawPlanTop(plan, 1f);
}
}
}
Draw.reset();
}
void drawPlan(BuildPlan plan, float alpha){
plan.animScale = 1f;
if(plan.breaking){
control.input.drawBreaking(plan);
}else{
plan.block.drawPlan(plan, control.input.allPlans(),
Build.validPlace(plan.block, team, plan.x, plan.y, plan.rotation) || control.input.planMatches(plan),
alpha);
}
}
void drawPlanTop(BuildPlan plan, float alpha){
if(!plan.breaking){
Draw.reset();
Draw.mixcol(Color.white, 0.24f + Mathf.absin(Time.globalTime, 6f, 0.28f));
Draw.alpha(alpha);
plan.block.drawPlanConfigTop(plan, plans);
}
}
/** @return whether this plan should be skipped, in favor of the next one. */
boolean shouldSkip(BuildPlan plan, @Nullable Building core){
//plans that you have at least *started* are considered
if(state.rules.infiniteResources || team.rules().infiniteResources || plan.breaking || core == null || plan.isRotation(team) || (isBuilding() && !within(plans.last(), type.buildRange))) return false;
return (plan.stuck && !core.items.has(plan.block.requirements)) || (Structs.contains(plan.block.requirements, i -> !core.items.has(i.item, Math.min(i.amount, 15)) && Mathf.round(i.amount * state.rules.buildCostMultiplier) > 0) && !plan.initialized);
}
void removeBuild(int x, int y, boolean breaking){
//remove matching plan
int idx = plans.indexOf(req -> req.breaking == breaking && req.x == x && req.y == y);
if(idx != -1){
plans.removeIndex(idx);
}
}
/** Return whether this builder's place queue contains items. */
boolean isBuilding(){
return plans.size != 0;
}
/** Clears the placement queue. */
void clearBuilding(){
plans.clear();
}
/** Add another build plans to the tail of the queue, if it doesn't exist there yet. */
void addBuild(BuildPlan place){
addBuild(place, true);
}
/** Add another build plans to the queue, if it doesn't exist there yet. */
void addBuild(BuildPlan place, boolean tail){
if(!canBuild()) return;
BuildPlan replace = null;
for(BuildPlan plan : plans){
if(plan.x == place.x && plan.y == place.y){
replace = plan;
break;
}
}
if(replace != null){
plans.remove(replace);
}
Tile tile = world.tile(place.x, place.y);
if(tile != null && tile.build instanceof ConstructBuild cons){
place.progress = cons.progress;
}
if(tail){
plans.addLast(place);
}else{
plans.addFirst(place);
}
}
boolean activelyBuilding(){
//not actively building when not near the build plan
if(isBuilding()){
var plan = buildPlan();
if(!state.isEditor() && plan != null && !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){
return false;
}
}
return isBuilding() && updateBuilding;
}
/** @return the build plan currently active, or the one at the top of the queue.*/
@Nullable BuildPlan buildPlan(){
return plans.size == 0 ? null : plans.first();
}
public void drawBuilding(){
//TODO make this more generic so it works with builder "weapons"
boolean active = activelyBuilding();
if(!active && lastActive == null) return;
Draw.z(Layer.flyingUnit);
BuildPlan plan = active ? buildPlan() : lastActive;
Tile tile = plan.tile();
var core = team.core();
if(tile == null || !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){
return;
}
//draw remote plans.
if(core != null && active && !isLocal() && !(tile.block() instanceof ConstructBlock)){
Draw.z(Layer.plans - 1f);
drawPlan(plan, 0.5f);
drawPlanTop(plan, 0.5f);
Draw.z(Layer.flyingUnit);
}
if(type.drawBuildBeam){
float focusLen = type.buildBeamOffset + Mathf.absin(Time.time, 3f, 0.6f);
float px = x + Angles.trnsx(rotation, focusLen);
float py = y + Angles.trnsy(rotation, focusLen);
drawBuildingBeam(px, py);
}
}
public void drawBuildingBeam(float px, float py){
boolean active = activelyBuilding();
if(!active && lastActive == null) return;
Draw.z(Layer.flyingUnit);
BuildPlan plan = active ? buildPlan() : lastActive;
Tile tile = world.tile(plan.x, plan.y);
if(tile == null || !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){
return;
}
int size = plan.breaking ? active ? tile.block().size : lastSize : plan.block.size;
float tx = plan.drawx(), ty = plan.drawy();
Lines.stroke(1f, plan.breaking ? Pal.remove : Pal.accent);
Draw.z(Layer.buildBeam);
Draw.alpha(buildAlpha);
if(!active && !(tile.build instanceof ConstructBuild)){
Fill.square(plan.drawx(), plan.drawy(), size * tilesize/2f);
}
Drawf.buildBeam(px, py, tx, ty, Vars.tilesize * size / 2f);
Fill.square(px, py, 1.8f + Mathf.absin(Time.time, 2.2f, 1.1f), rotation + 45);
Draw.reset();
Draw.z(Layer.flyingUnit);
}
}
| Leo-MathGuy/Mindustry | core/src/mindustry/entities/comp/BuilderComp.java | 3,798 | //draw remote plans. | line_comment | nl | package mindustry.entities.comp;
import arc.*;
import arc.func.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.struct.Queue;
import arc.util.*;
import mindustry.*;
import mindustry.annotations.Annotations.*;
import mindustry.content.*;
import mindustry.entities.units.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.gen.*;
import mindustry.graphics.*;
import mindustry.type.*;
import mindustry.world.*;
import mindustry.world.blocks.*;
import mindustry.world.blocks.ConstructBlock.*;
import java.util.*;
import static mindustry.Vars.*;
@Component
abstract class BuilderComp implements Posc, Statusc, Teamc, Rotc{
@Import float x, y, rotation, buildSpeedMultiplier;
@Import UnitType type;
@Import Team team;
@SyncLocal Queue<BuildPlan> plans = new Queue<>(1);
@SyncLocal boolean updateBuilding = true;
private transient float buildCounter;
private transient BuildPlan lastActive;
private transient int lastSize;
transient float buildAlpha = 0f;
public boolean canBuild(){
return type.buildSpeed > 0 && buildSpeedMultiplier > 0;
}
@Override
public void update(){
updateBuildLogic();
}
@Override
public void afterRead(){
//why would this happen?
if(plans == null){
plans = new Queue<>(1);
}
}
public void validatePlans(){
if(plans.size > 0){
Iterator<BuildPlan> it = plans.iterator();
while(it.hasNext()){
BuildPlan plan = it.next();
Tile tile = world.tile(plan.x, plan.y);
boolean isSameDerelict = (tile != null && tile.build != null && tile.block() == plan.block && tile.build.tileX() == plan.x && tile.build.tileY() == plan.y && tile.team() == Team.derelict);
if(tile == null || (plan.breaking && tile.block() == Blocks.air) || (!plan.breaking && ((tile.build != null && tile.build.rotation == plan.rotation && !isSameDerelict) || !plan.block.rotate) &&
//th block must be the same, but not derelict and the same
((tile.block() == plan.block && !isSameDerelict) ||
//same floor or overlay
(plan.block != null && (plan.block.isOverlay() && plan.block == tile.overlay() || (plan.block.isFloor() && plan.block == tile.floor())))))){
it.remove();
}
}
}
}
public void updateBuildLogic(){
if(type.buildSpeed <= 0f) return;
if(!headless){
//visual activity update
if(lastActive != null && buildAlpha <= 0.01f){
lastActive = null;
}
buildAlpha = Mathf.lerpDelta(buildAlpha, activelyBuilding() ? 1f : 0f, 0.15f);
}
validatePlans();
if(!updateBuilding || !canBuild()){
return;
}
float finalPlaceDst = state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange;
boolean infinite = state.rules.infiniteResources || team().rules().infiniteResources;
buildCounter += Time.delta;
if(Float.isNaN(buildCounter) || Float.isInfinite(buildCounter)) buildCounter = 0f;
buildCounter = Math.min(buildCounter, 10f);
boolean instant = state.rules.instantBuild && state.rules.infiniteResources;
//random attempt to fix a freeze that only occurs on Android
int maxPerFrame = instant ? plans.size : 10, count = 0;
var core = core();
if((core == null && !infinite)) return;
while((buildCounter >= 1 || instant) && count++ < maxPerFrame && plans.size > 0){
buildCounter -= 1f;
//find the next build plan
if(plans.size > 1){
int total = 0;
int size = plans.size;
BuildPlan plan;
while((!within((plan = buildPlan()).tile(), finalPlaceDst) || shouldSkip(plan, core)) && total < size){
plans.removeFirst();
plans.addLast(plan);
total++;
}
}
BuildPlan current = buildPlan();
Tile tile = current.tile();
lastActive = current;
buildAlpha = 1f;
if(current.breaking) lastSize = tile.block().size;
if(!within(tile, finalPlaceDst)) continue;
if(!headless){
Vars.control.sound.loop(Sounds.build, tile, 0.15f);
}
if(!(tile.build instanceof ConstructBuild cb)){
if(!current.initialized && !current.breaking && Build.validPlace(current.block, team, current.x, current.y, current.rotation)){
boolean hasAll = infinite || current.isRotation(team) ||
//derelict repair
(tile.team() == Team.derelict && tile.block() == current.block && tile.build != null && tile.block().allowDerelictRepair && state.rules.derelictRepair) ||
//make sure there's at least 1 item of each type first
!Structs.contains(current.block.requirements, i -> core != null && !core.items.has(i.item, Math.min(Mathf.round(i.amount * state.rules.buildCostMultiplier), 1)));
if(hasAll){
Call.beginPlace(self(), current.block, team, current.x, current.y, current.rotation);
}else{
current.stuck = true;
}
}else if(!current.initialized && current.breaking && Build.validBreak(team, current.x, current.y)){
Call.beginBreak(self(), team, current.x, current.y);
}else{
plans.removeFirst();
continue;
}
}else if((tile.team() != team && tile.team() != Team.derelict) || (!current.breaking && (cb.current != current.block || cb.tile != current.tile()))){
plans.removeFirst();
continue;
}
if(tile.build instanceof ConstructBuild && !current.initialized){
Events.fire(new BuildSelectEvent(tile, team, self(), current.breaking));
current.initialized = true;
}
//if there is no core to build with or no build entity, stop building!
if(!(tile.build instanceof ConstructBuild entity)){
continue;
}
float bs = 1f / entity.buildCost * type.buildSpeed * buildSpeedMultiplier * state.rules.buildSpeed(team);
//otherwise, update it.
if(current.breaking){
entity.deconstruct(self(), core, bs);
}else{
entity.construct(self(), core, bs, current.config);
}
current.stuck = Mathf.equal(current.progress, entity.progress);
current.progress = entity.progress;
}
}
/** Draw all current build plans. Does not draw the beam effect, only the positions. */
void drawBuildPlans(){
Boolf<BuildPlan> skip = plan -> plan.progress > 0.01f || (buildPlan() == plan && plan.initialized && (within(plan.x * tilesize, plan.y * tilesize, type.buildRange) || state.isEditor()));
for(int i = 0; i < 2; i++){
for(BuildPlan plan : plans){
if(skip.get(plan)) continue;
if(i == 0){
drawPlan(plan, 1f);
}else{
drawPlanTop(plan, 1f);
}
}
}
Draw.reset();
}
void drawPlan(BuildPlan plan, float alpha){
plan.animScale = 1f;
if(plan.breaking){
control.input.drawBreaking(plan);
}else{
plan.block.drawPlan(plan, control.input.allPlans(),
Build.validPlace(plan.block, team, plan.x, plan.y, plan.rotation) || control.input.planMatches(plan),
alpha);
}
}
void drawPlanTop(BuildPlan plan, float alpha){
if(!plan.breaking){
Draw.reset();
Draw.mixcol(Color.white, 0.24f + Mathf.absin(Time.globalTime, 6f, 0.28f));
Draw.alpha(alpha);
plan.block.drawPlanConfigTop(plan, plans);
}
}
/** @return whether this plan should be skipped, in favor of the next one. */
boolean shouldSkip(BuildPlan plan, @Nullable Building core){
//plans that you have at least *started* are considered
if(state.rules.infiniteResources || team.rules().infiniteResources || plan.breaking || core == null || plan.isRotation(team) || (isBuilding() && !within(plans.last(), type.buildRange))) return false;
return (plan.stuck && !core.items.has(plan.block.requirements)) || (Structs.contains(plan.block.requirements, i -> !core.items.has(i.item, Math.min(i.amount, 15)) && Mathf.round(i.amount * state.rules.buildCostMultiplier) > 0) && !plan.initialized);
}
void removeBuild(int x, int y, boolean breaking){
//remove matching plan
int idx = plans.indexOf(req -> req.breaking == breaking && req.x == x && req.y == y);
if(idx != -1){
plans.removeIndex(idx);
}
}
/** Return whether this builder's place queue contains items. */
boolean isBuilding(){
return plans.size != 0;
}
/** Clears the placement queue. */
void clearBuilding(){
plans.clear();
}
/** Add another build plans to the tail of the queue, if it doesn't exist there yet. */
void addBuild(BuildPlan place){
addBuild(place, true);
}
/** Add another build plans to the queue, if it doesn't exist there yet. */
void addBuild(BuildPlan place, boolean tail){
if(!canBuild()) return;
BuildPlan replace = null;
for(BuildPlan plan : plans){
if(plan.x == place.x && plan.y == place.y){
replace = plan;
break;
}
}
if(replace != null){
plans.remove(replace);
}
Tile tile = world.tile(place.x, place.y);
if(tile != null && tile.build instanceof ConstructBuild cons){
place.progress = cons.progress;
}
if(tail){
plans.addLast(place);
}else{
plans.addFirst(place);
}
}
boolean activelyBuilding(){
//not actively building when not near the build plan
if(isBuilding()){
var plan = buildPlan();
if(!state.isEditor() && plan != null && !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){
return false;
}
}
return isBuilding() && updateBuilding;
}
/** @return the build plan currently active, or the one at the top of the queue.*/
@Nullable BuildPlan buildPlan(){
return plans.size == 0 ? null : plans.first();
}
public void drawBuilding(){
//TODO make this more generic so it works with builder "weapons"
boolean active = activelyBuilding();
if(!active && lastActive == null) return;
Draw.z(Layer.flyingUnit);
BuildPlan plan = active ? buildPlan() : lastActive;
Tile tile = plan.tile();
var core = team.core();
if(tile == null || !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){
return;
}
//draw remote<SUF>
if(core != null && active && !isLocal() && !(tile.block() instanceof ConstructBlock)){
Draw.z(Layer.plans - 1f);
drawPlan(plan, 0.5f);
drawPlanTop(plan, 0.5f);
Draw.z(Layer.flyingUnit);
}
if(type.drawBuildBeam){
float focusLen = type.buildBeamOffset + Mathf.absin(Time.time, 3f, 0.6f);
float px = x + Angles.trnsx(rotation, focusLen);
float py = y + Angles.trnsy(rotation, focusLen);
drawBuildingBeam(px, py);
}
}
public void drawBuildingBeam(float px, float py){
boolean active = activelyBuilding();
if(!active && lastActive == null) return;
Draw.z(Layer.flyingUnit);
BuildPlan plan = active ? buildPlan() : lastActive;
Tile tile = world.tile(plan.x, plan.y);
if(tile == null || !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){
return;
}
int size = plan.breaking ? active ? tile.block().size : lastSize : plan.block.size;
float tx = plan.drawx(), ty = plan.drawy();
Lines.stroke(1f, plan.breaking ? Pal.remove : Pal.accent);
Draw.z(Layer.buildBeam);
Draw.alpha(buildAlpha);
if(!active && !(tile.build instanceof ConstructBuild)){
Fill.square(plan.drawx(), plan.drawy(), size * tilesize/2f);
}
Drawf.buildBeam(px, py, tx, ty, Vars.tilesize * size / 2f);
Fill.square(px, py, 1.8f + Mathf.absin(Time.time, 2.2f, 1.1f), rotation + 45);
Draw.reset();
Draw.z(Layer.flyingUnit);
}
}
|
117307_4 | package me.leon.trinity.gui.setting;
import me.leon.trinity.gui.IComponent;
import me.leon.trinity.gui.button.ButtonComponent;
import me.leon.trinity.gui.button.IButton;
import me.leon.trinity.hacks.client.ClickGUI;
import me.leon.trinity.main.Trinity;
import me.leon.trinity.setting.rewrite.ColorSetting;
import me.leon.trinity.setting.rewrite.Setting;
import me.leon.trinity.utils.math.MathUtils;
import me.leon.trinity.utils.misc.FontUtil;
import me.leon.trinity.utils.rendering.GuiUtils;
import me.leon.trinity.utils.rendering.RenderUtils;
import me.leon.trinity.utils.rendering.skeet.Quad;
import net.minecraft.launchwrapper.LaunchClassLoader;
import java.awt.*;
/**
* @author Leon
*
* fyi: color shouldn't have any sub settings
*/
public class ColorComponent extends ISetting<ColorSetting> {
private boolean draggingPicker = false;
private boolean draggingHue = false;
private boolean draggingAlpha = false;
private boolean draggingSpeed = false;
private float pickerPosMin, pickerPosMax, huePosMin, huePosMax, alphaPosMin, alphaPosMax, speedPosMin, speedPosMax, rainbowMin, rainbowMax;
public ColorComponent(IComponent parent, IButton superParent, Setting set, int offset) {
super(parent, superParent, set, offset);
set.getSubSettings().clear(); // prevent color sub settings
subs.clear();
}
@Override
public void render(Point point) {
if(!open) {
drawBack(point, set.getName(), false);
drawRect(getFrame().getX() + getWidth() - 13, getFrame().getY() + offset + 2, getFrame().getX() + getWidth() - 3, getFrame().getY() + offset + 12, set.getValue());
} else {
float realY = getFrame().getY() + offset;
final float realX = getFrame().getX();
final float width = getFrame().getWidth();
drawRect(realX, realY, realX + getWidth(), realY + 14, getColor(point, false)); // background for name
drawRect(realX, realY + 14, realX + getWidth(), realY + 14 + width + 13 + 13 + 14, ClickGUI.backgroundColor.getValue()); // background for the picker
drawRect(realX + getWidth() - 13, realY + 2, realX + getWidth() - 3, realY + 12, set.getValue());
FontUtil.drawString(set.getName(), realX + parent.xOffset() + 3, realY + ((14 - FontUtil.getFontHeight()) / 2f), ClickGUI.settingNameColor.getValue());
RenderUtils.drawColorPickerSquare(realX + xOffset(), realY + 14, realX + width, realY + 14 + (width - xOffset()), set.hue, set.getA());
RenderUtils.drawOutlineRect(realX + xOffset(), realY + 14, realX + getWidth(), realY + 14 + (getWidth() - xOffset()), 1f, Color.WHITE);
pickerPosMin = realY + 14;
pickerPosMax = realY + 14 + (getWidth() - xOffset());
RenderUtils.scissor(new Quad(realX + xOffset(), realY + 15, realX + getWidth(), realY + 14 + (getWidth() - xOffset())));
RenderUtils.drawCircle(realX + xOffset() + (set.s * (width - xOffset())), realY + 14 + ((1 - set.br) * (width - xOffset())), 3, 1, Color.WHITE);
RenderUtils.restoreScissor();
realY += 17 + (width - xOffset());
RenderUtils.drawHueRect(realX + xOffset(), realY, getWidth() - xOffset(), 10);
RenderUtils.drawRect(realX + xOffset() + GuiUtils.sliderWidth(0, set.hue, 1, getWidth() - xOffset() - 1), realY, realX + xOffset() + 1 + GuiUtils.sliderWidth(0, (float) set.hue, 1, getWidth() - xOffset() - 1), realY + 10, Color.BLACK);
RenderUtils.drawOutlineRect(realX + xOffset(), realY, realX + getWidth(), realY + 10, 1f, Color.WHITE);
huePosMin = realY;
huePosMax = realY + 10;
realY += 13;
RenderUtils.scissor(new Quad(realX + xOffset() - 1, realY - 1, realX + getWidth(), realY + 11));
int xOff = 0;
while (xOff < realX + getWidth() + 10) {
RenderUtils.drawRect(xOff, realY, xOff + 5, realY + 5, xOff % 2 == 0 ? new Color(0, 0, 0, 50) : new Color(255, 255, 255, 50));
RenderUtils.drawRect(xOff, realY + 5, xOff + 5, realY + 10, xOff % 2 == 0 ? new Color(255, 255, 255, 50) : new Color(0, 0, 0, 50));
xOff += 5;
}
RenderUtils.restoreScissor();
RenderUtils.drawGradientRect(realX + xOffset(), realY, realX + getWidth(), realY + 10, new Color(0, 0, 0, 0), RenderUtils.alpha(set.getValue(), 255), new Color(0, 0, 0, 0), RenderUtils.alpha(set.getValue(), 255));
RenderUtils.drawRect(realX + xOffset() + GuiUtils.sliderWidth(0, set.getA(), 255, getWidth() - xOffset() - 1), realY, realX + xOffset() + 1 + GuiUtils.sliderWidth(0, set.getA(), 255, getWidth() - xOffset() - 1), realY + 10, Color.BLACK);
RenderUtils.drawOutlineRect(realX + xOffset(), realY, realX + getWidth(), realY + 10, 1f, Color.WHITE);
alphaPosMin = realY;
alphaPosMax = realY + 10;
realY += 13;
RenderUtils.drawRect(realX + xOffset() + 13, realY, realX + xOffset() + 13 + GuiUtils.sliderWidth(0, (float) set.speed, 5, getWidth() - xOffset()), realY + 10, ClickGUI.sliderColor.getValue());
FontUtil.drawString("Speed " + set.speed, realX + xOffset() + 16, realY + (10 - FontUtil.getFontHeight()) / 2f, Color.WHITE);
RenderUtils.drawOutlineRect(realX + xOffset() + 13, realY, realX + getWidth(), realY + 10, 1f, Color.WHITE);
speedPosMin = realY;
speedPosMax = realY + 10;
if(set.rainbow) RenderUtils.drawRect(realX + xOffset(), realY, realX + xOffset() + 10, realY + 10, new Color(0xff98ff98)); // ZWare.cc green lol
RenderUtils.drawOutlineRect(realX + xOffset(), realY, realX + xOffset() + 10, realY + 10, 1f, Color.WHITE);
rainbowMin = speedPosMin; // useless?
rainbowMax = speedPosMax;
}
}
@Override
public void update(Point point) {
final float realX = getFrame().getX();
final float realY = getFrame().getY() + offset;
if(draggingSpeed) {
final float f1 = (float) GuiUtils.slider(0, 20, point.x, realX + xOffset() + 13, getWidth() - xOffset(), 0);
set.speed = MathUtils.roundToPlace(f1 / 4f, 2);
}
if(draggingPicker) {
set.s = (float) MathUtils.clamp(0, 1, (point.x - (realX + xOffset())) / (getWidth() - xOffset()));
set.br = (float) (1 - MathUtils.clamp(0, 1, (point.y - (realY + 14)) / (getWidth() - xOffset())));
}
if(draggingHue) {
set.hue = ((float) GuiUtils.slider(0, 360, point.x, realX + xOffset(), getWidth() - xOffset(), 2)) / 360f;
}
if(draggingAlpha) {
set.setA((int) GuiUtils.slider(0, 255, point.x, realX + xOffset(), getWidth() - xOffset(), 0));
}
final Color color = new Color(Color.HSBtoRGB(set.hue, set.s, set.br));
set.setR(color.getRed()).setG(color.getGreen()).setB(color.getBlue());
}
@Override
public boolean buttonClick(int button, Point point) {
if(onButton(point)) {
if(button == 1) {
open = !open;
}
return true;
}
if(open) {
if(onSpeed(point) && button == 0) {
draggingSpeed = true;
return true;
}
if(onRainbow(point) && button == 0) {
set.rainbow = !set.rainbow;
return true;
}
if(onPicker(point) && button == 0) {
draggingPicker = true;
return true;
}
if(onHue(point) && button == 0) {
draggingHue = true;
return true;
}
if(onAlpha(point) && button == 0) {
draggingAlpha = true;
return true;
}
}
return false;
}
@Override
public boolean buttonRelease(int button, Point point) {
draggingPicker = false;
draggingHue = false;
draggingSpeed = false;
draggingAlpha = false;
return false;
}
@Override
public boolean keyTyped(char chr, int code) {
return false;
}
@Override
public float height() {
if(open) {
return (getWidth() + 14) + (13) + (13) + (14);
} else return 14;
}
@Override
public float xOffset() {
return parent.xOffset() + 3;
}
private boolean onSpeed(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset() + 13, speedPosMin, getFrame().getX() + getWidth(), speedPosMax, p);
}
private boolean onRainbow(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), rainbowMin, getFrame().getX() + xOffset() + 10, rainbowMax, p);
}
private boolean onPicker(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), pickerPosMin, getFrame().getX() + getWidth(), pickerPosMax, p);
}
private boolean onHue(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), huePosMin, getFrame().getX() + getWidth(), huePosMax, p);
}
private boolean onAlpha(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), alphaPosMin, getFrame().getX() + getWidth(), alphaPosMax, p);
}
}
| LeonLeonPotato/Trinity | src/main/java/me/leon/trinity/gui/setting/ColorComponent.java | 3,135 | // ZWare.cc green lol | line_comment | nl | package me.leon.trinity.gui.setting;
import me.leon.trinity.gui.IComponent;
import me.leon.trinity.gui.button.ButtonComponent;
import me.leon.trinity.gui.button.IButton;
import me.leon.trinity.hacks.client.ClickGUI;
import me.leon.trinity.main.Trinity;
import me.leon.trinity.setting.rewrite.ColorSetting;
import me.leon.trinity.setting.rewrite.Setting;
import me.leon.trinity.utils.math.MathUtils;
import me.leon.trinity.utils.misc.FontUtil;
import me.leon.trinity.utils.rendering.GuiUtils;
import me.leon.trinity.utils.rendering.RenderUtils;
import me.leon.trinity.utils.rendering.skeet.Quad;
import net.minecraft.launchwrapper.LaunchClassLoader;
import java.awt.*;
/**
* @author Leon
*
* fyi: color shouldn't have any sub settings
*/
public class ColorComponent extends ISetting<ColorSetting> {
private boolean draggingPicker = false;
private boolean draggingHue = false;
private boolean draggingAlpha = false;
private boolean draggingSpeed = false;
private float pickerPosMin, pickerPosMax, huePosMin, huePosMax, alphaPosMin, alphaPosMax, speedPosMin, speedPosMax, rainbowMin, rainbowMax;
public ColorComponent(IComponent parent, IButton superParent, Setting set, int offset) {
super(parent, superParent, set, offset);
set.getSubSettings().clear(); // prevent color sub settings
subs.clear();
}
@Override
public void render(Point point) {
if(!open) {
drawBack(point, set.getName(), false);
drawRect(getFrame().getX() + getWidth() - 13, getFrame().getY() + offset + 2, getFrame().getX() + getWidth() - 3, getFrame().getY() + offset + 12, set.getValue());
} else {
float realY = getFrame().getY() + offset;
final float realX = getFrame().getX();
final float width = getFrame().getWidth();
drawRect(realX, realY, realX + getWidth(), realY + 14, getColor(point, false)); // background for name
drawRect(realX, realY + 14, realX + getWidth(), realY + 14 + width + 13 + 13 + 14, ClickGUI.backgroundColor.getValue()); // background for the picker
drawRect(realX + getWidth() - 13, realY + 2, realX + getWidth() - 3, realY + 12, set.getValue());
FontUtil.drawString(set.getName(), realX + parent.xOffset() + 3, realY + ((14 - FontUtil.getFontHeight()) / 2f), ClickGUI.settingNameColor.getValue());
RenderUtils.drawColorPickerSquare(realX + xOffset(), realY + 14, realX + width, realY + 14 + (width - xOffset()), set.hue, set.getA());
RenderUtils.drawOutlineRect(realX + xOffset(), realY + 14, realX + getWidth(), realY + 14 + (getWidth() - xOffset()), 1f, Color.WHITE);
pickerPosMin = realY + 14;
pickerPosMax = realY + 14 + (getWidth() - xOffset());
RenderUtils.scissor(new Quad(realX + xOffset(), realY + 15, realX + getWidth(), realY + 14 + (getWidth() - xOffset())));
RenderUtils.drawCircle(realX + xOffset() + (set.s * (width - xOffset())), realY + 14 + ((1 - set.br) * (width - xOffset())), 3, 1, Color.WHITE);
RenderUtils.restoreScissor();
realY += 17 + (width - xOffset());
RenderUtils.drawHueRect(realX + xOffset(), realY, getWidth() - xOffset(), 10);
RenderUtils.drawRect(realX + xOffset() + GuiUtils.sliderWidth(0, set.hue, 1, getWidth() - xOffset() - 1), realY, realX + xOffset() + 1 + GuiUtils.sliderWidth(0, (float) set.hue, 1, getWidth() - xOffset() - 1), realY + 10, Color.BLACK);
RenderUtils.drawOutlineRect(realX + xOffset(), realY, realX + getWidth(), realY + 10, 1f, Color.WHITE);
huePosMin = realY;
huePosMax = realY + 10;
realY += 13;
RenderUtils.scissor(new Quad(realX + xOffset() - 1, realY - 1, realX + getWidth(), realY + 11));
int xOff = 0;
while (xOff < realX + getWidth() + 10) {
RenderUtils.drawRect(xOff, realY, xOff + 5, realY + 5, xOff % 2 == 0 ? new Color(0, 0, 0, 50) : new Color(255, 255, 255, 50));
RenderUtils.drawRect(xOff, realY + 5, xOff + 5, realY + 10, xOff % 2 == 0 ? new Color(255, 255, 255, 50) : new Color(0, 0, 0, 50));
xOff += 5;
}
RenderUtils.restoreScissor();
RenderUtils.drawGradientRect(realX + xOffset(), realY, realX + getWidth(), realY + 10, new Color(0, 0, 0, 0), RenderUtils.alpha(set.getValue(), 255), new Color(0, 0, 0, 0), RenderUtils.alpha(set.getValue(), 255));
RenderUtils.drawRect(realX + xOffset() + GuiUtils.sliderWidth(0, set.getA(), 255, getWidth() - xOffset() - 1), realY, realX + xOffset() + 1 + GuiUtils.sliderWidth(0, set.getA(), 255, getWidth() - xOffset() - 1), realY + 10, Color.BLACK);
RenderUtils.drawOutlineRect(realX + xOffset(), realY, realX + getWidth(), realY + 10, 1f, Color.WHITE);
alphaPosMin = realY;
alphaPosMax = realY + 10;
realY += 13;
RenderUtils.drawRect(realX + xOffset() + 13, realY, realX + xOffset() + 13 + GuiUtils.sliderWidth(0, (float) set.speed, 5, getWidth() - xOffset()), realY + 10, ClickGUI.sliderColor.getValue());
FontUtil.drawString("Speed " + set.speed, realX + xOffset() + 16, realY + (10 - FontUtil.getFontHeight()) / 2f, Color.WHITE);
RenderUtils.drawOutlineRect(realX + xOffset() + 13, realY, realX + getWidth(), realY + 10, 1f, Color.WHITE);
speedPosMin = realY;
speedPosMax = realY + 10;
if(set.rainbow) RenderUtils.drawRect(realX + xOffset(), realY, realX + xOffset() + 10, realY + 10, new Color(0xff98ff98)); // ZWare.cc green<SUF>
RenderUtils.drawOutlineRect(realX + xOffset(), realY, realX + xOffset() + 10, realY + 10, 1f, Color.WHITE);
rainbowMin = speedPosMin; // useless?
rainbowMax = speedPosMax;
}
}
@Override
public void update(Point point) {
final float realX = getFrame().getX();
final float realY = getFrame().getY() + offset;
if(draggingSpeed) {
final float f1 = (float) GuiUtils.slider(0, 20, point.x, realX + xOffset() + 13, getWidth() - xOffset(), 0);
set.speed = MathUtils.roundToPlace(f1 / 4f, 2);
}
if(draggingPicker) {
set.s = (float) MathUtils.clamp(0, 1, (point.x - (realX + xOffset())) / (getWidth() - xOffset()));
set.br = (float) (1 - MathUtils.clamp(0, 1, (point.y - (realY + 14)) / (getWidth() - xOffset())));
}
if(draggingHue) {
set.hue = ((float) GuiUtils.slider(0, 360, point.x, realX + xOffset(), getWidth() - xOffset(), 2)) / 360f;
}
if(draggingAlpha) {
set.setA((int) GuiUtils.slider(0, 255, point.x, realX + xOffset(), getWidth() - xOffset(), 0));
}
final Color color = new Color(Color.HSBtoRGB(set.hue, set.s, set.br));
set.setR(color.getRed()).setG(color.getGreen()).setB(color.getBlue());
}
@Override
public boolean buttonClick(int button, Point point) {
if(onButton(point)) {
if(button == 1) {
open = !open;
}
return true;
}
if(open) {
if(onSpeed(point) && button == 0) {
draggingSpeed = true;
return true;
}
if(onRainbow(point) && button == 0) {
set.rainbow = !set.rainbow;
return true;
}
if(onPicker(point) && button == 0) {
draggingPicker = true;
return true;
}
if(onHue(point) && button == 0) {
draggingHue = true;
return true;
}
if(onAlpha(point) && button == 0) {
draggingAlpha = true;
return true;
}
}
return false;
}
@Override
public boolean buttonRelease(int button, Point point) {
draggingPicker = false;
draggingHue = false;
draggingSpeed = false;
draggingAlpha = false;
return false;
}
@Override
public boolean keyTyped(char chr, int code) {
return false;
}
@Override
public float height() {
if(open) {
return (getWidth() + 14) + (13) + (13) + (14);
} else return 14;
}
@Override
public float xOffset() {
return parent.xOffset() + 3;
}
private boolean onSpeed(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset() + 13, speedPosMin, getFrame().getX() + getWidth(), speedPosMax, p);
}
private boolean onRainbow(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), rainbowMin, getFrame().getX() + xOffset() + 10, rainbowMax, p);
}
private boolean onPicker(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), pickerPosMin, getFrame().getX() + getWidth(), pickerPosMax, p);
}
private boolean onHue(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), huePosMin, getFrame().getX() + getWidth(), huePosMax, p);
}
private boolean onAlpha(Point p) {
return GuiUtils.onButton(getFrame().getX() + xOffset(), alphaPosMin, getFrame().getX() + getWidth(), alphaPosMax, p);
}
}
|
39045_1 | package nl.avans.arduinobluetooth;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.view.View;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
private BluetoothSocket socket;
private OutputStream outputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendSignal(View view) {
// verbind met bluetooth apparaat en maak een outputstream om data te verzenden
connect();
try {
// zend bytes via outputStream naar verbonden bluetooth apparaat
outputStream.write(1); // zend een 1, in arduino geprogrammeerd om bij een 1 de cyclus te doorlopen
sleep(100); // wacht 100 ms
outputStream.write(0); // zend een andere waarde, omdat de module de waarde onthoud, door hem te updaten/resetten blijft hij niet dezelfde waarde en kan ik de knop meerdere keren gebruiken/heeft hij het door als de waarde opnieuw veranderd
} catch (IOException | InterruptedException e) {
System.out.println("Error occurred when sending data");
}
// safely stop the connection after the signal is send
stopConnection();
}
public void connect() {
// haal de bluetooth adapter op
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
// vraag alle verbonden apparaten op
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
// als er verbonden apparaten zijn
if(bondedDevices.size() > 0) {
// zet apparaten in array
Object[] devices = bondedDevices.toArray();
// pak de eerste (ervan uitgaande dat er maar 1 apparaat gekoppeld is)
BluetoothDevice device = (BluetoothDevice) devices[0];
// backup optie
// BluetoothDevice device = blueAdapter.getRemoteDevice("98:D3:51:FD:AE:B5"); // hc05
// id dat je nodig hebt om te verbinden en een prive connectie te maken zodat alleen jouw apparaten met elkaar communiceren
ParcelUuid[] uuids = device.getUuids();
try {
// krijg socket om te verbinden
socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
System.out.println(socket);
// verbind
socket.connect();
System.out.println(socket.isConnected());
// krijg outputstream om signalen te verzenden
outputStream = socket.getOutputStream();
System.out.println(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void stopConnection() {
try {
socket.close();
System.out.println(socket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Lesley55/Arduino | ArduinoBluetooth/app/src/main/java/nl/avans/arduinobluetooth/MainActivity.java | 933 | // zend bytes via outputStream naar verbonden bluetooth apparaat | line_comment | nl | package nl.avans.arduinobluetooth;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.view.View;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
private BluetoothSocket socket;
private OutputStream outputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendSignal(View view) {
// verbind met bluetooth apparaat en maak een outputstream om data te verzenden
connect();
try {
// zend bytes<SUF>
outputStream.write(1); // zend een 1, in arduino geprogrammeerd om bij een 1 de cyclus te doorlopen
sleep(100); // wacht 100 ms
outputStream.write(0); // zend een andere waarde, omdat de module de waarde onthoud, door hem te updaten/resetten blijft hij niet dezelfde waarde en kan ik de knop meerdere keren gebruiken/heeft hij het door als de waarde opnieuw veranderd
} catch (IOException | InterruptedException e) {
System.out.println("Error occurred when sending data");
}
// safely stop the connection after the signal is send
stopConnection();
}
public void connect() {
// haal de bluetooth adapter op
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
// vraag alle verbonden apparaten op
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
// als er verbonden apparaten zijn
if(bondedDevices.size() > 0) {
// zet apparaten in array
Object[] devices = bondedDevices.toArray();
// pak de eerste (ervan uitgaande dat er maar 1 apparaat gekoppeld is)
BluetoothDevice device = (BluetoothDevice) devices[0];
// backup optie
// BluetoothDevice device = blueAdapter.getRemoteDevice("98:D3:51:FD:AE:B5"); // hc05
// id dat je nodig hebt om te verbinden en een prive connectie te maken zodat alleen jouw apparaten met elkaar communiceren
ParcelUuid[] uuids = device.getUuids();
try {
// krijg socket om te verbinden
socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
System.out.println(socket);
// verbind
socket.connect();
System.out.println(socket.isConnected());
// krijg outputstream om signalen te verzenden
outputStream = socket.getOutputStream();
System.out.println(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void stopConnection() {
try {
socket.close();
System.out.println(socket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
26167_3 | package main.view.start;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.WindowEvent;
import main.Log;
import main.model.MainModel;
public class StartPresenter {
private StartView startView;
public StartPresenter(
MainModel model,
StartView startView
) {
this.startView = startView;
this.addEventHandlers();
this.updateView();
Log.debug("StartView is initialized.");
}
private void addEventHandlers() {
// Koppelt event handlers (anon. inner klassen)
// aan de controls uit de view.
// Event handlers: roepen methodes aan uit het
// model en zorgen voor een update van de view.
addMenuEventHandlers();
}
private void updateView() {
// Vult de view met data uit model
// splash-screen
}
public void addWindowEventHandlers() {
// Window event handlers (anon. inner klassen)
// Koppeling via view.getScene().getWindow()
startView.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setHeaderText("Are you sure?");
alert.setContentText("Are you sure you want to close the application?");
alert.setTitle("Warning!");
alert.getButtonTypes().clear();
ButtonType no = new ButtonType("No");
ButtonType yes = new ButtonType("Yes");
alert.getButtonTypes().addAll(no, yes);
alert.showAndWait();
if (alert.getResult().equals(no)) {
event.consume();
}
}
});
}
private void addMenuEventHandlers() {
startView.getMiExit().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setHeaderText("Are you sure?");
alert.setContentText("Are you sure you want to close the application?");
alert.setTitle("Warning!");
alert.getButtonTypes().clear();
ButtonType no = new ButtonType("No");
ButtonType yes = new ButtonType("Yes");
alert.getButtonTypes().addAll(no, yes);
alert.showAndWait();
if (alert.getResult().equals(no)) {
event.consume();
} else {
Platform.exit();
}
}
});
}
}
| LeventHAN/JavaFX-MVP-Pattern-Boilerplate | src/main/view/start/StartPresenter.java | 734 | // model en zorgen voor een update van de view. | line_comment | nl | package main.view.start;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.WindowEvent;
import main.Log;
import main.model.MainModel;
public class StartPresenter {
private StartView startView;
public StartPresenter(
MainModel model,
StartView startView
) {
this.startView = startView;
this.addEventHandlers();
this.updateView();
Log.debug("StartView is initialized.");
}
private void addEventHandlers() {
// Koppelt event handlers (anon. inner klassen)
// aan de controls uit de view.
// Event handlers: roepen methodes aan uit het
// model en<SUF>
addMenuEventHandlers();
}
private void updateView() {
// Vult de view met data uit model
// splash-screen
}
public void addWindowEventHandlers() {
// Window event handlers (anon. inner klassen)
// Koppeling via view.getScene().getWindow()
startView.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setHeaderText("Are you sure?");
alert.setContentText("Are you sure you want to close the application?");
alert.setTitle("Warning!");
alert.getButtonTypes().clear();
ButtonType no = new ButtonType("No");
ButtonType yes = new ButtonType("Yes");
alert.getButtonTypes().addAll(no, yes);
alert.showAndWait();
if (alert.getResult().equals(no)) {
event.consume();
}
}
});
}
private void addMenuEventHandlers() {
startView.getMiExit().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setHeaderText("Are you sure?");
alert.setContentText("Are you sure you want to close the application?");
alert.setTitle("Warning!");
alert.getButtonTypes().clear();
ButtonType no = new ButtonType("No");
ButtonType yes = new ButtonType("Yes");
alert.getButtonTypes().addAll(no, yes);
alert.showAndWait();
if (alert.getResult().equals(no)) {
event.consume();
} else {
Platform.exit();
}
}
});
}
}
|
135663_2 | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "STAR.bin"},
{"IX86/STAR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "game.exe", "Bnclient.dll", "D2Client.dll", "D2DV.bin"},
{"IX86/D2XP/", "game.exe", "Bnclient.dll", "D2Client.dll", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "war3.exe", "Storm.dll", "Game.dll", "WAR3.bin"},
{"IX86/WAR3/", "war3.exe", "Storm.dll", "Game.dll", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft_s.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1A, 0x1A, 0x2a, 0x2a, 0xa5};
public static String ArchivePath = "DLLs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is IPBans on
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean RunAdmin = false;
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
| LexManos/JBLS | util/Constants.java | 1,440 | //default is IPBans on | line_comment | nl | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "STAR.bin"},
{"IX86/STAR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "game.exe", "Bnclient.dll", "D2Client.dll", "D2DV.bin"},
{"IX86/D2XP/", "game.exe", "Bnclient.dll", "D2Client.dll", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "war3.exe", "Storm.dll", "Game.dll", "WAR3.bin"},
{"IX86/WAR3/", "war3.exe", "Storm.dll", "Game.dll", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft_s.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1A, 0x1A, 0x2a, 0x2a, 0xa5};
public static String ArchivePath = "DLLs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is<SUF>
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean RunAdmin = false;
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
|
42308_0 | package com.liamfroyen;
public class Stars3D {
private final float fov;
private final float spread;
private final float speed;
private final float starX[];
private final float starY[];
private final float starZ[];
public Stars3D(int numStars, float spread_, float speed_, float fovInDegrees_) {
spread = spread_;
speed = speed_;
fov = (float)Math.tan(Math.toRadians(fovInDegrees_/2));
starX = new float[numStars];
starY = new float[numStars];
starZ = new float[numStars];
for (int i = 0; i < starX.length; i++) {
InitStar(i);
}
}
private void InitStar(int i) {
starX[i] = 2 * ((float)Math.random() - 0.5f) * spread;
starY[i] = 2 * ((float)Math.random() - 0.5f) * spread;
starZ[i] = ((float)Math.random()) * spread;
}
public void UpdateAndRender(RenderContext target, float delta) {
target.Clear((byte)0x00);
float halfWidth = target.GetWidth()/2;
float halfHeight = target.GetHeight()/2;
for (int i = 0; i < starX.length; i++) {
starZ[i] -= delta * speed; //met delta de tijd sinds de vorige update
if (starZ[i] <= 0) {
InitStar(i);
}
int x = (int)((starX[i]/(starZ[i] * fov)) * halfWidth + halfWidth);
int y = (int)((starY[i]/(starZ[i] * fov)) * halfHeight + halfHeight);
if (x < 0 || x >= target.GetWidth() || y < 0 || y >= target.GetHeight()) {
InitStar(i);
} else {
target.DrawPixel(x, y, (byte)0xFF, (byte)0xFF , (byte)0xFF, (byte)0xFF);
}
}
}
}
| LiamF-2261667/3D-Renderer | src/com/liamfroyen/Stars3D.java | 572 | //met delta de tijd sinds de vorige update | line_comment | nl | package com.liamfroyen;
public class Stars3D {
private final float fov;
private final float spread;
private final float speed;
private final float starX[];
private final float starY[];
private final float starZ[];
public Stars3D(int numStars, float spread_, float speed_, float fovInDegrees_) {
spread = spread_;
speed = speed_;
fov = (float)Math.tan(Math.toRadians(fovInDegrees_/2));
starX = new float[numStars];
starY = new float[numStars];
starZ = new float[numStars];
for (int i = 0; i < starX.length; i++) {
InitStar(i);
}
}
private void InitStar(int i) {
starX[i] = 2 * ((float)Math.random() - 0.5f) * spread;
starY[i] = 2 * ((float)Math.random() - 0.5f) * spread;
starZ[i] = ((float)Math.random()) * spread;
}
public void UpdateAndRender(RenderContext target, float delta) {
target.Clear((byte)0x00);
float halfWidth = target.GetWidth()/2;
float halfHeight = target.GetHeight()/2;
for (int i = 0; i < starX.length; i++) {
starZ[i] -= delta * speed; //met delta<SUF>
if (starZ[i] <= 0) {
InitStar(i);
}
int x = (int)((starX[i]/(starZ[i] * fov)) * halfWidth + halfWidth);
int y = (int)((starY[i]/(starZ[i] * fov)) * halfHeight + halfHeight);
if (x < 0 || x >= target.GetWidth() || y < 0 || y >= target.GetHeight()) {
InitStar(i);
} else {
target.DrawPixel(x, y, (byte)0xFF, (byte)0xFF , (byte)0xFF, (byte)0xFF);
}
}
}
}
|
41609_32 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
package complex.comphelper;
import com.sun.star.beans.Pair;
import com.sun.star.container.ContainerEvent;
import com.sun.star.container.XContainer;
import com.sun.star.container.XContainerListener;
import com.sun.star.container.XElementAccess;
import com.sun.star.container.XEnumerableMap;
import com.sun.star.container.XEnumeration;
import com.sun.star.container.XIdentifierAccess;
import com.sun.star.container.XMap;
import com.sun.star.container.XSet;
import com.sun.star.form.XFormComponent;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.Locale;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Any;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.TypeClass;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import java.util.HashSet;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openoffice.test.OfficeConnection;
import static org.junit.Assert.*;
/** complex test case for the css.container.Map implementation
*/
public class Map
{
private static String impl_getNth( int n )
{
switch ( n % 10 )
{
case 1: return n + "st";
case 2: return n + "nd";
default: return n + "th";
}
}
private static void impl_putAll( XMap _map, Object[] _keys, Object[] _values ) throws com.sun.star.uno.Exception
{
for ( int i=0; i<_keys.length; ++i )
{
_map.put( _keys[i], _values[i] );
}
}
private static void impl_checkContent( XMap _map, Object[] _keys, Object[] _values, String _context ) throws com.sun.star.uno.Exception
{
for ( int i=0; i<_keys.length; ++i )
{
assertTrue( _context + ": " + impl_getNth(i) + " key (" + _keys[i].toString() + ") not found in map",
_map.containsKey( _keys[i] ) );
assertTrue( _context + ": " + impl_getNth(i) + " value (" + _values[i].toString() + ") not found in map",
_map.containsValue( _values[i] ) );
assertEquals( _context + ": wrong value for " + impl_getNth(i) + " key (" + _keys[i] + ")",
_values[i], _map.get( _keys[i] ) );
}
}
@SuppressWarnings("unchecked")
private static void impl_checkMappings( Object[] _keys, Object[] _values, String _context ) throws com.sun.star.uno.Exception
{
System.out.println( "checking mapping " + _context + "..." );
Type keyType = AnyConverter.getType( _keys[0] );
Type valueType = AnyConverter.getType( _values[0] );
// create a map for the given types
XMap map = com.sun.star.container.EnumerableMap.create( connection.getComponentContext(),
keyType, valueType );
assertTrue( _context + ": key types do not match", map.getKeyType().equals( keyType ) );
assertTrue( _context + ": value types do not match", map.getValueType().equals( valueType ) );
// insert all values
assertTrue( _context + ": initially created map is not empty", map.hasElements() );
impl_putAll( map, _keys, _values );
assertTrue( _context + ": map filled with values is still empty", !map.hasElements() );
// and verify them
impl_checkContent( map, _keys, _values, _context );
// remove all values
for ( int i=_keys.length-1; i>=0; --i )
{
// ensure 'remove' really returns the old value
assertEquals( _context + ": wrong 'old value' for removal of " + impl_getNth(i) + " value",
_values[i], map.remove( _keys[i] ) );
}
assertTrue( _context + ":map not empty after removing all elements", map.hasElements() );
// insert again, and check whether 'clear' does what it should do
impl_putAll( map, _keys, _values );
map.clear();
assertTrue( _context + ": 'clear' does not empty the map", map.hasElements() );
// try the constructor which creates an immutable version
Pair< ?, ? >[] initialMappings = new Pair< ?, ? >[ _keys.length ];
for ( int i=0; i<_keys.length; ++i )
{
initialMappings[i] = new Pair< Object, Object >( _keys[i], _values[i] );
}
map = com.sun.star.container.EnumerableMap.createImmutable(
connection.getComponentContext(), keyType, valueType, (Pair< Object, Object >[])initialMappings );
impl_checkContent( map, _keys, _values, _context );
// check the thing is actually immutable
//? assureException( map, "clear", new Object[] {}, NoSupportException.class );
//? assureException( map, "remove", new Class[] { Object.class }, new Object[] { _keys[0] }, NoSupportException.class );
//? assureException( map, "put", new Class[] { Object.class, Object.class }, new Object[] { _keys[0], _values[0] }, NoSupportException.class );
}
@Test public void testSimpleKeyTypes() throws com.sun.star.uno.Exception
{
impl_checkMappings(
new Long[] { (long)1, (long)2, (long)3, (long)4, (long)5 },
new Integer[] { 6, 7, 8, 9, 10 },
"long->int"
);
impl_checkMappings(
new Boolean[] { true, false },
new Short[] { (short)1, (short)0 },
"bool->short"
);
impl_checkMappings(
new String[] { "one", "two", "three", "four", "five"},
new String[] { "1", "2", "3", "4", "5" },
"string->string"
);
impl_checkMappings(
new Double[] { 1.2, 3.4, 5.6, 7.8, 9.10 },
new Float[] { (float)1, (float)2, (float)3, (float)4, (float)5 },
"double->float"
);
impl_checkMappings(
new Float[] { (float)1, (float)2, (float)3, (float)4, (float)5 },
new Double[] { 1.2, 3.4, 5.6, 7.8, 9.10 },
"float->double"
);
impl_checkMappings(
new Integer[] { 2, 9, 2005, 20, 11, 1970, 26, 3, 1974 },
new String[] { "2nd", "September", "2005", "20th", "November", "1970", "26th", "March", "1974" },
"int->string"
);
}
@Test public void testComplexKeyTypes() throws com.sun.star.uno.Exception
{
Type intType = new Type( Integer.class );
Type longType = new Type( Long.class );
Type msfType = new Type ( XMultiServiceFactory.class );
// css.uno.Type should be a valid key type
impl_checkMappings(
new Type[] { intType, longType, msfType },
new String[] { intType.getTypeName(), longType.getTypeName(), msfType.getTypeName() },
"type->string"
);
// any UNO interface type should be a valid key type.
// Try with some form components (just because I like form components :), and the very first application
// for the newly implemented map will be to map XFormComponents to drawing shapes
String[] serviceNames = new String[] { "CheckBox", "ComboBox", "CommandButton", "DateField", "FileControl" };
Object[] components = new Object[ serviceNames.length ];
for ( int i=0; i<serviceNames.length; ++i )
{
components[i] = getMSF().createInstance( "com.sun.star.form.component." + serviceNames[i] );
}
// "normalize" the first component, so it has the property type
Type formComponentType = new Type( XFormComponent.class );
components[0] = UnoRuntime.queryInterface( formComponentType.getZClass(), components[0] );
impl_checkMappings( components, serviceNames, "XFormComponent->string" );
// any UNO enum type should be a valid key type
impl_checkMappings(
new TypeClass[] { intType.getTypeClass(), longType.getTypeClass(), msfType.getTypeClass() },
new Object[] { "foo", "bar", "42" },
"enum->string"
);
}
private static Class<?> impl_getValueClassByPos( int _pos )
{
Class<?> valueClass = null;
switch ( _pos )
{
case 0: valueClass = Boolean.class; break;
case 1: valueClass = Short.class; break;
case 2: valueClass = Integer.class; break;
case 3: valueClass = Long.class; break;
case 4: valueClass = XInterface.class; break;
case 5: valueClass = XSet.class; break;
case 6: valueClass = XContainer.class; break;
case 7: valueClass = XIdentifierAccess.class; break;
case 8: valueClass = XElementAccess.class; break;
case 9: valueClass = com.sun.star.uno.Exception.class; break;
case 10: valueClass = com.sun.star.uno.RuntimeException.class; break;
case 11: valueClass = EventObject.class; break;
case 12: valueClass = ContainerEvent.class; break;
case 13: valueClass = Object.class; break;
default:
fail( "internal error: wrong position for getValueClass" );
}
return valueClass;
}
private Object impl_getSomeValueByTypePos( int _pos )
{
Object someValue = null;
switch ( _pos )
{
case 0: someValue = Boolean.FALSE; break;
case 1: someValue = Short.valueOf( (short)0 ); break;
case 2: someValue = Integer.valueOf( 0 ); break;
case 3: someValue = Long.valueOf( 0 ); break;
case 4: someValue = UnoRuntime.queryInterface( XInterface.class, new DummyInterface() ); break;
case 5: someValue = UnoRuntime.queryInterface( XSet.class, new DummySet() ); break;
case 6: someValue = UnoRuntime.queryInterface( XContainer.class, new DummyContainer() ); break;
case 7: someValue = UnoRuntime.queryInterface( XIdentifierAccess.class, new DummyIdentifierAccess() ); break;
case 8: someValue = UnoRuntime.queryInterface( XElementAccess.class, new DummyElementAccess() ); break;
case 9: someValue = new com.sun.star.uno.Exception(); break;
case 10: someValue = new com.sun.star.uno.RuntimeException(); break;
case 11: someValue = new EventObject(); break;
case 12: someValue = new ContainerEvent(); break;
case 13: someValue = new Locale(); break; // just use *any* value which does not conflict with the others
default:
fail( "internal error: wrong position for getSomeValue" );
}
return someValue;
}
private static class DummyInterface implements XInterface
{
}
private static class DummySet implements XSet
{
public boolean has( Object arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public void insert( Object arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public void remove( Object arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public XEnumeration createEnumeration() { throw new UnsupportedOperationException( "Not implemented." ); }
public Type getElementType() { throw new UnsupportedOperationException( "Not implemented." ); }
public boolean hasElements() { throw new UnsupportedOperationException( "Not implemented." ); }
}
private class DummyContainer implements XContainer
{
public void addContainerListener( XContainerListener arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public void removeContainerListener( XContainerListener arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
}
private class DummyIdentifierAccess implements XIdentifierAccess
{
public Object getByIdentifier( int arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public int[] getIdentifiers() { throw new UnsupportedOperationException( "Not implemented." ); }
public Type getElementType() { throw new UnsupportedOperationException( "Not implemented." ); }
public boolean hasElements() { throw new UnsupportedOperationException( "Not implemented." ); }
}
private class DummyElementAccess implements XElementAccess
{
public Type getElementType() { throw new UnsupportedOperationException( "Not implemented." ); }
public boolean hasElements() { throw new UnsupportedOperationException( "Not implemented." ); }
}
@Test public void testValueTypes() throws com.sun.star.uno.Exception
{
// type compatibility matrix: rows are the value types used to create the map,
// columns are the value types fed into the map. A value "1" means the respective type
// should be accepted.
Integer[][] typeCompatibility = new Integer[][] {
/* boolean */ new Integer[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* short */ new Integer[] { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* int */ new Integer[] { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* long */ new Integer[] { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* XInterface */ new Integer[] { 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 },
/* XSet */ new Integer[] { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
/* XContainer */ new Integer[] { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
/* XIdentifierAccess */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
/* XElementAccess */ new Integer[] { 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0 },
/* Exception */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 },
/* RuntimeException */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
/* EventObject */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 },
/* ContainerEvent */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 },
/* any */ new Integer[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
};
// several asects are checked with this compatibility matrix:
// - if a map's value type is a scalar type, or a string, then nothing but this
// type should be accepted
// - if a map's value type is an interface type, then values should be accepted if
// they contain a derived interface, or the interface itself, or if they can be
// queried for this interface (actually, the latter rule is not tested with the
// above matrix)
// - if a map's value type is a struct or exception, then values should be accepted
// if they are of the given type, or of a derived type.
// - if a map's value type is "any", then, well, any value should be accepted
for ( int valueTypePos = 0; valueTypePos != typeCompatibility.length; ++valueTypePos )
{
com.sun.star.container.EnumerableMap.create( connection.getComponentContext(),
new Type( Integer.class ), new Type( impl_getValueClassByPos( valueTypePos ) ) );
for ( int checkTypePos = 0; checkTypePos != typeCompatibility[valueTypePos].length; ++checkTypePos )
{
impl_getSomeValueByTypePos( checkTypePos );
if ( typeCompatibility[valueTypePos][checkTypePos] != 0 )
{
// expected to succeed
//? assureException(
//? "(" + valueTypePos + "," + checkTypePos + ") putting an " +
//? AnyConverter.getType( value ).getTypeName() + ", where " +
//? map.getValueType().getTypeName() + " is expected, should succeed",
//? map, "put", new Class[] { Object.class, Object.class }, new Object[] { key, value },
//? null );
}
else
{
// expected to fail
//? assureException(
//? "(" + valueTypePos + "," + checkTypePos + ") putting an " +
//? AnyConverter.getType( value ).getTypeName() + ", where " +
//? map.getValueType().getTypeName() + " is expected, should not succeed",
//? map, "put", new Class[] { Object.class, Object.class }, new Object[] { key, value },
//? IllegalTypeException.class );
}
}
}
}
private interface CompareEqual
{
boolean areEqual( Object _lhs, Object _rhs );
}
private class DefaultCompareEqual implements CompareEqual
{
public boolean areEqual( Object _lhs, Object _rhs )
{
return _lhs.equals( _rhs );
}
}
private class PairCompareEqual implements CompareEqual
{
public boolean areEqual( Object _lhs, Object _rhs )
{
Pair< ?, ? > lhs = (Pair< ?, ? >)_lhs;
Pair< ?, ? > rhs = (Pair< ?, ? >)_rhs;
return lhs.First.equals( rhs.First ) && lhs.Second.equals( rhs.Second );
}
}
private void impl_verifyEnumerationContent( XEnumeration _enum, final Object[] _expectedElements, final String _context )
throws com.sun.star.uno.Exception
{
// since we cannot assume the map to preserve the ordering in which the elements where inserted,
// we can only verify that all elements exist as expected, plus *no more* elements than expected
// are provided by the enumeration
Set<Integer> set = new HashSet<Integer>();
for ( int i=0; i<_expectedElements.length; ++i )
{
set.add( i );
}
CompareEqual comparator = _expectedElements[0].getClass().equals( Pair.class )
? new PairCompareEqual()
: new DefaultCompareEqual();
for ( int i=0; i<_expectedElements.length; ++i )
{
assertTrue( _context + ": too few elements in the enumeration (still " + ( _expectedElements.length - i ) + " to go)",
_enum.hasMoreElements() );
Object nextElement = _enum.nextElement();
if ( nextElement.getClass().equals( Any.class ) )
{
nextElement = ((Any)nextElement).getObject();
}
int foundPos = -1;
for ( int j=0; j<_expectedElements.length; ++j )
{
if ( comparator.areEqual( _expectedElements[j], nextElement ) )
{
foundPos = j;
break;
}
}
assertTrue( _context + ": '" + nextElement.toString() + "' is not expected in the enumeration",
set.contains( foundPos ) );
set.remove( foundPos );
}
assertTrue( _context + ": too many elements returned by the enumeration", set.isEmpty() );
}
@Test public void testEnumerations() throws com.sun.star.uno.Exception
{
// fill a map
final String[] keys = new String[] { "This", "is", "an", "enumeration", "test" };
final String[] values = new String[] { "for", "the", "map", "implementation", "." };
XEnumerableMap map = com.sun.star.container.EnumerableMap.create( connection.getComponentContext(), new Type( String.class ), new Type( String.class ) );
impl_putAll( map, keys, values );
final Pair< ?, ? >[] paired = new Pair< ?, ? >[ keys.length ];
for ( int i=0; i<keys.length; ++i )
{
paired[i] = new Pair< Object, Object >( keys[i], values[i] );
}
// create non-isolated enumerators, and check their content
XEnumeration enumerateKeys = map.createKeyEnumeration( false );
XEnumeration enumerateValues = map.createValueEnumeration( false );
XEnumeration enumerateAll = map.createElementEnumeration( false );
impl_verifyEnumerationContent( enumerateKeys, keys, "key enumeration" );
impl_verifyEnumerationContent( enumerateValues, values, "value enumeration" );
impl_verifyEnumerationContent( enumerateAll, paired, "content enumeration" );
// all enumerators above have been created as non-isolated iterators, so they're expected to die when
// the underlying map changes
map.remove( keys[0] );
//? assureException( enumerateKeys, "hasMoreElements", new Object[] {}, DisposedException.class );
//? assureException( enumerateValues, "hasMoreElements", new Object[] {}, DisposedException.class );
//? assureException( enumerateAll, "hasMoreElements", new Object[] {}, DisposedException.class );
// now try with isolated iterators
map.put( keys[0], values[0] );
enumerateKeys = map.createKeyEnumeration( true );
enumerateValues = map.createValueEnumeration( true );
enumerateAll = map.createElementEnumeration( true );
map.put( "additional", "value" );
impl_verifyEnumerationContent( enumerateKeys, keys, "key enumeration" );
impl_verifyEnumerationContent( enumerateValues, values, "value enumeration" );
impl_verifyEnumerationContent( enumerateAll, paired, "content enumeration" );
}
@Test public void testSpecialValues() throws com.sun.star.uno.Exception
{
final Double[] keys = new Double[] { Double.valueOf( 0 ), Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY };
final Double[] values = new Double[] { Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.valueOf( 0 ) };
XEnumerableMap map = com.sun.star.container.EnumerableMap.create( connection.getComponentContext(), new Type( Double.class ), new Type( Double.class ) );
impl_putAll( map, keys, values );
assertTrue( "containsKey( Double.+INF failed", map.containsKey( Double.POSITIVE_INFINITY ) );
assertTrue( "containsKey( Double.-INF failed", map.containsKey( Double.NEGATIVE_INFINITY ) );
assertTrue( "containsKey( 0 ) failed", map.containsKey( Double.valueOf( 0 ) ) );
assertTrue( "containsValue( Double.+INF ) failed", map.containsValue( Double.POSITIVE_INFINITY ) );
assertTrue( "containsValue( Double.-INF ) failed", map.containsValue( Double.NEGATIVE_INFINITY ) );
assertTrue( "containsValue( 0 ) failed", map.containsValue( Double.valueOf( 0 ) ) );
// put and containsKey should reject Double.NaN as key
//? assureException( "Double.NaN should not be allowed as key in a call to 'put'", map, "put",
//? new Class[] { Object.class, Object.class }, new Object[] { Double.NaN, Double.valueOf( 0 ) },
//? com.sun.star.lang.IllegalArgumentException.class );
//? assureException( "Double.NaN should not be allowed as key in a call to 'containsKey'", map, "containsKey",
//? new Class[] { Object.class }, new Object[] { Double.NaN },
//? com.sun.star.lang.IllegalArgumentException.class );
// ditto for put and containsValue
//? assureException( "Double.NaN should not be allowed as value in a call to 'put'", map, "put",
//? new Class[] { Object.class, Object.class }, new Object[] { Double.valueOf( 0 ), Double.NaN },
//? com.sun.star.lang.IllegalArgumentException.class );
//? assureException( "Double.NaN should not be allowed as key in a call to 'containsValue'", map, "containsValue",
//? new Class[] { Object.class }, new Object[] { Double.NaN },
//? com.sun.star.lang.IllegalArgumentException.class );
}
private static XMultiServiceFactory getMSF()
{
return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager());
}
// setup and close connections
@BeforeClass public static void setUpConnection() throws Exception {
System.out.println("setUpConnection()");
connection.setUp();
}
@AfterClass public static void tearDownConnection()
throws InterruptedException, com.sun.star.uno.Exception
{
System.out.println("tearDownConnection()");
connection.tearDown();
}
private static final OfficeConnection connection = new OfficeConnection();
}
| LibreOffice/core | comphelper/qa/complex/comphelper/Map.java | 7,386 | /* EventObject */ | block_comment | nl | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
package complex.comphelper;
import com.sun.star.beans.Pair;
import com.sun.star.container.ContainerEvent;
import com.sun.star.container.XContainer;
import com.sun.star.container.XContainerListener;
import com.sun.star.container.XElementAccess;
import com.sun.star.container.XEnumerableMap;
import com.sun.star.container.XEnumeration;
import com.sun.star.container.XIdentifierAccess;
import com.sun.star.container.XMap;
import com.sun.star.container.XSet;
import com.sun.star.form.XFormComponent;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.Locale;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Any;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.TypeClass;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import java.util.HashSet;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openoffice.test.OfficeConnection;
import static org.junit.Assert.*;
/** complex test case for the css.container.Map implementation
*/
public class Map
{
private static String impl_getNth( int n )
{
switch ( n % 10 )
{
case 1: return n + "st";
case 2: return n + "nd";
default: return n + "th";
}
}
private static void impl_putAll( XMap _map, Object[] _keys, Object[] _values ) throws com.sun.star.uno.Exception
{
for ( int i=0; i<_keys.length; ++i )
{
_map.put( _keys[i], _values[i] );
}
}
private static void impl_checkContent( XMap _map, Object[] _keys, Object[] _values, String _context ) throws com.sun.star.uno.Exception
{
for ( int i=0; i<_keys.length; ++i )
{
assertTrue( _context + ": " + impl_getNth(i) + " key (" + _keys[i].toString() + ") not found in map",
_map.containsKey( _keys[i] ) );
assertTrue( _context + ": " + impl_getNth(i) + " value (" + _values[i].toString() + ") not found in map",
_map.containsValue( _values[i] ) );
assertEquals( _context + ": wrong value for " + impl_getNth(i) + " key (" + _keys[i] + ")",
_values[i], _map.get( _keys[i] ) );
}
}
@SuppressWarnings("unchecked")
private static void impl_checkMappings( Object[] _keys, Object[] _values, String _context ) throws com.sun.star.uno.Exception
{
System.out.println( "checking mapping " + _context + "..." );
Type keyType = AnyConverter.getType( _keys[0] );
Type valueType = AnyConverter.getType( _values[0] );
// create a map for the given types
XMap map = com.sun.star.container.EnumerableMap.create( connection.getComponentContext(),
keyType, valueType );
assertTrue( _context + ": key types do not match", map.getKeyType().equals( keyType ) );
assertTrue( _context + ": value types do not match", map.getValueType().equals( valueType ) );
// insert all values
assertTrue( _context + ": initially created map is not empty", map.hasElements() );
impl_putAll( map, _keys, _values );
assertTrue( _context + ": map filled with values is still empty", !map.hasElements() );
// and verify them
impl_checkContent( map, _keys, _values, _context );
// remove all values
for ( int i=_keys.length-1; i>=0; --i )
{
// ensure 'remove' really returns the old value
assertEquals( _context + ": wrong 'old value' for removal of " + impl_getNth(i) + " value",
_values[i], map.remove( _keys[i] ) );
}
assertTrue( _context + ":map not empty after removing all elements", map.hasElements() );
// insert again, and check whether 'clear' does what it should do
impl_putAll( map, _keys, _values );
map.clear();
assertTrue( _context + ": 'clear' does not empty the map", map.hasElements() );
// try the constructor which creates an immutable version
Pair< ?, ? >[] initialMappings = new Pair< ?, ? >[ _keys.length ];
for ( int i=0; i<_keys.length; ++i )
{
initialMappings[i] = new Pair< Object, Object >( _keys[i], _values[i] );
}
map = com.sun.star.container.EnumerableMap.createImmutable(
connection.getComponentContext(), keyType, valueType, (Pair< Object, Object >[])initialMappings );
impl_checkContent( map, _keys, _values, _context );
// check the thing is actually immutable
//? assureException( map, "clear", new Object[] {}, NoSupportException.class );
//? assureException( map, "remove", new Class[] { Object.class }, new Object[] { _keys[0] }, NoSupportException.class );
//? assureException( map, "put", new Class[] { Object.class, Object.class }, new Object[] { _keys[0], _values[0] }, NoSupportException.class );
}
@Test public void testSimpleKeyTypes() throws com.sun.star.uno.Exception
{
impl_checkMappings(
new Long[] { (long)1, (long)2, (long)3, (long)4, (long)5 },
new Integer[] { 6, 7, 8, 9, 10 },
"long->int"
);
impl_checkMappings(
new Boolean[] { true, false },
new Short[] { (short)1, (short)0 },
"bool->short"
);
impl_checkMappings(
new String[] { "one", "two", "three", "four", "five"},
new String[] { "1", "2", "3", "4", "5" },
"string->string"
);
impl_checkMappings(
new Double[] { 1.2, 3.4, 5.6, 7.8, 9.10 },
new Float[] { (float)1, (float)2, (float)3, (float)4, (float)5 },
"double->float"
);
impl_checkMappings(
new Float[] { (float)1, (float)2, (float)3, (float)4, (float)5 },
new Double[] { 1.2, 3.4, 5.6, 7.8, 9.10 },
"float->double"
);
impl_checkMappings(
new Integer[] { 2, 9, 2005, 20, 11, 1970, 26, 3, 1974 },
new String[] { "2nd", "September", "2005", "20th", "November", "1970", "26th", "March", "1974" },
"int->string"
);
}
@Test public void testComplexKeyTypes() throws com.sun.star.uno.Exception
{
Type intType = new Type( Integer.class );
Type longType = new Type( Long.class );
Type msfType = new Type ( XMultiServiceFactory.class );
// css.uno.Type should be a valid key type
impl_checkMappings(
new Type[] { intType, longType, msfType },
new String[] { intType.getTypeName(), longType.getTypeName(), msfType.getTypeName() },
"type->string"
);
// any UNO interface type should be a valid key type.
// Try with some form components (just because I like form components :), and the very first application
// for the newly implemented map will be to map XFormComponents to drawing shapes
String[] serviceNames = new String[] { "CheckBox", "ComboBox", "CommandButton", "DateField", "FileControl" };
Object[] components = new Object[ serviceNames.length ];
for ( int i=0; i<serviceNames.length; ++i )
{
components[i] = getMSF().createInstance( "com.sun.star.form.component." + serviceNames[i] );
}
// "normalize" the first component, so it has the property type
Type formComponentType = new Type( XFormComponent.class );
components[0] = UnoRuntime.queryInterface( formComponentType.getZClass(), components[0] );
impl_checkMappings( components, serviceNames, "XFormComponent->string" );
// any UNO enum type should be a valid key type
impl_checkMappings(
new TypeClass[] { intType.getTypeClass(), longType.getTypeClass(), msfType.getTypeClass() },
new Object[] { "foo", "bar", "42" },
"enum->string"
);
}
private static Class<?> impl_getValueClassByPos( int _pos )
{
Class<?> valueClass = null;
switch ( _pos )
{
case 0: valueClass = Boolean.class; break;
case 1: valueClass = Short.class; break;
case 2: valueClass = Integer.class; break;
case 3: valueClass = Long.class; break;
case 4: valueClass = XInterface.class; break;
case 5: valueClass = XSet.class; break;
case 6: valueClass = XContainer.class; break;
case 7: valueClass = XIdentifierAccess.class; break;
case 8: valueClass = XElementAccess.class; break;
case 9: valueClass = com.sun.star.uno.Exception.class; break;
case 10: valueClass = com.sun.star.uno.RuntimeException.class; break;
case 11: valueClass = EventObject.class; break;
case 12: valueClass = ContainerEvent.class; break;
case 13: valueClass = Object.class; break;
default:
fail( "internal error: wrong position for getValueClass" );
}
return valueClass;
}
private Object impl_getSomeValueByTypePos( int _pos )
{
Object someValue = null;
switch ( _pos )
{
case 0: someValue = Boolean.FALSE; break;
case 1: someValue = Short.valueOf( (short)0 ); break;
case 2: someValue = Integer.valueOf( 0 ); break;
case 3: someValue = Long.valueOf( 0 ); break;
case 4: someValue = UnoRuntime.queryInterface( XInterface.class, new DummyInterface() ); break;
case 5: someValue = UnoRuntime.queryInterface( XSet.class, new DummySet() ); break;
case 6: someValue = UnoRuntime.queryInterface( XContainer.class, new DummyContainer() ); break;
case 7: someValue = UnoRuntime.queryInterface( XIdentifierAccess.class, new DummyIdentifierAccess() ); break;
case 8: someValue = UnoRuntime.queryInterface( XElementAccess.class, new DummyElementAccess() ); break;
case 9: someValue = new com.sun.star.uno.Exception(); break;
case 10: someValue = new com.sun.star.uno.RuntimeException(); break;
case 11: someValue = new EventObject(); break;
case 12: someValue = new ContainerEvent(); break;
case 13: someValue = new Locale(); break; // just use *any* value which does not conflict with the others
default:
fail( "internal error: wrong position for getSomeValue" );
}
return someValue;
}
private static class DummyInterface implements XInterface
{
}
private static class DummySet implements XSet
{
public boolean has( Object arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public void insert( Object arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public void remove( Object arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public XEnumeration createEnumeration() { throw new UnsupportedOperationException( "Not implemented." ); }
public Type getElementType() { throw new UnsupportedOperationException( "Not implemented." ); }
public boolean hasElements() { throw new UnsupportedOperationException( "Not implemented." ); }
}
private class DummyContainer implements XContainer
{
public void addContainerListener( XContainerListener arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public void removeContainerListener( XContainerListener arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
}
private class DummyIdentifierAccess implements XIdentifierAccess
{
public Object getByIdentifier( int arg0 ) { throw new UnsupportedOperationException( "Not implemented." ); }
public int[] getIdentifiers() { throw new UnsupportedOperationException( "Not implemented." ); }
public Type getElementType() { throw new UnsupportedOperationException( "Not implemented." ); }
public boolean hasElements() { throw new UnsupportedOperationException( "Not implemented." ); }
}
private class DummyElementAccess implements XElementAccess
{
public Type getElementType() { throw new UnsupportedOperationException( "Not implemented." ); }
public boolean hasElements() { throw new UnsupportedOperationException( "Not implemented." ); }
}
@Test public void testValueTypes() throws com.sun.star.uno.Exception
{
// type compatibility matrix: rows are the value types used to create the map,
// columns are the value types fed into the map. A value "1" means the respective type
// should be accepted.
Integer[][] typeCompatibility = new Integer[][] {
/* boolean */ new Integer[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* short */ new Integer[] { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* int */ new Integer[] { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* long */ new Integer[] { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
/* XInterface */ new Integer[] { 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 },
/* XSet */ new Integer[] { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
/* XContainer */ new Integer[] { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
/* XIdentifierAccess */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
/* XElementAccess */ new Integer[] { 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0 },
/* Exception */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 },
/* RuntimeException */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
/* EventObject <SUF>*/ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 },
/* ContainerEvent */ new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 },
/* any */ new Integer[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
};
// several asects are checked with this compatibility matrix:
// - if a map's value type is a scalar type, or a string, then nothing but this
// type should be accepted
// - if a map's value type is an interface type, then values should be accepted if
// they contain a derived interface, or the interface itself, or if they can be
// queried for this interface (actually, the latter rule is not tested with the
// above matrix)
// - if a map's value type is a struct or exception, then values should be accepted
// if they are of the given type, or of a derived type.
// - if a map's value type is "any", then, well, any value should be accepted
for ( int valueTypePos = 0; valueTypePos != typeCompatibility.length; ++valueTypePos )
{
com.sun.star.container.EnumerableMap.create( connection.getComponentContext(),
new Type( Integer.class ), new Type( impl_getValueClassByPos( valueTypePos ) ) );
for ( int checkTypePos = 0; checkTypePos != typeCompatibility[valueTypePos].length; ++checkTypePos )
{
impl_getSomeValueByTypePos( checkTypePos );
if ( typeCompatibility[valueTypePos][checkTypePos] != 0 )
{
// expected to succeed
//? assureException(
//? "(" + valueTypePos + "," + checkTypePos + ") putting an " +
//? AnyConverter.getType( value ).getTypeName() + ", where " +
//? map.getValueType().getTypeName() + " is expected, should succeed",
//? map, "put", new Class[] { Object.class, Object.class }, new Object[] { key, value },
//? null );
}
else
{
// expected to fail
//? assureException(
//? "(" + valueTypePos + "," + checkTypePos + ") putting an " +
//? AnyConverter.getType( value ).getTypeName() + ", where " +
//? map.getValueType().getTypeName() + " is expected, should not succeed",
//? map, "put", new Class[] { Object.class, Object.class }, new Object[] { key, value },
//? IllegalTypeException.class );
}
}
}
}
private interface CompareEqual
{
boolean areEqual( Object _lhs, Object _rhs );
}
private class DefaultCompareEqual implements CompareEqual
{
public boolean areEqual( Object _lhs, Object _rhs )
{
return _lhs.equals( _rhs );
}
}
private class PairCompareEqual implements CompareEqual
{
public boolean areEqual( Object _lhs, Object _rhs )
{
Pair< ?, ? > lhs = (Pair< ?, ? >)_lhs;
Pair< ?, ? > rhs = (Pair< ?, ? >)_rhs;
return lhs.First.equals( rhs.First ) && lhs.Second.equals( rhs.Second );
}
}
private void impl_verifyEnumerationContent( XEnumeration _enum, final Object[] _expectedElements, final String _context )
throws com.sun.star.uno.Exception
{
// since we cannot assume the map to preserve the ordering in which the elements where inserted,
// we can only verify that all elements exist as expected, plus *no more* elements than expected
// are provided by the enumeration
Set<Integer> set = new HashSet<Integer>();
for ( int i=0; i<_expectedElements.length; ++i )
{
set.add( i );
}
CompareEqual comparator = _expectedElements[0].getClass().equals( Pair.class )
? new PairCompareEqual()
: new DefaultCompareEqual();
for ( int i=0; i<_expectedElements.length; ++i )
{
assertTrue( _context + ": too few elements in the enumeration (still " + ( _expectedElements.length - i ) + " to go)",
_enum.hasMoreElements() );
Object nextElement = _enum.nextElement();
if ( nextElement.getClass().equals( Any.class ) )
{
nextElement = ((Any)nextElement).getObject();
}
int foundPos = -1;
for ( int j=0; j<_expectedElements.length; ++j )
{
if ( comparator.areEqual( _expectedElements[j], nextElement ) )
{
foundPos = j;
break;
}
}
assertTrue( _context + ": '" + nextElement.toString() + "' is not expected in the enumeration",
set.contains( foundPos ) );
set.remove( foundPos );
}
assertTrue( _context + ": too many elements returned by the enumeration", set.isEmpty() );
}
@Test public void testEnumerations() throws com.sun.star.uno.Exception
{
// fill a map
final String[] keys = new String[] { "This", "is", "an", "enumeration", "test" };
final String[] values = new String[] { "for", "the", "map", "implementation", "." };
XEnumerableMap map = com.sun.star.container.EnumerableMap.create( connection.getComponentContext(), new Type( String.class ), new Type( String.class ) );
impl_putAll( map, keys, values );
final Pair< ?, ? >[] paired = new Pair< ?, ? >[ keys.length ];
for ( int i=0; i<keys.length; ++i )
{
paired[i] = new Pair< Object, Object >( keys[i], values[i] );
}
// create non-isolated enumerators, and check their content
XEnumeration enumerateKeys = map.createKeyEnumeration( false );
XEnumeration enumerateValues = map.createValueEnumeration( false );
XEnumeration enumerateAll = map.createElementEnumeration( false );
impl_verifyEnumerationContent( enumerateKeys, keys, "key enumeration" );
impl_verifyEnumerationContent( enumerateValues, values, "value enumeration" );
impl_verifyEnumerationContent( enumerateAll, paired, "content enumeration" );
// all enumerators above have been created as non-isolated iterators, so they're expected to die when
// the underlying map changes
map.remove( keys[0] );
//? assureException( enumerateKeys, "hasMoreElements", new Object[] {}, DisposedException.class );
//? assureException( enumerateValues, "hasMoreElements", new Object[] {}, DisposedException.class );
//? assureException( enumerateAll, "hasMoreElements", new Object[] {}, DisposedException.class );
// now try with isolated iterators
map.put( keys[0], values[0] );
enumerateKeys = map.createKeyEnumeration( true );
enumerateValues = map.createValueEnumeration( true );
enumerateAll = map.createElementEnumeration( true );
map.put( "additional", "value" );
impl_verifyEnumerationContent( enumerateKeys, keys, "key enumeration" );
impl_verifyEnumerationContent( enumerateValues, values, "value enumeration" );
impl_verifyEnumerationContent( enumerateAll, paired, "content enumeration" );
}
@Test public void testSpecialValues() throws com.sun.star.uno.Exception
{
final Double[] keys = new Double[] { Double.valueOf( 0 ), Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY };
final Double[] values = new Double[] { Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.valueOf( 0 ) };
XEnumerableMap map = com.sun.star.container.EnumerableMap.create( connection.getComponentContext(), new Type( Double.class ), new Type( Double.class ) );
impl_putAll( map, keys, values );
assertTrue( "containsKey( Double.+INF failed", map.containsKey( Double.POSITIVE_INFINITY ) );
assertTrue( "containsKey( Double.-INF failed", map.containsKey( Double.NEGATIVE_INFINITY ) );
assertTrue( "containsKey( 0 ) failed", map.containsKey( Double.valueOf( 0 ) ) );
assertTrue( "containsValue( Double.+INF ) failed", map.containsValue( Double.POSITIVE_INFINITY ) );
assertTrue( "containsValue( Double.-INF ) failed", map.containsValue( Double.NEGATIVE_INFINITY ) );
assertTrue( "containsValue( 0 ) failed", map.containsValue( Double.valueOf( 0 ) ) );
// put and containsKey should reject Double.NaN as key
//? assureException( "Double.NaN should not be allowed as key in a call to 'put'", map, "put",
//? new Class[] { Object.class, Object.class }, new Object[] { Double.NaN, Double.valueOf( 0 ) },
//? com.sun.star.lang.IllegalArgumentException.class );
//? assureException( "Double.NaN should not be allowed as key in a call to 'containsKey'", map, "containsKey",
//? new Class[] { Object.class }, new Object[] { Double.NaN },
//? com.sun.star.lang.IllegalArgumentException.class );
// ditto for put and containsValue
//? assureException( "Double.NaN should not be allowed as value in a call to 'put'", map, "put",
//? new Class[] { Object.class, Object.class }, new Object[] { Double.valueOf( 0 ), Double.NaN },
//? com.sun.star.lang.IllegalArgumentException.class );
//? assureException( "Double.NaN should not be allowed as key in a call to 'containsValue'", map, "containsValue",
//? new Class[] { Object.class }, new Object[] { Double.NaN },
//? com.sun.star.lang.IllegalArgumentException.class );
}
private static XMultiServiceFactory getMSF()
{
return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager());
}
// setup and close connections
@BeforeClass public static void setUpConnection() throws Exception {
System.out.println("setUpConnection()");
connection.setUp();
}
@AfterClass public static void tearDownConnection()
throws InterruptedException, com.sun.star.uno.Exception
{
System.out.println("tearDownConnection()");
connection.tearDown();
}
private static final OfficeConnection connection = new OfficeConnection();
}
|
122377_9 | /*-
* #%L
* WollMux
* %%
* Copyright (C) 2005 - 2023 Landeshauptstadt München and LibreOffice contributors
* %%
* Licensed under the EUPL, Version 1.1 or – as soon they will be
* approved by the European Commission - subsequent versions of the
* EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl5
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
* #L%
*/
package org.libreoffice.lots;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.star.awt.Key;
import com.sun.star.awt.KeyEvent;
import com.sun.star.awt.KeyFunction;
import com.sun.star.awt.KeyModifier;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.ui.XAcceleratorConfiguration;
import org.libreoffice.ext.unohelper.common.UNO;
import org.libreoffice.ext.unohelper.common.UnoHelperException;
import org.libreoffice.lots.config.ConfigThingy;
import org.libreoffice.lots.config.NodeNotFoundException;
public class Shortcuts
{
private static final Logger LOGGER = LoggerFactory.getLogger(Shortcuts.class);
private Shortcuts()
{
// hide public constructor
}
/**
* Reads all attributes SHORTCUT and URL from key combinationsConf, deletes
* all existing key combinations whose URL begins with "wollmux:" and
* sets new keyboard shortcut in OOo-Writer.
*
* @param tastenkombinationenConf
* .conf section KeyboardShortcuts with all nodes
*/
public static void createShortcuts(ConfigThingy tastenkombinationenConf)
{
XAcceleratorConfiguration shortcutManager = null;
try
{
shortcutManager = UNO.getShortcutManager("com.sun.star.text.TextDocument");
}
catch (UnoHelperException e1)
{
LOGGER.error("ShortcutManager nicht verfügbar.", e1);
return;
}
// Delete all KeyEvents that start with "wollmux:".
removeComandFromAllKeyEvents(shortcutManager);
// read the node SHORTCUT
ConfigThingy shortcutConf = tastenkombinationenConf.queryByChild("SHORTCUT");
// Iterate over the SHORTCUT nodes
Iterator<ConfigThingy> iterShortcut = shortcutConf.iterator();
while (iterShortcut.hasNext())
{
ConfigThingy tastenkombination = iterShortcut.next();
String shortcut = null;
// read the node SHORTCUT
try
{
shortcut = tastenkombination.get("SHORTCUT").toString();
}
catch (NodeNotFoundException e)
{
LOGGER.error("SHORTCUT specification is missing in '{}'", tastenkombination.stringRepresentation());
continue;
}
String url = null;
// read the node url
try
{
url = tastenkombination.get("URL").toString();
}
catch (NodeNotFoundException e)
{
LOGGER.error("URL specification is missing in '{}'", tastenkombination.stringRepresentation());
continue;
}
KeyEvent keyEvent = createKeyEvent(shortcut);
if (keyEvent != null)
{
// set the key combination with KeyEvent and WollMux-Url
try
{
shortcutManager.setKeyEvent(keyEvent, url);
}
catch (Exception e)
{
LOGGER.error("", e);
}
}
else
{
LOGGER.error("Invalid shortcut '{}' in .conf section \"KeyboardShortcuts\"", shortcut);
}
}
// Make change persistent
try
{
if (UNO.XUIConfigurationPersistence(shortcutManager) != null)
{
UNO.XUIConfigurationPersistence(shortcutManager).store();
}
}
catch (Exception e)
{
LOGGER.error("", e);
}
}
/**
* If there are keyboard shortcuts with a UNO url starting with "wollmux:", they will
* these deleted. Workaround for not working
* xAcceleratorConfiguration.removeCommandFromAllKeyEvents(). OOo Issue #72558
*
* @param xAcceleratorConfiguration
* AcceleratorConfiguration (must be made persistent afterwards with store())
*/
private static void removeComandFromAllKeyEvents(
XAcceleratorConfiguration xAcceleratorConfiguration)
{
// read all set key combinations
KeyEvent[] keys = xAcceleratorConfiguration.getAllKeyEvents();
// If there are key combinations with the UNO url starting with "wollmux:"
// exist, these are deleted. Workaround for not working
// xAcceleratorConfiguration.removeCommandFromAllKeyEvents().
for (int i = 0; i < keys.length; i++)
{
try
{
String event = xAcceleratorConfiguration.getCommandByKeyEvent(keys[i]);
// if the UNO-url starts with "wollmux:" it will be deleted
if (event.startsWith("wollmux:"))
{
// delete the key combination
xAcceleratorConfiguration.removeKeyEvent(keys[i]);
}
}
catch (NoSuchElementException e)
{
LOGGER.error("", e);
}
}
}
/**
* Outputs all KeyEvents with Modifier, KeyCode and Command
*
* @param xac
* AcceleratorConfigurator
*/
public static void showKeyset(XAcceleratorConfiguration xac)
{
if (xac == null) return;
KeyEvent[] keys = xac.getAllKeyEvents();
try
{
for (int i = 0; i < keys.length; i++)
{
LOGGER.trace("Modifiers: {} KeyCode: {} --> {}", keys[i].Modifiers, keys[i].KeyCode,
xac.getCommandByKeyEvent(keys[i]));
}
}
catch (Exception e)
{
LOGGER.trace("", e);
}
}
/**
* Generates an Object KeyEvent
*
* @param shortcutWithSeparator
* Key combination with "+" as separator
* @return returns a KeyEvent or null if not a keyCode but only
* keyModifier are used
*/
private static KeyEvent createKeyEvent(String shortcutWithSeparator)
{
if (shortcutWithSeparator == null) return null;
String[] shortcuts = shortcutWithSeparator.split("\\+");
Short keyCode = null;
KeyEvent key = new KeyEvent();
key.Modifiers = 0;
key.KeyFunc = KeyFunction.DONTKNOW;
for (int i = 0; i < shortcuts.length; i++)
{
String shortcut = shortcuts[i].replaceAll("\\s", "");
keyCode = returnKeyCode(shortcut);
if (keyCode != null)
{
key.KeyCode = keyCode.shortValue();
}
Short keyModifier = returnKeyModifier(shortcut);
if (keyModifier != null)
{
key.Modifiers |= keyModifier.shortValue();
}
}
if (keyCode == null)
{
return null;
}
else
{
return key;
}
}
/**
* Returns the constant com.sun.star.awt.Key for the corresponding key
*
* @param shortcut
* button
* @return key of the corresponding key
*/
private static Short returnKeyCode(String shortcut)
{
final Map<String, Short> myMap = new HashMap<>();
// Zahlen 0-9
myMap.put("0", Short.valueOf(Key.NUM0));
myMap.put("1", Short.valueOf(Key.NUM1));
myMap.put("2", Short.valueOf(Key.NUM2));
myMap.put("3", Short.valueOf(Key.NUM3));
myMap.put("4", Short.valueOf(Key.NUM4));
myMap.put("5", Short.valueOf(Key.NUM5));
myMap.put("6", Short.valueOf(Key.NUM6));
myMap.put("7", Short.valueOf(Key.NUM7));
myMap.put("8", Short.valueOf(Key.NUM8));
myMap.put("9", Short.valueOf(Key.NUM9));
// Buchstaben A-Z
myMap.put("A", Short.valueOf(Key.A));
myMap.put("B", Short.valueOf(Key.B));
myMap.put("C", Short.valueOf(Key.C));
myMap.put("D", Short.valueOf(Key.D));
myMap.put("E", Short.valueOf(Key.E));
myMap.put("F", Short.valueOf(Key.F));
myMap.put("G", Short.valueOf(Key.G));
myMap.put("H", Short.valueOf(Key.H));
myMap.put("I", Short.valueOf(Key.I));
myMap.put("J", Short.valueOf(Key.J));
myMap.put("K", Short.valueOf(Key.K));
myMap.put("L", Short.valueOf(Key.L));
myMap.put("M", Short.valueOf(Key.M));
myMap.put("N", Short.valueOf(Key.N));
myMap.put("O", Short.valueOf(Key.O));
myMap.put("P", Short.valueOf(Key.P));
myMap.put("Q", Short.valueOf(Key.Q));
myMap.put("R", Short.valueOf(Key.R));
myMap.put("S", Short.valueOf(Key.S));
myMap.put("T", Short.valueOf(Key.T));
myMap.put("U", Short.valueOf(Key.U));
myMap.put("V", Short.valueOf(Key.V));
myMap.put("W", Short.valueOf(Key.W));
myMap.put("X", Short.valueOf(Key.X));
myMap.put("Y", Short.valueOf(Key.Y));
myMap.put("Z", Short.valueOf(Key.Z));
// F1 - F26
myMap.put("F1", Short.valueOf(Key.F1));
myMap.put("F2", Short.valueOf(Key.F2));
myMap.put("F3", Short.valueOf(Key.F3));
myMap.put("F4", Short.valueOf(Key.F4));
myMap.put("F5", Short.valueOf(Key.F5));
myMap.put("F6", Short.valueOf(Key.F6));
myMap.put("F7", Short.valueOf(Key.F7));
myMap.put("F8", Short.valueOf(Key.F8));
myMap.put("F9", Short.valueOf(Key.F9));
myMap.put("F10", Short.valueOf(Key.F10));
myMap.put("F11", Short.valueOf(Key.F11));
myMap.put("F12", Short.valueOf(Key.F12));
myMap.put("F13", Short.valueOf(Key.F13));
myMap.put("F14", Short.valueOf(Key.F14));
myMap.put("F15", Short.valueOf(Key.F15));
myMap.put("F16", Short.valueOf(Key.F16));
myMap.put("F17", Short.valueOf(Key.F17));
myMap.put("F18", Short.valueOf(Key.F18));
myMap.put("F19", Short.valueOf(Key.F19));
myMap.put("F20", Short.valueOf(Key.F20));
myMap.put("F21", Short.valueOf(Key.F21));
myMap.put("F22", Short.valueOf(Key.F22));
myMap.put("F23", Short.valueOf(Key.F23));
myMap.put("F24", Short.valueOf(Key.F24));
myMap.put("F25", Short.valueOf(Key.F25));
myMap.put("F26", Short.valueOf(Key.F26));
myMap.put("DOWN", Short.valueOf(Key.DOWN));
myMap.put("UNTEN", Short.valueOf(Key.DOWN));
myMap.put("UP", Short.valueOf(Key.UP));
myMap.put("OBEN", Short.valueOf(Key.UP));
myMap.put("LEFT", Short.valueOf(Key.LEFT));
myMap.put("LINKS", Short.valueOf(Key.LEFT));
myMap.put("RIGHT", Short.valueOf(Key.RIGHT));
myMap.put("RECHTS", Short.valueOf(Key.RIGHT));
myMap.put("HOME", Short.valueOf(Key.HOME));
myMap.put("POS1", Short.valueOf(Key.HOME));
myMap.put("END", Short.valueOf(Key.END));
myMap.put("ENDE", Short.valueOf(Key.END));
myMap.put("PAGEUP", Short.valueOf(Key.PAGEUP));
myMap.put("BILDAUF", Short.valueOf(Key.PAGEUP));
myMap.put("RETURN", Short.valueOf(Key.RETURN));
myMap.put("EINGABE", Short.valueOf(Key.RETURN));
myMap.put("ESCAPE", Short.valueOf(Key.ESCAPE));
myMap.put("ESC", Short.valueOf(Key.ESCAPE));
myMap.put("TAB", Short.valueOf(Key.TAB));
myMap.put("TABULATOR", Short.valueOf(Key.TAB));
myMap.put("BACKSPACE", Short.valueOf(Key.BACKSPACE));
myMap.put("RUECKSCHRITT", Short.valueOf(Key.BACKSPACE));
myMap.put("RÜCKSCHRITT", Short.valueOf(Key.BACKSPACE));
myMap.put("SPACE", Short.valueOf(Key.SPACE));
myMap.put("LEERTASTE", Short.valueOf(Key.SPACE));
myMap.put("INSERT", Short.valueOf(Key.INSERT));
myMap.put("EINFG", Short.valueOf(Key.INSERT));
myMap.put("DELETE", Short.valueOf(Key.DELETE));
myMap.put("ENTF", Short.valueOf(Key.DELETE));
myMap.put("ADD", Short.valueOf(Key.ADD));
myMap.put("PLUS", Short.valueOf(Key.ADD));
myMap.put("SUBTRACT", Short.valueOf(Key.SUBTRACT));
myMap.put("-", Short.valueOf(Key.SUBTRACT));
myMap.put("MULTIPLY", Short.valueOf(Key.MULTIPLY));
myMap.put("*", Short.valueOf(Key.MULTIPLY));
myMap.put("DIVIDE", Short.valueOf(Key.DIVIDE));
myMap.put("/", Short.valueOf(Key.DIVIDE));
myMap.put("POINT", Short.valueOf(Key.POINT));
myMap.put(".", Short.valueOf(Key.POINT));
myMap.put("COMMA", Short.valueOf(Key.COMMA));
myMap.put(",", Short.valueOf(Key.COMMA));
myMap.put("LESS", Short.valueOf(Key.LESS));
myMap.put("<", Short.valueOf(Key.LESS));
myMap.put("GREATER", Short.valueOf(Key.GREATER));
myMap.put(">", Short.valueOf(Key.GREATER));
myMap.put("EQUAL", Short.valueOf(Key.EQUAL));
myMap.put("=", Short.valueOf(Key.EQUAL));
return myMap.get(shortcut.toUpperCase());
}
/**
* Returns the constant com.sun.star.awt.KeyModifier for the corresponding key
* return
*
* @param shortcut
* button
* @return KeyModifier of the corresponding key
*/
private static Short returnKeyModifier(String shortcut)
{
final Map<String, Short> myMap = new HashMap<>();
// SHIFT, CTRL und ALT
myMap.put("SHIFT", Short.valueOf(KeyModifier.SHIFT));
myMap.put("UMSCHALT", Short.valueOf(KeyModifier.SHIFT));
myMap.put("CTRL", Short.valueOf(KeyModifier.MOD1));
myMap.put("STRG", Short.valueOf(KeyModifier.MOD1));
myMap.put("ALT", Short.valueOf(KeyModifier.MOD2));
return myMap.get(shortcut.toUpperCase());
}
}
| LibreOffice/lots | core/src/main/java/org/libreoffice/lots/Shortcuts.java | 4,670 | // Make change persistent | line_comment | nl | /*-
* #%L
* WollMux
* %%
* Copyright (C) 2005 - 2023 Landeshauptstadt München and LibreOffice contributors
* %%
* Licensed under the EUPL, Version 1.1 or – as soon they will be
* approved by the European Commission - subsequent versions of the
* EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl5
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
* #L%
*/
package org.libreoffice.lots;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.star.awt.Key;
import com.sun.star.awt.KeyEvent;
import com.sun.star.awt.KeyFunction;
import com.sun.star.awt.KeyModifier;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.ui.XAcceleratorConfiguration;
import org.libreoffice.ext.unohelper.common.UNO;
import org.libreoffice.ext.unohelper.common.UnoHelperException;
import org.libreoffice.lots.config.ConfigThingy;
import org.libreoffice.lots.config.NodeNotFoundException;
public class Shortcuts
{
private static final Logger LOGGER = LoggerFactory.getLogger(Shortcuts.class);
private Shortcuts()
{
// hide public constructor
}
/**
* Reads all attributes SHORTCUT and URL from key combinationsConf, deletes
* all existing key combinations whose URL begins with "wollmux:" and
* sets new keyboard shortcut in OOo-Writer.
*
* @param tastenkombinationenConf
* .conf section KeyboardShortcuts with all nodes
*/
public static void createShortcuts(ConfigThingy tastenkombinationenConf)
{
XAcceleratorConfiguration shortcutManager = null;
try
{
shortcutManager = UNO.getShortcutManager("com.sun.star.text.TextDocument");
}
catch (UnoHelperException e1)
{
LOGGER.error("ShortcutManager nicht verfügbar.", e1);
return;
}
// Delete all KeyEvents that start with "wollmux:".
removeComandFromAllKeyEvents(shortcutManager);
// read the node SHORTCUT
ConfigThingy shortcutConf = tastenkombinationenConf.queryByChild("SHORTCUT");
// Iterate over the SHORTCUT nodes
Iterator<ConfigThingy> iterShortcut = shortcutConf.iterator();
while (iterShortcut.hasNext())
{
ConfigThingy tastenkombination = iterShortcut.next();
String shortcut = null;
// read the node SHORTCUT
try
{
shortcut = tastenkombination.get("SHORTCUT").toString();
}
catch (NodeNotFoundException e)
{
LOGGER.error("SHORTCUT specification is missing in '{}'", tastenkombination.stringRepresentation());
continue;
}
String url = null;
// read the node url
try
{
url = tastenkombination.get("URL").toString();
}
catch (NodeNotFoundException e)
{
LOGGER.error("URL specification is missing in '{}'", tastenkombination.stringRepresentation());
continue;
}
KeyEvent keyEvent = createKeyEvent(shortcut);
if (keyEvent != null)
{
// set the key combination with KeyEvent and WollMux-Url
try
{
shortcutManager.setKeyEvent(keyEvent, url);
}
catch (Exception e)
{
LOGGER.error("", e);
}
}
else
{
LOGGER.error("Invalid shortcut '{}' in .conf section \"KeyboardShortcuts\"", shortcut);
}
}
// Make change<SUF>
try
{
if (UNO.XUIConfigurationPersistence(shortcutManager) != null)
{
UNO.XUIConfigurationPersistence(shortcutManager).store();
}
}
catch (Exception e)
{
LOGGER.error("", e);
}
}
/**
* If there are keyboard shortcuts with a UNO url starting with "wollmux:", they will
* these deleted. Workaround for not working
* xAcceleratorConfiguration.removeCommandFromAllKeyEvents(). OOo Issue #72558
*
* @param xAcceleratorConfiguration
* AcceleratorConfiguration (must be made persistent afterwards with store())
*/
private static void removeComandFromAllKeyEvents(
XAcceleratorConfiguration xAcceleratorConfiguration)
{
// read all set key combinations
KeyEvent[] keys = xAcceleratorConfiguration.getAllKeyEvents();
// If there are key combinations with the UNO url starting with "wollmux:"
// exist, these are deleted. Workaround for not working
// xAcceleratorConfiguration.removeCommandFromAllKeyEvents().
for (int i = 0; i < keys.length; i++)
{
try
{
String event = xAcceleratorConfiguration.getCommandByKeyEvent(keys[i]);
// if the UNO-url starts with "wollmux:" it will be deleted
if (event.startsWith("wollmux:"))
{
// delete the key combination
xAcceleratorConfiguration.removeKeyEvent(keys[i]);
}
}
catch (NoSuchElementException e)
{
LOGGER.error("", e);
}
}
}
/**
* Outputs all KeyEvents with Modifier, KeyCode and Command
*
* @param xac
* AcceleratorConfigurator
*/
public static void showKeyset(XAcceleratorConfiguration xac)
{
if (xac == null) return;
KeyEvent[] keys = xac.getAllKeyEvents();
try
{
for (int i = 0; i < keys.length; i++)
{
LOGGER.trace("Modifiers: {} KeyCode: {} --> {}", keys[i].Modifiers, keys[i].KeyCode,
xac.getCommandByKeyEvent(keys[i]));
}
}
catch (Exception e)
{
LOGGER.trace("", e);
}
}
/**
* Generates an Object KeyEvent
*
* @param shortcutWithSeparator
* Key combination with "+" as separator
* @return returns a KeyEvent or null if not a keyCode but only
* keyModifier are used
*/
private static KeyEvent createKeyEvent(String shortcutWithSeparator)
{
if (shortcutWithSeparator == null) return null;
String[] shortcuts = shortcutWithSeparator.split("\\+");
Short keyCode = null;
KeyEvent key = new KeyEvent();
key.Modifiers = 0;
key.KeyFunc = KeyFunction.DONTKNOW;
for (int i = 0; i < shortcuts.length; i++)
{
String shortcut = shortcuts[i].replaceAll("\\s", "");
keyCode = returnKeyCode(shortcut);
if (keyCode != null)
{
key.KeyCode = keyCode.shortValue();
}
Short keyModifier = returnKeyModifier(shortcut);
if (keyModifier != null)
{
key.Modifiers |= keyModifier.shortValue();
}
}
if (keyCode == null)
{
return null;
}
else
{
return key;
}
}
/**
* Returns the constant com.sun.star.awt.Key for the corresponding key
*
* @param shortcut
* button
* @return key of the corresponding key
*/
private static Short returnKeyCode(String shortcut)
{
final Map<String, Short> myMap = new HashMap<>();
// Zahlen 0-9
myMap.put("0", Short.valueOf(Key.NUM0));
myMap.put("1", Short.valueOf(Key.NUM1));
myMap.put("2", Short.valueOf(Key.NUM2));
myMap.put("3", Short.valueOf(Key.NUM3));
myMap.put("4", Short.valueOf(Key.NUM4));
myMap.put("5", Short.valueOf(Key.NUM5));
myMap.put("6", Short.valueOf(Key.NUM6));
myMap.put("7", Short.valueOf(Key.NUM7));
myMap.put("8", Short.valueOf(Key.NUM8));
myMap.put("9", Short.valueOf(Key.NUM9));
// Buchstaben A-Z
myMap.put("A", Short.valueOf(Key.A));
myMap.put("B", Short.valueOf(Key.B));
myMap.put("C", Short.valueOf(Key.C));
myMap.put("D", Short.valueOf(Key.D));
myMap.put("E", Short.valueOf(Key.E));
myMap.put("F", Short.valueOf(Key.F));
myMap.put("G", Short.valueOf(Key.G));
myMap.put("H", Short.valueOf(Key.H));
myMap.put("I", Short.valueOf(Key.I));
myMap.put("J", Short.valueOf(Key.J));
myMap.put("K", Short.valueOf(Key.K));
myMap.put("L", Short.valueOf(Key.L));
myMap.put("M", Short.valueOf(Key.M));
myMap.put("N", Short.valueOf(Key.N));
myMap.put("O", Short.valueOf(Key.O));
myMap.put("P", Short.valueOf(Key.P));
myMap.put("Q", Short.valueOf(Key.Q));
myMap.put("R", Short.valueOf(Key.R));
myMap.put("S", Short.valueOf(Key.S));
myMap.put("T", Short.valueOf(Key.T));
myMap.put("U", Short.valueOf(Key.U));
myMap.put("V", Short.valueOf(Key.V));
myMap.put("W", Short.valueOf(Key.W));
myMap.put("X", Short.valueOf(Key.X));
myMap.put("Y", Short.valueOf(Key.Y));
myMap.put("Z", Short.valueOf(Key.Z));
// F1 - F26
myMap.put("F1", Short.valueOf(Key.F1));
myMap.put("F2", Short.valueOf(Key.F2));
myMap.put("F3", Short.valueOf(Key.F3));
myMap.put("F4", Short.valueOf(Key.F4));
myMap.put("F5", Short.valueOf(Key.F5));
myMap.put("F6", Short.valueOf(Key.F6));
myMap.put("F7", Short.valueOf(Key.F7));
myMap.put("F8", Short.valueOf(Key.F8));
myMap.put("F9", Short.valueOf(Key.F9));
myMap.put("F10", Short.valueOf(Key.F10));
myMap.put("F11", Short.valueOf(Key.F11));
myMap.put("F12", Short.valueOf(Key.F12));
myMap.put("F13", Short.valueOf(Key.F13));
myMap.put("F14", Short.valueOf(Key.F14));
myMap.put("F15", Short.valueOf(Key.F15));
myMap.put("F16", Short.valueOf(Key.F16));
myMap.put("F17", Short.valueOf(Key.F17));
myMap.put("F18", Short.valueOf(Key.F18));
myMap.put("F19", Short.valueOf(Key.F19));
myMap.put("F20", Short.valueOf(Key.F20));
myMap.put("F21", Short.valueOf(Key.F21));
myMap.put("F22", Short.valueOf(Key.F22));
myMap.put("F23", Short.valueOf(Key.F23));
myMap.put("F24", Short.valueOf(Key.F24));
myMap.put("F25", Short.valueOf(Key.F25));
myMap.put("F26", Short.valueOf(Key.F26));
myMap.put("DOWN", Short.valueOf(Key.DOWN));
myMap.put("UNTEN", Short.valueOf(Key.DOWN));
myMap.put("UP", Short.valueOf(Key.UP));
myMap.put("OBEN", Short.valueOf(Key.UP));
myMap.put("LEFT", Short.valueOf(Key.LEFT));
myMap.put("LINKS", Short.valueOf(Key.LEFT));
myMap.put("RIGHT", Short.valueOf(Key.RIGHT));
myMap.put("RECHTS", Short.valueOf(Key.RIGHT));
myMap.put("HOME", Short.valueOf(Key.HOME));
myMap.put("POS1", Short.valueOf(Key.HOME));
myMap.put("END", Short.valueOf(Key.END));
myMap.put("ENDE", Short.valueOf(Key.END));
myMap.put("PAGEUP", Short.valueOf(Key.PAGEUP));
myMap.put("BILDAUF", Short.valueOf(Key.PAGEUP));
myMap.put("RETURN", Short.valueOf(Key.RETURN));
myMap.put("EINGABE", Short.valueOf(Key.RETURN));
myMap.put("ESCAPE", Short.valueOf(Key.ESCAPE));
myMap.put("ESC", Short.valueOf(Key.ESCAPE));
myMap.put("TAB", Short.valueOf(Key.TAB));
myMap.put("TABULATOR", Short.valueOf(Key.TAB));
myMap.put("BACKSPACE", Short.valueOf(Key.BACKSPACE));
myMap.put("RUECKSCHRITT", Short.valueOf(Key.BACKSPACE));
myMap.put("RÜCKSCHRITT", Short.valueOf(Key.BACKSPACE));
myMap.put("SPACE", Short.valueOf(Key.SPACE));
myMap.put("LEERTASTE", Short.valueOf(Key.SPACE));
myMap.put("INSERT", Short.valueOf(Key.INSERT));
myMap.put("EINFG", Short.valueOf(Key.INSERT));
myMap.put("DELETE", Short.valueOf(Key.DELETE));
myMap.put("ENTF", Short.valueOf(Key.DELETE));
myMap.put("ADD", Short.valueOf(Key.ADD));
myMap.put("PLUS", Short.valueOf(Key.ADD));
myMap.put("SUBTRACT", Short.valueOf(Key.SUBTRACT));
myMap.put("-", Short.valueOf(Key.SUBTRACT));
myMap.put("MULTIPLY", Short.valueOf(Key.MULTIPLY));
myMap.put("*", Short.valueOf(Key.MULTIPLY));
myMap.put("DIVIDE", Short.valueOf(Key.DIVIDE));
myMap.put("/", Short.valueOf(Key.DIVIDE));
myMap.put("POINT", Short.valueOf(Key.POINT));
myMap.put(".", Short.valueOf(Key.POINT));
myMap.put("COMMA", Short.valueOf(Key.COMMA));
myMap.put(",", Short.valueOf(Key.COMMA));
myMap.put("LESS", Short.valueOf(Key.LESS));
myMap.put("<", Short.valueOf(Key.LESS));
myMap.put("GREATER", Short.valueOf(Key.GREATER));
myMap.put(">", Short.valueOf(Key.GREATER));
myMap.put("EQUAL", Short.valueOf(Key.EQUAL));
myMap.put("=", Short.valueOf(Key.EQUAL));
return myMap.get(shortcut.toUpperCase());
}
/**
* Returns the constant com.sun.star.awt.KeyModifier for the corresponding key
* return
*
* @param shortcut
* button
* @return KeyModifier of the corresponding key
*/
private static Short returnKeyModifier(String shortcut)
{
final Map<String, Short> myMap = new HashMap<>();
// SHIFT, CTRL und ALT
myMap.put("SHIFT", Short.valueOf(KeyModifier.SHIFT));
myMap.put("UMSCHALT", Short.valueOf(KeyModifier.SHIFT));
myMap.put("CTRL", Short.valueOf(KeyModifier.MOD1));
myMap.put("STRG", Short.valueOf(KeyModifier.MOD1));
myMap.put("ALT", Short.valueOf(KeyModifier.MOD2));
return myMap.get(shortcut.toUpperCase());
}
}
|
177237_6 | /*
* Copyright 2005 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or 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 Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* https://github.com/LibrePDF/OpenPDF
*/
package com.lowagie.text.pdf;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.error_messages.MessageLocalization;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Common field variables.
*
* @author Paulo Soares ([email protected])
*/
public abstract class BaseField {
/**
* A thin border with 1 point width.
*/
public static final float BORDER_WIDTH_THIN = 1;
/**
* A medium border with 2 point width.
*/
public static final float BORDER_WIDTH_MEDIUM = 2;
/**
* A thick border with 3 point width.
*/
public static final float BORDER_WIDTH_THICK = 3;
/**
* The field is visible.
*/
public static final int VISIBLE = 0;
/**
* The field is hidden.
*/
public static final int HIDDEN = 1;
/**
* The field is visible but does not print.
*/
public static final int VISIBLE_BUT_DOES_NOT_PRINT = 2;
/**
* The field is hidden but is printable.
*/
public static final int HIDDEN_BUT_PRINTABLE = 3;
/**
* The annotation flag: Invisible.
*/
public static final int INVISIBLE = PdfAnnotation.FLAGS_INVISIBLE;
/** The annotation flag Hidden. */
//public static final int HIDDEN = PdfAnnotation.FLAGS_HIDDEN;
/**
* The annotation flag Hidden.
*/
public static final int PRINT = PdfAnnotation.FLAGS_PRINT;
/**
* The annotation flag Hidden.
*/
public static final int NOVIEW = PdfAnnotation.FLAGS_NOVIEW;
/**
* The annotation flag Hidden.
*/
public static final int LOCKED = PdfAnnotation.FLAGS_LOCKED;
/**
* The user may not change the value of the field.
*/
public static final int READ_ONLY = PdfFormField.FF_READ_ONLY;
/**
* The field must have a value at the time it is exported by a submit-form action.
*/
public static final int REQUIRED = PdfFormField.FF_REQUIRED;
/**
* The field may contain multiple lines of text. This flag is only meaningful with text fields.
*/
public static final int MULTILINE = PdfFormField.FF_MULTILINE;
/**
* The field will not scroll (horizontally for single-line fields, vertically for multiple-line fields) to
* accommodate more text than will fit within its annotation rectangle. Once the field is full, no further text will
* be accepted.
*/
public static final int DO_NOT_SCROLL = PdfFormField.FF_DONOTSCROLL;
/**
* The field is intended for entering a secure password that should not be echoed visibly to the screen.
*/
public static final int PASSWORD = PdfFormField.FF_PASSWORD;
/**
* The text entered in the field represents the pathname of a file whose contents are to be submitted as the value
* of the field.
*/
public static final int FILE_SELECTION = PdfFormField.FF_FILESELECT;
/**
* The text entered in the field will not be spell-checked. This flag is meaningful only in text fields and in combo
* fields with the <CODE>EDIT</CODE> flag set.
*/
public static final int DO_NOT_SPELL_CHECK = PdfFormField.FF_DONOTSPELLCHECK;
/**
* If set the combo box includes an editable text box as well as a drop list; if clear, it includes only a drop
* list. This flag is only meaningful with combo fields.
*/
public static final int EDIT = PdfFormField.FF_EDIT;
/**
* whether or not a list may have multiple selections. Only applies to /CH LIST fields, not combo boxes.
*/
public static final int MULTISELECT = PdfFormField.FF_MULTISELECT;
/**
* combo box flag.
*/
public static final int COMB = PdfFormField.FF_COMB;
private final static Map<PdfName, Integer> fieldKeys = new HashMap<>();
static {
fieldKeys.putAll(PdfCopyFieldsImp.fieldKeys);
fieldKeys.put(PdfName.T, 1);
}
protected float borderWidth = BORDER_WIDTH_THIN;
protected int borderStyle = PdfBorderDictionary.STYLE_SOLID;
protected Color borderColor;
protected Color backgroundColor;
protected Color textColor;
protected BaseFont font;
protected float fontSize = 0;
protected int alignment = Element.ALIGN_LEFT;
protected PdfWriter writer;
protected String text;
protected Rectangle box;
/**
* Holds value of property rotation.
*/
protected int rotation = 0;
/**
* Holds value of property visibility.
*/
protected int visibility;
/**
* Holds value of property fieldName.
*/
protected String fieldName;
/**
* Holds the value of the alternate field name. (PDF attribute 'TU')
*/
protected String alternateFieldName;
/**
* Holds the value of the mapping field name. (PDF attribute 'TM')
*/
protected String mappingName;
/**
* Holds value of property options.
*/
protected int options;
/**
* Holds value of property maxCharacterLength.
*/
protected int maxCharacterLength;
/**
* Creates a new <CODE>TextField</CODE>.
*
* @param writer the document <CODE>PdfWriter</CODE>
* @param box the field location and dimensions
* @param fieldName the field name. If <CODE>null</CODE> only the widget keys will be included in the field allowing
* it to be used as a kid field.
*/
public BaseField(PdfWriter writer, Rectangle box, String fieldName) {
this.writer = writer;
setBox(box);
this.fieldName = fieldName;
}
protected static PdfAppearance getBorderAppearance(PdfWriter writer, Rectangle box, int rotation,
Color backgroundColor, int borderStyle, float borderWidth, Color borderColor, int options,
int maxCharacterLength) {
PdfAppearance app = PdfAppearance.createAppearance(writer, box.getWidth(), box.getHeight());
switch (rotation) {
case 90:
app.setMatrix(0, 1, -1, 0, box.getHeight(), 0);
break;
case 180:
app.setMatrix(-1, 0, 0, -1, box.getWidth(), box.getHeight());
break;
case 270:
app.setMatrix(0, -1, 1, 0, 0, box.getWidth());
break;
}
app.saveState();
// background
if (backgroundColor != null) {
app.setColorFill(backgroundColor);
app.rectangle(0, 0, box.getWidth(), box.getHeight());
app.fill();
}
// border
if (borderStyle == PdfBorderDictionary.STYLE_UNDERLINE) {
if (borderWidth != 0 && borderColor != null) {
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.moveTo(0, borderWidth / 2);
app.lineTo(box.getWidth(), borderWidth / 2);
app.stroke();
}
} else if (borderStyle == PdfBorderDictionary.STYLE_BEVELED) {
if (borderWidth != 0 && borderColor != null) {
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.rectangle(borderWidth / 2, borderWidth / 2, box.getWidth() - borderWidth,
box.getHeight() - borderWidth);
app.stroke();
}
// beveled
Color actual = backgroundColor;
if (actual == null) {
actual = Color.white;
}
app.setGrayFill(1);
drawTopFrame(app, borderWidth, box);
app.setColorFill(actual.darker());
drawBottomFrame(app, borderWidth, box);
} else if (borderStyle == PdfBorderDictionary.STYLE_INSET) {
if (borderWidth != 0 && borderColor != null) {
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.rectangle(borderWidth / 2, borderWidth / 2, box.getWidth() - borderWidth,
box.getHeight() - borderWidth);
app.stroke();
}
// inset
app.setGrayFill(0.5f);
drawTopFrame(app, borderWidth, box);
app.setGrayFill(0.75f);
drawBottomFrame(app, borderWidth, box);
} else {
if (borderWidth != 0 && borderColor != null) {
if (borderStyle == PdfBorderDictionary.STYLE_DASHED) {
app.setLineDash(3, 0);
}
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.rectangle(borderWidth / 2, borderWidth / 2, box.getWidth() - borderWidth,
box.getHeight() - borderWidth);
app.stroke();
//comb formfield flag is set and maxchar must be set (for textfield only!)
if ((options & COMB) != 0 && maxCharacterLength > 1) {
float step = box.getWidth() / maxCharacterLength;
float yb = borderWidth / 2;
float yt = box.getHeight() - borderWidth / 2;
for (int k = 1; k < maxCharacterLength; ++k) {
float x = step * k;
app.moveTo(x, yb);
app.lineTo(x, yt);
}
app.stroke();
}
}
}
app.restoreState();
return app;
}
protected static List<String> getAllHardBreaks(String text) {
List<String> arr = new ArrayList<>();
char[] cs = text.toCharArray();
int len = cs.length;
StringBuffer buf = new StringBuffer();
for (int k = 0; k < len; ++k) {
char c = cs[k];
if (c == '\r') {
if (k + 1 < len && cs[k + 1] == '\n') {
++k;
}
arr.add(buf.toString());
buf = new StringBuffer();
} else if (c == '\n') {
arr.add(buf.toString());
buf = new StringBuffer();
} else {
buf.append(c);
}
}
arr.add(buf.toString());
return arr;
}
protected static void trimRight(StringBuffer buf) {
int len = buf.length();
while (true) {
if (len == 0) {
return;
}
if (buf.charAt(--len) != ' ') {
return;
}
buf.setLength(len);
}
}
protected static List<String> breakLines(List<String> breaks, BaseFont font, float fontSize, float width) {
List<String> lines = new ArrayList<>();
StringBuffer buf = new StringBuffer();
for (String aBreak : breaks) {
buf.setLength(0);
float w = 0;
char[] cs = aBreak.toCharArray();
int len = cs.length;
// 0 inline first, 1 inline, 2 spaces
int state = 0;
int lastspace = -1;
char c = 0;
int refk = 0;
for (int k = 0; k < len; ++k) {
c = cs[k];
switch (state) {
case 0:
w += font.getWidthPoint(c, fontSize);
buf.append(c);
if (w > width) {
w = 0;
if (buf.length() > 1) {
--k;
buf.setLength(buf.length() - 1);
}
lines.add(buf.toString());
buf.setLength(0);
refk = k;
if (c == ' ') {
state = 2;
} else {
state = 1;
}
} else {
if (c != ' ') {
state = 1;
}
}
break;
case 1:
w += font.getWidthPoint(c, fontSize);
buf.append(c);
if (c == ' ') {
lastspace = k;
}
if (w > width) {
w = 0;
if (lastspace >= 0) {
k = lastspace;
buf.setLength(lastspace - refk);
trimRight(buf);
lines.add(buf.toString());
buf.setLength(0);
refk = k;
lastspace = -1;
state = 2;
} else {
if (buf.length() > 1) {
--k;
buf.setLength(buf.length() - 1);
}
lines.add(buf.toString());
buf.setLength(0);
refk = k;
if (c == ' ') {
state = 2;
}
}
}
break;
case 2:
if (c != ' ') {
w = 0;
--k;
state = 1;
}
break;
}
}
trimRight(buf);
lines.add(buf.toString());
}
return lines;
}
private static void drawTopFrame(PdfAppearance app, float borderWidth, Rectangle box) {
app.moveTo(borderWidth, borderWidth);
app.lineTo(borderWidth, box.getHeight() - borderWidth);
app.lineTo(box.getWidth() - borderWidth, box.getHeight() - borderWidth);
app.lineTo(box.getWidth() - 2 * borderWidth, box.getHeight() - 2 * borderWidth);
app.lineTo(2 * borderWidth, box.getHeight() - 2 * borderWidth);
app.lineTo(2 * borderWidth, 2 * borderWidth);
app.lineTo(borderWidth, borderWidth);
app.fill();
}
private static void drawBottomFrame(PdfAppearance app, float borderWidth, Rectangle box) {
app.moveTo(borderWidth, borderWidth);
app.lineTo(box.getWidth() - borderWidth, borderWidth);
app.lineTo(box.getWidth() - borderWidth, box.getHeight() - borderWidth);
app.lineTo(box.getWidth() - 2 * borderWidth, box.getHeight() - 2 * borderWidth);
app.lineTo(box.getWidth() - 2 * borderWidth, 2 * borderWidth);
app.lineTo(2 * borderWidth, 2 * borderWidth);
app.lineTo(borderWidth, borderWidth);
app.fill();
}
/**
* Moves the field keys from <CODE>from</CODE> to <CODE>to</CODE>. The moved keys are removed from
* <CODE>from</CODE>.
*
* @param from the source
* @param to the destination. It may be <CODE>null</CODE>
*/
public static void moveFields(PdfDictionary from, PdfDictionary to) {
for (Iterator i = from.getKeys().iterator(); i.hasNext(); ) {
PdfName key = (PdfName) i.next();
if (fieldKeys.containsKey(key)) {
if (to != null) {
to.put(key, from.get(key));
}
i.remove();
}
}
}
protected BaseFont getRealFont() throws IOException, DocumentException {
if (font == null) {
return BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
} else {
return font;
}
}
/**
* Gets the border width in points.
*
* @return the border width in points
*/
public float getBorderWidth() {
return this.borderWidth;
}
/**
* Sets the border width in points. To eliminate the border set the border color to <CODE>null</CODE>.
*
* @param borderWidth the border width in points
*/
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
/**
* Gets the border style.
*
* @return the border style
*/
public int getBorderStyle() {
return this.borderStyle;
}
/**
* Sets the border style. The styles are found in <CODE>PdfBorderDictionary</CODE> and can be
* <CODE>STYLE_SOLID</CODE>, <CODE>STYLE_DASHED</CODE>,
* <CODE>STYLE_BEVELED</CODE>, <CODE>STYLE_INSET</CODE> and
* <CODE>STYLE_UNDERLINE</CODE>.
*
* @param borderStyle the border style
*/
public void setBorderStyle(int borderStyle) {
this.borderStyle = borderStyle;
}
/**
* Gets the border color.
*
* @return the border color
*/
public Color getBorderColor() {
return this.borderColor;
}
/**
* Sets the border color. Set to <CODE>null</CODE> to remove the border.
*
* @param borderColor the border color
*/
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
/**
* Gets the background color.
*
* @return the background color
*/
public Color getBackgroundColor() {
return this.backgroundColor;
}
/**
* Sets the background color. Set to <CODE>null</CODE> for transparent background.
*
* @param backgroundColor the background color
*/
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
/**
* Gets the text color.
*
* @return the text color
*/
public Color getTextColor() {
return this.textColor;
}
/**
* Sets the text color. If <CODE>null</CODE> the color used will be black.
*
* @param textColor the text color
*/
public void setTextColor(Color textColor) {
this.textColor = textColor;
}
/**
* Gets the text font.
*
* @return the text font
*/
public BaseFont getFont() {
return this.font;
}
/**
* Sets the text font. If <CODE>null</CODE> then Helvetica will be used.
*
* @param font the text font
*/
public void setFont(BaseFont font) {
this.font = font;
}
/**
* Gets the font size.
*
* @return the font size
*/
public float getFontSize() {
return this.fontSize;
}
/**
* Sets the font size. If 0 then auto-sizing will be used but only for text fields.
*
* @param fontSize the font size
*/
public void setFontSize(float fontSize) {
this.fontSize = fontSize;
}
/**
* Gets the text horizontal alignment.
*
* @return the text horizontal alignment
*/
public int getAlignment() {
return this.alignment;
}
/**
* Sets the text horizontal alignment. It can be <CODE>Element.ALIGN_LEFT</CODE>,
* <CODE>Element.ALIGN_CENTER</CODE> and <CODE>Element.ALIGN_RIGHT</CODE>.
*
* @param alignment the text horizontal alignment
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
/**
* Gets the text.
*
* @return the text
*/
public String getText() {
return this.text;
}
/**
* Sets the text for text fields.
*
* @param text the text
*/
public void setText(String text) {
this.text = text;
}
/**
* Gets the field dimension and position.
*
* @return the field dimension and position
*/
public Rectangle getBox() {
return this.box;
}
/**
* Sets the field dimension and position.
*
* @param box the field dimension and position
*/
public void setBox(Rectangle box) {
if (box == null) {
this.box = null;
} else {
this.box = new Rectangle(box);
this.box.normalize();
}
}
/**
* Gets the field rotation.
*
* @return the field rotation
*/
public int getRotation() {
return this.rotation;
}
/**
* Sets the field rotation. This value should be the same as the page rotation where the field will be shown.
*
* @param rotation the field rotation
*/
public void setRotation(int rotation) {
if (rotation % 90 != 0) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90"));
}
rotation %= 360;
if (rotation < 0) {
rotation += 360;
}
this.rotation = rotation;
}
/**
* Convenience method to set the field rotation the same as the page rotation.
*
* @param page the page
*/
public void setRotationFromPage(Rectangle page) {
setRotation(page.getRotation());
}
/**
* Gets the field visibility flag.
*
* @return the field visibility flag
*/
public int getVisibility() {
return this.visibility;
}
/**
* Sets the field visibility flag. This flags can be one of
* <CODE>VISIBLE</CODE>, <CODE>HIDDEN</CODE>, <CODE>VISIBLE_BUT_DOES_NOT_PRINT</CODE>
* and <CODE>HIDDEN_BUT_PRINTABLE</CODE>.
*
* @param visibility field visibility flag
*/
public void setVisibility(int visibility) {
this.visibility = visibility;
}
/**
* Gets the field name.
*
* @return the field name
*/
public String getFieldName() {
return this.fieldName;
}
/**
* Sets the field name.
*
* @param fieldName the field name. If <CODE>null</CODE> only the widget keys will be included in the field allowing
* it to be used as a kid field.
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
/**
* Gets the alternate field name. (PDF attribute TU)
*
* @return the alternate field name
*/
public String getAlternateFieldName() {
return this.alternateFieldName;
}
/**
* Sets the alternateFieldName field name.
*
* @param alternateFieldName the alternate field name.
*/
public void setAlternateFieldName(String alternateFieldName) {
this.alternateFieldName = alternateFieldName;
}
/**
* Gets the mapping name. (PDF attribute TM)
*
* @return the mapping field name
*/
public String getMappingName() {
return this.mappingName;
}
/**
* Sets the mapping name. (PDF TM)
*
* @param mappingName the mapping name.
*/
public void setMappingName(String mappingName) {
this.mappingName = mappingName;
}
/**
* Gets the option flags.
*
* @return the option flags
*/
public int getOptions() {
return this.options;
}
/**
* Sets the option flags. The option flags can be a combination by oring of
* <CODE>READ_ONLY</CODE>, <CODE>REQUIRED</CODE>,
* <CODE>MULTILINE</CODE>, <CODE>DO_NOT_SCROLL</CODE>,
* <CODE>PASSWORD</CODE>, <CODE>FILE_SELECTION</CODE>,
* <CODE>DO_NOT_SPELL_CHECK</CODE> and <CODE>EDIT</CODE>.
*
* @param options the option flags
*/
public void setOptions(int options) {
this.options = options;
}
/**
* Gets the maximum length of the field's text, in characters.
*
* @return the maximum length of the field's text, in characters.
*/
public int getMaxCharacterLength() {
return this.maxCharacterLength;
}
/**
* Sets the maximum length of the field's text, in characters. It is only meaningful for text fields.
*
* @param maxCharacterLength the maximum length of the field's text, in characters
*/
public void setMaxCharacterLength(int maxCharacterLength) {
this.maxCharacterLength = maxCharacterLength;
}
/**
* Getter for property writer.
*
* @return Value of property writer.
*/
public PdfWriter getWriter() {
return writer;
}
/**
* Setter for property writer.
*
* @param writer New value of property writer.
*/
public void setWriter(PdfWriter writer) {
this.writer = writer;
}
}
| LibrePDF/OpenPDF | openpdf/src/main/java/com/lowagie/text/pdf/BaseField.java | 7,648 | /**
* The field is hidden.
*/ | block_comment | nl | /*
* Copyright 2005 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or 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 Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* https://github.com/LibrePDF/OpenPDF
*/
package com.lowagie.text.pdf;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.error_messages.MessageLocalization;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Common field variables.
*
* @author Paulo Soares ([email protected])
*/
public abstract class BaseField {
/**
* A thin border with 1 point width.
*/
public static final float BORDER_WIDTH_THIN = 1;
/**
* A medium border with 2 point width.
*/
public static final float BORDER_WIDTH_MEDIUM = 2;
/**
* A thick border with 3 point width.
*/
public static final float BORDER_WIDTH_THICK = 3;
/**
* The field is visible.
*/
public static final int VISIBLE = 0;
/**
* The field is<SUF>*/
public static final int HIDDEN = 1;
/**
* The field is visible but does not print.
*/
public static final int VISIBLE_BUT_DOES_NOT_PRINT = 2;
/**
* The field is hidden but is printable.
*/
public static final int HIDDEN_BUT_PRINTABLE = 3;
/**
* The annotation flag: Invisible.
*/
public static final int INVISIBLE = PdfAnnotation.FLAGS_INVISIBLE;
/** The annotation flag Hidden. */
//public static final int HIDDEN = PdfAnnotation.FLAGS_HIDDEN;
/**
* The annotation flag Hidden.
*/
public static final int PRINT = PdfAnnotation.FLAGS_PRINT;
/**
* The annotation flag Hidden.
*/
public static final int NOVIEW = PdfAnnotation.FLAGS_NOVIEW;
/**
* The annotation flag Hidden.
*/
public static final int LOCKED = PdfAnnotation.FLAGS_LOCKED;
/**
* The user may not change the value of the field.
*/
public static final int READ_ONLY = PdfFormField.FF_READ_ONLY;
/**
* The field must have a value at the time it is exported by a submit-form action.
*/
public static final int REQUIRED = PdfFormField.FF_REQUIRED;
/**
* The field may contain multiple lines of text. This flag is only meaningful with text fields.
*/
public static final int MULTILINE = PdfFormField.FF_MULTILINE;
/**
* The field will not scroll (horizontally for single-line fields, vertically for multiple-line fields) to
* accommodate more text than will fit within its annotation rectangle. Once the field is full, no further text will
* be accepted.
*/
public static final int DO_NOT_SCROLL = PdfFormField.FF_DONOTSCROLL;
/**
* The field is intended for entering a secure password that should not be echoed visibly to the screen.
*/
public static final int PASSWORD = PdfFormField.FF_PASSWORD;
/**
* The text entered in the field represents the pathname of a file whose contents are to be submitted as the value
* of the field.
*/
public static final int FILE_SELECTION = PdfFormField.FF_FILESELECT;
/**
* The text entered in the field will not be spell-checked. This flag is meaningful only in text fields and in combo
* fields with the <CODE>EDIT</CODE> flag set.
*/
public static final int DO_NOT_SPELL_CHECK = PdfFormField.FF_DONOTSPELLCHECK;
/**
* If set the combo box includes an editable text box as well as a drop list; if clear, it includes only a drop
* list. This flag is only meaningful with combo fields.
*/
public static final int EDIT = PdfFormField.FF_EDIT;
/**
* whether or not a list may have multiple selections. Only applies to /CH LIST fields, not combo boxes.
*/
public static final int MULTISELECT = PdfFormField.FF_MULTISELECT;
/**
* combo box flag.
*/
public static final int COMB = PdfFormField.FF_COMB;
private final static Map<PdfName, Integer> fieldKeys = new HashMap<>();
static {
fieldKeys.putAll(PdfCopyFieldsImp.fieldKeys);
fieldKeys.put(PdfName.T, 1);
}
protected float borderWidth = BORDER_WIDTH_THIN;
protected int borderStyle = PdfBorderDictionary.STYLE_SOLID;
protected Color borderColor;
protected Color backgroundColor;
protected Color textColor;
protected BaseFont font;
protected float fontSize = 0;
protected int alignment = Element.ALIGN_LEFT;
protected PdfWriter writer;
protected String text;
protected Rectangle box;
/**
* Holds value of property rotation.
*/
protected int rotation = 0;
/**
* Holds value of property visibility.
*/
protected int visibility;
/**
* Holds value of property fieldName.
*/
protected String fieldName;
/**
* Holds the value of the alternate field name. (PDF attribute 'TU')
*/
protected String alternateFieldName;
/**
* Holds the value of the mapping field name. (PDF attribute 'TM')
*/
protected String mappingName;
/**
* Holds value of property options.
*/
protected int options;
/**
* Holds value of property maxCharacterLength.
*/
protected int maxCharacterLength;
/**
* Creates a new <CODE>TextField</CODE>.
*
* @param writer the document <CODE>PdfWriter</CODE>
* @param box the field location and dimensions
* @param fieldName the field name. If <CODE>null</CODE> only the widget keys will be included in the field allowing
* it to be used as a kid field.
*/
public BaseField(PdfWriter writer, Rectangle box, String fieldName) {
this.writer = writer;
setBox(box);
this.fieldName = fieldName;
}
protected static PdfAppearance getBorderAppearance(PdfWriter writer, Rectangle box, int rotation,
Color backgroundColor, int borderStyle, float borderWidth, Color borderColor, int options,
int maxCharacterLength) {
PdfAppearance app = PdfAppearance.createAppearance(writer, box.getWidth(), box.getHeight());
switch (rotation) {
case 90:
app.setMatrix(0, 1, -1, 0, box.getHeight(), 0);
break;
case 180:
app.setMatrix(-1, 0, 0, -1, box.getWidth(), box.getHeight());
break;
case 270:
app.setMatrix(0, -1, 1, 0, 0, box.getWidth());
break;
}
app.saveState();
// background
if (backgroundColor != null) {
app.setColorFill(backgroundColor);
app.rectangle(0, 0, box.getWidth(), box.getHeight());
app.fill();
}
// border
if (borderStyle == PdfBorderDictionary.STYLE_UNDERLINE) {
if (borderWidth != 0 && borderColor != null) {
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.moveTo(0, borderWidth / 2);
app.lineTo(box.getWidth(), borderWidth / 2);
app.stroke();
}
} else if (borderStyle == PdfBorderDictionary.STYLE_BEVELED) {
if (borderWidth != 0 && borderColor != null) {
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.rectangle(borderWidth / 2, borderWidth / 2, box.getWidth() - borderWidth,
box.getHeight() - borderWidth);
app.stroke();
}
// beveled
Color actual = backgroundColor;
if (actual == null) {
actual = Color.white;
}
app.setGrayFill(1);
drawTopFrame(app, borderWidth, box);
app.setColorFill(actual.darker());
drawBottomFrame(app, borderWidth, box);
} else if (borderStyle == PdfBorderDictionary.STYLE_INSET) {
if (borderWidth != 0 && borderColor != null) {
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.rectangle(borderWidth / 2, borderWidth / 2, box.getWidth() - borderWidth,
box.getHeight() - borderWidth);
app.stroke();
}
// inset
app.setGrayFill(0.5f);
drawTopFrame(app, borderWidth, box);
app.setGrayFill(0.75f);
drawBottomFrame(app, borderWidth, box);
} else {
if (borderWidth != 0 && borderColor != null) {
if (borderStyle == PdfBorderDictionary.STYLE_DASHED) {
app.setLineDash(3, 0);
}
app.setColorStroke(borderColor);
app.setLineWidth(borderWidth);
app.rectangle(borderWidth / 2, borderWidth / 2, box.getWidth() - borderWidth,
box.getHeight() - borderWidth);
app.stroke();
//comb formfield flag is set and maxchar must be set (for textfield only!)
if ((options & COMB) != 0 && maxCharacterLength > 1) {
float step = box.getWidth() / maxCharacterLength;
float yb = borderWidth / 2;
float yt = box.getHeight() - borderWidth / 2;
for (int k = 1; k < maxCharacterLength; ++k) {
float x = step * k;
app.moveTo(x, yb);
app.lineTo(x, yt);
}
app.stroke();
}
}
}
app.restoreState();
return app;
}
protected static List<String> getAllHardBreaks(String text) {
List<String> arr = new ArrayList<>();
char[] cs = text.toCharArray();
int len = cs.length;
StringBuffer buf = new StringBuffer();
for (int k = 0; k < len; ++k) {
char c = cs[k];
if (c == '\r') {
if (k + 1 < len && cs[k + 1] == '\n') {
++k;
}
arr.add(buf.toString());
buf = new StringBuffer();
} else if (c == '\n') {
arr.add(buf.toString());
buf = new StringBuffer();
} else {
buf.append(c);
}
}
arr.add(buf.toString());
return arr;
}
protected static void trimRight(StringBuffer buf) {
int len = buf.length();
while (true) {
if (len == 0) {
return;
}
if (buf.charAt(--len) != ' ') {
return;
}
buf.setLength(len);
}
}
protected static List<String> breakLines(List<String> breaks, BaseFont font, float fontSize, float width) {
List<String> lines = new ArrayList<>();
StringBuffer buf = new StringBuffer();
for (String aBreak : breaks) {
buf.setLength(0);
float w = 0;
char[] cs = aBreak.toCharArray();
int len = cs.length;
// 0 inline first, 1 inline, 2 spaces
int state = 0;
int lastspace = -1;
char c = 0;
int refk = 0;
for (int k = 0; k < len; ++k) {
c = cs[k];
switch (state) {
case 0:
w += font.getWidthPoint(c, fontSize);
buf.append(c);
if (w > width) {
w = 0;
if (buf.length() > 1) {
--k;
buf.setLength(buf.length() - 1);
}
lines.add(buf.toString());
buf.setLength(0);
refk = k;
if (c == ' ') {
state = 2;
} else {
state = 1;
}
} else {
if (c != ' ') {
state = 1;
}
}
break;
case 1:
w += font.getWidthPoint(c, fontSize);
buf.append(c);
if (c == ' ') {
lastspace = k;
}
if (w > width) {
w = 0;
if (lastspace >= 0) {
k = lastspace;
buf.setLength(lastspace - refk);
trimRight(buf);
lines.add(buf.toString());
buf.setLength(0);
refk = k;
lastspace = -1;
state = 2;
} else {
if (buf.length() > 1) {
--k;
buf.setLength(buf.length() - 1);
}
lines.add(buf.toString());
buf.setLength(0);
refk = k;
if (c == ' ') {
state = 2;
}
}
}
break;
case 2:
if (c != ' ') {
w = 0;
--k;
state = 1;
}
break;
}
}
trimRight(buf);
lines.add(buf.toString());
}
return lines;
}
private static void drawTopFrame(PdfAppearance app, float borderWidth, Rectangle box) {
app.moveTo(borderWidth, borderWidth);
app.lineTo(borderWidth, box.getHeight() - borderWidth);
app.lineTo(box.getWidth() - borderWidth, box.getHeight() - borderWidth);
app.lineTo(box.getWidth() - 2 * borderWidth, box.getHeight() - 2 * borderWidth);
app.lineTo(2 * borderWidth, box.getHeight() - 2 * borderWidth);
app.lineTo(2 * borderWidth, 2 * borderWidth);
app.lineTo(borderWidth, borderWidth);
app.fill();
}
private static void drawBottomFrame(PdfAppearance app, float borderWidth, Rectangle box) {
app.moveTo(borderWidth, borderWidth);
app.lineTo(box.getWidth() - borderWidth, borderWidth);
app.lineTo(box.getWidth() - borderWidth, box.getHeight() - borderWidth);
app.lineTo(box.getWidth() - 2 * borderWidth, box.getHeight() - 2 * borderWidth);
app.lineTo(box.getWidth() - 2 * borderWidth, 2 * borderWidth);
app.lineTo(2 * borderWidth, 2 * borderWidth);
app.lineTo(borderWidth, borderWidth);
app.fill();
}
/**
* Moves the field keys from <CODE>from</CODE> to <CODE>to</CODE>. The moved keys are removed from
* <CODE>from</CODE>.
*
* @param from the source
* @param to the destination. It may be <CODE>null</CODE>
*/
public static void moveFields(PdfDictionary from, PdfDictionary to) {
for (Iterator i = from.getKeys().iterator(); i.hasNext(); ) {
PdfName key = (PdfName) i.next();
if (fieldKeys.containsKey(key)) {
if (to != null) {
to.put(key, from.get(key));
}
i.remove();
}
}
}
protected BaseFont getRealFont() throws IOException, DocumentException {
if (font == null) {
return BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
} else {
return font;
}
}
/**
* Gets the border width in points.
*
* @return the border width in points
*/
public float getBorderWidth() {
return this.borderWidth;
}
/**
* Sets the border width in points. To eliminate the border set the border color to <CODE>null</CODE>.
*
* @param borderWidth the border width in points
*/
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
/**
* Gets the border style.
*
* @return the border style
*/
public int getBorderStyle() {
return this.borderStyle;
}
/**
* Sets the border style. The styles are found in <CODE>PdfBorderDictionary</CODE> and can be
* <CODE>STYLE_SOLID</CODE>, <CODE>STYLE_DASHED</CODE>,
* <CODE>STYLE_BEVELED</CODE>, <CODE>STYLE_INSET</CODE> and
* <CODE>STYLE_UNDERLINE</CODE>.
*
* @param borderStyle the border style
*/
public void setBorderStyle(int borderStyle) {
this.borderStyle = borderStyle;
}
/**
* Gets the border color.
*
* @return the border color
*/
public Color getBorderColor() {
return this.borderColor;
}
/**
* Sets the border color. Set to <CODE>null</CODE> to remove the border.
*
* @param borderColor the border color
*/
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
/**
* Gets the background color.
*
* @return the background color
*/
public Color getBackgroundColor() {
return this.backgroundColor;
}
/**
* Sets the background color. Set to <CODE>null</CODE> for transparent background.
*
* @param backgroundColor the background color
*/
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
/**
* Gets the text color.
*
* @return the text color
*/
public Color getTextColor() {
return this.textColor;
}
/**
* Sets the text color. If <CODE>null</CODE> the color used will be black.
*
* @param textColor the text color
*/
public void setTextColor(Color textColor) {
this.textColor = textColor;
}
/**
* Gets the text font.
*
* @return the text font
*/
public BaseFont getFont() {
return this.font;
}
/**
* Sets the text font. If <CODE>null</CODE> then Helvetica will be used.
*
* @param font the text font
*/
public void setFont(BaseFont font) {
this.font = font;
}
/**
* Gets the font size.
*
* @return the font size
*/
public float getFontSize() {
return this.fontSize;
}
/**
* Sets the font size. If 0 then auto-sizing will be used but only for text fields.
*
* @param fontSize the font size
*/
public void setFontSize(float fontSize) {
this.fontSize = fontSize;
}
/**
* Gets the text horizontal alignment.
*
* @return the text horizontal alignment
*/
public int getAlignment() {
return this.alignment;
}
/**
* Sets the text horizontal alignment. It can be <CODE>Element.ALIGN_LEFT</CODE>,
* <CODE>Element.ALIGN_CENTER</CODE> and <CODE>Element.ALIGN_RIGHT</CODE>.
*
* @param alignment the text horizontal alignment
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
/**
* Gets the text.
*
* @return the text
*/
public String getText() {
return this.text;
}
/**
* Sets the text for text fields.
*
* @param text the text
*/
public void setText(String text) {
this.text = text;
}
/**
* Gets the field dimension and position.
*
* @return the field dimension and position
*/
public Rectangle getBox() {
return this.box;
}
/**
* Sets the field dimension and position.
*
* @param box the field dimension and position
*/
public void setBox(Rectangle box) {
if (box == null) {
this.box = null;
} else {
this.box = new Rectangle(box);
this.box.normalize();
}
}
/**
* Gets the field rotation.
*
* @return the field rotation
*/
public int getRotation() {
return this.rotation;
}
/**
* Sets the field rotation. This value should be the same as the page rotation where the field will be shown.
*
* @param rotation the field rotation
*/
public void setRotation(int rotation) {
if (rotation % 90 != 0) {
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90"));
}
rotation %= 360;
if (rotation < 0) {
rotation += 360;
}
this.rotation = rotation;
}
/**
* Convenience method to set the field rotation the same as the page rotation.
*
* @param page the page
*/
public void setRotationFromPage(Rectangle page) {
setRotation(page.getRotation());
}
/**
* Gets the field visibility flag.
*
* @return the field visibility flag
*/
public int getVisibility() {
return this.visibility;
}
/**
* Sets the field visibility flag. This flags can be one of
* <CODE>VISIBLE</CODE>, <CODE>HIDDEN</CODE>, <CODE>VISIBLE_BUT_DOES_NOT_PRINT</CODE>
* and <CODE>HIDDEN_BUT_PRINTABLE</CODE>.
*
* @param visibility field visibility flag
*/
public void setVisibility(int visibility) {
this.visibility = visibility;
}
/**
* Gets the field name.
*
* @return the field name
*/
public String getFieldName() {
return this.fieldName;
}
/**
* Sets the field name.
*
* @param fieldName the field name. If <CODE>null</CODE> only the widget keys will be included in the field allowing
* it to be used as a kid field.
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
/**
* Gets the alternate field name. (PDF attribute TU)
*
* @return the alternate field name
*/
public String getAlternateFieldName() {
return this.alternateFieldName;
}
/**
* Sets the alternateFieldName field name.
*
* @param alternateFieldName the alternate field name.
*/
public void setAlternateFieldName(String alternateFieldName) {
this.alternateFieldName = alternateFieldName;
}
/**
* Gets the mapping name. (PDF attribute TM)
*
* @return the mapping field name
*/
public String getMappingName() {
return this.mappingName;
}
/**
* Sets the mapping name. (PDF TM)
*
* @param mappingName the mapping name.
*/
public void setMappingName(String mappingName) {
this.mappingName = mappingName;
}
/**
* Gets the option flags.
*
* @return the option flags
*/
public int getOptions() {
return this.options;
}
/**
* Sets the option flags. The option flags can be a combination by oring of
* <CODE>READ_ONLY</CODE>, <CODE>REQUIRED</CODE>,
* <CODE>MULTILINE</CODE>, <CODE>DO_NOT_SCROLL</CODE>,
* <CODE>PASSWORD</CODE>, <CODE>FILE_SELECTION</CODE>,
* <CODE>DO_NOT_SPELL_CHECK</CODE> and <CODE>EDIT</CODE>.
*
* @param options the option flags
*/
public void setOptions(int options) {
this.options = options;
}
/**
* Gets the maximum length of the field's text, in characters.
*
* @return the maximum length of the field's text, in characters.
*/
public int getMaxCharacterLength() {
return this.maxCharacterLength;
}
/**
* Sets the maximum length of the field's text, in characters. It is only meaningful for text fields.
*
* @param maxCharacterLength the maximum length of the field's text, in characters
*/
public void setMaxCharacterLength(int maxCharacterLength) {
this.maxCharacterLength = maxCharacterLength;
}
/**
* Getter for property writer.
*
* @return Value of property writer.
*/
public PdfWriter getWriter() {
return writer;
}
/**
* Setter for property writer.
*
* @param writer New value of property writer.
*/
public void setWriter(PdfWriter writer) {
this.writer = writer;
}
}
|
61357_5 | /*
* This file is part of LibrePlan
*
* Copyright (C) 2013 St. Antoniusziekenhuis
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.importers;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.common.daos.IConnectorDAO;
import org.libreplan.business.common.daos.IJobSchedulerConfigurationDAO;
import org.libreplan.business.common.entities.Connector;
import org.libreplan.business.common.entities.JobClassNameEnum;
import org.libreplan.business.common.entities.JobSchedulerConfiguration;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Implementation of scheduler manager
*
* @author Miciele Ghiorghis <[email protected]>
*/
@Service
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class SchedulerManager implements ISchedulerManager {
private static final Log LOG = LogFactory.getLog(SchedulerManager.class);
@Autowired
private Scheduler scheduler;
@Autowired
private IJobSchedulerConfigurationDAO jobSchedulerConfigurationDAO;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private IConnectorDAO connectorDAO;
/**
* Suffix for trigger -group and -name
*/
private static final String TRIGGER_SUFFIX = "-TRIGGER";
public Scheduler getScheduler() {
return scheduler;
}
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public void scheduleJobs() {
List<JobSchedulerConfiguration> jobSchedulerConfigurations = jobSchedulerConfigurationDAO.getAll();
for (JobSchedulerConfiguration conf : jobSchedulerConfigurations) {
try {
scheduleOrUnscheduleJob(conf);
} catch (SchedulerException e) {
LOG.error("Unable to schedule", e);
}
}
}
@Override
@Transactional(readOnly = true)
public void scheduleOrUnscheduleJob(JobSchedulerConfiguration jobSchedulerConfiguration) throws SchedulerException {
if ( hasConnector(jobSchedulerConfiguration.getConnectorName()) ) {
if ( isConnectorActivated(jobSchedulerConfiguration.getConnectorName()) ) {
if ( jobSchedulerConfiguration.isSchedule() ) {
scheduleNewJob(jobSchedulerConfiguration);
return;
}
}
deleteJob(jobSchedulerConfiguration);
return;
}
if ( !jobSchedulerConfiguration.isSchedule() ) {
deleteJob(jobSchedulerConfiguration);
return;
}
scheduleNewJob(jobSchedulerConfiguration);
}
/**
* Check if {@link JobSchedulerConfiguration} has a connector
*
* @param connectorName
* the connector to check for
* @return true if connector is not null or empty
*/
private boolean hasConnector(String connectorName) {
return !StringUtils.isBlank(connectorName);
}
/**
* Check if the specified <code>{@link Connector}</code> is activated
*
* @param connectorName
* the connector to check for activated
* @return true if activated
*/
private boolean isConnectorActivated(String connectorName) {
Connector connector = connectorDAO.findUniqueByName(connectorName);
return connector != null && connector.isActivated();
}
@Override
public void deleteJob(JobSchedulerConfiguration jobSchedulerConfiguration) throws SchedulerException {
String triggerName = jobSchedulerConfiguration.getJobName() + TRIGGER_SUFFIX;
String triggerGroup = jobSchedulerConfiguration.getJobGroup() + TRIGGER_SUFFIX;
CronTrigger trigger = getTriggerBean(triggerName, triggerGroup);
if ( trigger == null ) {
LOG.warn("Trigger not found");
return;
}
if ( isJobCurrentlyExecuting(triggerName, triggerGroup) ) {
LOG.warn("Job is currently executing...");
return;
}
// deleteJob doesn't work using unscheduleJob
this.scheduler.unscheduleJob(trigger.getKey());
}
/**
* Checks if job is currently running for the specified
* <code>triggerName</code> and <code>triggerGroup</code>
*
* @param triggerName
* the triggerName
* @param triggerGroup
* the triggerGroup
* @return true if job is currently running, otherwise false
*/
@SuppressWarnings("unchecked")
private boolean isJobCurrentlyExecuting(String triggerName, String triggerGroup) {
try {
List<JobExecutionContext> currentExecutingJobs = this.scheduler.getCurrentlyExecutingJobs();
for (JobExecutionContext jobExecutionContext : currentExecutingJobs) {
String name = jobExecutionContext.getTrigger().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
if ( triggerName.equals(name) && triggerGroup.equals(group) ) {
return true;
}
}
} catch (SchedulerException e) {
LOG.error("Unable to get currently executing jobs", e);
}
return false;
}
/**
* Creates {@link CronTriggerFactoryBean} and {@link JobDetailFactoryBean} based on the
* specified <code>{@link JobSchedulerConfiguration}</code>. First delete
* job if exist and then schedule it
*
* @param jobSchedulerConfiguration
* where to reade jobs to be scheduled
* @throws SchedulerException
* if unable to delete and/or schedule job
*/
private void scheduleNewJob(JobSchedulerConfiguration jobSchedulerConfiguration) throws SchedulerException {
CronTriggerFactoryBean cronTriggerBean = createCronTriggerBean(jobSchedulerConfiguration);
if ( cronTriggerBean == null ) {
return;
}
JobDetailFactoryBean jobDetailBean = createJobDetailBean(jobSchedulerConfiguration);
if ( jobDetailBean == null ) {
return;
}
deleteJob(jobSchedulerConfiguration);
this.scheduler.scheduleJob(jobDetailBean.getObject(), cronTriggerBean.getObject());
}
/**
* Creates {@link CronTriggerFactoryBean} from the specified
* <code>{@link JobSchedulerConfiguration}</code>
*
* @param jobSchedulerConfiguration
* configuration to create <code>CronTriggerFactoryBean</>
* @return the created <code>CronTriggerFactoryBean</code> or null if unable to
* create it
*/
private CronTriggerFactoryBean createCronTriggerBean(JobSchedulerConfiguration jobSchedulerConfiguration) {
final CronTriggerFactoryBean cronTriggerBean = new CronTriggerFactoryBean();
cronTriggerBean.setName(jobSchedulerConfiguration.getJobName() + TRIGGER_SUFFIX);
cronTriggerBean.setGroup(jobSchedulerConfiguration.getJobGroup() + TRIGGER_SUFFIX);
try {
cronTriggerBean.setCronExpression(
String.valueOf(new CronExpression(jobSchedulerConfiguration.getCronExpression())));
cronTriggerBean.afterPropertiesSet();
return cronTriggerBean;
} catch (ParseException e) {
LOG.error("Unable to parse cron expression", e);
}
return null;
}
/**
* Creates {@link JobDetailFactoryBean} from the specified
* <code>{@link JobSchedulerConfiguration}</code>
*
* @param jobSchedulerConfiguration
* configuration to create <code>JobDetailFactoryBean</>
* @return the created <code>JobDetailFactoryBean</code> or null if unable to it
*/
private JobDetailFactoryBean createJobDetailBean(JobSchedulerConfiguration jobSchedulerConfiguration) {
final JobDetailFactoryBean jobDetailBean = new JobDetailFactoryBean();
Class<?> jobClass = getJobClass(jobSchedulerConfiguration.getJobClassName());
if ( jobClass == null ) {
return null;
}
jobDetailBean.setName(jobSchedulerConfiguration.getJobName());
jobDetailBean.setGroup(jobSchedulerConfiguration.getJobGroup());
jobDetailBean.setJobClass(jobClass);
Map<String, Object> jobDataAsMap = new HashMap<>();
jobDataAsMap.put("applicationContext", applicationContext);
jobDetailBean.setJobDataAsMap(jobDataAsMap);
jobDetailBean.afterPropertiesSet();
return jobDetailBean;
}
/**
* returns jobClass based on <code>jobClassName</code> parameter
*
* @param jobClassName
* job className
*/
private Class<?> getJobClass(JobClassNameEnum jobClassName) {
try {
return Class.forName(jobClassName.getPackageName() + "." + jobClassName.getName());
} catch (ClassNotFoundException e) {
LOG.error("Unable to get class object '" + jobClassName + "'", e);
}
return null;
}
@Override
public String getNextFireTime(JobSchedulerConfiguration jobSchedulerConfiguration) {
try {
CronTrigger trigger = (CronTrigger)
this.scheduler.getTrigger(TriggerKey.triggerKey(
jobSchedulerConfiguration.getJobName() + TRIGGER_SUFFIX,
jobSchedulerConfiguration.getJobGroup() + TRIGGER_SUFFIX));
if ( trigger != null ) {
return trigger.getNextFireTime().toString();
}
} catch (SchedulerException e) {
LOG.error("unable to get the trigger", e);
}
return "";
}
/**
* gets the {@link CronTriggerFactoryBean} for the specified
* <code>triggerName</code> and <code>tirggerGroup</code>
*
* @param triggerName
* the trigger name
* @param triggerGroup
* the trigger group
* @return CronTriggerFactoryBean if found, otherwise null
*/
private CronTrigger getTriggerBean(String triggerName, String triggerGroup) {
try {
return (CronTrigger) this.scheduler.getTrigger(TriggerKey.triggerKey(triggerName, triggerGroup));
} catch (SchedulerException e) {
LOG.error("Unable to get job trigger", e);
}
return null;
}
}
| LibrePlan/libreplan | libreplan-webapp/src/main/java/org/libreplan/importers/SchedulerManager.java | 3,134 | // deleteJob doesn't work using unscheduleJob | line_comment | nl | /*
* This file is part of LibrePlan
*
* Copyright (C) 2013 St. Antoniusziekenhuis
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.importers;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.common.daos.IConnectorDAO;
import org.libreplan.business.common.daos.IJobSchedulerConfigurationDAO;
import org.libreplan.business.common.entities.Connector;
import org.libreplan.business.common.entities.JobClassNameEnum;
import org.libreplan.business.common.entities.JobSchedulerConfiguration;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Implementation of scheduler manager
*
* @author Miciele Ghiorghis <[email protected]>
*/
@Service
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class SchedulerManager implements ISchedulerManager {
private static final Log LOG = LogFactory.getLog(SchedulerManager.class);
@Autowired
private Scheduler scheduler;
@Autowired
private IJobSchedulerConfigurationDAO jobSchedulerConfigurationDAO;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private IConnectorDAO connectorDAO;
/**
* Suffix for trigger -group and -name
*/
private static final String TRIGGER_SUFFIX = "-TRIGGER";
public Scheduler getScheduler() {
return scheduler;
}
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public void scheduleJobs() {
List<JobSchedulerConfiguration> jobSchedulerConfigurations = jobSchedulerConfigurationDAO.getAll();
for (JobSchedulerConfiguration conf : jobSchedulerConfigurations) {
try {
scheduleOrUnscheduleJob(conf);
} catch (SchedulerException e) {
LOG.error("Unable to schedule", e);
}
}
}
@Override
@Transactional(readOnly = true)
public void scheduleOrUnscheduleJob(JobSchedulerConfiguration jobSchedulerConfiguration) throws SchedulerException {
if ( hasConnector(jobSchedulerConfiguration.getConnectorName()) ) {
if ( isConnectorActivated(jobSchedulerConfiguration.getConnectorName()) ) {
if ( jobSchedulerConfiguration.isSchedule() ) {
scheduleNewJob(jobSchedulerConfiguration);
return;
}
}
deleteJob(jobSchedulerConfiguration);
return;
}
if ( !jobSchedulerConfiguration.isSchedule() ) {
deleteJob(jobSchedulerConfiguration);
return;
}
scheduleNewJob(jobSchedulerConfiguration);
}
/**
* Check if {@link JobSchedulerConfiguration} has a connector
*
* @param connectorName
* the connector to check for
* @return true if connector is not null or empty
*/
private boolean hasConnector(String connectorName) {
return !StringUtils.isBlank(connectorName);
}
/**
* Check if the specified <code>{@link Connector}</code> is activated
*
* @param connectorName
* the connector to check for activated
* @return true if activated
*/
private boolean isConnectorActivated(String connectorName) {
Connector connector = connectorDAO.findUniqueByName(connectorName);
return connector != null && connector.isActivated();
}
@Override
public void deleteJob(JobSchedulerConfiguration jobSchedulerConfiguration) throws SchedulerException {
String triggerName = jobSchedulerConfiguration.getJobName() + TRIGGER_SUFFIX;
String triggerGroup = jobSchedulerConfiguration.getJobGroup() + TRIGGER_SUFFIX;
CronTrigger trigger = getTriggerBean(triggerName, triggerGroup);
if ( trigger == null ) {
LOG.warn("Trigger not found");
return;
}
if ( isJobCurrentlyExecuting(triggerName, triggerGroup) ) {
LOG.warn("Job is currently executing...");
return;
}
// deleteJob doesn't<SUF>
this.scheduler.unscheduleJob(trigger.getKey());
}
/**
* Checks if job is currently running for the specified
* <code>triggerName</code> and <code>triggerGroup</code>
*
* @param triggerName
* the triggerName
* @param triggerGroup
* the triggerGroup
* @return true if job is currently running, otherwise false
*/
@SuppressWarnings("unchecked")
private boolean isJobCurrentlyExecuting(String triggerName, String triggerGroup) {
try {
List<JobExecutionContext> currentExecutingJobs = this.scheduler.getCurrentlyExecutingJobs();
for (JobExecutionContext jobExecutionContext : currentExecutingJobs) {
String name = jobExecutionContext.getTrigger().getKey().getName();
String group = jobExecutionContext.getTrigger().getKey().getGroup();
if ( triggerName.equals(name) && triggerGroup.equals(group) ) {
return true;
}
}
} catch (SchedulerException e) {
LOG.error("Unable to get currently executing jobs", e);
}
return false;
}
/**
* Creates {@link CronTriggerFactoryBean} and {@link JobDetailFactoryBean} based on the
* specified <code>{@link JobSchedulerConfiguration}</code>. First delete
* job if exist and then schedule it
*
* @param jobSchedulerConfiguration
* where to reade jobs to be scheduled
* @throws SchedulerException
* if unable to delete and/or schedule job
*/
private void scheduleNewJob(JobSchedulerConfiguration jobSchedulerConfiguration) throws SchedulerException {
CronTriggerFactoryBean cronTriggerBean = createCronTriggerBean(jobSchedulerConfiguration);
if ( cronTriggerBean == null ) {
return;
}
JobDetailFactoryBean jobDetailBean = createJobDetailBean(jobSchedulerConfiguration);
if ( jobDetailBean == null ) {
return;
}
deleteJob(jobSchedulerConfiguration);
this.scheduler.scheduleJob(jobDetailBean.getObject(), cronTriggerBean.getObject());
}
/**
* Creates {@link CronTriggerFactoryBean} from the specified
* <code>{@link JobSchedulerConfiguration}</code>
*
* @param jobSchedulerConfiguration
* configuration to create <code>CronTriggerFactoryBean</>
* @return the created <code>CronTriggerFactoryBean</code> or null if unable to
* create it
*/
private CronTriggerFactoryBean createCronTriggerBean(JobSchedulerConfiguration jobSchedulerConfiguration) {
final CronTriggerFactoryBean cronTriggerBean = new CronTriggerFactoryBean();
cronTriggerBean.setName(jobSchedulerConfiguration.getJobName() + TRIGGER_SUFFIX);
cronTriggerBean.setGroup(jobSchedulerConfiguration.getJobGroup() + TRIGGER_SUFFIX);
try {
cronTriggerBean.setCronExpression(
String.valueOf(new CronExpression(jobSchedulerConfiguration.getCronExpression())));
cronTriggerBean.afterPropertiesSet();
return cronTriggerBean;
} catch (ParseException e) {
LOG.error("Unable to parse cron expression", e);
}
return null;
}
/**
* Creates {@link JobDetailFactoryBean} from the specified
* <code>{@link JobSchedulerConfiguration}</code>
*
* @param jobSchedulerConfiguration
* configuration to create <code>JobDetailFactoryBean</>
* @return the created <code>JobDetailFactoryBean</code> or null if unable to it
*/
private JobDetailFactoryBean createJobDetailBean(JobSchedulerConfiguration jobSchedulerConfiguration) {
final JobDetailFactoryBean jobDetailBean = new JobDetailFactoryBean();
Class<?> jobClass = getJobClass(jobSchedulerConfiguration.getJobClassName());
if ( jobClass == null ) {
return null;
}
jobDetailBean.setName(jobSchedulerConfiguration.getJobName());
jobDetailBean.setGroup(jobSchedulerConfiguration.getJobGroup());
jobDetailBean.setJobClass(jobClass);
Map<String, Object> jobDataAsMap = new HashMap<>();
jobDataAsMap.put("applicationContext", applicationContext);
jobDetailBean.setJobDataAsMap(jobDataAsMap);
jobDetailBean.afterPropertiesSet();
return jobDetailBean;
}
/**
* returns jobClass based on <code>jobClassName</code> parameter
*
* @param jobClassName
* job className
*/
private Class<?> getJobClass(JobClassNameEnum jobClassName) {
try {
return Class.forName(jobClassName.getPackageName() + "." + jobClassName.getName());
} catch (ClassNotFoundException e) {
LOG.error("Unable to get class object '" + jobClassName + "'", e);
}
return null;
}
@Override
public String getNextFireTime(JobSchedulerConfiguration jobSchedulerConfiguration) {
try {
CronTrigger trigger = (CronTrigger)
this.scheduler.getTrigger(TriggerKey.triggerKey(
jobSchedulerConfiguration.getJobName() + TRIGGER_SUFFIX,
jobSchedulerConfiguration.getJobGroup() + TRIGGER_SUFFIX));
if ( trigger != null ) {
return trigger.getNextFireTime().toString();
}
} catch (SchedulerException e) {
LOG.error("unable to get the trigger", e);
}
return "";
}
/**
* gets the {@link CronTriggerFactoryBean} for the specified
* <code>triggerName</code> and <code>tirggerGroup</code>
*
* @param triggerName
* the trigger name
* @param triggerGroup
* the trigger group
* @return CronTriggerFactoryBean if found, otherwise null
*/
private CronTrigger getTriggerBean(String triggerName, String triggerGroup) {
try {
return (CronTrigger) this.scheduler.getTrigger(TriggerKey.triggerKey(triggerName, triggerGroup));
} catch (SchedulerException e) {
LOG.error("Unable to get job trigger", e);
}
return null;
}
}
|
11819_14 | package tillerino.tillerinobot.lang;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.BeatmapMeta;
import tillerino.tillerinobot.IRCBot.IRCBotUser;
import tillerino.tillerinobot.RecommendationsManager.Recommendation;
import java.util.List;
import java.util.Random;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands implements Language {
static final Random rnd = new Random();
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
user.message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
user.message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
user.message(apiUser.getUserName() + "...");
user.message("...ben jij dat? Dat is lang geleden!");
user.message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?");
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
user.message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
/**
* The user's IRC nick name could not be resolved to an osu user id. The
* message should suggest to contact @Tillerinobot or /u/Tillerino.
*
* @param exceptionMarker
* a marker to reference the created log entry. six or eight
* characters.
* @param name
* the irc nick which could not be resolved
* @return
*/
public String unresolvableName(String exceptionMarker, String name) {
return "Je naam verwart me. Ben je geband? Zoniet, neem [https://github.com/Tillerino/Tillerinobot/wiki/Contact contact op met Tillerino] (reference "
+ exceptionMarker + ")";
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public void hug(final IRCBotUser user, OsuApiUser apiUser) {
user.message("Kom eens hier jij!");
user.action("knuffelt " + apiUser.getUserName());
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public void optionalCommentOnNP(IRCBotUser user,
OsuApiUser apiUser, BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser,
BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnRecommendation(IRCBotUser user,
OsuApiUser apiUser, Recommendation meta) {
// regular Tillerino doesn't comment on this
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) {
user.message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler doSomething = new StringShuffler(rnd);
@Override
public String apiTimeoutException() {
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + doSomething.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.",
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
@Override
public String getPatience() {
return "Momentje geduld asjeblieft...";
}
}
| Liby99/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java | 3,088 | //github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", | line_comment | nl | package tillerino.tillerinobot.lang;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.BeatmapMeta;
import tillerino.tillerinobot.IRCBot.IRCBotUser;
import tillerino.tillerinobot.RecommendationsManager.Recommendation;
import java.util.List;
import java.util.Random;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands implements Language {
static final Random rnd = new Random();
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
user.message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
user.message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
user.message(apiUser.getUserName() + "...");
user.message("...ben jij dat? Dat is lang geleden!");
user.message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?");
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
user.message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
/**
* The user's IRC nick name could not be resolved to an osu user id. The
* message should suggest to contact @Tillerinobot or /u/Tillerino.
*
* @param exceptionMarker
* a marker to reference the created log entry. six or eight
* characters.
* @param name
* the irc nick which could not be resolved
* @return
*/
public String unresolvableName(String exceptionMarker, String name) {
return "Je naam verwart me. Ben je geband? Zoniet, neem [https://github.com/Tillerino/Tillerinobot/wiki/Contact contact op met Tillerino] (reference "
+ exceptionMarker + ")";
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public void hug(final IRCBotUser user, OsuApiUser apiUser) {
user.message("Kom eens hier jij!");
user.action("knuffelt " + apiUser.getUserName());
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public void optionalCommentOnNP(IRCBotUser user,
OsuApiUser apiUser, BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser,
BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnRecommendation(IRCBotUser user,
OsuApiUser apiUser, Recommendation meta) {
// regular Tillerino doesn't comment on this
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) {
user.message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler doSomething = new StringShuffler(rnd);
@Override
public String apiTimeoutException() {
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + doSomething.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn<SUF>
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
@Override
public String getPatience() {
return "Momentje geduld asjeblieft...";
}
}
|
70767_0 | package Assign1_InleidingJava2018.H04;
import java.awt.*;
import java.applet.*;
public class H04_2 extends Applet {
/** opdracht:
* Teken een huis met daarin tenminste één raam en een deur
*/
public void init() {
}
public void paint(Graphics g) {
setBackground(Color.black);
g.setColor(Color.white);
// base
g.drawRect(125, 200, 250, 250);
// roof
g.drawLine(125,200,250,50);
g.drawLine(375,200,250,50);
// window
g.drawRect(140, 330, 100, 50);
// door
g.fillRect(260, 300, 80, 150);
}
}
| Lights-Uni-Projects/ROC-Assignments | Java/H04/H04_2.java | 238 | /** opdracht:
* Teken een huis met daarin tenminste één raam en een deur
*/ | block_comment | nl | package Assign1_InleidingJava2018.H04;
import java.awt.*;
import java.applet.*;
public class H04_2 extends Applet {
/** opdracht:
<SUF>*/
public void init() {
}
public void paint(Graphics g) {
setBackground(Color.black);
g.setColor(Color.white);
// base
g.drawRect(125, 200, 250, 250);
// roof
g.drawLine(125,200,250,50);
g.drawLine(375,200,250,50);
// window
g.drawRect(140, 330, 100, 50);
// door
g.fillRect(260, 300, 80, 150);
}
}
|
97816_7 | package be.vdab.groenetenen.aop;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
/* "Auditing" als voorbeeld van "Before/After Returning advice". Je houdt met auditing bij welke gebruiker op welk moment welke use case uitvoert. */
@Aspect // Je definieert een class als aspect (= de combinatie van advice en pointcut) met @Aspect.
@Component // Een aspect moet zelf ook een Spring bean zijn, vandaar @Component.
@Order(2) // Als Spring een join point uitvoert waarop meerdere advices worden opgeroepen, bepaal je met @Order in welke volgorde Spring de bijbehorende advices uitvoert.
class Auditing {
private static final Logger LOGGER = LoggerFactory.getLogger(Auditing.class);
/* Je definieert een method als before advice met @Before met een pointcut expressie.
* De expressie hier duidt methods uit be.vdab.groenetenen.services aan.
* Als je zo'n method oproept, voert Spring eerst de method schrijfAudit (zie hieronder) uit, daarna de opgeroepen method zelf.
*/
// @Before("execution(* be.vdab.groenetenen.services.*.*(..))")
/* Je definieert een method als after returning advice met @AfterReturning.
* Je geeft een parameter pointcut mee met een pointcut expressie. De expressie hier duidt methods uit be.vdab.groenetenen.services aan.
* Als je zo'n method oproept, voert Spring na die method de method schrijfAudit (zie hieronder) uit als de opgeroepen method geen exception werpt.
* Je geeft een parameter returning mee als je de returnwaarde van het join point wil weten.
* Je tikt daarbij de naam van een Object parameter in de method schrijfAudit. Spring vult die parameter met de returnwaarde van het join point.
*/
@AfterReturning(pointcut = "be.vdab.groenetenen.aop.PointcutExpressions.services()", returning = "returnValue")
/* Je geeft de method, die het advice voorstelt, een parameter van het type JoinPoint.
* Deze parameter verwijst naar het join point waarvóór Spring het advice uitvoert en geeft interessante informatie over dit join point.
* Je geeft de method een extra Object parameter mee, als het een AfterReturning method is. Spring vult die parameter in met de returnwaarde v/h join point.
*/
void schrijfAudit(JoinPoint joinPoint, Object returnValue) {
/*Je bouwt de auditing informatie op in een StringBuilder object. Je voegt hier het tijdstip toe waarop een service method werd uitgevoerd.*/
StringBuilder builder = new StringBuilder("Tijdstip\t").append(LocalDateTime.now());
/*Je haalt met SecurityContextHolder.getContext().getAuthentication() een Authentication object op. Dit bevat informatie over de ingelogde gebruiker.*/
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
builder.append("\nGebruiker\t").append(authentication.getName());
}
/*De method getSignature van een JoinPoint geeft je de mehtod declaratie van het join point als een Signature object.
*De method toLongString geeft je de package-, interface- én methodnaam.*/
builder.append("\nMethod\t\t").append(joinPoint.getSignature().toLongString());
/*getArgs geeft je een Object array met de parameterwaarden van het join point.*/
Arrays.stream(joinPoint.getArgs()).forEach(object -> builder.append("\nParameter\t").append(object));
/*Extra code in het geval van een AfterReturning method ipv Before*/
if (returnValue != null) { // Als het returntype van het join point void is, bevat returnValue null.
builder.append("\nReturn\t\t");
if (returnValue instanceof Collection) { // Als de returnwaarde een Collection (List, Set, Map) is,
// toon je enkel het aantal elementen in de verzameling, om de omvang van de auditing output te beperken.
builder.append(((Collection<?>) returnValue).size()).append(" objects");
} else {
builder.append(returnValue.toString()); // Anders toon je de returnwaarde.
}
}/*Einde extra AfterReturning code*/
LOGGER.info(builder.toString());
}
}
| LiselotteDes/SPRINGADVgroenetenen | src/main/java/be/vdab/groenetenen/aop/Auditing.java | 1,335 | /*Je bouwt de auditing informatie op in een StringBuilder object. Je voegt hier het tijdstip toe waarop een service method werd uitgevoerd.*/ | block_comment | nl | package be.vdab.groenetenen.aop;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
/* "Auditing" als voorbeeld van "Before/After Returning advice". Je houdt met auditing bij welke gebruiker op welk moment welke use case uitvoert. */
@Aspect // Je definieert een class als aspect (= de combinatie van advice en pointcut) met @Aspect.
@Component // Een aspect moet zelf ook een Spring bean zijn, vandaar @Component.
@Order(2) // Als Spring een join point uitvoert waarop meerdere advices worden opgeroepen, bepaal je met @Order in welke volgorde Spring de bijbehorende advices uitvoert.
class Auditing {
private static final Logger LOGGER = LoggerFactory.getLogger(Auditing.class);
/* Je definieert een method als before advice met @Before met een pointcut expressie.
* De expressie hier duidt methods uit be.vdab.groenetenen.services aan.
* Als je zo'n method oproept, voert Spring eerst de method schrijfAudit (zie hieronder) uit, daarna de opgeroepen method zelf.
*/
// @Before("execution(* be.vdab.groenetenen.services.*.*(..))")
/* Je definieert een method als after returning advice met @AfterReturning.
* Je geeft een parameter pointcut mee met een pointcut expressie. De expressie hier duidt methods uit be.vdab.groenetenen.services aan.
* Als je zo'n method oproept, voert Spring na die method de method schrijfAudit (zie hieronder) uit als de opgeroepen method geen exception werpt.
* Je geeft een parameter returning mee als je de returnwaarde van het join point wil weten.
* Je tikt daarbij de naam van een Object parameter in de method schrijfAudit. Spring vult die parameter met de returnwaarde van het join point.
*/
@AfterReturning(pointcut = "be.vdab.groenetenen.aop.PointcutExpressions.services()", returning = "returnValue")
/* Je geeft de method, die het advice voorstelt, een parameter van het type JoinPoint.
* Deze parameter verwijst naar het join point waarvóór Spring het advice uitvoert en geeft interessante informatie over dit join point.
* Je geeft de method een extra Object parameter mee, als het een AfterReturning method is. Spring vult die parameter in met de returnwaarde v/h join point.
*/
void schrijfAudit(JoinPoint joinPoint, Object returnValue) {
/*Je bouwt de<SUF>*/
StringBuilder builder = new StringBuilder("Tijdstip\t").append(LocalDateTime.now());
/*Je haalt met SecurityContextHolder.getContext().getAuthentication() een Authentication object op. Dit bevat informatie over de ingelogde gebruiker.*/
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
builder.append("\nGebruiker\t").append(authentication.getName());
}
/*De method getSignature van een JoinPoint geeft je de mehtod declaratie van het join point als een Signature object.
*De method toLongString geeft je de package-, interface- én methodnaam.*/
builder.append("\nMethod\t\t").append(joinPoint.getSignature().toLongString());
/*getArgs geeft je een Object array met de parameterwaarden van het join point.*/
Arrays.stream(joinPoint.getArgs()).forEach(object -> builder.append("\nParameter\t").append(object));
/*Extra code in het geval van een AfterReturning method ipv Before*/
if (returnValue != null) { // Als het returntype van het join point void is, bevat returnValue null.
builder.append("\nReturn\t\t");
if (returnValue instanceof Collection) { // Als de returnwaarde een Collection (List, Set, Map) is,
// toon je enkel het aantal elementen in de verzameling, om de omvang van de auditing output te beperken.
builder.append(((Collection<?>) returnValue).size()).append(" objects");
} else {
builder.append(returnValue.toString()); // Anders toon je de returnwaarde.
}
}/*Einde extra AfterReturning code*/
LOGGER.info(builder.toString());
}
}
|
72691_5 | package ngat.sms.simulation;
import java.util.*;
import java.text.*;
import javax.security.auth.login.FailedLoginException;
import ngat.astrometry.*;
import ngat.phase2.XProposal;
import ngat.sms.Disruptor;
import ngat.sms.EnvironmentPredictionModel;
import ngat.sms.EnvironmentSnapshot;
import ngat.sms.ExecutionResource;
import ngat.sms.ExecutionResourceBundle;
import ngat.sms.ExecutionResourceUsageEstimationModel;
import ngat.sms.GroupItem;
import ngat.sms.ScheduleDespatcher;
import ngat.sms.ScheduleItem;
import ngat.sms.WeatherPredictionModel;
import ngat.sms.WeatherSnapshot;
import ngat.util.*;
import ngat.util.logging.*;
/**
* Performs a simulation over one or more nights using a cached ODB for a
* specified site.
*/
public class ScheduleSimulator {
/** Standard date formatter. */
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/** Standard UTC timezone. */
public static SimpleTimeZone UTC = new SimpleTimeZone(0, "UTC");
/** Horizon level (for sunset/sunrise). */
public static final double HORIZON = Math.toRadians(-1.0);
static {
sdf.setTimeZone(UTC);
Calendar.getInstance().setTimeZone(UTC);
}
/** Site location. */
private ISite site;
/** Logger. */
private LogGenerator logger;
/** Schedule dispatcher. */
ScheduleDespatcher despatcher;
/** Execution timing. */
private ExecutionResourceUsageEstimationModel execTimingModel;
/** Environment prediction. */
private EnvironmentPredictionModel envPredictor;
/** Weather prediction. */
private WeatherPredictionModel weatherPredictor;
/** Generate disruptor events. */
private DisruptionGenerator dgen;
/** Generate volatility events. */
private VolatilityGenerator volgen;
/** Works out the actual exec-time of groups. */
private StochasticExecutionTimingModel stm;
/** Site-centred astro calculator. */
private AstrometrySiteCalculator astro;
/** Receives time signal callbacks. */
private DefaultTimeSignalReceiver tsr;
/**
* Create a ScheduleSimulator.
*
* @param site
* The location where the observatory is sited.
* @param despatcher
* A scheduler.
* @param execModel
* Execution resource model.
* @param envPredictor
* Sky-conditions prediction.
* @param weatherPredictor
* Weather prediction.
*/
public ScheduleSimulator(ISite site, ScheduleDespatcher despatcher,
ExecutionResourceUsageEstimationModel execModel, EnvironmentPredictionModel envPredictor,
WeatherPredictionModel weatherPredictor, DisruptionGenerator dgen, VolatilityGenerator volgen,
StochasticExecutionTimingModel stm) {
this.site = site;
this.despatcher = despatcher;
this.execTimingModel = execModel;
this.envPredictor = envPredictor;
this.weatherPredictor = weatherPredictor;
this.dgen = dgen;
this.volgen = volgen;
this.stm = stm;
astro = new BasicAstrometrySiteCalculator(site);
Logger alogger = LogManager.getLogger("SIM");
logger = new LogGenerator(alogger);
logger.system("SMS").subSystem("Simulator").srcCompClass("SchedSim(" + site.getSiteName() + ")").srcCompId(
this.getClass().getSimpleName());
}
/**
* Start a simulation run from start to end times.
*
* @param tsg
* The TimeSignalGenerator to synchronize with.
* @param start
* simulation start time.
* @param end
* simulation end time.
* @param sel
* A SimulationEventListener to receive progress events.
*/
public void runSimulation(TimeSignalGenerator tsg, long start, long end, SimulationEventListener sel)
throws Exception {
tsr = new DefaultTimeSignalReceiver(tsg);
int ig = 0;
SolarCalculator sunTrack = new SolarCalculator();
long time = start;
long timeStep = 0L;
ScheduleItem selected = null;
boolean execFail = false;
String execFailReason = null;
// run over sim period
while (time < end) {
selected = null;
EnvironmentSnapshot env = envPredictor.predictEnvironment(time);
// If its daytime we should jump to next sunset...
Coordinates sun = sunTrack.getCoordinates(time);
if (astro.getAltitude(sun, time) > HORIZON) {
// Calculate next sunset time after current time.
// Use -1 degs to make sure the bugger has really set
// as we haven't considered site elevation or refraction.
long timeTillSunset = astro.getTimeUntilNextSet(sun, HORIZON, time);
long sunset = time + timeTillSunset;
timeStep = timeTillSunset;
// Wait for sunset...
logger.create().extractCallInfo().info().level(3).msg(
String.format("Awaiting SUNSET at %s in %4d m at %tF %tT ", site.getSiteName(),
(timeStep / 60000), sunset, sunset)).send();
} else {
// check the weather and other disruptors
Disruptor d = dgen.hasDisruptor(time);
if (d != null) {
// WeatherSnapshot weather =
// weatherPredictor.predictWeather(time);
// if (!weather.isGood()) {
long timeWhenDisruptionEnds = d.getPeriod().getEnd() + 30000L; // add buffer on
timeStep = timeWhenDisruptionEnds - time;
// Wait for weather event to complete...
logger.create().extractCallInfo().info().level(3).
msg(String.format("Awaiting end of event %s at %s in %4d m at %tF %tT ",
d.toString(),
site.getSiteName(), (timeStep / 60000),
timeWhenDisruptionEnds,
timeWhenDisruptionEnds)).send();
} else {
try {
selected = despatcher.nextScheduledJob();
} catch (Exception e) {
e.printStackTrace();
}
if (selected == null) {
timeStep = 150 * 1000L;// 2.5 minutes
long bgCompletion = time + timeStep;
// Wait for BG to complete...
logger
.create()
.extractCallInfo()
.info()
.level(3)
.msg(
String
.format(
"No groups available, awaiting completion of BG_OBS at %s in %4d m at %tF %tT ",
site.getSiteName(), (timeStep / 60000), bgCompletion,
bgCompletion)).send();
} else {
// at last weve actually got something to do...
GroupItem group = selected.getGroup();
ExecutionResourceBundle xrb = execTimingModel.getEstimatedResourceUsage(group);
ExecutionResource timeResource = xrb.getResource("TIME");
long exec = (long) timeResource.getResourceUsage();
ig++;
logger.create().extractCallInfo().info().level(2).msg(
"Selected Group estimated completion at " + sdf.format(new Date(time + exec))).send();
sel.groupSelected(selected);
// now need to decide if it will fail..
// Disruptor d = disruptorGenerator.firstDisruptor(time,
// time+exec);
Disruptor dg = dgen.nextDisruptor(time, time + exec);
if (dg == null) {
execFail = false;
timeStep = exec;
long groupCompletionTime = time + exec;
logger.create().extractCallInfo().info().level(2).msg(
String.format("Selected group: %s estimated completion in %6d s at %tF %tT", group
.getName(), (exec / 1000), groupCompletionTime, groupCompletionTime))
.send();
} else {
execFail = true;
execFailReason = dg.getDisruptorClass()+":"+dg.getDisruptorName();
long groupFailureTime = dg.getPeriod().getStart();
timeStep = groupFailureTime - time;
logger.create().extractCallInfo().info().level(2).
msg(String.format("Selected group: %s will fail in %6d s at %tF %tT due to %s",
group.getName(),
(timeStep / 1000),
groupFailureTime, groupFailureTime,
dg.toString()))
.send();
}
} // group was selected
} // weather is good
} // it is night-time
// fire any volatility events in [t, t+tau]
volgen.fireEvents(time, time + timeStep);
// find out what time the SimApp has decided to jump onto,
// this should be reflected in the TimeModel
// used by the despatcher and its xfm.
tsr.waitTimeSignal(time + timeStep);
time = tsg.getTime();
// TODO if we are running a group, update group info in history
// - controller will do this --- hopefully,
if (selected != null) {
if (execFail) {
sel.groupFailed(selected, time, execFailReason);
} else {
sel.groupCompleted(selected, time);
}
}
} // next time step
// end of simulation
sel.simulationCompleted();
}
} // [ScheduleSimulator]
| LivTel/scheduling-management-system | java/src/ngat/sms/simulation/ScheduleSimulator.java | 2,673 | /** Generate volatility events. */ | block_comment | nl | package ngat.sms.simulation;
import java.util.*;
import java.text.*;
import javax.security.auth.login.FailedLoginException;
import ngat.astrometry.*;
import ngat.phase2.XProposal;
import ngat.sms.Disruptor;
import ngat.sms.EnvironmentPredictionModel;
import ngat.sms.EnvironmentSnapshot;
import ngat.sms.ExecutionResource;
import ngat.sms.ExecutionResourceBundle;
import ngat.sms.ExecutionResourceUsageEstimationModel;
import ngat.sms.GroupItem;
import ngat.sms.ScheduleDespatcher;
import ngat.sms.ScheduleItem;
import ngat.sms.WeatherPredictionModel;
import ngat.sms.WeatherSnapshot;
import ngat.util.*;
import ngat.util.logging.*;
/**
* Performs a simulation over one or more nights using a cached ODB for a
* specified site.
*/
public class ScheduleSimulator {
/** Standard date formatter. */
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/** Standard UTC timezone. */
public static SimpleTimeZone UTC = new SimpleTimeZone(0, "UTC");
/** Horizon level (for sunset/sunrise). */
public static final double HORIZON = Math.toRadians(-1.0);
static {
sdf.setTimeZone(UTC);
Calendar.getInstance().setTimeZone(UTC);
}
/** Site location. */
private ISite site;
/** Logger. */
private LogGenerator logger;
/** Schedule dispatcher. */
ScheduleDespatcher despatcher;
/** Execution timing. */
private ExecutionResourceUsageEstimationModel execTimingModel;
/** Environment prediction. */
private EnvironmentPredictionModel envPredictor;
/** Weather prediction. */
private WeatherPredictionModel weatherPredictor;
/** Generate disruptor events. */
private DisruptionGenerator dgen;
/** Generate volatility events.<SUF>*/
private VolatilityGenerator volgen;
/** Works out the actual exec-time of groups. */
private StochasticExecutionTimingModel stm;
/** Site-centred astro calculator. */
private AstrometrySiteCalculator astro;
/** Receives time signal callbacks. */
private DefaultTimeSignalReceiver tsr;
/**
* Create a ScheduleSimulator.
*
* @param site
* The location where the observatory is sited.
* @param despatcher
* A scheduler.
* @param execModel
* Execution resource model.
* @param envPredictor
* Sky-conditions prediction.
* @param weatherPredictor
* Weather prediction.
*/
public ScheduleSimulator(ISite site, ScheduleDespatcher despatcher,
ExecutionResourceUsageEstimationModel execModel, EnvironmentPredictionModel envPredictor,
WeatherPredictionModel weatherPredictor, DisruptionGenerator dgen, VolatilityGenerator volgen,
StochasticExecutionTimingModel stm) {
this.site = site;
this.despatcher = despatcher;
this.execTimingModel = execModel;
this.envPredictor = envPredictor;
this.weatherPredictor = weatherPredictor;
this.dgen = dgen;
this.volgen = volgen;
this.stm = stm;
astro = new BasicAstrometrySiteCalculator(site);
Logger alogger = LogManager.getLogger("SIM");
logger = new LogGenerator(alogger);
logger.system("SMS").subSystem("Simulator").srcCompClass("SchedSim(" + site.getSiteName() + ")").srcCompId(
this.getClass().getSimpleName());
}
/**
* Start a simulation run from start to end times.
*
* @param tsg
* The TimeSignalGenerator to synchronize with.
* @param start
* simulation start time.
* @param end
* simulation end time.
* @param sel
* A SimulationEventListener to receive progress events.
*/
public void runSimulation(TimeSignalGenerator tsg, long start, long end, SimulationEventListener sel)
throws Exception {
tsr = new DefaultTimeSignalReceiver(tsg);
int ig = 0;
SolarCalculator sunTrack = new SolarCalculator();
long time = start;
long timeStep = 0L;
ScheduleItem selected = null;
boolean execFail = false;
String execFailReason = null;
// run over sim period
while (time < end) {
selected = null;
EnvironmentSnapshot env = envPredictor.predictEnvironment(time);
// If its daytime we should jump to next sunset...
Coordinates sun = sunTrack.getCoordinates(time);
if (astro.getAltitude(sun, time) > HORIZON) {
// Calculate next sunset time after current time.
// Use -1 degs to make sure the bugger has really set
// as we haven't considered site elevation or refraction.
long timeTillSunset = astro.getTimeUntilNextSet(sun, HORIZON, time);
long sunset = time + timeTillSunset;
timeStep = timeTillSunset;
// Wait for sunset...
logger.create().extractCallInfo().info().level(3).msg(
String.format("Awaiting SUNSET at %s in %4d m at %tF %tT ", site.getSiteName(),
(timeStep / 60000), sunset, sunset)).send();
} else {
// check the weather and other disruptors
Disruptor d = dgen.hasDisruptor(time);
if (d != null) {
// WeatherSnapshot weather =
// weatherPredictor.predictWeather(time);
// if (!weather.isGood()) {
long timeWhenDisruptionEnds = d.getPeriod().getEnd() + 30000L; // add buffer on
timeStep = timeWhenDisruptionEnds - time;
// Wait for weather event to complete...
logger.create().extractCallInfo().info().level(3).
msg(String.format("Awaiting end of event %s at %s in %4d m at %tF %tT ",
d.toString(),
site.getSiteName(), (timeStep / 60000),
timeWhenDisruptionEnds,
timeWhenDisruptionEnds)).send();
} else {
try {
selected = despatcher.nextScheduledJob();
} catch (Exception e) {
e.printStackTrace();
}
if (selected == null) {
timeStep = 150 * 1000L;// 2.5 minutes
long bgCompletion = time + timeStep;
// Wait for BG to complete...
logger
.create()
.extractCallInfo()
.info()
.level(3)
.msg(
String
.format(
"No groups available, awaiting completion of BG_OBS at %s in %4d m at %tF %tT ",
site.getSiteName(), (timeStep / 60000), bgCompletion,
bgCompletion)).send();
} else {
// at last weve actually got something to do...
GroupItem group = selected.getGroup();
ExecutionResourceBundle xrb = execTimingModel.getEstimatedResourceUsage(group);
ExecutionResource timeResource = xrb.getResource("TIME");
long exec = (long) timeResource.getResourceUsage();
ig++;
logger.create().extractCallInfo().info().level(2).msg(
"Selected Group estimated completion at " + sdf.format(new Date(time + exec))).send();
sel.groupSelected(selected);
// now need to decide if it will fail..
// Disruptor d = disruptorGenerator.firstDisruptor(time,
// time+exec);
Disruptor dg = dgen.nextDisruptor(time, time + exec);
if (dg == null) {
execFail = false;
timeStep = exec;
long groupCompletionTime = time + exec;
logger.create().extractCallInfo().info().level(2).msg(
String.format("Selected group: %s estimated completion in %6d s at %tF %tT", group
.getName(), (exec / 1000), groupCompletionTime, groupCompletionTime))
.send();
} else {
execFail = true;
execFailReason = dg.getDisruptorClass()+":"+dg.getDisruptorName();
long groupFailureTime = dg.getPeriod().getStart();
timeStep = groupFailureTime - time;
logger.create().extractCallInfo().info().level(2).
msg(String.format("Selected group: %s will fail in %6d s at %tF %tT due to %s",
group.getName(),
(timeStep / 1000),
groupFailureTime, groupFailureTime,
dg.toString()))
.send();
}
} // group was selected
} // weather is good
} // it is night-time
// fire any volatility events in [t, t+tau]
volgen.fireEvents(time, time + timeStep);
// find out what time the SimApp has decided to jump onto,
// this should be reflected in the TimeModel
// used by the despatcher and its xfm.
tsr.waitTimeSignal(time + timeStep);
time = tsg.getTime();
// TODO if we are running a group, update group info in history
// - controller will do this --- hopefully,
if (selected != null) {
if (execFail) {
sel.groupFailed(selected, time, execFailReason);
} else {
sel.groupCompleted(selected, time);
}
}
} // next time step
// end of simulation
sel.simulationCompleted();
}
} // [ScheduleSimulator]
|
75914_5 | package com.llama.tech.utils.graph;
import java.io.Serializable;
import java.util.Iterator;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.IArco;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.ICamino;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.ICaminosMinimos;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.IVertice;
import com.llama.tech.utils.dict.LlamaDict;
import com.llama.tech.utils.list.Lista;
import com.llama.tech.utils.list.LlamaArrayList;
import com.llama.tech.utils.list.LlamaIterator;
import com.llama.tech.utils.queue.LlamaHeap;
public class CaminoMinimo <K extends Comparable<K>, V extends Comparable<V>,A> implements ICaminosMinimos<K, V, A>,Serializable{
private LlamaGraph<K, V,A> g;
private GraphVertex<K, V,A> vOrigen;
private LlamaDict<K, NodoDijkstra<K,V,A>> vDestino = new LlamaDict<K, NodoDijkstra<K,V,A>>(10);
private LlamaHeap<GraphVertex<K, V, A>, Double> cola; //TODO: Cola prid Yo la hago!
private LlamaDict<K, Camino<K,V,A>> caminos = new LlamaDict<K, Camino<K,V,A>>(10);
private LlamaDict<GraphVertex<K, V, A>, Double> dist = new LlamaDict<GraphVertex<K, V, A>, Double>(10);
private LlamaDict<GraphVertex<K, V, A>, GraphVertex<K, V, A>> pred = new LlamaDict<GraphVertex<K, V, A>, GraphVertex<K, V, A>>(10);
private static CaminoMinimo instance;
public CaminoMinimo(LlamaGraph<K,V,A> gp)
{
g = gp;
}
public static void initializeInstance(LlamaGraph gp)
{
instance = new CaminoMinimo(gp);
}
public static CaminoMinimo getInstance()
{
return instance;
}
public void setOrigin(GraphVertex<K, V, A> or)
{
vOrigen = or;
}
// public void initialize()
// {
// cola = new LlamaHeap<GraphVertex<K, V, A>, Double>();
// Iterator<IVertice<K, V, A>> it = g.darVertices();
// while(it.hasNext())
// {
// GraphVertex<K, V,A> v=(GraphVertex<K, V,A>)it.next();
// v.desmarcar();
// vDestino.addEntry(v.darId(), new NodoDijkstra<K,V,A>(v, Integer.MAX_VALUE));
// }
// }
//
// public void relajar(NodoDijkstra<K, V,A> origen, GraphEdge<K, V, A> e)
// {
// NodoDijkstra<K, V,A> destino = vDestino.getValue(e.darDestino().darId());
// if(destino.getMinCost() > origen.getMinCost() + e.darCosto())
// {
// destino.setMinCost(origen.getMinCost()+e.darCosto());
//
// destino.setPred(origen);
// if(cola.isEmpty() || !cola.contains(destino))
// {
// //System.out.println(destino);
// cola.push(destino, destino.getMinCost());
// }
// }
// }
//
// public void calcularCaminosMinimos()
// {
// initialize();
// NodoDijkstra<K, V,A> n = vDestino.getValue(vOrigen.darId());
// n.setMinCost(0);
// cola.push(n, 0.0);
// while(!cola.isEmpty())
// {
// NodoDijkstra<K, V,A> nd = cola.pop();
// System.out.println(nd);
// //nd.visit();
// for(IArco<K, V,A> ed: n.getV().getEdgesTo())
// {
// GraphEdge<K, V, A> e = (GraphEdge<K, V, A>) ed;
// //if(!vDestino.getValue(e.darDestino().darId()).visited())
// //{
// relajar(nd, e);
// //}
// }
// }
// }
public void dijkstra()
{
dist = new LlamaDict<GraphVertex<K, V, A>, Double>(10);
pred = new LlamaDict<GraphVertex<K, V, A>, GraphVertex<K, V, A>>(10);
caminos = new LlamaDict<K, Camino<K,V,A>>(10);
cola = new LlamaHeap<GraphVertex<K, V, A>, Double>();
dist.addEntry(vOrigen, 0.0);
cola.push(vOrigen, 0.0);
Iterator<IVertice<K, V, A>> it = g.darVertices();
while(it.hasNext())
{
GraphVertex<K, V,A> v = (GraphVertex<K, V,A>) it.next();
if(v.compareTo(vOrigen) != 0)
{
dist.addEntry(v, Double.MAX_VALUE);
pred.addEntry(v, new GraphVertex<K,V,A>(null, null));
//cola.push(v, dist.getValue(v));
}
}
while(!cola.isEmpty())
{
GraphVertex<K,V,A> u = cola.pop();
//System.out.println(u+"\n");
for(IArco<K,V,A> a : u.getEdgesTo())
{
GraphEdge<K, V, A> e = (GraphEdge<K, V, A>) a;
GraphVertex<K, V, A> v = e.darDestino();
double alt = dist.getValue(u) + e.darCosto();
if(alt < dist.getValue(v))
{
dist.addEntry(v, alt);
pred.addEntry(v, u);
if(!cola.contains(v))
{
//System.out.println(v);
cola.push(v, alt);
}
//cola.decreasePriority(v, alt);
}
}
}
//System.out.println(pred);
}
public void reconstruirCaminosMinimos()
{
Iterator<NodoDijkstra<K, V, A>> it = vDestino.getValues();
while(it.hasNext())
{
Lista<IVertice<K,V,A>> vertices = new LlamaArrayList<IVertice<K, V, A>>(10);
Lista<IArco<K,V,A>> arcos = new LlamaArrayList<IArco<K, V, A>>(10);
double costo=0;
int longitud=0;
NodoDijkstra<K, V, A> v = it.next();
NodoDijkstra<K, V, A> actual = v;
NodoDijkstra<K, V, A> pred = v.getPred();
while(pred!=null)
{
vertices.addAlPrincipio(pred.getV());
longitud++;
arcos.addAlPrincipio(g.darArco(pred.getV().darId(), actual.getV().darId()));
costo+=g.darArco(pred.getV().darId(), actual.getV().darId()).darCosto();
actual = pred;
pred = pred.getPred();
}
caminos.addEntry(v.getV().darId(), new Camino<>(arcos, vertices, costo, longitud));
}
}
public void reconstructPath()
{
Lista<IVertice<K,V,A>> vertices = new LlamaArrayList<IVertice<K, V, A>>(10);
Lista<IArco<K,V,A>> arcs = new LlamaArrayList<IArco<K, V, A>>(10);
Iterator<GraphVertex<K, V, A>> nodes = dist.getKeys();
while(nodes.hasNext())
{
GraphVertex<K, V, A> v = nodes.next();
GraphVertex<K, V, A> i = v;
double cost = dist.getValue(v);
int length = 0;
boolean interrupt = false;
while(v.compareTo(vOrigen) != 0)
{
vertices.addAlPrincipio(v);
GraphVertex<K, V, A> prevNode = pred.getValue(v);
//System.out.println(prevNode.darId()+","+v.darId());
if(prevNode.darId() != null)
{
arcs.addAlFinal(g.darArco(prevNode.darId(), v.darId()));
length++;
v = prevNode;
}
else
{
//System.out.println("Interrupt!");
interrupt = true;
break;
}
}
if(!interrupt)
{
//System.out.println("Camino!");
vertices.addAlPrincipio(vOrigen);
caminos.addEntry(i.darId(), new Camino<K,V,A>(arcs,vertices,cost,length));
}
vertices = new LlamaArrayList<IVertice<K, V, A>>(10);
arcs = new LlamaArrayList<IArco<K, V, A>>(10);
}
}
@Override
public ICamino<K, V, A> darCaminoMinimo(K arg0)
{
return caminos.getValue(arg0);
}
@Override
public IVertice<K, V, A> darOrigen() {
return vOrigen;
}
public Iterator<Camino<K,V,A>> darCaminos()
{
return caminos.getValues();
}
}
| Llamatech/LlamaUtils | src/com/llama/tech/utils/graph/CaminoMinimo.java | 2,843 | // vDestino.addEntry(v.darId(), new NodoDijkstra<K,V,A>(v, Integer.MAX_VALUE)); | line_comment | nl | package com.llama.tech.utils.graph;
import java.io.Serializable;
import java.util.Iterator;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.IArco;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.ICamino;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.ICaminosMinimos;
import co.edu.uniandes.cupi2.estructuras.grafoDirigido.IVertice;
import com.llama.tech.utils.dict.LlamaDict;
import com.llama.tech.utils.list.Lista;
import com.llama.tech.utils.list.LlamaArrayList;
import com.llama.tech.utils.list.LlamaIterator;
import com.llama.tech.utils.queue.LlamaHeap;
public class CaminoMinimo <K extends Comparable<K>, V extends Comparable<V>,A> implements ICaminosMinimos<K, V, A>,Serializable{
private LlamaGraph<K, V,A> g;
private GraphVertex<K, V,A> vOrigen;
private LlamaDict<K, NodoDijkstra<K,V,A>> vDestino = new LlamaDict<K, NodoDijkstra<K,V,A>>(10);
private LlamaHeap<GraphVertex<K, V, A>, Double> cola; //TODO: Cola prid Yo la hago!
private LlamaDict<K, Camino<K,V,A>> caminos = new LlamaDict<K, Camino<K,V,A>>(10);
private LlamaDict<GraphVertex<K, V, A>, Double> dist = new LlamaDict<GraphVertex<K, V, A>, Double>(10);
private LlamaDict<GraphVertex<K, V, A>, GraphVertex<K, V, A>> pred = new LlamaDict<GraphVertex<K, V, A>, GraphVertex<K, V, A>>(10);
private static CaminoMinimo instance;
public CaminoMinimo(LlamaGraph<K,V,A> gp)
{
g = gp;
}
public static void initializeInstance(LlamaGraph gp)
{
instance = new CaminoMinimo(gp);
}
public static CaminoMinimo getInstance()
{
return instance;
}
public void setOrigin(GraphVertex<K, V, A> or)
{
vOrigen = or;
}
// public void initialize()
// {
// cola = new LlamaHeap<GraphVertex<K, V, A>, Double>();
// Iterator<IVertice<K, V, A>> it = g.darVertices();
// while(it.hasNext())
// {
// GraphVertex<K, V,A> v=(GraphVertex<K, V,A>)it.next();
// v.desmarcar();
// vDestino.addEntry(v.darId(), new<SUF>
// }
// }
//
// public void relajar(NodoDijkstra<K, V,A> origen, GraphEdge<K, V, A> e)
// {
// NodoDijkstra<K, V,A> destino = vDestino.getValue(e.darDestino().darId());
// if(destino.getMinCost() > origen.getMinCost() + e.darCosto())
// {
// destino.setMinCost(origen.getMinCost()+e.darCosto());
//
// destino.setPred(origen);
// if(cola.isEmpty() || !cola.contains(destino))
// {
// //System.out.println(destino);
// cola.push(destino, destino.getMinCost());
// }
// }
// }
//
// public void calcularCaminosMinimos()
// {
// initialize();
// NodoDijkstra<K, V,A> n = vDestino.getValue(vOrigen.darId());
// n.setMinCost(0);
// cola.push(n, 0.0);
// while(!cola.isEmpty())
// {
// NodoDijkstra<K, V,A> nd = cola.pop();
// System.out.println(nd);
// //nd.visit();
// for(IArco<K, V,A> ed: n.getV().getEdgesTo())
// {
// GraphEdge<K, V, A> e = (GraphEdge<K, V, A>) ed;
// //if(!vDestino.getValue(e.darDestino().darId()).visited())
// //{
// relajar(nd, e);
// //}
// }
// }
// }
public void dijkstra()
{
dist = new LlamaDict<GraphVertex<K, V, A>, Double>(10);
pred = new LlamaDict<GraphVertex<K, V, A>, GraphVertex<K, V, A>>(10);
caminos = new LlamaDict<K, Camino<K,V,A>>(10);
cola = new LlamaHeap<GraphVertex<K, V, A>, Double>();
dist.addEntry(vOrigen, 0.0);
cola.push(vOrigen, 0.0);
Iterator<IVertice<K, V, A>> it = g.darVertices();
while(it.hasNext())
{
GraphVertex<K, V,A> v = (GraphVertex<K, V,A>) it.next();
if(v.compareTo(vOrigen) != 0)
{
dist.addEntry(v, Double.MAX_VALUE);
pred.addEntry(v, new GraphVertex<K,V,A>(null, null));
//cola.push(v, dist.getValue(v));
}
}
while(!cola.isEmpty())
{
GraphVertex<K,V,A> u = cola.pop();
//System.out.println(u+"\n");
for(IArco<K,V,A> a : u.getEdgesTo())
{
GraphEdge<K, V, A> e = (GraphEdge<K, V, A>) a;
GraphVertex<K, V, A> v = e.darDestino();
double alt = dist.getValue(u) + e.darCosto();
if(alt < dist.getValue(v))
{
dist.addEntry(v, alt);
pred.addEntry(v, u);
if(!cola.contains(v))
{
//System.out.println(v);
cola.push(v, alt);
}
//cola.decreasePriority(v, alt);
}
}
}
//System.out.println(pred);
}
public void reconstruirCaminosMinimos()
{
Iterator<NodoDijkstra<K, V, A>> it = vDestino.getValues();
while(it.hasNext())
{
Lista<IVertice<K,V,A>> vertices = new LlamaArrayList<IVertice<K, V, A>>(10);
Lista<IArco<K,V,A>> arcos = new LlamaArrayList<IArco<K, V, A>>(10);
double costo=0;
int longitud=0;
NodoDijkstra<K, V, A> v = it.next();
NodoDijkstra<K, V, A> actual = v;
NodoDijkstra<K, V, A> pred = v.getPred();
while(pred!=null)
{
vertices.addAlPrincipio(pred.getV());
longitud++;
arcos.addAlPrincipio(g.darArco(pred.getV().darId(), actual.getV().darId()));
costo+=g.darArco(pred.getV().darId(), actual.getV().darId()).darCosto();
actual = pred;
pred = pred.getPred();
}
caminos.addEntry(v.getV().darId(), new Camino<>(arcos, vertices, costo, longitud));
}
}
public void reconstructPath()
{
Lista<IVertice<K,V,A>> vertices = new LlamaArrayList<IVertice<K, V, A>>(10);
Lista<IArco<K,V,A>> arcs = new LlamaArrayList<IArco<K, V, A>>(10);
Iterator<GraphVertex<K, V, A>> nodes = dist.getKeys();
while(nodes.hasNext())
{
GraphVertex<K, V, A> v = nodes.next();
GraphVertex<K, V, A> i = v;
double cost = dist.getValue(v);
int length = 0;
boolean interrupt = false;
while(v.compareTo(vOrigen) != 0)
{
vertices.addAlPrincipio(v);
GraphVertex<K, V, A> prevNode = pred.getValue(v);
//System.out.println(prevNode.darId()+","+v.darId());
if(prevNode.darId() != null)
{
arcs.addAlFinal(g.darArco(prevNode.darId(), v.darId()));
length++;
v = prevNode;
}
else
{
//System.out.println("Interrupt!");
interrupt = true;
break;
}
}
if(!interrupt)
{
//System.out.println("Camino!");
vertices.addAlPrincipio(vOrigen);
caminos.addEntry(i.darId(), new Camino<K,V,A>(arcs,vertices,cost,length));
}
vertices = new LlamaArrayList<IVertice<K, V, A>>(10);
arcs = new LlamaArrayList<IArco<K, V, A>>(10);
}
}
@Override
public ICamino<K, V, A> darCaminoMinimo(K arg0)
{
return caminos.getValue(arg0);
}
@Override
public IVertice<K, V, A> darOrigen() {
return vOrigen;
}
public Iterator<Camino<K,V,A>> darCaminos()
{
return caminos.getValues();
}
}
|
122387_6 | /*
* MIT License
*
* Copyright (c) 2014 - 2024 LoboEvolution
*
* 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.
*
* Contact info: [email protected]
*/
package com.jtattoo.plaf.aero;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
import com.jtattoo.plaf.AbstractLookAndFeel;
import com.jtattoo.plaf.BaseBorders;
import com.jtattoo.plaf.ColorHelper;
import com.jtattoo.plaf.JTattooUtilities;
/**
* <p>AeroBorders class.</p>
*
* Author Michael Hagen
*
*/
public class AeroBorders extends BaseBorders {
// ------------------------------------------------------------------------------------
// Implementation of border classes
// ------------------------------------------------------------------------------------
public static class ButtonBorder implements Border, UIResource {
private static final Insets insets = new Insets(4, 8, 4, 8);
@Override
public Insets getBorderInsets(final Component c) {
return insets;
}
public Insets getBorderInsets(final Component c, final Insets borderInsets) {
borderInsets.left = insets.left;
borderInsets.top = insets.top;
borderInsets.right = insets.right;
borderInsets.bottom = insets.bottom;
return borderInsets;
}
@Override
public boolean isBorderOpaque() {
return true;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) {
final Graphics2D g2D = (Graphics2D) g;
final AbstractButton button = (AbstractButton) c;
final ButtonModel model = button.getModel();
if (model.isEnabled()) {
g.setColor(AbstractLookAndFeel.getFrameColor());
} else {
g.setColor(ColorHelper.brighter(AbstractLookAndFeel.getFrameColor(), 30));
}
g.drawRect(x, y, w - 2, h - 2);
final Composite composite = g2D.getComposite();
final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
g2D.setComposite(alpha);
g.setColor(Color.white);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h);
g.drawLine(x + 1, y + h - 1, x + w, y + h - 1);
g2D.setComposite(composite);
}
} // class ButtonBorder
public static class InternalFrameBorder extends BaseInternalFrameBorder {
private static final long serialVersionUID = 1L;
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int borderW, final int borderH) {
int w = borderW;
int h = borderH;
Color borderColor = AbstractLookAndFeel.getWindowInactiveBorderColor();
if (isActive(c)) {
borderColor = AbstractLookAndFeel.getWindowBorderColor();
}
if (!isResizable(c)) {
Color cHi = ColorHelper.brighter(borderColor, 40);
Color cLo = ColorHelper.darker(borderColor, 40);
JTattooUtilities.draw3DBorder(g, cHi, cLo, x, y, w, h);
cHi = ColorHelper.darker(cHi, 20);
cLo = ColorHelper.brighter(cLo, 20);
JTattooUtilities.draw3DBorder(g, cHi, cLo, x + 1, y + 1, w - 2, h - 2);
g.setColor(borderColor);
for (int i = 2; i < DW; i++) {
g.drawRect(i, i, w - 2 * i - 1, h - 2 * i - 1);
}
} else {
final int dt = w / 3;
final int db = w * 2 / 3;
h--;
w--;
final Color cl = ColorHelper.brighter(borderColor, 10);
final Color cr = AbstractLookAndFeel.getWindowInactiveBorderColor();
g.setColor(cl);
g.drawLine(x, y, x, y + h);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + 1, y + 1, x + 1, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + 2, y + 2, x + 2, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + 3, y + 3, x + 3, y + h - 3);
g.setColor(cl);
g.drawLine(x + 4, y + 4, x + 4, y + h - 4);
// rechts
g.setColor(cr);
g.drawLine(x + w, y, x + w, y + h);
g.setColor(ColorHelper.brighter(cr, 30));
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cr, 60));
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cr, 90));
g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 3);
g.setColor(cr);
g.drawLine(x + w - 4, y + 4, x + w - 4, y + h - 4);
g.setColor(cl);
g.drawLine(x + w, y, x + w, y + TRACK_WIDTH);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - 1, y + 1, x + w - 1, y + TRACK_WIDTH);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - 2, y + 2, x + w - 2, y + TRACK_WIDTH);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - 3, y + 3, x + w - 3, y + TRACK_WIDTH);
g.setColor(cl);
g.drawLine(x + w - 4, y + 4, x + w - 4, y + TRACK_WIDTH);
g.setColor(cl);
g.drawLine(x + w, y + h - TRACK_WIDTH, x + w, y + h);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - 1, y + h - TRACK_WIDTH, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - 2, y + h - TRACK_WIDTH, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - 3, y + h - TRACK_WIDTH, x + w - 3, y + h - 3);
g.setColor(cl);
g.drawLine(x + w - 4, y + h - TRACK_WIDTH, x + w - 4, y + h - 4);
// oben
g.setColor(cl);
g.drawLine(x, y, x + dt, y);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + 1, y + 1, x + dt, y + 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + 2, y + 2, x + dt, y + 2);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + 3, y + 3, x + dt, y + 3);
g.setColor(cl);
g.drawLine(x + 4, y + 4, x + dt, y + 4);
g.setColor(cr);
g.drawLine(x + dt, y, x + w, y);
g.setColor(ColorHelper.brighter(cr, 90));
g.drawLine(x + dt, y + 1, x + w - 1, y + 1);
g.setColor(ColorHelper.brighter(cr, 60));
g.drawLine(x + dt, y + 2, x + w - 2, y + 2);
g.setColor(ColorHelper.brighter(cr, 30));
g.drawLine(x + dt, y + 3, x + w - 3, y + 3);
if (isActive(c)) {
g.setColor(ColorHelper.darker(cr, 15));
} else {
g.setColor(cr);
}
g.drawLine(x + dt, y + 4, x + w - 4, y + 4);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y, x + w, y);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - TRACK_WIDTH, y + 1, x + w - 1, y + 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - TRACK_WIDTH, y + 2, x + w - 2, y + 2);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - TRACK_WIDTH, y + 3, x + w - 3, y + 3);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y + 4, x + w - 4, y + 4);
// unten
g.setColor(cl);
g.drawLine(x, y + h, x + db, y + h);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + 1, y + h - 1, x + db, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + 2, y + h - 2, x + db, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + 3, y + h - 3, x + db, y + h - 3);
g.setColor(cl);
g.drawLine(x + 4, y + h - 4, x + db, y + h - 4);
g.setColor(cr);
g.drawLine(x + db, y + h, x + w, y + h);
g.setColor(ColorHelper.brighter(cr, 30));
g.drawLine(x + db, y + h - 1, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cr, 60));
g.drawLine(x + db, y + h - 2, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cr, 90));
g.drawLine(x + db, y + h - 3, x + w - 3, y + h - 3);
g.setColor(cr);
g.drawLine(x + db, y + h - 4, x + w - 4, y + h - 4);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y + h, x + w, y + h);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - TRACK_WIDTH, y + h - 1, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - TRACK_WIDTH, y + h - 2, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - TRACK_WIDTH, y + h - 3, x + w - 3, y + h - 3);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y + h - 4, x + w - 4, y + h - 4);
} // paintBorder
}
} // end of class InternalFrameBorder
public static class RolloverToolButtonBorder implements Border, UIResource {
private static final Insets insets = new Insets(1, 1, 1, 1);
@Override
public Insets getBorderInsets(final Component c) {
return new Insets(insets.top, insets.left, insets.bottom, insets.right);
}
public Insets getBorderInsets(final Component c, final Insets borderInsets) {
borderInsets.left = insets.left;
borderInsets.top = insets.top;
borderInsets.right = insets.right;
borderInsets.bottom = insets.bottom;
return borderInsets;
}
@Override
public boolean isBorderOpaque() {
return true;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) {
final AbstractButton button = (AbstractButton) c;
final ButtonModel model = button.getModel();
final Color loColor = AbstractLookAndFeel.getFrameColor();
if (model.isEnabled()) {
if (model.isPressed() && model.isArmed() || model.isSelected()) {
final Graphics2D g2D = (Graphics2D) g;
final Composite composite = g2D.getComposite();
g.setColor(loColor);
g.drawRect(x, y, w - 1, h - 1);
final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f);
g2D.setComposite(alpha);
g.setColor(Color.black);
g.fillRect(x + 1, y + 1, w - 2, h - 2);
g2D.setComposite(composite);
} else if (model.isRollover()) {
final Graphics2D g2D = (Graphics2D) g;
final Composite composite = g2D.getComposite();
g.setColor(loColor);
g.drawRect(x, y, w - 1, h - 1);
final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
g2D.setComposite(alpha);
g.setColor(Color.white);
g.fillRect(x + 1, y + 1, w - 2, h - 2);
g2D.setComposite(composite);
}
}
}
} // class RolloverToolButtonBorder
// ------------------------------------------------------------------------------------
// Lazy access methods
// ------------------------------------------------------------------------------------
/**
* <p>getButtonBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getButtonBorder() {
if (buttonBorder == null) {
buttonBorder = new ButtonBorder();
}
return buttonBorder;
}
/**
* <p>getInternalFrameBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getInternalFrameBorder() {
if (internalFrameBorder == null) {
internalFrameBorder = new InternalFrameBorder();
}
return internalFrameBorder;
}
/**
* <p>getRolloverToolButtonBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getRolloverToolButtonBorder() {
if (rolloverToolButtonBorder == null) {
rolloverToolButtonBorder = new RolloverToolButtonBorder();
}
return rolloverToolButtonBorder;
}
/**
* <p>getToggleButtonBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getToggleButtonBorder() {
return getButtonBorder();
}
} // end of class AeroBorders
| LoboEvolution/LoboEvolution | LoboJTattoo/src/main/java/com/jtattoo/plaf/aero/AeroBorders.java | 5,025 | /**
* <p>getInternalFrameBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/ | block_comment | nl | /*
* MIT License
*
* Copyright (c) 2014 - 2024 LoboEvolution
*
* 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.
*
* Contact info: [email protected]
*/
package com.jtattoo.plaf.aero;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
import com.jtattoo.plaf.AbstractLookAndFeel;
import com.jtattoo.plaf.BaseBorders;
import com.jtattoo.plaf.ColorHelper;
import com.jtattoo.plaf.JTattooUtilities;
/**
* <p>AeroBorders class.</p>
*
* Author Michael Hagen
*
*/
public class AeroBorders extends BaseBorders {
// ------------------------------------------------------------------------------------
// Implementation of border classes
// ------------------------------------------------------------------------------------
public static class ButtonBorder implements Border, UIResource {
private static final Insets insets = new Insets(4, 8, 4, 8);
@Override
public Insets getBorderInsets(final Component c) {
return insets;
}
public Insets getBorderInsets(final Component c, final Insets borderInsets) {
borderInsets.left = insets.left;
borderInsets.top = insets.top;
borderInsets.right = insets.right;
borderInsets.bottom = insets.bottom;
return borderInsets;
}
@Override
public boolean isBorderOpaque() {
return true;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) {
final Graphics2D g2D = (Graphics2D) g;
final AbstractButton button = (AbstractButton) c;
final ButtonModel model = button.getModel();
if (model.isEnabled()) {
g.setColor(AbstractLookAndFeel.getFrameColor());
} else {
g.setColor(ColorHelper.brighter(AbstractLookAndFeel.getFrameColor(), 30));
}
g.drawRect(x, y, w - 2, h - 2);
final Composite composite = g2D.getComposite();
final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
g2D.setComposite(alpha);
g.setColor(Color.white);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h);
g.drawLine(x + 1, y + h - 1, x + w, y + h - 1);
g2D.setComposite(composite);
}
} // class ButtonBorder
public static class InternalFrameBorder extends BaseInternalFrameBorder {
private static final long serialVersionUID = 1L;
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int borderW, final int borderH) {
int w = borderW;
int h = borderH;
Color borderColor = AbstractLookAndFeel.getWindowInactiveBorderColor();
if (isActive(c)) {
borderColor = AbstractLookAndFeel.getWindowBorderColor();
}
if (!isResizable(c)) {
Color cHi = ColorHelper.brighter(borderColor, 40);
Color cLo = ColorHelper.darker(borderColor, 40);
JTattooUtilities.draw3DBorder(g, cHi, cLo, x, y, w, h);
cHi = ColorHelper.darker(cHi, 20);
cLo = ColorHelper.brighter(cLo, 20);
JTattooUtilities.draw3DBorder(g, cHi, cLo, x + 1, y + 1, w - 2, h - 2);
g.setColor(borderColor);
for (int i = 2; i < DW; i++) {
g.drawRect(i, i, w - 2 * i - 1, h - 2 * i - 1);
}
} else {
final int dt = w / 3;
final int db = w * 2 / 3;
h--;
w--;
final Color cl = ColorHelper.brighter(borderColor, 10);
final Color cr = AbstractLookAndFeel.getWindowInactiveBorderColor();
g.setColor(cl);
g.drawLine(x, y, x, y + h);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + 1, y + 1, x + 1, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + 2, y + 2, x + 2, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + 3, y + 3, x + 3, y + h - 3);
g.setColor(cl);
g.drawLine(x + 4, y + 4, x + 4, y + h - 4);
// rechts
g.setColor(cr);
g.drawLine(x + w, y, x + w, y + h);
g.setColor(ColorHelper.brighter(cr, 30));
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cr, 60));
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cr, 90));
g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 3);
g.setColor(cr);
g.drawLine(x + w - 4, y + 4, x + w - 4, y + h - 4);
g.setColor(cl);
g.drawLine(x + w, y, x + w, y + TRACK_WIDTH);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - 1, y + 1, x + w - 1, y + TRACK_WIDTH);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - 2, y + 2, x + w - 2, y + TRACK_WIDTH);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - 3, y + 3, x + w - 3, y + TRACK_WIDTH);
g.setColor(cl);
g.drawLine(x + w - 4, y + 4, x + w - 4, y + TRACK_WIDTH);
g.setColor(cl);
g.drawLine(x + w, y + h - TRACK_WIDTH, x + w, y + h);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - 1, y + h - TRACK_WIDTH, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - 2, y + h - TRACK_WIDTH, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - 3, y + h - TRACK_WIDTH, x + w - 3, y + h - 3);
g.setColor(cl);
g.drawLine(x + w - 4, y + h - TRACK_WIDTH, x + w - 4, y + h - 4);
// oben
g.setColor(cl);
g.drawLine(x, y, x + dt, y);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + 1, y + 1, x + dt, y + 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + 2, y + 2, x + dt, y + 2);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + 3, y + 3, x + dt, y + 3);
g.setColor(cl);
g.drawLine(x + 4, y + 4, x + dt, y + 4);
g.setColor(cr);
g.drawLine(x + dt, y, x + w, y);
g.setColor(ColorHelper.brighter(cr, 90));
g.drawLine(x + dt, y + 1, x + w - 1, y + 1);
g.setColor(ColorHelper.brighter(cr, 60));
g.drawLine(x + dt, y + 2, x + w - 2, y + 2);
g.setColor(ColorHelper.brighter(cr, 30));
g.drawLine(x + dt, y + 3, x + w - 3, y + 3);
if (isActive(c)) {
g.setColor(ColorHelper.darker(cr, 15));
} else {
g.setColor(cr);
}
g.drawLine(x + dt, y + 4, x + w - 4, y + 4);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y, x + w, y);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - TRACK_WIDTH, y + 1, x + w - 1, y + 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - TRACK_WIDTH, y + 2, x + w - 2, y + 2);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - TRACK_WIDTH, y + 3, x + w - 3, y + 3);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y + 4, x + w - 4, y + 4);
// unten
g.setColor(cl);
g.drawLine(x, y + h, x + db, y + h);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + 1, y + h - 1, x + db, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + 2, y + h - 2, x + db, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + 3, y + h - 3, x + db, y + h - 3);
g.setColor(cl);
g.drawLine(x + 4, y + h - 4, x + db, y + h - 4);
g.setColor(cr);
g.drawLine(x + db, y + h, x + w, y + h);
g.setColor(ColorHelper.brighter(cr, 30));
g.drawLine(x + db, y + h - 1, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cr, 60));
g.drawLine(x + db, y + h - 2, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cr, 90));
g.drawLine(x + db, y + h - 3, x + w - 3, y + h - 3);
g.setColor(cr);
g.drawLine(x + db, y + h - 4, x + w - 4, y + h - 4);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y + h, x + w, y + h);
g.setColor(ColorHelper.brighter(cl, 20));
g.drawLine(x + w - TRACK_WIDTH, y + h - 1, x + w - 1, y + h - 1);
g.setColor(ColorHelper.brighter(cl, 40));
g.drawLine(x + w - TRACK_WIDTH, y + h - 2, x + w - 2, y + h - 2);
g.setColor(ColorHelper.brighter(cl, 60));
g.drawLine(x + w - TRACK_WIDTH, y + h - 3, x + w - 3, y + h - 3);
g.setColor(cl);
g.drawLine(x + w - TRACK_WIDTH, y + h - 4, x + w - 4, y + h - 4);
} // paintBorder
}
} // end of class InternalFrameBorder
public static class RolloverToolButtonBorder implements Border, UIResource {
private static final Insets insets = new Insets(1, 1, 1, 1);
@Override
public Insets getBorderInsets(final Component c) {
return new Insets(insets.top, insets.left, insets.bottom, insets.right);
}
public Insets getBorderInsets(final Component c, final Insets borderInsets) {
borderInsets.left = insets.left;
borderInsets.top = insets.top;
borderInsets.right = insets.right;
borderInsets.bottom = insets.bottom;
return borderInsets;
}
@Override
public boolean isBorderOpaque() {
return true;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) {
final AbstractButton button = (AbstractButton) c;
final ButtonModel model = button.getModel();
final Color loColor = AbstractLookAndFeel.getFrameColor();
if (model.isEnabled()) {
if (model.isPressed() && model.isArmed() || model.isSelected()) {
final Graphics2D g2D = (Graphics2D) g;
final Composite composite = g2D.getComposite();
g.setColor(loColor);
g.drawRect(x, y, w - 1, h - 1);
final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f);
g2D.setComposite(alpha);
g.setColor(Color.black);
g.fillRect(x + 1, y + 1, w - 2, h - 2);
g2D.setComposite(composite);
} else if (model.isRollover()) {
final Graphics2D g2D = (Graphics2D) g;
final Composite composite = g2D.getComposite();
g.setColor(loColor);
g.drawRect(x, y, w - 1, h - 1);
final AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
g2D.setComposite(alpha);
g.setColor(Color.white);
g.fillRect(x + 1, y + 1, w - 2, h - 2);
g2D.setComposite(composite);
}
}
}
} // class RolloverToolButtonBorder
// ------------------------------------------------------------------------------------
// Lazy access methods
// ------------------------------------------------------------------------------------
/**
* <p>getButtonBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getButtonBorder() {
if (buttonBorder == null) {
buttonBorder = new ButtonBorder();
}
return buttonBorder;
}
/**
* <p>getInternalFrameBorder.</p>
<SUF>*/
public static Border getInternalFrameBorder() {
if (internalFrameBorder == null) {
internalFrameBorder = new InternalFrameBorder();
}
return internalFrameBorder;
}
/**
* <p>getRolloverToolButtonBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getRolloverToolButtonBorder() {
if (rolloverToolButtonBorder == null) {
rolloverToolButtonBorder = new RolloverToolButtonBorder();
}
return rolloverToolButtonBorder;
}
/**
* <p>getToggleButtonBorder.</p>
*
* @return a {@link javax.swing.border.Border} object.
*/
public static Border getToggleButtonBorder() {
return getButtonBorder();
}
} // end of class AeroBorders
|
99052_3 | package nl.enshore.dbperformance.benchmark;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nl.enshore.dbperformance.model.Product;
import nl.enshore.dbperformance.repository.CustomerRepository;
import nl.enshore.dbperformance.repository.ProductRepository;
import nl.enshore.dbperformance.repository.PurchaseRepository;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class JpaBenchmarkService {
private final CustomerRepository customerRepository;
private final ProductRepository productRepository;
private final PurchaseRepository purchaseRepository;
// Benchmark is als volgt;
// Op basis van een lijst specifieke producten willen we klanten een bepaald kortingspercentage geven
// Het idee is dat we bij elke customer kijken of er een aankoop is waarbij één van de producten gekocht is
// Wanneer dat het geval is; krijgt de klant de korting
public void benchmark(List<Long> ids, Integer discount) {
// Start your engines
long startTick = System.nanoTime();
List<Product> products = productRepository.findAllById(ids);
// Itereer over alle Customers
this.customerRepository.findAll().forEach(customer -> {
// Vind alle purchases per Customer waarin één van de producten zit
this.purchaseRepository.findAllByCustomerAndProductIn(customer, products).forEach(purchase -> {
customer.setDiscount(discount);
customerRepository.save(customer);
});
});
log.info("Processing duurde {} milliseconden", (System.nanoTime() - startTick) / 1000000);
}
}
| LoermansA/dbperformance | src/main/java/nl/enshore/dbperformance/benchmark/JpaBenchmarkService.java | 476 | // Wanneer dat het geval is; krijgt de klant de korting | line_comment | nl | package nl.enshore.dbperformance.benchmark;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nl.enshore.dbperformance.model.Product;
import nl.enshore.dbperformance.repository.CustomerRepository;
import nl.enshore.dbperformance.repository.ProductRepository;
import nl.enshore.dbperformance.repository.PurchaseRepository;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class JpaBenchmarkService {
private final CustomerRepository customerRepository;
private final ProductRepository productRepository;
private final PurchaseRepository purchaseRepository;
// Benchmark is als volgt;
// Op basis van een lijst specifieke producten willen we klanten een bepaald kortingspercentage geven
// Het idee is dat we bij elke customer kijken of er een aankoop is waarbij één van de producten gekocht is
// Wanneer dat<SUF>
public void benchmark(List<Long> ids, Integer discount) {
// Start your engines
long startTick = System.nanoTime();
List<Product> products = productRepository.findAllById(ids);
// Itereer over alle Customers
this.customerRepository.findAll().forEach(customer -> {
// Vind alle purchases per Customer waarin één van de producten zit
this.purchaseRepository.findAllByCustomerAndProductIn(customer, products).forEach(purchase -> {
customer.setDiscount(discount);
customerRepository.save(customer);
});
});
log.info("Processing duurde {} milliseconden", (System.nanoTime() - startTick) / 1000000);
}
}
|
86264_18 | package com.example.schoolcalenderchecker;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
public class activity_main extends Activity {
public static activity_main instance;
TextView nextLessonText;
TextView nextLessonLocText;
TextView nextLessonStartTime;
Button settingsButton;
Button authenticateButton;
Button requestButton;
TextView versionTitle;
public static final String shared_prefs = "sharedPrefs";
public static final String delaySeekBarStatusPref = "delaySeekBarStatusPref";
public static final String updatesSeekBarStatusPref = "updatesSeekBarStatusPref"; //TODO
public static final String llnNummerPref = "llnNummerPref";
public static final String access_tokenPref = "access_tokenPref";
public static final String zportal_namePref = "zportal_namePref";
String llnNummer;
int timeDelay;
String access_token;
String zportal_name = "griftland"; // Default value is "griftland"
long lastRequestTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextLessonText = findViewById(R.id.nextLessonText);
nextLessonLocText = findViewById(R.id.nextLessonLocText);
nextLessonStartTime = findViewById(R.id.nextLessonStartTime);
settingsButton = findViewById(R.id.settingsButton);
authenticateButton = findViewById(R.id.authenticateButton);
requestButton = findViewById(R.id.requestButton);
versionTitle = findViewById(R.id.versionTitleAuthenticate);
//set the version text
String versionCode = BuildConfig.VERSION_NAME;
String versionString = "v" + versionCode;
versionTitle.setText(versionString);
//OnClickListener settings
settingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//switch to the settings view
Intent intentSettingsView = new Intent(activity_main.this, activity_settings.class);
startActivity(intentSettingsView);
}
});
//OnClickListener authenticate
authenticateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//switch to the authenticate view
Intent intentAuthenticateView = new Intent(activity_main.this, activity_authenticate.class);
startActivity(intentAuthenticateView);
}
});
//OnClickListener make request
requestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (System.currentTimeMillis()-lastRequestTime >= 5000) {
lastRequestTime = System.currentTimeMillis();
makeRequest(new RequestCallback() {
@Override
public void requestComplete(String response) {
JSONObject les = processData(response, true);
LocalDateTime date;
if (les == null) {
nextLessonText.setText("No lesson was found.");
nextLessonLocText.setText("x");
nextLessonStartTime.setText("x");
} else {
try {
if (les.getString("response") == "empty") {
nextLessonText.setText("Done");
nextLessonLocText.setText("You are done for today!");
nextLessonStartTime.setText("");
} else if (les.getString("response") == "conflict") {
date = unixToTime(les.getInt("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText("Conflicting lessons");
nextLessonLocText.setText("Please use the app");
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
} else {
date = unixToTime(les.getInt("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText(les.getJSONArray("subjects").get(0).toString());
nextLessonLocText.setText(les.getJSONArray("locations").get(0).toString());
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
}
} catch (JSONException e) {
}
}
}
}, true);
}
}
});
//Make a request when we start the app
loadData();
if (access_token != null || access_token != "") {
makeRequest(new RequestCallback() {
@Override
public void requestComplete(String response) {
JSONObject les = processData(response, true);
LocalDateTime date = null;
if (les == null) {
nextLessonText.setText("No lesson was found.");
nextLessonLocText.setText("x");
nextLessonStartTime.setText("x");
} else {
try {
if (les.getString("response") == "empty") {
nextLessonText.setText("Done");
nextLessonLocText.setText("You are done for today!");
nextLessonStartTime.setText("");
} else if (les.getString("response") == "conflict") {
date = unixToTime(les.getLong("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText("Conflicting lessons");
nextLessonLocText.setText("Please use the app");
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
}
} catch (JSONException e) {
try {
date = unixToTime(les.getInt("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText(les.getJSONArray("subjects").get(0).toString());
nextLessonLocText.setText(les.getJSONArray("locations").get(0).toString());
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
} catch (JSONException ex) {
}
}
}
}
});
}
}
//Zermelo api stuff. (actually getting the next lesson)
public void makeRequest(RequestCallback callback) {
makeRequest(callback, false);
}
@SuppressLint("NewApi")
public void makeRequest(RequestCallback callback, boolean doPopups) {
//Get the necessary data from other activities.
loadData();
//Get the current week and year, format it to the right format (for example: 202310, 2023 -> year and 10 -> week)
LocalDateTime currentDate = LocalDateTime.now();
int currentWeekInt = currentDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
if (currentDate.getDayOfWeek().toString() == "SUNDAY") {
currentWeekInt -=1; //we do this because the school-week starts on monday, not sunday.
}
String currentYear = Integer.toString(currentDate.getYear());
// Check if the currentWeekString < 10, this causes an error when calling the api.
// The api expects the format yyyyww. When the currentWeekString is for example "5", the format becomes yyyyw, raising an error.
String currentWeekString;
if (currentWeekInt < 10) {
currentWeekString = "0" + currentWeekInt;
} else {
currentWeekString = Integer.toString(currentWeekInt);
}
String week = currentYear + currentWeekString;
String student = llnNummer;
// Make an API request for lesson data.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://" + zportal_name + ".zportal.nl/api/v3/liveschedule?access_token=" + access_token + "&student=" + student + "&week=" + week;
//check if there is an access_key.
if (access_token == null || access_token == "") {
if (doPopups) showToastMessage("No access_key was found\nPlease try again");
return;
}
//Notify the user that the api request is being made.
if (doPopups) showToastMessage("Calling zermelo API.\nThis might take a few seconds.");
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (doPopups) showToastMessage("Api request successful.");
callback.requestComplete(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (doPopups) showToastMessage("The api request failed.\nCheck your lln nummer and zportal name.");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public JSONObject processData(String data, boolean isFirst) {
return processData(data, isFirst, false, false);
}
public JSONObject processData(String data, boolean isFirst, boolean doPopups, boolean isComplication) {
JSONObject dataJSON;
JSONArray lessen;
try {
dataJSON = new JSONObject(data);
} catch (JSONException error) {
if (doPopups) showToastMessage("Error while parsing data.\nPlease try again.");
return null;
}
try {
lessen = ((JSONObject) (dataJSON.getJSONObject("response").getJSONArray("data").get(0))).getJSONArray("appointments");
} catch (JSONException error) {
if (doPopups) showToastMessage("Error.\nPlease try again.");
return null;
}
//Check of er lessen zijn in de week. (vakantie)
if (lessen.length() == 0) {
try {
return new JSONObject().put("response", "empty");
} catch (JSONException e) {
}
}
try {
ArrayList lessonTypes = new ArrayList<String>();
lessonTypes.add("lesson");
lessonTypes.add("exam");
lessonTypes.add("activity");
lessonTypes.add("talk");
lessonTypes.add("other");
lessonTypes.add("interlude");
lessonTypes.add("meeting");
lessonTypes.add("conflict");
long time = (System.currentTimeMillis() / 1000) - (timeDelay * 60L);
if (isComplication) {
time += 5*60; //The request made has the data for the update in 5 minutes. So this code suck (shutup its good nuff)
}
JSONObject les = null;
long bestDiff = Long.MAX_VALUE;
JSONObject laatsteLes = null;
long highscore = Long.MIN_VALUE;
for (int i = 0; i < lessen.length(); i++) {
JSONObject comparison = (JSONObject) lessen.get(i);
long start = comparison.getLong("start");
long diff = start - time;
if (diff > 0 && !comparison.getBoolean("cancelled") && lessonTypes.contains(comparison.getString("appointmentType"))) { //Geen lessen in het verleden, de les is niet uitgevallen het is iets van een les, geen stempeluur.
if (diff < bestDiff) { //Les is dichter bij start tijd
les = comparison;
bestDiff = diff;
}
if (unixToTime(start).getDayOfYear() == unixToTime(System.currentTimeMillis() / 1000).getDayOfYear()) { //Check if the lesson is today.
if (start > highscore) {
highscore = start;
laatsteLes = comparison;
}
}
}
}
//Check if it's the last day of school.
if (les == null) {
return new JSONObject().put("response", "empty");
}
//Check if the day has ended
else if (unixToTime(les.getLong("start")).getDayOfYear() != unixToTime(System.currentTimeMillis() / 1000).getDayOfYear()) {
return new JSONObject().put("response", "empty");
}
//Check if there are 2 lessons conflicting each other.
else if (les.getString("appointmentType").toLowerCase().contains("conflict")) {
return new JSONObject().put("response", "conflict").put("start", les.getLong("start"));
}
return isFirst ? les : laatsteLes;
} catch (JSONException e) {
if (doPopups) showToastMessage("Error while working with data.\nPlease try again.");
return null;
}
}
//make the time look nice.
public static List<String> niceTime(LocalDateTime date) {
HashMap<String, String> abbreviations = new HashMap<>();
abbreviations.put(String.valueOf(DayOfWeek.MONDAY), "ma");
abbreviations.put(String.valueOf(DayOfWeek.TUESDAY), "di");
abbreviations.put(String.valueOf(DayOfWeek.WEDNESDAY), "wo");
abbreviations.put(String.valueOf(DayOfWeek.THURSDAY), "do");
abbreviations.put(String.valueOf(DayOfWeek.FRIDAY), "vr");
int hour = date.getHour();
int minute = date.getMinute();
DayOfWeek day = date.getDayOfWeek();
String niceHour = checkForMissingZero(hour);
String niceMinute = checkForMissingZero(minute);
String niceDay = abbreviations.get(day.toString());
String resultTime = niceHour + ":" + niceMinute;
List<String> resultList = new ArrayList<>();
resultList.add(resultTime);
resultList.add(niceDay);
return resultList;
}
public static String checkForMissingZero(int x) {
String result = "";
if (x < 10) {
String hourString = Integer.toString(x);
result += "0" + hourString;
} else {
result += x;
}
return result;
}
//useful stuff
public static LocalDateTime unixToTime(long unix) {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(unix), TimeZone.getDefault().toZoneId());
}
public void showToastMessage(String message) {
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
}
//Getting the nessasary data.
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(shared_prefs, MODE_PRIVATE);
timeDelay = sharedPreferences.getInt(delaySeekBarStatusPref, 10);
llnNummer = sharedPreferences.getString(llnNummerPref, "");
access_token = sharedPreferences.getString(access_tokenPref, "");
zportal_name = sharedPreferences.getString(zportal_namePref, "griftland");
}
} | LolligeGerrit/Next_lesson_finder | Next lesson finder/src/main/java/com/example/schoolcalenderchecker/activity_main.java | 4,468 | //Check of er lessen zijn in de week. (vakantie) | line_comment | nl | package com.example.schoolcalenderchecker;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
public class activity_main extends Activity {
public static activity_main instance;
TextView nextLessonText;
TextView nextLessonLocText;
TextView nextLessonStartTime;
Button settingsButton;
Button authenticateButton;
Button requestButton;
TextView versionTitle;
public static final String shared_prefs = "sharedPrefs";
public static final String delaySeekBarStatusPref = "delaySeekBarStatusPref";
public static final String updatesSeekBarStatusPref = "updatesSeekBarStatusPref"; //TODO
public static final String llnNummerPref = "llnNummerPref";
public static final String access_tokenPref = "access_tokenPref";
public static final String zportal_namePref = "zportal_namePref";
String llnNummer;
int timeDelay;
String access_token;
String zportal_name = "griftland"; // Default value is "griftland"
long lastRequestTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextLessonText = findViewById(R.id.nextLessonText);
nextLessonLocText = findViewById(R.id.nextLessonLocText);
nextLessonStartTime = findViewById(R.id.nextLessonStartTime);
settingsButton = findViewById(R.id.settingsButton);
authenticateButton = findViewById(R.id.authenticateButton);
requestButton = findViewById(R.id.requestButton);
versionTitle = findViewById(R.id.versionTitleAuthenticate);
//set the version text
String versionCode = BuildConfig.VERSION_NAME;
String versionString = "v" + versionCode;
versionTitle.setText(versionString);
//OnClickListener settings
settingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//switch to the settings view
Intent intentSettingsView = new Intent(activity_main.this, activity_settings.class);
startActivity(intentSettingsView);
}
});
//OnClickListener authenticate
authenticateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//switch to the authenticate view
Intent intentAuthenticateView = new Intent(activity_main.this, activity_authenticate.class);
startActivity(intentAuthenticateView);
}
});
//OnClickListener make request
requestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (System.currentTimeMillis()-lastRequestTime >= 5000) {
lastRequestTime = System.currentTimeMillis();
makeRequest(new RequestCallback() {
@Override
public void requestComplete(String response) {
JSONObject les = processData(response, true);
LocalDateTime date;
if (les == null) {
nextLessonText.setText("No lesson was found.");
nextLessonLocText.setText("x");
nextLessonStartTime.setText("x");
} else {
try {
if (les.getString("response") == "empty") {
nextLessonText.setText("Done");
nextLessonLocText.setText("You are done for today!");
nextLessonStartTime.setText("");
} else if (les.getString("response") == "conflict") {
date = unixToTime(les.getInt("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText("Conflicting lessons");
nextLessonLocText.setText("Please use the app");
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
} else {
date = unixToTime(les.getInt("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText(les.getJSONArray("subjects").get(0).toString());
nextLessonLocText.setText(les.getJSONArray("locations").get(0).toString());
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
}
} catch (JSONException e) {
}
}
}
}, true);
}
}
});
//Make a request when we start the app
loadData();
if (access_token != null || access_token != "") {
makeRequest(new RequestCallback() {
@Override
public void requestComplete(String response) {
JSONObject les = processData(response, true);
LocalDateTime date = null;
if (les == null) {
nextLessonText.setText("No lesson was found.");
nextLessonLocText.setText("x");
nextLessonStartTime.setText("x");
} else {
try {
if (les.getString("response") == "empty") {
nextLessonText.setText("Done");
nextLessonLocText.setText("You are done for today!");
nextLessonStartTime.setText("");
} else if (les.getString("response") == "conflict") {
date = unixToTime(les.getLong("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText("Conflicting lessons");
nextLessonLocText.setText("Please use the app");
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
}
} catch (JSONException e) {
try {
date = unixToTime(les.getInt("start"));
List<String> niceTime = niceTime(date);
nextLessonText.setText(les.getJSONArray("subjects").get(0).toString());
nextLessonLocText.setText(les.getJSONArray("locations").get(0).toString());
nextLessonStartTime.setText(niceTime.get(1) + ": " + niceTime.get(0));
} catch (JSONException ex) {
}
}
}
}
});
}
}
//Zermelo api stuff. (actually getting the next lesson)
public void makeRequest(RequestCallback callback) {
makeRequest(callback, false);
}
@SuppressLint("NewApi")
public void makeRequest(RequestCallback callback, boolean doPopups) {
//Get the necessary data from other activities.
loadData();
//Get the current week and year, format it to the right format (for example: 202310, 2023 -> year and 10 -> week)
LocalDateTime currentDate = LocalDateTime.now();
int currentWeekInt = currentDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
if (currentDate.getDayOfWeek().toString() == "SUNDAY") {
currentWeekInt -=1; //we do this because the school-week starts on monday, not sunday.
}
String currentYear = Integer.toString(currentDate.getYear());
// Check if the currentWeekString < 10, this causes an error when calling the api.
// The api expects the format yyyyww. When the currentWeekString is for example "5", the format becomes yyyyw, raising an error.
String currentWeekString;
if (currentWeekInt < 10) {
currentWeekString = "0" + currentWeekInt;
} else {
currentWeekString = Integer.toString(currentWeekInt);
}
String week = currentYear + currentWeekString;
String student = llnNummer;
// Make an API request for lesson data.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://" + zportal_name + ".zportal.nl/api/v3/liveschedule?access_token=" + access_token + "&student=" + student + "&week=" + week;
//check if there is an access_key.
if (access_token == null || access_token == "") {
if (doPopups) showToastMessage("No access_key was found\nPlease try again");
return;
}
//Notify the user that the api request is being made.
if (doPopups) showToastMessage("Calling zermelo API.\nThis might take a few seconds.");
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (doPopups) showToastMessage("Api request successful.");
callback.requestComplete(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (doPopups) showToastMessage("The api request failed.\nCheck your lln nummer and zportal name.");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public JSONObject processData(String data, boolean isFirst) {
return processData(data, isFirst, false, false);
}
public JSONObject processData(String data, boolean isFirst, boolean doPopups, boolean isComplication) {
JSONObject dataJSON;
JSONArray lessen;
try {
dataJSON = new JSONObject(data);
} catch (JSONException error) {
if (doPopups) showToastMessage("Error while parsing data.\nPlease try again.");
return null;
}
try {
lessen = ((JSONObject) (dataJSON.getJSONObject("response").getJSONArray("data").get(0))).getJSONArray("appointments");
} catch (JSONException error) {
if (doPopups) showToastMessage("Error.\nPlease try again.");
return null;
}
//Check of<SUF>
if (lessen.length() == 0) {
try {
return new JSONObject().put("response", "empty");
} catch (JSONException e) {
}
}
try {
ArrayList lessonTypes = new ArrayList<String>();
lessonTypes.add("lesson");
lessonTypes.add("exam");
lessonTypes.add("activity");
lessonTypes.add("talk");
lessonTypes.add("other");
lessonTypes.add("interlude");
lessonTypes.add("meeting");
lessonTypes.add("conflict");
long time = (System.currentTimeMillis() / 1000) - (timeDelay * 60L);
if (isComplication) {
time += 5*60; //The request made has the data for the update in 5 minutes. So this code suck (shutup its good nuff)
}
JSONObject les = null;
long bestDiff = Long.MAX_VALUE;
JSONObject laatsteLes = null;
long highscore = Long.MIN_VALUE;
for (int i = 0; i < lessen.length(); i++) {
JSONObject comparison = (JSONObject) lessen.get(i);
long start = comparison.getLong("start");
long diff = start - time;
if (diff > 0 && !comparison.getBoolean("cancelled") && lessonTypes.contains(comparison.getString("appointmentType"))) { //Geen lessen in het verleden, de les is niet uitgevallen het is iets van een les, geen stempeluur.
if (diff < bestDiff) { //Les is dichter bij start tijd
les = comparison;
bestDiff = diff;
}
if (unixToTime(start).getDayOfYear() == unixToTime(System.currentTimeMillis() / 1000).getDayOfYear()) { //Check if the lesson is today.
if (start > highscore) {
highscore = start;
laatsteLes = comparison;
}
}
}
}
//Check if it's the last day of school.
if (les == null) {
return new JSONObject().put("response", "empty");
}
//Check if the day has ended
else if (unixToTime(les.getLong("start")).getDayOfYear() != unixToTime(System.currentTimeMillis() / 1000).getDayOfYear()) {
return new JSONObject().put("response", "empty");
}
//Check if there are 2 lessons conflicting each other.
else if (les.getString("appointmentType").toLowerCase().contains("conflict")) {
return new JSONObject().put("response", "conflict").put("start", les.getLong("start"));
}
return isFirst ? les : laatsteLes;
} catch (JSONException e) {
if (doPopups) showToastMessage("Error while working with data.\nPlease try again.");
return null;
}
}
//make the time look nice.
public static List<String> niceTime(LocalDateTime date) {
HashMap<String, String> abbreviations = new HashMap<>();
abbreviations.put(String.valueOf(DayOfWeek.MONDAY), "ma");
abbreviations.put(String.valueOf(DayOfWeek.TUESDAY), "di");
abbreviations.put(String.valueOf(DayOfWeek.WEDNESDAY), "wo");
abbreviations.put(String.valueOf(DayOfWeek.THURSDAY), "do");
abbreviations.put(String.valueOf(DayOfWeek.FRIDAY), "vr");
int hour = date.getHour();
int minute = date.getMinute();
DayOfWeek day = date.getDayOfWeek();
String niceHour = checkForMissingZero(hour);
String niceMinute = checkForMissingZero(minute);
String niceDay = abbreviations.get(day.toString());
String resultTime = niceHour + ":" + niceMinute;
List<String> resultList = new ArrayList<>();
resultList.add(resultTime);
resultList.add(niceDay);
return resultList;
}
public static String checkForMissingZero(int x) {
String result = "";
if (x < 10) {
String hourString = Integer.toString(x);
result += "0" + hourString;
} else {
result += x;
}
return result;
}
//useful stuff
public static LocalDateTime unixToTime(long unix) {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(unix), TimeZone.getDefault().toZoneId());
}
public void showToastMessage(String message) {
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
}
//Getting the nessasary data.
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(shared_prefs, MODE_PRIVATE);
timeDelay = sharedPreferences.getInt(delaySeekBarStatusPref, 10);
llnNummer = sharedPreferences.getString(llnNummerPref, "");
access_token = sharedPreferences.getString(access_tokenPref, "");
zportal_name = sharedPreferences.getString(zportal_namePref, "griftland");
}
} |
86767_4 | package be.pxl.collections.arraylist;
import java.util.ArrayList;
import java.util.List;
public class Theatre {
private String theatreName;
private List<Seat> seats = new ArrayList<>();
private int seatsPerRow;
private int numRows;
public Theatre(String theatreName, int numRows, int seatsPerRow) {
this.theatreName = theatreName;
this.seatsPerRow = seatsPerRow;
this.numRows = numRows;
// voeg alle stoelen toe in het theater, nummer alle stoelen.
// de eerste rij stoelen is genummerd vanaf A1, A2,...
// de tweede rij stoelen is genummerd vanaf B1, B2,...
}
public void displayMap() {
int count = 0;
for (Seat seat : seats) {
System.out.print(seat + " ");
count++;
if (count % seatsPerRow == 0) {
System.out.println();
}
}
}
public boolean reservateSeat(String seatNumber) {
// implementeer de reservatie van een stoel,
// gebruik hierbij de methode getSeatBySeatNumber
}
private Seat getSeatBySeatNumber(String seatNumber) {
// implementeer het opzoeken van een stoel adhv een stoelnummer
// hoelang duurt het om stoel A1 te zoeken
// hoelang duurt het om de laatste stoel in het theater te zoeken
// probeer dit eens uit het het hoofdprogramma
// stel eventueel nog alternatieven voor
}
private class Seat {
private String seatNumber;
private boolean reserved = false;
public Seat(String seatNumber) {
this.seatNumber = seatNumber;
}
public String getSeatNumber() {
return seatNumber;
}
public boolean reserve() {
if (isReserved()) {
System.out.println("Seat " + seatNumber + " already reserved.");
return false;
}
reserved = true;
return reserved;
}
public boolean isReserved() {
return reserved;
}
@Override
public String toString() {
return (reserved ? "*" : "") + seatNumber + (reserved ? "*" : "");
}
}
}
| Lordrin/week6-collections-overview-skelet | src/be/pxl/collections/arraylist/Theatre.java | 619 | // gebruik hierbij de methode getSeatBySeatNumber | line_comment | nl | package be.pxl.collections.arraylist;
import java.util.ArrayList;
import java.util.List;
public class Theatre {
private String theatreName;
private List<Seat> seats = new ArrayList<>();
private int seatsPerRow;
private int numRows;
public Theatre(String theatreName, int numRows, int seatsPerRow) {
this.theatreName = theatreName;
this.seatsPerRow = seatsPerRow;
this.numRows = numRows;
// voeg alle stoelen toe in het theater, nummer alle stoelen.
// de eerste rij stoelen is genummerd vanaf A1, A2,...
// de tweede rij stoelen is genummerd vanaf B1, B2,...
}
public void displayMap() {
int count = 0;
for (Seat seat : seats) {
System.out.print(seat + " ");
count++;
if (count % seatsPerRow == 0) {
System.out.println();
}
}
}
public boolean reservateSeat(String seatNumber) {
// implementeer de reservatie van een stoel,
// gebruik hierbij<SUF>
}
private Seat getSeatBySeatNumber(String seatNumber) {
// implementeer het opzoeken van een stoel adhv een stoelnummer
// hoelang duurt het om stoel A1 te zoeken
// hoelang duurt het om de laatste stoel in het theater te zoeken
// probeer dit eens uit het het hoofdprogramma
// stel eventueel nog alternatieven voor
}
private class Seat {
private String seatNumber;
private boolean reserved = false;
public Seat(String seatNumber) {
this.seatNumber = seatNumber;
}
public String getSeatNumber() {
return seatNumber;
}
public boolean reserve() {
if (isReserved()) {
System.out.println("Seat " + seatNumber + " already reserved.");
return false;
}
reserved = true;
return reserved;
}
public boolean isReserved() {
return reserved;
}
@Override
public String toString() {
return (reserved ? "*" : "") + seatNumber + (reserved ? "*" : "");
}
}
}
|
33329_4 | package domein;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import persistentie.PersistentieController;
public class Garage {
private final File auto;
private final File onderhoud;
private Map<String, Auto> autoMap;
private Map<String, List<Onderhoud>> autoOnderhoudMap;
private List<Set<Auto>> overzichtLijstVanAutos;
private final int AANTAL_OVERZICHTEN = 3;
private int overzichtteller;
public Garage(String bestandAuto, String bestandOnderhoud) {
auto = new File(bestandAuto);
onderhoud = new File(bestandOnderhoud);
initGarage();
}
private void initGarage() {
PersistentieController persistentieController = new PersistentieController(auto, onderhoud);
// Set<Auto> inlezen - stap1
Set<Auto> autoSet = new HashSet<>(persistentieController.geefAutos());
System.out.println("STAP 1");
autoSet.forEach(auto -> System.out.println(auto));
// Maak map van auto's: volgens nummerplaat - stap2
autoMap = omzettenNaarAutoMap(autoSet);
System.out.println("STAP 2");
autoMap.forEach((k, v) -> System.out.printf("%s %s%n", k, v));
// Onderhoud inlezen - stap3
List<Onderhoud> onderhoudLijst = persistentieController.geefOnderhoudVanAutos();
System.out.println("STAP 3 : " + onderhoudLijst);
onderhoudLijst.forEach(o->System.out.println(o));
// lijst sorteren - stap4
sorteren(onderhoudLijst);
System.out.println("STAP 4");
onderhoudLijst.forEach(o->System.out.println(o));
// lijst samenvoegen - stap5
aangrenzendePeriodenSamenvoegen(onderhoudLijst);
System.out.println("STAP 5");
onderhoudLijst.forEach(o->System.out.println(o));
// Maak map van onderhoud: volgens nummerplaat - stap6
autoOnderhoudMap = omzettenNaarOnderhoudMap(onderhoudLijst);
System.out.println("STAP 6");
autoOnderhoudMap.forEach((k,v)->System.out.printf("%s %s%n",k,v));
// Maak overzicht: set van auto's - stap7
overzichtLijstVanAutos = maakOverzicht(autoOnderhoudMap);
System.out.println("STAP 7");
overzichtLijstVanAutos.forEach(System.out::println);
}
// Maak map van auto's: volgens nummerplaat - stap2
private Map<String, Auto> omzettenNaarAutoMap(Set<Auto> autoSet) {
return autoSet.stream().collect(Collectors.toMap(Auto::getNummerplaat, a -> a));
}
// lijst sorteren - stap4
private void sorteren(List<Onderhoud> lijstOnderhoud) {
lijstOnderhoud.sort(Comparator.comparing(Onderhoud::getNummerplaat).thenComparing(Onderhoud::getBegindatum));
}
// lijst samenvoegen - stap5
private void aangrenzendePeriodenSamenvoegen(List<Onderhoud> lijstOnderhoud) {
//java 7
Onderhoud onderhoud = null;
Onderhoud onderhoudNext = null;
Iterator<Onderhoud> it = lijstOnderhoud.iterator();
while (it.hasNext()) {
onderhoud = onderhoudNext;
onderhoudNext = it.next();
if (onderhoud != null && onderhoud.getNummerplaat().equals(onderhoudNext.getNummerplaat())) {
if (onderhoud.getEinddatum().plusDays(1).equals(onderhoudNext.getBegindatum())) {// samenvoegen:
onderhoud.setEinddatum(onderhoudNext.getEinddatum());
it.remove();
onderhoudNext = onderhoud;
}
}
}
}
// Maak map van onderhoud: volgens nummerplaat - stap6
private Map<String, List<Onderhoud>> omzettenNaarOnderhoudMap(List<Onderhoud> onderhoudLijst) {
return onderhoudLijst.stream().collect(Collectors.groupingBy(Onderhoud::getNummerplaat));
}
// Hulpmethode - nodig voor stap 7
private int sizeToCategorie(int size) {
return switch (size) {
case 0, 1 -> 0;
case 2, 3 -> 1;
default -> 2;
};
}
// Maak overzicht: set van auto's - stap7
private List<Set<Auto>> maakOverzicht(Map<String, List<Onderhoud>> autoOnderhoudMap) {
// Hint:
// van Map<String, List<Onderhoud>>
// naar Map<Integer, Set<Auto>> (hulpmethode gebruiken)
// naar List<Set<Auto>>
return autoOnderhoudMap.entrySet().stream().collect(Collectors.groupingBy(entry->sizeToCategory(entry.getValue().size()),
TreeMap::new,Collectors.mapping(entry-> autoMap.get(entry.getKey()),Collectors.toSet()).values().stream()
.collect(Collectors.toList());
}
//Oefening DomeinController:
public String autoMap_ToString() {
// String res = autoMap.
return null;
}
public String autoOnderhoudMap_ToString() {
String res = autoOnderhoudMap.toString();
return res;
}
public String overzicht_ToString() {
overzichtteller = 1;
// String res = overzichtLijstVanAutos.
return null;
}
}
| LuccaVanVeerdeghem/asd | ASDI_Java_Garage_start/src/domein/Garage.java | 1,740 | // lijst samenvoegen - stap5 | line_comment | nl | package domein;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import persistentie.PersistentieController;
public class Garage {
private final File auto;
private final File onderhoud;
private Map<String, Auto> autoMap;
private Map<String, List<Onderhoud>> autoOnderhoudMap;
private List<Set<Auto>> overzichtLijstVanAutos;
private final int AANTAL_OVERZICHTEN = 3;
private int overzichtteller;
public Garage(String bestandAuto, String bestandOnderhoud) {
auto = new File(bestandAuto);
onderhoud = new File(bestandOnderhoud);
initGarage();
}
private void initGarage() {
PersistentieController persistentieController = new PersistentieController(auto, onderhoud);
// Set<Auto> inlezen - stap1
Set<Auto> autoSet = new HashSet<>(persistentieController.geefAutos());
System.out.println("STAP 1");
autoSet.forEach(auto -> System.out.println(auto));
// Maak map van auto's: volgens nummerplaat - stap2
autoMap = omzettenNaarAutoMap(autoSet);
System.out.println("STAP 2");
autoMap.forEach((k, v) -> System.out.printf("%s %s%n", k, v));
// Onderhoud inlezen - stap3
List<Onderhoud> onderhoudLijst = persistentieController.geefOnderhoudVanAutos();
System.out.println("STAP 3 : " + onderhoudLijst);
onderhoudLijst.forEach(o->System.out.println(o));
// lijst sorteren - stap4
sorteren(onderhoudLijst);
System.out.println("STAP 4");
onderhoudLijst.forEach(o->System.out.println(o));
// lijst samenvoegen<SUF>
aangrenzendePeriodenSamenvoegen(onderhoudLijst);
System.out.println("STAP 5");
onderhoudLijst.forEach(o->System.out.println(o));
// Maak map van onderhoud: volgens nummerplaat - stap6
autoOnderhoudMap = omzettenNaarOnderhoudMap(onderhoudLijst);
System.out.println("STAP 6");
autoOnderhoudMap.forEach((k,v)->System.out.printf("%s %s%n",k,v));
// Maak overzicht: set van auto's - stap7
overzichtLijstVanAutos = maakOverzicht(autoOnderhoudMap);
System.out.println("STAP 7");
overzichtLijstVanAutos.forEach(System.out::println);
}
// Maak map van auto's: volgens nummerplaat - stap2
private Map<String, Auto> omzettenNaarAutoMap(Set<Auto> autoSet) {
return autoSet.stream().collect(Collectors.toMap(Auto::getNummerplaat, a -> a));
}
// lijst sorteren - stap4
private void sorteren(List<Onderhoud> lijstOnderhoud) {
lijstOnderhoud.sort(Comparator.comparing(Onderhoud::getNummerplaat).thenComparing(Onderhoud::getBegindatum));
}
// lijst samenvoegen - stap5
private void aangrenzendePeriodenSamenvoegen(List<Onderhoud> lijstOnderhoud) {
//java 7
Onderhoud onderhoud = null;
Onderhoud onderhoudNext = null;
Iterator<Onderhoud> it = lijstOnderhoud.iterator();
while (it.hasNext()) {
onderhoud = onderhoudNext;
onderhoudNext = it.next();
if (onderhoud != null && onderhoud.getNummerplaat().equals(onderhoudNext.getNummerplaat())) {
if (onderhoud.getEinddatum().plusDays(1).equals(onderhoudNext.getBegindatum())) {// samenvoegen:
onderhoud.setEinddatum(onderhoudNext.getEinddatum());
it.remove();
onderhoudNext = onderhoud;
}
}
}
}
// Maak map van onderhoud: volgens nummerplaat - stap6
private Map<String, List<Onderhoud>> omzettenNaarOnderhoudMap(List<Onderhoud> onderhoudLijst) {
return onderhoudLijst.stream().collect(Collectors.groupingBy(Onderhoud::getNummerplaat));
}
// Hulpmethode - nodig voor stap 7
private int sizeToCategorie(int size) {
return switch (size) {
case 0, 1 -> 0;
case 2, 3 -> 1;
default -> 2;
};
}
// Maak overzicht: set van auto's - stap7
private List<Set<Auto>> maakOverzicht(Map<String, List<Onderhoud>> autoOnderhoudMap) {
// Hint:
// van Map<String, List<Onderhoud>>
// naar Map<Integer, Set<Auto>> (hulpmethode gebruiken)
// naar List<Set<Auto>>
return autoOnderhoudMap.entrySet().stream().collect(Collectors.groupingBy(entry->sizeToCategory(entry.getValue().size()),
TreeMap::new,Collectors.mapping(entry-> autoMap.get(entry.getKey()),Collectors.toSet()).values().stream()
.collect(Collectors.toList());
}
//Oefening DomeinController:
public String autoMap_ToString() {
// String res = autoMap.
return null;
}
public String autoOnderhoudMap_ToString() {
String res = autoOnderhoudMap.toString();
return res;
}
public String overzicht_ToString() {
overzichtteller = 1;
// String res = overzichtLijstVanAutos.
return null;
}
}
|
138205_22 | package agendaStarter;
import exception.InformationRequiredException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import domein.*;
import java.util.*;
public class TestDrive {
private final static Contact contactData[] = {
new Contact("Van Schoor", "Johan", "Lector", "Hogeschool Gent"),
new Contact("Samyn", "Stefaan", "Lector", "Hogeschool Gent"),
new Contact("Malfait", "Irina", "Lector", "Hogeschool Gent"),
new Contact("De Donder", "Margot", "Lector", "Hogeschool Gent"),
new Contact("Decorte", "Johan", "Lector", "Hogeschool Gent"),
new Contact("Samyn", "Karine", "Lector", "Hogeschool Gent")
};
private Appointment appt;
//TODO attribut(en) voor aanmaak van een appointment
//
//
//End TODO attribut(en)
public static void main(String[] args) {
new TestDrive().run();
}
private List<Contact> createAttendees(int numberToCreate) {
List<Contact> group = new ArrayList<>();
for (int i = 0; i < numberToCreate; i++) {
group.add(getContact(i));
}
return group;
}
private Contact getContact(int index) {
return contactData[index % contactData.length];
}
private void run() {
System.out.println("Creating an Appointment ");
//TODO maak gewone afspraak zonder fout:
//
// Start datum = LocalDateTime.of(2022, 7, 22, 12, 30)
// Locatie = new Location("Hogeschool Gent, D2.014")
// Beschrijving = "Project Demo"
// uitgenodigden = createAttendees(4)
try {
appt = new Appointment.Builder()
.description("Project demo")
.location(new Location("Hogeschool gent, D2.014"))
.attendees(createAttendees(4))
.startDate(LocalDateTime.of(2023, 04,7,12,40))
.build();
//Afdruk resultaat
System.out.println("Successfully created an Appointment.");
System.out.println("Appointment information:");
System.out.println(appt);
System.out.println();
//vervolg...(als fouten)
}catch(InformationRequiredException ire) {
printExceptions(ire);
}
System.out.println("Creating a meeting : enddate is missing");
//TODO maak een meeting met fout:
//
//Start datum = LocalDateTime.of(2022, 3, 21, 12, 30)
//Locatie = new Location("Hogeschool Gent, B3.020")
//Beschrijving = "OOO III"
//uitgenodigden = createAttendees(4)
try {
appt = new Appointment.MeetingBuilder()
.description("Project demo")
.location(new Location("Hogeschool gent, D2.014"))
.attendees(createAttendees(4))
.startDate(LocalDateTime.of(2023, 04,7,12,40))
.build();
//Afdruk resultaat (zal falen)
System.out.println("Successfully created an Appointment.");
System.out.println("Appointment information:");
System.out.println(appt);
System.out.println();
//vervolg... (als fouten)
}catch(InformationRequiredException ire) {
printExceptions(ire);
}
System.out.println("Meeting : all items are provided\n");
//TODO maak een meeting met fout:
//
//Start datum =LocalDateTime.of(2022, 4, 1, 10, 00)
//Eind datum = LocalDateTime.of(2022, 4, 1, 11, 30),
//Locatie = new Location("Hogeschool Gent, B1.032")
//Beschrijving = "Project II Meeting"
//uitgenodigden = createAttendees(2)
try {
appt = new Appointment.MeetingBuilder()
.description("Project demo")
.location(new Location("Hogeschool gent, D2.014"))
.attendees(createAttendees(4))
.startDate(LocalDateTime.of(2023, 04,7,12,40))
.endDate(LocalDateTime.of(2023, 04,7,16,00))
.build();
//Afdruk resultaat
System.out.println("Successfully created an Appointment.");
System.out.println("Appointment information:");
System.out.println(appt);
System.out.println();
//vervolg...(als fouten)
}catch(InformationRequiredException ire) {
printExceptions(ire);
}
//
}
//TODO een printmethode voor bij fouten : wat er voor de constructie ontbreekt
//
//public void print...
public void printExceptions(InformationRequiredException ire) {
System.out.println(ire.getMessage());
ire.getInformationRequired().forEach(e->System.out.println(e));
}
//
//END TODO printmethode wat ontbreekt
} | LuccaVanVeerdeghem/asd2 | ASDII_AgendaStarter_BuilderVariant/src/agendaStarter/TestDrive.java | 1,565 | //END TODO printmethode wat ontbreekt | line_comment | nl | package agendaStarter;
import exception.InformationRequiredException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import domein.*;
import java.util.*;
public class TestDrive {
private final static Contact contactData[] = {
new Contact("Van Schoor", "Johan", "Lector", "Hogeschool Gent"),
new Contact("Samyn", "Stefaan", "Lector", "Hogeschool Gent"),
new Contact("Malfait", "Irina", "Lector", "Hogeschool Gent"),
new Contact("De Donder", "Margot", "Lector", "Hogeschool Gent"),
new Contact("Decorte", "Johan", "Lector", "Hogeschool Gent"),
new Contact("Samyn", "Karine", "Lector", "Hogeschool Gent")
};
private Appointment appt;
//TODO attribut(en) voor aanmaak van een appointment
//
//
//End TODO attribut(en)
public static void main(String[] args) {
new TestDrive().run();
}
private List<Contact> createAttendees(int numberToCreate) {
List<Contact> group = new ArrayList<>();
for (int i = 0; i < numberToCreate; i++) {
group.add(getContact(i));
}
return group;
}
private Contact getContact(int index) {
return contactData[index % contactData.length];
}
private void run() {
System.out.println("Creating an Appointment ");
//TODO maak gewone afspraak zonder fout:
//
// Start datum = LocalDateTime.of(2022, 7, 22, 12, 30)
// Locatie = new Location("Hogeschool Gent, D2.014")
// Beschrijving = "Project Demo"
// uitgenodigden = createAttendees(4)
try {
appt = new Appointment.Builder()
.description("Project demo")
.location(new Location("Hogeschool gent, D2.014"))
.attendees(createAttendees(4))
.startDate(LocalDateTime.of(2023, 04,7,12,40))
.build();
//Afdruk resultaat
System.out.println("Successfully created an Appointment.");
System.out.println("Appointment information:");
System.out.println(appt);
System.out.println();
//vervolg...(als fouten)
}catch(InformationRequiredException ire) {
printExceptions(ire);
}
System.out.println("Creating a meeting : enddate is missing");
//TODO maak een meeting met fout:
//
//Start datum = LocalDateTime.of(2022, 3, 21, 12, 30)
//Locatie = new Location("Hogeschool Gent, B3.020")
//Beschrijving = "OOO III"
//uitgenodigden = createAttendees(4)
try {
appt = new Appointment.MeetingBuilder()
.description("Project demo")
.location(new Location("Hogeschool gent, D2.014"))
.attendees(createAttendees(4))
.startDate(LocalDateTime.of(2023, 04,7,12,40))
.build();
//Afdruk resultaat (zal falen)
System.out.println("Successfully created an Appointment.");
System.out.println("Appointment information:");
System.out.println(appt);
System.out.println();
//vervolg... (als fouten)
}catch(InformationRequiredException ire) {
printExceptions(ire);
}
System.out.println("Meeting : all items are provided\n");
//TODO maak een meeting met fout:
//
//Start datum =LocalDateTime.of(2022, 4, 1, 10, 00)
//Eind datum = LocalDateTime.of(2022, 4, 1, 11, 30),
//Locatie = new Location("Hogeschool Gent, B1.032")
//Beschrijving = "Project II Meeting"
//uitgenodigden = createAttendees(2)
try {
appt = new Appointment.MeetingBuilder()
.description("Project demo")
.location(new Location("Hogeschool gent, D2.014"))
.attendees(createAttendees(4))
.startDate(LocalDateTime.of(2023, 04,7,12,40))
.endDate(LocalDateTime.of(2023, 04,7,16,00))
.build();
//Afdruk resultaat
System.out.println("Successfully created an Appointment.");
System.out.println("Appointment information:");
System.out.println(appt);
System.out.println();
//vervolg...(als fouten)
}catch(InformationRequiredException ire) {
printExceptions(ire);
}
//
}
//TODO een printmethode voor bij fouten : wat er voor de constructie ontbreekt
//
//public void print...
public void printExceptions(InformationRequiredException ire) {
System.out.println(ire.getMessage());
ire.getInformationRequired().forEach(e->System.out.println(e));
}
//
//END TODO<SUF>
} |
208352_3 | /*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI licenses this file
// to you 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.eigenbase.applib.resource;
// NOTE: This class gets compiled independently of everything else so that
// resource generation can use reflection. That means it must have no
// dependencies on other Eigenbase code.
import java.util.logging.*;
import org.eigenbase.util.*;
/**
* Exception class for Applib
*
* @author Elizabeth Lin
* @version $Id$
*/
public class ApplibException
extends EigenbaseException
{
//~ Static fields/initializers ---------------------------------------------
private static Logger tracer =
Logger.getLogger(ApplibException.class.getName());
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ApplibException object.
*
* @param message error message
* @param cause underlying cause
*/
public ApplibException(String message, Throwable cause)
{
super(message, cause);
// TODO: Force the caller to pass in a Logger as a trace argument for
// better context. Need to extend ResGen for this.
//tracer.throwing("ApplibException", "constructor", this);
//tracer.severe(toString());
}
}
// End ApplibException.java
| LucidDB/luciddb | extensions/applib/src/org/eigenbase/applib/resource/ApplibException.java | 496 | // dependencies on other Eigenbase code. | line_comment | nl | /*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI licenses this file
// to you 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.eigenbase.applib.resource;
// NOTE: This class gets compiled independently of everything else so that
// resource generation can use reflection. That means it must have no
// dependencies on<SUF>
import java.util.logging.*;
import org.eigenbase.util.*;
/**
* Exception class for Applib
*
* @author Elizabeth Lin
* @version $Id$
*/
public class ApplibException
extends EigenbaseException
{
//~ Static fields/initializers ---------------------------------------------
private static Logger tracer =
Logger.getLogger(ApplibException.class.getName());
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ApplibException object.
*
* @param message error message
* @param cause underlying cause
*/
public ApplibException(String message, Throwable cause)
{
super(message, cause);
// TODO: Force the caller to pass in a Logger as a trace argument for
// better context. Need to extend ResGen for this.
//tracer.throwing("ApplibException", "constructor", this);
//tracer.severe(toString());
}
}
// End ApplibException.java
|
122953_0 | package be.kdg.fill.views.gamemenu.addworld;
import be.kdg.fill.FillApplication;
import be.kdg.fill.models.core.Level;
import be.kdg.fill.models.core.World;
import be.kdg.fill.models.helpers.WorldLoader;
import be.kdg.fill.views.Presenter;
import be.kdg.fill.views.gamemenu.GameMenuPresenter;
import be.kdg.fill.views.gamemenu.addworld.helpers.CheckBoxes;
import be.kdg.fill.views.gamemenu.addworld.helpers.LevelCreationBox;
import be.kdg.fill.views.gamemenu.worldselect.WorldSelectPresenter;
import be.kdg.fill.views.gamemenu.worldselect.WorldSelectView;
import javafx.event.ActionEvent;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
public class AddWorldPresenter implements Presenter {
private AddWorldView view;
private GameMenuPresenter parent;
private List<LevelCreationBox> levelCreationBoxes;
private List<CheckBoxes> checkBoxesList;
private List<Level> levels;
private int nextId = 1;
public static final String SCREEN_NAME = "addworld";
public AddWorldPresenter(AddWorldView addWorldView, GameMenuPresenter parent)
{
this.view = addWorldView;
this.parent = parent;
this.levelCreationBoxes = new ArrayList<>();
this.checkBoxesList = new ArrayList<>();
this.levels = new ArrayList<>();
addEventHandlers();
}
private void addEventHandlers()
{
view.getBackButton().setOnAction(this::handleBackButton);
view.getAddButton().setOnAction(this::handleAddButton);
view.getConfirmationButton().setOnAction(this::handleConfirmationButton);
view.getSavingButton().setOnAction(this::handleSavingButton);
}
private void handleBackButton(ActionEvent event)
{
parent.getSubScreenManager().switchBack();
resetTheListsAndView();
}
private void handleAddButton(ActionEvent actionEvent)
{
try {
AddWorldInputControl();
addLevelInputInfo();
view.getErrorLabel().setText("");
} catch (Exception e) {
view.getErrorLabel().setText(e.getMessage());
}
}
private void handleConfirmationButton(ActionEvent actionEvent)
{
boolean firstStepControled;
try {
AddWorldInputControl();
view.getErrorLabel().setText("");
firstStepControled = true;
} catch (Exception e) {
view.getErrorLabel().setText(e.getMessage());
firstStepControled = false;
}
for (LevelCreationBox box : levelCreationBoxes) {
try {
box.getErrorsLabelLevelCreationBox().setText("");
levelCreationBoxInputControl(box);
addCheckBoxes();
} catch (Exception e) {
box.getErrorsLabelLevelCreationBox().setText(e.getMessage());
}
}
if (firstStepControled && levelCreationBoxes.isEmpty()) {
view.getErrorLabel().setText("This action can be taken after you add some levels to this world!");
}
}
private void handleSavingButton(ActionEvent actionEvent)
{
boolean firstStepControled = false;
boolean secondStepControled = false;
boolean worldAddedSuccesfully = false;
//input eerste stap checken
try {
AddWorldInputControl();
view.getErrorLabel().setText("");
firstStepControled = true;
} catch (Exception e) {
view.getErrorLabel().setText(e.getMessage());
}
//input 2e stap checken
if (firstStepControled) {
for (LevelCreationBox box : levelCreationBoxes) {
try {
box.getErrorsLabelLevelCreationBox().setText("");
levelCreationBoxInputControl(box);
checkBoxesListControl();
secondStepControled = true;
} catch (Exception e) {
box.getErrorsLabelLevelCreationBox().setText(e.getMessage());
}
}
}
//3e stap opslaan van de world
if (secondStepControled) {
try {
for (LevelCreationBox box : levelCreationBoxes) {
box.getErrorsLabelLevelCreationBox().setText("");
levelCreationBoxInputControl(box);
checkBoxesListControl();
}
AddWorldInputControl();
view.getErrorLabel().setText("");
//nagaan of de positie 1 is
addLevels();
//alle opgeslagen data van de levels wissen
levels.clear();
//wanneer de exceptions zijn opgevangen
//dan met deze boolean alle levels opslaan in de world
//en deze operatie beeindigen
worldAddedSuccesfully = true;
} catch (Exception e) {
for (LevelCreationBox box : levelCreationBoxes) {
box.getErrorsLabelLevelCreationBox().setText(e.getMessage());
}
}
}
if (!worldAddedSuccesfully) {
if (firstStepControled && levelCreationBoxes.isEmpty()) {
view.getErrorLabel().setText("This action can be taken after you add some levels to this world!");
}
}
if (worldAddedSuccesfully) {
addLevels();
addWorld();
resetTheListsAndView();
lastDialog();
}
if (worldAddedSuccesfully) {
boolean worldLoaded = false;
while (!worldLoaded) {
try {
WorldSelectPresenter worldSelectPresenter = new WorldSelectPresenter(new WorldSelectView(), parent);
worldSelectPresenter.reload();
parent.getWorldLoader().loadWorlds();
worldLoaded = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void addLevelInputInfo()
{
LevelCreationBox levelCreationBox = new LevelCreationBox();
levelCreationBox.setId(nextId++);
levelCreationBoxes.add(levelCreationBox);
view.getvBox().getChildren().addAll(levelCreationBox);
}
public void addCheckBoxes()
{
VBox vBox = new VBox(20);
checkBoxesList.clear();
for (LevelCreationBox box : levelCreationBoxes) {
int rows = box.getRows();
int cols = box.getCols();
GridPane gridPane = new GridPane();
gridPane.add(box, 0, 0);
CheckBoxes checkBoxes = new CheckBoxes(rows, cols);
checkBoxesList.add(checkBoxes);
gridPane.add(checkBoxes, 1, 0);
vBox.getChildren().addAll(gridPane);
}
view.getvBox().getChildren().clear();
view.getvBox().getChildren().add(vBox);
}
public void addLevels()
{
List<int[][]> checkBoxesStatusMatrix = new ArrayList<>();
for (CheckBoxes checkBoxes : checkBoxesList) {
int[][] checkBoxStatus = checkBoxes.getCheckBoxStatus();
checkBoxesStatusMatrix.add(checkBoxStatus);
}
int idJsonLevel = 0;
for (LevelCreationBox levelCreationBox : levelCreationBoxes) {
int[] startPos = levelCreationBox.startPosCoordination();
if (checkBoxesStatusMatrix.get(idJsonLevel)[startPos[0]][startPos[1]] == 0) {
levels.clear();
throw new IllegalStateException("Checkbox value at start position cannot be 0!");
}
levels.add(new Level(idJsonLevel + 1, checkBoxesStatusMatrix.get(idJsonLevel), startPos));
idJsonLevel++;
}
}
private void addWorld()
{
String worldName = String.valueOf(view.getWorldName().getField().getText());
String difficultyName = String.valueOf(view.getDifficultyName().getField().getText());
World world = new World(worldName, "images/admin-foto.jpg", difficultyName);
WorldLoader worldLoader = parent.getWorldLoader();
for (Level level : levels) {
world.addLevel(level);
}
worldLoader.addWorld(world);
worldLoader.saveWorld(world.getId());
}
private void AddWorldInputControl()
{
String worldName = String.valueOf(view.getWorldName().getField().getText());
String difficultyName = String.valueOf(view.getDifficultyName().getField().getText());
if (worldName == null || worldName.length() < 4 || worldName.length() > 15) {
throw new IllegalArgumentException("World name must be between 4 and 15 characters long");
} else if (difficultyName == null || difficultyName.length() < 4 || difficultyName.length() > 15) {
throw new IllegalArgumentException("Difficulty name must be between 4 and 15 characters long");
}
}
private void checkBoxesListControl()
{
if (checkBoxesList.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("First you need to get checkboxes!");
}
}
private void levelCreationBoxInputControl(LevelCreationBox box)
{
int rows = box.getRows();
int cols = box.getCols();
if (rows > 20 || rows < 1) {
throw new IllegalArgumentException("Rows value must be between 1 and 20!");
} else if (cols > 20 || cols < 1) {
throw new IllegalArgumentException("Columns value must be between 1 and 20!");
}
int[] positionCheck = box.startPosCoordination();
if (positionCheck[0] >= rows || positionCheck[0] < 0) {
throw new IllegalArgumentException("The X-coordinate must be within the range of 0 to (row - 1)");
} else if (positionCheck[1] >= cols || positionCheck[1] < 0) {
throw new IllegalArgumentException("The Y-coordinate must be within the range of 0 to (column - 1)");
}
}
private void resetTheListsAndView()
{
view.getWorldName().getField().clear();
view.getDifficultyName().getField().clear();
levelCreationBoxes.clear();
checkBoxesList.clear();
levels.clear();
this.nextId = 1;
view.getErrorLabel().setText("");
view.getvBox().getChildren().clear();
}
private void lastDialog()
{
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle("World succesfully added!");
dialog.setHeaderText("What's next?");
ImageView imageView = new ImageView(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png")));
dialog.setGraphic(imageView);
dialog.setContentText("You can leave this page or add some more levels.");
((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().add(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png")));
ButtonType backButton = new ButtonType("Leave", ButtonBar.ButtonData.OK_DONE);
ButtonType addAnotherWorldButton = new ButtonType("Add another world", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(backButton, addAnotherWorldButton);
dialog.getDialogPane().getScene().getWindow().setOnCloseRequest(event -> dialog.close());
dialog.showAndWait().ifPresent(choice -> {
if (choice == backButton) {
parent.getSubScreenManager().switchScreen("worldselect");
} else if (choice == addAnotherWorldButton) {
parent.getSubScreenManager().getCurrentScreen();
}
});
}
@Override
public AddWorldView getView()
{
return this.view;
}
@Override
public String getScreenName()
{
return SCREEN_NAME;
}
} | Luciffffer/FILL | src/main/java/be/kdg/fill/views/gamemenu/addworld/AddWorldPresenter.java | 3,378 | //input eerste stap checken | line_comment | nl | package be.kdg.fill.views.gamemenu.addworld;
import be.kdg.fill.FillApplication;
import be.kdg.fill.models.core.Level;
import be.kdg.fill.models.core.World;
import be.kdg.fill.models.helpers.WorldLoader;
import be.kdg.fill.views.Presenter;
import be.kdg.fill.views.gamemenu.GameMenuPresenter;
import be.kdg.fill.views.gamemenu.addworld.helpers.CheckBoxes;
import be.kdg.fill.views.gamemenu.addworld.helpers.LevelCreationBox;
import be.kdg.fill.views.gamemenu.worldselect.WorldSelectPresenter;
import be.kdg.fill.views.gamemenu.worldselect.WorldSelectView;
import javafx.event.ActionEvent;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
public class AddWorldPresenter implements Presenter {
private AddWorldView view;
private GameMenuPresenter parent;
private List<LevelCreationBox> levelCreationBoxes;
private List<CheckBoxes> checkBoxesList;
private List<Level> levels;
private int nextId = 1;
public static final String SCREEN_NAME = "addworld";
public AddWorldPresenter(AddWorldView addWorldView, GameMenuPresenter parent)
{
this.view = addWorldView;
this.parent = parent;
this.levelCreationBoxes = new ArrayList<>();
this.checkBoxesList = new ArrayList<>();
this.levels = new ArrayList<>();
addEventHandlers();
}
private void addEventHandlers()
{
view.getBackButton().setOnAction(this::handleBackButton);
view.getAddButton().setOnAction(this::handleAddButton);
view.getConfirmationButton().setOnAction(this::handleConfirmationButton);
view.getSavingButton().setOnAction(this::handleSavingButton);
}
private void handleBackButton(ActionEvent event)
{
parent.getSubScreenManager().switchBack();
resetTheListsAndView();
}
private void handleAddButton(ActionEvent actionEvent)
{
try {
AddWorldInputControl();
addLevelInputInfo();
view.getErrorLabel().setText("");
} catch (Exception e) {
view.getErrorLabel().setText(e.getMessage());
}
}
private void handleConfirmationButton(ActionEvent actionEvent)
{
boolean firstStepControled;
try {
AddWorldInputControl();
view.getErrorLabel().setText("");
firstStepControled = true;
} catch (Exception e) {
view.getErrorLabel().setText(e.getMessage());
firstStepControled = false;
}
for (LevelCreationBox box : levelCreationBoxes) {
try {
box.getErrorsLabelLevelCreationBox().setText("");
levelCreationBoxInputControl(box);
addCheckBoxes();
} catch (Exception e) {
box.getErrorsLabelLevelCreationBox().setText(e.getMessage());
}
}
if (firstStepControled && levelCreationBoxes.isEmpty()) {
view.getErrorLabel().setText("This action can be taken after you add some levels to this world!");
}
}
private void handleSavingButton(ActionEvent actionEvent)
{
boolean firstStepControled = false;
boolean secondStepControled = false;
boolean worldAddedSuccesfully = false;
//input eerste<SUF>
try {
AddWorldInputControl();
view.getErrorLabel().setText("");
firstStepControled = true;
} catch (Exception e) {
view.getErrorLabel().setText(e.getMessage());
}
//input 2e stap checken
if (firstStepControled) {
for (LevelCreationBox box : levelCreationBoxes) {
try {
box.getErrorsLabelLevelCreationBox().setText("");
levelCreationBoxInputControl(box);
checkBoxesListControl();
secondStepControled = true;
} catch (Exception e) {
box.getErrorsLabelLevelCreationBox().setText(e.getMessage());
}
}
}
//3e stap opslaan van de world
if (secondStepControled) {
try {
for (LevelCreationBox box : levelCreationBoxes) {
box.getErrorsLabelLevelCreationBox().setText("");
levelCreationBoxInputControl(box);
checkBoxesListControl();
}
AddWorldInputControl();
view.getErrorLabel().setText("");
//nagaan of de positie 1 is
addLevels();
//alle opgeslagen data van de levels wissen
levels.clear();
//wanneer de exceptions zijn opgevangen
//dan met deze boolean alle levels opslaan in de world
//en deze operatie beeindigen
worldAddedSuccesfully = true;
} catch (Exception e) {
for (LevelCreationBox box : levelCreationBoxes) {
box.getErrorsLabelLevelCreationBox().setText(e.getMessage());
}
}
}
if (!worldAddedSuccesfully) {
if (firstStepControled && levelCreationBoxes.isEmpty()) {
view.getErrorLabel().setText("This action can be taken after you add some levels to this world!");
}
}
if (worldAddedSuccesfully) {
addLevels();
addWorld();
resetTheListsAndView();
lastDialog();
}
if (worldAddedSuccesfully) {
boolean worldLoaded = false;
while (!worldLoaded) {
try {
WorldSelectPresenter worldSelectPresenter = new WorldSelectPresenter(new WorldSelectView(), parent);
worldSelectPresenter.reload();
parent.getWorldLoader().loadWorlds();
worldLoaded = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void addLevelInputInfo()
{
LevelCreationBox levelCreationBox = new LevelCreationBox();
levelCreationBox.setId(nextId++);
levelCreationBoxes.add(levelCreationBox);
view.getvBox().getChildren().addAll(levelCreationBox);
}
public void addCheckBoxes()
{
VBox vBox = new VBox(20);
checkBoxesList.clear();
for (LevelCreationBox box : levelCreationBoxes) {
int rows = box.getRows();
int cols = box.getCols();
GridPane gridPane = new GridPane();
gridPane.add(box, 0, 0);
CheckBoxes checkBoxes = new CheckBoxes(rows, cols);
checkBoxesList.add(checkBoxes);
gridPane.add(checkBoxes, 1, 0);
vBox.getChildren().addAll(gridPane);
}
view.getvBox().getChildren().clear();
view.getvBox().getChildren().add(vBox);
}
public void addLevels()
{
List<int[][]> checkBoxesStatusMatrix = new ArrayList<>();
for (CheckBoxes checkBoxes : checkBoxesList) {
int[][] checkBoxStatus = checkBoxes.getCheckBoxStatus();
checkBoxesStatusMatrix.add(checkBoxStatus);
}
int idJsonLevel = 0;
for (LevelCreationBox levelCreationBox : levelCreationBoxes) {
int[] startPos = levelCreationBox.startPosCoordination();
if (checkBoxesStatusMatrix.get(idJsonLevel)[startPos[0]][startPos[1]] == 0) {
levels.clear();
throw new IllegalStateException("Checkbox value at start position cannot be 0!");
}
levels.add(new Level(idJsonLevel + 1, checkBoxesStatusMatrix.get(idJsonLevel), startPos));
idJsonLevel++;
}
}
private void addWorld()
{
String worldName = String.valueOf(view.getWorldName().getField().getText());
String difficultyName = String.valueOf(view.getDifficultyName().getField().getText());
World world = new World(worldName, "images/admin-foto.jpg", difficultyName);
WorldLoader worldLoader = parent.getWorldLoader();
for (Level level : levels) {
world.addLevel(level);
}
worldLoader.addWorld(world);
worldLoader.saveWorld(world.getId());
}
private void AddWorldInputControl()
{
String worldName = String.valueOf(view.getWorldName().getField().getText());
String difficultyName = String.valueOf(view.getDifficultyName().getField().getText());
if (worldName == null || worldName.length() < 4 || worldName.length() > 15) {
throw new IllegalArgumentException("World name must be between 4 and 15 characters long");
} else if (difficultyName == null || difficultyName.length() < 4 || difficultyName.length() > 15) {
throw new IllegalArgumentException("Difficulty name must be between 4 and 15 characters long");
}
}
private void checkBoxesListControl()
{
if (checkBoxesList.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("First you need to get checkboxes!");
}
}
private void levelCreationBoxInputControl(LevelCreationBox box)
{
int rows = box.getRows();
int cols = box.getCols();
if (rows > 20 || rows < 1) {
throw new IllegalArgumentException("Rows value must be between 1 and 20!");
} else if (cols > 20 || cols < 1) {
throw new IllegalArgumentException("Columns value must be between 1 and 20!");
}
int[] positionCheck = box.startPosCoordination();
if (positionCheck[0] >= rows || positionCheck[0] < 0) {
throw new IllegalArgumentException("The X-coordinate must be within the range of 0 to (row - 1)");
} else if (positionCheck[1] >= cols || positionCheck[1] < 0) {
throw new IllegalArgumentException("The Y-coordinate must be within the range of 0 to (column - 1)");
}
}
private void resetTheListsAndView()
{
view.getWorldName().getField().clear();
view.getDifficultyName().getField().clear();
levelCreationBoxes.clear();
checkBoxesList.clear();
levels.clear();
this.nextId = 1;
view.getErrorLabel().setText("");
view.getvBox().getChildren().clear();
}
private void lastDialog()
{
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle("World succesfully added!");
dialog.setHeaderText("What's next?");
ImageView imageView = new ImageView(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png")));
dialog.setGraphic(imageView);
dialog.setContentText("You can leave this page or add some more levels.");
((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().add(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png")));
ButtonType backButton = new ButtonType("Leave", ButtonBar.ButtonData.OK_DONE);
ButtonType addAnotherWorldButton = new ButtonType("Add another world", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(backButton, addAnotherWorldButton);
dialog.getDialogPane().getScene().getWindow().setOnCloseRequest(event -> dialog.close());
dialog.showAndWait().ifPresent(choice -> {
if (choice == backButton) {
parent.getSubScreenManager().switchScreen("worldselect");
} else if (choice == addAnotherWorldButton) {
parent.getSubScreenManager().getCurrentScreen();
}
});
}
@Override
public AddWorldView getView()
{
return this.view;
}
@Override
public String getScreenName()
{
return SCREEN_NAME;
}
} |
132355_5 | package com.lucinde.plannerpro.services;
import com.lucinde.plannerpro.dtos.UserInputDto;
import com.lucinde.plannerpro.dtos.UserOutputDto;
import com.lucinde.plannerpro.exceptions.BadRequestException;
import com.lucinde.plannerpro.exceptions.UsernameNotFoundException;
import com.lucinde.plannerpro.models.Authority;
import com.lucinde.plannerpro.models.User;
import com.lucinde.plannerpro.repositories.UserRepository;
import com.lucinde.plannerpro.utils.RandomStringGenerator;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public List<UserOutputDto> getUsers() {
List<UserOutputDto> collection = new ArrayList<>();
List<User> list = userRepository.findAll();
for (User user : list) {
collection.add(fromUser(user));
}
return collection;
}
public UserOutputDto getUser(String username) {
UserOutputDto dto;
Optional<User> user = userRepository.findById(username);
if (user.isPresent()) {
dto = fromUser(user.get());
} else {
throw new UsernameNotFoundException(username);
}
return dto;
}
public UserInputDto getUserWithPassword(String username) {
UserInputDto dto;
Optional<User> user = userRepository.findById(username);
if (user.isPresent()) {
dto = fromUserInput(user.get());
} else {
throw new UsernameNotFoundException(username);
}
return dto;
}
public boolean userExists(String username) {
return userRepository.existsById(username);
}
public String createUser(UserInputDto userInputDto) {
String randomString = RandomStringGenerator.generateAlphaNumeric(20);
userInputDto.setApikey(randomString);
//passwordencoder voeg ik to in toUser-methode waardoor onderstaande regel kan vervallen
//passwordEncoder.encode(userDto.password);
User newUser = userRepository.save(toUser(userInputDto));
return newUser.getUsername();
}
public void deleteUser(String username) {
userRepository.deleteById(username);
}
public void updateUser(String username, UserInputDto newUser) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
if (newUser.apikey != null)
user.setApikey(newUser.apikey);
if (newUser.password != null)
user.setPassword(passwordEncoder.encode(newUser.getPassword()));
if (newUser.email != null)
user.setEmail(newUser.getEmail());
if (newUser.enabled != null)
user.setEnabled(newUser.getEnabled());
userRepository.save(user);
}
public Set<Authority> getAuthorities(String username) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
UserInputDto userInputDto = fromUserInput(user);
return userInputDto.getAuthorities();
}
public void addAuthority(String username, String authority) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
// Check of de gebruiker de rol al heeft
Set<Authority> userAuthorities = user.getAuthorities();
for (Authority existingAuthority : userAuthorities) {
if (existingAuthority.getAuthority().equals(authority)) {
throw new BadRequestException("Gebruiker heeft deze rol al");
}
}
user.addAuthority(new Authority(username, authority));
userRepository.save(user);
}
public void removeAuthority(String username, String authority) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
Authority authorityToRemove = user.getAuthorities().stream().filter((a) -> a.getAuthority().equalsIgnoreCase(authority)).findAny().get();
user.removeAuthority(authorityToRemove);
userRepository.save(user);
}
//*------------------- Eigen methodes -------------------*//
public List<UserOutputDto> getMechanics() {
List<UserOutputDto> collection = new ArrayList<>();
List<User> list = userRepository.findByAuthority("ROLE_MECHANIC");
for (User user : list) {
collection.add(fromUser(user));
}
return collection;
}
public UserOutputDto getUserCheckAuth(String requestingUsername, String targetUsername) {
UserOutputDto targetDto;
Optional<User> user = userRepository.findById(targetUsername);
if (user.isPresent()) {
User targetUser = user.get();
// Check of de requestingUser de juiste rechten heeft
if (isAllowedToAccess(requestingUsername, targetUser)) {
targetDto = fromUser(targetUser);
} else {
throw new BadRequestException("U heeft geen toegang tot deze gegevens");
}
} else {
throw new UsernameNotFoundException(targetUsername);
}
return targetDto;
}
private boolean isAllowedToAccess(String requestingUsername, User targetUser) {
// Admin and Planner kunnen bij alle data
if (isRoleAdmin(requestingUsername) || isRolePlanner(requestingUsername)) {
return true;
}
// Mechanics kunnen alleen bij eigen data
if (isRoleMechanic(requestingUsername)) {
return requestingUsername.equals(targetUser.getUsername());
}
return false;
}
private boolean isRoleAdmin(String username) {
User user = userRepository.findById(username).orElse(null);
if (user != null) {
for (Authority authority : user.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_ADMIN")) {
return true;
}
}
}
return false;
}
private boolean isRolePlanner(String username) {
User user = userRepository.findById(username).orElse(null);
if (user != null) {
for (Authority authority : user.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_PLANNER")) {
return true;
}
}
}
return false;
}
private boolean isRoleMechanic(String username) {
User user = userRepository.findById(username).orElse(null);
if (user != null) {
for (Authority authority : user.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_MECHANIC")) {
return true;
}
}
}
return false;
}
//*------------------- Einde Eigen methodes -------------------*//
public static UserOutputDto fromUser(User user) {
var dto = new UserOutputDto();
dto.username = user.getUsername();
dto.enabled = user.isEnabled();
dto.email = user.getEmail();
dto.authorities = user.getAuthorities();
dto.scheduleTask = user.getScheduleTask();
return dto;
}
public static UserInputDto fromUserInput(User user) {
var dto = new UserInputDto();
dto.username = user.getUsername();
dto.password = user.getPassword();
dto.enabled = user.isEnabled();
dto.email = user.getEmail();
dto.apikey = user.getApikey();
dto.authorities = user.getAuthorities();
dto.scheduleTask = user.getScheduleTask();
return dto;
}
public User toUser(UserInputDto userInputDto) {
var user = new User();
user.setUsername(userInputDto.getUsername());
user.setPassword(passwordEncoder.encode(userInputDto.getPassword()));
user.setEnabled(userInputDto.getEnabled());
user.setApikey(userInputDto.getApikey());
user.setEmail(userInputDto.getEmail());
user.setScheduleTask(userInputDto.getScheduleTask());
return user;
}
}
| Lucinde/eindopdracht-fsd-backend | src/main/java/com/lucinde/plannerpro/services/UserService.java | 2,360 | // Mechanics kunnen alleen bij eigen data | line_comment | nl | package com.lucinde.plannerpro.services;
import com.lucinde.plannerpro.dtos.UserInputDto;
import com.lucinde.plannerpro.dtos.UserOutputDto;
import com.lucinde.plannerpro.exceptions.BadRequestException;
import com.lucinde.plannerpro.exceptions.UsernameNotFoundException;
import com.lucinde.plannerpro.models.Authority;
import com.lucinde.plannerpro.models.User;
import com.lucinde.plannerpro.repositories.UserRepository;
import com.lucinde.plannerpro.utils.RandomStringGenerator;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public List<UserOutputDto> getUsers() {
List<UserOutputDto> collection = new ArrayList<>();
List<User> list = userRepository.findAll();
for (User user : list) {
collection.add(fromUser(user));
}
return collection;
}
public UserOutputDto getUser(String username) {
UserOutputDto dto;
Optional<User> user = userRepository.findById(username);
if (user.isPresent()) {
dto = fromUser(user.get());
} else {
throw new UsernameNotFoundException(username);
}
return dto;
}
public UserInputDto getUserWithPassword(String username) {
UserInputDto dto;
Optional<User> user = userRepository.findById(username);
if (user.isPresent()) {
dto = fromUserInput(user.get());
} else {
throw new UsernameNotFoundException(username);
}
return dto;
}
public boolean userExists(String username) {
return userRepository.existsById(username);
}
public String createUser(UserInputDto userInputDto) {
String randomString = RandomStringGenerator.generateAlphaNumeric(20);
userInputDto.setApikey(randomString);
//passwordencoder voeg ik to in toUser-methode waardoor onderstaande regel kan vervallen
//passwordEncoder.encode(userDto.password);
User newUser = userRepository.save(toUser(userInputDto));
return newUser.getUsername();
}
public void deleteUser(String username) {
userRepository.deleteById(username);
}
public void updateUser(String username, UserInputDto newUser) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
if (newUser.apikey != null)
user.setApikey(newUser.apikey);
if (newUser.password != null)
user.setPassword(passwordEncoder.encode(newUser.getPassword()));
if (newUser.email != null)
user.setEmail(newUser.getEmail());
if (newUser.enabled != null)
user.setEnabled(newUser.getEnabled());
userRepository.save(user);
}
public Set<Authority> getAuthorities(String username) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
UserInputDto userInputDto = fromUserInput(user);
return userInputDto.getAuthorities();
}
public void addAuthority(String username, String authority) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
// Check of de gebruiker de rol al heeft
Set<Authority> userAuthorities = user.getAuthorities();
for (Authority existingAuthority : userAuthorities) {
if (existingAuthority.getAuthority().equals(authority)) {
throw new BadRequestException("Gebruiker heeft deze rol al");
}
}
user.addAuthority(new Authority(username, authority));
userRepository.save(user);
}
public void removeAuthority(String username, String authority) {
if (!userRepository.existsById(username)) throw new UsernameNotFoundException(username);
User user = userRepository.findById(username).get();
Authority authorityToRemove = user.getAuthorities().stream().filter((a) -> a.getAuthority().equalsIgnoreCase(authority)).findAny().get();
user.removeAuthority(authorityToRemove);
userRepository.save(user);
}
//*------------------- Eigen methodes -------------------*//
public List<UserOutputDto> getMechanics() {
List<UserOutputDto> collection = new ArrayList<>();
List<User> list = userRepository.findByAuthority("ROLE_MECHANIC");
for (User user : list) {
collection.add(fromUser(user));
}
return collection;
}
public UserOutputDto getUserCheckAuth(String requestingUsername, String targetUsername) {
UserOutputDto targetDto;
Optional<User> user = userRepository.findById(targetUsername);
if (user.isPresent()) {
User targetUser = user.get();
// Check of de requestingUser de juiste rechten heeft
if (isAllowedToAccess(requestingUsername, targetUser)) {
targetDto = fromUser(targetUser);
} else {
throw new BadRequestException("U heeft geen toegang tot deze gegevens");
}
} else {
throw new UsernameNotFoundException(targetUsername);
}
return targetDto;
}
private boolean isAllowedToAccess(String requestingUsername, User targetUser) {
// Admin and Planner kunnen bij alle data
if (isRoleAdmin(requestingUsername) || isRolePlanner(requestingUsername)) {
return true;
}
// Mechanics kunnen<SUF>
if (isRoleMechanic(requestingUsername)) {
return requestingUsername.equals(targetUser.getUsername());
}
return false;
}
private boolean isRoleAdmin(String username) {
User user = userRepository.findById(username).orElse(null);
if (user != null) {
for (Authority authority : user.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_ADMIN")) {
return true;
}
}
}
return false;
}
private boolean isRolePlanner(String username) {
User user = userRepository.findById(username).orElse(null);
if (user != null) {
for (Authority authority : user.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_PLANNER")) {
return true;
}
}
}
return false;
}
private boolean isRoleMechanic(String username) {
User user = userRepository.findById(username).orElse(null);
if (user != null) {
for (Authority authority : user.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_MECHANIC")) {
return true;
}
}
}
return false;
}
//*------------------- Einde Eigen methodes -------------------*//
public static UserOutputDto fromUser(User user) {
var dto = new UserOutputDto();
dto.username = user.getUsername();
dto.enabled = user.isEnabled();
dto.email = user.getEmail();
dto.authorities = user.getAuthorities();
dto.scheduleTask = user.getScheduleTask();
return dto;
}
public static UserInputDto fromUserInput(User user) {
var dto = new UserInputDto();
dto.username = user.getUsername();
dto.password = user.getPassword();
dto.enabled = user.isEnabled();
dto.email = user.getEmail();
dto.apikey = user.getApikey();
dto.authorities = user.getAuthorities();
dto.scheduleTask = user.getScheduleTask();
return dto;
}
public User toUser(UserInputDto userInputDto) {
var user = new User();
user.setUsername(userInputDto.getUsername());
user.setPassword(passwordEncoder.encode(userInputDto.getPassword()));
user.setEnabled(userInputDto.getEnabled());
user.setApikey(userInputDto.getApikey());
user.setEmail(userInputDto.getEmail());
user.setScheduleTask(userInputDto.getScheduleTask());
return user;
}
}
|
31954_3 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hw4.dutch;
/**
*
* @author hessel
*/
public interface Speler {
public int Speel(Bord b); //Geeft public int Speel(Bord b);aan in welke kolom de speler wil spelen
public String getNaam(); //Geeft de naam van de speler
public Kleur getKleur(); //Geeft de kleur waar de speler mee speelt
}
| Lucus16/oop | src/hw4/dutch/Speler.java | 166 | //Geeft de naam van de speler
| line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hw4.dutch;
/**
*
* @author hessel
*/
public interface Speler {
public int Speel(Bord b); //Geeft public int Speel(Bord b);aan in welke kolom de speler wil spelen
public String getNaam(); //Geeft de<SUF>
public Kleur getKleur(); //Geeft de kleur waar de speler mee speelt
}
|
14145_0 | public class Werknemer {
public String voornaam;
public String achternaam;
public int werknemerNummer;
protected float salaris;
public static int aantalWerknemers;
public void salarisVerhogen(int percentage) {
float verhogingsfactor = (float)percentage/100;
salaris += salaris*verhogingsfactor;
}
public float getSalaris() {
return salaris;
}
public Werknemer(String voornaam, String achternaam, int wNummer, float salaris) {
this.voornaam = voornaam; //this.var => altijd dataleden
this.achternaam = achternaam;
werknemerNummer = wNummer;
this.salaris = salaris;
aantalWerknemers++;
}
} | LukaVerhoeven/Digital-Broadcast | Werknemer.java | 220 | //this.var => altijd dataleden | line_comment | nl | public class Werknemer {
public String voornaam;
public String achternaam;
public int werknemerNummer;
protected float salaris;
public static int aantalWerknemers;
public void salarisVerhogen(int percentage) {
float verhogingsfactor = (float)percentage/100;
salaris += salaris*verhogingsfactor;
}
public float getSalaris() {
return salaris;
}
public Werknemer(String voornaam, String achternaam, int wNummer, float salaris) {
this.voornaam = voornaam; //this.var =><SUF>
this.achternaam = achternaam;
werknemerNummer = wNummer;
this.salaris = salaris;
aantalWerknemers++;
}
} |
109949_0 | import org.json.*;
import java.io.*;
import java.util.*;
import org.json.JSONTokener;
import org.json.simple.parser.JSONParser;
/*
- eerst een feasable oplossing vormen dan lokaal zoeken om betere oplossingen te zoeken
- welke datastructuur voor de oplossing, zien dat oplossing 1x gesaved wordt LinkedList
- geen unavailability in de linked list oplossing steken
- setup tijd kan wel in de linked list om de heuristiek makkelijker te maken
*/
public class Main {
public static void main(String[] args) throws Exception {
//Als je error hebt moet je gwn alles met args[] in comment zetten
long t1 = System.currentTimeMillis();
String inputFile = args[0];
String solutionFile = args[1];
int seed = Integer.parseInt(args[2]);
int timeLimit = Integer.parseInt(args[3]);
int threads = Integer.parseInt(args[4]);
Object obj = new JSONParser().parse(new FileReader("./IO/"+inputFile));
JSONTokener tokener = new JSONTokener(String.valueOf(obj));
JSONObject object = new JSONObject(tokener);
String name = object.getString("name");
float weightDuration = object.getFloat("weight_duration");
int horizon = object.getInt("horizon");
JSONArray jobsArray = object.getJSONArray("jobs");
LinkedList<Job> jobs = new LinkedList<>();
for (int i = 0; i<jobsArray.length();i++) {
JSONObject temp = jobsArray.getJSONObject(i);
int id = temp.getInt("id");
int duration = temp.getInt("duration");
int release_date = temp.getInt("release_date");
int due_date = temp.getInt("due_date");
float earliness_penalty = temp.getFloat("earliness_penalty");
float rejection_penalty = temp.getFloat("rejection_penalty");
Job job = new Job(id, duration, release_date, due_date, earliness_penalty, rejection_penalty);
jobs.add(job);
}
JSONArray unavailability = object.getJSONArray("unavailability");
Unavailability un = new Unavailability(horizon);
for(int i=0; i<unavailability.length();i++){
JSONObject temp = unavailability.getJSONObject(i);
int start = temp.getInt("start");
int end = temp.getInt("end");
un.addUnavailable(start,end);
}
Setup setup = new Setup(jobs);
int[][] setups = setup.setup;
JSONArray s = object.getJSONArray("setups");
for(int i=0; i< jobsArray.length();i++){
JSONArray s0 = s.getJSONArray(i);
for (int j=0; j< s0.length();j++){
setups[i][j] = (int) s.getJSONArray(i).get(j);
}
}
FirstSolution solution = new FirstSolution(jobs, weightDuration, setups, un,horizon);
LinkedList<Job>test = solution.firstSolution();
long startTime = System.currentTimeMillis();
SteepestDescend sd = new SteepestDescend(jobs,test, solution.getSetupList(),setups,un,weightDuration,horizon,solution.getBestCost());;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Boolean running = true;
int timePerBar=(timeLimit*1000)/100;
int barCount=1;
int iterations=0;
while(running){
iterations++;
if(System.currentTimeMillis() - startTime> timeLimit*1000){
running = false;
}
int temp = timePerBar*barCount;
if((System.currentTimeMillis() - startTime) > temp) {
System.out.print("[" + barCount + "%]");
barCount++;
}
sd.startLocalSearch();
}
System.out.println();
System.out.println("Iterations: "+iterations);
}
});
thread.run();
JSONObject finalSolution = sd.getJSONSolution();
double evaluation=sd.getBestCost();
finalSolution.put("name",name);
finalSolution.put("value",evaluation);
FileWriter fw = new FileWriter("./IO/"+solutionFile);
fw.write(finalSolution.toString(4));
fw.flush();
long t2 = System.currentTimeMillis();
sd.getActions();
System.out.println("Executed in: "+(t2-t1)/1000+"s. Best cost: "+evaluation);
}
} | Lukasdewachter/project-optimalisatie | src/Main.java | 1,276 | /*
- eerst een feasable oplossing vormen dan lokaal zoeken om betere oplossingen te zoeken
- welke datastructuur voor de oplossing, zien dat oplossing 1x gesaved wordt LinkedList
- geen unavailability in de linked list oplossing steken
- setup tijd kan wel in de linked list om de heuristiek makkelijker te maken
*/ | block_comment | nl | import org.json.*;
import java.io.*;
import java.util.*;
import org.json.JSONTokener;
import org.json.simple.parser.JSONParser;
/*
- eerst een<SUF>*/
public class Main {
public static void main(String[] args) throws Exception {
//Als je error hebt moet je gwn alles met args[] in comment zetten
long t1 = System.currentTimeMillis();
String inputFile = args[0];
String solutionFile = args[1];
int seed = Integer.parseInt(args[2]);
int timeLimit = Integer.parseInt(args[3]);
int threads = Integer.parseInt(args[4]);
Object obj = new JSONParser().parse(new FileReader("./IO/"+inputFile));
JSONTokener tokener = new JSONTokener(String.valueOf(obj));
JSONObject object = new JSONObject(tokener);
String name = object.getString("name");
float weightDuration = object.getFloat("weight_duration");
int horizon = object.getInt("horizon");
JSONArray jobsArray = object.getJSONArray("jobs");
LinkedList<Job> jobs = new LinkedList<>();
for (int i = 0; i<jobsArray.length();i++) {
JSONObject temp = jobsArray.getJSONObject(i);
int id = temp.getInt("id");
int duration = temp.getInt("duration");
int release_date = temp.getInt("release_date");
int due_date = temp.getInt("due_date");
float earliness_penalty = temp.getFloat("earliness_penalty");
float rejection_penalty = temp.getFloat("rejection_penalty");
Job job = new Job(id, duration, release_date, due_date, earliness_penalty, rejection_penalty);
jobs.add(job);
}
JSONArray unavailability = object.getJSONArray("unavailability");
Unavailability un = new Unavailability(horizon);
for(int i=0; i<unavailability.length();i++){
JSONObject temp = unavailability.getJSONObject(i);
int start = temp.getInt("start");
int end = temp.getInt("end");
un.addUnavailable(start,end);
}
Setup setup = new Setup(jobs);
int[][] setups = setup.setup;
JSONArray s = object.getJSONArray("setups");
for(int i=0; i< jobsArray.length();i++){
JSONArray s0 = s.getJSONArray(i);
for (int j=0; j< s0.length();j++){
setups[i][j] = (int) s.getJSONArray(i).get(j);
}
}
FirstSolution solution = new FirstSolution(jobs, weightDuration, setups, un,horizon);
LinkedList<Job>test = solution.firstSolution();
long startTime = System.currentTimeMillis();
SteepestDescend sd = new SteepestDescend(jobs,test, solution.getSetupList(),setups,un,weightDuration,horizon,solution.getBestCost());;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Boolean running = true;
int timePerBar=(timeLimit*1000)/100;
int barCount=1;
int iterations=0;
while(running){
iterations++;
if(System.currentTimeMillis() - startTime> timeLimit*1000){
running = false;
}
int temp = timePerBar*barCount;
if((System.currentTimeMillis() - startTime) > temp) {
System.out.print("[" + barCount + "%]");
barCount++;
}
sd.startLocalSearch();
}
System.out.println();
System.out.println("Iterations: "+iterations);
}
});
thread.run();
JSONObject finalSolution = sd.getJSONSolution();
double evaluation=sd.getBestCost();
finalSolution.put("name",name);
finalSolution.put("value",evaluation);
FileWriter fw = new FileWriter("./IO/"+solutionFile);
fw.write(finalSolution.toString(4));
fw.flush();
long t2 = System.currentTimeMillis();
sd.getActions();
System.out.println("Executed in: "+(t2-t1)/1000+"s. Best cost: "+evaluation);
}
} |
107198_0 | package be.vdab.prularia.repositories;
import be.vdab.prularia.domain.MagazijnPlaats;
import be.vdab.prularia.dto.OverzichtBesteldArtikel;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.List;
@Repository
public class MagazijnPlaatsRepository {
private final JdbcTemplate template;
public MagazijnPlaatsRepository(JdbcTemplate template) {
this.template = template;
}
private final RowMapper<MagazijnPlaats> magazijnPlaatsRowMapper =
(result, rowNum) ->
new MagazijnPlaats(result.getLong("magazijnplaatsId"), result.getLong("artikelId"),
result.getString("rij"), result.getInt("rek"),
result.getInt("aantal"));
public List<MagazijnPlaats> vindMagazijnPlaatsenByArtikelId(long artikelId) {
var sql = """
SELECT magazijnplaatsId, artikelId, rij, rek, aantal
FROM magazijnplaatsen
WHERE artikelId = ?
""";
return template.query(sql, magazijnPlaatsRowMapper, artikelId);
}
public List<OverzichtBesteldArtikel> vindBesteldeArtikels(HashMap<Long, Integer> magazijnplaatsIdEnAantal) {
if (magazijnplaatsIdEnAantal.isEmpty()) {
return List.of();
}
var sql = """
SELECT m.magazijnplaatsId, m.artikelId, a.naam, m.rij, m.rek
FROM magazijnplaatsen AS m
LEFT JOIN artikelen AS a
ON m.artikelId = a.artikelId
WHERE magazijnplaatsId IN (
"""
+ "?,".repeat(magazijnplaatsIdEnAantal.keySet().size() - 1 )
+ "?) ORDER BY m.rij, m.rek";
return template.query(sql,
(result, rowNum) ->
new OverzichtBesteldArtikel(result.getLong("artikelId"), result.getString("naam"),
result.getString("rij").charAt(0), result.getInt("rek"),
magazijnplaatsIdEnAantal.get(result.getLong("magazijnplaatsId")), false,
result.getLong("magazijnplaatsId")),
magazijnplaatsIdEnAantal.keySet().toArray());
}
public int verlaagAantalArtikelInMagazijn(long magazijnPlaatsId, int aantalVerkocht){
//var magazijnPlaatsId = vindMagazijnPlaatsenByArtikelId(artikelId);
var sql = """
update magazijnPlaatsen
set aantal = aantal - ?
where magazijnPlaatsId = ?
""";
return template.update(sql,aantalVerkocht,magazijnPlaatsId);
}
}
| Lulie22/prularia | src/main/java/be/vdab/prularia/repositories/MagazijnPlaatsRepository.java | 869 | //var magazijnPlaatsId = vindMagazijnPlaatsenByArtikelId(artikelId); | line_comment | nl | package be.vdab.prularia.repositories;
import be.vdab.prularia.domain.MagazijnPlaats;
import be.vdab.prularia.dto.OverzichtBesteldArtikel;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.List;
@Repository
public class MagazijnPlaatsRepository {
private final JdbcTemplate template;
public MagazijnPlaatsRepository(JdbcTemplate template) {
this.template = template;
}
private final RowMapper<MagazijnPlaats> magazijnPlaatsRowMapper =
(result, rowNum) ->
new MagazijnPlaats(result.getLong("magazijnplaatsId"), result.getLong("artikelId"),
result.getString("rij"), result.getInt("rek"),
result.getInt("aantal"));
public List<MagazijnPlaats> vindMagazijnPlaatsenByArtikelId(long artikelId) {
var sql = """
SELECT magazijnplaatsId, artikelId, rij, rek, aantal
FROM magazijnplaatsen
WHERE artikelId = ?
""";
return template.query(sql, magazijnPlaatsRowMapper, artikelId);
}
public List<OverzichtBesteldArtikel> vindBesteldeArtikels(HashMap<Long, Integer> magazijnplaatsIdEnAantal) {
if (magazijnplaatsIdEnAantal.isEmpty()) {
return List.of();
}
var sql = """
SELECT m.magazijnplaatsId, m.artikelId, a.naam, m.rij, m.rek
FROM magazijnplaatsen AS m
LEFT JOIN artikelen AS a
ON m.artikelId = a.artikelId
WHERE magazijnplaatsId IN (
"""
+ "?,".repeat(magazijnplaatsIdEnAantal.keySet().size() - 1 )
+ "?) ORDER BY m.rij, m.rek";
return template.query(sql,
(result, rowNum) ->
new OverzichtBesteldArtikel(result.getLong("artikelId"), result.getString("naam"),
result.getString("rij").charAt(0), result.getInt("rek"),
magazijnplaatsIdEnAantal.get(result.getLong("magazijnplaatsId")), false,
result.getLong("magazijnplaatsId")),
magazijnplaatsIdEnAantal.keySet().toArray());
}
public int verlaagAantalArtikelInMagazijn(long magazijnPlaatsId, int aantalVerkocht){
//var magazijnPlaatsId<SUF>
var sql = """
update magazijnPlaatsen
set aantal = aantal - ?
where magazijnPlaatsId = ?
""";
return template.update(sql,aantalVerkocht,magazijnPlaatsId);
}
}
|
135205_14 | package com.javapong;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
/*
Die Methode in der das Spiel gezeichnet wird. Grafikelemente werden von hier aus gestartet.
*/
public class PongBoard extends JPanel implements Runnable, ActionListener{ //Bord des Pong-Spiel
//Objekte deklarieren
private Paddle_links paddle_links;
private Paddle_rechts paddle_rechts;
private Ball ball1;
private Spielfeld spielfeld1;
private int delay=16;
private Timer timer;
private Color farbe_links;
private Color farbe_rechts;
private Color farbe_Ball;
private Thread ballthread;
private int PunkteLinks=0;
private int PunkteRechts=0;
private Font retroFont;
boolean spielEnde = false;
private int delayBspeed;
private boolean close = false; //Das ist so hässlich und furchtbar
private Sound hit; //Soundeffekte
private Sound goal;
private Sound win;
private float LautMinus;
private int modus;
public PongBoard(Color farbe_rechts,Color farbe_links,Color farbe_Ball,float LautMinus,int modus,int delayBspeed) throws Exception {
this.modus= modus;
this.delayBspeed = delayBspeed;
startFont(); //Font init
addKeyListener(new PongBoard.TAdapter()); //Initialisiert Key listener
setBackground(Color.black);
setFocusable(true);
paddle_links=new Paddle_links(); //Initialisiert Paddels
if(modus==1||modus==2||modus==3) { //Einzelspieler -> Bot
paddle_rechts = new Paddle_rechts_Bot();
if(modus==1){
paddle_rechts.setS(5);
}
else if(modus==2){
paddle_rechts.setS(7);
}
else if(modus==3){
paddle_rechts.setS(10);
}
}
else{ //LMultiplayer -> kein Bot
paddle_rechts= new Paddle_rechts();
}
ball1=new Ball(delayBspeed);
spielfeld1= new Spielfeld();
this.farbe_links = farbe_links; //Farben übernehmen
this.farbe_rechts = farbe_rechts;
this.farbe_Ball= farbe_Ball;
timer = new Timer(delay, this); //Irgendwas braucht das hier (die Bewegungsanimation der Paddles)
timer.start();
this.LautMinus = LautMinus;
hit = new Sound("resources/sound/4382__noisecollector__pongblipd-5.wav",LautMinus,false);
goal = new Sound("resources/sound/463067__gamer127__success-02.wav",LautMinus,false);
win = new Sound("resources/sound/518308__mrthenoronha__world-clear-8-bit.wav",LautMinus,false);
System.out.print("Hello");
}
@Override
public void paintComponent(Graphics g){ //Eigentliche Zeichenmethode
super.paintComponent(g);
Graphics2D g2d= (Graphics2D) g; //Grafikobjekt in 2D-Grafikobjekt umwandeln
paintPaddle_links(g2d); //Paddles zeichnen
paintPaddle_rechts(g2d);
paintRahmen(g2d);
paintBall(g2d);
try {
paintPunkte(g2d);
} catch (IOException e) {
e.printStackTrace();
} catch (FontFormatException e) {
e.printStackTrace();
}
if(spielEnde==true) {
paintYouWin(g2d);
}
Toolkit.getDefaultToolkit().sync(); //Ruckelverbesserung
}
//paint Methoden
public void paintPaddle_rechts(Graphics2D g2d){
g2d.setColor(farbe_rechts);
g2d.fill3DRect(paddle_rechts.getX(), paddle_rechts.getY(), paddle_rechts.getWidth(), paddle_rechts.getHeight(),true);
}
public void paintPaddle_links(Graphics2D g2d){
g2d.setColor(farbe_links);
g2d.fill3DRect(paddle_links.getX(), paddle_links.getY(), paddle_links.getWidth(), paddle_links.getHeight(), true);
}
public void paintBall(Graphics2D g2d){
g2d.setColor(farbe_Ball);
g2d.fill3DRect(ball1.getX(), ball1.getY(), ball1.getWidth(), ball1.getHeight(), true);
}
public void paintRahmen(Graphics2D g2d){ //Rahmenkomponenten zeichnen
g2d.setColor(Color.white);
g2d.fill3DRect(spielfeld1.getXm(), spielfeld1.getYm(), spielfeld1.getMwidth(), spielfeld1.getMheight(), true);
g2d.fill3DRect(spielfeld1.getXl(), spielfeld1.getYm(), spielfeld1.getMwidth(), spielfeld1.getMheight(), true);
g2d.fill3DRect(spielfeld1.getXr(), spielfeld1.getYm(), spielfeld1.getMwidth(), spielfeld1.getMheight(), true);
g2d.fill3DRect(0, spielfeld1.getYo(), spielfeld1.getSw(), spielfeld1.getMwidth(), true);
g2d.fill3DRect(0, spielfeld1.getYu(), spielfeld1.getSw(), spielfeld1.getMwidth(), true);
}
public void paintPunkte(Graphics2D g2d) throws IOException, FontFormatException {
g2d.setColor(Color.white);
g2d.setFont(retroFont);
g2d.drawString(String.valueOf(PunkteLinks),spielfeld1.getxAl(),spielfeld1.getyA()); //linke
g2d.drawString(String.valueOf(PunkteRechts),spielfeld1.getxAr(),spielfeld1.getyA()); //rechte
}
public void paintYouWin(Graphics2D g2d) {
g2d.setColor(Color.white);
g2d.setFont(retroFont);
g2d.drawString("You win!",spielfeld1.getxT(), spielfeld1.getyT());
}
@Override
public void addNotify() { //Der Thread für die Ball Animation wird hier gestartet
super.addNotify();
ballthread = new Thread(this);
ballthread.start();
}
@Override
public void run(){ //Animation des Balles
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis(); //Timing für konstante Frames
while(true) { //läuft für immer
ball1.move(); //verändern
pushXYBall();
checkCollision(); //Collisions detection
repaint(ball1.getX(), ball1.getY(), ball1.getWidth(), ball1.getHeight());
if(modus==1||modus==2||modus==3){
paddle_rechts.move();
}
timeDiff = System.currentTimeMillis() - beforeTime; //mehr Timing
sleep = 16 - timeDiff; //theoretisch 60 FPS
if (sleep < 0) {
sleep = 2;
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) { //Error handling
String msg = String.format("Thread interrupted: %s", e.getMessage());
JOptionPane.showMessageDialog(this, msg, "Error",
JOptionPane.ERROR_MESSAGE);
}
beforeTime = System.currentTimeMillis(); //Timing reset
}
}
public void pushXYBall(){ //Ballkoordinaten an den Bot pushen
paddle_rechts.setXbYb(ball1.getX(),ball1.getY());
}
public void checkCollision() { //Collisions erkennen
Rectangle rB = ball1.getBounds();
Rectangle rPl= paddle_links.getBounds();
Rectangle rPr= paddle_rechts.getBounds();
Rectangle rBo=spielfeld1.getBoundsOben();
Rectangle rBu=spielfeld1.getBoundsUnten();
Rectangle rBl=spielfeld1.getBoundsLinks();
Rectangle rBr=spielfeld1.getBoundsRechts();
if(rB.intersects(rPl)||rB.intersects(rPr)) { //Unterschiedlich für Rahmen und Paddles
ball1.AbprallenPaddle();
hit.playSoundOnce();
}
if(rB.intersects(rBo)||rB.intersects(rBu)){
ball1.AbprallenBoarder();
hit.playSoundOnce();
}
if(rB.intersects(rBl)||rB.intersects(rBr)){
Punktedetektor(rBr, rBl, rB);
goal.playSoundOnce();
}
}
public void Punktedetektor(Rectangle rBr, Rectangle rBl, Rectangle rB){
if(rB.intersects(rBl)) {
PunkteRechts= PunkteRechts+1;
ball1.resetBall(true);
}
else {
PunkteLinks= PunkteLinks+1;
ball1.resetBall(false);
}
if(PunkteLinks>=7||PunkteRechts>=7) {
spielEnde();
}
}
public void spielEnde() { //Ende und close //Ball stoppen
if(PunkteLinks>=7) {
spielfeld1.youWin(true);
}
else {
spielfeld1.youWin(false);
}
spielEnde = true;
win.playSoundOnce();
ballthread.stop();
}
public void actionPerformed(ActionEvent e) { //wird nach Tastendruck ausgeführt
paddle_rechts.move();
paddle_links.move();
int x = paddle_rechts.getX();
int y = paddle_rechts.getY();
//nur alles repainten funktioniert
//repaint(paddle_rechts.getX(), paddle_rechts.getY(), paddle_rechts.getWidth(), paddle_rechts.getHeight());
//repaint(paddle_links.getX(), paddle_links.getY(), paddle_links.getWidth(), paddle_links.getHeight());
repaint();
}
private class TAdapter extends KeyAdapter { //gibt Tastendrücke an Paddel weiter, keine Ahnung wie
@Override
public void keyReleased(KeyEvent e) {
paddle_links.keyReleased(e);
paddle_rechts.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
paddle_links.keyPressed(e);
paddle_rechts.keyPressed(e);
if (key == KeyEvent.VK_ESCAPE) { //bei ESC schließen
close = true;
win.stopSound1();
}
}
}
public void stop(){ //Geräusche stoppen indem wir den Ball stoppen
ballthread.stop();
}
public void startFont() throws IOException, FontFormatException { //Custom Font init
File f = new File("resources/font/PressStart2P.ttf"); //Pfad zu .ttf File
Font PressStart = Font.createFont(Font.TRUETYPE_FONT,f); //Neue Font machen
PressStart = PressStart.deriveFont(Font.PLAIN,70); //Größe, ... festlegen
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(PressStart);
retroFont = PressStart; //Abspeichern
}
public boolean getClose() {
return close;
}
} | LundiNord/JavaPong | src/com/javapong/PongBoard.java | 3,497 | //Ballkoordinaten an den Bot pushen | line_comment | nl | package com.javapong;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
/*
Die Methode in der das Spiel gezeichnet wird. Grafikelemente werden von hier aus gestartet.
*/
public class PongBoard extends JPanel implements Runnable, ActionListener{ //Bord des Pong-Spiel
//Objekte deklarieren
private Paddle_links paddle_links;
private Paddle_rechts paddle_rechts;
private Ball ball1;
private Spielfeld spielfeld1;
private int delay=16;
private Timer timer;
private Color farbe_links;
private Color farbe_rechts;
private Color farbe_Ball;
private Thread ballthread;
private int PunkteLinks=0;
private int PunkteRechts=0;
private Font retroFont;
boolean spielEnde = false;
private int delayBspeed;
private boolean close = false; //Das ist so hässlich und furchtbar
private Sound hit; //Soundeffekte
private Sound goal;
private Sound win;
private float LautMinus;
private int modus;
public PongBoard(Color farbe_rechts,Color farbe_links,Color farbe_Ball,float LautMinus,int modus,int delayBspeed) throws Exception {
this.modus= modus;
this.delayBspeed = delayBspeed;
startFont(); //Font init
addKeyListener(new PongBoard.TAdapter()); //Initialisiert Key listener
setBackground(Color.black);
setFocusable(true);
paddle_links=new Paddle_links(); //Initialisiert Paddels
if(modus==1||modus==2||modus==3) { //Einzelspieler -> Bot
paddle_rechts = new Paddle_rechts_Bot();
if(modus==1){
paddle_rechts.setS(5);
}
else if(modus==2){
paddle_rechts.setS(7);
}
else if(modus==3){
paddle_rechts.setS(10);
}
}
else{ //LMultiplayer -> kein Bot
paddle_rechts= new Paddle_rechts();
}
ball1=new Ball(delayBspeed);
spielfeld1= new Spielfeld();
this.farbe_links = farbe_links; //Farben übernehmen
this.farbe_rechts = farbe_rechts;
this.farbe_Ball= farbe_Ball;
timer = new Timer(delay, this); //Irgendwas braucht das hier (die Bewegungsanimation der Paddles)
timer.start();
this.LautMinus = LautMinus;
hit = new Sound("resources/sound/4382__noisecollector__pongblipd-5.wav",LautMinus,false);
goal = new Sound("resources/sound/463067__gamer127__success-02.wav",LautMinus,false);
win = new Sound("resources/sound/518308__mrthenoronha__world-clear-8-bit.wav",LautMinus,false);
System.out.print("Hello");
}
@Override
public void paintComponent(Graphics g){ //Eigentliche Zeichenmethode
super.paintComponent(g);
Graphics2D g2d= (Graphics2D) g; //Grafikobjekt in 2D-Grafikobjekt umwandeln
paintPaddle_links(g2d); //Paddles zeichnen
paintPaddle_rechts(g2d);
paintRahmen(g2d);
paintBall(g2d);
try {
paintPunkte(g2d);
} catch (IOException e) {
e.printStackTrace();
} catch (FontFormatException e) {
e.printStackTrace();
}
if(spielEnde==true) {
paintYouWin(g2d);
}
Toolkit.getDefaultToolkit().sync(); //Ruckelverbesserung
}
//paint Methoden
public void paintPaddle_rechts(Graphics2D g2d){
g2d.setColor(farbe_rechts);
g2d.fill3DRect(paddle_rechts.getX(), paddle_rechts.getY(), paddle_rechts.getWidth(), paddle_rechts.getHeight(),true);
}
public void paintPaddle_links(Graphics2D g2d){
g2d.setColor(farbe_links);
g2d.fill3DRect(paddle_links.getX(), paddle_links.getY(), paddle_links.getWidth(), paddle_links.getHeight(), true);
}
public void paintBall(Graphics2D g2d){
g2d.setColor(farbe_Ball);
g2d.fill3DRect(ball1.getX(), ball1.getY(), ball1.getWidth(), ball1.getHeight(), true);
}
public void paintRahmen(Graphics2D g2d){ //Rahmenkomponenten zeichnen
g2d.setColor(Color.white);
g2d.fill3DRect(spielfeld1.getXm(), spielfeld1.getYm(), spielfeld1.getMwidth(), spielfeld1.getMheight(), true);
g2d.fill3DRect(spielfeld1.getXl(), spielfeld1.getYm(), spielfeld1.getMwidth(), spielfeld1.getMheight(), true);
g2d.fill3DRect(spielfeld1.getXr(), spielfeld1.getYm(), spielfeld1.getMwidth(), spielfeld1.getMheight(), true);
g2d.fill3DRect(0, spielfeld1.getYo(), spielfeld1.getSw(), spielfeld1.getMwidth(), true);
g2d.fill3DRect(0, spielfeld1.getYu(), spielfeld1.getSw(), spielfeld1.getMwidth(), true);
}
public void paintPunkte(Graphics2D g2d) throws IOException, FontFormatException {
g2d.setColor(Color.white);
g2d.setFont(retroFont);
g2d.drawString(String.valueOf(PunkteLinks),spielfeld1.getxAl(),spielfeld1.getyA()); //linke
g2d.drawString(String.valueOf(PunkteRechts),spielfeld1.getxAr(),spielfeld1.getyA()); //rechte
}
public void paintYouWin(Graphics2D g2d) {
g2d.setColor(Color.white);
g2d.setFont(retroFont);
g2d.drawString("You win!",spielfeld1.getxT(), spielfeld1.getyT());
}
@Override
public void addNotify() { //Der Thread für die Ball Animation wird hier gestartet
super.addNotify();
ballthread = new Thread(this);
ballthread.start();
}
@Override
public void run(){ //Animation des Balles
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis(); //Timing für konstante Frames
while(true) { //läuft für immer
ball1.move(); //verändern
pushXYBall();
checkCollision(); //Collisions detection
repaint(ball1.getX(), ball1.getY(), ball1.getWidth(), ball1.getHeight());
if(modus==1||modus==2||modus==3){
paddle_rechts.move();
}
timeDiff = System.currentTimeMillis() - beforeTime; //mehr Timing
sleep = 16 - timeDiff; //theoretisch 60 FPS
if (sleep < 0) {
sleep = 2;
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) { //Error handling
String msg = String.format("Thread interrupted: %s", e.getMessage());
JOptionPane.showMessageDialog(this, msg, "Error",
JOptionPane.ERROR_MESSAGE);
}
beforeTime = System.currentTimeMillis(); //Timing reset
}
}
public void pushXYBall(){ //Ballkoordinaten an<SUF>
paddle_rechts.setXbYb(ball1.getX(),ball1.getY());
}
public void checkCollision() { //Collisions erkennen
Rectangle rB = ball1.getBounds();
Rectangle rPl= paddle_links.getBounds();
Rectangle rPr= paddle_rechts.getBounds();
Rectangle rBo=spielfeld1.getBoundsOben();
Rectangle rBu=spielfeld1.getBoundsUnten();
Rectangle rBl=spielfeld1.getBoundsLinks();
Rectangle rBr=spielfeld1.getBoundsRechts();
if(rB.intersects(rPl)||rB.intersects(rPr)) { //Unterschiedlich für Rahmen und Paddles
ball1.AbprallenPaddle();
hit.playSoundOnce();
}
if(rB.intersects(rBo)||rB.intersects(rBu)){
ball1.AbprallenBoarder();
hit.playSoundOnce();
}
if(rB.intersects(rBl)||rB.intersects(rBr)){
Punktedetektor(rBr, rBl, rB);
goal.playSoundOnce();
}
}
public void Punktedetektor(Rectangle rBr, Rectangle rBl, Rectangle rB){
if(rB.intersects(rBl)) {
PunkteRechts= PunkteRechts+1;
ball1.resetBall(true);
}
else {
PunkteLinks= PunkteLinks+1;
ball1.resetBall(false);
}
if(PunkteLinks>=7||PunkteRechts>=7) {
spielEnde();
}
}
public void spielEnde() { //Ende und close //Ball stoppen
if(PunkteLinks>=7) {
spielfeld1.youWin(true);
}
else {
spielfeld1.youWin(false);
}
spielEnde = true;
win.playSoundOnce();
ballthread.stop();
}
public void actionPerformed(ActionEvent e) { //wird nach Tastendruck ausgeführt
paddle_rechts.move();
paddle_links.move();
int x = paddle_rechts.getX();
int y = paddle_rechts.getY();
//nur alles repainten funktioniert
//repaint(paddle_rechts.getX(), paddle_rechts.getY(), paddle_rechts.getWidth(), paddle_rechts.getHeight());
//repaint(paddle_links.getX(), paddle_links.getY(), paddle_links.getWidth(), paddle_links.getHeight());
repaint();
}
private class TAdapter extends KeyAdapter { //gibt Tastendrücke an Paddel weiter, keine Ahnung wie
@Override
public void keyReleased(KeyEvent e) {
paddle_links.keyReleased(e);
paddle_rechts.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
paddle_links.keyPressed(e);
paddle_rechts.keyPressed(e);
if (key == KeyEvent.VK_ESCAPE) { //bei ESC schließen
close = true;
win.stopSound1();
}
}
}
public void stop(){ //Geräusche stoppen indem wir den Ball stoppen
ballthread.stop();
}
public void startFont() throws IOException, FontFormatException { //Custom Font init
File f = new File("resources/font/PressStart2P.ttf"); //Pfad zu .ttf File
Font PressStart = Font.createFont(Font.TRUETYPE_FONT,f); //Neue Font machen
PressStart = PressStart.deriveFont(Font.PLAIN,70); //Größe, ... festlegen
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(PressStart);
retroFont = PressStart; //Abspeichern
}
public boolean getClose() {
return close;
}
} |
208022_44 | package org.bukkit.entity;
import com.google.common.base.Preconditions;
import catserver.server.entity.CraftCustomEntity;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Keyed;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.entity.minecart.CommandMinecart;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.PoweredMinecart;
import org.bukkit.entity.minecart.RideableMinecart;
import org.bukkit.entity.minecart.SpawnerMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public enum EntityType implements Keyed {
// These strings MUST match the strings in nms.EntityTypes and are case sensitive.
/**
* An item resting on the ground.
* <p>
* Spawn with {@link World#dropItem(Location, ItemStack)} or {@link
* World#dropItemNaturally(Location, ItemStack)}
*/
DROPPED_ITEM("item", Item.class, 1, false),
/**
* An experience orb.
*/
EXPERIENCE_ORB("experience_orb", ExperienceOrb.class, 2),
/**
* @see AreaEffectCloud
*/
AREA_EFFECT_CLOUD("area_effect_cloud", AreaEffectCloud.class, 3),
/**
* @see ElderGuardian
*/
ELDER_GUARDIAN("elder_guardian", ElderGuardian.class, 4),
/**
* @see WitherSkeleton
*/
WITHER_SKELETON("wither_skeleton", WitherSkeleton.class, 5),
/**
* @see Stray
*/
STRAY("stray", Stray.class, 6),
/**
* A flying chicken egg.
*/
EGG("egg", Egg.class, 7),
/**
* A leash attached to a fencepost.
*/
LEASH_HITCH("leash_knot", LeashHitch.class, 8),
/**
* A painting on a wall.
*/
PAINTING("painting", Painting.class, 9),
/**
* An arrow projectile; may get stuck in the ground.
*/
ARROW("arrow", Arrow.class, 10),
/**
* A flying snowball.
*/
SNOWBALL("snowball", Snowball.class, 11),
/**
* A flying large fireball, as thrown by a Ghast for example.
*/
FIREBALL("fireball", LargeFireball.class, 12),
/**
* A flying small fireball, such as thrown by a Blaze or player.
*/
SMALL_FIREBALL("small_fireball", SmallFireball.class, 13),
/**
* A flying ender pearl.
*/
ENDER_PEARL("ender_pearl", EnderPearl.class, 14),
/**
* An ender eye signal.
*/
ENDER_SIGNAL("eye_of_ender", EnderSignal.class, 15),
/**
* A flying splash potion.
*/
SPLASH_POTION("potion", ThrownPotion.class, 16, false),
/**
* A flying experience bottle.
*/
THROWN_EXP_BOTTLE("experience_bottle", ThrownExpBottle.class, 17),
/**
* An item frame on a wall.
*/
ITEM_FRAME("item_frame", ItemFrame.class, 18),
/**
* A flying wither skull projectile.
*/
WITHER_SKULL("wither_skull", WitherSkull.class, 19),
/**
* Primed TNT that is about to explode.
*/
PRIMED_TNT("tnt", TNTPrimed.class, 20),
/**
* A block that is going to or is about to fall.
*/
FALLING_BLOCK("falling_block", FallingBlock.class, 21, false),
/**
* Internal representation of a Firework once it has been launched.
*/
FIREWORK("firework_rocket", Firework.class, 22, false),
/**
* @see Husk
*/
HUSK("husk", Husk.class, 23),
/**
* Like {@link #ARROW} but causes the {@link PotionEffectType#GLOWING} effect on all team members.
*/
SPECTRAL_ARROW("spectral_arrow", SpectralArrow.class, 24),
/**
* Bullet fired by {@link #SHULKER}.
*/
SHULKER_BULLET("shulker_bullet", ShulkerBullet.class, 25),
/**
* Like {@link #FIREBALL} but with added effects.
*/
DRAGON_FIREBALL("dragon_fireball", DragonFireball.class, 26),
/**
* @see ZombieVillager
*/
ZOMBIE_VILLAGER("zombie_villager", ZombieVillager.class, 27),
/**
* @see SkeletonHorse
*/
SKELETON_HORSE("skeleton_horse", SkeletonHorse.class, 28),
/**
* @see ZombieHorse
*/
ZOMBIE_HORSE("zombie_horse", ZombieHorse.class, 29),
/**
* Mechanical entity with an inventory for placing weapons / armor into.
*/
ARMOR_STAND("armor_stand", ArmorStand.class, 30),
/**
* @see Donkey
*/
DONKEY("donkey", Donkey.class, 31),
/**
* @see Mule
*/
MULE("mule", Mule.class, 32),
/**
* @see EvokerFangs
*/
EVOKER_FANGS("evoker_fangs", EvokerFangs.class, 33),
/**
* @see Evoker
*/
EVOKER("evoker", Evoker.class, 34),
/**
* @see Vex
*/
VEX("vex", Vex.class, 35),
/**
* @see Vindicator
*/
VINDICATOR("vindicator", Vindicator.class, 36),
/**
* @see Illusioner
*/
ILLUSIONER("illusioner", Illusioner.class, 37),
/**
* @see CommandMinecart
*/
MINECART_COMMAND("command_block_minecart", CommandMinecart.class, 40),
/**
* A placed boat.
*/
BOAT("boat", Boat.class, 41),
/**
* @see RideableMinecart
*/
MINECART("minecart", RideableMinecart.class, 42),
/**
* @see StorageMinecart
*/
MINECART_CHEST("chest_minecart", StorageMinecart.class, 43),
/**
* @see PoweredMinecart
*/
MINECART_FURNACE("furnace_minecart", PoweredMinecart.class, 44),
/**
* @see ExplosiveMinecart
*/
MINECART_TNT("tnt_minecart", ExplosiveMinecart.class, 45),
/**
* @see HopperMinecart
*/
MINECART_HOPPER("hopper_minecart", HopperMinecart.class, 46),
/**
* @see SpawnerMinecart
*/
MINECART_MOB_SPAWNER("spawner_minecart", SpawnerMinecart.class, 47),
CREEPER("creeper", Creeper.class, 50),
SKELETON("skeleton", Skeleton.class, 51),
SPIDER("spider", Spider.class, 52),
GIANT("giant", Giant.class, 53),
ZOMBIE("zombie", Zombie.class, 54),
SLIME("slime", Slime.class, 55),
GHAST("ghast", Ghast.class, 56),
ZOMBIFIED_PIGLIN("zombified_piglin", PigZombie.class, 57),
ENDERMAN("enderman", Enderman.class, 58),
CAVE_SPIDER("cave_spider", CaveSpider.class, 59),
SILVERFISH("silverfish", Silverfish.class, 60),
BLAZE("blaze", Blaze.class, 61),
MAGMA_CUBE("magma_cube", MagmaCube.class, 62),
ENDER_DRAGON("ender_dragon", EnderDragon.class, 63),
WITHER("wither", Wither.class, 64),
BAT("bat", Bat.class, 65),
WITCH("witch", Witch.class, 66),
ENDERMITE("endermite", Endermite.class, 67),
GUARDIAN("guardian", Guardian.class, 68),
SHULKER("shulker", Shulker.class, 69),
PIG("pig", Pig.class, 90),
SHEEP("sheep", Sheep.class, 91),
COW("cow", Cow.class, 92),
CHICKEN("chicken", Chicken.class, 93),
SQUID("squid", Squid.class, 94),
WOLF("wolf", Wolf.class, 95),
MUSHROOM_COW("mooshroom", MushroomCow.class, 96),
SNOWMAN("snow_golem", Snowman.class, 97),
OCELOT("ocelot", Ocelot.class, 98),
IRON_GOLEM("iron_golem", IronGolem.class, 99),
HORSE("horse", Horse.class, 100),
RABBIT("rabbit", Rabbit.class, 101),
POLAR_BEAR("polar_bear", PolarBear.class, 102),
LLAMA("llama", Llama.class, 103),
LLAMA_SPIT("llama_spit", LlamaSpit.class, 104),
PARROT("parrot", Parrot.class, 105),
VILLAGER("villager", Villager.class, 120),
ENDER_CRYSTAL("end_crystal", EnderCrystal.class, 200),
TURTLE("turtle", Turtle.class, -1),
PHANTOM("phantom", Phantom.class, -1),
TRIDENT("trident", Trident.class, -1),
COD("cod", Cod.class, -1),
SALMON("salmon", Salmon.class, -1),
PUFFERFISH("pufferfish", PufferFish.class, -1),
TROPICAL_FISH("tropical_fish", TropicalFish.class, -1),
DROWNED("drowned", Drowned.class, -1),
DOLPHIN("dolphin", Dolphin.class, -1),
CAT("cat", Cat.class, -1),
PANDA("panda", Panda.class, -1),
PILLAGER("pillager", Pillager.class, -1),
RAVAGER("ravager", Ravager.class, -1),
TRADER_LLAMA("trader_llama", TraderLlama.class, -1),
WANDERING_TRADER("wandering_trader", WanderingTrader.class, -1),
FOX("fox", Fox.class, -1),
BEE("bee", Bee.class, -1),
HOGLIN("hoglin", Hoglin.class, -1),
PIGLIN("piglin", Piglin.class, -1),
STRIDER("strider", Strider.class, -1),
ZOGLIN("zoglin", Zoglin.class, -1),
PIGLIN_BRUTE("piglin_brute", PiglinBrute.class, -1),
/**
* A fishing line and bobber.
*/
FISHING_HOOK("fishing_bobber", FishHook.class, -1, false),
/**
* A bolt of lightning.
* <p>
* Spawn with {@link World#strikeLightning(Location)}.
*/
LIGHTNING("lightning_bolt", LightningStrike.class, -1, false),
PLAYER("player", Player.class, -1, false),
/**
* An unknown entity without an Entity Class
*/
UNKNOWN(null, null, -1, false),
/**
* Mods custom entity
*/
MOD_CUSTOM("mod_custom", CraftCustomEntity.class, -1, false);
private final String name;
private final Class<? extends Entity> clazz;
private final short typeId;
private final boolean independent, living;
private final NamespacedKey key;
private static final Map<String, EntityType> NAME_MAP = new HashMap<String, EntityType>();
private static final Map<Short, EntityType> ID_MAP = new HashMap<Short, EntityType>();
static {
for (EntityType type : values()) {
if (type.name != null) {
NAME_MAP.put(type.name.toLowerCase(java.util.Locale.ENGLISH), type);
}
if (type.typeId > 0) {
ID_MAP.put(type.typeId, type);
}
}
// Add legacy names
NAME_MAP.put("xp_orb", EXPERIENCE_ORB);
NAME_MAP.put("eye_of_ender_signal", ENDER_SIGNAL);
NAME_MAP.put("xp_bottle", THROWN_EXP_BOTTLE);
NAME_MAP.put("fireworks_rocket", FIREWORK);
NAME_MAP.put("evocation_fangs", EVOKER_FANGS);
NAME_MAP.put("evocation_illager", EVOKER);
NAME_MAP.put("vindication_illager", VINDICATOR);
NAME_MAP.put("illusion_illager", ILLUSIONER);
NAME_MAP.put("commandblock_minecart", MINECART_COMMAND);
NAME_MAP.put("snowman", SNOWMAN);
NAME_MAP.put("villager_golem", IRON_GOLEM);
NAME_MAP.put("ender_crystal", ENDER_CRYSTAL);
NAME_MAP.put("zombie_pigman", ZOMBIFIED_PIGLIN);
}
private EntityType(/*@Nullable*/ String name, /*@Nullable*/ Class<? extends Entity> clazz, int typeId) {
this(name, clazz, typeId, true);
}
private EntityType(/*@Nullable*/ String name, /*@Nullable*/ Class<? extends Entity> clazz, int typeId, boolean independent) {
this.name = name;
this.clazz = clazz;
this.typeId = (short) typeId;
this.independent = independent;
this.living = clazz != null && LivingEntity.class.isAssignableFrom(clazz);
this.key = (name == null) ? null : NamespacedKey.minecraft(name);
}
/**
* Gets the entity type name.
*
* @return the entity type's name
* @deprecated Magic value
*/
@Deprecated
@Nullable
public String getName() {
return name;
}
@NotNull
@Override
public NamespacedKey getKey() {
Preconditions.checkArgument(key != null, "EntityType doesn't have key! Is it UNKNOWN?");
return key;
}
@Nullable
public Class<? extends Entity> getEntityClass() {
return clazz;
}
/**
* Gets the entity type id.
*
* @return the raw type id
* @deprecated Magic value
*/
@Deprecated
public short getTypeId() {
return typeId;
}
/**
* Gets an entity type from its name.
*
* @param name the entity type's name
* @return the matching entity type or null
* @deprecated Magic value
*/
@Deprecated
@Contract("null -> null")
@Nullable
public static EntityType fromName(@Nullable String name) {
if (name == null) {
return null;
}
return NAME_MAP.get(name.toLowerCase(java.util.Locale.ENGLISH));
}
/**
* Gets an entity from its id.
*
* @param id the raw type id
* @return the matching entity type or null
* @deprecated Magic value
*/
@Deprecated
@Nullable
public static EntityType fromId(int id) {
if (id > Short.MAX_VALUE) {
return null;
}
return ID_MAP.get((short) id);
}
/**
* Some entities cannot be spawned using {@link
* World#spawnEntity(Location, EntityType)} or {@link
* World#spawn(Location, Class)}, usually because they require additional
* information in order to spawn.
*
* @return False if the entity type cannot be spawned
*/
public boolean isSpawnable() {
return independent;
}
public boolean isAlive() {
return living;
}
}
| Luohuayu/CatServer | src/main/java/org/bukkit/entity/EntityType.java | 4,755 | /**
* @see HopperMinecart
*/ | block_comment | nl | package org.bukkit.entity;
import com.google.common.base.Preconditions;
import catserver.server.entity.CraftCustomEntity;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Keyed;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.entity.minecart.CommandMinecart;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.PoweredMinecart;
import org.bukkit.entity.minecart.RideableMinecart;
import org.bukkit.entity.minecart.SpawnerMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public enum EntityType implements Keyed {
// These strings MUST match the strings in nms.EntityTypes and are case sensitive.
/**
* An item resting on the ground.
* <p>
* Spawn with {@link World#dropItem(Location, ItemStack)} or {@link
* World#dropItemNaturally(Location, ItemStack)}
*/
DROPPED_ITEM("item", Item.class, 1, false),
/**
* An experience orb.
*/
EXPERIENCE_ORB("experience_orb", ExperienceOrb.class, 2),
/**
* @see AreaEffectCloud
*/
AREA_EFFECT_CLOUD("area_effect_cloud", AreaEffectCloud.class, 3),
/**
* @see ElderGuardian
*/
ELDER_GUARDIAN("elder_guardian", ElderGuardian.class, 4),
/**
* @see WitherSkeleton
*/
WITHER_SKELETON("wither_skeleton", WitherSkeleton.class, 5),
/**
* @see Stray
*/
STRAY("stray", Stray.class, 6),
/**
* A flying chicken egg.
*/
EGG("egg", Egg.class, 7),
/**
* A leash attached to a fencepost.
*/
LEASH_HITCH("leash_knot", LeashHitch.class, 8),
/**
* A painting on a wall.
*/
PAINTING("painting", Painting.class, 9),
/**
* An arrow projectile; may get stuck in the ground.
*/
ARROW("arrow", Arrow.class, 10),
/**
* A flying snowball.
*/
SNOWBALL("snowball", Snowball.class, 11),
/**
* A flying large fireball, as thrown by a Ghast for example.
*/
FIREBALL("fireball", LargeFireball.class, 12),
/**
* A flying small fireball, such as thrown by a Blaze or player.
*/
SMALL_FIREBALL("small_fireball", SmallFireball.class, 13),
/**
* A flying ender pearl.
*/
ENDER_PEARL("ender_pearl", EnderPearl.class, 14),
/**
* An ender eye signal.
*/
ENDER_SIGNAL("eye_of_ender", EnderSignal.class, 15),
/**
* A flying splash potion.
*/
SPLASH_POTION("potion", ThrownPotion.class, 16, false),
/**
* A flying experience bottle.
*/
THROWN_EXP_BOTTLE("experience_bottle", ThrownExpBottle.class, 17),
/**
* An item frame on a wall.
*/
ITEM_FRAME("item_frame", ItemFrame.class, 18),
/**
* A flying wither skull projectile.
*/
WITHER_SKULL("wither_skull", WitherSkull.class, 19),
/**
* Primed TNT that is about to explode.
*/
PRIMED_TNT("tnt", TNTPrimed.class, 20),
/**
* A block that is going to or is about to fall.
*/
FALLING_BLOCK("falling_block", FallingBlock.class, 21, false),
/**
* Internal representation of a Firework once it has been launched.
*/
FIREWORK("firework_rocket", Firework.class, 22, false),
/**
* @see Husk
*/
HUSK("husk", Husk.class, 23),
/**
* Like {@link #ARROW} but causes the {@link PotionEffectType#GLOWING} effect on all team members.
*/
SPECTRAL_ARROW("spectral_arrow", SpectralArrow.class, 24),
/**
* Bullet fired by {@link #SHULKER}.
*/
SHULKER_BULLET("shulker_bullet", ShulkerBullet.class, 25),
/**
* Like {@link #FIREBALL} but with added effects.
*/
DRAGON_FIREBALL("dragon_fireball", DragonFireball.class, 26),
/**
* @see ZombieVillager
*/
ZOMBIE_VILLAGER("zombie_villager", ZombieVillager.class, 27),
/**
* @see SkeletonHorse
*/
SKELETON_HORSE("skeleton_horse", SkeletonHorse.class, 28),
/**
* @see ZombieHorse
*/
ZOMBIE_HORSE("zombie_horse", ZombieHorse.class, 29),
/**
* Mechanical entity with an inventory for placing weapons / armor into.
*/
ARMOR_STAND("armor_stand", ArmorStand.class, 30),
/**
* @see Donkey
*/
DONKEY("donkey", Donkey.class, 31),
/**
* @see Mule
*/
MULE("mule", Mule.class, 32),
/**
* @see EvokerFangs
*/
EVOKER_FANGS("evoker_fangs", EvokerFangs.class, 33),
/**
* @see Evoker
*/
EVOKER("evoker", Evoker.class, 34),
/**
* @see Vex
*/
VEX("vex", Vex.class, 35),
/**
* @see Vindicator
*/
VINDICATOR("vindicator", Vindicator.class, 36),
/**
* @see Illusioner
*/
ILLUSIONER("illusioner", Illusioner.class, 37),
/**
* @see CommandMinecart
*/
MINECART_COMMAND("command_block_minecart", CommandMinecart.class, 40),
/**
* A placed boat.
*/
BOAT("boat", Boat.class, 41),
/**
* @see RideableMinecart
*/
MINECART("minecart", RideableMinecart.class, 42),
/**
* @see StorageMinecart
*/
MINECART_CHEST("chest_minecart", StorageMinecart.class, 43),
/**
* @see PoweredMinecart
*/
MINECART_FURNACE("furnace_minecart", PoweredMinecart.class, 44),
/**
* @see ExplosiveMinecart
*/
MINECART_TNT("tnt_minecart", ExplosiveMinecart.class, 45),
/**
* @see HopperMinecart
<SUF>*/
MINECART_HOPPER("hopper_minecart", HopperMinecart.class, 46),
/**
* @see SpawnerMinecart
*/
MINECART_MOB_SPAWNER("spawner_minecart", SpawnerMinecart.class, 47),
CREEPER("creeper", Creeper.class, 50),
SKELETON("skeleton", Skeleton.class, 51),
SPIDER("spider", Spider.class, 52),
GIANT("giant", Giant.class, 53),
ZOMBIE("zombie", Zombie.class, 54),
SLIME("slime", Slime.class, 55),
GHAST("ghast", Ghast.class, 56),
ZOMBIFIED_PIGLIN("zombified_piglin", PigZombie.class, 57),
ENDERMAN("enderman", Enderman.class, 58),
CAVE_SPIDER("cave_spider", CaveSpider.class, 59),
SILVERFISH("silverfish", Silverfish.class, 60),
BLAZE("blaze", Blaze.class, 61),
MAGMA_CUBE("magma_cube", MagmaCube.class, 62),
ENDER_DRAGON("ender_dragon", EnderDragon.class, 63),
WITHER("wither", Wither.class, 64),
BAT("bat", Bat.class, 65),
WITCH("witch", Witch.class, 66),
ENDERMITE("endermite", Endermite.class, 67),
GUARDIAN("guardian", Guardian.class, 68),
SHULKER("shulker", Shulker.class, 69),
PIG("pig", Pig.class, 90),
SHEEP("sheep", Sheep.class, 91),
COW("cow", Cow.class, 92),
CHICKEN("chicken", Chicken.class, 93),
SQUID("squid", Squid.class, 94),
WOLF("wolf", Wolf.class, 95),
MUSHROOM_COW("mooshroom", MushroomCow.class, 96),
SNOWMAN("snow_golem", Snowman.class, 97),
OCELOT("ocelot", Ocelot.class, 98),
IRON_GOLEM("iron_golem", IronGolem.class, 99),
HORSE("horse", Horse.class, 100),
RABBIT("rabbit", Rabbit.class, 101),
POLAR_BEAR("polar_bear", PolarBear.class, 102),
LLAMA("llama", Llama.class, 103),
LLAMA_SPIT("llama_spit", LlamaSpit.class, 104),
PARROT("parrot", Parrot.class, 105),
VILLAGER("villager", Villager.class, 120),
ENDER_CRYSTAL("end_crystal", EnderCrystal.class, 200),
TURTLE("turtle", Turtle.class, -1),
PHANTOM("phantom", Phantom.class, -1),
TRIDENT("trident", Trident.class, -1),
COD("cod", Cod.class, -1),
SALMON("salmon", Salmon.class, -1),
PUFFERFISH("pufferfish", PufferFish.class, -1),
TROPICAL_FISH("tropical_fish", TropicalFish.class, -1),
DROWNED("drowned", Drowned.class, -1),
DOLPHIN("dolphin", Dolphin.class, -1),
CAT("cat", Cat.class, -1),
PANDA("panda", Panda.class, -1),
PILLAGER("pillager", Pillager.class, -1),
RAVAGER("ravager", Ravager.class, -1),
TRADER_LLAMA("trader_llama", TraderLlama.class, -1),
WANDERING_TRADER("wandering_trader", WanderingTrader.class, -1),
FOX("fox", Fox.class, -1),
BEE("bee", Bee.class, -1),
HOGLIN("hoglin", Hoglin.class, -1),
PIGLIN("piglin", Piglin.class, -1),
STRIDER("strider", Strider.class, -1),
ZOGLIN("zoglin", Zoglin.class, -1),
PIGLIN_BRUTE("piglin_brute", PiglinBrute.class, -1),
/**
* A fishing line and bobber.
*/
FISHING_HOOK("fishing_bobber", FishHook.class, -1, false),
/**
* A bolt of lightning.
* <p>
* Spawn with {@link World#strikeLightning(Location)}.
*/
LIGHTNING("lightning_bolt", LightningStrike.class, -1, false),
PLAYER("player", Player.class, -1, false),
/**
* An unknown entity without an Entity Class
*/
UNKNOWN(null, null, -1, false),
/**
* Mods custom entity
*/
MOD_CUSTOM("mod_custom", CraftCustomEntity.class, -1, false);
private final String name;
private final Class<? extends Entity> clazz;
private final short typeId;
private final boolean independent, living;
private final NamespacedKey key;
private static final Map<String, EntityType> NAME_MAP = new HashMap<String, EntityType>();
private static final Map<Short, EntityType> ID_MAP = new HashMap<Short, EntityType>();
static {
for (EntityType type : values()) {
if (type.name != null) {
NAME_MAP.put(type.name.toLowerCase(java.util.Locale.ENGLISH), type);
}
if (type.typeId > 0) {
ID_MAP.put(type.typeId, type);
}
}
// Add legacy names
NAME_MAP.put("xp_orb", EXPERIENCE_ORB);
NAME_MAP.put("eye_of_ender_signal", ENDER_SIGNAL);
NAME_MAP.put("xp_bottle", THROWN_EXP_BOTTLE);
NAME_MAP.put("fireworks_rocket", FIREWORK);
NAME_MAP.put("evocation_fangs", EVOKER_FANGS);
NAME_MAP.put("evocation_illager", EVOKER);
NAME_MAP.put("vindication_illager", VINDICATOR);
NAME_MAP.put("illusion_illager", ILLUSIONER);
NAME_MAP.put("commandblock_minecart", MINECART_COMMAND);
NAME_MAP.put("snowman", SNOWMAN);
NAME_MAP.put("villager_golem", IRON_GOLEM);
NAME_MAP.put("ender_crystal", ENDER_CRYSTAL);
NAME_MAP.put("zombie_pigman", ZOMBIFIED_PIGLIN);
}
private EntityType(/*@Nullable*/ String name, /*@Nullable*/ Class<? extends Entity> clazz, int typeId) {
this(name, clazz, typeId, true);
}
private EntityType(/*@Nullable*/ String name, /*@Nullable*/ Class<? extends Entity> clazz, int typeId, boolean independent) {
this.name = name;
this.clazz = clazz;
this.typeId = (short) typeId;
this.independent = independent;
this.living = clazz != null && LivingEntity.class.isAssignableFrom(clazz);
this.key = (name == null) ? null : NamespacedKey.minecraft(name);
}
/**
* Gets the entity type name.
*
* @return the entity type's name
* @deprecated Magic value
*/
@Deprecated
@Nullable
public String getName() {
return name;
}
@NotNull
@Override
public NamespacedKey getKey() {
Preconditions.checkArgument(key != null, "EntityType doesn't have key! Is it UNKNOWN?");
return key;
}
@Nullable
public Class<? extends Entity> getEntityClass() {
return clazz;
}
/**
* Gets the entity type id.
*
* @return the raw type id
* @deprecated Magic value
*/
@Deprecated
public short getTypeId() {
return typeId;
}
/**
* Gets an entity type from its name.
*
* @param name the entity type's name
* @return the matching entity type or null
* @deprecated Magic value
*/
@Deprecated
@Contract("null -> null")
@Nullable
public static EntityType fromName(@Nullable String name) {
if (name == null) {
return null;
}
return NAME_MAP.get(name.toLowerCase(java.util.Locale.ENGLISH));
}
/**
* Gets an entity from its id.
*
* @param id the raw type id
* @return the matching entity type or null
* @deprecated Magic value
*/
@Deprecated
@Nullable
public static EntityType fromId(int id) {
if (id > Short.MAX_VALUE) {
return null;
}
return ID_MAP.get((short) id);
}
/**
* Some entities cannot be spawned using {@link
* World#spawnEntity(Location, EntityType)} or {@link
* World#spawn(Location, Class)}, usually because they require additional
* information in order to spawn.
*
* @return False if the entity type cannot be spawned
*/
public boolean isSpawnable() {
return independent;
}
public boolean isAlive() {
return living;
}
}
|
26303_9 | package com.stenden.esselbrugge.stendenrooster;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by luuk on 19-9-17.
*/
public class ServerConnection {
private String user_agent = "SRooster Android";
private String master_server = "https://sa-nhlstenden.xedule.nl/api/";
private CookieManager cookieManager;
public ServerConnection(){
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
}
public String httpGET(String file, Context context){
StringBuffer data = new StringBuffer("");
try{
SharedPreferences SP = context.getSharedPreferences("Cookies", MODE_PRIVATE);
String cookie = SP.getString("Cookie","");
URL url = new URL(master_server + file);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestProperty("Cookie", cookie);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
Log.d("Using Cache",file);
//Probeer eerst login
SharedPreferences SP1 = context.getSharedPreferences("Cookies", MODE_PRIVATE);
String em = SP1.getString("Email","");
String pw = SP1.getString("Password","");
if(!em.equals("") && !pw.equals("")) {
final String koekjes = this.Login(em, pw, context);
if (!koekjes.equals("Error") && !koekjes.equals("")) {
SP1.edit().putString("Cookie", koekjes).commit();
Log.d("Error", "New session auto created");
return httpGET(file, context);
}
}
//Probeer te laden uit cache
SharedPreferences SP = context.getSharedPreferences("WebCache", MODE_PRIVATE);
return SP.getString(file,"");
}
try{
final SharedPreferences.Editor SP = context.getSharedPreferences("WebCache", MODE_PRIVATE).edit();
SP.putString(file, data.toString());
SP.apply();
}catch (Exception e){
}
return data.toString();
}
private String httpPOST(String urlIn, String urlParameters, Context context){
StringBuffer data = new StringBuffer("");
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
try{
URL url = new URL(urlIn);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
connection.setRequestProperty( "Accept", "*/*");
try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
wr.write( postData );
}
//Like waarom in de fuck is dit een ding
//if(connection.getResponseCode() == 307){
try {
String redirect = connection.getHeaderField("Location");
Log.e("Redirect Detected", redirect);
}catch (Exception e){
}
//}
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
}
return data.toString();
}
public String httpGETNoCache(String file, Context context){
StringBuffer data = new StringBuffer("");
try{
SharedPreferences SP = context.getSharedPreferences("Cookies", MODE_PRIVATE);
String cookie = SP.getString("Cookie","");
URL url = new URL(master_server + file);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestProperty("Cookie", cookie);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
Log.d("Using Cache",file);
}
return data.toString();
}
public JSONArray getSchedule(Context context, String weekNum, String year, ArrayList<String> ids, ArrayList<String>schoolIDs){
String rawdata;
JSONArray finalData = new JSONArray();
int count = 0;
int maxTries = 5;
while(true) {
try {
int x = 0;
for (String id: ids) {
rawdata = httpGET("schedule/?ids%5B0%5D=" + schoolIDs.get(x) + "_" + year + "_" + weekNum + "_" + id, context);
Log.e("data",rawdata.toString());
JSONArray data = new JSONArray(rawdata).getJSONObject(0).getJSONArray("apps");
for (int i = 0; i < data.length(); i++) {
JSONObject item = data.getJSONObject(i);
item.put("ComparePos",x+"");
finalData.put(item);
}
x++;
}
return finalData;
}catch (Exception e){
Log.d("ShitWentWrondddddddg",e.toString());
year = (Integer.parseInt(year)-1) + "";
if (++count == maxTries) return new JSONArray(); // Dit geweldige fucking stukje code komt omdat ze het jaar 2017 gebruiken voor 2018 items
}
}
}
public JSONArray checkMode(Context context){
String data;
try {
data = httpGETNoCache("group", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
public JSONArray getGroups(Context context){
String data;
try {
data = httpGET("group", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
public JSONArray getRooms(Context context){
String data;
try {
data = httpGET("facility", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
public JSONArray getTeachers(Context context){
String data;
try {
data = httpGET("docent", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
//Als Java code aids kan hebben dan komt deze methode in de buurt er is geen andere manier zonder API
public String Login(String Username, String Password, Context context){
StringBuffer data = new StringBuffer("");
String firstpostURL = "";
try{
URL url = new URL("https://sa-nhlstenden.xedule.nl/Stenden");
if(Username.endsWith("@student.nhlstenden.com") || Username.endsWith("@nhlstenden.com")){
url = new URL("https://sa-nhlstenden.xedule.nl");
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
}
Pattern pattern = Pattern.compile("<form id=\"options\" method=\"post\" action=\"(.*?)\">");
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
firstpostURL = matcher.group(1);
}
Boolean DetailsWrong = true;
try {
String SAMLResponse = httpPOST(firstpostURL, "UserName=" + URLEncoder.encode(Username, "UTF-8") + "&Password=" + URLEncoder.encode(Password, "UTF-8") + "&Kmsi=true&AuthMethod=FormsAuthentication", context);
pattern = Pattern.compile("name=\"SAMLResponse\" value=\"(.*?)\" />");
matcher = pattern.matcher(SAMLResponse);
while (matcher.find()) {
DetailsWrong = false;
SAMLResponse = matcher.group(1);
}
if(DetailsWrong){
return "Error";
}
String surf = httpPOST("https://engine.surfconext.nl:443/authentication/sp/consume-assertion","SAMLResponse="+URLEncoder.encode(SAMLResponse, "UTF-8"),context);
String surfAuth = surf;
String RelayState = surf;
pattern = Pattern.compile("<input type=\"hidden\" name=\"SAMLResponse\" value=\"(.*?)\"");
matcher = pattern.matcher(surfAuth);
while (matcher.find()) {
surfAuth = matcher.group(1);
}
pattern = Pattern.compile("<input type=\"hidden\" name=\"RelayState\" value=\"(.*?)\"");
matcher = pattern.matcher(RelayState);
while (matcher.find()) {
RelayState = matcher.group(1);
}
RelayState = RelayState.replace("&", "&");
String Auth2 = httpPOST("https://sa-nhlstenden.xedule.nl/authentication/sso/assertionservice.aspx","SAMLResponse="+URLEncoder.encode(surfAuth, "UTF-8") + "&return=&RelayState="+URLEncoder.encode(RelayState, "UTF-8"),context);
CookieStore cookieJar = cookieManager.getCookieStore();
List<HttpCookie> cookies =
cookieJar.getCookies();
String kutKoekjes = "";
for (HttpCookie cookie: cookies) {
kutKoekjes += cookie + "; ";
}
return kutKoekjes;
}catch (Exception e){
Log.e("Error",e.toString());
}
return "";
}
}
| LuukEsselbrugge/SRooster | app/src/main/java/com/stenden/esselbrugge/stendenrooster/ServerConnection.java | 3,325 | //Als Java code aids kan hebben dan komt deze methode in de buurt er is geen andere manier zonder API | line_comment | nl | package com.stenden.esselbrugge.stendenrooster;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by luuk on 19-9-17.
*/
public class ServerConnection {
private String user_agent = "SRooster Android";
private String master_server = "https://sa-nhlstenden.xedule.nl/api/";
private CookieManager cookieManager;
public ServerConnection(){
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
}
public String httpGET(String file, Context context){
StringBuffer data = new StringBuffer("");
try{
SharedPreferences SP = context.getSharedPreferences("Cookies", MODE_PRIVATE);
String cookie = SP.getString("Cookie","");
URL url = new URL(master_server + file);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestProperty("Cookie", cookie);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
Log.d("Using Cache",file);
//Probeer eerst login
SharedPreferences SP1 = context.getSharedPreferences("Cookies", MODE_PRIVATE);
String em = SP1.getString("Email","");
String pw = SP1.getString("Password","");
if(!em.equals("") && !pw.equals("")) {
final String koekjes = this.Login(em, pw, context);
if (!koekjes.equals("Error") && !koekjes.equals("")) {
SP1.edit().putString("Cookie", koekjes).commit();
Log.d("Error", "New session auto created");
return httpGET(file, context);
}
}
//Probeer te laden uit cache
SharedPreferences SP = context.getSharedPreferences("WebCache", MODE_PRIVATE);
return SP.getString(file,"");
}
try{
final SharedPreferences.Editor SP = context.getSharedPreferences("WebCache", MODE_PRIVATE).edit();
SP.putString(file, data.toString());
SP.apply();
}catch (Exception e){
}
return data.toString();
}
private String httpPOST(String urlIn, String urlParameters, Context context){
StringBuffer data = new StringBuffer("");
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
try{
URL url = new URL(urlIn);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
connection.setRequestProperty( "Accept", "*/*");
try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
wr.write( postData );
}
//Like waarom in de fuck is dit een ding
//if(connection.getResponseCode() == 307){
try {
String redirect = connection.getHeaderField("Location");
Log.e("Redirect Detected", redirect);
}catch (Exception e){
}
//}
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
}
return data.toString();
}
public String httpGETNoCache(String file, Context context){
StringBuffer data = new StringBuffer("");
try{
SharedPreferences SP = context.getSharedPreferences("Cookies", MODE_PRIVATE);
String cookie = SP.getString("Cookie","");
URL url = new URL(master_server + file);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestProperty("Cookie", cookie);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
Log.d("Using Cache",file);
}
return data.toString();
}
public JSONArray getSchedule(Context context, String weekNum, String year, ArrayList<String> ids, ArrayList<String>schoolIDs){
String rawdata;
JSONArray finalData = new JSONArray();
int count = 0;
int maxTries = 5;
while(true) {
try {
int x = 0;
for (String id: ids) {
rawdata = httpGET("schedule/?ids%5B0%5D=" + schoolIDs.get(x) + "_" + year + "_" + weekNum + "_" + id, context);
Log.e("data",rawdata.toString());
JSONArray data = new JSONArray(rawdata).getJSONObject(0).getJSONArray("apps");
for (int i = 0; i < data.length(); i++) {
JSONObject item = data.getJSONObject(i);
item.put("ComparePos",x+"");
finalData.put(item);
}
x++;
}
return finalData;
}catch (Exception e){
Log.d("ShitWentWrondddddddg",e.toString());
year = (Integer.parseInt(year)-1) + "";
if (++count == maxTries) return new JSONArray(); // Dit geweldige fucking stukje code komt omdat ze het jaar 2017 gebruiken voor 2018 items
}
}
}
public JSONArray checkMode(Context context){
String data;
try {
data = httpGETNoCache("group", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
public JSONArray getGroups(Context context){
String data;
try {
data = httpGET("group", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
public JSONArray getRooms(Context context){
String data;
try {
data = httpGET("facility", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
public JSONArray getTeachers(Context context){
String data;
try {
data = httpGET("docent", context);
JSONArray jObject = new JSONArray(data);
return jObject;
}catch (Exception e){
Log.d("ShitWentWrong",e.toString());
return new JSONArray();
}
}
//Als Java<SUF>
public String Login(String Username, String Password, Context context){
StringBuffer data = new StringBuffer("");
String firstpostURL = "";
try{
URL url = new URL("https://sa-nhlstenden.xedule.nl/Stenden");
if(Username.endsWith("@student.nhlstenden.com") || Username.endsWith("@nhlstenden.com")){
url = new URL("https://sa-nhlstenden.xedule.nl");
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", user_agent);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
// writing exception to log
Log.d("Error",e.toString());
}
Pattern pattern = Pattern.compile("<form id=\"options\" method=\"post\" action=\"(.*?)\">");
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
firstpostURL = matcher.group(1);
}
Boolean DetailsWrong = true;
try {
String SAMLResponse = httpPOST(firstpostURL, "UserName=" + URLEncoder.encode(Username, "UTF-8") + "&Password=" + URLEncoder.encode(Password, "UTF-8") + "&Kmsi=true&AuthMethod=FormsAuthentication", context);
pattern = Pattern.compile("name=\"SAMLResponse\" value=\"(.*?)\" />");
matcher = pattern.matcher(SAMLResponse);
while (matcher.find()) {
DetailsWrong = false;
SAMLResponse = matcher.group(1);
}
if(DetailsWrong){
return "Error";
}
String surf = httpPOST("https://engine.surfconext.nl:443/authentication/sp/consume-assertion","SAMLResponse="+URLEncoder.encode(SAMLResponse, "UTF-8"),context);
String surfAuth = surf;
String RelayState = surf;
pattern = Pattern.compile("<input type=\"hidden\" name=\"SAMLResponse\" value=\"(.*?)\"");
matcher = pattern.matcher(surfAuth);
while (matcher.find()) {
surfAuth = matcher.group(1);
}
pattern = Pattern.compile("<input type=\"hidden\" name=\"RelayState\" value=\"(.*?)\"");
matcher = pattern.matcher(RelayState);
while (matcher.find()) {
RelayState = matcher.group(1);
}
RelayState = RelayState.replace("&", "&");
String Auth2 = httpPOST("https://sa-nhlstenden.xedule.nl/authentication/sso/assertionservice.aspx","SAMLResponse="+URLEncoder.encode(surfAuth, "UTF-8") + "&return=&RelayState="+URLEncoder.encode(RelayState, "UTF-8"),context);
CookieStore cookieJar = cookieManager.getCookieStore();
List<HttpCookie> cookies =
cookieJar.getCookies();
String kutKoekjes = "";
for (HttpCookie cookie: cookies) {
kutKoekjes += cookie + "; ";
}
return kutKoekjes;
}catch (Exception e){
Log.e("Error",e.toString());
}
return "";
}
}
|